diff --git a/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L2-Embeddings-api-intro.ipynb b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L2-Embeddings-api-intro.ipynb new file mode 100644 index 0000000..c539170 --- /dev/null +++ b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L2-Embeddings-api-intro.ipynb @@ -0,0 +1,633 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "207942ee-1cad-4ff4-a64a-90aebc10d040", + "metadata": {}, + "source": [ + "# Getting Started With Text Embeddings" + ] + }, + { + "cell_type": "markdown", + "id": "ed132594-2b03-449b-87e2-2529d60aa05a", + "metadata": {}, + "source": [ + "#### Project environment setup\n", + "\n", + "- Load credentials and relevant Python Libraries\n", + "- If you were running this notebook locally, you would first install Vertex AI. In this classroom, this is already installed.\n", + "```Python\n", + "!pip install google-cloud-aiplatform\n", + "```\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "2931ae6b-23c1-4d02-a724-1bc0b1b9a820", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from utils import authenticate\n", + "credentials, PROJECT_ID = authenticate() # Get credentials and project ID" + ] + }, + { + "cell_type": "markdown", + "id": "f3cfcd44-8eba-4eee-b7b4-a7be3c876685", + "metadata": {}, + "source": [ + "#### Enter project details" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "fb9c9a86-f9bd-45a6-93c2-f6dbf7d32b12", + "metadata": { + "height": 32 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DLAI_PROJECT\n" + ] + } + ], + "source": [ + "print(PROJECT_ID)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "2d411edf-7fe6-4160-9ecb-6f5e05161951", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "REGION = 'us-central1'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "f9223fa5-1cd8-42a9-a967-9f2c848727ee", + "metadata": { + "height": 117 + }, + "outputs": [], + "source": [ + "# Import and initialize the Vertex AI Python SDK\n", + "\n", + "import vertexai\n", + "vertexai.init(project = PROJECT_ID, \n", + " location = REGION, \n", + " credentials = credentials)" + ] + }, + { + "cell_type": "markdown", + "id": "0e448c9f-8311-420b-b408-a1fb712bbff4", + "metadata": {}, + "source": [ + "#### Use the embeddings model\n", + "- Import and load the model." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "681bfe86-6880-4afa-bdd6-77a8dfbc5f21", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from vertexai.language_models import TextEmbeddingModel" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "fa62b23a-b423-4651-88f1-b00509900be3", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "embedding_model = TextEmbeddingModel.from_pretrained(\n", + " \"textembedding-gecko@001\")" + ] + }, + { + "cell_type": "markdown", + "id": "ce2289d4-882f-4336-a720-75e80cac6900", + "metadata": {}, + "source": [ + "- Generate a word embedding" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "f05aea17-cb72-4c7f-9da2-df0ee954e663", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "embedding = embedding_model.get_embeddings(\n", + " [\"life\"])" + ] + }, + { + "cell_type": "markdown", + "id": "685a6bc7-455a-4783-93d5-fa491e82e828", + "metadata": {}, + "source": [ + "- The returned object is a list with a single `TextEmbedding` object.\n", + "- The `TextEmbedding.values` field stores the embeddings in a Python list." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "ea301db6-a439-4c0b-aae1-5e6ef943419c", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Length = 768\n", + "[-0.006005102302879095, 0.015532972291111946, -0.030447669327259064, 0.05322219058871269, 0.014444807544350624, -0.0542873740196228, 0.045140113681554794, 0.02127358317375183, -0.06537645310163498, 0.019103270024061203]\n" + ] + } + ], + "source": [ + "vector = embedding[0].values\n", + "print(f\"Length = {len(vector)}\")\n", + "print(vector[:10])" + ] + }, + { + "cell_type": "markdown", + "id": "5b803ae9-dd2e-421e-bc06-d6e7e0898b06", + "metadata": {}, + "source": [ + "- Generate a sentence embedding." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "f53a4cd7-f89a-4931-ae16-519d1feb5197", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "embedding = embedding_model.get_embeddings(\n", + " [\"What is the meaning of life?\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "7ca0182e-1744-4fbb-b240-2d193ec907d4", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Length = 768\n", + "[0.020522113889455795, 0.02229207195341587, -0.009265718050301075, 0.005001612473279238, 0.016248879954218864, -0.018983161076903343, 0.04320966452360153, 0.02643178217113018, -0.04369377717375755, 0.023666976019740105]\n" + ] + } + ], + "source": [ + "vector = embedding[0].values\n", + "print(f\"Length = {len(vector)}\")\n", + "print(vector[:10])" + ] + }, + { + "cell_type": "markdown", + "id": "7179f3de-e405-4c97-aaf5-055a99c464b6", + "metadata": {}, + "source": [ + "#### Similarity\n", + "\n", + "- Calculate the similarity between two sentences as a number between 0 and 1.\n", + "- Try out your own sentences and check if the similarity calculations match your intuition." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "91b2520b-9687-4eed-be07-9ff75f1fcd74", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from sklearn.metrics.pairwise import cosine_similarity" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "04483bf2-4d5d-4fd2-9aec-27711f2c780c", + "metadata": { + "height": 219 + }, + "outputs": [], + "source": [ + "emb_1 = embedding_model.get_embeddings(\n", + " [\"What is the meaning of life?\"]) # 42!\n", + "\n", + "emb_2 = embedding_model.get_embeddings(\n", + " [\"How does one spend their time well on Earth?\"])\n", + "\n", + "emb_3 = embedding_model.get_embeddings(\n", + " [\"Would you like a salad?\"])\n", + "\n", + "vec_1 = [emb_1[0].values]\n", + "vec_2 = [emb_2[0].values]\n", + "vec_3 = [emb_3[0].values]" + ] + }, + { + "cell_type": "markdown", + "id": "c0e70a55-21a4-4532-be59-1b9749d639b0", + "metadata": {}, + "source": [ + "- Note: the reason we wrap the embeddings (a Python list) in another list is because the `cosine_similarity` function expects either a 2D numpy array or a list of lists.\n", + "```Python\n", + "vec_1 = [emb_1[0].values]\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "9b370eaa-a3b7-44e4-90a2-6dc84e460122", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0.65503744]]\n", + "[[0.52001556]]\n", + "[[0.54139322]]\n" + ] + } + ], + "source": [ + "print(cosine_similarity(vec_1,vec_2)) \n", + "print(cosine_similarity(vec_2,vec_3))\n", + "print(cosine_similarity(vec_1,vec_3))" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "f56290de", + "metadata": { + "height": 287 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0.62619186]]\n", + "[[0.57645054]]\n", + "[[0.79741994]]\n" + ] + } + ], + "source": [ + "emb_1 = embedding_model.get_embeddings(\n", + " [\"I live playing basketball\"]) # 42!\n", + "\n", + "emb_2 = embedding_model.get_embeddings(\n", + " [\"I love to go camping on the weekends\"])\n", + "\n", + "emb_3 = embedding_model.get_embeddings(\n", + " [\"I love slam dunks\"])\n", + "\n", + "vec_1 = [emb_1[0].values]\n", + "vec_2 = [emb_2[0].values]\n", + "vec_3 = [emb_3[0].values]\n", + "\n", + "print(cosine_similarity(vec_1,vec_2)) \n", + "print(cosine_similarity(vec_2,vec_3))\n", + "print(cosine_similarity(vec_1,vec_3))" + ] + }, + { + "cell_type": "markdown", + "id": "fe4b69f0-e64b-477d-9466-72ba1be05043", + "metadata": {}, + "source": [ + "#### From word to sentence embeddings\n", + "- One possible way to calculate sentence embeddings from word embeddings is to take the average of the word embeddings.\n", + "- This ignores word order and context, so two sentences with different meanings, but the same set of words will end up with the same sentence embedding." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "b88fff09-a268-4a29-a04b-7c84a588db80", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "in_1 = \"The kids play in the park.\"\n", + "in_2 = \"The play was for kids in the park.\"" + ] + }, + { + "cell_type": "markdown", + "id": "40437875-53db-4c88-8882-a2d6266d43d3", + "metadata": {}, + "source": [ + "- Remove stop words like [\"the\", \"in\", \"for\", \"an\", \"is\"] and punctuation." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "3bab3a74-ec19-48cc-b5fb-1f0bd520b2c2", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "in_pp_1 = [\"kids\", \"play\", \"park\"]\n", + "in_pp_2 = [\"play\", \"kids\", \"park\"]" + ] + }, + { + "cell_type": "markdown", + "id": "f2202a83-a704-41aa-ae2a-ba9ee2afd351", + "metadata": {}, + "source": [ + "- Generate one embedding for each word. So this is a list of three lists." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "412df546-e2e2-4a90-9cd4-86b4887ab908", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "embeddings_1 = [emb.values for emb in embedding_model.get_embeddings(in_pp_1)]" + ] + }, + { + "cell_type": "markdown", + "id": "a3ac14b1-3d55-4227-9014-88447d5a08b8", + "metadata": {}, + "source": [ + "- Use numpy to convert this list of lists into a 2D array of 3 rows and 768 columns." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "e5bcf45a-fb96-4838-a676-fbf52afc0b32", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 768)\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "emb_array_1 = np.stack(embeddings_1)\n", + "print(emb_array_1.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "a8d20a4e-c56d-4a23-83ff-97d98e86cf32", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(3, 768)\n" + ] + } + ], + "source": [ + "embeddings_2 = [emb.values for emb in embedding_model.get_embeddings(in_pp_2)]\n", + "emb_array_2 = np.stack(embeddings_2)\n", + "print(emb_array_2.shape)" + ] + }, + { + "cell_type": "markdown", + "id": "3a83a56b-404d-4517-a666-c161f92ae48f", + "metadata": {}, + "source": [ + "- Take the average embedding across the 3 word embeddings \n", + "- You'll get a single embedding of length 768." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "5d6d9b65-a0ce-49eb-9627-b550053663c3", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(768,)\n" + ] + } + ], + "source": [ + "emb_1_mean = emb_array_1.mean(axis = 0) \n", + "print(emb_1_mean.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "23ba79b5-ba81-4c7e-b1d8-642b428e16ec", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "emb_2_mean = emb_array_2.mean(axis = 0)" + ] + }, + { + "cell_type": "markdown", + "id": "fdfe77e1-0b0c-407e-b179-862db2e2e454", + "metadata": {}, + "source": [ + "- Check to see that taking an average of word embeddings results in two sentence embeddings that are identical." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "22dd51c8-cee8-46f1-b717-0a44ff8f1d1c", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[-0.00385805 -0.00522636 0.00574341 0.03331106]\n", + "[-0.00385805 -0.00522636 0.00574341 0.03331106]\n" + ] + } + ], + "source": [ + "print(emb_1_mean[:4])\n", + "print(emb_2_mean[:4])" + ] + }, + { + "cell_type": "markdown", + "id": "a8014b28-ddfa-43e0-969b-5bd4ed0f6fdb", + "metadata": {}, + "source": [ + "#### Get sentence embeddings from the model.\n", + "- These sentence embeddings account for word order and context.\n", + "- Verify that the sentence embeddings are not the same." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "3f69ff3c-dd02-45ae-b34c-a10f3d78614b", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The kids play in the park.\n", + "The play was for kids in the park.\n" + ] + } + ], + "source": [ + "print(in_1)\n", + "print(in_2)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "08dcfe77-013f-4cdc-a6c5-455c364b2507", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "embedding_1 = embedding_model.get_embeddings([in_1])\n", + "embedding_2 = embedding_model.get_embeddings([in_2])" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "dd4e998f-01b4-4d90-b509-cb03f26c106c", + "metadata": { + "height": 83 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0.0039385221898555756, -0.020830577239394188, -0.002994248876348138, -0.007580515928566456]\n", + "[-0.01565515622496605, -0.012884826399385929, 0.01229254249483347, -0.0005865463172085583]\n" + ] + } + ], + "source": [ + "vector_1 = embedding_1[0].values\n", + "print(vector_1[:4])\n", + "vector_2 = embedding_2[0].values\n", + "print(vector_2[:4])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4ccfbb6f-c72b-4f5e-a86c-265bab07d9e1", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L4-visualizing-embeddings.ipynb b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L4-visualizing-embeddings.ipynb new file mode 100644 index 0000000..7783ab4 --- /dev/null +++ b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L4-visualizing-embeddings.ipynb @@ -0,0 +1,513 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "34589b64-1a75-49b1-8e5e-1ea3cd857111", + "metadata": {}, + "source": [ + "## Lesson 3: Visualizing Embeddings" + ] + }, + { + "cell_type": "markdown", + "id": "88adc7f3-52b6-432f-80c4-995605b556eb", + "metadata": {}, + "source": [ + "#### Project environment setup\n", + "\n", + "- Load credentials and relevant Python Libraries" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "aeeebfae-c08f-4c9d-a714-9090a04fbc5c", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from utils import authenticate\n", + "credentials, PROJECT_ID = authenticate() #Get credentials and project ID" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "2b56c0f4-cfc3-4f6a-a189-f30f08cb585e", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "REGION = 'us-central1'" + ] + }, + { + "cell_type": "markdown", + "id": "5ba3a1c7-2d3a-41de-91b9-d3780801742b", + "metadata": {}, + "source": [ + "#### Enter project details" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "b3519fb1-7ba3-481b-ac5d-c45cfa6b27a0", + "metadata": { + "height": 117 + }, + "outputs": [], + "source": [ + "# Import and initialize the Vertex AI Python SDK\n", + "\n", + "import vertexai\n", + "vertexai.init(project=PROJECT_ID, \n", + " location=REGION, \n", + " credentials = credentials)" + ] + }, + { + "cell_type": "markdown", + "id": "dea550bf-d3fb-4ae2-80da-4f3d9179a9b9", + "metadata": {}, + "source": [ + "## Embeddings capture meaning" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "763e2623-ca37-43ed-90d5-d0e52cc6fba5", + "metadata": { + "height": 321 + }, + "outputs": [], + "source": [ + "in_1 = \"Missing flamingo discovered at swimming pool\"\n", + "\n", + "in_2 = \"Sea otter spotted on surfboard by beach\"\n", + "\n", + "in_3 = \"Baby panda enjoys boat ride\"\n", + "\n", + "\n", + "in_4 = \"Breakfast themed food truck beloved by all!\"\n", + "\n", + "in_5 = \"New curry restaurant aims to please!\"\n", + "\n", + "\n", + "in_6 = \"Python developers are wonderful people\"\n", + "\n", + "in_7 = \"TypeScript, C++ or Java? All are great!\" \n", + "\n", + "\n", + "input_text_lst_news = [in_1, in_2, in_3, in_4, in_5, in_6, in_7]" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "726ce640-0505-4d01-9620-94502af9eb70", + "metadata": { + "height": 100 + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "from vertexai.language_models import TextEmbeddingModel\n", + "\n", + "embedding_model = TextEmbeddingModel.from_pretrained(\n", + " \"textembedding-gecko@001\")" + ] + }, + { + "cell_type": "markdown", + "id": "b270e703-62fd-47cf-893e-3fe7a1282f29", + "metadata": {}, + "source": [ + "- Get embeddings for all pieces of text.\n", + "- Store them in a 2D NumPy array (one row for each embedding)." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "30dbf38d-5f88-4ee0-804c-87099b5d6693", + "metadata": { + "height": 134 + }, + "outputs": [], + "source": [ + "embeddings = []\n", + "for input_text in input_text_lst_news:\n", + " emb = embedding_model.get_embeddings(\n", + " [input_text])[0].values\n", + " embeddings.append(emb)\n", + " \n", + "embeddings_array = np.array(embeddings) " + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "9129943c-d624-4ada-9dbf-8277fc12554d", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape: (7, 768)\n", + "[[ 0.04559246 -0.01472285 -0.02949955 ... 0.04057328 -0.03193641\n", + " -0.01936668]\n", + " [-0.01995482 0.00037652 0.0116593 ... 0.02617216 -0.03978169\n", + " -0.02036468]\n", + " [ 0.01030084 0.02219611 0.02433357 ... 0.03538613 -0.0273955\n", + " -0.04193578]\n", + " ...\n", + " [-0.0263201 -0.01767797 -0.01261324 ... -0.01372547 0.00060259\n", + " 0.01581882]\n", + " [-0.00561961 -0.02237099 -0.03271009 ... -0.02777804 -0.03388645\n", + " -0.01553735]\n", + " [ 0.00867064 -0.0131854 0.04283332 ... -0.04224638 0.01800203\n", + " 0.01088098]]\n" + ] + } + ], + "source": [ + "print(\"Shape: \" + str(embeddings_array.shape))\n", + "print(embeddings_array)" + ] + }, + { + "cell_type": "markdown", + "id": "deffaf3d-f57e-4b14-a391-620194c5d354", + "metadata": {}, + "source": [ + "#### Reduce embeddings from 768 to 2 dimensions for visualization\n", + "- We'll use principal component analysis (PCA).\n", + "- You can learn more about PCA in [this video](https://www.coursera.org/learn/unsupervised-learning-recommenders-reinforcement-learning/lecture/73zWO/reducing-the-number-of-features-optional) from the Machine Learning Specialization. " + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "a8fa6ec2-fa3b-47da-831a-1892dd8560dc", + "metadata": { + "height": 117 + }, + "outputs": [], + "source": [ + "from sklearn.decomposition import PCA\n", + "\n", + "# Perform PCA for 2D visualization\n", + "PCA_model = PCA(n_components = 2)\n", + "PCA_model.fit(embeddings_array)\n", + "new_values = PCA_model.transform(embeddings_array)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "8743daf4-31f3-467d-be38-fc5984857682", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape: (7, 2)\n", + "[[-0.40980753 -0.10084478]\n", + " [-0.39561909 -0.18401444]\n", + " [-0.29958523 0.07514691]\n", + " [ 0.16077688 0.32879395]\n", + " [ 0.1893873 0.48556638]\n", + " [ 0.31516547 -0.23624716]\n", + " [ 0.4396822 -0.36840086]]\n" + ] + } + ], + "source": [ + "print(\"Shape: \" + str(new_values.shape))\n", + "print(new_values)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "9328db18-bb41-4405-8139-b62f69850a2a", + "metadata": { + "height": 117 + }, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "54a9e240eb1e49008699f6a7230414bd", + "version_major": 2, + "version_minor": 0 + }, + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAA6nElEQVR4nO3de3gU9b3H8c9mc0OWTQIBIoJEECORNVgwASqhSiRqNGCpAgUNiCL1gKUoLVQLCH0atFhRRPFQBS9ULlaUQwTC1RQNF0HsUiIV5WYwIBASEi5JNnP+4LCnSxJIQrKb7Lxfz7PP4/7mNzPfzSzu5/nNb2YshmEYAgAAgGkE+LoAAAAAeBcBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgEADFB0drXvvvbfe97N//35ZLBYtWLDgsn2HDx+u6OhojzaLxaKpU6fWS211YePGjbJYLNq4cWODq6Oyv6c3+Gq/NfmuAah/BECgmhYsWCCLxVLla/Pmzb4uEZAkHT58WFOnTtXOnTt9XUq9KS8v14IFC5Samqp27dqpadOm6tKli/74xz/q7NmzHn0vhM8Lr6CgIEVGRqpXr176/e9/r4MHD/roUwC+E+jrAoDGZtq0abruuusqtF9//fU+qMa3zpw5o8DAhvu/kcTERJ05c0bBwcG+LqWCefPmqby8vF62ffjwYT333HOKjo5W165dvbbfS2nfvr3OnDmjoKCgOtne6dOnNWLECPXo0UOjR49Wq1atlJ2drSlTpmjdunVav369LBaLxzpDhgzRPffco/LycuXn52vbtm2aNWuWXn75Zb355psaPHhwndQGNAYN9//cQAN19913q3v37r4uo0EIDQ31dQmXFBAQ0GBrrKsg1Fj2a7FY6vRYBAcH67PPPlOvXr3cbY899piio6PdITApKcljnZ/85CcaNmyYR9uBAwfUr18/paWlqXPnzoqLi6uzGoGGjFPAQB27cLpp5syZmjNnjjp06KCrrrpK/fr106FDh2QYhqZPn662bduqSZMm6t+/v06cOFHptjIzM9W1a1eFhoYqNjZWH374YYU+J0+e1Lhx49SuXTuFhITo+uuv1/PPP19hlOfkyZMaPny4wsLCFB4errS0NJ08ebLS/X700Ufq0qWLQkND1aVLFy1btqzSfhfPAZw6daosFov27t2r4cOHKzw8XGFhYRoxYoROnz7tse6ZM2f05JNPKjIyUs2aNVNqaqpyc3MvO6/wyJEjCgwM1HPPPVdh2Z49e2SxWPTqq69Kqnzu3TfffKOBAwcqKipKoaGhatu2rQYPHqyCggJJl56rdnFtBw4c0BNPPKGYmBg1adJELVq00AMPPKD9+/dXWf8FF8/F+9nPflbl9IILtZw4cUJPP/20HA6HbDab7Ha77r77bn311Vfu7WzcuFG33nqrJGnEiBEVtlHZHMDi4mI99dRT7u9QTEyMZs6cKcMwKnz+MWPGuL8fISEhuummm7Rq1arLft7K/q7Dhw+XzWZTbm6uBgwYIJvNppYtW+rpp5+Wy+W65PaCg4M9wt8F999/vyQpJyfnsjVJ50cmFyxYoJKSEr3wwgvVWgfwB4wAAjVUUFCgY8eOebRZLBa1aNHCo23hwoUqKSnR2LFjdeLECb3wwgt68MEHdccdd2jjxo363e9+p71792r27Nl6+umn9dZbb3ms/80332jQoEEaPXq00tLSNH/+fD3wwANatWqV7rzzTknnT4P16dNHubm5evzxx3Xttdfq888/16RJk/TDDz9o1qxZkiTDMNS/f39t2rRJo0ePVufOnbVs2TKlpaVV+HyZmZkaOHCgYmNjlZ6eruPHj2vEiBFq27Zttf9GDz74oK677jqlp6drx44d+utf/6pWrVrp+eefd/cZPny4lixZooceekg9evTQp59+qpSUlMtuu3Xr1urTp4+WLFmiKVOmeCxbvHixrFarHnjggUrXLSkpUXJyss6dO6exY8cqKipKubm5WrFihU6ePKmwsLBqf0ZJ2rZtmz7//HMNHjxYbdu21f79+/X666/rZz/7mXbv3q2rrrqq2tt65pln9Oijj3q0vffee1q9erVatWolSfruu+/00Ucf6YEHHtB1112nI0eO6I033lCfPn20e/dutWnTRp07d9a0adM0efJkjRo1Sr1795akSsOSdP67kZqaqg0bNmjkyJHq2rWrVq9erQkTJig3N1cvvfSSR/9Nmzbpww8/1BNPPKFmzZrplVde0cCBA3Xw4MEK/waqw+VyKTk5WQkJCZo5c6bWrl2rF198UR07dtSvfvWrGm8vLy9PkhQZGVntdXr27KmOHTtqzZo1Nd4f0GgZAKpl/vz5hqRKXyEhIe5++/btMyQZLVu2NE6ePOlunzRpkiHJiIuLM0pLS93tQ4YMMYKDg42zZ8+629q3b29IMv7+97+72woKCoyrr77auOWWW9xt06dPN5o2bWr8+9//9qh14sSJhtVqNQ4ePGgYhmF89NFHhiTjhRdecPcpKyszevfubUgy5s+f727v2rWrcfXVV3vUnpmZaUgy2rdv77EfScaUKVPc76dMmWJIMh555BGPfvfff7/RokUL9/vt27cbkoxx48Z59Bs+fHiFbVbmjTfeMCQZTqfToz02Nta444473O83bNhgSDI2bNhgGIZhfPnll4YkY+nSpVVu+8Lx+8+/SVWf9/Tp0xX6ZGdnG5KMd955p8o6DMMw0tLSKvw9/9Nnn31mBAUFefwtz549a7hcrgr1hoSEGNOmTXO3bdu2rcrPcPF+L3w3/vjHP3r0+8UvfmFYLBZj79697jZJRnBwsEfbV199ZUgyZs+eXeVnuVDnxTWlpaUZkjxqNwzDuOWWW4xu3bpdcntVSUpKMux2u5Gfn19h33/+85+rXK9///6GJKOgoKBW+wUaG04BAzU0Z84crVmzxuO1cuXKCv0eeOABjxGlhIQESdKwYcM8LpxISEhQSUmJcnNzPdZv06aN+3SWJNntdj388MP68ssv3aMcS5cuVe/evRUREaFjx465X0lJSXK5XMrKypIkffLJJwoMDPQYUbFarRo7dqzHPn/44Qft3LlTaWlpHrXfeeedio2NrfbfaPTo0R7ve/furePHj6uwsFCS3KcMn3jiCY9+F9dTlZ///OcKDAzU4sWL3W27du3S7t27NWjQoCrXu/CZVq9eXeGUdG00adLE/d+lpaU6fvy4rr/+eoWHh2vHjh213m5eXp5+8YtfqGvXrnrttdfc7SEhIQoIOP+/bZfLpePHj8tmsykmJqbW+/vkk09ktVr15JNPerQ/9dRTMgyjwnc7KSlJHTt2dL+/+eabZbfb9d1339Vq/1Ll35fabO9Pf/qT1q5dqxkzZig8PLxG69psNknSqVOnarxfoDHiFDBQQ/Hx8dW6COTaa6/1eH8hfLRr167S9vz8fI/266+/vsJVjDfccIOk8/OpoqKi9M033+if//ynWrZsWWkNR48elXR+rtrVV1/t/pG7ICYmxuP9gQMHJEmdOnWqsK2ahIyLP3tERISk85/RbrfrwIEDCggIqHA1dXWvpI6MjFTfvn21ZMkSTZ8+XdL507+BgYH6+c9/XuV61113ncaPH6+//OUvWrhwoXr37q3U1FQNGzasxqd/pfPzGNPT0zV//nzl5uZ6zJm7MKewpsrKyvTggw/K5XLpww8/VEhIiHtZeXm5Xn75Zb322mvat2+fxzy52px+lc4f8zZt2qhZs2Ye7Z07d3Yv/08XH1vp/PG9+PtbXaGhoRW+v7XZ3uLFi/Xss89q5MiRtTp1XFRUJEkV/g6AvyIAAvXEarXWqN24aMJ9dZSXl+vOO+/Ub3/720qXXwiM3laXn7EqgwcP1ogRI7Rz50517dpVS5YsUd++fS879+vFF1/U8OHD9fHHHyszM1NPPvmk0tPTtXnzZrVt27ZC6L6gsosSxo4dq/nz52vcuHHq2bOnwsLCZLFYNHjw4FrfamXChAnKzs7W2rVrK8y7/NOf/qQ//OEPeuSRRzR9+nQ1b95cAQEBGjdunNdu7VLXx7aq7dXEmjVr9PDDDyslJUVz586t1TZ27dqlVq1ayW63X3E9QGNAAAQaqL1798owDI9A8u9//1uS3FdxduzYUUVFRRVud3Gx9u3ba926dSoqKvIYBdyzZ0+FftL5C1AudnHfK9G+fXuVl5dr3759HqONe/furfY2BgwYoMcff9x9Gvjf//63Jk2aVK11HQ6HHA6Hnn32WX3++ef66U9/qrlz5+qPf/yje7Ty4iukLx4Jk6QPPvhAaWlpevHFF91tZ8+erfLq6stZtGiRZs2apVmzZqlPnz6V7u/222/Xm2++6dF+8uRJj+BbVYitTPv27bV27VqdOnXKY/Tr66+/di9vyLZs2aL7779f3bt315IlS2p1X8rs7Gx9++23FW4RA/gz5gACDdThw4c9br9SWFiod955R127dlVUVJSk81fbZmdna/Xq1RXWP3nypMrKyiRJ99xzj8rKyvT666+7l7tcLs2ePdtjnauvvlpdu3bV22+/7XEKc82aNdq9e3edfbbk5GRJ8pjfJqlCPZcSHh6u5ORkLVmyRIsWLVJwcLAGDBhwyXUKCwvdf5MLHA6HAgICdO7cOUnn51pGRka6509ecHGt0vnRq4tHvmbPnn3ZW5hUZteuXXr00Uc1bNgw/frXv660T2X7W7p0aYX5o02bNpVUMcRW5p577pHL5XLfOueCl156SRaLRXfffXcNPoV35eTkKCUlRdHR0VqxYoXHnMzqOnDggIYPH67g4GBNmDChHqoEGiZGAIEaWrlypXt05D/16tVLHTp0qLP93HDDDRo5cqS2bdum1q1b66233tKRI0c0f/58d58JEyZo+fLluvfeezV8+HB169ZNxcXFcjqd+uCDD7R//35FRkbqvvvu009/+lNNnDhR+/fvd99TsLJ5aunp6UpJSdFtt92mRx55RCdOnNDs2bN10003uedJXalu3bpp4MCBmjVrlo4fP+6+DcyFEc7qjmANGjRIw4YN02uvvabk5OTLTvxfv369xowZowceeEA33HCDysrK9O6778pqtWrgwIHufo8++qhmzJihRx99VN27d1dWVpa7tv9077336t1331VYWJhiY2Pdp25rMx9vxIgRks4/veS9997zWHbhu3Xvvfdq2rRpGjFihHr16iWn06mFCxdW+N517NhR4eHhmjt3rpo1a6amTZsqISGh0ifY3Hfffbr99tv1zDPPaP/+/YqLi1NmZqY+/vhjjRs3zuOCj4bk1KlTSk5OVn5+viZMmKCMjAyP5R07dlTPnj092nbs2KH33ntP5eXlOnnypLZt26a///3vslgsevfdd3XzzTd78yMAPkUABGpo8uTJlbbPnz+/TgNgp06dNHv2bE2YMEF79uzRddddp8WLF7tHzyTpqquu0qeffqo//elPWrp0qd555x3Z7XbdcMMNeu6559wXNgQEBGj58uUaN26c3nvvPVksFqWmpurFF1/ULbfc4rHfu+66S0uXLtWzzz6rSZMmqWPHjpo/f74+/vhjjxsqX6l33nlHUVFRev/997Vs2TIlJSVp8eLFiomJqfYTI1JTU9WkSROdOnXqklf/XhAXF6fk5GT9z//8j3Jzc3XVVVcpLi5OK1euVI8ePdz9Jk+erB9//FEffPCBlixZorvvvlsrV65034/vgpdffllWq1ULFy7U2bNn9dOf/lRr1671OEbV9eOPP6q4uFijRo2qsOzCd+v3v/+9iouL9be//U2LFy/WT37yE2VkZGjixIke/YOCgvT2229r0qRJGj16tMrKyjR//vxKA+CF78bkyZO1ePFizZ8/X9HR0frzn/+sp556qsafw1uOHz+uQ4cOSVKFzy9JaWlpFQLg+++/r/fff1+BgYGy2+3q1KmTxo0bp9GjR1d6cQvgzyxGXc7KBoArsHPnTt1yyy167733NHToUF+XAwB+izmAAHzizJkzFdpmzZqlgIAAJSYm+qAiADAPTgED8IkXXnhB27dv1+23367AwECtXLlSK1eu1KhRoyrcKxEAULc4BQzAJ9asWaPnnntOu3fvVlFRka699lo99NBDeuaZZ2p1Kw8AQPURAAEAAEyGOYAAAAAmQwAEAAAwGQIgAACAyTDT+gqUl5fr8OHDatasWY2evQkAAHzHMAydOnVKbdq0UUCAOcfCCIBX4PDhw9yuAgCARurQoUNq27atr8vwCQLgFWjWrJmk818gu93u42oAAEB1FBYWql27du7fcTMiAF6BC6d97XY7ARAAgEbGzNO3zHniGwAAwMQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAw3ggYA+Fx+fr6cTqeKiopks9nkcDgUERHh67IAv0UABAD4jMvlUkZGhjKzNuv4GZesoTa5zhapxfJV6pfYQykpKbJarb4uE/A7BEAAgM9kZGRoyep/KDImXt06xcoaGKSy0hLl7s3RktWbJEmpqak+rhLwP8wBBAD4RH5+vjKzNisyJl7tO8fJGhgkSQoMClb7znGKjLlVmVmblZ+f7+NKAf9DAAQA+ITT6dTxMy617RRb6fK2nWJ1/IxLTqfTy5UB/o8ACADwiaKiIllDbe6Rv4tZA4NkDW2qoqIiL1cG+D8CIADAJ2y28xd8uMpKK11eVloi19li2Ww2L1cG+D8CIADAJxwOh1o0ser7b3ZXujx3b45aNLHK4XB4uTLA/xEAAQA+ERERoX6JPXRszzYdyPnKPRJYVlqiAzlf6diebeqX2IP7AQL1gNvAAAB8JiUlRZKUmbVZ2/d8IWtoU7nOFqtFE6seTL7NvRxA3bIYhmH4uojGqrCwUGFhYSooKJDdbvd1OQDQaPEkEHgTv9+MAAIAGoCIiAglJib6ugzANJgDCAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyfhVAJwzZ46io6MVGhqqhIQEbd26tVrrLVq0SBaLRQMGDKjfAgEAABoAvwmAixcv1vjx4zVlyhTt2LFDcXFxSk5O1tGjRy+53v79+/X000+rd+/eXqoUAADAt/wmAP7lL3/RY489phEjRig2NlZz587VVVddpbfeeqvKdVwul4YOHarnnntOHTp08GK1AAAAvuMXAbCkpETbt29XUlKSuy0gIEBJSUnKzs6ucr1p06apVatWGjlyZLX2c+7cORUWFnq8AAAAGhu/CIDHjh2Ty+VS69atPdpbt26tvLy8StfZtGmT3nzzTc2bN6/a+0lPT1dYWJj71a5duyuqGwAAwBf8IgDW1KlTp/TQQw9p3rx5ioyMrPZ6kyZNUkFBgft16NCheqwSAACgfgT6uoC6EBkZKavVqiNHjni0HzlyRFFRURX6f/vtt9q/f7/uu+8+d1t5ebkkKTAwUHv27FHHjh0rrBcSEqKQkJA6rh4AAMC7/GIEMDg4WN26ddO6devcbeXl5Vq3bp169uxZof+NN94op9OpnTt3ul+pqam6/fbbtXPnTk7tAgAAv+YXI4CSNH78eKWlpal79+6Kj4/XrFmzVFxcrBEjRkiSHn74YV1zzTVKT09XaGiounTp4rF+eHi4JFVoBwAA8Dd+EwAHDRqkH3/8UZMnT1ZeXp66du2qVatWuS8MOXjwoAIC/GLAEwAA4IpYDMMwfF1EY1VYWKiwsDAVFBTIbrf7uhwAAFAN/H77yRxAAAAAVB8BEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkwn0dQEAgMYvPz9fTqdTRUVFstlscjgcioiI8HVZAKpAAAQA1JrL5VJGRoYyszbr+BmXrKE2uc4WqcXyVeqX2EMpKSmyWq2+LhPARQiAAIBay8jI0JLV/1BkTLy6dYqVNTBIZaUlyt2boyWrN0mSUlNTfVwlgIsxBxAAUCv5+fnKzNqsyJh4te8cJ2tgkCQpMChY7TvHKTLmVmVmbVZ+fr6PKwVwMQIgAKBWnE6njp9xqW2n2EqXt+0Uq+NnXHI6nV6uDMDlEAABALVSVFQka6jNPfJ3MWtgkKyhTVVUVOTlygBcDgEQAFArNtv5Cz5cZaWVLi8rLZHrbLFsNpuXKwNwOQRAAECtOBwOtWhi1fff7K50ee7eHLVoYpXD4fByZQAuhwAIAKiViIgI9UvsoWN7tulAzlfukcCy0hIdyPlKx/ZsU7/EHtwPEGiAuA0MAKDWUlJSJEmZWZu1fc8XsoY2letssVo0serB5NvcywE0LBbDMAxfF9FYFRYWKiwsTAUFBbLb7b4uBwB8hieBoDHh95sRQABAHYiIiFBiYqKvywBQTcwBBAAAMBkCIAAAgMkQAAEAAEyGAAgAAGAyBEAAAACTIQACAACYDAEQAADAZAiAAAAAJkMABAAAMBkCIAAAgMkQAAEAAEyGAAgAAGAyBEAAAACTIQACAACYDAEQAADAZAiAAAAAJkMABAAAMBkCIAAAgMkQAAEAAEyGAAgAAGAyBEAAAACTIQACAACYDAEQAADAZAiAAAAAJkMABAAAMBkCIAAAgMkQAAEAAEyGAAgAAGAyBEAAAACTIQACAACYDAEQAADAZAiAAAAAJkMABAAAMBkCIAAAgMkQAAEAAEyGAAgAAGAyBEAAAACTIQACAACYDAEQAADAZPwqAM6ZM0fR0dEKDQ1VQkKCtm7dWmXfefPmqXfv3oqIiFBERISSkpIu2R8AAMBf+E0AXLx4scaPH68pU6Zox44diouLU3Jyso4ePVpp/40bN2rIkCHasGGDsrOz1a5dO/Xr10+5ublerhwAAMC7LIZhGL4uoi4kJCTo1ltv1auvvipJKi8vV7t27TR27FhNnDjxsuu7XC5FRETo1Vdf1cMPP1ytfRYWFiosLEwFBQWy2+1XVD8AAPAOfr/9ZASwpKRE27dvV1JSkrstICBASUlJys7OrtY2Tp8+rdLSUjVv3ry+ygQAAGgQAn1dQF04duyYXC6XWrdu7dHeunVrff3119Xaxu9+9zu1adPGI0Re7Ny5czp37pz7fWFhYe0KBgAA8CG/GAG8UjNmzNCiRYu0bNkyhYaGVtkvPT1dYWFh7le7du28WCUAAEDd8IsAGBkZKavVqiNHjni0HzlyRFFRUZdcd+bMmZoxY4YyMzN18803X7LvpEmTVFBQ4H4dOnToimsHAADwNr8IgMHBwerWrZvWrVvnbisvL9e6devUs2fPKtd74YUXNH36dK1atUrdu3e/7H5CQkJkt9s9XgAAAI2NX8wBlKTx48crLS1N3bt3V3x8vGbNmqXi4mKNGDFCkvTwww/rmmuuUXp6uiTp+eef1+TJk/W3v/1N0dHRysvLkyTZbDbZbDaffQ4AAID65jcBcNCgQfrxxx81efJk5eXlqWvXrlq1apX7wpCDBw8qIOD/Bzxff/11lZSU6Be/+IXHdqZMmaKpU6d6s3QAAACv8pv7APoC9xECAKDx4ffbT+YAAgAAoPoIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMoG+LgDmlZ+fL6fTqaKiItlsNjkcDkVERPi6LAAA/B4BEF7ncrmUkZGhzKzNOn7GJWuoTa6zRWqxfJX6JfZQSkqKrFarr8sEAMBv1WkAfO211/Thhx+qefPmevzxx9W3b1/3smPHjik+Pl7fffddXe4SjVBGRoaWrP6HImPi1a1TrKyBQSorLVHu3hwtWb1JkpSamurjKgEA8F91NgfwlVde0YQJE3TjjTcqJCRE99xzj9LT093LXS6XDhw4UFe7QyOVn5+vzKzNioyJV/vOcbIGBkmSAoOC1b5znCJjblVm1mbl5+f7uFIAAPxXnQXAN954Q/PmzdOrr76qd999Vxs2bNBLL72kyZMn19Uu4AecTqeOn3GpbafYSpe37RSr42dccjqdXq4MAADzqLNTwPv27VOvXr3c73v16qX169crKSlJpaWlGjduXF3tCo1YUVGRrKE298jfxayBQbKGNlVRUZGXKwMAwDzqLABGRkbq0KFDio6Odrd16dJF69ev1x133KHDhw/X1a7QiNls5y/4cJWVVhoCy0pL5DpbLJvN5oPqAAAwhzo7BXzbbbfpww8/rNAeGxurdevWaeXKlXW1KzRiDodDLZpY9f03uytdnrs3Ry2aWOVwOLxcGQAA5lFnI4ATJ07U9u3bK1120003af369fr73/9eV7tDIxUREaF+iT3cV/u2vegq4GN7tunB5Nu4HyAAAPXIYhiG4YsdP/HEE5o2bZoiIyN9sfs6UVhYqLCwMBUUFMhut/u6nEaj4n0Am8p1tlgtmli5DyAAoN7x++3DAGi327Vz50516NDBF7uvE3yBrgxPAgEA+AK/3z58EoiPcicakIiICCUmJvq6DAAATKfOLgIBAABA40AABAAAMBkCIAAAgMkQAAEAAEymzgLgH/7wB5WVlVW5/ODBg7rzzjvd74cNG2baK28AAAB8qc4C4Ntvv61bb71Vu3btqrDsjTfeUJcuXRQY+P8XHb/++uuN+h6AAAAAjVWdBcBdu3bJ4XCoe/fuSk9PV3l5uQ4ePKikpCT99re/1cyZM3kcHAAAQANQ5zeC/vjjj/X4448rKipK+/btU3x8vP7617+qffv2dbmbBoEbSQIA0Pjw+10PF4H06NFDDodD//znP1VeXq5nn33WL8MfAABAY1WnAfD9999XbGysysvLlZOTo1/96lfq16+ffvOb3+js2bN1uSsAAADUUp0FwIEDB+qxxx7T1KlTtW7dOsXExOiFF17Qhg0b9MknnyguLk7Z2dl1tTsAAADUUp09CzgvL09ffvmlOnXq5NHeq1cv7dy5UxMnTlSfPn1UUlJSV7sEAABALdTZRSDl5eUKCLj0gGJWVpYSExPrYncNApNIAQBofPj9rsNTwJcLf5L8KvwBAAA0VjwKDgAAwGQIgAAAACZDAAQAADAZAiAAAIDJ+FUAnDNnjqKjoxUaGqqEhARt3br1kv2XLl2qG2+8UaGhoXI4HPrkk0+8VCkAAIDv+E0AXLx4scaPH68pU6Zox44diouLU3Jyso4ePVpp/88//1xDhgzRyJEj9eWXX2rAgAEaMGCAdu3a5eXKAQAAvKvO7gPoawkJCbr11lv16quvSjp/X8J27dpp7NixmjhxYoX+gwYNUnFxsVasWOFu69Gjh7p27aq5c+dWa5/cRwgAgMaH328/GQEsKSnR9u3blZSU5G4LCAhQUlJSlY+fy87O9ugvScnJyZd8XN25c+dUWFjo8QIAAGhs/CIAHjt2TC6XS61bt/Zob926tfLy8ipdJy8vr0b9JSk9PV1hYWHuV7t27a68eAAAAC/ziwDoLZMmTVJBQYH7dejQIV+XBAAAUGOBvi6gLkRGRspqterIkSMe7UeOHFFUVFSl60RFRdWovySFhIQoJCTkygsGAADwIb8YAQwODla3bt20bt06d1t5ebnWrVunnj17VrpOz549PfpL0po1a6rsDwAA4C/8YgRQksaPH6+0tDR1795d8fHxmjVrloqLizVixAhJ0sMPP6xrrrlG6enpkqRf//rX6tOnj1588UWlpKRo0aJF+uKLL/Tf//3fvvwYAAAA9c5vAuCgQYP0448/avLkycrLy1PXrl21atUq94UeBw8eVEDA/w949urVS3/729/07LPP6ve//706deqkjz76SF26dPHVRwAAAPAKv7kPoC9wHyEAABoffr/9ZA4gAAAAqo8ACAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJgMARAAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJhMoK8LQEX5+flyOp0qKiqSzWaTw+FQRESEr8sCAAB+ggDYgLhcLmVkZCgza7OOn3HJGmqT62yRWixfpX6JPZSSkiKr1errMgEAQCNHAGxAMjIytGT1PxQZE69unWJlDQxSWWmJcvfmaMnqTZKk1NRUH1cJAAAaO+YANhD5+fnKzNqsyJh4te8cJ2tgkCQpMChY7TvHKTLmVmVmbVZ+fr6PKwUAAI0dAbCBcDqdOn7GpbadYitd3rZTrI6fccnpdHq5MgAA4G8IgA1EUVGRrKE298jfxayBQbKGNlVRUZGXKwMAAP6GANhA2GznL/hwlZVWurystESus8Wy2WxergwAAPgbAmAD4XA41KKJVd9/s7vS5bl7c9SiiVUOh8PLlQEAAH9DAGwgIiIi1C+xh47t2aYDOV+5RwLLSkt0IOcrHduzTf0Se3A/QAAAcMW4DUwDkpKSIknKzNqs7Xu+kDW0qVxni9WiiVUPJt/mXg4AAHAlLIZhGL4uorEqLCxUWFiYCgoKZLfb62y7PAkEAID6U1+/340JI4ANUEREhBITE31dBgAA8FPMAQQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkwn0dQGomfz8fDmdThUVFclms8nhcCgiIsLXZQEAgEaEANhIuFwuZWRkKDNrs46fcckaapPrbJFaLF+lfok9lJKSIqvV6usyAQBAI0AAbCQyMjK0ZPU/FBkTr26dYmUNDFJZaYly9+ZoyepNkqTU1FQfVwkAABoD5gA2Avn5+crM2qzImHi17xwna2CQJCkwKFjtO8cpMuZWZWZtVn5+vo8rBQAAjQEBsBFwOp06fsaltp1iK13etlOsjp9xyel0erkyAADQGBEAG4GioiJZQ23ukb+LWQODZA1tqqKiIi9XBgAAGiMCYCNgs52/4MNVVlrp8rLSErnOFstms3m5MgAA0Bj5RQA8ceKEhg4dKrvdrvDwcI0cOfKSo2EnTpzQ2LFjFRMToyZNmujaa6/Vk08+qYKCAi9WXX0Oh0Mtmlj1/Te7K12euzdHLZpY5XA4vFwZAABojPwiAA4dOlT/+te/tGbNGq1YsUJZWVkaNWpUlf0PHz6sw4cPa+bMmdq1a5cWLFigVatWaeTIkV6suvoiIiLUL7GHju3ZpgM5X7lHAstKS3Qg5ysd27NN/RJ7cD9AAABQLRbDMAxfF3ElcnJyFBsbq23btql79+6SpFWrVumee+7R999/rzZt2lRrO0uXLtWwYcNUXFyswMDq3R2nsLBQYWFhKigokN1ur/VnqI6K9wFsKtfZYrVoYuU+gAAA1IA3f78bqkZ/H8Ds7GyFh4e7w58kJSUlKSAgQFu2bNH9999fre1c+BJcKvydO3dO586dc78vLCysfeE1ZLValZqaqt69e/MkEAAAcEUafQDMy8tTq1atPNoCAwPVvHlz5eXlVWsbx44d0/Tp0y952liS0tPT9dxzz9W61roQERGhxMREn9YAAAAatwY7B3DixImyWCyXfH399ddXvJ/CwkKlpKQoNjZWU6dOvWTfSZMmqaCgwP06dOjQFe8fAADA2xrsCOBTTz2l4cOHX7JPhw4dFBUVpaNHj3q0l5WV6cSJE4qKirrk+qdOndJdd92lZs2aadmyZQoKqvw+exeEhIQoJCSkWvUDAAA0VA02ALZs2VItW7a8bL+ePXvq5MmT2r59u7p16yZJWr9+vcrLy5WQkFDleoWFhUpOTlZISIiWL1+u0NDQOqsdAACgIWuwp4Crq3Pnzrrrrrv02GOPaevWrfrss880ZswYDR482H0FcG5urm688UZt3bpV0vnw169fPxUXF+vNN99UYWGh8vLylJeXJ5fL5cuPAwAAUO8a7AhgTSxcuFBjxoxR3759FRAQoIEDB+qVV15xLy8tLdWePXt0+vRpSdKOHTu0ZcsWSdL111/vsa19+/YpOjraa7UDAAB4W6O/D6AvcR8hAAAaH36//eAUMAAAAGqGAAgAAGAyfjEHEAAAf5Cfn8/TnuAVBEAAAHys4vPebXKdLVKL5at43jvqBQEQAAAfy8jI0JLV/1BkTLy6dYqVNTBIZaUlyt2boyWrN0mSUlNTfVwl/AlzAAEA8KH8/HxlZm1WZEy82neOkzXw/FOpAoOC1b5znCJjblVm1mbl5+f7uFL4EwIgAAA+5HQ6dfyMS207xVa6vG2nWB0/45LT6fRyZfBnBEAAAHyoqKhI1lCbe+TvYtbAIFlDm6qoqMjLlcGfEQABAPAhm+38BR+ustJKl5eVlsh1tlg2m83LlcGfEQABAPAhh8OhFk2s+v6b3ZUuz92boxZNrHI4HF6uDP6MAAgAgA9FRESoX2IPHduzTQdyvnKPBJaVluhAzlc6tmeb+iX24H6AqFPcBgYAAB9LSUmRJGVmbdb2PV/IGtpUrrPFatHEqgeTb3MvB+qKxTAMw9dFNFY8TBoAUJd4Eoh38PvNCCAAAA1GRESEEhMTfV0GTIA5gAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQCfV0AAADAf8rPz5fT6VRRUZFsNpscDociIiJ8XZZfIQACAIAGweVyKSMjQ5lZm3X8jEvWUJtcZ4vUYvkq9UvsoZSUFFmtVl+X6RcIgAAAoEHIyMjQktX/UGRMvLp1ipU1MEhlpSXK3ZujJas3SZJSU1N9XKV/YA4gAADwufz8fGVmbVZkTLzad46TNTBIkhQYFKz2neMUGXOrMrM2Kz8/38eV+gcCIAAA8Dmn06njZ1xq2ym20uVtO8Xq+BmXnE6nlyvzTwRAAADgc0VFRbKG2twjfxezBgbJGtpURUVFXq7MPxEAAQCAz9ls5y/4cJWVVrq8rLRErrPFstlsXq7MPxEAAQCAzzkcDrVoYtX33+yudHnu3hy1aGKVw+HwcmX+iQAIAAB8LiIiQv0Se+jYnm06kPOVeySwrLREB3K+0rE929QvsQf3A6wj3AYGAAA0CCkpKZKkzKzN2r7nC1lDm8p1tlgtmlj1YPJt7uW4chbDMAxfF9FYFRYWKiwsTAUFBbLb7b4uBwAAv1DfTwLh95sRQAAA0MBEREQoMTHR12X4NeYAAgAAmIxfBMATJ05o6NChstvtCg8P18iRI6t9nyDDMHT33XfLYrHoo48+qt9CAQAAGgC/CIBDhw7Vv/71L61Zs0YrVqxQVlaWRo0aVa11Z82aJYvFUs8VAgAANByNfg5gTk6OVq1apW3btql79+6SpNmzZ+uee+7RzJkz1aZNmyrX3blzp1588UV98cUXuvrqq71VMgAAgE81+hHA7OxshYeHu8OfJCUlJSkgIEBbtmypcr3Tp0/rl7/8pebMmaOoqChvlAoAANAgNPoRwLy8PLVq1cqjLTAwUM2bN1deXl6V6/3mN79Rr1691L9//2rv69y5czp37pz7fWFhYc0LBgAA8LEGOwI4ceJEWSyWS76+/vrrWm17+fLlWr9+vWbNmlWj9dLT0xUWFuZ+tWvXrlb7BwAA8KUGOwL41FNPafjw4Zfs06FDB0VFReno0aMe7WVlZTpx4kSVp3bXr1+vb7/9VuHh4R7tAwcOVO/evbVx48ZK15s0aZLGjx/vfl9YWEgIBAAAjU6DDYAtW7ZUy5YtL9uvZ8+eOnnypLZv365u3bpJOh/wysvLlZCQUOk6EydO1KOPPurR5nA49NJLL+m+++6rcl8hISEKCQmpwacAAABoeBpsAKyuzp0766677tJjjz2muXPnqrS0VGPGjNHgwYPdVwDn5uaqb9++eueddxQfH6+oqKhKRwevvfZaXXfdddXe94Wn6DEXEACAxuPC77aZn4bb6AOgJC1cuFBjxoxR3759FRAQoIEDB+qVV15xLy8tLdWePXt0+vTpOt3vqVOnJInTwAAANEKnTp1SWFiYr8vwCYth5vh7hcrLy3X48GE1a9bMKzeTvjDn8NChQ6Z9eHVjwHFqHDhOjQPHqXFobMfJMAydOnVKbdq0UUBAg70etl75xQigrwQEBKht27Ze36/dbm8U/8DMjuPUOHCcGgeOU+PQmI6TWUf+LjBn7AUAADAxAiAAAIDJEAAbkZCQEE2ZMoVb0TRwHKfGgePUOHCcGgeOU+PDRSAAAAAmwwggAACAyRAAAQAATIYACAAAYDIEQAAAAJMhADZgJ06c0NChQ2W32xUeHq6RI0eqqKioWusahqG7775bFotFH330Uf0WihofqxMnTmjs2LGKiYlRkyZNdO211+rJJ59UQUGBF6v2f3PmzFF0dLRCQ0OVkJCgrVu3XrL/0qVLdeONNyo0NFQOh0OffPKJlyo1t5ocp3nz5ql3796KiIhQRESEkpKSLntcUTdq+u/pgkWLFslisWjAgAH1WyBqhADYgA0dOlT/+te/tGbNGq1YsUJZWVkaNWpUtdadNWuWVx5Ph/NqeqwOHz6sw4cPa+bMmdq1a5cWLFigVatWaeTIkV6s2r8tXrxY48eP15QpU7Rjxw7FxcUpOTlZR48erbT/559/riFDhmjkyJH68ssvNWDAAA0YMEC7du3ycuXmUtPjtHHjRg0ZMkQbNmxQdna22rVrp379+ik3N9fLlZtLTY/TBfv379fTTz+t3r17e6lSVJuBBmn37t2GJGPbtm3utpUrVxoWi8XIzc295Lpffvmlcc011xg//PCDIclYtmxZPVdrbldyrP7TkiVLjODgYKO0tLQ+yjSd+Ph447/+67/c710ul9GmTRsjPT290v4PPvigkZKS4tGWkJBgPP744/Vap9nV9DhdrKyszGjWrJnx9ttv11eJMGp3nMrKyoxevXoZf/3rX420tDSjf//+XqgU1cUIYAOVnZ2t8PBwde/e3d2WlJSkgIAAbdmypcr1Tp8+rV/+8peaM2eOoqKivFGq6dX2WF2soKBAdrtdgYE8ovtKlZSUaPv27UpKSnK3BQQEKCkpSdnZ2ZWuk52d7dFfkpKTk6vsjytXm+N0sdOnT6u0tFTNmzevrzJNr7bHadq0aWrVqhVnNhoofmkaqLy8PLVq1cqjLTAwUM2bN1deXl6V6/3mN79Rr1691L9///ouEf+ntsfqPx07dkzTp0+v9il+XNqxY8fkcrnUunVrj/bWrVvr66+/rnSdvLy8SvtX9xii5mpznC72u9/9Tm3atKkQ3lF3anOcNm3apDfffFM7d+70QoWoDUYAvWzixImyWCyXfFX3f3wXW758udavX69Zs2bVbdEmVZ/H6j8VFhYqJSVFsbGxmjp16pUXDpjEjBkztGjRIi1btkyhoaG+Lgf/59SpU3rooYc0b948RUZG+rocVIERQC976qmnNHz48Ev26dChg6KioipMri0rK9OJEyeqPLW7fv16ffvttwoPD/doHzhwoHr37q2NGzdeQeXmU5/H6oJTp07prrvuUrNmzbRs2TIFBQVdadmQFBkZKavVqiNHjni0HzlypMpjEhUVVaP+uHK1OU4XzJw5UzNmzNDatWt1880312eZplfT4/Ttt99q//79uu+++9xt5eXlks6fHdmzZ486duxYv0Xj8nw9CRGVu3BhwRdffOFuW7169SUvLPjhhx8Mp9Pp8ZJkvPzyy8Z3333nrdJNpzbHyjAMo6CgwOjRo4fRp08fo7i42Bulmkp8fLwxZswY93uXy2Vcc801l7wI5N577/Vo69mzJxeB1LOaHifDMIznn3/esNvtRnZ2tjdKhFGz43TmzJkKv0X9+/c37rjjDsPpdBrnzp3zZumoAgGwAbvrrruMW265xdiyZYuxadMmo1OnTsaQIUPcy7///nsjJibG2LJlS5XbEFcBe0VNj1VBQYGRkJBgOBwOY+/evcYPP/zgfpWVlfnqY/iVRYsWGSEhIcaCBQuM3bt3G6NGjTLCw8ONvLw8wzAM46GHHjImTpzo7v/ZZ58ZgYGBxsyZM42cnBxjypQpRlBQkOF0On31EUyhpsdpxowZRnBwsPHBBx94/Ls5deqUrz6CKdT0OF2Mq4AbHgJgA3b8+HFjyJAhhs1mM+x2uzFixAiP/8nt27fPkGRs2LChym0QAL2jpsdqw4YNhqRKX/v27fPNh/BDs2fPNq699lojODjYiI+PNzZv3uxe1qdPHyMtLc2j/5IlS4wbbrjBCA4ONm666SYjIyPDyxWbU02OU/v27Sv9dzNlyhTvF24yNf339J8IgA2PxTAMw9unnQEAAOA7XAUMAABgMgRAAAAAkyEAAgAAmAwBEAAAwGQIgAAAACZDAAQAADAZAiAAAIDJEAABAABMhgAIwDRcLpd69eqln//85x7tBQUFateunZ555pnLbuPJJ59Ut27dFBISoq5du9ZTpQBQvwiAAEzDarVqwYIFWrVqlRYuXOhuHzt2rJo3b64pU6ZUazuPPPKIBg0aVF9lAkC9C/R1AQDgTTfccINmzJihsWPH6o477tDWrVu1aNEibdu2TcHBwZdd/5VXXpEk/fjjj/rnP/9Z3+UCQL0gAAIwnbFjx2rZsmV66KGH5HQ6NXnyZMXFxfm6LADwGgIgANOxWCx6/fXX1blzZzkcDk2cONHXJQGAVzEHEIApvfXWW7rqqqu0b98+ff/9974uBwC8igAIwHQ+//xzvfTSS1qxYoXi4+M1cuRIGYbh67IAwGsIgABM5fTp0xo+fLh+9atf6fbbb9ebb76prVu3au7cub4uDQC8hgAIwFQmTZokwzA0Y8YMSVJ0dLRmzpyp3/72t9q/f/9l19+7d6927typvLw8nTlzRjt37tTOnTtVUlJSz5UDQN2xGJz3AGASn376qfr27auNGzfqtttu81iWnJyssrIyrV27VhaLpcpt/OxnP9Onn35aoX3fvn2Kjo6u65IBoF4QAAEAAEyGU8AAAAAmQwAEgP8zevRo2Wy2Sl+jR4/2dXkAUGc4BQwA/+fo0aMqLCysdJndblerVq28XBEA1A8CIAAAgMlwChgAAMBkCIAAAAAmQwAEAAAwGQIgAACAyRAAAQAATIYACAAAYDIEQAAAAJMhAAIAAJjM/wLGRjohSXCAGwAAAABJRU5ErkJggg==", + "text/html": [ + "\n", + "
\n", + "
\n", + " Figure\n", + "
\n", + " \n", + "
\n", + " " + ], + "text/plain": [ + "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "import mplcursors\n", + "%matplotlib ipympl\n", + "\n", + "from utils import plot_2D\n", + "plot_2D(new_values[:,0], new_values[:,1], input_text_lst_news)" + ] + }, + { + "cell_type": "markdown", + "id": "20c789c6-7f12-41ab-96a0-15aea8082a1a", + "metadata": {}, + "source": [ + "#### Embeddings and Similarity\n", + "- Plot a heat map to compare the embeddings of sentences that are similar and sentences that are dissimilar." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "99dcb75a-abd7-4a45-a78b-3800fb4cf559", + "metadata": { + "height": 236 + }, + "outputs": [], + "source": [ + "in_1 = \"\"\"He couldn’t desert \n", + " his post at the power plant.\"\"\"\n", + "\n", + "in_2 = \"\"\"The power plant needed \n", + " him at the time.\"\"\"\n", + "\n", + "in_3 = \"\"\"Cacti are able to \n", + " withstand dry environments.\"\"\" \n", + "\n", + "in_4 = \"\"\"Desert plants can \n", + " survive droughts.\"\"\" \n", + "\n", + "input_text_lst_sim = [in_1, in_2, in_3, in_4]" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "f86c0c3d-87d9-4601-bc03-dd998bf12166", + "metadata": { + "height": 117 + }, + "outputs": [], + "source": [ + "embeddings = []\n", + "for input_text in input_text_lst_sim:\n", + " emb = embedding_model.get_embeddings([input_text])[0].values\n", + " embeddings.append(emb)\n", + " \n", + "embeddings_array = np.array(embeddings) " + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "e5057cff-18dc-42a8-918a-86e54c2e7c0f", + "metadata": { + "height": 117 + }, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "9817b7fcb943416395c18e1d86d22265", + "version_major": 2, + "version_minor": 0 + }, + "image/png": "iVBORw0KGgoAAAANSUhEUgAAE4gAAAEsCAYAAAAvVFnUAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOzdd5hcV33/8c9snbK72pW00u5K27Sr1apX23I3YMemGAzEDuAAJjSb4pBgAiSEUANOcEJwgBBCMARMCLhggg22cbfVe9f2MjPb6/SZnfn94R96onzPGCuYSEner+fR83jPtHPvPfec7yn32JPL5XICAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJx1BWc7AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACA57FBHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcI9ggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOEWwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADnCDaIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBzBBvEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMA5gg3iAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAcwQZxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCOYIM4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADhHsEEcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJwj2CAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM4RbBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOcINogDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgHMEG8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwDmCDeIAAAAAAAAAAAAAAAAAAPgfrqmpSa95zWt+67/T29srj8eju+6669e+96abblJTU9NpaR6PR5/61Kd+K3kDAAAAAAAAAAAAAAAAgP8t2CAOAAAAAAAAAAAAAAAAAIDfgrvuuksejyfvv+3bt5/tLOI/+NX12r17t/P1K664QmvWrPmt5uHBBx9kAz0AAAAAAAAAAAAAAAAAKjrbGQAAAAAAAAAAAAAAAAAA4H+zz3zmM2pubjbpra2tZyE3Z1c8HldREUsX83nwwQf11a9+lU3iAAAAAAAAAAAAAAAAgP/jWGUFAAAAAAAAAAAAAAAAAMBv0Stf+Upt2bLlbGfjnOD1es92FgAAAAAAAAAAAAAAAADgnFdwtjMAAAAAAAAAAAAAAAAAAMD/Zb29vfJ4PPrSl76kr371q1q2bJn8fr9+53d+RwMDA8rlcvrsZz+rpUuXyufz6XWve50mJiac3/Xwww9rw4YN8nq9WrVqle69917znqmpKX3oQx9SfX29SktL1draqttvv13ZbNa876abbtK8efNUWVmpt7/97ZqamnL+7v333681a9bI6/VqzZo1uu+++5zv83g8+tSnPnXq70996lPyeDzq7OzUTTfdpMrKSs2bN0/veMc7FIvFTvtsPB7XrbfeqoULF6q8vFyvfe1rFQwGzXfOzs7qQx/6kJqamlRaWqpFixbpqquu0t69e515+k1973vf0+bNm+Xz+TR//ny96U1v0sDAwGnvefrpp3X99deroaFBpaWlqq+v1x/90R8pHo+fes9NN92kr371q5KeP0+/+ie9NGXkJz/5iV796lerrq5OpaWlamlp0Wc/+1nNzc2d9r4rrrhCa9as0Z49e3TRRRfJ5/OpublZ//AP//DbOH0AAAAAAAAAAAAAAAAAHIrOdgYAAAAAAAAAAAAAAAAAAPjfbHp6WmNjY6eleTweLViw4LS073//+0qlUvrgBz+oiYkJ/dVf/ZVuuOEGvfzlL9cTTzyhj370o+rs7NSdd96p2267Tf/8z/982uc7Ojr0e7/3e7r55pv19re/Xd/+9rd1/fXX6+c//7muuuoqSVIsFtPll1+uYDCo9773vWpoaNBzzz2nj3/84wqHw/ryl78sScrlcnrd616nZ555RjfffLNWrlyp++67T29/+9vN8T388MN64xvfqFWrVukLX/iCxsfH9Y53vENLly590efohhtuUHNzs77whS9o7969+qd/+ictWrRIt99++6n33HTTTfq3f/s3vfWtb9XWrVv15JNP6tWvfrX5rptvvlk//vGP9YEPfECrVq3S+Pi4nnnmGR07dkybNm36tXlxXS9JSqfTJu3zn/+8/vzP/1w33HCD3vWud2l0dFR33nmnLrvsMu3bt0+VlZWSpB/96EeKxWK65ZZbtGDBAu3cuVN33nmnBgcH9aMf/UiS9N73vlehUEiPPPKI/uVf/sWZt9+kjNx1110qKyvTH//xH6usrEyPPfaYPvnJT2pmZkZ//dd/fdrvTE5O6lWvepVuuOEGvfnNb9a//du/6ZZbblFJSYn+4A/+4NeeQwAAAAAAAAAAAAAAAAC/GTaIAwAAAAAAAAAAAAAAAADgt+jKK680aaWlpUokEqelBYNBdXR0aN68eZKkubk5feELX1A8Htfu3btVVPT8kr/R0VF9//vf19e//nWVlpae+vzJkyd1zz336A1veIMk6Z3vfKfa29v10Y9+9NQGcX/zN3+jrq4u7du3T8uXL5f0/MZkdXV1+uu//mt9+MMfVn19vR544AE99dRT+qu/+it95CMfkSTdcsstetnLXmaO5aMf/agWL16sZ5555lTeL7/8cv3O7/yOGhsbX9Q52rhxo771rW+d+nt8fFzf+ta3Tm0Qt3fvXv3bv/2bPvShD+lv//ZvJUnve9/79I53vEMHDhw47bt+9rOf6d3vfrfuuOOOU2l/8id/8qLyIbmv16+sXr361H/39fXpL/7iL/S5z31Of/qnf3oq/Q1veIM2btyor33ta6fSb7/9dvl8vlPvec973qPW1lb96Z/+qfr7+9XQ0KALL7xQbW1teuSRR/T7v//7zt//TcrI3XfffVoebr75Zt1888362te+ps997nOnlaVQKKQ77rhDf/zHfyzp+TJywQUX6OMf/7je+ta3qri4+MWdTAAAAAAAAAAAAAAAAAD/JQVnOwMAAAAAAAAAAAAAAAAAAPxv9tWvflWPPPLIaf8eeugh877rr7/+1MZfknTBBRdIkn7/93//1MZfv0pPpVIKBoOnfb6urk6vf/3rT/1dUVGht73tbdq3b5+GhoYkST/60Y906aWXqqqqSmNjY6f+XXnllZqbm9NTTz0lSXrwwQdVVFSkW2655dT3FRYW6oMf/OBpvxkOh7V//369/e1vPy3vV111lVatWvWiz9HNN9982t+XXnqpxsfHNTMzI0n6+c9/Lun5TeH+o/+cH0mqrKzUjh07FAqFXvTv/0eu6/XII49o3bp1p73v3nvvVTab1Q033HDauaypqdHy5cv1+OOPn3rvf9yYLRqNamxsTBdddJFyuZz27dv3ovP2m5SR/5iH2dlZjY2N6dJLL1UsFtPx48dP+52ioiK9973vPfV3SUmJ3vve92pkZER79ux50fkFAAAAAAAAAAAAAAAA8F9T9OvfAgAAAAAAAAAAAAAAAAAA/qvOP/98bdmy5de+r6Gh4bS/f7URWH19vTN9cnLytPTW1lZ5PJ7T0tra2iRJvb29qqmpUUdHhw4ePKjq6mpnHkZGRiRJfX19qq2tVVlZ2Wmvr1ix4rS/+/r6JEnLly8337VixQrt3bvX+Tv/2X8+9qqqKknPH2NFRYX6+vpUUFCg5ubm097X2tpqvuuv/uqv9Pa3v1319fXavHmzXvWqV+ltb3ubli1b9qLyku96/WpTvV/p6OhQLpdzHrskFRcXn/rv/v5+ffKTn9QDDzxgrtv09PSLypf0m5WRI0eO6BOf+IQee+yxUxvv5ctDXV2dAoHAaWn/sSxt3br1RecZAAAAAAAAAAAAAAAAwJljgzgAAAAAAAAAAAAAAAAAAM4BhYWFZ5Sey+XO+Dey2ayuuuoq/cmf/Inz9V9tAvbf7aU8xhtuuEGXXnqp7rvvPj388MP667/+a91+++2699579cpXvvI3zeop2WxWHo9HDz30kDP/v9pcb25uTldddZUmJib00Y9+VO3t7QoEAgoGg7rpppuUzWZf9G/+V8vI1NSULr/8clVUVOgzn/mMWlpa5PV6tXfvXn30ox89ozwAAAAAAAAAAAAAAAAA+O1jgzgAAAAAAAAAAAAAAAAAAP4X6OzsVC6Xk8fjOZV28uRJSVJTU5MkqaWlRZFIRFdeeeULfldjY6N++ctfKhKJnNroTJJOnDhh3idJHR0d5jv+83t/E42Njcpms+rp6dHy5ctPpXd2djrfX1tbq/e973163/vep5GREW3atEmf//znX9IN4lpaWpTL5dTc3PyCG+sdOnRIJ0+e1He+8x297W1vO5X+yCOPmPf+x2v3UnriiSc0Pj6ue++9V5dddtmp9J6eHuf7Q6GQotGoAoHAqbT/XJYAAAAAAAAAAAAAAAAA/PYUnO0MAAAAAAAAAAAAAAAAAACA31woFNJ999136u+ZmRl997vf1YYNG1RTUyNJuuGGG7Rt2zb94he/MJ+fmppSJpORJL3qVa9SJpPR17/+9VOvz83N6c477zztM7W1tdqwYYO+853vaHp6+lT6I488oqNHj75kx3b11VdLkr72ta+dlv6f8zM3N3daPiRp0aJFqqurUzKZfMnyI0lveMMbVFhYqE9/+tPK5XKnvZbL5TQ+Pi5JKiwsPJX2H1//u7/7O/Odv9qQbWpq6iXNqysPqVTKnM9fyWQy+sY3vnHae7/xjW+ourpamzdvfknzBgAAAAAAAAAAAAAAAMAqOtsZAAAAAAAAAAAAAAAAAADgf7OHHnpIx48fN+kXXXSRli1b9pL9Tltbm975zndq165dWrx4sf75n/9Zw8PD+va3v33qPR/5yEf0wAMP6DWveY1uuukmbd68WdFoVIcOHdKPf/xj9fb2auHChbr22mt18cUX62Mf+5h6e3u1atUq3XvvvWbzNUn6whe+oFe/+tW65JJL9Ad/8AeamJjQnXfeqdWrVysSibwkx7Z582a98Y1v1Je//GWNj49r69atevLJJ3Xy5ElJksfjkSTNzs5q6dKl+t3f/V2tX79eZWVlevTRR7Vr1y7dcccdL0lefqWlpUWf+9zn9PGPf1y9vb267rrrVF5erp6eHt133316z3veo9tuu03t7e1qaWnRbbfdpmAwqIqKCt1zzz2anJx0Hqck3Xrrrbr66qtVWFioN73pTb9xXi+66CJVVVXp7W9/u2699VZ5PB79y7/8i9nY7lfq6up0++23q7e3V21tbfrhD3+o/fv36x//8R9VXFz8G+cHAAAAAAAAAAAAAAAAwAtjgzgAAAAAAAAAAAAAAAAAAH6LPvnJTzrTv/3tb7+kG8QtX75cd955pz7ykY/oxIkTam5u1g9/+ENdffXVp97j9/v15JNP6i//8i/1ox/9SN/97ndVUVGhtrY2ffrTn9a8efMkSQUFBXrggQf0oQ99SN/73vfk8Xj02te+VnfccYc2btx42u9ec801+tGPfqRPfOIT+vjHP66WlhZ9+9vf1k9+8hM98cQTL9nxffe731VNTY1+8IMf6L777tOVV16pH/7wh1qxYoW8Xu+p43vf+96nhx9+WPfee6+y2axaW1v1ta99TbfccstLlpdf+djHPqa2tjb97d/+rT796U9Lkurr6/U7v/M7eu1rXytJKi4u1k9/+lPdeuut+sIXviCv16vXv/71+sAHPqD169ef9n1veMMb9MEPflD/+q//qu9973vK5XIvyQZxCxYs0L//+7/rwx/+sD7xiU+oqqpKv//7v69XvOIVp5WPX6mqqtJ3vvMdffCDH9Q3v/lNLV68WH//93+vd7/73b9xXgAAAAAAAAAAAAAAAAD8ep5cvv/9IwAAAAAAAAAAAAAAAAAAwDls//792rhxo773ve/pxhtvPNvZ+V/hiiuu0NjYmA4fPny2swIAAAAAAAAAAAAAAAD8n1VwtjMAAAAAAAAAAAAAAAAAAADw68TjcZP25S9/WQUFBbrsssvOQo4AAAAAAAAAAAAAAAAA4Lej6GxnAAAAAAAAAAAAAAAAAAAA4Nf5q7/6K+3Zs0cve9nLVFRUpIceekgPPfSQ3vOe96i+vv5sZw8AAAAAAAAAAAAAAAAAXjJsEAcAAAAAAAAAAAAAAAAAAM55F110kR555BF99rOfVSQSUUNDgz71qU/pz/7sz8521gAAAAAAAAAAAAAAAADgJeXJ5XK5s50JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBUcLYzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4HhvEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMA5ouhsZwDA/wzZbFahUEjl5eXyeDxnOzsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADnpFwup9nZWdXV1amgoOCMP88GcQBelFAopPr6+rOdDQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8RBgYGtHTp0jP+HBvEAXhRysvLJUnf+vde+QMVp71W0nOPLlpSaj7zeFCqWPk7Jj188BG9tiZq0p8+2q1L1rSa9EQqrZ9ltmphTZN5LT56QEsaltvP9D+r9oYak/5UZ1zzlp5n0mPdj+jStiqTvufwcW1dbivXbUc6tXbrpSY9Go3Lc/hJLZlfYV47OTuntsWVNk+pWtW1rDbpoye2a13TYpP+5MlplTdfYdK7ju/S/IYLTfrgkV/qHRd4Tfrk9KzGiiq1aNEi89rP9ydVVbPSpC+M/lIrltnzMXBoj9bXlJn0Z4dSal631aTvOXBMC1vtMRzd/5wKF1xu0menR/V7JfeoprLcvHZieFIrqu35floNWrrMHsNQxx6tbq4z6Qe6Q2pdYd9/6Mgxta3aZN+/d5c2bN5i0oeHh1RcXKz58xeY13r7BrWkodmkh/pOqr6xxaQfPtmvhfXrTXryyP26vCZn0h8byMi/4XqT3nPkKb1yU61JD4bCWqiY5s+z5/VkeFwtS+1njoUmtLzRloH9A+NqbFll0g8c69X8BnvPjXU8qUvWLTHpu/cd0tot55v0vr5etRRGNK/clrOfhhZrYV2bSc+N71ZD0zKTPtK5S6ubbBnY3TmqhvaNJv3ooQNatsoeQ9fex/W6+ZMm/eTgsHwbX6aysoDztaaGRpPe19Ollia7CWdoz9NaO6/QpP9kYoky9a806anQ43r5Fvs9u/YdUtO6l9tjOHlMyxpq5AvYvB44OaZFdbZOnh4+rJr6FSa9t/OYFiy15bXw6L/qsqqYSd85ktCmNbb+3nG8V5vWrzXph052q3zlpfKW+sxriWO/VGudrcv2TeTU3GzPd/D4Qa1aYu/Royc6tKGqxKQ/PVGgpeddbdKP735K19R5TPqezn75t/6eSkps2zjdv1+NDfYaDZ04oLa6apN+8kSH1lTbcv/A2CKVLHuFSZ/o26HW9g0mvefoNm3eZM/rkQN7tXpNu4qLis1r/3T/uHxVtgxcvHS3lrXYumzi2HNaVWvb0u3Dc6prs/XoiWMHtazdph89sFsr1tl64MieZ/S7FSHnrtif771EZQtsXq/M/rNWV9vy/VxmoRpbbZ0f2v+0Ni+y1237SEqt6209sO/QMbWute3cvt3P6Zp17s7ZifCkGhttGTjWN6GljbbOGuztUEOzbSOOdXRrSbO9ph1HD6qmxZ6/oV3369rkAZP+7NCsat76aZOeyWRU9sw31bTAtrFHCqvUtsTecwfHEmp13HPHOnu1qqXBpO/qHFFtm83rc8/u1omxzSY9PrpN73zHFSY9EYsrEDmgJXW23ToxMKLGxiaT3t07oIYme17H9z+ujdW2HnhsqEiVa2xc23Nsm7ast3Hcgb07dfEmW1fORiIqCHeqrnq+ee3gZFbNjrbgUO+Eljbb75o8+EttWmxjvGdGpMVrLzPpJ4/s1erV6+z3735G1zbaoYHx6Vn1V67Uomobjwb7O9XQaK91T0+fmhxt79Bj92i9Z9rmtbRFdRfa9qzr4HZdstK21bsOHNbW1fZeHx2fUEl8SouqbHn998lGLVrabj8zcFg1DTZ2yZ18QFvqbFtzoDekjTWVJv3JYFqVm15v0k/uf1LXrp5n0kNDIypPTqnaEX/95cEVKq6w1/rCxU9rZYutU547PqmqenuvRPuf1JaVjrJ06Ig2rLbfv3P/ETVvsm1KeLBfa078RFVl9nzsr16n5iZ7X+/sjam2wZ7vmf4dal9m89R9aJ8219p6endHUOc127L31MkhLbj4RpPe39upC478q+b5bB3etXSlWhxxwtHxuFrqbTnrPrBX6+bb79nXN6INFbYNenimSoUb327Se449p5ZVF5n0wd5jeu384yoL+M1rD4w2qHqpjWs19pxaHPXryOGdWlNjy9KB4JRWO873/iPHtHWxPd/bjvdp6wJb9x0cHFPn5k+o1Gc/Mx7q0II6G8s1HbpDq22WtL+kRu2tTSb9u8/G1Ju0bUGTd5fecKUtYwcOHNTGdbbePXL0mFYtXSSf11674+EpNTn6MF19QWc5zhcrPhOcU/Vym9fOo/vUsMLGCScO7tCq9fb9xw7tUfOKdSoutue8OPiEmhzl8nho3NmP2HVyQtUNtm6P9z6uzS223D9xdEJFDVea9KGOZ3T+FkcMvn+3KhsvU2GhbSeW/OLDaqmw5/vw8ku0zFFeDw1MqKHZlu/R/U9oc7WNRZ8ZmtOSTS8z6ccPbtclq+x1e27fEaWb3iKPx8bn7X3fUEutvaZf2LdMuYBtC9YsPqRlbba+jD77A51fYvuAv5xrkH+j7Yt3HN2pqvqLTXr34Sd0w5U2DsnmsproPabGettX3taXVq2jH6aTP9OaWnvTPRr2qaLZ1kHT3U/qwpV2vGz/oSM6v73JpG8/cFQrt9rrkE6nlTm5TY2LF5rXvnakUaUL7H26afjvtXle2qTvKFmq1rW2L3n82FFtcMSQe451aeV624/Ys/05XZXoMenRZEo/rH6v5lXbculNHNIiR707N7xNLc32t092dWtZi23n+g5u0wVLbRyyvWtIK7bY67B73z6t32Trh9nZWZVM9KlmkS2vA88+rrZKe88d8i5RW5MtM4dCk1q+rMkew/ZntEW2HD+bCGjpK95k0vfv3aHzN9uxkomJcYVj81S10MbgM+Ejqm2wZTx98jG1L7Fx8K7hlJqW23ux7+BzzvO6szOkDWtsf273waO6cIW9bsPjE9pZcLkqqmy9WDqzTU2O/kJvT6eaHf2w0Sfv1foiO679bEmjlmyx9WvnwR26yBHXPr3/pHztN5j0kaF+XeF5TgsdseIvZhtVU2/b3uLnvqHVZXaccF/xYrUvt7H5/t4htbfb+uTI4aPauML29Z860KlM4++Z9NFQt97gfUKVjvGvI48/rWVeO57V09iuVXW2DGxLVKp++RqTvvdon6qW2ntl+tD9unbemEl/rm9U511k++gdvQNamo2qImD7Tw8WX6DaetvHSIZ2aJmj797beVwrG+09d+SXD2vdzKBJ31nRrKZr3mLS9+0/oIXL7Vhdf/dReQIt8vlsGajJPKFGRz9sYt8TWrXY9j2ei5arvtXWx72dR9TW6hiLPnpMbascY6M7ntQrS4bt+weH1Oz3yldq2/EDSzarqcHGX33dnVruiHWe6suoummDSY91PqYtzbbMPNsxoap2x/k7+JSuWWPPxYHDx7VuskulxTam6VrQqJYltu9xfHhabUvsWN2JwVG1L7Ht3/0dxUotuMKke8af0MvOc7RnBw6reY3tux8/tFerVrWruNie10TX01q2xNa7e4bTamiy5Xjknn/QysSoST9ZWaNNdfY8PRZbqIotbzDpwQOP6nWOOb3tx7p1XkO1CgttP6ljOqPWOtuedZzsdrZnDxSer4ome79PDuxRfauNU6f3PaBXzLPjDM+FIlp7qY1dnt17RIHVtp2TpNjYEdXV2/rvREe/FtTZ9sYz9qyWO8ZG9xwb1IIGO2c01fesNjvi1yMHD+i8lfZ7tu/dp4s22hg/k5nTaPdxNdfacnl0ak7L6m3ZODI44YzNdx0f0cImm9fZww/oFQuSJv3h/pRSq99p0vuOPKk3XWbb10Qioa5Jj2rqbD063H9cjY32uA93hLTYMU4zd/QBnVdty9gzY4VavP4Kk95xcIcuWGfruF3PPquLO7eb9NlEWlPXvlV1NbYe2DeQUG2DbUuH+46r3nHPDZ/cpbXNjutw5KjOq6+0eTrWra2OWP7prhFVvuJmkz49Pan56V7VLLJlYHTfc2pzjFs9najWkmX2vAa7j6ilxZ6ng8e7Vddix5pCux7UK0tD9vsHJtT+ut+3+RkbU9XwcdU4xup2zFU7xxX3nJjUgiW23Rob2K+GZTY91LVbK9rtsR0+fEhL2ux8+fGD27TFEdeODodVVpp1zusm9j2k5TV2zuOR2TotbrKxS7D3qOqabF47jx92rk8Y635Gmzfb9x/au0MbNtn3hwf7Ve+LqqrS1uGDXSfUUmfL8bGRWbU02Nils7NTq+pt3/DIoSPaXGn71dsnslp93gUmfefBE2rfYvu9fb29Wl4wqspyW8afmynXUkd/4el9wypbZOv89Ph+Lay36SP9+7SgwfYNIz2P6/JNjrns3bv1smX2ep7sC8q/fKPKyuxc3F2PS775NgbfWny/VjfYeODkzh1a482Y9CdLWrV401UmvffEbq1bZfuYR3Y8pavSvSb9aHhc5a/8ffkd87o/O5jTglob55fM7nbWWandP9aGiqxJ/2ViiSpX2bZ0+PjTumSVLWN79h/SxW02vjvc0aP2xfPkLbXt/t+daFf5QtsXX13yqNqabXnt6OnV8uYmm378mNY51n1s7xxVzSq7lqdr96N6TWG/Sd/XN6zVyxudseLPS7ZoSaM9f93dfapeYs93sOeYKutseU0NP6vV7bYs9e95XJfNt2Vme2dQW5c65lx7wqq+5p0qcozVHeseUV29bbeK9t2tVQvtWPRPoq2a12jjr0hwh5a323K5c/cxJQL2fk8MPaOrX2ZjpgN7dmjtxvOc87oF27+n1sU2zv9FbpUW19vf7ujoVGWtPa+e4ce1od3e7ycO7tXWJY7xhBO9uqDFlrFnj3Rq08V2nZIkdYbHnWN1R4MTzvnH4RP71F5v75WTJ7u0rs7maV/fiDY41oVt6xrW6vNse7Zz9x5d2WLbrFQqpX+fXavqWhtnlUw9p8YGG4/++LExJUvteW3079XKNY41bMef1tblNg7ZdrRPdevtmMihvTu0YYttzxKxmPZ2ZlXpGKurSzyilmbHWornHtEax/zM4am01lTb8v3T8YVKNdm+TXT39/Xq0MMmfWdM2vjhT5r02dlZRWNxLV5sr9HE8V3ONSpPjvhV3WDjhHDPATU41gYGO3Zq7Spbzxw4fFxNK23be2Tfdl242cZAk5OTmvfY91RTbuf0utMFWl5px0SeqL5Ita227xE9+kttqLPt4rZwUktX2XGXzoPbdEmrLRtP7OvUdP1NJn1mclivLn9Ci+bbem7bzDzVOWLwE139WrTUcdyDe9TSYtuUvhP7tGaF/Z7DR49q9Sp7HfbsP6CVG2wdNzQU0nR2keZV2ePzhR9Vi6MftmMgpZpGWy+mnvmuNhTPmvSdJXVq3WLP67HdO3TpAhuXPd01qtor32bSw4P9ynkXq3yePa8afFrNDbbNPNQ/raXNtn362ZMDipfaMfvqwt1av8Gm95/cpTWr7fU5cmCHLltj7/Xuvn4trixzrgHcEZTqHOtm5g7/TKtqbD16tDuoNfPtfNveaWntcvvbz/VMqHGDHY/ZvWe/KpbZdWGh3iN6/dgPVeaYf3y28SotcZTXxI4fabVjrvlg95BWldp2f3dZg9o32j76sX17deECW/dt7wxqa4sj/uoNqX71WvkdeX1gqNY5F5IaOaAljnUz8cMPa32NrU/2hWe1usWe1/3HOnR+vSN2OdyhCyvtOPGBwWG1t7XKW2LHv45m/Fq2xDGPNZZWU7Nt54YObtPaWls2DvcOa50jfUc4qjXrbN333KEu1W24xqSf3L9Dr5x6ViVF9jiOLVmrZkec8FSw0LlGJT34jFY22mM72tmjVa322A4e79RqR3/h4O6duqJyzqTvONmvTVVeFRbYuqNnNq2WBbZ/9svKrappsnVW+sD9Wl9t246ds0VqdfTF953o19IVNrbs2veUfqfF9l+ePXhCKy59pRzTunrkUEbVS2zdFBk+poWOGDwQelBr6m1s+dxAQjXL7b3Ve2KPVq10rDc4tF/ta+2YyIHd23XJFnuOsrmsdnanVbvE0W6d7FFlrf1M5cwv1d7imHc4fkRrGmxccaijRxsd6du6wmo938avu3bt1grH2p9kIqE9J5KqWmzLWXX6WTU12lhx6uATWrXI1tP7xlJa6Vj3cfCpp5xzJPtzfm293LZzzx7p0nlbHOud4nHdN7jSOa9bEj+gxY758mhor5qW2Xiqp/uk6h3PEPSd3KeVK+y9dfzAbl240vG8yP7DWnX+FSZ9dnZWjx6rUvl8Ww9smrtPrUvttevq7NLKOltfHj58Umt9to3YN57Uxnm2/7cjXqL2l9v1dtv2HtG8VXYN2/TkqNYln9FiR/zV3T+o5Y61FEdHZrXCsT70qZESLVxmr93UiSd1QaOtZ/Ye79T5y2zMtO1Qhy5ca+/14bEJTVa3a/4Cm6eJjv3ONuKx/mItdMTg+/YeVjZgxwPrg9/Wq0r7TPoz2WoteLld/3V8/zZdttmWsVA4pNr0qBbMs+3NtqmAljqeC5nq3qPWBns+nuuOa0Gjzets52O6wBFr7zwxoOZ1dh3Cvr17VbvKsQYw2K211TFVVNhxxeHu42p2xLVHB8ed8wvB3U9rfZUtl9sjJWpbt8Gk7zgyoAWtts7qOfyMXrnBjq919vSpunqRyh2xYk/fgJY51n/99HCByhbb/m3hzC41ufoLHQfVtNzGA+Hn7tfL5uyakycnPZr/mttMem/nMTU3VMsXsHktePTraq2y8dSxwkrnPONPh6oVqLd9wNJD/6JLfHZefPesRxs32Db5qeNhLTzvd016x4lDWlLfJq/P5ikT2qYm15r2/gktcYzjdnV3q84RPwx17daqNsf6hCOdWtJm24Kevb/U62oTJn1PV1DJLe90PoNR3nmPltU61q5PzmmZYw3go0cS8tU62pvwHtUts2VgpusJXb7Ssabl4HFt3GDfv+/gYW1urVeRY1yxp39Ay5bauH3fWFb1jj7P3mPDmrfE8RzOge/qUr+dE308OV/V519n0rsPP6crVtu6cvfe/bqiZMY5Vretap0aHOsSRzsPaLnjebJDwXG1LLPHMLD9cW3y2mu6dySqjVU29t82ltKmS+047nP7j2rNJXasSZIGe3vU6KgHdvYkVVPvuN+7Tmr+EttGREI71brCxhXD2/9dlzrWBj41UaD5L7vJpB/d+7Sur7Pz6JnMnHojaee87r3hpaqqs/Fo6eTTam211+FkZ68aHTHN4MGndVGd4znezmn51tk1PicPPKlXXGTrjUQyofGJCdXV2pgm2N+lhoYmk37g5LAWNdhjyJx8UFuW2jpx98CkVjrGDQ4cOaG1a236tj2HVdJi67JYdEabh/5FS+fb9uxRrVJtk40tQr3HtaTJXusTJ7tUtWSDSZ87eo9eMW/KpO8ITum8VbZOfPZwpy5ts3Xo5GxERxddooWL7P2Y6N7unNvfPzCr+mW2HB/r6NbSZbYcD3ds16YV9n44eOS41q52rKvbd0irNtvxr7HxUR0bq1HFfJvX5Qe+qBVVtm94uKRaKxzj4NvHpLoWW5ft3Nepomobu4z3blODYwx04NiTuvoSG7MPDw+peWyXqh3x14F0hZodc6JHB0bV1GzrrGcPjcvvaCNKD96lK4qCJn13olgbL7B9zB2HT+qSJnuv9w2Nqqf+WlXMs+2K/+S9Wu6IB751rEaeefb8rY7/my6qs+MSu0aTWt1uy8yeEz1a6YjL9u3Zq8tW2LapZyCk8pqlqnDEXwM9Xc4Y/Gc9Zaqos22jd/SXWttqy/fBrrAaHWsDu4/s0tZWxxzJoZNqP8+2Ed1dHVpdElG54xmM3hPHtXxRpUk/kih2r//qC2tVra1PnhkpUN1qG7v0HXxWF7Xa6/bs0X6VrbHzEb1dR9TetEhevx0XKXrqH9XqGKe5v+ACzXc8R14w9JjWOPpVe7pHVddq+xGhQ0/rskZ7jraf6NXq8+y9eOToca2tqZC31I6z9necVGudPe79Ua/z2bfu7m6tcIxFnzy4X5vm23jgp0GvEs223Zrqe0KvvdjWcYcPHdba1nqVOMYVd/ZnVOeIX3XiIa1wrFk9Ep5UuyOvR7v6tK7e9kl39U+pbZ29Pgd37dDLKlImfUfXoDZuWK8ix7jirlSVGhxzd0e6J1Tj2CtjuO+wGh1tRPjkbq1pdTwzdKJHrY51oMcO7NZFjrnV7fuPqGLd9c5nMPx9/65ljpjwyHDE+RxOZ0+v2hzpB3pGtLTF9tt27zspLXDMQfc8rLdstLHrc/uO6eL1jucpJJ2YSDifw9kVmlOdY84/uft+rVvoeG5sMqM1y2yb8lhPUuVtdt1H8OSz2rrRXp+9e3bq4k021kmlUhoeGVX9UvsbJ/uHnHPQu09MaL5jHUIm/JTWOPY/6Ti4T+e5xuy7Qmp3PNewa/ceXbHW3j+xWEJjs1EtrbH9sN7+fmcb8UxIqmm0dX705GPa2OAYFztwSFsCdlxsx3hKm7bYcvzU4W4VrLXrGCOz05qNRFS50N4TNdMPqdVxvx8cnFaDY57sZGeP6poda9ie/jddmBow6dszAa265nUmfdeefdq60V63ickpHY42Op/BmB4+rpqltrz2d59U9VKbp6ngHjU5npEfP/mszltm6++9x3u0ap3N096dO3VVpa3LhiamFW3ZooULbD069PSDWlHl2JfCu0Stjjai68QJrXHM2+wbGNc6x7j5ngPHdIHf5um53hFd3O4YsxqbUteaGzWv0tbhkfBBZ7/3SFfY+Qxs+tBPtLna9vX3D01rfb29Hx7rT6mo/Y0m/fjBZ1Red4VJnxjt0+duXndq76YzxQZxAF6UXwV3/kCF/GWnV8Clfr8qAjYQ8vulQJmtrP0+vyoCdrFpwFuqCkcHraQ4JV+6zPyuJHmiZc7fKPT7Ve5YxOv3Fzi/R36/KhwPswX8Pme63+d1fr/HUyCPz6sKvx08L5vLqCJg0/1FAZWV2Uo85ver3PXb/rTzGLy+gNm871fpFWV2QCaTmVO8KOBsQHz+Yvkc3xXIBZzHHfD7nNcu4C9SmeP7/X6/87p5fQEV+m16OpVQeanXef7KfHH3ec0FnL8dyFs2/M5z4ff7nd/jy5MeiURUXFLsPu6A+1r7A+68+v2BvOXbdQ/5fRnn+30+9zEHAn6VS3nKfjxPeiLP+Uuc0TFE/e6ylO86BAIBlRdmnXny+d31Qy7hPq/RvGUg6r4+/oDK8pzXCr+dxCjzeeUry3OvBCLOSctAIM818vlU4bcDAb64XxnHPVroDzi/3+/3O4/h+etT7nyQwOdPOM9retZd7+a7DoU+nyr89kHlgE/uesPnzVsfl5WVy+u193tRnro6kMzmqbPy1Pk+nyr8dkDLHy/IW5dVBOzgR8DnVaCs3Dk5mQm4y0bkhdohVx0X86vEUQbiee45n99d//j8fpWVlTsfOi3xJlXqc5SbPHVWMs8x+GczeeuH/HnKd8/5nJOTpd4yeR3tR9mc+/wF0u46/PnzbdvMgL8w/73laiN87jZckgKBpLsOCiTztx1nUL/68qX7fKrwOOK10qTzOmQyGZX5SlXht+ejrNCnijLH/RsryHvPuevdiPNae30BlXgdeSp1xw+FBUX5Y5RA1N2+5zmvCb8vT1xblP/eyhMnuPKTk1Tgz3P+Uu46K1/ZSOWrH/zK057lL68VATs0kEpnFAiUue+VgDuGDOQ5rwGfVxUe22b6S3158+o8Fz53fR9PJFTqSTrbFX/S3W5F/e70nN/vrjd8ec63L0/Z8LnrxJmAX+WF7ryWestU7Kh3A3njplSeY3iBOCtPujtGLVO5r1QVPke9mCd28fs9zjzN5clT3n6Ez+u+nj6vu4/pL1O5t0QVjg3iyvLFCXHPC+TJfk/A51WF37ZB/rRPhfn6Z3lipvKA3zk56cvTv1Xcfc9F8/bDkvljHVf59pY6z13AWypfoEJexwZxMX+Zs/9Z5vOqwv6EAqXu6+D1SiUe1/l7gX5b3vSAc4O4QCCVvz90BrGi35+nv3WmbfL/T3duEJcvT4FEnlgk6fwNT97zlFBRnnEDZ/zlf36cobDIthNlpSWqcJ3vfL+dpz2L+X2qCDhicH++GDJ/G5EOVDgnJ8vy3Cul3jLlHPVuvmsnn1cVJbZO9M/58o5xuMZWvD53e5nNZpXMW7+m3XnKc2z5xl3SectGvvEvn7P+SaVSyuT5ba+vTKWO2Pz5etT2bwMl+e9F97iYz30/5Il3Czweef3l7mtR4K535yLuetefJ/Z7vt5wXYc8ec0z9pHL5VSSdNdB+WLzgDdPO+d39zsCPq8q5Ih3Pd4zGv9KJpPye8qd5y8TKHPWKal8/d5Z9/hhwO/PEyfkL6+u6xCNx+UrLHePp87luaZ54tqYz6uKIjsR7S/xnXGd5XPWu+Uq9+S5r+fc5bXE53WPuxTnKxsv3Ja68uoag/L6y1XuzRNblJao3LFBXJnPPb4bKHCXM7/fHU+lff4890OpswyU+X0qz845x+z9xe7zWhRwj7HlO38Br1flSUd75s1/b+UbX/P4K+TzO8plxl03pfLFhLl85/XMxsH9Pp8qSt3nu9xXKr9jg7gXirPcdbs7zso3b+P3J/Kcv/zja+WJUnkdi/PzxQkBfyrPd0XcY9S+YhU67hVPnlg+33jtr8bwXGN1RfmOL5J2j4N7S1Wes+Uy4HW3Kf6cO6bxvdCcnt/n3CCuLJ12ntcyn1cVfkc7VOi+3xN54rK0z6cKx+KPgC+Tt951zg1KUvzMxrs9sTMbq0v585eBfHl1pWcyGcXzldfUXP5+RJ65EGcM5POrIuDo9/oK8/YjXN9fXFQkf8rjHGuInOFY55zfp4qAbVP8scIzHlMqdyxmzeXyj9n7A4XO+3Q2zzFE8rURLzT24WqbvO6xj0wmo7K0O6/5yoa/IM/5PsPr4Pf5VOF11BveUnd+4nGV5zvuuXz3hLvPE8uXpzyxed5xc597PiIamVXAm3V+V1G+8zqXP0/5xgHcY0QvPG9jvj9QpjKfnOe8LG8bkad+yDtP5h7/CsTd3+P3u+PgQCCg8oKou5+UJwb3+aPOfltR3F0f+/KMTeUbh/TnuZ5lfp/8ZWXOz5T65Jx7ChS/wPnz2o3R/aX552nzxl9FrrG6EpWVlSngnNfNOc9HyZx7zCfp86nC71hvUOCOU/OPyeXrd/hUHvDL59ggzutzz+m98PjAmYzhRd3n2+dXRZErri1Rhd+rUkf85S/NHyecSfxQNJuvzvKpwrHYOZB3DKBUZWXlKnKM1fkDMWeeivP0w/w5d92UzVc3+QKS47opT/36q7rMuUFcvjxlzzAum33p5h3yz+vG88RZSWd79sJz/nnGOPKk550nc7w/VVwk35z7PJWm3W2v15eQSl/82Gg0b38u/9y+q2wUFhTK68+616QVuq/pbL72KVnojqdifmf/LOv1qdzx0JA/o7xjdfIU5OmL56mDIvnqUXd97H+B/oK7z+ju06fTaZXlmycrLHCm58uT8ozJ+f2F+dfN5BlTSjmuQyoZU3kgz3jqXJ51dXnq3WTemND/AuOyL37dR2C2TOmseww033oAvz+Zp+31qqLY0Y8tyXO/+33O9Uh+nzdvrJjzuvOqfPMOAfc8jNcXUNZVPxS+wHqkM+j3Bvx+lefth+Wc528uXyyXZ5whkHavh8y3vtHn97vHj/3Pz5eXO+bD8vWrinze/GOXjjHTfHX+822Ho+7LN8bq86o84FfAMbefL3YpirrvuYK842WZM2zn8swL/f8xJdcGcWWZPG1pPO2s/2bz5jVfevbM2jO/XxXJUucGcfnHOt1rSPLN0b3wmH2eeMBvN4j71Zx/oSP+KksXuMcD87QFqXzr5+aKz2zNSd42wqvy8jLnvK7Pn87T13PHOvn7Be5xnfzjCe5j8OVpO7LZbN6xjHz9VX8mX/z6Qs8vuOJX9/xtvmMoKiqW11/ijr/S7vORzncPxQqd5T7g86oi5RiLzrmfC8m3RrigIP+8boknzzqvFxjnyrse/EzHa/PEil5fuXyu/u3cmfYLvKpwbBAX8EoVPtv/C8g9Jpd3jUAqobJCd/yVf44k4y5/kdI84+AvsCY7Tz/MlR6NxZUuKzuzGNxfnGe9Rpmyjuvj9/qca138c+5x2Xz1QGAmoPJ01J2nvPdW/ueb3OPjL9APO8P5x7KyAudxRPKuU8rTH/b7VOF3lMtsyRmVy7zPtvj9Ksv7DIb7Mz5/gXtcMfMCY8v5xsHnHGUj7l4P+XyMVS6/a4O4F1p77VozmGcMudTnc6/dzHjy3Ft55vr+//MiXp/9TCZvfyHPmvb/Qv82//yj+xmMorIK5zMYZfnWXifd49c+f6GzTc7miY8zLzAGmj89oGLnHHS+uNY9H+HzR93jij6fKvz2f+7kL/DluQ4vEEOWppxjdfnWg+d7njHgz1M/5Fs36s2owueas/a8YKzokn/dsrstyDeumG8MdNbnU0Vp3H5/vCD/sy0Bu14nk8moLFuU537PM4aX+i+sVXM97+BL5X3e1NmHLS5WIum+3/OtnfL7I3nvIec9mvcZxPzltSTP3H6+dUd+5a+b3H0993WYy3PPBXyJFxhzdmy+OTf3/DMYrvHRvPWuu37IO397pn3JPHN68URcvlh5nvXgedqzkjxr92LKU8cF8q43yPccdL7ndctj+Z8Pc8cPsTzPTSecv12ab45OJfnnBp3zj175A+6xunz9Aq/v+TVj9rd9zmd9AtGCvLHimczplfl9KsszVpevPct3D3mjL/CsSt5+WL41wu51DuUlWXffJs/9WFZQfEb9M7+/4AzHOPLFX8/Hij7XBnF5xg99BXmey817TWN544G868Hz1RsBv/MZjLx9Rrn3Vsg3Xvb8+XbMz/h88jjuxYQv//PR5WVlzg3i/IGM83zk8sWQ+Z63eYHnc/KP1eUZAw34nRvEBYrztPuBlHudUt4xjpfonvv/5dg1Vpd33CqS/5ntM3lu3+cPSI4yIJ9fFWWO9WI+r/N6SlJZ0v1M6/NlI9+aIEedn3SPg/v9hS/JHEkqlVIkGsvTbuXb78Md42Ve6Dm9fOOKL9C3+c8KCwqVyOby3Nf5xml0RmuBn59HcIyLxQry1mUFrhg/m1Um63G27/njhBd65t2xhs3nU0Wha04q31id+3ynUmn55Y4TznTvhlSeWDH+Qm3sGdRl0XhSnnz7IeSdD3uhtsBVv8bylw2fow/7/9f4/GfTvtK88Vf+MeSZPPM5eeIvXyrPeEyhis7kebLI83lx1bsvhj0rAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICzgg3iAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAcwQZxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCOYIM4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADhHsEEcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJwj2CAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM4RbBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOcINogDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgHMEG8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwDmCDeIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4BzBBnH4P+2uu+5SZWXl2c4GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIIkN4uBw0003yePxyOPxqLi4WIsXL9ZVV12lf/7nf1Y2mz3b2VNvb688Ho/2799/trPidK7nDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOcuNoiD0zXXXKNwOKze3l499NBDetnLXqY//MM/1Gte8xplMpmzlq9UKnXWfhsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4bWODODiVlpaqpqZGS5Ys0aZNm/Snf/qn+slPfqKHHnpId91116n3TU1N6V3vepeqq6tVUVGhl7/85Tpw4MCp1w8cOKCXvexlKi8vV0VFhTZv3qzdu3efev2ZZ57RpZdeKp/Pp/r6et16662KRqOnXm9qatJnP/tZve1tb1NFRYXe8573qLm5WZK0ceNGeTweXXHFFc5jeOKJJ+TxePSzn/1M69atk9fr1datW3X48OG8x93V1aXXve51Wrx4scrKynTeeefp0UcfPe09TU1N+su//Ev9wR/8gcrLy9XQ0KB//Md/PPV6vvw98cQTOv/88xUIBFRZWamLL75YfX19efMyODioN7/5zZo/f74CgYC2bNmiHTt2vGT5BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwLmHDeLwor385S/X+vXrde+9955Ku/766zUyMqKHHnpIe/bs0aZNm/SKV7xCExMTkqQbb7xRS5cu1a5du7Rnzx597GMfU3FxsaTnNzm75ppr9MY3vlEHDx7UD3/4Qz3zzDP6wAc+cNrvfulLX9L69eu1b98+/fmf/7l27twpSXr00UcVDodPy4/LRz7yEd1xxx3atWuXqqurde211yqdTjvfG4lE9KpXvUq//OUvtW/fPl1zzTW69tpr1d/ff9r77rjjDm3ZskX79u3T+973Pt1yyy06ceKEJDnzl8lkdN111+nyyy/XwYMHtW3bNr3nPe+Rx+PJm4/LL79cwWBQDzzwgA4cOKA/+ZM/UTabfcnyCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgHNP0dnOAP5naW9v18GDByVJzzzzjHbu3KmRkRGVlpZKen4zt/vvv18//vGP9Z73vEf9/f36yEc+ovb2dknS8uXLT33XF77wBd1444360Ic+dOq1r3zlK7r88sv19a9/XV6vV9LzG9N9+MMfPvW5wsJCSdKCBQtUU1Pza/P8F3/xF7rqqqskSd/5zne0dOlS3XfffbrhhhvMe9evX6/169ef+vuzn/2s7rvvPj3wwAOnbVz3qle9Su973/skSR/96Ef1t3/7t3r88ce1YsUKVVdXm/xNTExoenpar3nNa9TS0iJJWrlyZd4833333RodHdWuXbs0f/58SVJra+tLmk8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcewrOdgbwP0sul5PH45EkHThwQJFIRAsWLFBZWdmpfz09Perq6pIk/fEf/7He9a536corr9QXv/jFU+m/+vxdd9112mevvvpqZbNZ9fT0nHrfli1bfqM8X3jhhaf+e/78+VqxYoWOHTvmfG8kEtFtt92mlStXqrKyUmVlZTp27Jj6+/tPe9+6detO/bfH41FNTY1GRkby5mH+/Pm66aabdPXVV+vaa6/V3/3d3ykcDud9//79+7Vx48ZTm8P9d+UTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ1fR2c4A/mc5duyYmpubJT2/SVltba2eeOIJ877KykpJ0qc+9Sm95S1v0c9+9jM99NBD+ou/+Av967/+q17/+tcrEonove99r2699Vbz+YaGhlP/HQgEfivH4nLbbbfpkUce0Ze+9CW1trbK5/Ppd3/3d5VKpU57X3Fx8Wl/ezweZbPZF/zub3/727r11lv185//XD/84Q/1iU98Qo888oi2bt1q3uvz+c5aPgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHD2sEEcXrTHHntMhw4d0h/90R9JkjZt2qShoSEVFRWpqakp7+fa2trU1tamP/qjP9Kb3/xmffvb39brX/96bdq0SUePHlVra+sZ5aOkpESSNDc396Lev3379lMbzk1OTurkyZNauXKl873PPvusbrrpJr3+9a+X9PwmeL29vS9Z/jZu3KiNGzfq4x//uC688ELdfffdzg3i1q1bp3/6p3/SxMSE5s+f/1vJJwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM49BWc7Azg3JZNJDQ0NKRgMau/evfrLv/xLve51r9NrXvMave1tb5MkXXnllbrwwgt13XXX6eGHH1Zvb6+ee+45/dmf/Zl2796teDyuD3zgA3riiSfU19enZ599Vrt27Tq1OdtHP/pRPffcc/rABz6g/fv3q6OjQz/5yU/0gQ984AXztmjRIvl8Pv385z/X8PCwpqenX/D9n/nMZ/TLX/5Shw8f1k033aSFCxfquuuuc753+fLluvfee7V//34dOHBAb3nLW5TNZs/o3Lny19PTo49//OPatm2b+vr69PDDD6ujoyPvRnVvfvObVVNTo+uuu07PPvusuru7dc8992jbtm0vWT4BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABw7mGDODj9/Oc/V21trZqamnTNNdfo8ccf11e+8hX95Cc/UWFhoSTJ4/HowQcf1GWXXaZ3vOMdamtr05ve9Cb19fVp8eLFKiws1Pj4uN72trepra1NN9xwg175ylfq05/+tCRp3bp1evLJJ3Xy5Eldeuml2rhxoz75yU+qrq7uBfNWVFSkr3zlK/rGN76huro6ve51r3vB93/xi1/UH/7hH2rz5s0aGhrST3/6U5WUlDjf+zd/8zeqqqrSRRddpGuvvVZXX321Nm3adEbnzpU/v9+v48eP641vfKPa2tr0nve8R+9///v13ve+1/kdJSUlevjhh7Vo0SK96lWv0tq1a/XFL37x1Ll/KfIJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAc0/R2c4Azj133XWX7rrrrhf13vLycn3lK1/RV77yFefrP/jBD17w8+edd54efvjhvK/39vY609/1rnfpXe9614vK4yWXXKLDhw87X7vpppt00003nfq7qalJjz322Gnvef/73/9r87R///5fm7/77rvvReX3VxobG/XjH//Y+dpLlU8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcWwrOdgYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9jgzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOEcUne0MAL8tV1xxhXK53NnOxv9YyWRSyWTy1N8zMzNnMTcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/NxSc7QwAODd94Qtf0Lx58079q6+vP9tZAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+F+PDeJwTuvt7ZXH49H+/fv/T/xuPjfddJOuu+66/9bf/PjHP67p6elT/wYGBv5bfx8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOD/IjaIwzmtvr5e4XBYa9asOdtZOec1NTXpy1/+8kv2faWlpaqoqDjtHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH672CAOZ006nf617yksLFRNTY2Kior+G3L04uVyOWUymbOdDQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwvwwZxeFFyuZw+9alPqaGhQaWlpaqrq9Ott9566nWPx6P777//tM9UVlbqrrvukiT19vbK4/Hohz/8oS6//HJ5vV59/etfl8/n00MPPXTa5+677z6Vl5crFoud+tz+/fuVzWa1dOlSff3rXz/t/fv27VNBQYH6+vokSVNTU3rXu96l6upqVVRU6OUvf7kOHDjwgse3c+dObdy4UV6vV1u2bNG+fftOe/2JJ56Qx+PRQw89pM2bN6u0tFTPPPOMksmkbr31Vi1atEher1eXXHKJdu3adepzd911lyorK0/7rvvvv18ej+e0tM997nNatGiRysvL9a53vUsf+9jHtGHDBpPPL33pS6qtrdWCBQv0/ve//9Qme1dccYX6+vr0R3/0R/J4PKe+v6+vT9dee62qqqoUCAS0evVqPfjggy94LgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHD2sEEcXpR77rlHf/u3f6tvfOMb6ujo0P3336+1a9ee8fd87GMf0x/+4R/q2LFjuv766/Wa17xGd99992nv+f73v6/rrrtOfr//tPSCggK9+c1vdr7/4osvVmNjoyTp+uuv18jIiB566CHt2bNHmzZt0ite8QpNTEw48xSJRPSa17xGq1at0p49e/SpT31Kt912W978f/GLX9SxY8e0bt06/cmf/Inuuecefec739HevXvV2tqqq6++Ou9vuXz/+9/X5z//ed1+++3as2ePGhoazCZ4kvT444+rq6tLjz/+uL7zne/orrvuOrUB37333qulS5fqM5/5jMLhsMLhsCTp/e9/v5LJpJ566ikdOnRIt99+u8rKyl503gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPDfq+hsZwD/M/T396umpkZXXnmliouL1dDQoPPPP/+Mv+dDH/qQ3vCGN5z6+8Ybb9Rb3/pWxWIx+f1+zczM6Gc/+5nuu+8+5+dvvPFG3XHHHerv71dDQ4Oy2az+9V//VZ/4xCckSc8884x27typkZERlZaWSpK+9KUv6f7779ePf/xjvec97zHfeffddyubzepb3/qWvF6vVq9ercHBQd1yyy3mvZ/5zGd01VVXSZKi0ai+/vWv66677tIrX/lKSdI3v/lNPfLII/rWt76lj3zkIy/qnNx555165zvfqXe84x2SpE9+8pN6+OGHFYlETntfVVWV/v7v/16FhYVqb2/Xq1/9av3yl7/Uu9/9bs2fP1+FhYUqLy9XTU3Nqc/09/frjW9846nN/JYtW/ai8gQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICzo+BsZwD/M1x//fWKx+NatmyZ3v3ud+u+++5TJpM54+/ZsmXLaX+/6lWvUnFxsR544AFJ0j333KOKigpdeeWVzs9v2LBBK1eu1N133y1JevLJJzUyMqLrr79eknTgwAFFIhEtWLBAZWVlp/719PSoq6vL+Z3Hjh3TunXr5PV6T6VdeOGFvzb/XV1dSqfTuvjii0+lFRcX6/zzz9exY8d+3ak45cSJE2azPdfme6tXr1ZhYeGpv2trazUyMvKC333rrbfqc5/7nC6++GL9xV/8hQ4ePPii8wUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID/fmwQhxelvr5eJ06c0Ne+9jX5fD69733v02WXXaZ0Oi1J8ng8yuVyp33mV6/9R4FA4LS/S0pK9Lu/+7unNny7++679Xu/93sqKirKm5cbb7zxtPdfc801WrBggSQpEomotrZW+/fvP+3fiRMn9JGPfOS/fgLy5P/XKSgoeFHn5cUoLi4+7W+Px6NsNvuCn3nXu96l7u5uvfWtb9WhQ4e0ZcsW3Xnnnf+l3wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBvHxvE4UXz+Xy69tpr9ZWvfEVPPPGEtm3bpkOHDkmSqqurFQ6HT723o6NDsVjsRX3vjTfeqJ///Oc6cuSIHnvsMd14440v+P63vOUtOnz4sPbs2aMf//jHp71/06ZNGhoaUlFRkVpbW0/7t3DhQuf3rVy5UgcPHlQikTiVtn379l+b75aWFpWUlOjZZ589lZZOp7Vr1y6tWrVK0vPnZXZ2VtFo9NR79u/ff9r3rFixQrt27Tot7T///WKUlJRobm7OpNfX1+vmm2/Wvffeqw9/+MP65je/ecbfDQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8ebBCHF+Wuu+7St771LR0+fFjd3d363ve+J5/Pp8bGRknSy1/+cv393/+99u3bp927d+vmm29WcXHxi/ruyy67TDU1NbrxxhvV3NysCy644AXf39TUpIsuukjvfOc7NTc3p9e+9rWnXrvyyit14YUX6rrrrtPDDz+s3t5ePffcc/qzP/sz7d692/l9b3nLW+TxePTud79bR48e1YMPPqgvfelLvzbfgUBAt9xyiz7ykY/o5z//uY4ePap3v/vdisVieuc73ylJuuCCC+T3+/Wnf/qn6urq0t1336277rrrtO/54Ac/qG9961v6zne+o46ODn3uc5/TwYMH5fF4fm0e/vN5eeqppxQMBjU2NiZJ+tCHPqRf/OIX6unp0d69e/X4449r5cqVpz7T3t6u++6774x+BwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL89bBCHF6WyslLf/OY3dfHFF2vdunV69NFH9dOf/lQLFiyQJN1xxx2qr6/XpZdeqre85S267bbb5Pf7X9R3ezwevfnNb9aBAwd04403vqjP3HjjjTpw4IBe//rXy+fznfZdDz74oC677DK94x3vUFtbm970pjepr69Pixcvdn5XWVmZfvrTn+rQoUPauHGj/uzP/ky33377i8rHF7/4Rb3xjW/UW9/6Vm3atEmdnZ36xS9+oaqqKknS/Pnz9b3vfU8PPvig1q5dqx/84Af61Kc+ZY7l4x//uG677TZt2rRJPT09uummm+T1el9UHn7lM5/5jHp7e9XS0qLq6mpJ0tzcnN7//vdr5cqVuuaaa9TW1qavfe1rpz5z4sQJTU9Pn9HvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4Len6GxnAP8zXHfddbruuuvyvl5XV6df/OIXp6VNTU2d+u+mpiblcrm8n7/99tudm7Ll+9wtt9yiW265xfld5eXl+spXvqKvfOUreX/vP9u6dav2799/Wtp//N0rrrjCmQ+v1/trf8t17t797nef9vef//mf68///M9P/X3VVVeptbX11N933XWX+d4vf/nL5hgOHDhwWtqdd96ZN1+SXvCaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4L8fG8QBZ1ksFtM//MM/6Oqrr1ZhYaF+8IMf6NFHH9UjjzxytrMGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACA/2ZsEAecZR6PRw8++KA+//nPK5FIaMWKFbrnnnt05ZVXnu2sAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4L8ZG8QBZ5nP59Ojjz56trMBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAc0DB2c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOB5bBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOcINogDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgHMEG8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwDmCDeIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4BzBBnEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcI5ggzgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOEewQRwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnCPYIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzhFsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5wg2iAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAcwQbxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAOaLobGcAwP8soY4d8vkDp6VlhsfkyZWb9/YPzaqsYLtJHx8Ka1s2a98/Fdf2vjGTnkqlNRTfIcWD5rWJoR7NxSdsenhQM/GMSR8cmNRMPGfSI8F+7Zkbt3kaDKt0LmXTg0PyHD5i0hPxhJKDEwomzUsamJzRVNLmqXt2WtGk/Y3hwZCiaXue+gYm5Uva8zo02KN0xu77OTHSr10nvSY9MhtRJHZCMwsXmNdCPUWKR2ZM+li0T/Fk3KSPDw4rlUiY9P6RKSUL7W8PDYaVyG2z3zPUo4LIsyY9Hp3R7rlBVVfNM68Njk1oOmZPeH86okQyatLDg4OKpu11CIaGFZsrtN/TH1Y8a6/1wGBYlcU2r5PTU8qoUOPzq8xrocGQMtMhkz4UDmtuZtimh2aVStjzHQ2GtCNqy0ZoLCX/CZun8VCPju7uN+ljk1MK5jKqrKgwr3VOpTSWsuVpaLBfsVjEpPcNTTnLQGhwTPGUzetoeFC7iu116w2NKnfwmM3ryLCmctOqnGfLwNhwvwqT9vyNDA9oetaev8nQkGZsVhUe7FFB0pb7YP+YJpM+kz4+MKxtmbRJD02lVHCkQ2XlAfNauL9XyclRkz44MqpYNGbSxwaHlZi1vz0ylVCB5xmTPjvSpwOH7fUJh4PylD5n0keDISnap4Df5jXYN6NM3NbJo0MDikdn7W8EB5RJ2fOdDIblj86Z9N6xKamkxKT3h4ZUVHjYpg+NKjt3SF6vPR/x/hGNJT0mfXB4VMkZ20YMDQwo4ajjggMhpWfsueibzmj60AGTHgoOaUfCtildw5PyH9qh0lLH8Q2ENDxtz0ekf1CzEVsGgsFRxTL2N4ZHIwoU2DIwEupVocd+fzjYryNeR70x2K+5bE7FjmsRHRtWqWfKpB+M9Wg6Ztut2EBYsZgtA92jcU2mS016f/+AIin7u8H+oDyFe0z6UCiobYm4CgrttU5P7FFBqb3W+6ZnNOPo8vSNH1M6astAeHBImfR8k94zOqVoyXGTPhgMK1O4z6QPh4LaU+qoaPR8GY/OTJr0k+GopmdtGRgdHlA0btuzwcEhJRO2DhocCGo6bo95ZmxSOyttm9+vjLqfO2TS03MZLRqJacRj2/GeaFBT9qfVNTKjyaRtO0b6uqVZe30GRqKaydjvHw31KTVj2+rEdK9Cx58y6fFEQpmJPk1N2Fiud2hcsaij3QqOaiZir9Hs4LAyMZun4FhS8dKnbV6DfTpUbO/RYDikg4fsPReLx5UJdWho1FXOZpUcs/Hu0ZEChSftdyVDE0rM2Xaxd3hakaJdJn2wv1+pOXvPDYbG9HhJpUmPRFKKDu7WzNBC81ooGFRiyrYRPcNTmo3a8zo5Mqk5Rx3Un+5T7PBukx7u69Kh2T7H747oOZ+NW6ZnplQ61KUFlfa1cGpSmYQtf6PhAeVS0yY9OhCS4rat6Q8Nay5t69eB4ZhGj9jzPRQc1N6CIZM+NjWlouisFlTZvCbHUyottOW148RJKeqIHwYSmora8hcd6VdpztYbA8GgimSPIRgKKnV4r83r6KjSE0lVporNawcn+hWO2rqmo29EIxO2gkhMDmrWUWeNDw4rm7B1X8/IhLKlfpPeNz6t2aO2HzE6PKwdxYtVVmr7pSMnOjQ9bWOX3qm4Zhxt7+DB45oqsOV1KOtRpnmJSQ+PDau027bJ06M9Gjxh+xejI0HtHu9XWcAeX3B8XKm4bSMioz2ambVtb6R/UMmIPeaB8Kgys7Z89w8EVThly3fv8JiKCheb9L7InCZ7n5HXZ+Ojgb5BJSL23oqEJhSrtHVNVy6omQL726PDE8o62urgZJ/2HLHH3BMcVVSDJj0cnFQskXTGiv3BoKZitm4aGuxXwnGeRvp6lJydMumD42lFHX3G4WCvigps+R4b6tOJI/b+GQr1KuCZVnGxPU8zgyc1M2PLa9/IuCKzNr2/f1qzccc9F+pTccoew8jgtPxZ25bODHeq94itfybDvUrNFauoyF6jcPeowhWOPs/cMUXi9nwHg2Fp0vaHw4ODysZsOe4biyris3HW4GBQ++Toe4aGFE8+q4JCe42SQ8MaT9n6cioYVfE8GxN2zgQ1l7FxbTw8qgKv47cTvSqrsHHC5FC/sjmbn8h4j44esud7bm5OE/0dikzaeys4klTW0T+LdvcpNeto/yY9is7ZuHlyoEuH07Z9Ghwc0rYiGwN1D89ocm+3zWsqrZL+Xo1O2eOYGZ7RPNn0o0NTys3Ze6IrOaDZojJ7DINhZTM2JuwNjihVcsKkDwyNaVfO3g/xVEZj8R3KxW35S852O+vd6EinEjFbNgbDw0qkHPf7YFhFSXvM/eERJQ/bfkQoNKTAfhs/RONxRSOzWjRt67+xsaimC22/qis8oCnXeNbIqKYdMftocFS5Atv+9ccimjm035HXsB7f0WnSY5FZKXtC0fFF5rWBwbBGJ+1veEJ9ikemTHr3WFLTjjGoiZ4BFU/bMtM/OKQCx/cMhEe1w9EPn5qaUXhuu+Lzq81r8fETmo3YuGk42KdE3FEvDg4rWWzL5UBBt6Jlth8bDA1qZ6FjjHpoVN5CG9NMTY5pd6pPC+bZ+3ooOirFwiZ9diql2WL7/oFQv5IZG/t1D08rJnteg8EheXI2BgqGw8rN2TGlyYkRbfPOqNJ2SdQ/k9SMx9btod5BRedsfdw/PaykIyYc7JvV6IwtG7HwmJ6T/Z7emYSKDthxxfDYhMKFOZUHHGM+mX1KRG29OzvSrVnXWN1At9KOMaWe4LCiEdt29E8HlXTE2sOhfnkKbdsxEw4qVTSigN+ev8jUISWnbL93rHfQ3e+d8SietOOv4XBIGccYf39/SKmcY5wmPKztXkcdNxnXeFLye+21OBrt0njUVkITvSeVcBxDaExKpGzdN9vXo9KYHfftD8cVTtl7bnxgQHsKbd+pLzisdCojb7FtG/sn+zUZt789MDyhiGOcKzg0omjMlo2poTl5HXHt9HCXjh2wZWx4cFAqsvM8I8FeHZhLq6TE1vmJgV5NOvrc/aFxzU2NmPTw5IzSxfZ7BkenlalwzF9MhDV73PZthocHtN0xp9IzPisVlaiw0N6n/ePTmkzaMjDQH9aUI3YZyh1UzDFvOD7Uo4KsPd+T4aC2R2ye+oYn5Dlkx7nC4UGV+eyxSdLkcJcyUVvOOk+Oa2LClv3sbK/ijrmQ8GBYGUc5Hg916UjOxhsDwaBUYOvj3qFpeY/1mPRMJqPJgZDGHXOfXRNxZ/rA0KhmHeU7PDikrCPeHQ+HtD1l44q+4YjiBbYtGAv1aO9R26dKJVMaGZtSamLAvBYKh5VwteODk4o57q1kcFS5pGN8cjSp8cKDJn1oIKjDjlgnPDykQyW20YoqqdEjxzQ8YY/j2GBUY46YZnasxxkrjvd1SzF7vw8Gw9KcvR96R6dUKFsv9U1GNOoYL4tGIupPDWtwzJbL6c4+TU87jiE2raFZ+xuRkU6l4/YYhoNhKW2PeSjcp+3FjrZmfFapIzY2n56eln8srIXTtpydjI0pEnGMf3XNaHjC3lupyQ4VZeyxBYP9KszZ7x8aDGoua8vx+FCPOo/a2GhyckrKZTR/vh0DjXX1a3rW5jUYHVMyZc/TSHhQHkdffGhgWPGk/e3xoT51HLbHPBbuU/8+x/ePjWvU59c8RwAWHJhQMGHr/LHhfmdMMzTYr5TjnhsYHlMmZ9uI3uEJZY7YOCsYCil10M6jj40Ma3ZuRPMqbExzcrJEUzP22s2EwyrJ2vpyaCikdMrG7CND/ZpL21hnNtSjo0U2HgiHgtohWyeGRiblj+1RWZkdqxsbKFBFzMYuhzO9SsemTHpwfFbJ+Y51M2N9ivp32t8e6JcnZ2OpweEx7QzYum8wUyLfgT0K+GxeBzsLlXTUr5o9oUzCps+OzSjhWOPTM9KvoZytgyZDYRUV2HLcPzSlghLHOOdITJNJyed1lMvePUo7zuuxbJeSrr740KgijnU2w/2DyjjKQH9wUjOyseJwMKhtOfu7PSPTihUPq7TEtss92qdk1NZBvf3DmnWM4YWCg5p01H2aOKGypB2PCYbDenbOxka90wkVFtlz0TsZ1+TBnSoucuR1YFJJx3htundIkYgddwlF0oqkbfmbHO5WNmuPYSQUVmGF/d2pkT7t22fjuIGBsMpKtqugyDE2NjiuCddYRuSgYo51CEODYc2lbHoieFL+mJ1X6w0PyRFaqmcsplTAlpmu6TkVHOuyH5DUHwpresZei67hGc04+oBTfb1KRmyZGQwPK5F2z+vOOeasB0anlfPbWCcUHtL2Intw6XRGgxO7lXbEtcnxTs3M2np0dmxSReX2fITGOzSvxLGWYjAoR5defaFhZUrtOqWJ4S71HrL1RiKR1EBPTpEJe+1mkp2Kxey1nhgIKz5l68X+aErRQtuPDQ0NKuexeYrMjOvYglqTPjI3qaMHbN89Go9rKpLQ2Lgdl506flKzjvTBiFfxuKMdD/WoIO2o44L9yuUc9Wt/ULE51/h4WLsc41/R2VmVTacV8jjGXcbHNJlytO+TRxVJ2d+eCY4p5hhT6g8PK52zsWVooFd7MvbYQsPDimTsdZiNTGunb0TVjjHQ7rF+xRx1WXf/hDN+iI11Kpeyvz0U7FdBxhHrDISU9di++2BoWJli25ecmhxXJtutWJVdZxEN9zrHE/pCk0rEbTmOTkQ056hHe8aGNXvkpEkPDY3Jm7LtaN/UrOJHdpj00dFRpQoGVeFYVxcb6tGkY54s3N0pDdux38nBrLKO+nJwrlfzfPaYg/39Smds2RjqD2u/o382NDKq3uH5Ki+3bWB3aFTx6JRJT/QGFY3auqx/eEKRrB337RufVqzYMRYYHFa6xDG3H+rXaNyO106MDGhXLK4yn723+qI7netAJ8PjimbsPdcXGlWszN6/vSPdmnPMGQ6GwtqWttezezKqwqBta/omYhromZDPESv2DYwq4YhpIuPdijraoUhoTNG5SkeehpTI2XGgvtCoPI7Gt2diVsU5m5/+SFYzwzF5HWvVuqenNJZ0jP2OTCoas2VgYiCspCM9OBhSyjGOOzA2o5zHHkN4cFhzPse626Eu7SgqU0mhrTsOnRxSf8zepz2hSWe/Nz7cq5TjfPcOjSqSsfVD38CIojnHms7QpMpmbVzRMxFRrrBEhY51df0TMY2X2nvu5NAxTUTsd831Dik96xiPmZ1TzNHnHggOK+2YEw2FBrQza+fvB4ZHVbjzGXkc44o9nYWKTtu2YGxkQKNjthwHZoNKJG1d0xeOaNqx1mU4OKBc1rHOa3BApYWOvnu4R/sO22PLZLIaCo2qMG7XLvScGNfkxJRJL491SI7nHYLhIcVTjrmk0JhSjvPaOzKhxCHbFw8NDSlwyM47JFNJjQ7kpKSts0amOzXhaGMTPSHFZ20/omsqrqijDAwOTyjjiCt6E5Mq7HGM2Y/PqPCkXReWSCQ1NRZRccaOKw6NdWvOMa87PtyrpGNt5dDQoNKOZwgGBwflGLpWODjsvH/6hiZVcNjG5rFYTFPBEilh83p44oRik3bMvn90SrP2Uis4MqFUhb1XekIjSk446spMkaJHbRs+ODSimWLbnkVmZ5WdPKnFC2z71D8+qwnbvGtwaEiRuI0HhkZjkuM6DIX6tDNjx9f6gsMqcvTdB8LD2mVPtyYjEU2N5rRggV1bOd7T7RyrGxjKKhp39M9GgipL24MbHBvRDse6j8FUSNFjjnX2Q/3aedAxlz05rmB6TPOrbB3UPRpX3NH2DgcHNBG398pgcEIxx7NEM/3dCsTt/PBAeEqJYsdcbCioRIGNFafGRnR4eEqVrjnovh7NTk+Z9JOjMY3HbPs+GxxTKm7bp96puJKFthwHB8Y0M2fzNBTu177Dtk4MDw9rdKBXFY553ZNTaWeehvtjzrn95HSnco5+WDg4qIxjHejk6Jh2lTr6PDNxjR6y42UjQ4NKzA7J77fxzlxwUpOOMeH+5Iwijn7E+OSQ5nL2XokPhbTDb9N7ZpOa67T1+uDQqGaP2nHIkWC/UtEZeX32GkXDJzXriF36Q2NKONZ994TGNRu1eRoL9Svlmk/sG9R0yvZvRwdD2u6Y4+4ZGlf88E6Vlto4KxOaUsix5jw0NOScvw31J1TuWFcXH+1QRc7x7NFAj/bIHnN/eERzR3tNel9oXIWpuEpcce3QuMYcjxGcGI5pZMqep5Fwvzxpx7qF4WFtL3OsW55JatIxlzQcHNQ+jyMODg9rW0lKhY6xuoOhTo06FhjFBroUd4yLdY/POsdrJ8KjmgvY+rJ3cFjJSUfcPBNXoWNN1WBoSHOOdEka6zmmuKONDY5mlI471iEMDiuVtH308aFepRxtxPTotEorbezfOzWj4UN27CgcCmlH2l7oTGZO4YlpTTieZRubGJUnbdvS2PBx5Rzj5gNDY0o74t2RgQGVRu09HQpPqqLMsT50pEud++31TKdS6p9MaXzc5mkk3K/ZiGu8dlhKOdblB0cVzdoyEAqNKFnYYdJ7Q2ElCx199/C4Ah7bJicSMe0eGlUoZu+JnsR+xR3zCyPhXuccyfjgkIpS9nxPDYe13bHOtG98WgXdjjZ5bErbu20dEInG1D22X2Mj9jPx/k5FZhz9+uEppRxzT+HQiJR2zNP2DWo24VijHhxTrsBxb4VHpMP2mbjp6RkNT/UrOW3HVxLDs5p2jLX3JQc043jGrXs0qWnHc32jwZAqHHHwxEiPMwYfC/fq+GHHupzJaU2OBrVgni2XPZE+xcdt/dA5EXO2ESODk6py3L/JiQntrHDUA+OT0nG7jrZ/aETbC+wxjExMaTi2SxUVNq7NdfU414kP94yr2BFbHp/pV0nUMR4zPqOsY04lODSqIsdc9nD/gPY45tdHxiZUPB5VeYXtA/aFRzXqeEa+q6NfZRP2u3yzPfIkbf3QOzQlx/CDRvsH5Xc8zxMcHFTRfsfc6tCIkqU5lZW5xksmNJGz165nOqMxx7jLSHBYEUdfvGM4qaG0faZ1IjimQsfzJT3DY/IfccRfoUFlIsPyOsbqPJ1BjU044vmifYo7nstND/cqm3C175NKOuLakYE+7Y7buqlvcETJI7YcDwZHlIzMyOd17AHQ2acpx3xYTySj2MyUSe8fGdeMIw4Oj8wqJns/hCeGVeyzYxlTo33aedAxRh0c0dxcSiXF9poODgzLM2vHaYaDYxp1lIHh4KCzHxYcHFQ6ZeuHgdCIco56Ixwc0LY5e2zdkYyyHf0qcsVfkQmNOOZIhoeCSrnigWBYszF7E00P9qjAsU6pa3BKQ3E7tjwSHNecHGPUQxEtOLZNHse4aa7npGZcc6UTcc1GHWt2wiHneG3f0JQijrIRGhhSwZQ9R9HhoJ7qtn3Yrsm4fCd6Tbr0fFvqWjvVM5pQwjHvMDsYVtL5DMuE0o65vuBoWpMe13rPPh31OuZCQoPa63iWKJ1Oa3hkQsPTtox39w8r5Hh+dDg8pLRj7iky0q2C5JTNazAsZR39s/C4Zg/adYk9wXHtdzyfk0gkNR6JaWLMzon2jUxo0vF8+cBwQjFHv3c2FFYm47iHRiaViznWDozNONve0NCo/N1POvIaVXcopaoROwc9HulW1NHvPTEc09is49nBoaBmHDHn7NikfKWO9fdTU9J+218YCga122/b19nZiHpnxjQ7Zp/hi4x1Khe3/dVQcEjZpKPNDA1oJmavdTLYLZ+jTgyGx+RxrL8PhULannA8gzET1UymU/MX2P7CRGhS047Y+cTcoEYcewYMh6Y17pgvGA2NKTNnz3ffyLgKqxzxSSyrZ2bt948lSjV6bLeqKm2dPDXcqWjEHkPfwLgSjjorNhBWLm7b8J7xGc0W2/q1f2RcZY7nzmdGe5WT7dtExu2Y+ZlggzgAZ6RhxXnyl50eWM2VRbSm3T4oHzkW1KK28026NzOjLa22EYwnEjp/RaNJTyRSSmbbVLu0ybw2VlmkxuYWk95b5lXTsuUmPVbUo4WNW2xeCyZ03nIbMOaSMV3QaBf5JKPT2rzS/m4kGlNG46pfWGleq5w3TytqbcMSjy9Uw/I1Jr2ktEStbatM+mSuQ/4lF9s8paTFLRfZ9HhUG1bb352cmpZnrEdLFtrG6MhcmypqbJ5qM2ktb2026WFPUhvr7W9k/GNqX9Nu0hOZAi1eacvGTCStiG+rSU+XjGhL4U7VzrMdzWOlC7VykT2GbHG9WpavMOmHS31qcZzXXPFRtbavs3mdK1Z9uz2v0VhCF62wk6XB4SLl/FVauMCxCY/Po5YGe690+HJa0VBn8+RNqLZ1k0mfSPVra5Vjg4jinBavs+8vTE7q4lrHIghPVGXeci2cZ4Ok3NI6NTUvM+nzSgu0qqHGpBf5J9TWZu+5TGG5FreeZ9JLCua0fO1qewzJnFassfeot6dLq70TqnQ8SJCuLlJ9o70fj3ZUqKbBXutSb6kaWm359ntSuqip0qTPJgqVqLvMpCdmY9qy2gaeJ/xelaxYp/Jym9fFhSm1Oa71gfIKtS5rMukDsRFtqLIdnJGKOpW0XWjSJ71xrVlnz0UindaGdfaYvSUFWllXqYBjg5K4N6va+jaTXlZWrpqGlSa91OvVkmWOeyjRoa2VjoXwRcW6oNEOImfjMV1YX2m/PzWr9MqtKnVs+jHnT6qlqd6kzztxVO2O8nq8IKM1S+09eiAd1+YqGx5H/V7VrrblOBed1tZa2xkvSCW0eG27c4O4rH+pljS02s8Uz6p9qV0g4fOWaG2D7exND+S0cMVmk15SJC1tu8Ckz2UyWrF6g0lPprJqXnmBihyDY5U9ffIvtGWgaWFA9c22DMwVz2pdgz2GaG9Sixx5SsyVqHqZbc+iiayaVtq2IBJN6LzlaRUU2AGnw2VtWrjE1vlLp8fV3mjLgLezW6sb7eLvfUU5rV1u27lUZ1gta239mswUaMUaex2ikYg2r7JlUpKqAqVqdbQFqYBHS5ptm1lR5lVziy0zhcUdqm9Zb9IjqRKV1l5i35+a1vnrbX0yW3RSvfMvN+m5TEabfIe1rMbeKyUJv5Y77rl0f0QNrbbenTc3o/NrHAsLiqu0YKUtG8GhlE6M2zYl55nW5g32OsdiMaWGCtVQZ691ybyFWtZsr6lKh7Wk2eY1Mjeu8+psXpNlCbWst+Xek02pdbWNaWKxpDautr87E4moMDei+oW2jagsKdBKx3kaLFmhwFJbB3l9Sa1ZudSkp0/0qWWVrY9TaY8WtNr2bDKSUctm2yZPTEyoLDqg2kW2ru7yFai13rZnBeWLVb/MluOJsZM6r9QOmCS0RA1rN5j00tlhXRywAy/pqQK1bLDne3R0RHXJAdXMs2V8Zv5K1TfbchMsL1FTi63jxjWsLUvs9SkuLtLmBnsuZopjKm93xK+RWV1gm2QNDBcpECvSonn2N3aVnKeyxbZcrkmGtbbB3otjnmIFGmycmvYmtHat7VdpLq0tK225TKbSqne0c4GBPm0p7dd8x6a3o74LVdtor/V4tkPzam3dtKCyUC1t9jqUK6ktjZU2q4XFWu+IXSK5Ii1fZ7+/p7tTzfOXa55j4+PxPY+rrcb2VUoXljrrMu14Tsv67UByyeYLdP4qe1Gn+5NasNbGr3PptJautPGap+SIzq/MqNxv7/fwgmWqbXDcQ4Ne1TvaiKQmtLHOlqVSZbV5kWNCMeLT+eWOjVYjJdraZtsmb5E0sWaL2SRekmK5alXV2jytiT+htfYyaK58hZatsdduX7BbE7O2jV1UkdXKtY4ykCzUvNYrTfp4ZrdWbqiQ1zE56Zs3X81NTSZ9fqlHKxrtcXfnYlpba/uYyfIiLV1tj6GoYE5rHXmdS6dV44jZ4ynpgrVVzsVhQ/6YWuptnnzz5mtZU4NJjxbOamGTPX/pogmd12LLfcIzoZo1G026tyCq89fa/p/SUc1v3+LcIC76rzNqciyqmfc712qFI56a70lojaO87tcibXDUr3F/TPVr7LHlUjFtWWnboFg0rrEll8jjsWV8fflhLV9iN7G6r3+RUqW2fW9sKVNT+1qTnho7qPML7QRXvLBONes3mPS5bFaVzbaeTsTiWr/G1tPZbFbTRTG11NuYxjO/QE3LbEw4MRfW2sW2Tx+rDKhmpb3WYY3pwgZbP2QyGa3YYOPayaRU0fxyk55KpbQ6d1zNi+24yFH/es2rs7FIU8l+bam2bXUivUiNjnq0uMCj9Sua7G+rSMsd4wbRqVld4HiAOZJIqWPRBZq/yH5XSdSn2gYbDyTmpdW2zF6johK/WlbYuKlnLqbNzbYvFC8s0QpHrJNIJHR+u/3+qZkZjWb9qqmxZWAqPa72Wnu+czGfWltt7KzOfrW22fLdO9KvLdFekx7zLdSSNTYemIpmVFL3CnsMkyNqXzSi6kU2r+niGi1cYn97QfGg1i9xPKBYXqwl7fa3R6JDurDSTgbnZkq1tcSOc82VZLVptY03wiNjyhZsVuV827dOjRSosdneW5X+YrW22LpssPeg1qXsYrL0wqVqXmvLvSeb1up1Nr6bins0r922ESWhPp2fGFS1I1b0aLGzPRv0xdReb/u3pR3dWtdojzntq9Iyxz2nbE6b2m1bM5OQMo66zBPs0salXudYXfmJ/WoL2Pu9Y2mzVjfY+rhoIqOVLbZvM56Oa26R7d+Wz01p83rb5iezWV24yC4sPp4sUO3CKs0L2Phronit6hptPTA9WKhmx9ho2JPQeke7NXfooJp6bNnIrGnSGkfZSKfTWr3BMT7pL1S0dKN8AXtel0wOa7ljPKEvOarVNY65jXi5MwY/VlyglSsc47i5IjWtdowpzUxpq88umvClYmpdWC6/Y/wrvXiDGprs+ZvJjGl1TaVJj82rUl2bbbcmskPausTxP+7IZjTXZMvGXDKq81bY/BSm49qYysjr2PSj0luttqX2XgmUV2hlvSO9tERrHGN4kUChFq2wxxA8Mq3z2m3skk6mtHytjS2zc3Na3Hqxc6zO55/UMkesWFlarBWO8cMjPZVanbMLg7wLmrVxraP964+qYb2NgY6nJnRBrV3IkYlGtLV5sXODuKoyn9rq7HmqmB7TijJbP0xWt6u6zdZNYV9Oy9tt2xuMDWjrPEdbIOn8FlsnxmdmVO2YO5GkSLBAjY76tX92Vt5qe58uqs5p+Qp7bxWWHNKyNnv++kti2uRo9zOZnFrX2fGEqXhGa9fZY85kMpopzWiZo7zmpovV5Bj/Kurq0TLHXGlx6RGtcBxDV3ZM59fZWHE4PaPwYtsWlE4ntGZtk0lPJBKqHx5Q/RJb9o+Xe9XiyOtcyZhqm219GS8e15aGSpM+2x1TlWM8RumYtrTbtiY1OaYLc3Yx1Ewsob61a1VXa8vNWFFGC5famKam0qPWFlvHhTSjTY650kKPtHGFff/cXEbnNzo2JUvnNG+VrY9npibky41q0WKb1+TYEa1c4NgEYG695jXZsbTF/rTWO8YBSgulNe32+hyc6df5WTsXEkv4tHytrftGR0dUUx5X7Xwb+83NLXKW14H4jLzVG0x6VVVSGxzjrN7iOa1aZe+VuaxHTatsfZJJJ7TW0SYPhcPyFHu1YIFt3zMzx7RysSN+zTap3jG3PxiQ2pbbsaO0x6eKBhv7lRamtHqtjRUzsYgubXVsKOFLK1q7QVVV9jUFQlrSaO/3qp5ntaLJMTddlNN6V1xWVKCNyxxz1r5BbXSUjWQyrQZHP6Kkp1ObVKoqx4MEE5N1WtJk6yC/77BzbPno8YCqltpyVlpSrJoWe62nPVPautzGUtnotDavdsx7+kq1dH6ZKhwPEjwaXKLiKpvXdYEebWiw1+FwQU7rHWNK8fESLXX0DQsKpOWrbPs0l4jo/Abbvvq6vFq6rE5ljnHFI+k6VdXa8rQwNaeWVtvnGS1NarVj/mzkeFS+BscckyerJsc9FMkUqG2TTc+UHtG6+nnOBwken/DJt8Ce11UVU1q1zPYLigLznOs+fJ6cNrba9ycKhrTYMd7tmRrSlmm7AFZFWW2cX6LSYjv+NVWzXkubbLlJFg1ofp2tg1I6JP+iDSa92j+iS1ptudydS2jjKnvvpjNz2rrY9m2yqaSWrV7uHKtTWUJLGhyTEtP7tWaBvQ4jc+2qarHtzbhPWr7S1nEziSPyLLDxQIFnTtWtto4bj+S0aX2Dc153Jt6rNsdY3XSsQbVNjnUI/hOqa7LnO14Q1EVL7LGpsFArN9oyEC/wavkmR/w1V6RNqx1jo5KqyrzOGDw3L62GZls2pjwzWudYh1Dq9Wpts6N8pxO6oNwuOp/LlGmTY/1cMjLpHPtIpVIaHa3X4iWOmGO0QA1Ntmz0zQypoHKDSa+dS2nzuiaT7ikoUL0j/ornCrXF0b/IJqZ0gaMNj8Xi6kgsUmCh/Y1VJTNqW2bnbYJDJ7XWb9fmFNcu1do2+xvDpRnN1dvyGkuEdOkC27eZ8xZro2MN4NTMjMbTRap1xIrTs71qr7btXCLbrLpW2y+o8qW1qs3+RlGRRy2r7LhsIlOk2hV2LcVsLKsGx5jS1OSYVkztUt08255VFOW0wrExWXTJKi1ZscGkD/tyWukY4y84clgbl9uxo+LkjM5fYcv3ZCStoTp7HTQxpHWNhVrk+B/aFoRn1NjkKDeeSVUtte1NtjyltY4Y5YQno/Xt9nxn5VG7I36NJufU7FijMhweUEWgQFWO//HERKXU3Nxkj6FsQI3L7H06mRnSZse4VXK8UE1rbRkoSMZ0XqNj7D9boFVrbV05MFCmWOkyVTgeeohX5ZzjijWzg1q7wPaTDk62aMJn+xFLvR4td6w7ymQLtbDFxg/xeEpbVtqYqcNbrGztRlVU2LipeF6HGpps7BLPBrW6ttKkl1RUaXWTI37tH9PKdhtbpgqPa/0ax1hgJKWZ+ba8liQP6Tz/bpU7Nr0N1C9xrgPtyk5r9RJ7HYonx7VGds1EUdVibWy1x7B7LqUtjlgnnc3q/OU2vaRA8m282LlByVDJtBbX2/ORHilRvas98805x2sLvce1vtXWA55cTluW23ORTiW1dYktx8WerNrWrJDXMa5YPDGnZY22LSjpC6llmWPMfm5W65fYcnYwm9Gm+bbu8xQXa/Myx7h5Kq0V6xzjPdmYzqtrcj50Oja6WLWOseVM4KRqHOc7G4hptaO/lfFWqqnd9gsSHp8aHGuq0pGItlba+cpsdEYXtC5xj9VFFjvnSoPjjVrUaNstX6pDW6rtMWejPi1fY+OyXGGJ2tbYGLIwMakLmm0cnJqd1iXN853zuntjbSpzrENI64hKFto+T8uiWa1fbtvq2ZIJLWq1dbvH41HLatsWZOfSOm91k0nPRKed65mz2azmzz+pJkf9enI8oqL59ny0Lx7TplZb/kq8fufaa5WUam274zmIguNqd8yjRyNxbV3tegYjoWn/QlXX2lgxM+HTEkc5LsgEtX6RY53udJHaHOMxCvZo45B9qC03f4G2ONbZJFJJbXb0hSKxmGYmm1Rd22Remw2Xqt4xnjBUXqymFpte5i3Scsd59RSUaMly285l5rJasd5et9lkVusc5X5mZkbDRdWat9DWWRtCe7XSMW9TUlmt9mW2HvUlI9pcae/d7GxMqyN27ilR0aD2dTZ+mE3mtMTxbMbk+Ig2DHWqzjFW519Yo+WOdTNlvlKtWmpjoFL/pNY45sX3FqW0tt224UoldGGtLUvpmXHnnF64KKGxNaudz2CMFSa0fKkdy5j0e1XdZOdb0jqsslrH8wiJAzpvzq5LTBUuVKtjXncuFVfDKhubFwf7tLI0rAVVleY1TzjifAajI1CuxmbHulhfp+pbbPkbmxvShTV2TiWVK1aDY+1PNJ5RzQrbXyj2d2rLwiHnBnH9RWnneY1XlGppiz0f0cyENtc4NkQbSmqVo78ay/qcY/nZVMwZK54s8ahlblzzAo75x9o1anDM7Y96RjSv1rZnBRM5LV9u67jCwmI1tNl7aCga0oVltlzOeuIqWu5Yo1lwWM1NtfIHbLxTNviY2ubb81RWtECrHPOM8ZkyNa6w53t49oQuKLblNReo0OaVtoxFMwWqc6xpV0GR6hrbnRuUZCoSzjVpZWWDWuZo5+ZKJ7SocYNJLy0pVKtjTCmS8aq6xd5D2ZkxbZ3fb7MandVs+4XO/5mWZ4HHOadX0XHAuQ50SCmVO9ZeF1fM6oIVttwfKIxok2M+J5nOqXWdjcviGY8uaCxRsWNcsWRBrZqbbLs80xHXonp7reeXP6cVrU0mfSDaqQvKbb9temaeFqyy91ZBJqHNq2wZy8RndaEv6hyrG/af54wHigvHtLLexpAaTmuZYx1CcDas8xwbGuaiMa11bJKb9nm11TFPFp+eUoujnyxJ8ey4Wh15ys4vU72jfi3xzVNto23H+0uL1LB8g0kfy85oc4utK2ePDSmwwvFM4WxMFyyz6yczmYx6K7xqqXWsOV/coCWO53AinTNa3Wzj2hKvT60r7Pu7UtO6oNaOjcY9JWpwrEWZS07qwhW2zU8kEiqena/aJbYeqKrwq8kxTlPmPablrTbGO1haonrHeVXpNq1bZe+tVLZQLWtd8+VStWP8KxaZ0UbfUTVU2/Yjmm1RvWM8ZkHAo9ZWx3ORXo9WLLfpnbkRne8Ym59TgS5otvVGIjKjrUsrTfrETJEKl2xS9WLbB8yWTDrXqJSWVajN8Uyh11vqXJ+QmCtVeeMVJj2dLdLatfZ6xlMZrXLED6OjIyqYrFblQlv+GhPPaKVjDLS0oFptzbbejffHVddqfyOtw6ptsXGqclmVLXU8H51MaINjHUI4HFZ9Sdj5DMa8eIHaHOMxnvl1znmyTHFYdctsXmdyg7pwoa13PQPjOm+ZPUeZaETnt9lz0RMsUdmS8zSv0sa1gdQhrXSsnXoq2q502QaT3lZ2WFsX2Y2hiiRtWWBjxYKEV1sd9YOmS3WBYz1NZ0lW82obnf/jr5L5dWpytGeHZ2ZVNN/mtbVqTOetsPV0pmRKS1c6nofKxHS+o95NJ6I6b4Utx8cLM1pas0jljnnd+UU5tS11tBERr3PtdZm3WGsc8+UjJUn5muzzdR5PVm0bHONoGZ8qHLFOMndQS5qb5PU58nro37S8yLaZw23rtMhRLrOBGa1rcT13PqymdtsX6k1P6oLFts2Pp7JqXGvvxbSnVOub3PO6NfEhrXCUV3/Cq7YGW54KKxaq2REnFJaUatUKex2mSns139FHL/Kk1PD/2PvzOLmqOo//f1d19b530tnT6WyddIesBEhASNweoJKvuOACIxMFN0RFB1xHDSqbA45GBsYRTRi+6DhuyAAySiTRQEIWyL73Uvva1bXvVf37w6/9sz03LIomOq/n45HHo/tTt+8999xzz3ZvnVi895Eu1+icRVMsv4PR0XBUc2eZc5rPtbRp1hzz2rXUPq3Fs8wyUFdls/xeQ1WlpAummHlkSzVqpcWcfbFS0arpbXJY/Mf34cpSy+8Wt7fstXxnVdVtmjzbvNYTNaJVs9uMeKTYpvI0893/uqxD0xaZc0rhXI16Fp1vOVfXoBOW7VbVxGrL+dqmumr1WrQRpbqoZli8HzqSOaJ8s9nPciinuSvMOcJYvqIL5pn3lSR1NDdprsW71LYJDnVZrEESzbq1zGL+q7baoeXTzLopVlOvFov5WodyWrLY7IvmslktsnhPpFAoqN6f0PSZ3cZncZtf7TPM/mt9417L75PF+zNaOs/s4zlsFS1baJal5Gi9pvaZz3PiybxWz7RYNDqXU7DQrq4p5j1R3z5Rcy3m8vNNKU2bY47RI7U5LZlvMfefS2lVq/kcuFJdqwss6r5cNqeZyy3eZ0jEFBmtU+MEs/1YrJAWWDxLSjZInbMs3v2v3q/pc814MuXU6haz/18JZrTS4jlPIZ3QoiUW70VHoxqNTlJ7p/k3VZNk2QevqW/W9Nlm2ajYG9Q602LcW/LroqnmGiS2YkErLJ7nlBMRrZpl9rP9w3Ua7l6szonm2C0aOaneieb9mK5frOkWz8vtje2aNd+sL6vto7pghjlfMVrIa5XV+j42mxZfYI4jvP6AJjQsUFu7mdZEm03dFs91bbUBy++XZyo+nWfxHm0xVNLcJRZrFNUc08xei+c8uZyau806rrp5yIi9HGYrDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4I1ggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOEiwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABnCRaIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICzBAvEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBZggXiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAswQJxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHCWYIE4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADhLsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJwlWCAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM4SLBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGcJFojD34ytW7fKZrMpFoud6aS8JJs3b1ZbW9sLbrNhwwYtW7bsr5IeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnP1YIA4vWyAQ0Ec/+lHNmTNHtbW1mjlzptatW6ctW7a8YsdYu3atbrzxxnGxCy+8UH6/X62tra/Ycf4eWOUVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/jY5znQC8LdlaGhIF110kdra2vQv//IvWrx4sYrFov73f/9XH/nIR3Ts2LG/2LFramo0ZcqUV3Sf5XJZNptNdjtrJQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODMY1UsvCzXX3+9bDabdu3apbe97W3q6enRokWL9MlPflI7d+4c2+7rX/+6Fi9erMbGRs2cOVPXX3+9UqnUuH09/fTTWrt2rRoaGtTe3q5LL71UIyMjWr9+vbZt26ZvfvObstlsstlsGhoa0tatW2Wz2RSLxU6bvhc77ubNm9XW1qZHHnlEfX19qq2tlcvlUj6f10033aTp06ersbFRF1xwgbZu3fqCefFSzlGSHn74Yc2fP191dXW69NJL5Xa7X3C/999/v3p7e1VXV6eFCxfq3nvvPe22p8srSdq2bZvOP/981dbWaurUqfrMZz6jUqn0gscGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAmcUCcXjJotGonnjiCX3kIx9RY2Oj8XlbW9vYz3a7XRs3btThw4f1wAMP6Ne//rU+9alPjX2+b98+vfa1r1VfX5927Nih7du3a926dSqXy/rmN7+p1atX6/3vf7/8fr/8fr9mzpz5ktL4YseVpEwmozvvvFP333+/Dh8+rEmTJumGG27Qjh079F//9V86cOCArrzySl122WU6efLkn32sW2+9Vf/5n/+pp59+WrFYTO9617tOu8+HHnpIX/ziF3Xrrbfq6NGjuu222/SFL3xBDzzwgOX2p8srr9erN77xjTrvvPO0f/9+3Xffffrud7+rr371qy8pHwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHBmOM50AvC349SpUxodHdXChQtfdNsbb7xx7Ofu7m599atf1Yc+9CHde++9kqSvfe1rWrly5djvkrRo0aKxn2tqatTQ0KApU6a8rDS+2HElqVgs6t5779XSpUslSS6XS5s2bZLL5dK0adMkSTfddJOeeOIJbdq0Sbfddtufdax77rlHF1xwgSTpgQceUG9vr3bt2qXzzz/f2OeXvvQl3X333XrrW98qSZo9e7aOHDmib3/72/rHf/xHY/vW1lbLvLr33ns1c+ZM3XPPPbLZbFq4cKF8Pp8+/elP64tf/KLsdtaGBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOBuxQBxestHR0Ze87ZNPPqnbb79dx44dUyKRUKlUUi6XUyaTUUNDg/bt26crr7zyFU/jix1X+t3ic0uWLBn7m4MHD6pcLqunp2fcvvL5vCZMmPBnHcvhcOi8884b+5uFCxeqra1NR48eNRaIS6fT6u/v17XXXqv3v//9Y/FSqaTW1taXlQ9Hjx7V6tWrZbPZxmIXXXSRUqmUPB6Purq6Xtb+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8NfBAnF4yebPny+bzaZjx4694HZDQ0O6/PLL9eEPf1i33nqrOjo6tH37dl177bUqFApqaGhQfX39K56+l3JcSaqvrx+3cFoqlVJVVZX27t2rqqqqcftsamr6s471cqRSKUnSd77zHV1wwQXjPvvjdAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODvk/1MJwB/Ozo6OnTppZfq3/7t35ROp43PY7GYJGnv3r2qVCq6++67tWrVKvX09Mjn843bdsmSJdqyZctpj1VTU6Nyufyy0vdSjmtl+fLlKpfLCoVCmjdv3rh/U6ZM+bOOVSqVtGfPnrHfjx8/rlgspt7eXmPbyZMna9q0aRoYGDDSMXv27NOm3yqvent7tWPHDo2Ojo7Fnn76aTU3N2vGjBkvmicAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4M1ggDi/Lv/3bv6lcLuv888/XT37yE508eVJHjx7Vxo0btXr1aknSvHnzVCwW9a1vfUsDAwN68MEH9e///u/j9vPZz35Wu3fv1vXXX68DBw7o2LFjuu+++xSJRCRJ3d3devbZZzU0NKRIJKJKpfKiaXspx7XS09Ojq6++Wtdcc41++tOfanBwULt27dLtt9+uxx577M86VnV1tT760Y/q2Wef1d69e7V+/XqtWrVK559/vuV+b7nlFt1+++3auHGjTpw4oYMHD2rTpk36+te/ftr0W+XV9ddfL7fbrY9+9KM6duyYfv7zn+tLX/qSPvnJT8pu57YHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4W7FSFF6WOXPm6LnnntOrX/1q/dM//ZPOOeccvf71r9eWLVt03333SZKWLl2qr3/967rzzjt1zjnn6KGHHtLtt98+bj89PT365S9/qf379+v888/X6tWr9fOf/1wOh0OSdNNNN6mqqkp9fX3q7OyUy+V60bS9lOOezqZNm3TNNdfon/7pn7RgwQJdccUV2r17t7q6uv6sYzU0NOjTn/60rrrqKl100UVqamrSD3/4w9Om47rrrtP999+vTZs2afHixVqzZo02b96s2bNnn/ZvrPJq+vTpevzxx7Vr1y4tXbpUH/rQh3Tttdfqn//5n19SfgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODMcJzpBOBvz9SpU3XPPffonnvuOe02n/jEJ/SJT3xiXOw973nPuN/XrFmjp59+2vLve3p6tGPHjnGx7u5ujY6OvmDaXuy469ev1/r1642/q66u1i233KJbbrnlBff/px7rrW99q+U+NmzYoA0bNoyLXXXVVbrqqqtecjqs8kr6Xf7u2rXrJe8HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ579TCcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPA7LBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGcJx5lOAICzUz6fVz6fH/s9kUicwdQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD832A/0wkAcHa6/fbb1draOvZv5syZZzpJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/dYIO4FrF+/XldcccULbrN161bZbDbFYrG/Spr+XBs2bNCyZcte1t/8rZ3jH/tTzhnSZz/7WcXj8bF/brf7TCcJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg7x4LxL2Ab37zm9q8efPY72vXrtWNN974ih5j8+bNamtre0X3ifFuuukmbdmy5Uwn4y9qaGhINptN+/bte8X2WVtbq5aWlnH/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8JflONMJOJu1trae6ST8TSiXy7LZbLLbz871BpuamtTU1HTazwuFgmpqav6KKQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACsnZ0rev2F3HTTTbr88svHfv/GN74hm82mJ554Yiw2b9483X///ZKk9evX64orrhj7edu2bfrmN78pm80mm82moaGhsb/bu3evVq5cqYaGBl144YU6fvz42Gf79+/Xq1/9ajU3N6ulpUXnnnuu9uzZo61bt+q9732v4vH42D43bNggSXrwwQe1cuVKNTc3a8qUKbrqqqsUCoXG9rl161bZbDZt2bLltMeVpDvuuEOTJ09Wc3Ozrr32WuVyuRfNp8cff1w9PT2qr6/Xq1/96nHnKUmbN29WW1ubHnnkEfX19am2tlbbt29XdXW1AoHAuG1vvPFGXXzxxac9ViwW03XXXafOzk61tLToNa95jfbv3z/2+YYNG7Rs2TI9+OCD6u7uVmtrq971rncpmUxKkv7jP/5D06ZNU6VSGbffN7/5zXrf+943bh+/9/vreuutt2ratGlasGCBJOngwYN6zWteo/r6ek2YMEEf+MAHlEqljL+76667NHXqVE2YMEEf+chHVCwWx7bp7u7WV7/6VV1zzTVqamrSrFmz9MgjjygcDuvNb36zmpqatGTJEu3Zs2dcerdv366LL75Y9fX1mjlzpj72sY8pnU6P2+9tt92m973vfWpublZXV5f+4z/+Y+zz2bNnS5KWL18um82mtWvXSvpdOTn//PPV2NiotrY2XXTRRXI6nae9HgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADiz/k8tELdmzRpt375d5XJZkrRt2zZNnDhRW7dulSR5vV719/ePLa71h775zW9q9erVev/73y+/3y+/36+ZM2eOff75z39ed999t/bs2SOHwzG2OJkkXX311ZoxY4Z2796tvXv36jOf+Yyqq6t14YUX6hvf+IZaWlrG9nnTTTdJkorFor7yla9o//79evjhhzU0NKT169cb6Xqh4/73f/+3NmzYoNtuu0179uzR1KlTde+9975gHrndbr31rW/VunXrtG/fPl133XX6zGc+Y2yXyWR055136v7779fhw4e1cuVKzZkzRw8++ODYNsViUQ899NC4NP2xK6+8UqFQSL/4xS+0d+9erVixQq997WsVjUbHtunv79fDDz+sRx99VI8++qi2bdumO+64Y+zvh4eH9dRTT41tH41G9cQTT+jqq68+7XG3bNmi48eP61e/+pUeffRRpdNpXXrppWpvb9fu3bv1ox/9SE8++aRuuOGGcX/31FNPqb+/X0899ZQeeOABbd68WZs3bx63zb/+67/qoosu0vPPP683velNes973qNrrrlG//AP/6DnnntOc+fO1TXXXKPR0dGx87vsssv0tre9TQcOHNAPf/hDbd++3Tj23XffrZUrV+r555/X9ddfrw9/+MNjCwLu2rVLkvTkk0/K7/frpz/9qUqlkq644gqtWbNGBw4c0I4dO/SBD3xANpvttPkCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAM8txphPw13TxxRcrmUzq+eef17nnnqvf/OY3uvnmm/Xwww9LkrZu3arp06dr3rx5xt+2traqpqZGDQ0NmjJlivH5rbfeqjVr1kiSPvOZz+hNb3qTcrmc6urq5HK5dPPNN2vhwoWSpPnz54/br81mM/b5h4uqzZkzRxs3btR5552nVCqlpqaml3Tcb3zjG7r22mt17bXXSpK++tWv6sknn1QulzttHt13332aO3eu7r77bknSggULdPDgQd15553jtisWi7r33nu1dOnSsdi1116rTZs26eabb5Yk/c///I9yuZze8Y53WB5r+/bt2rVrl0KhkGprayVJd911lx5++GH9+Mc/1gc+8AFJUqVS0ebNm9Xc3CxJes973qMtW7bo1ltvVXt7u97whjfo+9//vl772tdKkn784x9r4sSJevWrX33a82xsbNT999+vmpoaSdJ3vvMd5XI5/ed//qcaGxslSffcc4/WrVunO++8U5MnT5Yktbe365577lFVVZUWLlyoN73pTdqyZYve//73j+37jW98oz74wQ9Kkr74xS/qvvvu03nnnacrr7xSkvTpT39aq1evVjAY1JQpU3T77bfr6quv1o033ijpd+Vj48aNWrNmje677z7V1dWN7ff6668f28e//uu/6qmnntKCBQvU2dkpSZowYcJYWYpGo4rH47r88ss1d+5cSVJvb+9p8wQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABnnv1MJ+Cvqa2tTUuXLtXWrVt18OBB1dTU6AMf+ICef/55pVIpbdu2bWyxtZdryZIlYz9PnTpVkhQKhSRJn/zkJ3Xdddfpda97ne644w719/e/6P727t2rdevWqaurS83NzWPpcrlcL/m4R48e1QUXXDBu+9WrV7/gcV/q39TU1Iw7tiStX79ep06d0s6dOyVJmzdv1jve8Y6xBdf+2P79+5VKpTRhwgQ1NTWN/RscHByXR93d3WOLw/3+PH9/jpJ09dVX6yc/+Yny+bwk6aGHHtK73vUu2e2nL96LFy8eWxzu9+e9dOnScWm96KKLVKlUdPz48bHYokWLVFVVddq0SOOvye8Xllu8eLER+/3f7d+/X5s3bx6XB5deeqkqlYoGBwct9/v7RQX/+Nh/qKOjQ+vXr9ell16qdevW6Zvf/Kb8fv9ptwcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMCZ939qgThJWrt2rbZu3Tq2GFxHR4d6e3u1ffv2P2uBuOrq6rGfbTabJKlSqUiSNmzYoMOHD+tNb3qTfv3rX6uvr08/+9nPTruvdDqtSy+9VC0tLXrooYe0e/fuse0LhcJLPu5fUn19/djxfm/SpElat26dNm3apGAwqF/84hd63/ved9p9pFIpTZ06Vfv27Rv37/jx47r55pvHtvvDc5R+d55/eI7r1q3T6OioHnvsMbndbv32t7/V1Vdf/YLpP92idS/mxdLyx9v8Po9e6DqlUil98IMfHJcH+/fv18mTJzV37tyXdew/tmnTJu3YsUMXXnihfvjDH6qnp2dsAT8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcfRxnOgF/bWvWrNH3vvc9ORwOXXbZZZJ+t2jcD37wA504cUJr16497d/W1NSoXC7/Scft6elRT0+PPvGJT+jd7363Nm3apLe85S2W+zx27JiGh4d1xx13aObMmZKkPXv2vOxj9vb26tlnn9U111wzFnuxxcF6e3v1yCOPjIu9nAXFrrvuOr373e/WjBkzNHfuXF100UWn3XbFihUKBAJyOBzq7u5+ycf4Y3V1dXrrW9+qhx56SKdOndKCBQu0YsWKl7WP3t5ebd68Wel0emzxuKefflp2u10LFiz4k9P2UqxYsUJHjhzRvHnz/uR91NTUSJJl+Vy+fLmWL1+uz372s1q9erW+//3va9WqVX/ysQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPCXYz/TCfhru+SSS5RMJvXoo4+OLQa3du1aPfTQQ5o6dap6enpO+7fd3d169tlnNTQ0pEgkokql8qLHy2azuuGGG7R161Y5nU49/fTT2r17t3p7e8f2mUqltGXLFkUiEWUyGXV1dammpkbf+ta3NDAwoEceeURf+cpXXva5fvzjH9f3vvc9bdq0SSdOnNCXvvQlHT58+AX/5kMf+pBOnjypm2++WcePH9f3v/99bd68+SUf89JLL1VLS4u++tWv6r3vfe8Lbvu6171Oq1ev1hVXXKFf/vKXGhoa0jPPPKPPf/7zL3tBvKuvvlqPPfaYvve97+nqq69+WX/7+7+vq6vTP/7jP+rQoUN66qmn9NGPflTvec97NHny5Je9v5fj05/+tJ555hndcMMN2rdvn06ePKmf//znuuGGG17yPiZNmqT6+no98cQTCgaDisfjGhwc1Gc/+1nt2LFDTqdTv/zlL3Xy5Mmxsrdr1y4tXLhQXq/3L3VqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeJn+zy0Q197ersWLF6uzs1MLFy6U9LtF4yqVitasWfOCf3vTTTepqqpKfX196uzslMvletHjVVVVaXh4WNdcc416enr0jne8Q294wxt0yy23SJIuvPBCfehDH9I73/lOdXZ26mtf+5o6Ozu1efNm/ehHP1JfX5/uuOMO3XXXXS/7XN/5znfqC1/4gj71qU/p3HPPldPp1Ic//OEX/Juuri795Cc/0cMPP6ylS5fq3//933Xbbbe95GPa7XatX79e5XJZ11xzzQtua7PZ9Pjjj+uSSy7Re9/7XvX09Ohd73qXnE7ny16U7TWveY06Ojp0/PhxXXXVVS/rbyWpoaFB//u//6toNKrzzjtPb3/72/Xa175W99xzz8ve18u1ZMkSbdu2TSdOnNDFF1+s5cuX64tf/KKmTZv2kvfhcDi0ceNGffvb39a0adP05je/WQ0NDTp27Jje9ra3qaenRx/4wAf0kY98RB/84AclSZlMRsePH1exWPxLnRoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABeJseZTsCZsG/fvnG/d3R0qFKpGNtt3rx53O89PT3asWPHuFh3d7dGR0fHxZYtWzYu9oMf/OAF03PffffpvvvuGxd797vfrXe/+93jYn+4z7Vr177ocSXpc5/7nD73uc+Ni915550vmJ7LL79cl19++bjYe9/73rGf169fr/Xr15/2771er974xjdq6tSpL3gcSWpubtbGjRu1ceNGy883bNigDRs2jIvdeOONuvHGG8fF7Ha7fD7fS9rHH1/X31u8eLF+/etfnzatVn/3jW98Y9zvQ0NDxjZ/fE2sysx5552nX/7yl6c9ttV+/7gcX3fddbruuuvGxX72s5+ddp9WZQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABn1v/JBeLwlxGPx3Xw4EF9//vf1yOPPHKmkwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8zWGBOLxi3vzmN2vXrl360Ic+pNe//vVnOjkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADA3xwWiMMrZuvWrWc6CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMDfNPuZTgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4HdYIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzhIsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZwkWiAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAswQLxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAWYIF4gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgLMECcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwlmCBOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4S7BAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcJVggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOEiwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABnCRaIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICzhONMJwDA3xZ//w7VNzSOi2VCg7KXEsa2TndUkVyDER9xDmpXOG7EXd6AdlXZjHihUJC34NNoZJrxWdB5SvIdMeJDyaLy6REz/d6IivmsEY+5BrU3a1aJHrdXz6ZjZlo9AVU/t9eIZ3N5JSIj8hTM9TdPjpTkUpsRPxEYkj9hbp8OHJc9HTHPYSihqniVEY8EBiWbmX8jIad2HDWvTzqTUTE2oskZ87wDA88plzavUTZzUIp7zTQFfMrm80bc6xySokEjHg4lZbOZ55CJDKptknkOVcWEns441FnTaHzmiaQUqrW4dqFDKsSHjfjJYF6RlHmMmL9f9px5zhGPT9WjRXP74IB2Hesw4iMjcalwShPbW43PvE6X0p4BMx4aVtYzZMR9mSqVs2aavIER5UYnGXFX0KnR5x4z4tGhfj3jzxnx4URS0c7FaknWG5/54wMKjJSNeMbnVipj7ssVGrYsA35vWJVC2ox7vNJoxYg7XT6lyuY9HQ0HlU8/r9ZGs05xFxyS75gRP+Sp0qA7Y8SrUkdVkzHLpdMbUKpYbcS9AZ8mV/2PES+NnNTuI2bZ84fCqhveoqZGs7wGfD4lh837+mDMIU/c3FcilFfENsEiTW41Vv3WiIc9Tu1ylIy42+VXdfXzRtzn9SoRa1N9vZnWkNur6tSQER/yxZVOmXVKKnBcdVmzfhj2urQzbt5zg9G0yvXNRvzUcFYxn5kXvmGHJhzcovr6OvMzv1vDmYIRDztdSlqUV2/Ar1TO3H4oktFI1VQzreGIsoefMeLBgEc7Ler7/uGEIvv3qq6m1vgs4AmrKjFoxONDJ5WOhY24xxtUbsQsM64Rh0ZK5v59bpfKFfPe8nmderpkUd97fCqWd8lRXWN8NuJ3SwXz2EdDbiUS5n1tcx5TyW+mKZisqGxRD8TdfjVWYkY8FfRowKwGFAk49dvqBtmrzDzPu5/SaOmEET/uP6L8SMCIO8MxpfJm3e4dHFAl4jfirkRBOZntltfrVtlm5l3A79czZrUkSRp2nlAiYd5DvmBKSniMeNDvlWJu8xwCGSXSZj0d8rrVbhYBjQSGtNtu1g++oF8t9WbbUSqXtHdwUOFhsx06WmlW2OxOaTAQ1UjazNdsv0ujIXN7T7JKiSqzvcylXFo5zzw3ryus3+zpN+KFXFalhFfOmHni3oBfsaSZ2PCJQ6pymfViIBFXOWe274OhpNKO/Ubc5xpU3ajZ/o14B3VYZluTzuWVGRyUu73N+MxdtCtaNtuhkeHnZB+16A/43cqXzGvq9fkVL5jl0ud1yq4njXgqfEqHDpp1YiqZVCmTVOeweX7Rw7uVHjSv3Ylim4YTFmUgklK5zaJuHxmUnn3CiAd8bu2YYPZPXPGMRvea7V88mZQvmNREizr5VOCQEhZlIOE/otGEeb8HfH5lLfLV6U8pNGq2ye5gVJ3HtxnxaGRQv3W2GfGRaFK1EY8mtJj5F0/vkb1i9l8PJAJKFsx89bgzajQvj9Ihp+w2i/bPG5TsZl025A8rfWi3eQ7Dwyom82q3aG9OOfcpmTTrsoDbr1I+acRL0aOqzpkVQcDnUblklr/BQFxxh0X97Y9p9OCzRjwYDCsecKi5qcn4LOYMKpoz6xSXL6Ssx2yTnbWNyq+8xIiHohHZj5nbuyMlBR17jLjP65TN8bQRjwS92h4fUVOjeU3dwX3KZ8xxbCToVjqdMuJpX1TJ0qgR90YyilW1mPFoVrKov4eiadn9Zr/ZEyupdPI3aqgz++Ax37BqLCr3XYka+evNejRy+IBKEbOdC/UXlMjEjLi7KaSDB8zrFvA5JfuvjXg6OKQTu22qqzPrv6PBnEIxs5wlPf1Kpcx8DZ4aUGbYLEtDqRoNF828CHqcssuijfU6la6Y5TXgGdRjmZSqLfpf5VhI7pRF3yLkVThllhm/L6xywbwXY0cOyH7KoowVapS2mfVrwOfUPodZBtxer+KVnapymHV4rqNDmtBm7mvfbhWGzXGBK57VSNEcF7gDI4rZzHx1+oLKVJt1k9fn0dNVZps/GBpRc/UvLeca9p08oZGw2a/NxcKqbTNvisFTXqli5kdmJC17uzl2Ohkc1sCzh4y4z+1Re3qHEQ/5h3Rof9SIl8sVBf1B+YoWbabPr2LM7FsEPQGl8uY95xz2K1U228Ww169nymYb1O+LKvrcKSPucvu1MP//mmktlLV7ZER+i75LLLxHjop5fkdODakQNMuAt+LXaNZsO9yhYZXKZjke8viVsR0w4r5gUM82menJ5ioKD+5UJW3WQSNhl0LDZj1QiQ8plTbLQMDrUjlr3nP+wQHVJMzr4wmOqFxjthF+j1MHimabn87kFC2OKj6p09yXP6GAzSx/7nBIibxZX3p8IaUs2r9oLKkqi3raO5JQ6cBvjPiI16m6itn/SiWTOhGOaCRopjXmdqkhZ85/RdxOFZJm++QeqShXtkirP6idGbPMDMWzGm0w58UG80mNHjOPOzKS0A5vXs0tE43Pptr2yxYdMuJ+j1OVoLkvny+onMW8y0DGpfgBsx4IDvar2WIuNer2qz5nlr3RWEy7FNWEVrMvdzCTUShh5lNy6KSyEbNNdg0nlC6a9aXb65csju3xhfXbUbMO7fcPq5jcbsRj0aB2p8JqbTHndnyJvJJ2sz3z9DuVsujXHo9XFCiYbcGwz6vOsnkvhv1HtTdnnpvHG9TOgnmd/cNpDVUa1Nxk0RdOPq9syux/Jf0nVIyZ/dHA4f3KnzTr6ROn3AqEzfIaGQqocsCss7wej2odO839+/yq1MdUbjT7Is8FfQqZ0yuKHx9QMmjRPqlZiYJZZobcYYWzFmNGj1+Z0efMeDCkpyea9au7UK3hcFYN9WZ/dDCwU8WIy4j7vSGNlMz26UQgqmDavD75IY8cZpOiyEhRrY5HjXg21K89Ry36Ff6gCo6S6qrNa9RfiChYtpjPcg0qnTDH4p5gRNmkeQ/5YmXlKub+QwNHdTB81NxPKKlsjcUY0+1WTfInln3F48MBDafMQeAJb0yDGYt7qNgi/4RuIx4LuFSqsmj3h7PKVJv78frcetai/hkIRVVomyq7xX9H53dHFalYlLNISvGKxVgleVgZi7bA7/WoUDD78jFPQDuHzX7cQDSt3KB5T58aTsu3z5wHkqRS+IAyMbMerQQjarRbjAGjfo0WzbLh97lVKZo3adDZr9qc2e57vBFl7RZzTV6Pjm43659SuSxvqmjZV/T6/SpEzTkOn9srBc1z8A7HNWpR9/k8XtmKFs8jolEVqszxbT4xoJM7zf0XCiWF0jkNR81jHHSlNBS2eMYZ9iqZNst3wTUo24hZlpyRioIls1874nTqQMaiDXe59Wyt2XZkcnlFntut+BSzb5E66VOL1zxvd1FKWsw1hbxRxQrm9XF74hpWzIgH3DFVZ8yy5PSPyHHAfAadSSdVWw5pOOQz0+qLKm7R7key+1QZNdvSeMipYtGM+7xeFUsWcyiRhGwTzDw6VcmrcHCfEU8kEvL6XepsM+/3/pxPuRHzniv6RtReGjLi7mG/7GWLvovHq2LZbIOGnD4NZ800Bd0eddaa5xyNjSinerV3mH2IrDusuEVf+3iqoEjKPPZw0KV42mJe0RlQY9Lq+YxL6axF/8ETUqfdHHdEoiPSsYcVazH7CcfzbYolzHFV0XtceYv8HgglFC6Yz9uG3QGVs2Z+nwokFKsy6wdXYER63pyniYRD2hNzqcXiuW4kf0R1YbPv3D9SUtJiHOb3eVW0mG90On2KxMz8LkS82lFt9lEHwzHZTlq95zCsQDisJot5RaVCamyMGeHDviEVk+Y8w2A0o5jMfsXxQESBsnnOYZ9Lqlg8C/G69WzOLBueYEShVFGNFs9KMxGXmm1mW3Ao6FEkbralJd8plSzmGZzuimW9m432q9NunnPY49Fei3kjn8cluzum+lpzXy3hiqZVme3yMX9IOYvyNxQYVjJrjiOCbq9yFnOjHo9XlYr5LCQScmlPrUXZUFp5z4hqaizm5MLb5Bg+acQzgx61+s3+fD5lU7PMe87tPqG9FvXAwHBK+Srzeg5GErJVm/XSQFqKHDolh8Psn/vdbinuNOIxd1CpjHne3sJhpctm2xH2u1UqmW1yxO9Vs3kZlBk+qVi/xTxauF/PPFeQ3aKzmPKl5bWZ5dIZ3q+cxfx4yOuUI20xth4YkCNmXrdT0ZLCNrPd8juDqpX5zD/kHtIztWaeSpLf61YoY+bTMW9SEYs551RgWCMFs68T9AWULZp11olAXs78TDNNkX5Vjph9do8vrOcch414qVRSKDkkR8bsm434B1SMmfVDPJBTU8ninks45ZBFv3awX3Uj5jPrkWBU+6ot5qJ9Qf222pyPy+eyKkQGJbu5rxORgyqOWDy7i6aUtpt9v4FIVMMOc57L7Y+ppmT240aiET1Rb85lDeTSyh0x05PJZlT0HFNyQrvxWcjvUSxhxt35ERVTZv/fGwyqmDfne4Y8fmUtxslB75BqRi2eawQHNXTUrPtSyYQS7qgmWTxHGBjwKtRqtnPu5B4VC2YbGwx4VLbopw75gkpZlG9fIKaSw2LeMppQY4NZH9emkjq476QmdbQZnx0esSkSM+ugQWdU0bhZ1xRGnMpbvPsT8npUKZr76XeF5Mua9XrAHVRdldmniY6MaNguxdvNax1x9ysfNcdu7kBYFYt7Lnz8uPJu81o7Sw1KWbQFfueQdocs+paBmHId5jzD8PCw8raomlvajM+ygSPKxsxyGQmMKFk276Fo6KRKLWb96i8NaKDRLMdBr1slizmRSGBIu4+aEzvBUFiVaEXNTeZ4IeI6rkrUvB+jJ04oHTDLmStZUC4RM+ID0ZySFs8vvC63HGWzzIz4vWqTOdeUTvu1u1SlJru5r2MnffJZvHcb8iUUGjWfxQXzdqU7ZhjxoXBSyQGL95zdQcniujlDUZUbrOb4S6o6cFj1dRbvgbqCUt58Jy0bOCZ70sxvdzCimEX/K+T1W/a/vP6QRmUxPhuOq6rGLN/OREmJIydVa9H/Op6Q5fxX0DOkXMIsT27vsKIlcz9hX1gFi2eu/bGCEo1mfXIqmJZ/t9V8wrAquSZVW6TV43epkjHrgWHncTWMmC++OSNJRSzmd91enyIZc/8h75CqKhbv44Z9esph0S7ma1QYLqmqymLuyOvVcM6sU+Keo2oMmHPCQ/GIMjL7oydCSflLZp8z6PerOGr28T0+n3ZbvJfvDARVU1Vl+Q5gJhhTs8PsU+cjTrVaxI+OeJSymD/0+fwql838C3ldqrF6n8bj1jaLdwMHPXGFdx434pVyWbn4oIIj5rHzIxE1VseM+ImYW5Wi2f/yuoZUDpnz6Z5oSqNFc/9ej1flaot73evWvmqL+bVCQalISc05s/3whoaVT5t1zbAnK2feHEfEgv0qpyzeYYuNqKbJ7Ge5YyntOWS+ROn0hhSpNfeTy2eVyD6rStJibOM/qSqLOssTCKiSNuu4oNclW9K8R8NOj2pD5vuHsUBQAzmz/xpxenWkxhwTpLMZxcJNqsoPGZ/tDObks1s8Ew0HNGzRnwpFc0pWmXX7UCSpWMziff14SMl95vV0e4MqVJnvqKSSCRXdLk1uN9N0qlRn+U5VwO1VMmuWP1ckpmTJbPd9A6c0GjLzzx2MaGfCrLNcoZh21pt91Gg8r9zOrYpavFvpDUc1kjLnZV2BilJZM59Cbo9KRTOeDwS006IecJX8Ku3bZcSDHo+yMuvK2EhE5eJJtTeb+fpcrE6eqFlu8oEjqkTNfPKEEypaPL8N+cMqWbyvOBSIqLjPfH477HGp1mGWsWQ4rGcidjVbvK+YGBpSPGk2UAH/iKqGzXGpP+RXrmiOuZ2DQyoHzboslChZ9hMSgUHtOWKWe38wJF91lZqbzfw7GD6ukMV4YdjvUVXBbCNSoX5Vp8359KA/otGyWQbCIb+eKVu0o8mkOk49bsRzXr+G/TllLebq+iMZjdjNuDvtVjJn9rOcqVFlimZ8eHhEajHTdGo4o3h/zIgPhuIqHDbLRtjjUT49ovp6s/3wuL1yjVh8ly10TNmY2f8a8ucVS5ppTfqOqCFnjoWSg261xofM/Xs8esbiHZiBdEW5IztVU2vOsyZDJxSJmX25mG9Q8bRZPwRdaeUtvt8U9QcUtfg+2UhwWAWLr1kPBUIqHDT7Ol6PW9tKraquNscLA/5hhZJW7xMGJIvvMY14T8g2YvF83ePVqMW7UJ5kXNFGs84K+DzaWW3e04OhmOwTmlRlN88vPPSU6uLmdzACwYCGzaZAvoF+lb3m2NodjSs9ZbKZ1kKVShbPrN3BiHY4LcY8IwnZd5tjdEny+oMKWbx/2B8eUsqqj+ILqpwxy7HP61O5aJaZYa9XOyvmXInXH9CEml8Z8VTouJ616K+VSmU5szZ5Rs22zud7RrbYkBF3hmIKW7wjFQq5lbZ478Pvj6ho0Ub0B2OK77d6Bu3XrhqLvmuxoKHYkJIW37cJ+4cs3xP3+ryKZyy+h+PzKl8w7zmn06tYzizHAW9QRbv5TDTgcytWNOffc/mMspmcBkfNe6t/+JDSafPa+X0exSzmyyJBp7I5i/6DNyjlLeomf0hVObPMOH1hbWs3v3+WSldpOPZbFYLmuCridSpmUWcdD2TkT1uMPX1++ZJmfNh9Qg0Zs/1LBHw64jDrGb/Lo7TN7LMnE3HZCgdUkzTTus8dVtxi7u14Ka9Q3uxzHHUnNGDxLkAmclK1pZh57EBAslk8Q4gMasfzFmPYWFSBkYQmWNwrJ5Kj8lrcc8GhQyr7zXnzUKwge8YcR0Q8Tu1MmuW1PxJTrsHinotmlXVZtOHRUVWdelClZnNcdSIV1kjZPAdb4oAmNJh9wv5AWHUWdd+pWFHD9eZcU2AkolGXWfcNDidVcpn3dCiYVatvr+Vz3eeSLXINW3xnzRNSU8Zsb45mfRodtXiXxxdTJG/xnUVvQLWj5n76g0kNHzTPIRTMyB13qanJzNege1ghq76c16dS0BxjDkUyiuTM8ufzRtQxutWIR1zH1V82+/LDnpBk8Z5kLuTVQDaoOovv6/ryVUq0mufQf/SQIhb9h/KITxmLdy4DbpdG02Y+uTw+bSub9/vgcFyFAxbvK7rdOhQuq97iO7C+ky6NWHx/9GC+XafS5jnEo05lMxbl2BNRKG3u3+91Kz9qvp8cDQxo8LB5zmHvkJ4bjanGov/lcvrlsnge6wmEFI6b+0oH/JbfK/V5Q8pYvIvi9Q9r1GIOaigQkf2gOXfk9ARkTyflsHiWPlSoKJc0r10s2G/5ne2Qy62qrDm2iXqdqsqbfaCRQEzttkeMeD7ilu+ouX3SP6iBIzbZLerkwqBf0YI5PhsKJ5SLm+8P+JwulULm/E1wOCV7zOJ7586MSi3WbcGxg2ZZ8vvc2l007zlJGohmFLZ4r/hYOK/hhFk3pT1hZXNm2zEQSSpWazGXEQiotcZ8/ujxuLWtYrZ/7qGQ2kvmc7JSqaRTKYeSMTP/Bk4NKxE3+zT24edVP2L22f0hv+wpsz/gDEaVG7UYR/gDKlicw0hwUM/mzH5cLl/QcKGs4HDM+GxoJKNUzOL9w2BCFYt1UUKDx+QImfMMzlBUpVGzPzUUy6rkNPffH0lpxKK/m8umVe/1qKNgttdH4y5lk+a+wqGMbBZz/D7/sIp5s+6LRNIq2iyez8QSKpwyx8ODoRGVDprvCiWTScXTx2RLWPQVQ24lk+Z9OuiOKJEy+69+j1sli2eiyeCIbBbzk67hgoZPmGXMFS6qts68T0ZiBQUTA5rQYdZN+UG/4kmzLRiqsittMVcX8LtUsljDxeuNKFU2y0AgkFRVwUzTUCCs4hFzfjcajWq04lXG4n3Fk8G0vFGzjU27DsoRMuvwYDigQtG8PkOhmPIWz0S9nrBiBav1RNyqtxhLVobNfujLwQJxAF6WBYtWqPGPXs6I92e1dIH5wlrS5ldT90VGvCbu0wVls9EsKK/V08yKN1coaEr1BM2aZlamg1m3ejvNyrR+0kzNmddjxB11zZo5b4kR95cCunCKxeA6HdfqiebgoxSr1uqZ5ss/qUxO0c5mzZxkdiJy6Yma0T3fiEcPedQxY5kRn1qT0gXzzP2MFNqU7TTztVSRpvdcaMQL+ZwWLltgxGOxmOyZkKZONidhDxVtapq0yIj35nxa2mWmaV9DrRbMm2vEa9JxXVhnTsKrvVa9S+eY8VJC81YsM8LR4bA6Ku2a1GmWgfohp+Z2dxnxtkN7tWi6mdZkbaPa5pj511aV14U95vbVo0X1LjPLkq0Q04pFC424LxBUa8Jr+SD1ZKJGC1rMAeKRYr36ms0Jk+qJU7Sg1zy3HdW1mr5wtREvOZ7Uq2ebD5Nqog6dlzevg3M0red736yGNjNfp4QOaFqXeX72+px6Z0830zro1cL55jWtqa5R3wIzbrNJU3vNc4hlKqqf/moj7iif0MrUVrVbvPQyaWqXeqaYg6jn0+eo1LLciPd1xLR6oflwslzdqEk95mIgZftTWnuO2cHcPRrQ6hnmIPCYraDpDVVqaTDrlOO2Ni2YYnZ6A+2L1DHLTGtTS6NmzzfrjcyRE5o+71wjfrKqrO7e84x4NlfRksV9Rrymulod0xeqweJLp9Man9HcLnOysNI4TZ0zzzHjtSNaPsecQDqcbtN5jWb5rtQ16txzzLopZavXxOVvMuKJuuf1qu6K6uvMMr6/o03d3bONeLi6pIVdU4x4Q0O9Fs0yr2mxZZq6es18LRzao+WLe424IxfT+V3mJKitUtLcvrmWL7JNbHRozkxzwVPnaFi9k9uM+MFKUUs7zWMkm6dq4qLzjXiV3aGuBWYZyORGVT15jRFXrFpz+hbJYTE59lz/BFV3mPXf9I52Teoyy0Bnep9WtpiTY462TvUuMvsJjbaslveZ9YmjktHUc8xzy+fyWnTuLMsvErS3ntCcLjNf3bUhLZxqDrxrWzq0YK5ZZhrSUZ3XZFFe6ydozpLFRrxUluZYpDWZyal3mXlPS1KqKqV5M83y19IYVU+XWTedqMmqb7p5DrmaKeqYZ7b7Fe1W10IzTb5yWBdONycniqmYFl9gtjWlUknJVKPmTLD4ItCE5Zo117x/Sw1Dmj7b7D+kYye0qt6cmMu2TNHUJWY+2UdLOmepeS/uerakCXNeY8RzuYwai6c0dbp5HnWtRzRr9jwjPjN0RIvrY0b8ueZOnbPA7NMUGkY0Z7FFWot5XbzArGccqaAu6jL7iolURrFhh2Y0mpOOjVP7tGCWeU+UggXNnme2yYeP1WjmvKXm9o4Dmjl/pREfHR3VquVmXthKMZ1jcW7RaFT5QkmTJpvlNe/cpQUWLxHEpl+kTov2qTQa0vnTzZdLHP1erZxu1us7ck06v8/sPxQkrZ5rtjXBSJWqqydrSpvZxoarV2jqLLMOH60d0aJZZj/4+fpqLeixaHvr/Jo837znsrXP6Nxl5v5tpaQWLzfjXr9fUw6HNcnipfqBWcs1cYbZXtdFC5o/d5YRH3aE1TrTog6qL6vnHHM/lVGb+paZ8XTJpgWLzevmdTu1uGxXh8UDKH94mqZ0mednrz2qSRb9BLs/paVzzbK0v9auBb1mvZGyH9P0PrPdShaqtGKxeX36G+s0ceJEtbSYffBYZUTzLcaSLdmE+hrMvqXtvJWav8is8/t3/Var2sy+/EhVrWp6zPFFNl/WvEUXGPHq2sNa3FVQU5M5+ZcYKGnaLLPtbWpq1PRu89rFm0a1YL7ZnlWaTmruAvM6jOZzusBuPvgvjErnLjWvQ3XdgFoX9aqhweyLVBrimjLTTGt6kkNds81rNOG3/69WWqxouM3WIl/AvBfnrJD6Fq8w4sVSSctXmGltqCnqova86uvM8XuqZYqmd5tpLddl1WvRJxxIRbSk1exvJNtnaUKfOYZx2CtastispzP5itot6o103q5K23kqWyz6MX3qRM2YZbZDdZ5D6uo26/C6hkOaO99sk13OPVoRN18aK3Yu0qylFu1ZJa/lFvdWqVhSZ995lg8n612/UM8Es344VqxWX4eZf45JCzS3x7wOo6dcmr/ArE9KtQe16BzzWo+W8lq4zKLuK9q0YuUi2SwWzi9Ft2p+h3kOv5y+VKMt5hzRvIn7NcfiHsraQjq/yxw7BY6XlJ1m1ln16Sq1zDDrh1g8q5WLzPmHSqWioxMnq7u72/hsYu0uLZhp9jmO1trVazHmKXoz6lpg9hP67Tkt6zH75onRRk1YaI6HE8mC3jjNfHBYKJQ0NG2+uqeZ928s1KZps817ouj7tZbazAdKte1TtGyWWZaerqnWXIvymq84NOccs37NptO6YJY5HkllcnIXz9eEyd3GZ1V1HWqdYtavbROleRbzXM0Oack8c5x8ODeiC6eYfZryqNRnMe6tZOK6cLpZX8VSDsXt9ZpuMa+4a8I0dc82+0eO/n7NnWum1V47pFnzzHLsLyW0appZ/1QGQ1rcZ/Y3Cumk6vrMuiwWDamrKaDOSWb5m95Y0rxZZj657WEtmmK21YVYjWb3mW2vKx/RBZPNe7fsqNH5i818LVTXWc7VBUJhPe6co0zeHG+tW+BWn0W//XgxonM6zWPvndCkvrLFQ87JszX9HHMsXpse1iUt5sNM23BZF0+xeCnSllF9+1R1WvS/4qUFlv2E0ZJPiyeZ/Yrqlg4ttOjX1tik8yzOeXS0SlOXmHVWKFOtkRqzDNiK/Vp6jl9treY1nXTqOfW0WiwE0TZTi2aY/flEfIImW4xh6mq3a2WPOdY/UBjS6mqzPik32LSq29z/saqyOhb2qbXZzKdstMmy7U3XpyznlI7071ef1Qvb6Yqadpgvk9nmn6Nei752sVjSueeY17OxRmqZfo4aLRYocQ01qKvbTGvG87zOqbeYy5gyR3POMduCrN2rjm6zT5MffVpz+8zrUM6ltXyxOS9RfeyEzrGn1GCxQG9rsVbzLOYy9jU3qWe2OXYPHitYjm2qs0Na3WHOa1fqbepbbrZnezWs8xdYzDWVC1rWWqW6GnP+q8o+RXO6zfpvoi2vvinmiz6Hamp0zjTzHiqOVGm2xTjsVHxIq0fN52HZRocmn7PK3E9pVK/vHFG1Rf/r+Um9mj3LPO9oXUkdFnN1tqbJmjbX7E+17/upVlv8Rz2l+rLmLDH340iPaFWreR1K6YTmnnehqqrMufmJTXWa12X2tScUk1rYbs4P5GoWavqCZUa8pqZGs+ab/YFgwqMLas17MVtVq3krzDorWnCoee7FRlySOjuSmtNl5mt7Q416us066HlXneU8TWOdXQsXmO3TqdG0VlvUu8WSNMWiT5NJpXRJm8UCcSVpz5wVmjXLLK8TDu/SghkW84qlpBZPMu/R3bUTtMjiue5ztrKWLTTHHdGKW6MWz9VsxbQumW6+sJgrFHTKPkNd080y4BqtUcN0s5zNbN6tmRbltVh0arU5pFe8ukm1FmPxukxYF000+6+l4KjOt2ibEtmK4nMmaeZk8yCTwwNa0GS+sPZk+4WaalEuHbUN6uoxzy1dfUCTe8w6rpzJaHW7+cWXTCqvUYtzS8Sj6qod0mSL57qp5En1TjLb5GRljqZbzB/6+qX5FuOzaodDiy3KQKUyqkVLzf5aavdeLVlsnnM4HNYku09TLV64arBP1Nwus65ur6/Swi7zOux2OzR3gVk27FU16ukzx3OpQp1qpptjm3SmoFULzfT4gnWKNc7WhAnmsYvZU5bPF0LJ2eqcbZaBuoYGdVmU41TpsBqmmW1vOieVO8xrbR8paGWfWVc6vX5NOLlHExzmuCfRtUZTLJ7r1jj8lu1WtrFLU3vM/mtDJadVU816PWtvUedi8/ltumDTJT0Wi5DX5DUpk1e7xeKsEya2aeFUixeLO3o1ZY5ZXusbDmjmHIvnDoV6FZvMtrSpKq3FS80yli1VtGSpWWbqm/o1v7aoliZz/svVPEudM8x87TxyQEsnmduPds7S/IXmHMfwwYBau81yabfZtGSJeS/ac3GtmmLxJdhKXnM6W9Vk8aXT7IwezbSYO9p7uEMTZpjn3VIV0soZZv/YWaxVyqJctlcl9KreNiM+Wshq2iKz7S2rTq/KPav6GnM+dVJjreZblIHd2bmaa/HsTg0hdc+3fs7d22vx/NZu0/nzzTZ8dzakC6ea8epqm3qLSdVWm2nqmNKqHov3AU4kS+ptixnx7TMWqLvXHId5ygNa1WK+bFqqadSCZeYcaH5UWrzELPf56oPqWrLKcq5uekNFcyzqV3eiX30TLP4DEC3U5B6z/19f61B3j3kvVrRPU+eZ7VljdU7nrzD7QKPlpCYvWGv5XLfSUWf5bL96aFCzus25j2Bd3nIe91jOq/PazTorXtui5oVmnVUqlLS6x2wLSqkRzVtq1tOS1NzWZjlXl6iLa3KXWS4zzQ7Ns3i/o75+t5bONs8hVJksTb/MiDfUPKGVfWbZy6VTWm0x7i0USqqzT9HMLnO8FWjMab7Fc/S4w67m6RZz8P6yevssxquZiNa2mnMZW4vVmr/ELDOZXNHyOU8uk1H1pKgmTTX7tS0n+tVr8Z7XYYe0aKbZVucjDnUtNNvkmP2kmmaadZPDXtS0leY5h6p/o3lLzXYxkYirM3pAM+rMZ6LHp0/Uwonm/E2NbaJ65pjzYnsb6jR/oVlmSvZ6dfdavPdRKeqiJd1G3F6Kq2fJMiM+Eh3WZPcWTWs0216NVjTH4ksmdZdcpp4+c57heL1NvXPM61N2NGv6QrPtzdlqNG+52dbEy1VasdKsy8LhkGYGhzWlw+xDJDu7NW2WWadEK0NqnmIew95q0xyLfK1zlLXCYswzUmhUYcprjXhNQrrwHIvFsv21qqlv0IQOiy97ONLqsXjv42it1Ntl9tmP+Gu1WBb/yVbnHM1evMxM00hAF4yaX5bKNlara7FZXt1up1Q7VS1tZlptzWnNtXgPYchRVO9Mcyz5XKFWyXqzXpxWNapFFu3TqKo0Y4FZju3ljJYuMe+H/oFB1UyarxaLBUpSjhH1WKSpf7hBfU1m+W5s6dTimea1K7U4NGuJmU/2SlGr55n7r+TSOvc8M63HT+bUpzlqbjD759nR+ZbzirWtHZo9x+yXNdbXa7FFW1AeCGnuIrMuq8omtdpufkGkmGvQgpXm9Rk9ckxNM881/vNvSapq7NeMWWb7VG6KWc6B7myaoOnzzDFgTU21Fln0dWw2afkCs97Ilypautzcj+rqtaLVpjqLxYQrpanqsugnTKyraKFFe2Zr7NSs+Wa5bC4mtKrJ4gttrfWaea7ZPkUqe9XUbdYPjkyDZi3rtlwgrqHjsGWfJi6/eqeaZeZ/W2Zq4hxzrjhj36/Js83yWmMr6byl5v5tlax6zjX7cemaZi1dOMtyrq6zwaF5082y35Y9qL52s256dvI89Sww+wOx43G1Wcwt2x2/1eLFZrm3p+NaZRZ7FRLDurCrw/K5rm/KUk3vsjj2pDrL9++9g9WaOcccF9TW71HfQnP7OkdZCy3eBymWpckLzHfSgkmHaqaafctKpaJJkw9qWpfFPErNCcu+ot0d0+I5ZjluzsV0rtlN1TPV7eo7x+KZ66hNCy3ajnw6pfMXmnVZLpfX1ClZdU03j73L02mZr4drOtQ602x7O6p/pIummfPse7KTdL7Fdy1s3rhWzTL7r+lEVtk5bzDiyqTUXX1CU6dZfCelMa4ei3rgcJNDPbPNOuhUVVZLLfqQTamwzms232N8Jl3WhVPMc7PF7FrRa9b3sURC5UndmjDZzPPRqaOW9YPt1Cl1W7xzWdPYoN755jGyp4Y0+6i5EFymb6a6+yzmD7PS3D6zTR4ZDmlxZqemtZl1WdXEPs2d3W3EW2vs6rPo09h9CfXMt3h3JRnRBVUWz0QbqrRqijm2KaQTOn+heVx/JCpHqajJ7WZ5OtAxR/Ms3r2ONVVrUrc5JnHU1GuKxRxeNrhH51r8p7KV9klatsg8t1yuoKaeVxnxKp9TF2QD6rRYjNnZtkITZpr1wITaiBZPN+fqalra1d1jtmfHHNKCPov3aRx7tNri2f5oPqllFu+HDjmrpdY5amltMz6rOOLqsWgjWm1FLZpizj/sae7WQosyUJ0Y1sqyOd9tb23XosVmWneXYlrZZ9Y/J+qq1T59llosFlMJn6hYzoF2tu1S92zzHgofS2rxLPPcqmtqNdfifaQT5bhWzrX4DljVSZ272LzXj9ZkdU78pJrqzEUiTvTMVM9ks2/eFCuob7pZN5XiNZqz0EyTq5zQ+dMs5gdcKU1dttaIpyrPaOUSs56pq6poypxzVF9vzhHlHDPU0WX+zezGlOV4IVnrUNsss+9Sskf0qjnmdWtKB7S6w/xC9/bMqOV7H7bqGqX7VqvGYoGSZEeTplu0vZlmab5FW5CuGdGkbnMe4KSjTnXTzXPoqK5W3zKz/s6WbeqzeMe6WCqrZ/EiywXiRge8ls/221sPWD6b9tuHtWSaOUban4ro3BazzxRvmaC2PvM5o61S0KJlFnlUGtU5S3st5+omHtmj+TPbjPjuCW2aM8fiHGJeLWswnx0/0zpH85eZ/V17Y5Mu6DbLfflQv+V3iTK5rC7uNtMjSQfaWzVnljn/VeWNqttiXrG5sUFz5pr5UVNXq675y4y4x57R8oUW7/HbqrR0abcRd2SDWtVmLnxQKpVU29qrWRbPoCce3qWF09uM+K+aZmrKXDNNdUPPWn4fz+Go0kKL+fGk/ZDld1vS2ZyWWHyHM5fLqX5EmmbxHQxfa4PlfK2jrk1dc81j19Tu04IFZj2dr9SpdZY5DstXtmnREnM/qUxBtulm25tJJdTXYtP0qeY4tuIcsfy+SHV9q2ZYPGNqaqjWwh7z3PpV1HmzzPp7NJfTBfXmGDObrNOi8815yJFYTEpFNdXiP4k91WSz7NPEm2TZp0nbD6l1pjkGbCvFdGm3eU/vsNdr+QLzeuYzeVXNWWvE7ZGAFjeftPy+bjjZqd5Os27PVy/QTIvnNp68R6PtZv06szanVy0xz1mqqMNiTkmlnKYvNMtATdCrcyelNcniGXShONmy3p2UCWmJeUlV3zxBfQvNNB0pRnRep/kcrlTXpN4VZh2XUo1mrHi9Ebe5nVq6d7Mm2M0x97GFCy3nFZOdTZo623z2nt9zUue1W/ynIakOTVlmHrtc86TO7zbb0WzFpoXnmmP62oEBLQrtVVuj2Z45O1epY4Z5n07KHlb9RHPMOLOc1TkW/dRMtVcds817pU4FLV1s5kW86FD9fPPZSbzqsHoXjKrZoq/Y1tyoORbfL+8czapvksW7va1dmrbA7CeUag9o7sJlRtxdCeuSLotFqXJJzV9hzmMcbago37bacoG4mbmdWjDZbPdPJldYPrep76ioZ4FZxzXZCjp/hnk/7LRVtHC5WW/k7DVaeY7F+6Sjea2uiVv+x1/H483qmWCWJ0/DRWrrMuusTv+vtNjiO0OJygQ1WrQFFds2LVtmlvuq0bwWL11mxKWKevt6Lf/jr2xNRJMt5pTK9Uc1ZZZZZxWbyuqbZ5bX2rp6nTPPLEuOSkUXTDX706ViQRdavBem1LDOn9wkh8Vc3UjTUk2fZV7TWFuVZs82+6MTHEWd023m66GqnJbOMfsuqnZr6SKLeSBHQkuWmMcdzSc0Z8lKy7k6Obyab1FnNTeFtXCmOW9wNBfTUos5okaHtHSGeS9Gc00atlgro96R07LF3Ua8kBzRqulmnkpS49Quzbb4LnzeU7b8LlG2EtGy6eY9VAxXNPecZUY8dfCEZi0w761iWWqaZc4f1o2UtHaq1XcwqlTVdY5mdJnlL1wMq22qeU/Mrh/QCovvZD5fM0FLrJ47VDdq9jJzvJAfdWiZxffGKumIVjea7wBmcg6FHA2aNclifNshy/asvjmqBRbvCJ9KOnVui/kejL1mqvpWWrxHe/CIllh8nz9ZqtJ0i+/pJRIxXdwQ1oxOsz07HJ1u+T2cutaUerrNMlNd36ypFt+NPeWwa8pCM5499BstXWKec6o4qj6L98ej0aiqSilNmmTxvudQo2UfvFTt05RZVs9t6jXdYhwRbCiru8+81omafZrUa/azooUqLV9msZB/KCxH1WJ1TDTzr9n1Gy1sM/M7N3Whuiye27TW27XAYg2Ssr1eU3vMPkqlUNCqVnNhv1y2oN6lZhvk9fk1uTisie0W/0FCQ586Z5pjlfZCv5aaXXbtbupSr8V4wd7v1jk9Fu/xl2tVP9diDJMtaPV5Ft8t9lj8J6Yvg8X/6Q0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOBNYIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzhIsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZwkWiAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAswQLxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAWYIF4gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgLMECcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwlmCBOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4S7BAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcJVggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOEiwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABnCRaIO0O2bt0qm82mWCx2ppPyN2Xz5s1qa2s708n4q9uwYYOWLVv2Z+1jaGhINptN+/bte0XSBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgFceC8T9Bdhsthf8t2HDhjOdRPwBFk4DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADA2cJxphPw98jv94/9/MMf/lBf/OIXdfz48bFYU1OT9uzZcyaSdlYol8uy2Wyy21mfEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPhDrND1FzBlypSxf62trbLZbONiTU1NY9vu3btXK1euVENDgy688MJxC8lJ0s9//nOtWLFCdXV1mjNnjm655RaVSqXTHnv9+vW64oordMstt6izs1MtLS360Ic+pEKhMLZNPp/Xxz72MU2aNEl1dXV61atepd27d499vnLlSt11111jv19xxRWqrq5WKpWSJHk8HtlsNp06dWpsfzfddJOmT5+uxsZGXXDBBdq6devY32/evFltbW165JFH1NfXp9raWrlcLiPtW7dulc1m02OPPaYlS5aorq5Oq1at0qFDh057vv39/Xrzm9+syZMnq6mpSeedd56efPLJcdt0d3frtttu0/ve9z41Nzerq6tL//Ef/zH2+ezZsyVJy5cvl81m09q1ay2P9fv0bdmy5c+6ZrFYTNddd93Y9XnNa16j/fv3j9vHHXfcocmTJ6u5uVnXXnutcrmckZ77779fvb29qqur08KFC3XvvfeO+3zXrl1avny56urqtHLlSj3//POnzUcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcHVgg7gz7/Oc/r7vvvlt79uyRw+HQ+973vrHPfvvb3+qaa67Rxz/+cR05ckTf/va3tXnzZt16660vuM8tW7bo6NGj2rp1q37wgx/opz/9qW655Zaxzz/1qU/pJz/5iR544AE999xzmjdvni699FJFo1FJ0po1a8YWeBsdHdVvf/tbtbW1afv27ZKkbdu2afr06Zo3b54k6YYbbtCOHTv0X//1Xzpw4ICuvPJKXXbZZTp58uTYMTOZjO68807df//9Onz4sCZNmnTa9N988826++67tXv3bnV2dmrdunUqFouW26ZSKb3xjW/Uli1b9Pzzz+uyyy7TunXrjAXo7r777rFF0q6//np9+MMfHlvYbdeuXZKkJ598Un6/Xz/96U9fMH//3Gt25ZVXKhQK6Re/+IX27t2rFStW6LWvfe1Y/v/3f/+3NmzYoNtuu0179uzR1KlTjcXfHnroIX3xi1/UrbfeqqNHj+q2227TF77wBT3wwANj+XL55Zerr69Pe/fu1YYNG3TTTTe94HkBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgzGOBuDPs1ltv1Zo1a9TX16fPfOYzeuaZZ5TL5SRJt9xyiz7zmc/oH//xHzVnzhy9/vWv11e+8hV9+9vffsF91tTU6Hvf+54WLVqkN73pTfryl7+sjRs3qlKpKJ1O67777tO//Mu/6A1veIP6+vr0ne98R/X19frud78rSVq7dq22b9+ucrmsAwcOqKamRldfffXYonFbt27VmjVrJEkul0ubNm3Sj370I1188cWaO3eubrrpJr3qVa/Spk2bxtJULBZ177336sILL9SCBQvU0NBw2vR/6Utf0utf/3otXrxYDzzwgILBoH72s59Zbrt06VJ98IMf1DnnnKP58+frK1/5iubOnatHHnlk3HZvfOMbdf3112vevHn69Kc/rYkTJ+qpp56SJHV2dkqSJkyYoClTpqijo+MF8/fPuWbbt2/Xrl279KMf/UgrV67U/Pnzddddd6mtrU0//vGPJUnf+MY3dO211+raa6/VggUL9NWvflV9fX1GHt19991661vfqtmzZ+utb32rPvGJT4wd5/vf/74qlYq++93vatGiRbr88st18803v+B5AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4MxznOkE/F+3ZMmSsZ+nTp0qSQqFQurq6tL+/fv19NNP69Zbbx3bplwuK5fLKZPJnHaRtaVLl477bPXq1UqlUnK73YrH4yoWi7rooovGPq+urtb555+vo0ePSpIuvvhiJZNJPf/883rmmWe0Zs0arV27VnfccYckadu2bWOLjR08eFDlclk9PT3j0pDP5zVhwoSx32tqasad6wtZvXr12M8dHR1asGDBWNr+WCqV0oYNG/TYY4/J7/erVCopm83K5XKN2+4Pj22z2TRlyhSFQqGXlJ4/9udcs/379yuVSo3LG0nKZrPq7++XJB09elQf+tCHxn2+evXqsQXt0um0+vv7de211+r973//2DalUkmtra1j+1iyZInq6urG7QMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABnNxaIO8Oqq6vHfrbZbJKkSqUi6XeLn91yyy1661vfavzdHy789Upra2vT0qVLtXXrVu3YsUOvf/3rdckll+id73ynTpw4oZMnT2rNmjVjaayqqtLevXtVVVU1bj9NTU1jP9fX14+d3yvppptu0q9+9Svdddddmjdvnurr6/X2t79dhUJh3HZ/mM/S7/L69/n8cv051yyVSmnq1KnaunWr8XlbW9tLOn4qlZIkfec739EFF1ww7rM/vgYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD428ICcWexFStW6Pjx45o3b97L+rv9+/crm82qvr5ekrRz5041NTVp5syZmjhxompqavT0009r1qxZkqRisajdu3frxhtvHNvHmjVr9NRTT2nXrl269dZb1dHRod7eXt16662aOnWqenp6JEnLly9XuVxWKBTSxRdf/Iqc986dO9XV1SVJGhkZ0YkTJ9Tb22u57dNPP63169frLW95i6TfLZ42NDT0so5XU1MjSSqXy396ov8/L3bNVqxYoUAgIIfDoe7ubsttent79eyzz+qaa64Zi+3cuXPs58mTJ2vatGkaGBjQ1Vdffdp9PPjgg8rlcmOLCf7hPgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHB2YoG4s9gXv/hFXX755erq6tLb3/522e127d+/X4cOHdJXv/rV0/5doVDQtddeq3/+53/W0NCQvvSlL+mGG26Q3W5XY2OjPvzhD+vmm29WR0eHurq69LWvfU2ZTEbXXnvt2D7Wrl2rb33rW+rs7NTChQvHYvfcc4+uvPLKse16enp09dVX65prrtHdd9+t5cuXKxwOa8uWLVqyZIne9KY3vezz/vKXv6wJEyZo8uTJ+vznP6+JEyfqiiuusNx2/vz5+ulPf6p169bJZrPpC1/4giqVyss63qRJk1RfX68nnnhCM2bMUF1dnVpbW192uqUXv2ave93rtHr1al1xxRX62te+pp6eHvl8Pj322GN6y1veopUrV+rjH/+41q9fr5UrV+qiiy7SQw89pMOHD2vOnDljx7nlllv0sY99TK2trbrsssuUz+e1Z88ejYyM6JOf/KSuuuoqff7zn9f73/9+ffazn9XQ0JDuuuuuP+mcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8NdjP9MJwOldeumlevTRR/XLX/5S5513nlatWqV//dd/1axZs17w71772tdq/vz5uuSSS/TOd75T/8//8/9ow4YNY5/fcccdetvb3qb3vOc9WrFihU6dOqX//d//VXt7+9g2F198sSqVitasWTMWW7t2rcrlstauXTvueJs2bdI111yjf/qnf9KCBQt0xRVXaPfu3erq6vqTzvuOO+7Qxz/+cZ177rkKBAL6n//5H9XU1Fhu+/Wvf13t7e268MILtW7dOl166aVasWLFyzqew+HQxo0b9e1vf1vTpk3Tm9/85j8p3dKLXzObzabHH39cl1xyid773veqp6dH73rXu+R0OjV58mRJ0jvf+U594Qtf0Kc+9Smde+65cjqd+vCHPzzuONddd53uv/9+bdq0SYsXL9aaNWu0efNmzZ49W5LU1NSk//mf/9HBgwe1fPlyff7zn9edd975J58XAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/jocZzoBf+/Wr1+v9evXG/G1a9dqdHR0XGzZsmVG7NJLL9Wll176so97yy236JZbbrH8rK6uThs3btTGjRtP+/cdHR2qVCrjYldccYWRPkmqrq5+weOdLg9O51WvepUOHTr0kvbV3d2tX//61+O2+chHPjLu96GhIWM/+/btG/f7ddddp+uuu+4F0/VKXbPm5uYXzf/Pfe5z+tznPjcu9scLvF111VW66qqrTruPVatWGedpdf0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABw9rCf6QQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH6HBeIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4CzhONMJwCtr8+bNZzoJf7K1a9dqdHT0TCcD/598Pq98Pj/2eyKROIOpAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+L/BfqYTAODsdPvtt6u1tXXs38yZM890kgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7usUAcXlE2m00PP/zwaT/funWrbDabYrHYXy1Nr4QNGzZo2bJlf5Vjbd68WW1tbX+VY72Qz372s4rH42P/3G73mU4SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADA3z0WiMNf1YUXXii/36/W1ta/+rG7u7v1jW9840W3e7FF7l5JVml65zvfqRMnTvxVjv9Camtr1dLSMu4fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/rIcZzoB+L+lpqZGU6ZMOdPJOKvV19ervr7+TCcDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ4D9TCcAf38ikYje8pa3qKGhQfPnz9cjjzwy9tnWrVtls9kUi8UkSZs3b1ZbW5seffRRLViwQA0NDXr729+uTCajBx54QN3d3Wpvb9fHPvYxlcvl0x6zv79fb37zmzV58mQ1NTXpvPPO05NPPjn2+dq1a+V0OvWJT3xCNptNNpvNcj/d3d2SpLe85S2y2Wxjv//egw8+qO7ubrW2tupd73qXksnk2GeVSkW33367Zs+erfr6ei1dulQ//vGPT5vm06Xp93nyexs2bNCyZcv0ve99T11dXWpqatL111+vcrmsr33ta5oyZYomTZqkW2+9ddz+Y7GYrrvuOnV2dqqlpUWvec1rtH///tOmBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGceC8ThFXfLLbfoHe94hw4cOKA3vvGNuvrqqxWNRk+7fSaT0caNG/Vf//VfeuKJJ7R161a95S1v0eOPP67HH39cDz74oL797W+/4GJrqVRKb3zjG7VlyxY9//zzuuyyy7Ru3Tq5XC5J0k9/+lPNmDFDX/7yl+X3++X3+y33s3v3bknSpk2b5Pf7x36XfrcI3cMPP6xHH31Ujz76qLZt26Y77rhj7PPbb79d//mf/6l///d/1+HDh/WJT3xC//AP/6Bt27ZZHuulpun3x/7FL36hJ554Qj/4wQ/03e9+V29605vk8Xi0bds23Xnnnfrnf/5nPfvss2N/c+WVVyoUCukXv/iF9u7dqxUrVui1r33tC14LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnFmOM50A/P1Zv3693v3ud0uSbrvtNm3cuFG7du3SZZddZrl9sVjUfffdp7lz50qS3v72t+vBBx9UMBhUU1OT+vr69OpXv1pPPfWU3vnOd1ruY+nSpVq6dOnY71/5ylf0s5/9TI888ohuuOEGdXR0qKqqSs3NzZoyZcpp097Z2SlJamtrM7arVCravHmzmpubJUnvec97tGXLFt16663K5/O67bbb9OSTT2r16tWSpDlz5mj79u369re/rTVr1hjHeqlp+v2xv/e976m5uXksP44fP67HH39cdrtdCxYs0J133qmnnnpKF1xwgbZv365du3YpFAqptrZWknTXXXfp4Ycf1o9//GN94AMfeMHjAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4MxggTi84pYsWTL2c2Njo1paWhQKhU67fUNDw9jicJI0efJkdXd3q6mpaVzshfaRSqW0YcMGPfbYY/L7/SqVSspms3K5XH/m2fz/dXd3jy0OJ0lTp04dS9OpU6eUyWT0+te/ftzfFAoFLV++/BU/9uTJk1VVVSW73T4u9vv07N+/X6lUShMmTBi3n2w2q/7+/j87PQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPjLYIE4vOKqq6vH/W6z2VSpVF7W9i93HzfddJN+9atf6a677tK8efNUX1+vt7/97SoUCn/CGbz0dP4+TalUSpL02GOPafr06eO2q62t/Ysc+8XSM3XqVG3dutXYV1tb25+dHgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPxlsEAc/i48/fTTWr9+vd7ylrdI+t0CaUNDQ+O2qampUblcftF9VVdXv6Tt/lBfX59qa2vlcrm0Zs2al/x3LzVNL9eKFSsUCATkcDjU3d39iu8fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfxn2M50A4JUwf/58/fSnP9W+ffu0f/9+XXXVVapUKuO26e7u1m9+8xt5vV5FIpHT7qu7u1tbtmxRIBDQyMjISzp+c3OzbrrpJn3iE5/QAw88oP7+fj333HP61re+pQceeOAFj/VS0vRyve51r9Pq1at1xRVX6Je//KWGhob0zDPP6POf/7z27NkjSdq1a5cWLlwor9f7ih0XAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfx4WiMPfha9//etqb2/XhRdeqHXr1unSSy/VihUrxm3z5S9/WUNDQ5o7d646OztPu6+7775bv/rVrzRz5kwtX778JafhK1/5ir7whS/o9ttvV29vry677DI99thjmj179mn/5qWm6eWy2Wx6/PHHdckll+i9732venp69K53vUtOp1OTJ0+WJGUyGR0/flzFYvEVOy4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+PI4znQD8fRkdHTVisVhs7Oe1a9eO22b9+vVav379uO03bNigDRs2jItt3rz5BY/b3d2tX//61+NiH/nIR8b9vmrVKu3fv/8F9yNJ69at07p16140TTfeeKNuvPHGsd9tNps+/vGP6+Mf//iLHuOF0vTHefJS82Pr1q3jfm9ubtbGjRu1ceNGy2P/8bUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAmWc/0wkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwOC8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwFmCBeIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4CzBAnEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcJZggTgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOEuwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnCVYIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzhIsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZwkWiAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAswQLxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAWYIF4gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgLMECcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwlmCBOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4S7BAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcJVggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOEo4znQAAf1ucx/eovqFxXCwecGm0lDK2DXiiaiub1UxkxK89tTVG3F1yaGcwY8QLhaKCyWMaHhkxPvM6fUpkO4z4kUJeoax5DK/fp0R21ExTMKaCbaIR98XKsttLRtyZKcnhDBnxbC6vSLYiT85cf/N4OKJYImvE/a6ASoW0ua+gT5XRvLm9Py5b/hkjHgsPKDJgnlsiMqgDB4tGPJ1KqioyoPhEM//8gw1qS8WNeCXnVSFvXiNXIKR8xox7IyNSR5MRdw9HZHv2t0Y87ParvsosM/FkUseL1Zo40cy/gM+jQNJmxKOemCLlOjNNfq/ylYp5DHe/9me9RtzjH9aoRZr8XrcOjprnHE0kVZBDHYV647PwSE7R2hYzTcERJUutRry/4FJK1WaavGGVRs1r7fe5tDtnptUdjqimztxPpFSt8MDTKrZPMD6LBU6qKh8w4inXSRUTESM+OJxUtmDeK16vW+VCzoj73GGlR3cZ8eGAWxXbdiOeCfu1J5xVS7153sGURyO5shGvxParud68t/oDXlXZzXvL7RlWpmzWGz6PV1tGq8y4N6GmgkXdF47JU+dQc6OZH65wTNFR81qE489rtGzec2G/V7mcRb3hdctuUe9GvUPyVZnnPOwf0IFDZrn3ejxKjkTV0GCW18jQcWVGho34EZdDjQHzmtYkQ0qXzesQ8YZVrjWPPZQuq9BvljF3MKLs8aeN+IjXrb3ZKtXVmff1oD+sTNJsI6Injyk3HDTiznhOqbyZ1sFgXKmyea09bo9KFt1mnzug3TGzfh30hzXS0K/a2lrjM5ffr5BFOxQd8CiVMq+dc9CpbLjBiLvLcSWrzPo16HWq2mZen0TYqQlVZl2pdL8GjiRVXWOWy1TYK0clZsSPB32KjpjlLxSIqVww8+94OqjhKrOe8fvCksyy4fcHVajdYcSHg4M6eCCuqirzGP3eiDwps+1NuUOKWVzrgXBSyYJ5HQKRhEqjZj09MBxVdN8JI+50+5XXc+Z+fF5t32teH0kq+KLylcxr2u+OajDTbMSz/oBS2YK5va8id8K8H0ZCgxodNfM14vdoZ9Esr0ORhHJHB414qVhUKikFmsy0njxxQomMmSanN6h40oyXQ3E5Wsw0uRI+xQ+Z+ef2ulWxmfWx3+dXqcrsA+XzOTUMPye7p9P47OCwFBwxz7s86FfSom7yVKeVGzXL0lAoobTdvKY+j1fPVcz7wRUIafeomRfpbE6JkbwCNrPeHUgPKWFRXofCMeWyFv0vb1j5vHkMr9erfNEs32GPU0fsCSMe8Lp1+OABI55IJlTKppQImfka80cVyzQacXf8kFJFs/0ruDyyp8zy6gxGVDKTqsFAWHa7eR1cvpBqbAfNtKbSyldG1Vk28/X48CENx8y21OE+pmLYY6YpllYlZbYpTl9OQYtzGA66VVNlnrPH69feOrPtGBmOyhtMqsOiLfD4n1faog9ejrsUs7jn/O6gCkUzHg30q9Zu0Td3u+Qwq1C5vX4Vq/ab+xkOKV/2qr3FrJuGh12qyZr5F/JHpYKZfzn/CVWlzDbZFRpRsWSW+6DXI7vNbLeG/ad0bK/ZFw2Gogr6WtTaYtbhkX6XYimzDHj9EaVy5n3t9B1ROWe2yZ4hp9RoZmAgYVNTyzYjHg8N6ORhi35f0KPDI1E1NZr1664TdrU7k0a8kHYrMmJe62TYo+GkRb8iOKhRi3Pwer3aKbPOcg7HVX3gsBH3BMIqlzvU2GCmdXAorEwyZsSzkRMqZMwykAzHVcqbdXu+GNGMaWEjHov7deyw2UYEPUMaGrXoh7g92t1erzqL/tfJUEjJpJmvmVBA0bxZzmLBEWXzFvV0fEiBUTNNMZ9LtVXm9Ql5XbI7fm3E88NONVQysteYaT027FI8YdbVqdAp5dJm/eDx+pTKmceOFSpS5zwj7o4nlT2814j73QM6nvMZ8aDbr7S9VQ6LMXExXlK81qyr3dFhJS0q9xOFQcVKZn4HvG5VLMrrkDuoZMliTO8OyV5ttlt+n0/P7zsou928T0vBhKIWY+vw0HOqajXz9eSwX6WSWW9kPUGNVsy+9pAzqWTInONIRE6p2qLiTUWH9MwRs54ulSsaDnmUTsSMz4YHB5RKmWXfHY4qkTP7Os7wiHIls31yu72qVCza2EBIMftuIx4MurTTZpaxUrEsVz4pb948P2fAq2zGvOey4bgKFv0vZzqobH2bER8KRpV1WFxrr1uq2mnEIwGndmfMsX4mn5e3WK9cwm98Fg045Sib497h6AnlcxZ1jddjma+BYES2itkGnQqOKLTPnGvyeuNqL5h5kc7kFLC1qjNjMZYMRhRPWcyveH1KpM0y4PX6lM6aaR3xBlSdN++tAX9U6aNm2+4KRdVRZ1G+E3FFill1TLBo98NDimfMtIY9ISUs5o6Oh8oKWrTJyQG3HEGLcUcorqqSec4eX1hVzceMeCyWUE05p2aZfZFdzqgio2adH3X6lU6Z17TfHVTcYhw7lBpQst1sI0Jer56Nmve7MzyimnqLuZiRhEazDrWnzfv0ZPSwRhJmuZTTr2zK7JsPxrIq5M26zOkLqzhq1sdD/ojl+Czsd2u06VkjXk4EdOigT63N5rXz50YVbzHjnpODyli0yd5sSOmima9Rn0u2kkWfJjCs2gazrRlK5GQfNvuW/pTUdGJAzY1mmk4M25WwyNfc0AnlomaZccdTKtSbfSO//KpfPNWIx2MBuZ57yohHXB49V2NeB7/Pp7qRkhobzWs64AwoGDXrOSXLytZY9GsHTqpgVWf5YipYjNtCPpdsFn3woNejfWWzfvD4g0o11amh3sxzV8Rv2QcfGk4qm7IoA56iklmL+V1fUA0W8cGRghJNLjNNgajq7Bb3qD+qXKrGsq94LJ1SzKL9GHYFlchb1K8ej7KxqLmfVJ08uTYjnnSGVWuPmWmKVxTav8+I+9xe/bpYrWqz6yx3aFCRjJkmn3tE5bx5jHDAqXLBzO+UL6Aqi+dn/ZGCgtX9Rjzoj6rFot88mCgod2C/5Vyd1+nUiEX+BYIxxcoW+8odV8JiLqN/KKBQ3Nx/3h9Vc7vFXFM0oewhs//g8/vUYjfnlCQp4j+kzIg5JjkVSiuasyhPvohiaTMe8rtUKJjnHHT7ZS+a7aIrEFT2qNUcqFM7zWKvUrEsp3uv8hGzT+MKhjVcNNuOkC+slEWaXJGYChZtqTMQUcWijfB6I8qmzbSG3QP6beikES+UivJP6VEgadEfcGU0WoqZafW7NJIw70VbYESVitlmuvxx1djNPuFIIKCdFs9WhxI5VSXNNjmdLyhT7lcgao7DnMlRDTea/QF3/2HlLcYLQa9LjrxZP3hcEY2kzTFVyhfWzpKZVk8io5aBXxnxTDqlZ9MldUw072sd6deI35y/OVFVVDBplo2896Cqh805Yc9wTKMWafL6PKq2Wzyf83p0apfFnEgyJXcwpM52c18nKlmFzKIhvz8gq2bO5Q8rY1E/OF0+ZYsW8zQ+l9rK5nPGVLhfB/abeRGNJxSpSWpCh/kMI+OJKla2GPcOH1Emb9F2BJ2qWDw3HDzlU8lpMVaJD2q+xXPPYsap35wy52SHh5NqT0kddotnwSeeVz4dM+KlgQHlh81+hS/tULFspinq9WpX1uLZdDip/BHzWg8HBrS72uJdg0BQ3nyVWhwWYxtXWCMVi2du8f0qF8170e0NKWMxvogG/GrssOhDBgZ15HlzjsPv9mtHbbsRDwYjitQW1Nxk9qe83mEVs+Z9HRrwKhe3mO/O2lTKmmUg4ktr1OL9hIDPqT0WfZeAJ6xns2Y97Q6OKFiuUWO9xdg69pxKKbM987sSKuXNesPvC6hcsDhnd0nZqHkPVaW92tVizqEM+sIKO/YZ8ZDHpR11FdXXm+3KQCwhv82ss9xBjzJpswx4/FGNWlwHn9evKou+jtPjVcXiOZkrOKyGtEU/JBRTur1VtTaL8trvUtxi3sUbTiheaTPiA8FBJS3qjWGvTzJPQe5kUeUGc67O53Jrv91Mq8frUcJ+QA6L+aaku18jKbOtCzsDSiQtxkK5KrmTZp9wJOxS3NyNwv4hlS3L8ZCefc5Mq9MdUtn+W1VZzNVlB5/VaNDsdzqjGRXiFuXY71U6a9YDAbdflRGLd3mSYWWazDorHBjSszVmneUMjShr8ZxMkiK+ASUsnuEfP5lQ2GK8r9gxy/Lq9/mUs3hOGw5E1Gozx4yx8KB2Hzf7Ia7gsHbnzfukWCrqVFVU8bh5nw65gvKkzGs95B5Ri8Vz3crISdWXzOvgCwS0o2COh4ciMWUOHjG39/lUU20xP57P6USwrOGQeYw6f8ByrtPrdimbMPN1KOlQ0qIf7PP41W7uRmHfkA5a9Ac8Hr/21pjPSLLZtNriJXmrzb/xBkOKWzzXPVIoyZs3295w0KliweI9JXdE2ZLZ9obcbh2umPOWAbdXVfVmPziRTMnpHFanxTyNK1dQptlMU+joERULZr92IJxUPGfe1z6vR5WyxbMQj1uHLd5C93q9qq0znz8mEwkFhwPqTJr5cTKa+f+1d+fhdVf1vsc/e2fvzFPTpknTJM3QpEnapjOlDFK0yiQPg0cUq1AVPSiIgOWI91ylTuDR6xHxIA7HCzijPjKIgmKxRRBbWmgpU+fM87jned8/KrmnZ61fIHhsArxfz9Pnadb+Zf/Wb1rru4bfisYs/TRD3b1Swrz3fYNHpKT5LA51dygjaYnZ+waVmTL7OoMjR7TrxTEjfWRkRBlKqWSWGUMMHj6sgGU8p7O9XeGeTiO9ra1TPpelP2vksPyFZp9SX9+AdrrMY+sa8cn1tPlsDY6Matw7T0VFxcZn0Z5D8lnGF7r6BjScsNQpo2F5U2Z6v/+IDj1v5mmgu1Muy7GN9B/Rvn1jRnpf/4DSA0EVFJnl3MDRYfXGzDjL1zsmf6FZV3eFxhS21BHdvrgSlnqrp+Oong6b5U9XV6/clvZfT2+fgvFR61hpR2xccZ857+1wz4hG/GbfW6j9kFLj5nzj9uGwwpZ5if19g9qZZx5D52hAqWfM8Zyunj4lR93KsYxBj/YeUTps7ru/a0C9lvbqcN9RpW2xZVeHsv1mv0R3T5+eSVj6Pnr6lcw252R39YwrPp5UlmUOYNtgm5KDbUb6wQG/+kNmednb16OwZW7qSP+IFDPrv44hn8LPm+dvoKdToZTZd+QbPKy9e33yZprfFex9XtFxc+7CcFuX/GGzDOoZHVDU0kc03N0pr2UMf7jroA6kzPM90NWnFzPMuqm3s0N74355LJ91dXRrxDK/tutot8aHzXvmUFZUAUv/VF/PqJK2PpGeNr3gssXyPfpr0hI/jEbk6R6zxooHB5+Vb9z8rvDwIUUt8xC6e3rlD5p1ylBPhyKWsbiuji7FLWVcX0+7ZJm37B88rITM+jWRSKjX36GRUTOvg33tClnGSqOD3Qpa+uaHj3Yrlmme8PZoSmlZ2gW9o/K7zX6Mju5h7cw0jzkWi2l4ZFgjo5b5Bv1jSvvNNnR3V1AhyzsBia5eeSOW2LK9W/F+895rHw3IbRmn6OobVc5cMw6ORCJ6KTio0WEzDvK3H1bYUve29/YpPmaWWe2DYwpa+pR6hn1KyCzzj46Hle6zjKuNheWxtBcCwbB6ov2Kj7cZnwX7nldizKwj2nsHFQ+NGekDnUeU4TPHpAbDAXkW1hjpQ/GQ3C+aY3fDfW06/LzZl+rzjyvWM6pOy3jLocEXFbSM2/S2tylimRPUOTiq1Lh5fToHhuQqMvd9NBCVzK/R0VBSGV3mPTk6HpTCAc0J2dr1hxUYNM/TwLhbrqh5D7S1jWp43Lz/0r6QCvLKjPTu8XF5d5nvNfR39Sua9ZiRPj4yqKf8gyopNsv2o0N7NG6Ja9tHRzRi6dPs6B/SuKVvtLerS5Zmh/o6u/RsfMxI7+nukfdZMwYfHBxSOmdIhZZ5db7DHRoPmsfQ3juuUZnXtLu7W7Fxszzu6BuQ8sy6usM3ID2zy0jv7ejWXsv8m96BIWWMR1WQb/YdDXQMKTNqzr8Y6O+0zlUbfv5ZJY6aeToa8cqfNsuy/s4u5VnmN3b29EsFZrnb3d2tsfZ25WWbcWpP/mwNusw6sLu7RwFL/HrUJ+t4+XBnjxS2zNPt98ufZZ7Xvt4u7X3eLPs6Ozo1HEwoJ8f8rqGOLmUnzLHgnu4OBUPmfdzTn1TIMm850NUjb8q8bm2DAcW95jN3xBeT5/lD5va9gwrqr8q0nNfg4AElg2ZcO9b1kqKWfoOe3rBitlixt1tKmWX+cG+HdnrMh66zq19ZXrN8GOhq0+HYkDK95n3WPuBXMmiWTYNdRxWzxJADR9oV9Znnr6unXwnLvOVuX0hDeWZc29fVoV2WuVkd3f3KzpAyLLHi4KE2jQfN83FoNKZQ0OwXG+rqVyTXLMs60yElU5b3p3oHlE5a+rT7R5RxsN3cfsCnP3aY95gkDXe8pNCoef5eHE5oxNLPNdJzVHHLfPDe7j65I2Zc0dt+WPsi5j3W2TuoRKblWRwY0l8t/TqJeFJHO/cqYBmDHujolN8yP2FgOCp3xKxje/t7rWNP3V1dSlrOa29Pu7Is/Y2jPUf0pz3mvRSLxRTyD8hniaf6u7sVCFjeO+jqsPaBdvd0SZa89nQOym+ZOzzSfVhHvZY2VU+HFDPHpsPhgJ7TixoeMs/TSz1+jVnGpru7uxWwjDGN9rUrYikfho8ckWfY7Nfp6OiSp9DShh0JKLDPnLsSDPqVPfiSBkvMPqVDgZSGwrZ3qMaVjJnxUU/bkPyWuYHqbNdTlvH19iGf0pbxue7eXhXkmv3mPv+4HosEVTLH8tx19MsXNvdxKCmNRSzzjnqHlGNJHxnpVralzdPR2aeQzLb4SP9RHX7BvGfGx0bkDnZrdpFlPDbQYx9fGIlp2Gu+r9s2OKwRl+Wdg6M9SnTb3yOP51nigZ4eJSx18vDwkOLJbJVY2h6dB47KZ5tTNeqV33K/RvqGlYxZrumoTzGv2dfZ09Olv1r22z4wpuQ+M1bs7+/TYCpHhTLrof3tz2pw0CwHRofaNSdltiPaxg4pK26WD51dPo2FzT6osZ4O7bHMqers7FHEb5YDowNdKoonreO6PR32+my0rVsBv3kPdIaHFUlY3sXq6lEqabm/Ozv1lGXqZkffsCLPPWekd3V1KZHjMtZhkKShA20aHTKv0bAylLL0d/ePHFYybu58tK1Tbr8Zs7cN+hTMNI/5aNeQYh6zjOvuHJEry68cS/x1OJihviKzLGs7/LxGApZGzGi3QpaxkL7uQc2yzF3v6zqqF7y2+c8dysyyvHPQ06Z0Kq5My8S6ro4+pSJmvdLT06lU1IwHQkeflWfInDdzZCSqgGXsqa9nSBkR8xy19Q/La5lzeaRvTKlASB6Pee8fzXpGkaD5rIz1HlTUb5nTfnS/EqNmP0PbsF+W5rM6uvqUdJnxWlt3v/wZZvzV1jWisPdpZVje4Yu092okZhkzajuioM+stzp7hhROmuXl0WG/xj2WMYHhQXk8ljk+I23a85xljKS3XzuGzRhVko6ks63v4bQNxhS29McE2joUD1jmLQwHlI6YZdxQz6gykub9Ot7XoVy35V2L8QN6ot98RuPxhA4F9srvM691x8FRjVv68HyhUQVktvW6+4bll3lfHukZUiDDfPeys6tLHq95b/T29mpHrqUOisY04I6r0/KuZk9fr/yW+QltA6PWOT59g6OKW9qM7QO9Snr3GOldXd3KTpjf39fdo2SeGT+EQwEdHoqrNGrex8FDzynQa/YnHIl65be8s32oK6D+gPnsDvR0KGB5d36ku0e7veb3dPUNKLrHfK8h4PfJlRhXab9ZDvT1dCpiWSehp3tECct92dvTobTlPHV3dSoUtc3165A3wzLXr/+QnnnOfEZHx306FE+oePZc47Ps8Zh8WWY913bwBQVjtjHlNsUt7+f0dQ8ombTktbdbOyzjyW3DYxrba5bfoyPDmhtu16xZ5nH0jXQpaakjjg5ENGxZo6Gvt1NRS33W3jeopGXOYF/XkErcZjssMHRY+/aZcfDwoBm3TgULxAGYkoUty5Wff3zhOJgVVWtjtbFtwt2hyublRvrR6IBOnmV2eEeSMa1uqTfTIzH1DwyottycLLA/HlBzqRkUjKlZZQtXmAeQuU/VC5cayW63S9WLlxnp8ZS0tsKsWGKJhNY01hjpgVBIPel8Vc4rNz/rTKliwSIjPSPrJVXULjHSR/Mjal5kno+hZIcyytcZ6R53UnUta81jiIe0aPFyI31sbFQV2cOaP8c8fztjS5RXauZpkWtIrXXmsWVnZWlJjTlZ6RlXUqvqK430pOclnTbfrDTTvkytXmR+z+Bwtl50L1bJHHPf7twXNb/GPK8F+VlauNB8IT554JDqGhYb6b2pAa2rMINhpdNa0mxeh3hwVOtqLJ07A9LY/GWaM9v8bG5WWo3zzUCo0CMtLjE7C9PJ2Wpobjbz5D2iRYvN9OzIsE4uNzuYk/5xnTzbMvCQ41JB6woVFZt5DZQkVVtba6QPuQa1eL65vQrmaGGTmafMDJeWLzTLh2g6S3MXrzHSw5GYqi33cU7eAS3ru1/FmZZF6GortajcnMg7XNGostpWI93XHlFzg3lsEU+bFjSZ5UYyJc1pPN1ID4XiWltjNihfykhpXuksFVomXBXMnqPGSnOQKzqapQX1TUb6/txsVdaZz2JuZlqti8xjyFJIK5eY6Yr51bLEPDa3J1OtZbnKs+S1xz2uhfPNvO4JV8gz2ywvK0qTamhpMNLzBru0RmbAGi+Yo5Zl5veE0x41t5rPaFZGSq0LPhKZqgAATP9JREFUZivHMjksr7BLdTXmfdYf7NHiUrOs8cyep4YGs3xIHO5TzaLlRnoq7VJ9y0nm9mOjWptrTpBx+dyqbF2iLMvksMxZc1VTU2Okj0cH1TLXzGvW+IiWZJqdB77iBZq3ZJX5/Z6Uliw2z186GVND63Jz+4yoFraskccyOPn04TnKKmk00nN1UJm2OiLrBa0tsyzSFpyjssXmM+RSWiubzTI/knCpvtV8duPRoFYtrrYuGhXNX6j51WZZnc4Oa1GlWe66en1qsNQRue6EVi4wX7wKHAmorMWse0OJDNU1m2XWmC+qktr1Rrok5cz2qqbGfE7Hs4c0p7rFSM/Miaq12ix32+VSau5pRro3Q6pfvNJIz4oOa22l2cESjkRVu9S8lxKJhKL5adVWmtco0ONWZa1ZZiUyDmnuAvO5dsWOau0cszEbHMvRvCVmXhMJqarJPN+j/phqLOc7Eg6p6fA+1cy1vMheuFxzqszYr+DAH7QkYTbssyobtKyxytxHll/VlrwqFtTqRjNGjQd9WrvA7Aj3BUMad4VUNcuMvzIL69VQY+47o3NQDfV1RrorM181Deaz4srwan6DWcdmpkJa1VJhpEfCITUvWW6kj46MKDM2rLIy8xka3L9djZaFsnwLWlTWYJ6nSLJTa8vMMtGVmamVDWb5nUqmtLbGPK8J/7jWzTU7Fvu8ccXn1alsdrHx2aH2Cs2uNMvFedE9WjHH7BLJzslRq2XfQ2mPVG0+cy6l1LjYfHZDoagWLzWfh56ebi2IH9XcQrMT7ED2SpXMN7/LPerRgjqzPJbnBVXWW/aRHVPrYjM+TqeSarKUD8FIStWWZ87beVSrMr0qKTLvV+9QXPWWujczf5Yq68xjCGYOaXmlOdDkzs5VY4tZnqSSSS1rNeMKV2RYp9SaZeJBd1QFVfUqsixm1xMbUuM8M1Z8KRJQS5F5D2Smi7TUcg88M96vVdlmnRzKKVblcrOcSSaimtNgnteU+3mtnXtQBZb46/fdlQplm+ejbNYsFVea+8jJzdGcGrMcKMhMWNtV3sE2rba8ZBmLZmpdVbGRviceULxlrXVwMurtUlmVeV+mBxKqrzPruYFoj1bMNY/5ybEs9QdOMdKrSveodYn57Loifp1WZ+Y1Lzqqxvpa6+Bkd2GZyqvNZyJWnKGaOvM+88eHtWKOZSLgUKmy60810rPcMS1ZYn5PLBbTyuXmfjMVVtnCldYXCQ4fma3yKvO7krOkOkv7zJOZr6p68zwNKqQ1tZZy9PCAapeY5UZGYFSnzTYHxl0jUsnSZdbByXRgnxrnmc9jYW+emsvM5z2RKteCRrN8yPW6tbTeLE9CqRxrOywaS6t5ifk8BMMx1S1eZ13YJm90lxrKzHr5Zz1NCrnMa1RdX6gFTeZ5imQF1No430g/ON6rkbhZvmYXJlRWb5YDwVBItZY6IpVKqbzzGdUssLRtFFCTJa7NLCpRY+0CI911tFcNi8zyRMpQ/WIz9huNZ6p80clGeigY0Jomc4AmFospOz1bVZVmn0/08KgqLf00kbbtanWZA1MZZfVavNS8jxM5nWqy1LHJRErNSy3tBf+I1haYg6WBcIbac9dodlmN8VlpSZ7mVZl5DfZKtXWW9kKmW4sWmWVfZiqqVZY+olHXkHIa3mqkjwUSWls7ZkkP6oVZq1VWbsZs3qMHtaDWbPN4swqt/QkZmftVVW+22wbl16oa8xkNe/tU02q2e0cjKTW1mv0JI8ODGg14NavUzGt2ScraRu/xpNVSZYktc10qqjHrguKRQzrJYw7IpqJZ1n6uuN+rVU1m3Nw7MKQ96ZOUV2j2cTTOluos9dZosFets806JXE0W3WDZp6ii9aqevFqIz1rvFdrc8xJ5LFAjtaWWwa63XG5Wlo0Z1ax8dlAV4HKLfdrXvygWi0xsnckoaW15vVxebPU0mI+c2HPUWubxxdMKl1qXh93zmGtqZV1MeHD6ZAWVZj1UOGhdi2ebeY16KpXhWUcoSszrtZFNea+g2NaW2iWTdG0S8tXmOVr7pE2VRZlqyjfjGn8Q7NVscCse5Xs0BLLNcrzlanV8mLm2P4hFT3TZqSPrGnWqQvNfoZUNKB6S1vcnZmn0nl1yrNMZPO7B1RaaT7vc11HtbTCfK4zhhNqqq8x0hOZI6q01HNSWvMtdYGCY1pXaZbfe2NjqlvYoFxL/FXc1a+G+eZx5xaGtGiBeV8Oer0qrDbb+574Qa2dY1lQpyBT85eaeY3HE1rZbO5XyaRWVBQp2/KHi1KhfNVa+uoG0gG1zDfv4/xkVK2zzDKoL1Anb+2ZRnr2wBGtilgWRE4XKLfRfLaCMbcWrq6S19JXl9V2RAsseVVOtyprzfKhK8+j2oXmPTOY6NNJ5eZ1G8+W8i3xVzIc1upGyyJtqZSWN9VaF4gryclQfbUZJ3QooqayYiM9FCpVxUKzfh+LHVJWmRlPFcf7tLbGLAfCWSOqs/RxBIJRlVvGHSSpNOegFs43x56SJblaYGkvJLLbNN8yppeT5VFTkxknZCup5Q1mDBmVR01LzTGVeGBEqxeak1QSiYTmjARVZxlf8JaUWcdzijMSWlJhxsGe9n4trzGPWRletVr6+PsDWRqYZV6H7MFhLRk2X4yLJBIq2vBPmm+JFX2ZPpVXm8ft9uSrsGK5kV6UM6IVCy3jP5kB5Vhi7Zz4sNY0mOV0OBDQcstkfl8ipsSCuaoqNc9TTlml9T5O94yrtt6MFY96E1piadv44nlyzTf7lDKjIzqp0byPI0mpabkZ942NjemZgXLNKjXvp3kv3a+mDLNN11m9VEW15nkqTLbrlDKz7eTJnKvGJWYMnk7EtarZPOZ4YEynVZt1UP9wSsoo1rxiywvURa1aUGvGbJkFR1RXZ+kDzTmkhY2WvmjlaMEisw80lsxQTYsZ03gSozq51vKHlAbc6ipbphLLRLaEq0+LLM/cSH+hyi3jj7PyM1TXYJbHbb0ZavMvN9Jnz0po5Sozry+4A6pfZsbgmZ3tap0d1WzLQrzDqcWqWGCWQe7I82otscS1iTmqt/QfHokP6KQyM15LZOap2TL+mBEd0wpLuVGYm63qYIZmWeKvgmiWGqvM85oczVDtQkt/YGaR5tYsN/OkZzWr2mzDhLxDWldr9mNEQxHNW2z266Sz92tpWcr6IsFQftoag+ePP6llxWb9500XaWmd5diyIlpgad9mZKQ1r8HMUyIU1NpKc1JkbjquiuZm5Vv+8JdnIGRth0WzQipbYNZbqZwhLV9gtmNfDMU04DXrzDl5AbUuNcvEsUiGcurMMi4Yz9HqBYXWvjrPuEs1C8y+jIIDz6up2uzTzM3OUnOduX1OhrTUMubvdrnUuMwy9hQOaW2+Gde6Qz4taW1SluWPaRX3j1rH9ou8bjVZ+r/ikRJVN5rnu3ukTWuzzGuazCvW8qYaIz0VDVvL3WQsqjkta6x9dfHciOos9VbX4GG1FJnHtj+5RN4KM/bLyMhSaZ3ZvvW4XWqy9CumkgmVW2LI4WBaS5cts47rumIvqHG+ZS7FrFlauMAcJ3shN0sNdTVGev54n9bkmO2FcFGxapeZz5w3GVCrZdzBH02o3jJ3RZJmF+ZYY/DOsF8F5ea1Li/xq3WhWVfvy85WQ6NZniQyDqiu2fyel9zjWrbU3G8wENDabPOlgFhCypzfpOpq2xhnlcqrzbp0zH1QhfPMa5rXP6q1i8x68dlEQKtrzechlNmnWsvYUygU1TrLMYRCIY1lz1WJpa+utqBTTdXmPgqSYbXOMcu+8OxyzbfsO+F6XvPqLdc0mdC8BrMdNhaIaZ7lPg74xrQkt1uVlljxQLZXTZa5KGNarLn1y430/Jw/a1mDeX2irjzNW2TWZ5mJgE6uN+fGxIM+LV5iXs+RkRElt4ZVZvmDEblFeaq3vODeUVelxZb7NZGXVGWjGYt4PDu1wlJmKRVXo6UdFgpH1GTpaxoaHFD1nJh1XLd/uFJlVebx5eQ9r/IF5nM9cFSqbTCfobyMuJa2mHVEMHVExQ1mPedOh9SyzCwfenp6VJyR0OwSs03Snxy193+ND2hxvnkdXFmZWugzXzKPN6xWreU8eUd7dFLK0v+VSGidpa+prTuh3jkrVVhs5jWd79fCavNaewrnqK7ebHt0p4aUXWY5T4NRtS416yeXK61Fi83r4I6Pa1WTWTcdyspQxvzFKiy0/DHdvGJV15j7iAy9pCX5ZhsmN5ap1nKzDe3yZ2jxIvOZy4yM6WTLmHUsHNHyxea9l5vpUUvEpYJc83n0eOarzlJvxbIrNK/GEn8lurV6nln/xfNkHbvLCY1q7WzzXoq7PVrVaJ7X3HRUwQUnW8d1K2fJOk/p2ZzZmrfAPO7SrJiWLTDv7+dS41plOX8ZqbhWNJnfH44nVdtqtkmj7hytKo9b++pKjhxVw3xzH5GihaqoM/u1s/N3qbHBvI87kz6trjD7d2Md42qwtHtDkaSKGsz+xlhSqmxqldfy0mlWfkj1ljk+3a6AmirMWDs6kqVqW5mVldYiy7zbI6khnVJtHkMyHNTyFvM5SUcCWttQbu2rm53tUX2V2ReU33FATZYFqNM1DWqwzD9057RbY5qXvFEta7a058I+rbaUWeFwRCc111vHdV8oaFBppbmP7DkZ1nGyjOwiVdRY5ppmebRwkZkul1vNtncFEim1LDPb+uFIQN5Ky7yPVErRsVLNrTTb4jl5BSqzzAFMFiWs92t3z0GtjJtjSRl5s7S6ynwegjGpoNFsh435Ylq21CzvI5GIRvt7tMDSB1qY36+FC8zfCWemNbt6uZEuV5fWVFrmuo8Oa7mlHzyVnaGT8s13MELZLlWtNJ+HUCCgkfF5mldhKV/dQ2qyjDPmZ6S1pNJ85tz5xWq0jJd73dJqSxkX9+ZoZav5LIYSCa2tN8c1xnwBZXqaNLfMPH/x/DE1VJnt27zcLDVaxiUPJ/1aUWXGnN7eEi23xHfyzFOVZb5BJBrRAsvcytHhAa3wPaZ5Rea1y5pbp4Yas145nI5oyXwzT7mZHrXOLzbSd6fmaZVl3m0yp0CrbOfV5dayVvMe6BsYVG5kTHNLzH3M8qS0aK5ZLmbMnaWFloX0RuJzlFFqPr+zUu06Zb7ZlnR3DOkkyzMXCwVUudzS1u/uVMvomEot8+r25CxXcYVZBpWWJ1RvmQeaPnhQtQvN8+Rye9XQbF5rb9SvtQvMNlIsFLT21R1tz1ZO6XwVFZnHN+IaVYNlLopnVpkaLHNR8hXXilLLvRSerdWzLH/9aCSuNZZ5eOnAmNZZ0l9URN6WpSossIzTFhxVnaWNfqjNa51T1dP1nJZZFjANly9RheWdgKzgiNaVWubHRMNaYokfsjwZWnDgr8pLm/0uRSefbo3BC71uLZ5nPlsxf47qmsz7rCMZ1Jr55rmIZI6rdqllvmIspCWW+TQut0elC5Yqx/KH0GYXelVjOX8DOQEtssQPofykyuqWG+mjmeNaUW+26RMZWWqxvBMQUYZOLjPjFnckpLHmk5Vp+cOrGXNk7acZzAqqqdosq+N5Uc23zK/NysxU1UIz/ZA3paom896IRBNavsSsw1OxkE6vLpDX0leXXTLXOgbdk5VUg2W8/GjCp6WW90ieiYa1stCMmUYL5iq/yYxfk8mE6lvMNn0gnNLypQusfXVDqXE1WPpA3WNu6zzQzs59avWa7yN4c0u1rNasCzJcbrW0mvdrLJXWSktc6w9GNX/ZBiNdkhZk2MusUMkc6zuFc7JSaq41n8Ucr1uLG8wy7vnEqE6uNp/ReCqlhUuXG+nhYEir681nNJFIqNifUF2lea0PedNqsoyReHt8WlRn1sl7czOsMXiG222d+5OORXRKs3nMMf+I8i1z2GKRiKrjz2v+fDP+KsrP04Ias94qznSpyTImmpspNTea9VAwkaeCWvN+zZVfJzcVG+nhQEDBGst7OwGfludEre/rhvKSml9jmT+X9ZLm15rnaSjXpUWNZizfFRjQunxzzDXty9NJlnlkgWhCcy1jT+NjI6pzd2q+7T3R6npruevJP6q6etv561HOPDPGy44c0NoCs68pqSKtajTv73AkpirLXPehwX71+IpVPMeMX6tGn1LzHLPu8Oe0WOd3jMePKLvM7JdNDCS1YLG571BypxqXmv1i0WjY+s7QYH+3VgcGNLfY7AvKCueofoH5DD2bX6A6y9h+/ECbaizvl+cMdWh1zJxXkMgs0hLL2GokGle9pW+0u7NdiysTmm35AwlF3UNqtJRl/tHZmmeZixJRr1ZZ+pQSvREtsvTVPZsMakWzeQ+EEmmtsPR/Hc3LUe6cSmtf3a5IQN45ZpxaW5ynudXm+cvtHdHKhWYZ53cFrOVAnjuglS3muRjypdSWbZkXFnheS5ZIBZZYsTAv2xorDoX6tLjU7C9LxEtUZ+mPyfB4Vde03EjPDfXp5CJzAZ5ILKk6S9+e25OpdMlJyrYs0Ft25FdqyLX8EdzKFs2ts9TjXQk1Wsqs3tio1lrmf0Uzi1S9xHwWfVGX5jW9xUgPJvO0Zm6vcix/eNVduUi1Neb91P5sQoXzLM/QeEJNjWbdEfMcVFWDeWxZnrgabeM8iYSWLjHLmXQypcampdZ3MLy5Haqy9C0X5ueoyjKvLhw5pFWl5vck8stUtdQ2bhPUSeVm3JeIhrS2sthIT/pHtSrXbf1jDoH6JapcYMaXvvy4FlrKso7okJZZ3sNR3iwtspwnub1aYVkPIZj0aHbTGUb6UNCthYvXWvvqXLl+a/lako6o2dK2ycnO0ZJqS/9Af1SNzWa7ypfVoVl15vluywyr2dIOC475tCZmLrglSQVl1aqvMuMvlbhVbelXHIl2a3mZ+Yx6snO0fIE51uJyudVkKXczUmEtX27e9974sFqXm89uLBaTa9Sjyirz2TowOKTs2WbsUpcd1OIG8zq4Dx3RogYzfohkHlJdi+1d4aQWW8qsiG9MawvHjPRQJKbDpc2qrDDjhFkHnrPOpcgsLNYiS3/C/nRMK6osY1i5/VppO7Z4WCdb+g1igXE1tJr1mc/n05GRZSotN7+rbmSfmgvNPkp3Ub3qLWsMDLvGlTff0icsj8rrLeNnqahaWs17bDyc1PxGM1YcGx3SLM+QSueace2s/CxruevK7lN1vVlv5eVkqMYy7pB2Z2r2Ast8cKW0ypJXhUe0ptG8nr2DQ/Il16lotpnXutQeNc8rNtIT8TItWGiWu+2ZaTXXm8eWzshWfYtZpxwK9mptoTnPJhCTCposc116O7U6GFSpJVb0l9VZ59UNFUn1llgx77m/aHmVef95vF61NtQY6XGXV3UrzDLLlfBbx8t7usx4cyrMmgUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMC1YIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZggWiAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAGYIF4gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABghmCBOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACYIVggDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmCBaIAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAZggXiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCGYIE4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJghWCAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGYIFogDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgBmCBeLwurVp0yZdeOGFk26zfv16XXvttSckPzY1NTW69dZbp23/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeH1hgbg3MacF1rZt2yaXy6WxsbETnqeZYNOmTTrzzDMnfp7uReb+Xm1tbXK5XNqzZ890ZwUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACvgAXigP/mwIEDOuuss6Y7G/8jYrHYdGcBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU8ACcXhVHn/8cZ1++unKyclRVVWVrrnmGgWDwUl/5ze/+Y3WrFmj7OxszZkzRxdddNHEZ6Ojo7rssss0a9Ys5ebm6pxzztHBgwcnPt+yZYuWL19+3PfdeuutqqmpcdxfMBjUZZddpvz8fM2bN09f//rXjW1qamp0880360Mf+pAKCgpUXV2t733vexOfj42NqaOjQ9dcc40kadOmTdq+fbu++c1vyuVyyeVyqa2tzbr/gYEBnX/++crJyVFtba1+8pOfGNuMjY3piiuuUGlpqQoLC/XWt75Ve/funfh87969OvPMM1VQUKDCwkKtWrVKu3btmvj8la5DTU2NvvjFL+qyyy5TYWGhPvrRj6q2tlaStGLFCrlcLq1fv97xHAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGB6sUAcXtHhw4d19tln613vepeeffZZ3XPPPXr88cd19dVXO/7Ob3/7W1100UU699xz9cwzz2jr1q066aSTJj7ftGmTdu3apQceeEBPPvmk0um0zj33XMXj8deczxtuuEHbt2/X/fffrz/84Q/atm2bnn76aWO7r3/961q9erWeeeYZffzjH9fHPvYx7d+/X5JUXFysrq4u5ebmSpK++c1vat26dfrIRz6i3t5e9fb2qqqqyrr/TZs2qbOzU3/605/0q1/9St/+9rc1MDBw3Dbvfve7NTAwoIceeki7d+/WypUr9ba3vU0jIyOSpI0bN6qyslJPPfWUdu/erRtvvFFer1fSq78O/+f//B8tW7ZMzzzzjD772c9q586dkqQ//vGP6u3t1a9//evXfI4BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwj+WZ7gxgej344IPKz88/Li2ZTB738y233KKNGzfq2muvlSQ1NDTotttu0xlnnKE77rhD2dnZxvd++ctf1nvf+159/vOfn0hbtmyZJOngwYN64IEH9MQTT+iUU06RJP3kJz9RVVWV7rvvPr373e+e8nEEAgH94Ac/0I9//GO97W1vkyTdfffdqqysNLY999xz9fGPf1yS9OlPf1rf+MY39Kc//UmLFi0yti0qKlJmZqZyc3NVXl7uuP8DBw7ooYce0s6dO7VmzRpJ0g9+8AM1NzdPbPP4449r586dGhgYUFZWlqRji7ndd999+tWvfqWPfvSj6ujo0A033KCmpiZJx871y17tdXjrW9+qT33qUxO/l5GRIUmaPXv2pMcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACA6ccCcW9yZ555pu64447j0nbs2KH3v//9Ez/v3btXzz77rH7yk59MpKXTaaVSKR09evS4RdBetmfPHn3kIx+x7vPFF1+Ux+PR2rVrJ9Jmz56tRYsW6cUXX3xNx3H48GHFYrHjvrOkpMS66Ftra+vE/10ul8rLyzUwMPCa9vuyl49p1apVE2lNTU0qLi6e+Hnv3r0KBAKaPXv2cb8bDod1+PBhSdL111+vK664Qj/60Y+0YcMGvfvd71Z9ff3E77+a67B69eq/61gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwfVgg7k0uLy9PCxcuPC6tq6vruJ8DgYD++Z//Wddcc43x+9XV1dbvzcnJ+bvy5Xa7lU6nj0uLx+N/13e+zOv1Hvezy+VSKpX6H/nuyQQCAc2bN0/btm0zPnt5IbktW7bofe97n37729/qoYce0k033aSf//znuuiii171dcjLy/tHHQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+wVggDq9o5cqVeuGFF4yF5CbT2tqqrVu36oMf/KDxWXNzsxKJhHbs2KFTTjlFkjQ8PKz9+/erpaVFklRaWqq+vj6l02m5XC5J0p49exz3V19fL6/Xqx07dkwsljY6OqoDBw7ojDPOeNX5tsnMzFQymZx0m6amJiUSCe3evVtr1qyRJO3fv19jY2MT26xcuVJ9fX3yeDyqqalx/K7GxkY1Njbquuuu06WXXqo777xTF1100Wu6Di/nX9IrHgMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACmn3u6M4CZ79Of/rT+8pe/6Oqrr9aePXt08OBB3X///br66qsdf+emm27Sz372M91000168cUXtW/fPv3bv/2bJKmhoUEXXHCBPvKRj+jxxx/X3r179f73v1/z58/XBRdcIElav369BgcH9dWvflWHDx/W7bffroceeshxf/n5+frwhz+sG264QY8++qiee+45bdq0SW7333+L19TUaMeOHWpra9PQ0JBSqZSxzaJFi3T22Wfrn//5n7Vjxw7t3r1bV1xxhXJycia22bBhg9atW6cLL7xQf/jDH9TW1qa//OUv+td//Vft2rVL4XBYV199tbZt26b29nY98cQTeuqpp9Tc3CzptV0HSZo7d65ycnL08MMPq7+/X+Pj43/3OQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMA/BgvE4RW1trZq+/btOnDggE4//XStWLFCn/vc51RRUeH4O+vXr9cvf/lLPfDAA1q+fLne+ta3aufOnROf33nnnVq1apXe+c53at26dUqn0/rd734nr9crSWpubta3v/1t3X777Vq2bJl27typzZs3T5rPr33tazr99NN1/vnna8OGDTrttNO0atWqv/v4N2/erIyMDLW0tKi0tFQdHR3W7e68805VVFTojDPO0MUXX6yPfvSjmjt37sTnLpdLv/vd7/SWt7xFH/zgB9XY2Kj3vve9am9vV1lZmTIyMjQ8PKzLLrtMjY2NuuSSS3TOOefo85//vKTXdh0kyePx6LbbbtN3v/tdVVRUTCzCBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgJnHM90ZwPS56667rOnr169XOp0+Lm3NmjX6wx/+MKXvv/jii3XxxRdbP5s1a5Z++MMfTvr7V155pa688srj0v7X//pfE///7/nPz8/Xj370I/3oRz+aSLvhhhuO26atrc3Yz549eybNR2Njo5588slJt5Gk8vJyPfjgg8elfeADHzju54KCAt1222267bbbrN/xs5/9bNJ9vNJ1sB2fJF1xxRW64oorJv1uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATD/3dGcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAMC8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAzhme4MAJiZotGootHoxM8+n28acwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPDm4J7uDACYmW655RYVFRVN/KuqqpruLAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALzhsUDcf+NyuXTfffc5fr5t2za5XC6NjY2dsDy9Hm3ZskXLly+f7my87mzatEkXXnjhdGdDkvSZz3xG4+PjE/86OzunO0sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABveCwQN0WnnHKKent7VVRUNN1ZsbrrrrtUXFz8P/JdNTU1uvXWW19xu1daVA/T67XeE1lZWSosLDzuHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP6xWCBuijIzM1VeXi6XyzXdWcEMFYvFpjsLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeJ1igTiLoaEhXXTRRcrNzVVDQ4MeeOCBic+2bdsml8ulsbExSVJ7e7vOP/98zZo1S3l5eVq8eLF+97vfOX53TU2NvvjFL+rSSy9VXl6e5s+fr9tvv/24bTo6OnTBBRcoPz9fhYWFuuSSS9Tf3z/x+d69e3XmmWeqoKBAhYWFWrVqlXbt2qVt27bpgx/8oMbHx+VyueRyubRlyxZrPg4fPqwLLrhAZWVlys/P15o1a/THP/5x4vP169ervb1d11133cR3OR2PJF100UVyuVwTP7/sRz/6kWpqalRUVKT3vve98vv9E5+lUindcsstqq2tVU5OjpYtW6Zf/epXjufuf+L8jY+PKyMjQ7t27ZrIQ0lJiU4++eSJ3//xj3+sqqqqiZ87Ozt1ySWXqLi4WCUlJbrgggvU1tY28fmmTZt04YUX6stf/rIqKiq0aNEia963bNmi5cuX67vf/a6qqqqUm5urSy65ROPj447H+/DDD+u0005TcXGxZs+erXe+8506fPjwxOdtbW1yuVz69a9/rTPPPFO5ublatmyZnnzySUma0j0BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACA6ccCcRaf//zndckll+jZZ5/Vueeeq40bN2pkZMS67VVXXaVoNKrHHntM+/bt07/9278pPz9/0u//2te+pmXLlumZZ57RjTfeqE9+8pN65JFHJB1bsOyCCy7QyMiItm/frkceeURHjhzRe97znonf37hxoyorK/XUU09p9+7duvHGG+X1enXKKafo1ltvVWFhoXp7e9Xb26vNmzdb8xAIBHTuuedq69ateuaZZ3T22Wfr/PPPV0dHhyTp17/+tSorK/WFL3xh4rtsnnrqKUnSnXfeqd7e3omfpWOL0N1333168MEH9eCDD2r79u36yle+MvH5Lbfcoh/+8If6zne+o+eff17XXXed3v/+92v79u3/sPNXVFSk5cuXa9u2bZKkffv2yeVy6ZlnnlEgEJAkbd++XWeccYYkKR6P66yzzlJBQYH+/Oc/64knnlB+fr7OPvtsxWKxiTxt3bpV+/fv1yOPPKIHH3zQMe+HDh3SL37xC/3mN7/Rww8/rGeeeUYf//jHHbcPBoO6/vrrtWvXLm3dulVut1sXXXSRUqnUcdv967/+qzZv3qw9e/aosbFRl156qRKJxJTuCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEw/z3RnYCbatGmTLr30UknSzTffrNtuu007d+7U2WefbWzb0dGhd73rXVq6dKkkqa6u7hW//9RTT9WNN94oSWpsbNQTTzyhb3zjG3r729+urVu3at++fTp69KiqqqokST/84Q+1ePFiPfXUU1qzZo06Ojp0ww03qKmpSZLU0NAw8d1FRUVyuVwqLy+fNA/Lli3TsmXLJn7+4he/qHvvvVcPPPCArr76apWUlCgjI0MFBQWTfldpaakkqbi42NgulUrprrvuUkFBgSTpAx/4gLZu3aovf/nLikajuvnmm/XHP/5R69atmzh3jz/+uL773e9OLND2jzh/69ev17Zt27R582Zt27ZNb3/72/XSSy/p8ccf19lnn61t27bpX/7lXyRJ99xzj1KplP7zP/9TLpdL0rHF8IqLi7Vt2za94x3vkCTl5eXpP//zP5WZmTnpeY9EIvrhD3+o+fPnS5K+9a1v6bzzztPXv/5163l+17veddzP//f//l+VlpbqhRde0JIlSybSN2/erPPOO0/SsQUOFy9erEOHDqmpqelV3xMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACYfu7pzsBM1NraOvH/vLw8FRYWamBgwLrtNddcoy996Us69dRTddNNN+nZZ599xe9/eUG0//rziy++KEl68cUXVVVVNbG4mSS1tLSouLh4Ypvrr79eV1xxhTZs2KCvfOUrOnz48JSPMRAIaPPmzWpublZxcbHy8/P14osvqqOjY8rf5aSmpmZicThJmjdv3sR5PHTokEKhkN7+9rcrPz9/4t8Pf/jDVzyev/f8nXHGGXr88ceVTCa1fft2rV+/fmLRuJ6eHh06dEjr16+XJO3du1eHDh1SQUHBRB5LSkoUiUSOy+fSpUtfcXE4Saqurp5YHO7lvKdSKe3fv9+6/cGDB3XppZeqrq5OhYWFqqmpkSTjOv3Xe3bevHmS5HjPAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYOZigTgLr9d73M8ul0upVMq67RVXXKEjR47oAx/4gPbt26fVq1frW9/61j80f1u2bNHzzz+v8847T48++qhaWlp07733Tuk7Nm/erHvvvVc333yz/vznP2vPnj1aunSpYrHY/1g+JzuPgUBAkvTb3/5We/bsmfj3wgsv6Fe/+tX/WB5s3vKWt8jv9+vpp5/WY489dtwCcdu3b1dFRYUaGhom8rlq1arj8rhnzx4dOHBA73vf+ya+My8v7x+S1/PPP18jIyP6/ve/rx07dmjHjh2SZFyn/3quXS6XJDneswAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJi5PNOdgTeCqqoqXXnllbryyiv1mc98Rt///vf1iU98wnH7v/71r8bPzc3NkqTm5mZ1dnaqs7NTVVVVkqQXXnhBY2NjamlpmfidxsZGNTY26rrrrtOll16qO++8UxdddJEyMzOVTCZfMc9PPPGENm3apIsuukjSsYXQ2trajtvm1X6X1+t9Vdv9Vy0tLcrKylJHR4fOOOOMKf3u33v+iouL1draqv/4j/+Q1+tVU1OT5s6dq/e85z168MEHj8vPypUrdc8992ju3LkqLCycUj5tOjo61NPTo4qKiom8u91uLVq0yNh2eHhY+/fv1/e//32dfvrpkqTHH398yvt8tdcRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA08893Rl4vbv22mv1+9//XkePHtXTTz+tP/3pTxOLlTl54okn9NWvflUHDhzQ7bffrl/+8pf65Cc/KUnasGGDli5dqo0bN+rpp5/Wzp07ddlll+mMM87Q6tWrFQ6HdfXVV2vbtm1qb2/XE088oaeeempinzU1NQoEAtq6dauGhoYUCoWseWhoaNCvf/1r7dmzR3v37tX73vc+pVKp47apqanRY489pu7ubg0NDTkeT01NjbZu3aq+vj6Njo6+qvNWUFCgzZs367rrrtPdd9+tw4cP6+mnn9a3vvUt3X333f+w8/ey9evX6yc/+cnEYnAlJSVqbm7WPffcc9wCcRs3btScOXN0wQUX6M9//rOOHj2qbdu26ZprrlFXV9erOtb/Kjs7W5dffrn27t2rP//5z7rmmmt0ySWXqLy83Nh21qxZmj17tr73ve/p0KFDevTRR3X99ddPeZ9O98RnPvMZXXbZZVP+PgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPzjsEDc3ymZTOqqq65Sc3Ozzj77bDU2Nurb3/72pL/zqU99Srt27dKKFSv0pS99Sf/+7/+us846S5Lkcrl0//33a9asWXrLW96iDRs2qK6uTvfcc48kKSMjQ8PDw7rsssvU2NioSy65ROecc44+//nPS5JOOeUUXXnllXrPe96j0tJSffWrX7Xm4d///d81a9YsnXLKKTr//PN11llnaeXKlcdt84UvfEFtbW2qr69XaWmp4/F8/etf1yOPPKKqqiqtWLHiVZ+7L37xi/rsZz+rW265ZeL8/fa3v1Vtbe0/7Py97IwzzlAymdT69esn0tavX2+k5ebm6rHHHlN1dbUuvvhiNTc368Mf/rAikYgKCwtf9bG+bOHChbr44ot17rnn6h3veIdaW1sd7xe3262f//zn2r17t5YsWaLrrrtOX/va16a8T6d7ore3Vx0dHVP+PgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPzjeKY7AzNNOp020sbGxib+v379+uO2+da3vjXlfRQWFuoXv/iF4+fV1dW6//77rZ9lZmbqZz/72aTff8cdd+iOO+6YdJuamho9+uijx6VdddVVx/188skna+/evZN+jySdf/75Ov/8849L27Jli7Zs2XJc2rXXXqtrr7124meXy6VPfvKT+uQnP/mK+/iv/p7z97ILL7zQuNa33nqrbr31VmPb8vJy3X333Y7fddddd026r//uYx/7mD72sY+9qu/asGGDXnjhhePS/mu+a2pqjOMoLi420mz3xFTzDQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgH8893RnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwDAvEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAM4ZnuDLzZtLW1TXcWXtdez+dvy5Yt2rJly3RnAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOYe7ozAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4hgXiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCGYIE4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJghWCAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGYIFogDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgBmCBeIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYIZggTgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmCFYIA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZggWiAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAGYIF4gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABghmCBOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACYITzTnQEArw/pdFqSFAz4jc9CoZD8gYA1PRDwmenhkHxZYSM9GInKFwwZ6dFITIFQ2PpZIByRL2QWZSEFFbTtO+ScHnA4Nl8wbeY1HLHmJxgKKZB2289HMGU/H5Pkye838xQOBZURNLePhIMKWb4nErYfWzAQkD8Uli+YafmdgDJC5ncFXfZrHQyF5AsELelhe3o4LF8wy5IesW4fCIYUcvuVlZ1rfBYKBeznLxhUwHL+QiF7ejAUki+YtObVej3DDvdkKKxAIKisTPO8BhzOx7H72HKfJZ2fLdu9EQqF5QvGLccQkS9kHlsgElUw6JfH4zV/J2i//45dU9u9n5Dfb783nI7Bdt3CDvdxOBSQPxpXhttlHkc4Il/QLFNC8cmeLVuegtZnNOzwjIbDIcdyyR8y8yNJgVDEfv6CCef7dUrHMEl57PD9/kBaqXTKklf7tY6EA/JYyoeQy+HZCkfkU9RMT0emmNeQ/IEsJRIJ87uC9uM+VndkmNvHHMrpSc6TY32miPn9kaj8gYBilnLA6dlyzGskKl/SfK5DmQ51rEMZ51Qnv3x/e7xmORCLBJQRNn/HLYc6IhyWL2iuP+0YD0zxfg3/bXu327KPYNq6DznWT1Orz17p/Bnp4ZC1LJOklGP9ZK/P4qGQfIFsy75dSlnigZhTXBEOyRc079dQOGLNTyKZUNTpfATdDtfUfgyucNhax4ZCaWuMMtl5taVHIyHHuiAcCVivhTsSlT8ZM9KdYpHJyibr9g758YfCCoSj8mVZ6l5PSH7b/epQxjnHr071n9P3hO3ldyCgWDyoXFv5GonK5zbLLKd9R0Jh+YKW8tsprnCKtSMR+Sx1rD8cUSIYUo7lvIZD9nsgGA5b2xHBkNu671DII1meubDDdQg7xGvBYFD+cFTZHvP8hVMBhSz7cAed4wHHto1TXeBQvtrj6YD88ZA8GWa5GwwmHNo8TnkNyRewne/J4l37/Wq7ZwKhsFzBoNy2WHGytqTXkqd0pv3+C0fkS1vq5EjE8R5wjGuDIaXN8F/RSEAuS90bTtvvjZhDuRtzqufCEfkilrgsGrOWWcFwRPGAX8mUWYaHHfadnqwdYRZxikSSikfN7SORycpdSxkaDssfDCluiRWd8hp3qJOP5dVWb4WUcogHpvLMHWsL+eXNtJdZtrwmJ2vf2tr7k8U0Tuc12x7XZgb88mSYz0raoa47Vidb4uC0Q7k41Tajw/l+uSxzucxyIB221x+xaFCxjFcfi0Qd8hoOhxSNW56HSFBhy7MbjdivWyqVUigYdG7bOPS7OMW19n6DqdUFkXBIvqAZM8ViMQXT2fay2qEuiEai8rksZVAobI+BHOsCh/s4HJIvw3IfhyMKy28tR+OvoU/J6T62xeyhcEjpKfQn+ENhBTMD9n075SnoHBNOpU52igmd4wS/QkGvsnLsZZZTH5G9bHLJayunw2H5PJZ7JhKVL2Qvs5z6FaNhvzI8OebvZNvP67G+OrOvJBiNyR+zxAPhsEO/QVi+tENeLccQCEflCoaUaWmjh0Iue93rUMcGQ4kptYePtXst90A4pLS1L9ovfzCkDEsbffK+fDOvIZd9345tmHBYPo+lPReJOpcnnpTMGkIKBbMc+hMc+mnCEfnc5r0RisflscRMoVjMoc1of+aOxfh+pWUGi45tm1BYvqAlPgolrOfD8VpP2gdqjxX9wZASSUu/s8M94FwOeOWx7NsTDssXMsuBUDjpPJ7jVF8GvYrZ+hVDrin1gwfCEfmyLNc6HLKWZZFwWL6oeb+GIlGHOuJYue516LN3rgte/biXc7wruZzugYD9efAHgsrIsHwWsvdxBBzGpEIO41jhUNDa/xV3iFGcni2n+kyScpz6JoLpSZ7TqbXFnfpjrPFaOCxf0KyrE4mEc0wY1CT3sWUsznGcxx6XhcMhRbLsfXL+qFkvRpIJx35wp/7DcCggj+Vae0Mh6zGEQpPFWZZyOhKV3/Is+qMxJUP2tk0wJoe+OueY0NpeCAXlsvUpOdzHwXDEGksFAgGFQ35l2eqCSEw+y5+GDIeC1rIpIxSWL2jWjMGQnPtppjBW6g+FpXBEeZmWfhePw/lzvGcmaw9PdUzPPhYWDAaUmWXGigmHZy4UyphSORAJBxWLWJ4hj0Nendo8waD8obC8lnI3lJqkb94W1yac2uhh+9wIh7ZnaLL2XChijxWjKYdy1+14Dzj1D9ieh2P1lqXN4xSzh4IKBMxzdOyztMN5jciXaan/0pkO90x0SnXKpGPQwZBSKcs1DTpdI3sdmHIaewrHFE1YYpqoczvCVh5HwoG/9dVZ5l8EXVOcc+I8pjfluRRu53lKWXEz/nJs2zjF4NFsh/HysHxJW59F2iFmd37mggG/MizjCwmn8fJwRD6vpX83FVTC1tZzaHc4lq9O40J/i+9s47oup/ZCOGm/1g7HdqzP3tJvEHdqbznXZ7ZY9Ni+nfoi7bHLpPer4xj+FNvDKfNeik3EX7b7Zmrxl8vxGOwx5GR9SvbYKKxwyN5X51QOOPYnxJzOn/P96jSvzqn/69jzbsajx/JkqZMd5ytOrR/8WPvW1vZ0ihWDSsbiyrXEhEGXW35Ln4XTnL5QyLnNPdX5HdYyMXhsvmJOtqVt6NRf65ju3AfqlFdbfBwOO8eonoyEMp3mADqOP1rihMn6FZ3ahimHvlGH9nYw6FeGxzKe41SOOsTg4VDQ2h/oeg3jYU6xojsQkNtlm/vjFFNH5MuwjAPHUvKFbP1iGQ77dqjDw/Y5bMFQSP5IxNpXF8xwus9iDvGXUz+uHM5fWL5sS1+Ww5yWYCisUNCvlOV5Tzq1t4L2Z8tprlDQsc/PqTyx17GhUFD+YEKxuPlMOD1bjs/7JG10a/+uU3+MQ/nwch3h9ZrlgGP85XieJpkf6jR+azmGkNN85r9dB1tfneO85UhUPpetDTjVWNu5/8saP/xtTpBtXDccss+NcJ5vN9V3AiabW2kfI7HFzalUSlHH2Nn+bDkdQzAckS9hKfPd9rlToXBYboe2pO06RCJRBYLOZbL92knZTnMxLf0rwUhUvoilnyuali9s6eOP2NvJ4WBAoWDAei1iUy6b7POaJn2vwWE8x5buD4YU8gSsZVNikjrQMU+2dyoczmvI4zxPySmu9Uei9r46x7w65MmxPTdJusN5tY4hBENKRsPKzrLEXw5zVILJLMd+Wdv7NlmT9Mvanzn7/NqX49osSxs9EgpY54qEYpOM80xhTpDT+00hp5gmGFIyxz732nkuSnSS+9Xh3aosS/kQjjvPw7P2uUTkDQTksozsOrV7HfvswxHrHJWQxylGCTm+h+MYK8biSlnmAAac2reOz1Z6SjGNU1t8sro6GPAraRnXnWzMw6nN6NzutY9NO48v2McfQwGf4pnmecpwnOvntO/olObdOvd/Oc9f8gUzrH32x/q7X32f5rF7wzJPNxyRz2M+D6Fw2D6u6zh24vwOhmP8GrS/b+MYu7gc3pOa4viCU1++JHmc2gsO4+VT7Vt2rP/Czu0I2318bFzXPmfHudydrF9xqrG5/bzaYshYNCLFHZ6tSZ+5qfTZB5XheF9a5keFw9Z6NBzyKZBy2EcwNfV3iJ3GyZzGEcKWujdiL2eCQb/84Yi9zyLh3A9l72Oz99OkwmGHuZJJ53lKtvkjwYDCwQxlZucZnx3rA7X036Sd5ncErHlNvIZxXce4NhRWtm3ufyQ9pf4vx/k04Yh8sam8/+gQVwQD8sfC8lr66pz7PrLt824d+5Sc38l0KgecYsVUtr2vLhIOWt8fdcft7eG0Y51sLwec4oRwOKRIylJmRQKybP6347DHio51rMN4uXO/QVg+r33+nFMsn87yWeOvQCQqn9nkeW1llu1deIexaac2YzgUnGRc1z52Fw4lrGNM6Unmd0yl/8ZxzsTf+m9sfXWOc6kd0iOO5887SV+dpfxxeEchGInK53Jb38VyypPjmKjjHB/n96Od0m39PeG/9YHa+uqcxg2d2zZO/TT2NmYoFFTmVN4XCYet5fREnqzzvNyTPEO28+rcDz7Vd99s28dicQWDHoexkIBke28/ZX+/ZNJ3LRzavY5jUh7L+gyR+N/6Fafybstk9/GrH19w6ms6NlZqmfcfCCgUtLdXXeGofFmWvgzvJHP9pjDWHHZcC8Y5psn0BJTjOH/O6f2cVx/TTDWvTnOvA8GQwim/vJa1XRzLAaf2xRTHmp3vy4i1bRN6ua/OEiuGovZ+XKc+uamumTPZWKlTv6L0/9dumipX+rX+JoA3lSNHjqi+vn66swEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPC60NnZqcrKyin/nrkEHgBYlJSUSJI6OjpUVFQ0zbkBAAB48/L5fKqqqlJnZ6cKCwunOzsAAABvasRmAAAAMwNxGQAAwMxAXAYAADAzEJcBAADMDMRlAAAAMwNxGQBgOqXTafn9flVUVLym32eBOACvitvtliQVFRUR9AIAAMwAhYWFxGUAAAAzBLEZAADAzEBcBgAAMDMQlwEAAMwMxGUAAAAzA3EZAADAzEBcBgCYLkVFRa/5d93/g/kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwdWCAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGYIFogD8KpkZWXppptuUlZW1nRnBQAA4E2NuAwAAGDmIDYDAACYGYjLAAAAZgbiMgAAgJmBuAwAAGBmIC4DAACYGYjLAACvZ650Op2e7kwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACT3dGcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAMC8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAzBAnEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEOwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzBAsEAfgVbn99ttVU1Oj7OxsrV27Vjt37pzuLAEAALyhPPbYYzr//PNVUVEhl8ul++6777jP0+m0Pve5z2nevHnKycnRhg0bdPDgweO2GRkZ0caNG1VYWKji4mJ9+MMfViAQOIFHAQAA8Pp3yy23aM2aNSooKNDcuXN14YUXav/+/cdtE4lEdNVVV2n27NnKz8/Xu971LvX39x+3TUdHh8477zzl5uZq7ty5uuGGG5RIJE7koQAAALyu3XHHHWptbVVhYaEKCwu1bt06PfTQQxOfE5MBAACceF/5ylfkcrl07bXXTqQRlwEAAJwYW7ZskcvlOu5fU1PTxOfEZQAAACdOd3e33v/+92v27NnKycnR0qVLtWvXronPmfsPAADwj1dTU2P0l7lcLl111VWS6C8DALxxsEAcgFd0zz336Prrr9dNN92kp59+WsuWLdNZZ52lgYGB6c4aAADAG0YwGNSyZct0++23Wz//6le/qttuu03f+c53tGPHDuXl5emss85SJBKZ2Gbjxo16/vnn9cgjj+jBBx/UY489po9+9KMn6hAAAADeELZv366rrrpKf/3rX/XII48oHo/rHe94h4LB4MQ21113nX7zm9/ol7/8pbZv366enh5dfPHFE58nk0mdd955isVi+stf/qK7775bd911lz73uc9NxyEBAAC8LlVWVuorX/mKdu/erV27dumtb32rLrjgAj3//POSiMkAAABOtKeeekrf/e531draelw6cRkAAMCJs3jxYvX29k78e/zxxyc+Iy4DAAA4MUZHR3XqqafK6/XqoYce0gsvvKCvf/3rmjVr1sQ2zP0HAAD4x3vqqaeO6yt75JFHJEnvfve7JdFfBgB443Cl0+n0dGcCwMy2du1arVmzRv/xH/8hSUqlUqqqqtInPvEJ3XjjjdOcOwAAgDcel8ule++9VxdeeKGkY39BrKKiQp/61Ke0efNmSdL4+LjKysp011136b3vfa9efPFFtbS06KmnntLq1aslSQ8//LDOPfdcdXV1qaKiYroOBwAA4HVtcHBQc+fO1fbt2/WWt7xF4+PjKi0t1U9/+lP90z/9kyTppZdeUnNzs5588kmdfPLJeuihh/TOd75TPT09KisrkyR95zvf0ac//WkNDg4qMzNzOg8JAADgdaukpERf+9rX9E//9E/EZAAAACdQIBDQypUr9e1vf1tf+tKXtHz5ct166630lQEAAJxAW7Zs0X333ac9e/YYnxGXAQAAnDg33nijnnjiCf35z3+2fs7cfwAAgOlx7bXX6sEHH9TBgwfl8/noLwMAvGG4pzsDAGa2WCym3bt3a8OGDRNpbrdbGzZs0JNPPjmNOQMAAHjzOHr0qPr6+o6LyYqKirR27dqJmOzJJ59UcXHxxACxJG3YsEFut1s7duw44XkGAAB4oxgfH5d0bDESSdq9e7fi8fhxsVlTU5Oqq6uPi82WLl06MVAsSWeddZZ8Pp+ef/75E5h7AACAN4ZkMqmf//znCgaDWrduHTEZAADACXbVVVfpvPPOOy7+kugrAwAAONEOHjyoiooK1dXVaePGjero6JBEXAYAAHAiPfDAA1q9erXe/e53a+7cuVqxYoW+//3vT3zO3H8AAIATLxaL6cc//rE+9KEPyeVy0V8GAHhDYYE4AJMaGhpSMpk8LrCVpLKyMvX19U1TrgAAAN5cXo67JovJ+vr6NHfu3OM+93g8KikpIW4DAAB4jVKplK699lqdeuqpWrJkiaRjcVdmZqaKi4uP2/a/x2a22O3lzwAAAPDq7Nu3T/n5+crKytKVV16pe++9Vy0tLcRkAAAAJ9DPf/5zPf3007rllluMz4jLAAAATpy1a9fqrrvu0sMPP6w77rhDR48e1emnny6/309cBgAAcAIdOXJEd9xxhxoaGvT73/9eH/vYx3TNNdfo7rvvlsTcfwAAgOlw3333aWxsTJs2bZLEOCYA4I3FM90ZAAAAAAAAAABgJrrqqqv03HPP6fHHH5/urAAAALwpLVq0SHv27NH4+Lh+9atf6fLLL9f27dunO1sAAABvGp2dnfrkJz+pRx55RNnZ2dOdHQAAgDe1c845Z+L/ra2tWrt2rRYsWKBf/OIXysnJmcacAQAAvLmkUimtXr1aN998syRpxYoVeu655/Sd73xHl19++TTnDgAA4M3pBz/4gc455xxVVFRMd1YAAPgf557uDACY2ebMmaOMjAz19/cfl97f36/y8vJpyhUAAMCby8tx12QxWXl5uQYGBo77PJFIaGRkhLgNAADgNbj66qv14IMP6k9/+pMqKysn0svLyxWLxTQ2Nnbc9v89NrPFbi9/BgAAgFcnMzNTCxcu1KpVq3TLLbdo2bJl+uY3v0lMBgAAcILs3r1bAwMDWrlypTwejzwej7Zv367bbrtNHo9HZWVlxGUAAADTpLi4WI2NjTp06BD9ZQAAACfQvHnz1NLSclxac3OzOjo6JDH3HwAA4ERrb2/XH//4R11xxRUTafSXAQDeSFggDsCkMjMztWrVKm3dunUiLZVKaevWrVq3bt005gwAAODNo7a2VuXl5cfFZD6fTzt27JiIydatW6exsTHt3r17YptHH31UqVRKa9euPeF5BgAAeL1Kp9O6+uqrde+99+rRRx9VbW3tcZ+vWrVKXq/3uNhs//796ujoOC4227dv33GT+B555BEVFhYakwMBAADw6qVSKUWjUWIyAACAE+Rtb3ub9u3bpz179kz8W716tTZu3Djxf+IyAACA6REIBHT48GHNmzeP/jIAAIAT6NRTT9X+/fuPSztw4IAWLFggibn/AAAAJ9qdd96puXPn6rzzzptIo78MAPBG4pnuDACY+a6//npdfvnlWr16tU466STdeuutCgaD+uAHPzjdWQMAAHjDCAQCOnTo0MTPR48e1Z49e1RSUqLq6mpde+21+tKXvqSGhgbV1tbqs5/9rCoqKnThhRdKOvZXx84++2x95CMf0Xe+8x3F43FdffXVeu9736uKioppOioAAIDXn6uuuko//elPdf/996ugoEB9fX2SpKKiIuXk5KioqEgf/vCHdf3116ukpESFhYX6xCc+oXXr1unkk0+WJL3jHe9QS0uLPvCBD+irX/2q+vr69L//9//WVVddpaysrOk8PAAAgNeNz3zmMzrnnHNUXV0tv9+vn/70p9q2bZt+//vfE5MBAACcIAUFBVqyZMlxaXl5eZo9e/ZEOnEZAADAibF582adf/75WrBggXp6enTTTTcpIyNDl156Kf1lAAAAJ9B1112nU045RTfffLMuueQS7dy5U9/73vf0ve99T5LkcrmY+w8AAHCCpFIp3Xnnnbr88svl8fz/5XPoLwMAvJGwQByAV/Se97xHg4OD+tznPqe+vj4tX75cDz/8sMrKyqY7awAAAG8Yu3bt0plnnjnx8/XXXy9Juvzyy3XXXXfpX/7lXxQMBvXRj35UY2NjOu200/Twww8rOzt74nd+8pOf6Oqrr9bb3vY2ud1uvetd79Jtt912wo8FAADg9eyOO+6QJK1fv/649DvvvFObNm2SJH3jG9+YiLei0ajOOussffvb357YNiMjQw8++KA+9rGPad26dcrLy9Pll1+uL3zhCyfqMAAAAF73BgYGdNlll6m3t1dFRUVqbW3V73//e7397W+XREwGAAAwUxCXAQAAnBhdXV269NJLNTw8rNLSUp122mn661//qtLSUknEZQAAACfKmjVrdO+99+ozn/mMvvCFL6i2tla33nqrNm7cOLENc/8BAABOjD/+8Y/q6OjQhz70IeMz+ssAAG8UrnQ6nZ7uTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJPd0ZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAwLxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADADMECcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQ7BAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMECwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzBAvEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAMwQJxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBDsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMwQLBAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMEC8QBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAzBAnEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMEOwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzBAsEAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMwQLxAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADADMECcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwQ7BAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMECwQBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzxP8DnGfkP5x2sQAAAAAASUVORK5CYII=", + "text/html": [ + "\n", + "
\n", + "
\n", + " Figure\n", + "
\n", + " \n", + "
\n", + " " + ], + "text/plain": [ + "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from utils import plot_heatmap\n", + "\n", + "y_labels = input_text_lst_sim\n", + "\n", + "# Plot the heatmap\n", + "plot_heatmap(embeddings_array, y_labels = y_labels, title = \"Embeddings Heatmap\")" + ] + }, + { + "cell_type": "markdown", + "id": "b984ee27-fa85-4839-b799-748b9d82107e", + "metadata": {}, + "source": [ + "Note: the heat map won't show everything because there are 768 columns to show. To adjust the heat map with your mouse:\n", + "- Hover your mouse over the heat map. Buttons will appear on the left of the heatmap. Click on the button that has a vertical and horizontal double arrow (they look like axes).\n", + "- Left click and drag to move the heat map left and right.\n", + "- Right click and drag up to zoom in.\n", + "- Right click and drag down to zoom out." + ] + }, + { + "cell_type": "markdown", + "id": "e075dc41-18e8-40e1-8435-d0f972d0c8ab", + "metadata": {}, + "source": [ + "#### Compute cosine similarity\n", + "- The `cosine_similarity` function expects a 2D array, which is why we'll wrap each embedding list inside another list.\n", + "- You can verify that sentence 1 and 2 have a higher similarity compared to sentence 1 and 4, even though sentence 1 and 4 both have the words \"desert\" and \"plant\"." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "0dff11a0-ae2b-4898-b565-3be7439a27b0", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from sklearn.metrics.pairwise import cosine_similarity" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "05e99af9-2bf6-4ba5-ad72-809a12c6fca1", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "def compare(embeddings,idx1,idx2):\n", + " return cosine_similarity([embeddings[idx1]],[embeddings[idx2]])" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "8842d87c-1abf-4908-9ff7-ab8b3200532e", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He couldn’t desert \n", + " his post at the power plant.\n", + "The power plant needed \n", + " him at the time.\n", + "[[0.80995305]]\n" + ] + } + ], + "source": [ + "print(in_1)\n", + "print(in_2)\n", + "print(compare(embeddings,0,1))" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "35860466-0090-4c86-b39a-baf6926b613c", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He couldn’t desert \n", + " his post at the power plant.\n", + "Desert plants can \n", + " survive droughts.\n", + "[[0.48815018]]\n" + ] + } + ], + "source": [ + "print(in_1)\n", + "print(in_4)\n", + "print(compare(embeddings,0,3))" + ] + }, + { + "cell_type": "markdown", + "id": "d3f2115e-785b-45a6-acb0-431e015420d5", + "metadata": {}, + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9131d8a3", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/L5-applications-of-embeddings.ipynb b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/L5-applications-of-embeddings.ipynb new file mode 100644 index 0000000..9fae087 --- /dev/null +++ b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/L5-applications-of-embeddings.ipynb @@ -0,0 +1,1621 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d56d7546-3664-4ea0-85ca-59add93161f4", + "metadata": {}, + "source": [ + "## Lesson 4: Applications of Embeddings" + ] + }, + { + "cell_type": "markdown", + "id": "7cdc073e-d1ac-49af-97b0-b73fb840d38c", + "metadata": {}, + "source": [ + "#### Project environment setup\n", + "\n", + "- Load credentials and relevant Python Libraries" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "30dd137e-8522-4e6c-b981-6c5863bc159e", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from utils import authenticate\n", + "credentials, PROJECT_ID = authenticate()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "6ce0ce04-d90d-4016-a636-5fc4c5578818", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "REGION = 'us-central1'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "a2a787d9-b471-41dc-89e2-e2e35d2e3a4c", + "metadata": { + "height": 83 + }, + "outputs": [], + "source": [ + "import vertexai\n", + "vertexai.init(project=PROJECT_ID, \n", + " location=REGION, \n", + " credentials = credentials)" + ] + }, + { + "cell_type": "markdown", + "id": "a84c7df8-5404-4697-804c-3e91a500a125", + "metadata": {}, + "source": [ + "#### Load Stack Overflow questions and answers from BigQuery\n", + "- BigQuery is Google Cloud's serverless data warehouse.\n", + "- We'll get the first 500 posts (questions and answers) for each programming language: Python, HTML, R, and CSS." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "737db5e4-a5c4-480c-ab43-ae8e7db75c64", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from google.cloud import bigquery\n", + "import pandas as pd" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "0031e73e-517e-4a3f-b738-f75de03ec6b3", + "metadata": { + "height": 389 + }, + "outputs": [], + "source": [ + "def run_bq_query(sql):\n", + "\n", + " # Create BQ client\n", + " bq_client = bigquery.Client(project = PROJECT_ID, \n", + " credentials = credentials)\n", + "\n", + " # Try dry run before executing query to catch any errors\n", + " job_config = bigquery.QueryJobConfig(dry_run=True, \n", + " use_query_cache=False)\n", + " bq_client.query(sql, job_config=job_config)\n", + "\n", + " # If dry run succeeds without errors, proceed to run query\n", + " job_config = bigquery.QueryJobConfig()\n", + " client_result = bq_client.query(sql, \n", + " job_config=job_config)\n", + "\n", + " job_id = client_result.job_id\n", + "\n", + " # Wait for query/job to finish running. then get & return data frame\n", + " df = client_result.result().to_arrow().to_pandas()\n", + " print(f\"Finished job_id: {job_id}\")\n", + " return df" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "c1adceeb-c109-43b2-bda9-489e1ab69413", + "metadata": { + "height": 66 + }, + "outputs": [], + "source": [ + "# define list of programming language tags we want to query\n", + "\n", + "language_list = [\"python\", \"html\", \"r\", \"css\"]" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "c9e0cba0-daaf-4475-99d9-bb4a6ae72874", + "metadata": { + "height": 508 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "generating python dataframe\n", + "Finished job_id: e827c228-4b84-434f-ba5c-b043d3c181ec\n", + "generating html dataframe\n", + "Finished job_id: e1fc67ab-9b7a-4174-8dff-3f2e08e2d2cc\n", + "generating r dataframe\n", + "Finished job_id: 80f2afa3-3a93-4468-842e-91840fa9e012\n", + "generating css dataframe\n", + "Finished job_id: dc900daa-fe60-4a43-b1de-40ef0848e7ed\n" + ] + } + ], + "source": [ + "so_df = pd.DataFrame()\n", + "\n", + "for language in language_list:\n", + " \n", + " print(f\"generating {language} dataframe\")\n", + " \n", + " query = f\"\"\"\n", + " SELECT\n", + " CONCAT(q.title, q.body) as input_text,\n", + " a.body AS output_text\n", + " FROM\n", + " `bigquery-public-data.stackoverflow.posts_questions` q\n", + " JOIN\n", + " `bigquery-public-data.stackoverflow.posts_answers` a\n", + " ON\n", + " q.accepted_answer_id = a.id\n", + " WHERE \n", + " q.accepted_answer_id IS NOT NULL AND \n", + " REGEXP_CONTAINS(q.tags, \"{language}\") AND\n", + " a.creation_date >= \"2020-01-01\"\n", + " LIMIT \n", + " 500\n", + " \"\"\"\n", + "\n", + " \n", + " language_df = run_bq_query(query)\n", + " language_df[\"category\"] = language\n", + " so_df = pd.concat([so_df, language_df], \n", + " ignore_index = True) " + ] + }, + { + "cell_type": "markdown", + "id": "bc1eeb1a-c3da-42bd-986c-2d8beb31eef4", + "metadata": {}, + "source": [ + "- You can reuse the above code to run your own queries if you are using Google Cloud's BigQuery service.\n", + "- In this classroom, if you run into any issues, you can load the same data from a csv file." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "e9b70a17-7441-427b-94e3-8c902c01a057", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "# Run this cell if you get any errors or you don't want to wait for the query to be completed\n", + "# so_df = pd.read_csv('so_database_app.csv')" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "8f912a8d-a391-4fda-a7b4-eee4c0d8490d", + "metadata": { + "height": 32 + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
input_textoutput_textcategory
0Using a function to provide parameters for pyt...<p>You can use the <code>parametrize</code> ap...python
1How to fix df.apply using the first rows of a ...<p>You can use lambda in your apply to have be...python
2Python copy data from 1 df to first matching r...<p>You can use <code>merge</code> to map the <...python
3How to let PIL's Image.open find files from st...<p>STATIC_URL has no concept of the actual loc...python
4Python substring find<p>I'v a little request f...<p>Try using pattern <code>'\\w*(benoît|Nicolas...python
............
1995How to set hexadecimal color on SVG pseudoelem...<p>The <code>#</code> <a href=\"https://yoksel....css
1996Are rems and ems equivalent when used at root ...<p>Yes</p>\\n<p><div class=\"snippet\" data-lang=...css
1997Is there a way to change the order that 3 HTML...<p>You can do this with <code>z-index</code>.<...css
1998CSS issue when changing vanilla javascript ove...<p>So I'm relatively new to React and one thin...css
1999Row-reverse flexboxes not aligning well on mob...<p>Rather than starting from a desktop browser...css
\n", + "

2000 rows × 3 columns

\n", + "
" + ], + "text/plain": [ + " input_text \\\n", + "0 Using a function to provide parameters for pyt... \n", + "1 How to fix df.apply using the first rows of a ... \n", + "2 Python copy data from 1 df to first matching r... \n", + "3 How to let PIL's Image.open find files from st... \n", + "4 Python substring find

I'v a little request f... \n", + "... ... \n", + "1995 How to set hexadecimal color on SVG pseudoelem... \n", + "1996 Are rems and ems equivalent when used at root ... \n", + "1997 Is there a way to change the order that 3 HTML... \n", + "1998 CSS issue when changing vanilla javascript ove... \n", + "1999 Row-reverse flexboxes not aligning well on mob... \n", + "\n", + " output_text category \n", + "0

You can use the parametrize ap... python \n", + "1

You can use lambda in your apply to have be... python \n", + "2

You can use merge to map the <... python \n", + "3

STATIC_URL has no concept of the actual loc... python \n", + "4

Try using pattern '\\w*(benoît|Nicolas... python \n", + "... ... ... \n", + "1995

The # Yes

\\n

You can do this with z-index.<... css \n", + "1998

So I'm relatively new to React and one thin... css \n", + "1999

Rather than starting from a desktop browser... css \n", + "\n", + "[2000 rows x 3 columns]" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "so_df" + ] + }, + { + "cell_type": "markdown", + "id": "2107a70c-d6a4-48ef-9798-f6bdbf44aa27", + "metadata": {}, + "source": [ + "#### Generate text embeddings\n", + "- To generate embeddings for a dataset of texts, we'll need to group the sentences together in batches and send batches of texts to the model.\n", + "- The API currently can take batches of up to 5 pieces of text per API call." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "678f7521-52ef-40a7-b258-a47a2b14ebc5", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from vertexai.language_models import TextEmbeddingModel" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "4b1902c7-6a47-4a43-bf15-6de20ed5d7f7", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "model = TextEmbeddingModel.from_pretrained(\n", + " \"textembedding-gecko@001\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "0b8da7eb-cc45-4621-ac3c-bf08ee2e282a", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "import time\n", + "import numpy as np" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "d531fad6-cfde-4aa7-9486-f10ab4efa71d", + "metadata": { + "height": 100 + }, + "outputs": [], + "source": [ + "# Generator function to yield batches of sentences\n", + "\n", + "def generate_batches(sentences, batch_size = 5):\n", + " for i in range(0, len(sentences), batch_size):\n", + " yield sentences[i : i + batch_size]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "cf78aa64-5b40-490f-85a5-f54127684823", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "so_questions = so_df[0:200].input_text.tolist() \n", + "batches = generate_batches(sentences = so_questions)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "4c1e9d08-5949-4046-987c-ea13b26dad0a", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "batch = next(batches)\n", + "len(batch)" + ] + }, + { + "cell_type": "markdown", + "id": "70c12ffc-dab7-41fd-93e4-a6baef7ab221", + "metadata": {}, + "source": [ + "#### Get embeddings on a batch of data\n", + "- This helper function calls `model.get_embeddings()` on the batch of data, and returns a list containing the embeddings for each text in that batch." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "fe933993-1cdf-460b-afad-0173b2282e8d", + "metadata": { + "height": 117 + }, + "outputs": [], + "source": [ + "def encode_texts_to_embeddings(sentences):\n", + " try:\n", + " embeddings = model.get_embeddings(sentences)\n", + " return [embedding.values for embedding in embeddings]\n", + " except Exception:\n", + " return [None for _ in range(len(sentences))]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "b9190606-9d73-4455-ab4b-97df20f0a2fb", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "batch_embeddings = encode_texts_to_embeddings(batch)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "259f5f5d-0c6b-4030-9a45-92438625b792", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'5 embeddings of size 768'" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "f\"{len(batch_embeddings)} embeddings of size \\\n", + "{len(batch_embeddings[0])}\"" + ] + }, + { + "cell_type": "markdown", + "id": "debb7234-eccd-4dc8-bb4b-abd7a21c7714", + "metadata": {}, + "source": [ + "#### Code for getting data on an entire data set\n", + "- Most API services have rate limits, so we've provided a helper function (in utils.py) that you could use to wait in-between API calls.\n", + "- If the code was not designed to wait in-between API calls, you may not receive embeddings for all batches of text.\n", + "- This particular service can handle 20 calls per minute. In calls per second, that's 20 calls divided by 60 seconds, or `20/60`.\n", + "\n", + "```Python\n", + "from utils import encode_text_to_embedding_batched\n", + "\n", + "so_questions = so_df.input_text.tolist()\n", + "question_embeddings = encode_text_to_embedding_batched(\n", + " sentences=so_questions,\n", + " api_calls_per_second = 20/60, \n", + " batch_size = 5)\n", + "```\n", + "\n", + "In order to handle limits of this classroom environment, we're not going to run this code to embed all of the data. But you can adapt this code for your own projects and datasets." + ] + }, + { + "cell_type": "markdown", + "id": "fdd85d39-72d8-432d-9210-55e14cac508c", + "metadata": {}, + "source": [ + "#### Load the data from file\n", + "- We'll load the stack overflow questions, answers, and category labels (Python, HTML, R, CSS) from a .csv file.\n", + "- We'll load the embeddings of the questions (which we've precomputed with batched calls to `model.get_embeddings()`), from a pickle file." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "87c78630-2cda-487a-be24-5ade753d76f9", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "data": { + "text/html": [ + "

\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
input_textoutput_textcategory
0python's inspect.getfile returns \"<string>\"<p>...<p><code>&lt;string&gt;</code> means that the ...python
1Passing parameter to function while multithrea...<p>Try this and note the difference:</p>\\n<pre...python
2How do we test a specific method written in a ...<p>Duplicate of <a href=\"https://stackoverflow...python
3how can i remove the black bg color of an imag...<p>The alpha channel &quot;disappears&quot; be...python
4How to extract each sheet within an Excel file...<p>You need to specify the <code>index</code> ...python
\n", + "
" + ], + "text/plain": [ + " input_text \\\n", + "0 python's inspect.getfile returns \"\"

... \n", + "1 Passing parameter to function while multithrea... \n", + "2 How do we test a specific method written in a ... \n", + "3 how can i remove the black bg color of an imag... \n", + "4 How to extract each sheet within an Excel file... \n", + "\n", + " output_text category \n", + "0

<string> means that the ... python \n", + "1

Try this and note the difference:

\\nDuplicate of
The alpha channel "disappears" be... python \n", + "4

You need to specify the index ... python " + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "so_df = pd.read_csv('so_database_app.csv')\n", + "so_df.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "7a413056-0ec7-4137-a191-814e4797e0a2", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "import pickle" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "c7836318-0148-456d-b29e-4a26aa4f8221", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "with open('question_embeddings_app.pkl', 'rb') as file:\n", + " question_embeddings = pickle.load(file)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "7a4134a8-76d3-4677-b180-f8477b1a2c15", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape: (2000, 768)\n", + "[[-0.03571156 -0.00240684 0.05860338 ... -0.03100227 -0.00855574\n", + " -0.01997405]\n", + " [-0.02024316 -0.0026255 0.01940405 ... -0.02158143 -0.05655403\n", + " -0.01040497]\n", + " [-0.05175979 -0.03712264 0.02699278 ... -0.07055898 -0.0402537\n", + " 0.00092099]\n", + " ...\n", + " [-0.00580394 -0.01621097 0.05829635 ... -0.03350992 -0.05343556\n", + " -0.06016821]\n", + " [-0.00436622 -0.02692963 0.03363771 ... -0.01686567 -0.03812337\n", + " -0.02329491]\n", + " [-0.04240424 -0.01633749 0.05516777 ... -0.02697376 -0.01751165\n", + " -0.04558187]]\n" + ] + } + ], + "source": [ + "print(\"Shape: \" + str(question_embeddings.shape))\n", + "print(question_embeddings)" + ] + }, + { + "cell_type": "markdown", + "id": "3061eb7d-b69c-4eae-b583-67e9d7ca1f47", + "metadata": {}, + "source": [ + "#### Cluster the embeddings of the Stack Overflow questions" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "a58b189d-61f7-4c68-8c73-769c59a23987", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from sklearn.cluster import KMeans\n", + "from sklearn.decomposition import PCA" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "dd2cd054-426e-4d92-9561-285a0b55792e", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "clustering_dataset = question_embeddings[:1000]" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "05421596-894c-4d53-9551-61839e72c0eb", + "metadata": { + "height": 83 + }, + "outputs": [], + "source": [ + "n_clusters = 2\n", + "kmeans = KMeans(n_clusters=n_clusters, \n", + " random_state=0, \n", + " n_init = 'auto').fit(clustering_dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "7fac5a79-7639-4072-8c9d-86dc2e2c6658", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "kmeans_labels = kmeans.labels_" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "210b0fbe-a5df-488f-9814-60f4304804d0", + "metadata": { + "height": 66 + }, + "outputs": [], + "source": [ + "PCA_model = PCA(n_components=2)\n", + "PCA_model.fit(clustering_dataset)\n", + "new_values = PCA_model.transform(clustering_dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "6d2095e0-605f-4dd3-9786-2f313ff5c60a", + "metadata": { + "height": 66 + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import mplcursors\n", + "%matplotlib ipympl" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "961b770b-53ea-4b49-bfc8-507cd711fc99", + "metadata": { + "height": 66 + }, + "outputs": [], + "source": [ + "from utils import clusters_2D\n", + "clusters_2D(x_values = new_values[:,0], y_values = new_values[:,1], \n", + " labels = so_df[:1000], kmeans_labels = kmeans_labels)" + ] + }, + { + "cell_type": "markdown", + "id": "b499cf9d-c739-4a34-b38d-e270fffe14f7", + "metadata": {}, + "source": [ + "- Clustering is able to identify two distinct clusters of HTML or Python related questions, without being given the category labels (HTML or Python)." + ] + }, + { + "cell_type": "markdown", + "id": "c46c217f-d121-4a14-a351-340a134db73f", + "metadata": {}, + "source": [ + "## Anomaly / Outlier detection\n", + "\n", + "- We can add an anomalous piece of text and check if the outlier (anomaly) detection algorithm (Isolation Forest) can identify it as an outlier (anomaly), based on its embedding." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "8f7e3a9e-ec14-4f85-9eef-5766f85e0d0c", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import IsolationForest" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "96d872a2-5fbb-466b-ac80-84a1c6458006", + "metadata": { + "height": 83 + }, + "outputs": [], + "source": [ + "input_text = \"\"\"I am making cookies but don't \n", + " remember the correct ingredient proportions. \n", + " I have been unable to find \n", + " anything on the web.\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "ffb3b6f7-8cc8-4f3b-a19e-541956903e9e", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "emb = model.get_embeddings([input_text])[0].values" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "b89da1d8-d17f-4ac7-a774-7fc0f67fba00", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "embeddings_l = question_embeddings.tolist()\n", + "embeddings_l.append(emb)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "1f98eb7a-9a62-4d08-8744-5618cdf6d241", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "embeddings_array = np.array(embeddings_l)" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "b8a6eaa7-1067-4414-9e40-05352eb5ec03", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape: (2001, 768)\n", + "[[-0.03571156 -0.00240684 0.05860338 ... -0.03100227 -0.00855574\n", + " -0.01997405]\n", + " [-0.02024316 -0.0026255 0.01940405 ... -0.02158143 -0.05655403\n", + " -0.01040497]\n", + " [-0.05175979 -0.03712264 0.02699278 ... -0.07055898 -0.0402537\n", + " 0.00092099]\n", + " ...\n", + " [-0.00436622 -0.02692963 0.03363771 ... -0.01686567 -0.03812337\n", + " -0.02329491]\n", + " [-0.04240424 -0.01633749 0.05516777 ... -0.02697376 -0.01751165\n", + " -0.04558187]\n", + " [-0.00302366 -0.02049104 0.02172194 ... -0.04479321 -0.05254056\n", + " -0.00319716]]\n" + ] + } + ], + "source": [ + "print(\"Shape: \" + str(embeddings_array.shape))\n", + "print(embeddings_array)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "11467308-b48a-4341-a918-83940239762f", + "metadata": { + "height": 117 + }, + "outputs": [ + { + "data": { + "text/html": [ + "

\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
input_textoutput_textcategory
1996Flip Clock code works on Codepen and doesn't w...<p>You forgot to attach the CSS file for the f...css
1997React Native How can I put one view in front o...<p>You can do it using zIndex for example:</p>...css
1998setting fixed width with 100% height of the pa...<p>You can use <code>width: calc(100% - 100px)...css
1999How to make sidebar button not bring viewpoint...<p>It is quite simple, just remove that href=\"...css
2001I am making cookies but don't \\n ...Nonebaking
\n", + "
" + ], + "text/plain": [ + " input_text \\\n", + "1996 Flip Clock code works on Codepen and doesn't w... \n", + "1997 React Native How can I put one view in front o... \n", + "1998 setting fixed width with 100% height of the pa... \n", + "1999 How to make sidebar button not bring viewpoint... \n", + "2001 I am making cookies but don't \\n ... \n", + "\n", + " output_text category \n", + "1996

You forgot to attach the CSS file for the f... css \n", + "1997

You can do it using zIndex for example:

... css \n", + "1998

You can use width: calc(100% - 100px)... css \n", + "1999

It is quite simple, just remove that href=\"... css \n", + "2001 None baking " + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Add the outlier text to the end of the stack overflow dataframe\n", + "so_df = pd.read_csv('so_database_app.csv')\n", + "new_row = pd.Series([input_text, None, \"baking\"], \n", + " index=so_df.columns)\n", + "so_df.loc[len(so_df)+1] = new_row\n", + "so_df.tail()" + ] + }, + { + "cell_type": "markdown", + "id": "da8b00f6-bc36-4e07-87af-043609e273c4", + "metadata": {}, + "source": [ + "#### Use Isolation Forest to identify potential outliers\n", + "\n", + "- `IsolationForest` classifier will predict `-1` for potential outliers, and `1` for non-outliers.\n", + "- You can inspect the rows that were predicted to be potential outliers and verify that the question about baking is predicted to be an outlier." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "36815aaf-fa2a-4e0f-98d0-07c334a79887", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "clf = IsolationForest(contamination=0.005, \n", + " random_state = 2) " + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "5781dcd9-cdce-4307-ba49-dccf9cd7646e", + "metadata": { + "height": 66 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2001 predictions. Set of possible values: {1, -1}\n" + ] + } + ], + "source": [ + "preds = clf.fit_predict(embeddings_array)\n", + "\n", + "print(f\"{len(preds)} predictions. Set of possible values: {set(preds)}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "483e753a-5291-423b-a7a3-c36af012d3f4", + "metadata": { + "height": 32 + }, + "outputs": [ + { + "data": { + "text/html": [ + "

\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
input_textoutput_textcategory
203extract channel names from a multi-channel ima...<p>PerkinElmer QPI metadata are stored as XML ...python
1018ASP .NET - JSON Serializer not working on clas...<p>Ok, I forgot to add default <code>{ get; se...r
1138parse year and month from a string SQL BigQuer...<p>How about using string operations?</p>\\n<pr...r
1313Array initialization with ternary operator in ...<p>To make your code work, do the following in...r
1358How to represent 2 Entity with 2 Relation in E...<p><a href=\"https://i.stack.imgur.com/BJxBP.pn...r
1403Apache ignite Partition Map Exchange , Baselin...<p>Long story short, these topics are about da...r
1427Shortcut to reveal in Finder for currently ope...<p>No. It is not present but we can add it. Go...r
1493How to change id of datatable?<p>I have some w...<p>In short - you can't. But maybe you can:</p...r
1498What’s the difference between Next.js rewrites...<p><code>rewrites</code> are a convenient way ...r
2001I am making cookies but don't \\n ...Nonebaking
\n", + "
" + ], + "text/plain": [ + " input_text \\\n", + "203 extract channel names from a multi-channel ima... \n", + "1018 ASP .NET - JSON Serializer not working on clas... \n", + "1138 parse year and month from a string SQL BigQuer... \n", + "1313 Array initialization with ternary operator in ... \n", + "1358 How to represent 2 Entity with 2 Relation in E... \n", + "1403 Apache ignite Partition Map Exchange , Baselin... \n", + "1427 Shortcut to reveal in Finder for currently ope... \n", + "1493 How to change id of datatable?

I have some w... \n", + "1498 What’s the difference between Next.js rewrites... \n", + "2001 I am making cookies but don't \\n ... \n", + "\n", + " output_text category \n", + "203

PerkinElmer QPI metadata are stored as XML ... python \n", + "1018

Ok, I forgot to add default { get; se... r \n", + "1138

How about using string operations?

\\nTo make your code work, do the following in... r \n", + "1358

Long story short, these topics are about da... r \n", + "1427

No. It is not present but we can add it. Go... r \n", + "1493

In short - you can't. But maybe you can:rewrites are a convenient way ... r \n", + "2001 None baking " + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "so_df.loc[preds == -1]" + ] + }, + { + "cell_type": "markdown", + "id": "4237f497-489e-448c-bf52-781a31d28558", + "metadata": {}, + "source": [ + "#### Remove the outlier about baking" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "e8da293f-7945-4686-93fb-0a62269fed07", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "so_df = so_df.drop(so_df.index[-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "869a7b82-a813-474d-98d3-d740a2e8e6c5", + "metadata": { + "height": 32 + }, + "outputs": [ + { + "data": { + "text/html": [ + "

\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
input_textoutput_textcategory
0python's inspect.getfile returns \"<string>\"<p>...<p><code>&lt;string&gt;</code> means that the ...python
1Passing parameter to function while multithrea...<p>Try this and note the difference:</p>\\n<pre...python
2How do we test a specific method written in a ...<p>Duplicate of <a href=\"https://stackoverflow...python
3how can i remove the black bg color of an imag...<p>The alpha channel &quot;disappears&quot; be...python
4How to extract each sheet within an Excel file...<p>You need to specify the <code>index</code> ...python
............
1995Is it possible to made inline-block elements l...<p>If this is only for the visual purpose then...css
1996Flip Clock code works on Codepen and doesn't w...<p>You forgot to attach the CSS file for the f...css
1997React Native How can I put one view in front o...<p>You can do it using zIndex for example:</p>...css
1998setting fixed width with 100% height of the pa...<p>You can use <code>width: calc(100% - 100px)...css
1999How to make sidebar button not bring viewpoint...<p>It is quite simple, just remove that href=\"...css
\n", + "

2000 rows × 3 columns

\n", + "
" + ], + "text/plain": [ + " input_text \\\n", + "0 python's inspect.getfile returns \"\"

... \n", + "1 Passing parameter to function while multithrea... \n", + "2 How do we test a specific method written in a ... \n", + "3 how can i remove the black bg color of an imag... \n", + "4 How to extract each sheet within an Excel file... \n", + "... ... \n", + "1995 Is it possible to made inline-block elements l... \n", + "1996 Flip Clock code works on Codepen and doesn't w... \n", + "1997 React Native How can I put one view in front o... \n", + "1998 setting fixed width with 100% height of the pa... \n", + "1999 How to make sidebar button not bring viewpoint... \n", + "\n", + " output_text category \n", + "0

<string> means that the ... python \n", + "1

Try this and note the difference:

\\nDuplicate of
The alpha channel "disappears" be... python \n", + "4

You need to specify the index ... python \n", + "... ... ... \n", + "1995

If this is only for the visual purpose then... css \n", + "1996

You forgot to attach the CSS file for the f... css \n", + "1997

You can do it using zIndex for example:

... css \n", + "1998

You can use width: calc(100% - 100px)... css \n", + "1999

It is quite simple, just remove that href=\"... css \n", + "\n", + "[2000 rows x 3 columns]" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "so_df" + ] + }, + { + "cell_type": "markdown", + "id": "a14167fd-21f5-4929-9ec3-ff85a9a4de9e", + "metadata": {}, + "source": [ + "## Classification\n", + "- Train a random forest model to classify the category of a Stack Overflow question (as either Python, R, HTML or CSS)." + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "id": "319bf0c2-92d1-403b-acd9-919a3e21033f", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import RandomForestClassifier" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "6dd46eb2-445a-4e1f-97a0-8c995bfaf892", + "metadata": { + "height": 49 + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "from sklearn.model_selection import train_test_split" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "c6a79406-57bb-4480-9184-1ba9bebd5c36", + "metadata": { + "height": 83 + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(2000, 768)" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# re-load the dataset from file\n", + "so_df = pd.read_csv('so_database_app.csv')\n", + "X = question_embeddings\n", + "X.shape" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "id": "10826eca-8fa0-4ce7-9b93-aa3e8fb19e2e", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(2000,)" + ] + }, + "execution_count": 45, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y = so_df['category'].values\n", + "y.shape" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "a6a3ac12-b97a-4345-aea4-498de0babb38", + "metadata": { + "height": 83 + }, + "outputs": [], + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, \n", + " y, \n", + " test_size = 0.2, \n", + " random_state = 2)" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "id": "b65f8db9-7c39-42bd-ac01-8217688454ec", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "clf = RandomForestClassifier(n_estimators=200)" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "1e6a0d25-9708-41b8-a754-bdccf5b94b66", + "metadata": { + "height": 32 + }, + "outputs": [ + { + "data": { + "text/html": [ + "

RandomForestClassifier(n_estimators=200)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" + ], + "text/plain": [ + "RandomForestClassifier(n_estimators=200)" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "clf.fit(X_train, y_train)" + ] + }, + { + "cell_type": "markdown", + "id": "7d6eda9b-25f5-4cbd-8ab1-462361f48a21", + "metadata": {}, + "source": [ + "#### You can check the predictions on a few questions from the test set" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "9e134eb4-b3cd-425a-81dd-e2a96362c782", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [ + "y_pred = clf.predict(X_test)" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "id": "0805c099-1349-45a0-b1bc-47b64b15495a", + "metadata": { + "height": 49 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Accuracy: 0.7025\n" + ] + } + ], + "source": [ + "accuracy = accuracy_score(y_test, y_pred) # compute accuracy\n", + "print(\"Accuracy:\", accuracy)" + ] + }, + { + "cell_type": "markdown", + "id": "6ae498a1-26ee-4111-90ba-b625804353de", + "metadata": {}, + "source": [ + "#### Try out the classifier on some questions" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "id": "1641137e-f556-443b-b67a-7468229ce7ee", + "metadata": { + "height": 253 + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "For question 2, the prediction is `python`\n", + "The actual label is `python`\n", + "The question text is:\n", + "--------------------------------------------------\n", + "How do we test a specific method written in a list of files for functional testing in python

The project has so many modules. There are functional test cases being written for almost every api written like for GET requests, POST requests and PUT requests. To test an individual file we use the syntact pytest tests/file_name.py\n", + "but I want to test a specific method in that file. Is there any way to test it like that??

\n" + ] + } + ], + "source": [ + "# choose a number between 0 and 1999\n", + "i = 2\n", + "label = so_df.loc[i,'category']\n", + "question = so_df.loc[i,'input_text']\n", + "\n", + "# get the embedding of this question and predict its category\n", + "question_embedding = model.get_embeddings([question])[0].values\n", + "pred = clf.predict([question_embedding])\n", + "\n", + "print(f\"For question {i}, the prediction is `{pred[0]}`\")\n", + "print(f\"The actual label is `{label}`\")\n", + "print(\"The question text is:\")\n", + "print(\"-\"*50)\n", + "print(question)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "932aa937-9b26-4e5e-8242-001cc2794a75", + "metadata": { + "height": 32 + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/question_embeddings_app.pkl b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/question_embeddings_app.pkl new file mode 100644 index 0000000..89a3ae0 Binary files /dev/null and b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/question_embeddings_app.pkl differ diff --git a/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/so_database_app.csv b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/so_database_app.csv new file mode 100644 index 0000000..494a63e --- /dev/null +++ b/G-DeepLearning.AI/Q-Text-Embedding-GoogleCloud/L5-Applications/so_database_app.csv @@ -0,0 +1,156031 @@ +input_text,output_text,category +"python's inspect.getfile returns """"

Consider this code:

+
from sqlalchemy import exists
+import inspect
+
+print(inspect.getfile(exists))
+# Effectively calls:
+print(exists.__code__.co_filename)
+
+

On 2 systems I've tested it on it prints:

+
<string>
+<string>
+
+

What does it mean? Could anything be done to get a proper filepath?

","

<string> means that the function was defined dynamically by executing a string, rather than being defined in the text of a file. You can see this if you do:

+
exec('def foo(): return 1')
+print(inspect.getfile(foo))
+
+

I'm not sure why sqlAlchemy needs to define exists() this way. But I don't think there's any way to get the source file that does it.

",python +"Passing parameter to function while multithreading

I'm learning about multithreading and when I try to pass a parameter to my function in each thread it will process sequentially. Why is that?

+
import time
+import threading
+
+start = time.perf_counter()
+
+def sleepy_duck(name):
+    print(name, "duck going to sleep 1 sec")
+    time.sleep(1)
+    print(name, "waking up")    
+
+
+t1 = threading.Thread(target=sleepy_duck("Johny"))
+t2 = threading.Thread(target=sleepy_duck("Dicky"))
+t3 = threading.Thread(target=sleepy_duck("Loly"))
+
+t1.start()
+t2.start()
+t3.start()
+
+t1.join()
+t2.join()
+t3.join()
+
+finish = time.perf_counter()
+print("The ducks slept ", finish-start, " seconds.")
+
+

Result:

+
Johny duck going to sleep 1 sec
+Johny waking up
+Dicky duck going to sleep 1 sec
+Dicky waking up
+Loly duck going to sleep 1 sec
+Loly waking up
+The ducks slept  3.0227753  seconds.
+
","

Try this and note the difference:

+
import time
+import threading
+
+start = time.perf_counter()
+
+def sleepy_duck(name):
+    print(name, "duck going to sleep 1 sec")
+    time.sleep(1)
+    print(name, "waking up")    
+
+
+t1 = threading.Thread(target=sleepy_duck, args=("Johnny",))
+t2 = threading.Thread(target=sleepy_duck, args=("Dicky",))
+t3 = threading.Thread(target=sleepy_duck, args=("Loly",))
+
+t1.start()
+t2.start()
+t3.start()
+
+t1.join()
+t2.join()
+t3.join()
+
+finish = time.perf_counter()
+print("The ducks slept ", finish-start, " seconds.")
+
+

The way you did it originally the target was None

",python +"How do we test a specific method written in a list of files for functional testing in python

The project has so many modules. There are functional test cases being written for almost every api written like for GET requests, POST requests and PUT requests. To test an individual file we use the syntact pytest tests/file_name.py +but I want to test a specific method in that file. Is there any way to test it like that??

","

Duplicate of Is there a way to specify which pytest tests to run from a file?

+

In a few words, you can use the -k option of pytest to specify the name of the test you would like to run.

",python +"how can i remove the black bg color of an image with no alpha layer

So i started doing a game to pass the time and i don't know how to solve this issue: +my player is a part of a sprite sheet, the sprite sheet has a alpha layer so its transparent but when i divide my sprite sheet into small sprite, this alpha layer disapear and i have a black bg instead... I tried using set_colorkey([0, 0, 0]) to remove the black bg, but beceause my player is dark skinned, my player partially disappear. Any suggestion?

+
import pygame
+
+
+class Player(pygame.sprite.Sprite):
+    def __init__(self):
+        super().__init__()
+        self.image = pygame.image.load("assets/img/plr.png")
+        self.image = self.get_image(0, 0)
+        self.image = pygame.transform.scale(self.image, (96, 96))
+        self.image.set_colorkey([0, 0, 0])
+        self.rect = self.image.get_rect(center=(250, 250))
+
+    def get_image(self, x, y):
+        image = pygame.Surface([48, 48])
+        image.blit(self.image, (0, 0), (x, y, 48, 48))
+        return image
+
+    def update(self):
+        pass
+
","

The alpha channel "disappears" because you create a Surface without alpha channel (RGB). You have to use the SRCALPHA flag to create a Surface with an alpha channel (RGBA). Also see pygame.Surface:

+

image = pygame.Surface([48, 48])

+
image = pygame.Surface([48, 48], pygame.SRCALPHA)
+
+

For a surface without alpha channels you can set the transparent color key with set_colorkey:

+
image = pygame.Surface([48, 48])
+image.set_colorkey((0, 0, 0))
+
",python +"How to extract each sheet within an Excel file into an individual csv file as it is without appending any column or row?

I'm trying to extract each sheet in an Excel file into multiple CSVs. +For example Sheet1, Sheet2 and Sheet3 from Sample_1.xlsx into Sheet1.csv, Sheet2.csv and Sheet3.csv +The code I run is as below :

+
import pandas as pd
+
+dfs = pd.read_excel('Sample_1.xlsx', sheet_name=None)
+
+for sheet_name, data in dfs.items():
+    data.to_csv(f"{sheet_name}.csv")
+
+
+

It outputs all of the three CSVs as desired but each csv has an extra column (column A) with index starting 0,1,2..n . Why is that happening? and How do I get rid of it?

","

You need to specify the index parameter of pandas.DataFrame.to_csv as False

+

Replace :

+
data.to_csv(f"{sheet_name}.csv")
+
+

By :

+
data.to_csv(f"{sheet_name}.csv", index=False)
+
",python +"Screen Manager set/get TextInput when button pressed

All I'm trying to do is get and/or set the input from the TextInput: inside the GridLayout, inside the SeccondWindow. (id: "text_input") But after googling, and googling... all my attempts have failed.

+

I have tried

+
main_screen = self.manager.get_screen('second')
+main_screen.ids.text_input.text = "Something..."
+
+

Only to get the error "AttributeError: 'super' object has no attribute 'getattr'"

+

I've tried

+
text = self.root.ids["text_input"].text
+
+

But I get the error "AttributeError: 'SecondWindow' object has no attribute 'root'"

+

I've tried loads of things... +I'M GOING INSANE!! (And I'm dumb so please help!)

+

Here's my new_window.kv file

+
WindowManager:
+    transition: NoTransition()
+    FirstWindow:
+    SecondWindow:
+
+
+<FirstWindow>:
+    name: "first"
+
+    BoxLayout:
+        orientation: "vertical"
+        size: root.width, root.height
+
+        Button:
+            text: "Go To Next Screen"
+            on_release:
+                app.root.current = "second"
+
+
+<SecondWindow>:
+    name: "second"
+    GridLayout:
+        id: "Container"
+        cols: 2
+        rows: 1
+
+        ScrollView:
+            id: "SideMenuScrollView"
+            size_hint: ("0.3dp", 1)
+            do_scroll_y: True
+            do_scroll_x: False
+
+            StackLayout:
+                id: "SideMenuStack"
+                size_hint_y: None
+                height: self.minimum_height
+
+                Button:
+                    size_hint: (None, None)
+                    size: ("92dp", "92dp")
+
+                Button:
+                    size_hint: (None, None)
+                    size: ("92dp", "92dp")
+
+
+        GridLayout:
+            size_hint: (1, 1)
+            id: "MyGrid"
+            size: (1, 1)
+            spacing: 10
+            padding: 10
+            cols: 1
+            rows: 2
+
+            TextInput:
+                id: "text_input"
+                multiline: False
+                text: ""
+                size_hint: (1, None)
+                height: "30dp"
+
+
+            Button:
+                text: "Do Stuff"
+                on_release: root.DoStuff()
+                size_hint: (1, None)
+                height: "70dp"
+
+

Here's my code

+
from kivy.app import App
+from kivy.uix.screenmana.........
+
+class WindowManager(ScreenManager):
+    pass
+
+
+class FirstWindow(Screen):
+    pass
+
+
+class SecondWindow(Screen):
+    def DoStuff(self):
+
+        #
+        # text_input.text = "what ever..."
+        #
+
+
+kv = Builder.load_file('new_window.kv')
+
+
+class AwesomeApp(App):
+    def build(self):
+        return kv
+
+
+if __name__ == "__main__":
+    AwesomeApp().run()
+
+
+

Does anyone know how to get/set the TextInput .text value and DoStuff with it??

","

The main problem is in your kv file:

+
        TextInput:
+            id: "text_input"
+
+

If you define an id with enclosing ", those " become part of the id. You can do that, but it complicates accessing that id. A simpler approach is to just eliminate the ", like this:

+
        TextInput:
+            id: text_input
+
+

Then you can access the TextInput as:

+
class SecondWindow(Screen):
+    def DoStuff(self):
+        self.ids.text_input.text = 'Abba'
+
",python +"Group by, summarise and divide by the number of distinct months using Python

Assume I have a following data:

+
id  date        value
+1   2020-01-22  20
+1   2020-03-12  18
+1   2020-03-25  16
+2   2020-04-22  20
+2   2020-04-22  23
+
+

First I wish group by id and date and sum values for distinct dates. Then, I want to group by id to sum the total value and divide by the count of distinct months from date.

+

The first part is easy. I can simply do: df.groupby(["id", "date"]).sum(). I then get the following:

+
                value
+id  date        
+1   2020-01-22  20
+1   2020-03-12  18
+1   2020-03-25  16
+2   2020-04-22  43
+
+

But I do not only want to get the aggregate but the sum being divided by the number of unique months in the date. My idea for counting the unique months would be: len(pd.to_datetime(df["date"]).dt.to_period('M').unique()). However, I have no idea how to combine the two together.

+

Basically, the output I'm looking for is:

+
id  value_after_division
+1   27
+2   43
+
+

In simpler terms: 27=(20+18+16)/2 and 43=(43)/1.

","

You'd like to aggregate "number of unique months" and "total value", and divide them. You already had the latter part. For the former, if only we had a (temporary) column indicating the month. So we go:

+
# get hold on a grouper object after making month available
+g = df.assign(month=df.date.dt.month).groupby("id")
+
+# aggregate
+nuniq_mon = g["month"].nunique()
+total_val = g["value"].sum()
+
+# div is method way of /
+result = total_val.div(nuniq_mon)
+
+

to get

+
>>> result
+
+id
+1    27.0
+2    43.0
+dtype: float64
+
",python +"Why is text inside HTML tags getting translated when requested while Web Scraping?

I am learning a little bit about web scraping and currently i am trying to do a small project. So with this code I am storing the HTML code inside soup variable.

+
source=requests.get(URL)
+soup=BeautifulSoup(source.text,'html.parser')
+
+

The problem is: when I inspect the code inside my browser it looks like this:

+
<a ...>The Godfather</a>
+
+

but when I try to use it in my program only the text inside tag (The Godfather) gets translated to my native language (Кум):

+
<a ...>Кум</a>
+
+

I dont want it to get translated. +My browser is completely in English and I have no idea why is this happening. Any help would be much appreciated!

","

Try to specify Accept-Language HTTP header in your request:

+
import requests
+from bs4 import BeautifulSoup
+
+
+url = "https://www.imdb.com/search/title/?groups=top_100&sort=user_rating,desc"
+
+headers = {"Accept-Language": "en-US,en;q=0.5"}
+soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")
+
+
+for h3 in soup.select("h3"):
+    print(h3.get_text(strip=True, separator=" "))
+
+

Prints:

+
1. The Shawshank Redemption (1994)
+2. The Godfather (1972)
+3. The Dark Knight (2008)
+4. The Lord of the Rings: The Return of the King (2003)
+5. Schindler's List (1993)
+6. The Godfather Part II (1974)
+
+...
+
",python +"Python pandas df: if col_A contains a string from a list, append the string to col_B

I have a list of about 60 words and a data frame of over 7000 sentences. I would like to add a column for each line that contains a word from the list (some have multiple words from the list and some repeat words). I've tried a bunch of ways to no avail. Starting off with

+
list=['a', 'b', 'c', ...]
+    
+   for x in list:
+       if df["col_A].str.contains(x):
+          df[col_B].append(x)
+
+

but it returns an error

+
+

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

+
+

any help on how to fix this or possibly other ways to approach this would be much appreciated. New to stackoverflow and a only been coding for a few months if that helps gauge where I am at in terms of knowlage.

+

Edit: id like the new column to be of the words from the list that appear within the string from the existing one.

+

Also if it helps:its a movie script im trying to analyze where each row is a line from the script and who said it. I want to analyze how many times a word is said and who had favorite words.

","

try this:

+
list_words=["a",....]
+def add_list_words(sentences):
+ returned_list=[]
+ for word in list_words:
+   if word in sentences:
+     returned_list.append(word)
+ return list(set(returned_list)) # the set use to drop duplicate
+df["col_B"]=df["col_A"].apply(add_list_words)
+
",python +"Python how to add two maticies with different number of rows and columns?

Suppose I have two 2D matricies: [[1,2],[0,0]] and [[4,8],[0,0],[5,6]] and I want to sum them up and get the matrix [[5,10],[0,0],[5,6]]. How can I do it in the most easiest way without writing my own function? As I understood, numpy matricies don't support this.

+
import numpy as np
+m1 = np.array([[1, 2], [0, 0]])
+m2 = np.array([[4, 8], [0, 0], [5, 6]])
+res = m1+m2 
+
","
import numpy as np
+
+m1 = np.array([[1, 2], [0, 0]])
+m2 = np.array([[4, 8], [0, 0], [5, 6]])
+
+# Array size matching
+m1.resize(m2.shape) if m1.shape < m2.shape else m2.resize(m1.shape)
+
+answer = m1 + m2
+print(answer)
+
+

Output:

+
[[ 5 10]
+ [ 0  0]
+ [ 5  6]]
+
",python +"Beginner in Python: Trying to check for identical items in multiple lists

I'm a beginner trying to create a small Python project to help me find out which ingredient I might be allergic to from a group of four products. Ideally, I would like to input the ingredients of each product into a list format, and then return identical ingredients which appear in two or more of the products.

+

I'd like to input something like:

+
product_1 = ["polybutene", "cranberry seed oil", "beeswax"]
+product_2 = ["vegetable oil", "beeswax", "shea butter"]
+
+

and get a result like:

+
list1 = ["beeswax"]
+
+

I've tried to use compare_intersect but haven't made any progress. Thank you very much in advance!

","

If you want a list out you can do

+
list(set(product_1).intersection(set(product_2)))
+
+

Factored out to make each operation clear this looks like

+
set_1 = set(product_1)
+set_2 = set(product_2)
+
+intersection = set_1.intersection(set_2)
+
+result = list(intersection)
+
+

If you want to preserve duplicates you can implement this efficiently like so.

+
from collections import Counter
+def list_intersection(l1, l2):
+  c2 = Counter(l2)
+  result = []
+  for element in l1:
+    if c2[element] > 0:  # There are still more of those elements in the other list
+      # The element is shared between the lists
+      result.append(element)
+      c2[element] -= 1
+  return result
+
+

This will preserve the order of the first list, while only keeping the number of elements of the same type shared between the lists. Here's an example

+
list_intersection(['beeswax', 'test', 'other', 'beeswax', 'beeswax'],
+                  ['frank', 'green', 'test', 'beeswax', 'beeswax'])
+
+
+prints: ['beeswax', 'test', 'beeswax']
+
",python +"GroupBy results to list of dictionaries, Using the grouped by object in it

My DataFrame looks like so:

+
Date Column1 Column2
+1.1       A      1
+1.1       B      3
+1.1       C      4
+2.1       A      2
+2.1       B      3
+2.1       C      5
+3.1       A      1
+3.1       B      2
+3.1       C      2
+
+

And I'm looking to group it by Date and extract that data to a list of dictionaries so it appears like this:

+
[
+  {
+    "Date": "1.1",
+    "A": 1,
+    "B": 3,
+    "C": 4
+  },
+  {
+    "Date": "2.1",
+    "A": 2,
+    "B": 3,
+    "C": 5
+  },
+  {
+    "Date": "3.1",
+    "A": 1,
+    "B": 2,
+    "C": 2
+  }
+]
+
+

This is my code so far:

+
df.groupby('Date')['Column1', 'Column2'].apply(lambda g: {k, v for k, v in g.values}).to_list()
+
+

Using this method can't use my grouped by objects in the apply method itself:

+
[
+  {
+
+    "A": 1,
+    "B": 3,
+    "C": 4
+  },
+  {
+    "A": 2,
+    "B": 3,
+    "C": 5
+  },
+  {
+    "A": 1,
+    "B": 2,
+    "C": 2
+  }
+]
+
+

Using to_dict() giving me the option to reach the grouped by object, but not to parse it to the way I need.

+

Anyone familiar with some elegant way to solve it?

+

Thanks!!

","

You could first reshape your data using df.pivot, reset the index, and then apply to_dict to the new shape with the orient parameter set to "records". So:

+
import pandas as pd
+
+data = {'Date': ['1.1', '1.1', '1.1', '2.1', '2.1', '2.1', '3.1', '3.1', '3.1'],
+ 'Column1': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
+ 'Column2': [1, 3, 4, 2, 3, 5, 1, 2, 2]}
+
+df = pd.DataFrame(data)
+
+df_pivot = df.pivot(index='Date',columns='Column1',values='Column2')\
+    .reset_index(drop=False)
+result = df_pivot.to_dict('records')
+
+target = [{'Date': '1.1', 'A': 1, 'B': 3, 'C': 4},
+ {'Date': '2.1', 'A': 2, 'B': 3, 'C': 5},
+ {'Date': '3.1', 'A': 1, 'B': 2, 'C': 2}]
+
+print(result == target)
+# True
+
",python +"How to add/remove only specific blocks of XML to a new file?

I'm trying to filter an XML such that only specific blocks of XML would be needed I have the original XML like this

+
<PROJECT>
+  <BLOCKLIST>
+      <BLOCK>
+        <TASK>
+            <INSTALL_METHOD installer="TYPE 1" />
+            <FILE>
+                <INSTALL_OPTIONS option="signature"/>
+                <INSTALL_OPTIONS option="checksum"/>
+            </FILE>
+        </TASK>
+        <TASK>
+             <INSTALL_METHOD installer="TYPE 2" />
+             <FILE>
+                <INSTALL_OPTIONS option="signature"/>
+                <INSTALL_OPTIONS option="checksum"/>
+             </FILE>
+         </TASK>
+         <TASK>
+            <INSTALL_METHOD installer="TYPE 3" />
+            <FILE>
+                <INSTALL_OPTIONS option="signature"/>
+                <INSTALL_OPTIONS option="checksum"/>
+            </FILE>
+        </TASK>
+        <TASK>
+            <INSTALL_METHOD installer="TYPE 4" />
+            <FILE>
+                <INSTALL_OPTIONS option="signature"/>
+                <INSTALL_OPTIONS option="checksum"/>
+            </FILE>
+        </TASK>
+    </BLOCK>
+  </BLOCKLIST>
+</PROJECT>
+
+

Now I need to compare <INSTALL_METHOD installer="x" /> and move the entire TASK block to a new file , so for example, if I want only TYPE 1 and TYPE 3 the new.xml should look something like this

+
<PROJECT>
+<BLOCKLIST>
+    <BLOCK>
+      <TASK>
+        <INSTALL_METHOD installer="TYPE 1" />
+        <FILE>
+            <INSTALL_OPTIONS option="signature"/>
+            <INSTALL_OPTIONS option="checksum"/>
+        </FILE>
+      </TASK>
+      <TASK>
+        <INSTALL_METHOD installer="TYPE 3" />
+        <FILE>
+            <INSTALL_OPTIONS option="signature"/>
+            <INSTALL_OPTIONS option="checksum"/>
+        </FILE>
+      </TASK>
+    </BLOCK>
+</BLOCKLIST>
+</PROJECT>
+
+
+

I tried the below approach, but I'm getting the following error ValueError: list.remove(x): x not in list.

+
import xml.etree.ElementTree as ET
+
+tree = ET.parse("input.xml")
+root = tree.getroot()
+tasks = root.findall(".//BLOCKLIST/BLOCK/TASK")
+   
+for task in tasks:
+    install_method = task.find("INSTALL_METHOD")
+    if not install_method.get("installer") in ["TYPE 1" , "TYPE 3"]:
+        root.remove(task)
+
+tree.write("new.xml", encoding='UTF-8', xml_declaration=True)
+
","

The task is not a direct child of root, so you can't remove it like this. If you use lxml.etree instead of xml.etree.ElementTree you can get the task parent and use it to remove the task (the rest of the code is without change)

+
import lxml.etree as ET
+
+...
+if not install_method.get("installer") in ["TYPE 1", "TYPE 3"]:
+    task.getparent().remove(task)
+...
+
",python +"Hyperscience DatabaseAccessBlock - Test Connection Failing

I’m leveraging a DatabaseAccessBlock on the Hyperscience application (v34.0.3) to communicate with an external database. I’m not able to see the query in the UI and the test connection fails. I'm not finding much information regarding debugging database queries in the SDK; how do I debug this?

+

Here is my code snippet:

+
def build_query(submission: Any) -> Any:
+    table_name = 'table'
+    id = '1'
+    query = 'SELECT * FROM ' + table_name + ' WHERE 1 = 1 AND id = ' + id
+    return query
+
+cct_build_query = CodeBlock(
+    reference_name='build_query',
+    code=build_query,
+    code_input={'submission': load_submission.output()},
+    title='Build Query',
+    description='Build Query',
+)
+
+db_lookup = DatabaseAccessBlock(
+    reference_name='db_lookup',
+    title='Database Lookup',
+    description='Perform database lookup',
+    db_type='postgres',
+    database='<database_name>',
+    host='<hostname>',
+    username='<username>',
+    password='<password>',
+    port = 5432,
+    timeout = 200,
+    query= cct_build_query.output(),
+)
+
","

The Hyperscience UI does not show the query field if the query is dynamically drawing values from a previous block, but only when a static query has been defined within the DatabaseAccessBlock itself.

+

To test a connection, set a static query value, test the connection, and then revert to the dynamically set value. It seems that while a query is required to test the connection, the query does not have to be valid - the system simply checks if there is a value present in the query field to go on to test the connection.

+

You can change the db block to the following, for example:

+
db_lookup = DatabaseAccessBlock(
+    reference_name='db_lookup',
+    title='Database Lookup',
+    description='Perform database lookup',
+    db_type='postgres',
+    database='<database_name>',
+    host='<hostname>',
+    username='<username>',
+    password='<password>',
+    port = 5432,
+    timeout = 200,
+    query= select * from random_table,
+)
+
",python +"Why does pandas.DataFrame change the data source?

I'm learning Python, and I found a thing I can't understand.

+

I created a pandas.DataFrame from a ndarray, and then only modified the DF instead of ndarray.

+

And to my suprise, the ndarray has changed too! +Is the data cached inside DF? +If yes, why does they changed inside ndarray? +If no, how about a DF created without any source?

+
from pandas import DataFrame
+import numpy as np
+
+if __name__ == '__main__':
+    nda1 = np.zeros((3,3), dtype=float)
+    print(f'original nda1:\n{nda1}\n')
+
+    df1 = DataFrame(nda1)
+    print(f'original df1:\n{df1}\n')
+
+    df1.iat[2,2] = 999
+    #print(f'df1 in main:\n{df}\n')
+    print(f'nda1 after modify:\n{nda1}\n')
+
","

DataFrames are using numpy arrays under the hood. As you have a full homogeneous type, the array is kept as is.

+

You can check it with:

+
pd.DataFrame(nda1).values.base is nda1
+# True
+
+

You can force a copy to avoid the issue:

+
df1 = pd.DataFrame(nda1.copy())
+
+

or copy from within the constructor:

+
df1 = pd.DataFrame(nda1, copy=True)
+
+

check that the underlying array is different:

+
pd.DataFrame(nda1, copy=True).values.base is nda1
+# False
+
",python +"Why the horizontal scroll bar does not show up in PYQT6 QtextEdit widget

In the example below I am using PyQt6 to create text with long lines that exceed the QtextEdit widget's viewing size vertically and horizontally. The vertical scroll bar shows up however, the horizontal scroll bar does not show up. Any help with this issue is appreciated.

+
import sys
+from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton,
+    QWidget, QHBoxLayout, QVBoxLayout, QTextEdit)
+from PyQt6.QtCore import QSize
+
+class MainWindow(QMainWindow):
+    def __init__(self):
+        super().__init__()
+        self.setWindowTitle("Example")
+        self.setContentsMargins(20,20,20,20)
+        self.setFixedSize(QSize(800, 600)) 
+        self.setWindowTitle("Example")     
+        layout1 = QHBoxLayout()
+        layout2 = QVBoxLayout()
+        self.output_text = QTextEdit()
+        self.button_start = QPushButton("Start")
+        self.button_start.clicked.connect(self.start)
+        layout1.addLayout(layout2)
+        layout2.addWidget(self.output_text)
+        layout2.addWidget(self.button_start)        
+        widget = QWidget()
+        widget.setLayout(layout1)
+        self.setCentralWidget(widget)
+
+    def start(self):
+        for i in range (1, 30):
+            self.output_text.append("Line " + str(i) + ": This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. ")
+        
+app = QApplication(sys.argv)
+window = MainWindow()
+window.show()
+app.exec()
+
","

If you want a horizontal scrollbar, you will need to set the QTextEdit column width higher than the QTextEdit area. So let's say for example 1000 will work for your code.

+
import sys
+from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton,
+    QWidget, QHBoxLayout, QVBoxLayout, QTextEdit)
+from PyQt6.QtCore import QSize, Qt
+
+class MainWindow(QMainWindow):
+    def __init__(self):
+        super().__init__()
+        self.setWindowTitle("Example")
+        self.setContentsMargins(20,20,20,20)
+        self.setFixedSize(QSize(800, 600)) 
+        self.setWindowTitle("Example")     
+        layout1 = QHBoxLayout()
+        layout2 = QVBoxLayout()
+        self.output_text = QTextEdit()
+        self.output_text.setLineWrapColumnOrWidth(1000) #Here you set the width you want
+        self.output_text.setLineWrapMode(QTextEdit.LineWrapMode.FixedPixelWidth)
+        self.button_start = QPushButton("Start")
+        self.button_start.clicked.connect(self.start)
+        layout1.addLayout(layout2)
+        layout2.addWidget(self.output_text)
+        layout2.addWidget(self.button_start)        
+        widget = QWidget()
+        widget.setLayout(layout1)
+        self.setCentralWidget(widget)
+
+    def start(self):
+        for i in range (1, 30):
+            self.output_text.append("Line " + str(i) + ": This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. ")
+        
+app = QApplication(sys.argv)
+window = MainWindow()
+window.show()
+app.exec()
+
+

And here is the result: +

+

Tell me if this wasn't what you were looking for or if it doesn't work for you.

",python +"Convert 16 bit hex value to FP16 in Python?

I'm trying to write a basic FP16 based calculator in python to help me debug some hardware. Can't seem to find how to convert 16b hex values unto floating point values I can use in my code to do the math. I see lots of online references to numpy but I think the float16 constructor expects a string like float16("1.2345"). I guess what I'm looking for is something like float16("0xabcd").

+

Thanks!

","

The numpy.float16 is indeed a signed floating point format with a 5-bit exponent and 10-bit mantissa.

+

To get the result of your example:

+
import numpy as np
+
+np.frombuffer(b'\xab\xcd', dtype=np.float16, count=1)
+
+

Result:

+
array([-22.67], dtype=float16)
+
+

Or, to show how you can encode and decode the other example 1.2345:

+
import numpy as np
+
+a = np.array([1.2345], numpy.float16)
+b = a.tobytes()
+print(b)
+c = np.frombuffer(b, dtype=np.float16, count=1)
+print(c)
+
+

Result:

+
b'\xf0<'
+[1.234]
+
+

If you literally needed to turn the string you provided into an FP16:

+
import numpy as np
+
+s = "0xabcd"
+b = int("0xabcd", base=16).to_bytes(2, 'big')
+print(b)
+c = np.frombuffer(b, dtype=np.float16, count=1)
+print(c)
+
+

Output:

+
b'\xab\xcd'
+[-22.67]
+
",python +"Discord.py: Is it possible to use one cogs function into another cogs?

Hello I just want to use the async module on the first cogs into another by so that the code wont be too long for a single file and maximize the code reuse:

+

Module_cogs_1.py :

+
class Music_base(commands.Cog):
+    def __init__(self, bot):
+        self.bot = bot
+
+    # this is the module that to be imported
+
+    async def insert_player_song(self, ctx, track, track_index):
+        player = self.bot.lavalink.player_manager.get(ctx.guild.id)
+        player.add(requester=ctx.author.id, track=track, index=track_index)
+
+
+

Module_cogs_2.py :

+
class Module_test(commands.Cog):
+    def __init__(self, bot):
+        self.bot = bot
+    @commands.command(aliases=['test'])
+    async def test_track(self, ctx, track_index :typing.Optional[int]=0, *, query:str):
+    # accessing the async module from Module_cogs_1.py
+    await Music_base.insert_player_song(self, ctx, track, track_index)
+
+
+

If imported locally i can used as await self.insert_player_song() but when i try to import outside or in second file without self on the argument await Music_base.insert_player_song(ctx, track, track_index):

+
Traceback (most recent call last):
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
+    await ctx.command.invoke(ctx)
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
+    await injected(*ctx.args, **ctx.kwargs)
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
+    raise CommandInvokeError(exc) from exc
+discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: insert_player_song() missing 1 required positional argument: 'track_index'
+
+
+

But when adding the self onto the argument await Music_base.insert_player_song(self, ctx, track, track_index)

+
The above exception was the direct cause of the following exception:
+
+Traceback (most recent call last):
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
+    await ctx.command.invoke(ctx)
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
+    await injected(*ctx.args, **ctx.kwargs)
+  File "/home/vee/sauce-v3x/venv/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
+    raise CommandInvokeError(exc) from exc
+discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Music_base' object has no attribute 'guild_queues'
+
+

I hope you can understand guys and thank you so much in advance

","

Non-static methods can't be called without an instance of the class.

+

You should be able to get the created instance of the class using bot.get_cog passing the name of the Cog.

+

Then you can use that instance to call the method.

+
music_base = self.bot.get_cog("Music_base")
+music_base.func(ctx, ...)
+
+

If it is a command you want to run, you can also get the command with bot.get_command, store it in a variable, and execute it as a function.

",python +"ModuleNotFoundError: No module named 'xxx' with my custom type in Visual Studio code

I try to run the code below by clicking the red box Run Python File in the screenshot below :

+

car_client.py

+
from MyLib.car import Car
+
+car = Car()
+print(car.get_name())
+
+

But I get the error below:

+
+
from MyLib.car import Car 
+
+

ModuleNotFoundError: No module named 'MyLib'

+
+

car.py

+
class Car:
+   def get_name(self):
+      return 'BMW'
+
+

","

Add the following to the top of the code in the car_client.py file:

+
import sys
+sys.path.append("./MyLib")
+
+

and modify the import as

+
from car import Car
+
+

the code will work fine

+

",python +"Group data in pivot Pandas

hello I made a table with the help of a pandas, then I created a pivot with two indexes., I would like to group this data like that, but one index was the header of another. Below I will show what is happening in the tables and what I would like the result +Table:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameLangSkillCorp
Michaeljava2Google
PiterC++3Facebook
Cristianopython5Google
Michaeljava1Facebook
PiterC++2Google
Cristianopython3Facebook
Michaeljava4Google
PiterC++5Facebook
Cristianopython1Google
Michaelpython2Facebook
+
+

I used:

+
pivot = pd.pivot_table(df, values="Skill", index=["Corp", "Name"], columns = "Lang", aggfunc="sum")
+
+
+

and I have pivot:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CorpNameC++javapython
FacebookCristianonannan3
FacebookMichaelnan12
FacebookPiter8nannan
GoogleCristianonannan6
GoogleMichaelnan6nan
GooglePiter2nannan
+
+

the result I would like:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameC++javapython
Facebooksum_fbsum_fbsum_fb
Cristianonannan3
Michaelnan12
Piter8nannan
Googlesum_googlesum_googlesum_google
Cristianonannan6
Michaelnan6nan
Piter2nannan
+
+

Thank You in advance

","

You can aggregate sum by Corp level, which is first by GroupBy.sum, append index to MultiIndex with same values:

+
df1 = (pivot.groupby(level=0).sum()
+            .assign(Name = lambda x: x.index)
+            .set_index('Name', append=True))
+
+

Or use level=[0,0] for MultiIndex, only necessary set names by DataFrame.rename_axis:

+
df1 = pivot.groupby(level=[0,0]).sum().rename_axis(['Corp','Name'])
+print (df1)         
+Lang               C++  java  python
+Corp     Name                       
+Facebook Facebook  8.0   1.0     5.0
+Google   Google    2.0   6.0     6.0
+
+

Then is appended pivot DataFrame by concat, but is necessary sorting for correct ordering by first level of MultiIndex with DataFrame.sort_index, remove first level Corp by DataFrame.droplevel and last convert Name to column with remove columns name Lang by DataFrame.rename_axis:

+
df = (pd.concat([df1, pivot])
+        .sort_index(level=0, sort_remaining=False)
+        .droplevel(0)
+        .reset_index()
+        .rename_axis(None, axis=1))
+print (df)
+        Name  C++  java  python
+0   Facebook  8.0   1.0     5.0
+1  Cristiano  NaN   NaN     3.0
+2    Michael  NaN   1.0     2.0
+3      Piter  8.0   NaN     NaN
+4     Google  2.0   6.0     6.0
+5  Cristiano  NaN   NaN     6.0
+6    Michael  NaN   6.0     NaN
+7      Piter  2.0   NaN     NaN
+
",python +"Should I retrain the entire model with additional data?

I trained a model with the default training data. However, when testing on examples from production, the testing accuracy is very low. Do I have to add new data from production? Is it necessary to train the entire model again? Should I use all new data or only some of it? I have tried using all the new data. This is what my code looks like:

+
    # In[]: Retrain the module(s) with the new data: Strategy 1: All old+new data
+     model=load_model(‘model.h5’)
+    (x_train_old, y_train_old)=dataset.load_old_data()
+    (x_train_new, y_train_new)=dataset.load_new_data()
+    x_train=x_train_old+x_train_new
+    y_train=y_train_old+y_train_new
+
+    model.fit(x_train,y_train, epoch=nb_epoch,batch_size=128)
+    
+
+
    # In[]: Retrain the module(s) with the new data: Strategy 2: Only new data
+    model=load_model(‘model.h5’)
+    (x_train_new, y_train_new)=dataset.load_new_data()
+
+    model.fit(x_train_new,y_train_new, epoch=nb_epoch,batch_size=128)
+    
+
+

Here, model.h5 is the already trained module.

","

Yes, your should retrain then model with the new data. This is known as MLops in which you closed check the model accuracy after it is gone on production and it the model accuracy is decreasing with the surge of new data. you retrain the model. so do retrain them model on new data.

",python +"Django model auto update status when the medicine is expired

How to Auto update the status when the medicine is expired? for example, I created medicine record and set the expirationdate to july 2022, if the current date is greater than the expirationdate it will update the status of medicine to "Expired", How do I do that?

+
class Medicine(models.Model):
+    medstatus = [
+        ("Expired", "Expired"),
+        ("Active", "Active")
+    ]
+    description = models.CharField(max_length=50, null=True)
+    expirationDate = models.DateField(null=True)
+    status = models.CharField(max_length=50, choices=medstatus,  null=True)
+
","

Create crontab for one time in a day as:

+
#this is example for each day 00:00 sending get request to you api
+0 0 * * * /usr/bin/curl --silent http://example.com/your_views_url/ &>/dev/null
+
+

This is good and easy to understand cronjob generator:

+

https://crontab.guru/#0_0_*_*_*

+

Cronjob will trigger a view, which will search for a medicine, and change its status:

+

urls.py:

+
path("your_views_url", views.your_view_name_here),
+
+

views.py:

+
from django.http import HttpResponse
+from datetime import datetime
+
+def your_view_name_here(request):
+    now = datetime.today()
+    
+    #this will return a queryset of all medecine which you need to change status
+    all_target_medecine = Medicine.objects.filter(medstatus = "Active", expirationDate__lt = now)
+
+    for medecine in all_target_medecine:
+        medecine.medstatus = "Expired"
+        medecine.save()
+    return HttpResponse("Ok")
+
",python +"Aggregate points into a grid using Polars

I have a points dataset in the following format (x, y, value), is it possible to get aggregated dataset using Polars native (maybe even lazy) code as much as possible?

+

Basically I want to create a virtual grid and then sum all the points in respective grid cells, x_step and y_step being grid cell dimensions. The output would be a dataset with columns (cell_x, cell_y, agg_value) while cell_x and cell_y columns only taking values divisible by my predefined steps (representing bottom left coordinate of the grid cell), and agg_value being a sum of all point values inside the cell:
+(cell_x >= x and x < cell_x + x_step) and (cell_y >= y and y < cell_y + y_step).

+

Currently I am iterating from start, incrementing my variable cell_x by x_step and the same for Y axis in a nested loop. Then I call sum on the filtered subset (cell) of points and I output one row to the output cell. It is rather slow in Python.

+

Here is a visual example, all points have value of 1 for simplicity:
+

","

Edit: As of Polars 0.14.1, we can use the // operator as floor division instead of using floor, so that the algorithm becomes:

+
step_x = 2
+step_y = 2
+(
+    df.with_columns(
+        [
+            ((pl.col("x") // step_x) * step_x).alias("cell_x"),
+            ((pl.col("y") // step_y) * step_y).alias("cell_y"),
+        ]
+    )
+    .groupby(["cell_x", "cell_y"])
+    .agg(
+        [
+            pl.col("val").sum().alias("agg_value"),
+        ]
+    )
+    .sort(["cell_x", "cell_y"]).collect()
+)
+
+

One easy (and performant) way to solve this is to use the floor function to calculate the grid coordinates. We can easily accomplish all of this in Lazy mode, and using only Polars Expressions. (And best of all, no slow nested for loops.)

+

Let's start with your data. We'll put the DataFrame in Lazy mode.

+
import polars as pl
+df = (
+    pl.DataFrame(
+        {
+            "x": [0.5, 2, 2.5, 5.5],
+            "y": [1.5, 2.5, 3.5, 3.5],
+            "val": [1, 1, 1, 1],
+        }
+    )
+).lazy()
+df.collect()
+
+
shape: (4, 3)
+┌─────┬─────┬─────┐
+│ x   ┆ y   ┆ val │
+│ --- ┆ --- ┆ --- │
+│ f64 ┆ f64 ┆ i64 │
+╞═════╪═════╪═════╡
+│ 0.5 ┆ 1.5 ┆ 1   │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
+│ 2.0 ┆ 2.5 ┆ 1   │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
+│ 2.5 ┆ 3.5 ┆ 1   │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
+│ 5.5 ┆ 3.5 ┆ 1   │
+└─────┴─────┴─────┘
+
+

We can aggregate the values into grid cells as follows:

+
step_x = 2
+step_y = 2
+(
+    df.with_columns(
+        [
+            ((pl.col("x") / step_x).floor() * step_x).alias("cell_x"),
+            ((pl.col("y") / step_y).floor() * step_y).alias("cell_y"),
+        ]
+    )
+    .groupby(["cell_x", "cell_y"])
+    .agg(
+        [
+            pl.col("val").sum().alias("agg_value"),
+        ]
+    )
+    .sort(["cell_x", "cell_y"])
+    .collect()
+)
+
+
shape: (3, 3)
+┌────────┬────────┬───────────┐
+│ cell_x ┆ cell_y ┆ agg_value │
+│ ---    ┆ ---    ┆ ---       │
+│ f64    ┆ f64    ┆ i64       │
+╞════════╪════════╪═══════════╡
+│ 0.0    ┆ 0.0    ┆ 1         │
+├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
+│ 2.0    ┆ 2.0    ┆ 2         │
+├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
+│ 4.0    ┆ 2.0    ┆ 1         │
+└────────┴────────┴───────────┘
+
+

Since the calculation of the coordinates is in a with_columns context, they will run in parallel.

+

Other Notes

+

To trace how the algorithm maps each point to the lower-left coordinate of the grid that contains it, just comment out the groupby and agg methods.

+
step_x = 2
+step_y = 2
+(
+    df.with_columns(
+        [
+            ((pl.col("x") / step_x).floor() * step_x).alias("cell_x"),
+            ((pl.col("y") / step_y).floor() * step_y).alias("cell_y"),
+        ]
+    )
+    .sort(["cell_x", "cell_y"])
+    .collect()
+)
+
+
shape: (4, 5)
+┌─────┬─────┬─────┬────────┬────────┐
+│ x   ┆ y   ┆ val ┆ cell_x ┆ cell_y │
+│ --- ┆ --- ┆ --- ┆ ---    ┆ ---    │
+│ f64 ┆ f64 ┆ i64 ┆ f64    ┆ f64    │
+╞═════╪═════╪═════╪════════╪════════╡
+│ 0.5 ┆ 1.5 ┆ 1   ┆ 0.0    ┆ 0.0    │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 2.0 ┆ 2.5 ┆ 1   ┆ 2.0    ┆ 2.0    │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 2.5 ┆ 3.5 ┆ 1   ┆ 2.0    ┆ 2.0    │
+├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 5.5 ┆ 3.5 ┆ 1   ┆ 4.0    ┆ 2.0    │
+└─────┴─────┴─────┴────────┴────────┘
+
+

Also, I was careful to design the algorithm to work with negative grid coordinates (if you need that). In general, you have to be careful to distinguish between "truncating" and "casting" which converts -2.5 to -2, versus "floor" which converts -2.5 to -3. (We want "floor" in this case.)

+

For example:

+
import numpy as np
+
+rng = np.random.default_rng(1)
+nbr_rows = 10
+df = (
+    pl.DataFrame(
+        {
+            "x": rng.uniform(-10, 10, nbr_rows),
+            "y": rng.uniform(-10, 10, nbr_rows),
+            "val": rng.integers(1, 10, nbr_rows),
+        }
+    )
+    .with_columns([pl.col(["x", "y"]).round(1).keep_name()])
+    .sort(["x", "y"])
+    .lazy()
+)
+df.collect()
+
+
shape: (10, 3)
+┌──────┬──────┬─────┐
+│ x    ┆ y    ┆ val │
+│ ---  ┆ ---  ┆ --- │
+│ f64  ┆ f64  ┆ i64 │
+╞══════╪══════╪═════╡
+│ -9.4 ┆ -4.8 ┆ 9   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ -7.1 ┆ -3.4 ┆ 1   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ -3.8 ┆ -3.9 ┆ 5   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ -1.8 ┆ -1.9 ┆ 9   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ -1.5 ┆ -0.9 ┆ 5   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ 0.2  ┆ 5.1  ┆ 1   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ 1.0  ┆ -5.9 ┆ 7   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ 6.6  ┆ -7.3 ┆ 2   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ 9.0  ┆ 0.8  ┆ 7   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
+│ 9.0  ┆ 5.8  ┆ 3   │
+└──────┴──────┴─────┘
+
+

The algorithm maps each point to lower-left grid coordinates as follows:

+
shape: (10, 5)
+┌──────┬──────┬─────┬────────┬────────┐
+│ x    ┆ y    ┆ val ┆ cell_x ┆ cell_y │
+│ ---  ┆ ---  ┆ --- ┆ ---    ┆ ---    │
+│ f64  ┆ f64  ┆ i64 ┆ f64    ┆ f64    │
+╞══════╪══════╪═════╪════════╪════════╡
+│ -9.4 ┆ -4.8 ┆ 9   ┆ -10.0  ┆ -6.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ -7.1 ┆ -3.4 ┆ 1   ┆ -8.0   ┆ -4.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ -3.8 ┆ -3.9 ┆ 5   ┆ -4.0   ┆ -4.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ -1.8 ┆ -1.9 ┆ 9   ┆ -2.0   ┆ -2.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ -1.5 ┆ -0.9 ┆ 5   ┆ -2.0   ┆ -2.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 1.0  ┆ -5.9 ┆ 7   ┆ 0.0    ┆ -6.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 0.2  ┆ 5.1  ┆ 1   ┆ 0.0    ┆ 4.0    │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 6.6  ┆ -7.3 ┆ 2   ┆ 6.0    ┆ -8.0   │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 9.0  ┆ 0.8  ┆ 7   ┆ 8.0    ┆ 0.0    │
+├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
+│ 9.0  ┆ 5.8  ┆ 3   ┆ 8.0    ┆ 4.0    │
+└──────┴──────┴─────┴────────┴────────┘
+
+
",python +"How to save a DataFrame to excel with caption in Python

I'm trying to set a caption for my DataFrame and export it to excel but when I check the excel workbook the caption is not reflected.

+

+
+
import pandas as pd
+
+data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}
+
+df=pd.DataFrame(data)
+
+df.style.set_caption(""This is caption"").hide(axis='index').to_excel(""output.xlsx"", engine='xlsxwriter')
+
+
+

+

Can anyone please help me to export the DataFrame with caption to xlsx?

+

Thanks in advance!

","

If you want to write on the first row, you can use:

+
with pd.ExcelWriter('output.xlsx') as writer:
+    df.to_excel(writer, sheet_name='Data', index=False, startrow=1)
+    ws = writer.book.get_worksheet_by_name('Data')
+    ws.write('A1', 'This is a caption')
+
+

",python +"zipfile.BadZipFile: File is not a zip file when using ""openpyxl"" engine

I have created a script which dumps the excel sheets stored in S3 into my local postgres database. I've used pandas read_excel and ExcelFile method to read the excel sheets. +Code for the same can be found here.

+
import boto3
+import pandas as pd
+import io
+import os
+from sqlalchemy import create_engine
+import xlrd
+
+os.environ["AWS_ACCESS_KEY_ID"] = "xxxxxxxxxxxx"
+os.environ["AWS_SECRET_ACCESS_KEY"] = "xxxxxxxxxxxxxxxxxx"
+s3 = boto3.client('s3')
+
+obj = s3.get_object(Bucket='bucket-name', Key='file.xlsx')
+data = pd.ExcelFile(io.BytesIO(obj['Body'].read()))
+print(data.sheet_names)
+a = len(data.sheet_names)
+
+engine1 = create_engine('postgresql://postgres:postgres@localhost:5432/postgres')
+for i in range(a):
+    df = pd.read_excel(io.BytesIO(obj['Body'].read()),sheet_name=data.sheet_names[i], engine='openpyxl')
+    df.to_sql("test"+str(i), engine1, index=False)
+
+

Basically, code parses the S3 bucket and runs in a loop. For each sheet, it creates a table +and dumps the data from sheet in that table.

+

Where I'm having trouble is, when I run this code, I get this error.

+
df = pd.read_excel(io.BytesIO(obj['Body'].read()),sheet_name=data.sheet_names[i-1], engine='openpyxl')
+zipfile.BadZipFile: File is not a zip file
+
+

This is coming after I added 'openpyxl' engine in read_excel method. When I remove the engine, I get this error.

+
raise ValueError(
+ValueError: Excel file format cannot be determined, you must specify an engine manually.
+
+

Please note that I can print the connection to database, so there is no problem in connectivity, and I'm using latest version of python and pandas. Also, I can get all the sheet_names in the excel file so I'm able to reach to that file as well.

+

Many Thanks!

","

You are reading the obj twice, fully:

+
    +
  1. data = pd.ExcelFile(io.BytesIO(obj['Body'].read()))
  2. +
  3. pd.read_excel(io.BytesIO(obj['Body'].read()), ...)
  4. +
+

Your object can only be .read() once, second read produce nothing, an empty b"".

+

In order to avoid re-reading the S3 stream many times, you could store it once in a BytesIO, and rewind that BytesIO with seek.

+
buf = io.BytesIO(obj["Body"].read())
+
+pd.ExcelFile(buf)
+
+buf.seek(0)
+
+pd.read_excel(buf, ...)
+
+# repeat
+
",python +"Running task / function in the background

i wrote a program to capture the position of license plate with my webcam feed using YOLOv4. The result of the detection is then passed to easyOCR to do character identification. Right now, im calling the OCR function in the while loop everytime a detection occured. Is there a way to call the OCR function outside the loop without stopping the webcam feed ? some people suggested me to use queue or sub process but im not quite familiar with the concept. Any help would be very appreciated

+
#detection
+while 1:
+    #_, pre_img = cap.read()
+    #pre_img= cv2.resize(pre_img, (640, 480))
+    _, img = cap.read()
+    #img = cv2.flip(pre_img,1)
+    hight, width, _ = img.shape
+    blob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)
+
+    net.setInput(blob)
+
+    output_layers_name = net.getUnconnectedOutLayersNames()
+
+    layerOutputs = net.forward(output_layers_name)
+
+    boxes = []
+    confidences = []
+    class_ids = []
+
+    for output in layerOutputs:
+        for detection in output:
+            score = detection[5:]
+            class_id = np.argmax(score)
+            confidence = score[class_id]
+            if confidence > 0.7:
+                center_x = int(detection[0] * width)
+                center_y = int(detection[1] * hight)
+                w = int(detection[2] * width)
+                h = int(detection[3] * hight)
+                x = int(center_x - w / 2)
+                y = int(center_y - h / 2)
+                boxes.append([x, y, w, h])
+                confidences.append((float(confidence)))
+                class_ids.append(class_id)
+
+    indexes = cv2.dnn.NMSBoxes(boxes, confidences, .5, .4)
+
+    boxes = []
+    confidences = []
+    class_ids = []
+
+    for output in layerOutputs:
+        for detection in output:
+            score = detection[5:]
+            class_id = np.argmax(score)
+            confidence = score[class_id]
+            if confidence > 0.5:
+                center_x = int(detection[0] * width)
+                center_y = int(detection[1] * hight)
+                w = int(detection[2] * width)
+                h = int(detection[3] * hight)
+
+                x = int(center_x - w / 2)
+                y = int(center_y - h / 2)
+
+                boxes.append([x, y, w, h])
+                confidences.append((float(confidence)))
+                class_ids.append(class_id)
+
+    indexes = cv2.dnn.NMSBoxes(boxes, confidences, .8, .4)
+    font = cv2.FONT_HERSHEY_PLAIN
+    colors = np.random.uniform(0, 255, size=(len(boxes), 3))
+    if len(indexes) > 0:
+        for i in indexes.flatten():
+            x, y, w, h = boxes[i]
+            label = str(classes[class_ids[i]])
+            confidence = str(round(confidences[i], 2))
+            color = colors[i]
+            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
+            detected_image = img[y:y+h, x:x+w]
+            cv2.putText(img, label + " " + confidence, (x, y + 400), font, 2, color, 2)
+            #print(detected_image)
+            cv2.imshow('detection',detected_image)
+
+            result = OCR(detected_image)
+            print(result)
+
+

Function for OCR

+
def OCR(cropped_image):
+
+    result = reader.readtext(cropped_image)
+    text = ''
+    for result in result:
+        text += result[1] + ' '
+
+    spliced = (remove(text)).upper()
+    return spliced
+
","

You could run the OCR function on an other thread with the thread library like so:

+
import time  # not necessary only to simulate work time
+import _thread as thread  # in python 3 the name has changed to _thread
+
+
+def OCR(cropped_image):
+
+    result = reader.readtext(cropped_image)
+    text = ''
+    for result in result:
+        text += result[1] + ' '
+
+    spliced = (remove(text)).upper()
+    print(spliced) # you would have to print the result in the OCR function because you can't easily return stuff
+
+
+while 1:
+    time.sleep(5)  # simulating some work time
+    print("main")
+
+    detected_image = 1
+    thread.start_new_thread(OCR, (detected_image,)) # calling the OCR function on a new thread.
+
+

I hope it will help you...

",python +"Pydantic exclude field from __eq__ to avoid recursion error

I have a pydantic model like this:

+
class SomeModel(pydantic.BaseModel):
+    name: str
+    content: str
+    previous_model: typing.Optional["SomeModel"] = None
+
+

My code look like this, this is greatly simplified, In my real code there are many and circular dependencies occur by chance occasionally rather than being purposefully created:

+
models = [
+   SomeModel("bob", "2"),
+   SomeModel("bob", "2"),
+]
+models[0].previous_model = models[1]
+models[1].previous_model = models[0]
+
+models.remove(models[0])
+
+

This throws the following error:

+
File "c:\Users\username\project-name\src\main.py", line 108, in run_all
+    models.remove(models[0])
+  File "pydantic\main.py", line 902, in pydantic.main.BaseModel.__eq__
+  File "pydantic\main.py", line 445, in pydantic.main.BaseModel.dict
+  File "pydantic\main.py", line 861, in _iter
+  File "pydantic\main.py", line 736, in pydantic.main.BaseModel._get_value
+  File "pydantic\main.py", line 445, in pydantic.main.BaseModel.dict
+  File "pydantic\main.py", line 861, in _iter
+  File "pydantic\main.py", line 736, in pydantic.main.BaseModel._get_value
+  File "pydantic\main.py", line 445, in pydantic.main.BaseModel.dict
+  File "pydantic\main.py", line 861, in _iter
+  File "pydantic\main.py", line 736, in pydantic.main.BaseModel._get_value
+  File "pydantic\main.py", line 445, in pydantic.main.BaseModel.dict
+  File "pydantic\main.py", line 861, in _iter
+  File "pydantic\main.py", line 736, in pydantic.main.BaseModel._get_value
+  File "pydantic\main.py", line 445, in pydantic.main.BaseModel.dict
+  File "pydantic\main.py", line 861, in _iter
+
+... Snip several hunderd more lines
+
+  File "pydantic\main.py", line 734, in pydantic.main.BaseModel._get_value
+  File "pydantic\main.py", line 304, in pydantic.main.ModelMetaclass.__instancecheck__
+RecursionError: maximum recursion depth exceeded
+
+

I don't really need the previous_model field to be included in the equality at all. Is there a way to exclude it so that my stack doesn't overflow? This field is irrelevant for the purpose equality in this case.

","

When pydantic generates __repr__, it iterates over its arguments. That makes sense, that's one of the key selling points. But it doesn't work well in your scenario, you'd have to omit previous_node from __repr__ to make it work. You can either skip previous_node in __repr_args__ or return something simpler in __repr__. To give you a very simplified example that is working

+

+import typing
+
+import pydantic
+
+
+class SomeModel(pydantic.BaseModel):
+    name: str
+    content: str
+    previous_model: typing.Optional["SomeModel"] = None
+
+    def __repr__(self):
+        return self.name
+
+
+SomeModel.update_forward_refs()
+
+
+models = [
+   SomeModel(name="bob", content="2"),
+   SomeModel(name="bob", content="2"),
+]
+models[0].previous_model = models[1]
+models[1].previous_model = models[0]
+
+models.remove(models[0])
+
+print(models)
+
+

Less simple version that's closer to how pydantic behaves but will also work in your case

+

+import typing
+
+import pydantic
+
+
+class SomeModel(pydantic.BaseModel):
+    name: str
+    content: str
+    previous_model: typing.Optional["SomeModel"] = None
+
+    def __repr_args__(self, *args, **kwargs):
+        args = self.dict(exclude={'previous_model',})
+        return list(args.items())
+
+
+SomeModel.update_forward_refs()
+
+
+models = [
+   SomeModel(name="bob", content="2"),
+   SomeModel(name="bob", content="2"),
+]
+models[0].previous_model = models[1]
+models[1].previous_model = models[0]
+
+models.remove(models[0])
+
",python +"Convert a list of ""dictionary of dictionaries"" to a dataframe

I have a list of "dictionary of dictionaries" that looks like this:

+
lis = [{'Health and Welfare Plan + Change Notification': {'evidence_capture': 'null',
+   'test_result_justification': 'null',
+   'latest_test_result_date': 'null',
+   'last_updated_by': 'null',
+   'test_execution_status': 'Not Started',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Computations': {'evidence_capture': 'null',
+   'test_result_justification': 'null',
+   'latest_test_result_date': 'null',
+   'last_updated_by': 'null',
+   'test_execution_status': 'Not Started',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Data Agreements': {'evidence_capture': 'null',
+   'test_result_justification': 'Due to the Policy',
+   'latest_test_result_date': '2019-10-02',
+   'last_updated_by': 'null',
+   'test_execution_status': 'In Progress',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Data Elements': {'evidence_capture': 'null',
+   'test_result_justification': 'xxx',
+   'latest_test_result_date': '2019-10-02',
+   'last_updated_by': 'null',
+   'test_execution_status': 'In Progress',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Data Quality Monitoring': {'evidence_capture': 'null',
+   'test_result_justification': 'xxx',
+   'latest_test_result_date': '2019-08-09',
+   'last_updated_by': 'null',
+   'test_execution_status': 'Completed',
+   'test_result': 'xxx'}},
+ {'Health and Welfare Plan + HPU Source Reliability': {'evidence_capture': 'null',
+   'test_result_justification': 'xxx.',
+   'latest_test_result_date': '2019-10-02',
+   'last_updated_by': 'null',
+   'test_execution_status': 'In Progress',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Lineage': {'evidence_capture': 'null',
+   'test_result_justification': 'null',
+   'latest_test_result_date': 'null',
+   'last_updated_by': 'null',
+   'test_execution_status': 'Not Started',
+   'test_result': 'null'}},
+ {'Health and Welfare Plan + Metadata': {'evidence_capture': 'null',
+   'test_result_justification': 'Valid',
+   'latest_test_result_date': '2020-07-02',
+   'last_updated_by': 'null',
+   'test_execution_status': 'Completed',
+   'test_result': 'xxx'}},
+ {'Health and Welfare Plan + Usage Reconciliation': {'evidence_capture': 'null',
+   'test_result_justification': 'Test out of scope',
+   'latest_test_result_date': '2019-10-02',
+   'last_updated_by': 'null',
+   'test_execution_status': 'In Progress',
+   'test_result': 'null'}}]
+
+

I would like to convert the list into a dataframe that looks like this:

+
                        evidence_capture last_updated_by latest_test_result_date test_execution_status test_result test_result_justification            test_category
+Change Notification                 null            null                    null           Not Started        null                      null  Health and Welfare Plan
+Computations                        null            null                    null           Not Started        null                      null  Health and Welfare Plan
+Data Agreements                     null            null              2019-10-02           In Progress        null         Due to the Policy  Health and Welfare Plan
+Data Elements                       null            null              2019-10-02           In Progress        null                       xxx  Health and Welfare Plan
+Data Quality Monitoring             null            null              2019-08-09             Completed         xxx                       xxx  Health and Welfare Plan
+HPU Source Reliability              null            null              2019-10-02           In Progress        null                      xxx.  Health and Welfare Plan
+Lineage                             null            null                    null           Not Started        null                      null  Health and Welfare Plan
+Metadata                            null            null              2020-07-02             Completed         xxx                     Valid  Health and Welfare Plan
+Usage Reconciliation                null            null              2019-10-02           In Progress        null         Test out of scope  Health and Welfare Plan
+
+

My code to build the dataframe is using a for-loop to concat the records column by column. After that to process the column names, and then transpose it. The final output would have the repeated string "Health and Welfare Plan" removed from each row index, but appended as a new column.

+
df3 = pd.DataFrame(lis[0])
+for i in range(1, len(lis)):
+    df3 = pd.concat([df3, pd.DataFrame(lis[i])], axis=1)
+df3.columns = [col.split(' + ')[1] for col in df3.columns]
+df3 = df3.T
+df3['test_category'] = 'Health and Welfare Plan'
+print(df3)
+
+

The code is able to produce the final output, but using "expensive" functions of both for-loop and dataframe concat. So I was wondering if there is a better way to output the same results?

","

Let us do dict comp to flatten the list of dictionaries

+
pd.DataFrame({k.split(' + ')[1]: v for d in lis for k, v in d.items()}).T
+
+
+
                        evidence_capture test_result_justification latest_test_result_date last_updated_by test_execution_status test_result
+Change Notification                 null                      null                    null            null           Not Started        null
+Computations                        null                      null                    null            null           Not Started        null
+Data Agreements                     null         Due to the Policy              2019-10-02            null           In Progress        null
+Data Elements                       null                       xxx              2019-10-02            null           In Progress        null
+Data Quality Monitoring             null                       xxx              2019-08-09            null             Completed         xxx
+HPU Source Reliability              null                      xxx.              2019-10-02            null           In Progress        null
+Lineage                             null                      null                    null            null           Not Started        null
+Metadata                            null                     Valid              2020-07-02            null             Completed         xxx
+Usage Reconciliation                null         Test out of scope              2019-10-02            null           In Progress        null
+
",python +"How can I replace each occurrence of a substring independently of the others?

I have a sentence like this:

+
sentence = "it is a stupid book and a stupid hat and a stupid computer"
+
+

and I want to replace the word "stupid" with the word "silly". And create a sentence for each replacement.

+

The result is something like this:

+
    +
  • "it is a silly book and a stupid hat and a stupid computer"

    +
  • +
  • "it is a stupid book and a silly hat and a stupid computer"

    +
  • +
  • "it is a stupid book and a stupid hat and a silly computer"

    +
  • +
+

I mean the creating just 3 sentences each one for each replacement. +I found the method replace() in Python but the count parameter determines the number of replacements not the one that I want. Could anyone help me?

","

One solution:

+
string = "it is a stupid book and a stupid hat and a stupid computer"
+
+for i in range(string.count('stupid')):
+    new = string.replace('stupid', 'silly', i+1)
+    new = new.replace('silly', 'stupid', i)
+    print(new)
+
+

EDIT

+

Another solution with a list comprehension:

+
string = "it is a stupid book and a stupid hat and a stupid computer"
+
+word1 = 'stupid'
+word2 = 'silly'
+
+strings = [string.replace(word1, word2, i+1).replace(word2, word1, i) for i in range(string.count(word1))]
+
+print(strings)
+
+

EDIT2 +If word2 happens to be in string (as W. Ding comment), then you can try this (choosing an unlikely string as long as you want):

+
string = "silly...it is a stupid book and a stupid hat and a stupid computer"
+word1 = 'stupid'
+word2 = 'silly'
+unlikely = '$*$ù^$*ù*;;;,:;!::*ù*$^^$$^d^^d^eêê'
+
+
+strings = [string.replace(word1, unlikely, i+1).
+                  replace(unlikely, word1, i).
+                  replace(unlikely, word2) for i in range(string.count(word1))]
+
+print(strings)
+
",python +"function that checks valid words with certain letters, loop functions

Hello I am trying to create a function that will retrieve a word of any length and combination of the six letters such as odd, Pow. I want the function to see if the word is valid. If it is not I then want the person to type a new word in and then check that word to see if it is valid. If it is not I want to continue the loop until the word contains only the six letters. Thank you.

+
accepeted_letters = "U", "P", "D", "O", "W", "N"
+user_input_uppercase = str(input("Select one or more of each 
+letter to be displated [U, P, D, O, W, N], Thank you ")).upper()
+user_input_string = str(user_input_uppercase).replace(" ", "")
+
+def valid():
+    global accepeted_letters, user_input_string
+    while user_input_string[0] not in accepeted_letters:
+        user_input_uppercase = input("Please Enter one or more 
+of the following letters: [U, P, D, O, W, N]").upper()
+    if user_input_uppercase in accepeted_letters:
+        pass 
+
+valid()
+
","

You need to prompt for input in a loop, and either break the loop or return the value from your function when the condition is met. An easy way to test your valid letter condition is to turn the user's input into a set and then check to see if it's a subset of the valid letters.

+
valid_letters = "UPDOWN"
+
+def get_valid_letters():
+    while True:
+        user_letters = input(
+            "Select one or more of each letter: ["
+            + ", ".join(valid_letters)
+            + "], Thank you "
+        ).upper().replace(" ", "")
+        if set(user_letters).issubset(valid_letters):
+            return user_letters
+
+print(get_valid_letters(), "is valid!")
+
",python +"python Twitch-chatbot MONKALOT encounters json error on startup

Presently I'm trying to make MONKALOT run on a PythonAnywhere account (customized Web Developer). I have basic knowledge of Linux but unfortunately no knowledge of dev'oping python scripts but advanced knowledge of dev'oping Java (hope that helps).

+

My success log so far: +After upgrading my account to Web Developer level I finally made pip download the (requirements)[https://github.com/NMisko/monkalot/blob/master/requirements.txt] and half the internet (2 of 5GB used). All modules and dependencies seem to be successfully installed.

+

I configured my own monkalot-channel including OAuth which serves as a staging instance for now. The next challenge was how to get monkalot starting up. Using python3.7 instead of python or any other python3 environment did the trick.

+

But now I'm stuck. After "completing the training stage" the monkalot-script prematurely ends with the following message:

+
[22:14] ...chat bot finished training.
+Traceback (most recent call last):
+  File "monkalot.py", line 72, in <module>
+    bots.append(TwitchBot(path))
+  File "/home/Chessalot/monkalot/bot/bot.py", line 56, in __init__
+    self.users = self.twitch.get_chatters()
+  File "/home/Chessalot/monkalot/bot/data_sources/twitch.py", line 25, in get_chatters
+    data = requests.get(USERLIST_API.format(self.channel)).json()
+  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 900, in json
+    return complexjson.loads(self.text, **kwargs)
+  File "/usr/local/lib/python3.7/site-packages/simplejson/__init__.py", line 525, in loads
+    return _default_decoder.decode(s)
+  File "/usr/local/lib/python3.7/site-packages/simplejson/decoder.py", line 370, in decode
+    obj, end = self.raw_decode(s)
+  File "/usr/local/lib/python3.7/site-packages/simplejson/decoder.py", line 400, in raw_decode
+    return self.scan_once(s, idx=_w(s, idx).end())
+simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
+
+

By now I figured out that monkalot tries to load the chatters list and expects at least an empty json array as result but actually seems to receive an empty string.

+

So my question is: What can I do to make the monkalot-script work? Is monkalot's current version incompatible to the current Twitch-API? Are there any outdated python libraries which may cause the incompatibility? Or is there an unrecognized configuration issue preventing the script from running successfully?

+

Thank you all in advance. Any ideas provided by you are highly appreciated.

","

After I expected the response, I found out that I received a HTTP 400, Bad Request error WITHOUT any data in the HTTP response body. Since monkalot expects a JSON answer the errors were raised. This was due to the fact that in the channel configuration I used an uppercase letter whereas Twitch expects all letters lowercase.

",python +"length of list read from a csv varies, depending on when a read is performed

I'm trying to write a simple function that reads in a csv and stores its content inside a list and either returns said list formatted or a string containing the information on why the csv is empty.

+

For clarification, the csv is provided by an API called via curl. If there is new data available, the csv-structure is as follows:

+
{
+entry1;entry2;entry3
+entry1;entry2;entry3
+}
+
+

however, if there is an error or no data is available, the structure is as follows:

+
{error code / info / warning / whatever}
+
+

so to gather the data, i'm first checking if the csv contains at least more than 2 rows, simply by reading the file and check the length returned via f.readlines(). if that is the case, i filter the data through a list comprehension to ignore the "{}" and return the list as a result. If the list length is below 3, that means there is definitely no data available and that theres solely the error code in line 0 - so i return f.readlines()[0].

+

here's the code of the function that does the above said:

+
def belege_to_list() -> Union[list, str, None]:
+    try:
+        with open(export_path + "Belege.csv", mode='r', encoding="utf-8") as f:
+            if 0 < len(f.readlines()) < 3:
+                return str(f.readlines()[0])
+            if len(f.readlines()) > 2:
+                belege_list = [i.replace("\n", "").split(";") for i in f.readlines()[1:-1]]
+                return belege_list
+    except FileNotFoundError as e:
+        print("Belegdatei nicht gefunden.")
+        with open(main_path + "log.txt", "a+", encoding="utf-8") as log:
+            log.write("[" + str(datetime.now()) + "]: " + "Belege nicht gefunden / Datei fehlt - Error: " + str(e) + "\n")
+        return None
+
+

the csv i'm reading is most definitely containing one line - also at the runtime of the code:

+
{"error":"sessionid expired or loginname,passwort failed"}
+
+

the function is executed as follows:

+
def main():
+    export_belege() # creates csv
+    belege = belege_to_list()
+    ...
+
+

however, im always getting an IndexError: list index out of range at return str(f.readlines()[0]. Now heres the part i sincerely do not understand. If i print out len(f.readlines) BEFORE if 0 < len(f.readlines()) < 3:, the result is 1, the code works. If it's not printed out however, the len(f.readlines) is supposedly 0, giving me an IndexError: list index out of range. Does anyone have an idea why that might be the case?

","

You should save the list returned by readlines() then refer to the list for subsequent operations. Something like this:

+
from datetime import datetime
+export_path = 'foo'
+main_path = 'bar'
+def belege_to_list():
+    try:
+        with open(export_path + "Belege.csv", encoding="utf-8") as f:
+            lines = list(map(str.strip, f))
+            if len(lines) < 3:
+                return lines[0] if len(lines) > 0 else None
+            if lines[0][0] == '{' and lines[-1][0] == '}':
+                return [line.split(';') for line in lines[1:-1]]
+    except FileNotFoundError as e:
+        print("Belegdatei nicht gefunden.")
+        with open(main_path + "log.txt", "a+", encoding="utf-8") as log:
+            log.write("[" + str(datetime.now()) + "]: " + "Belege nicht gefunden / Datei fehlt - Error: " + str(e) + "\n")
+
",python +"editing the first word in match, regex

I have a regex problem. In found matches (these are lines from a text file) I want to edit them so I can get shortened version of these lines. For example:

+

matches=[Dog Alex, Dog Chriss, Cat Susan, Lizard Bob, and so on]

+

From this I want to get:

+

new_version=[D.Alex, D.Chriss, C.Susan, and so on]

+

So I wrote this code:

+
for match in matches:
+    mpattern=re.compile(r'^\w (.+)')
+    match=re.sub(mpattern, r'[A-Z]\. (.+)', match)
+    list_of_descriptions.append(match)
+
+

but it doesn't work correctly :(

+

I need the program to find the first word (which could begin with any letter) and then shorten it to the first letter and add a dot. Could someone help me, please? I'm using Python 3.7.9.

","

The regex should capture the first letter, but should allow for more letters in the first word. On the other hand, as you're not planning to change anything to the second word, there is no need to include it in the match.

+

Side note: when you compile your regex, you can call the sub method on that object, instead of on re.

+

So:

+
mpattern = re.compile(r'^(\w)\w* ')
+list_of_descriptions = [mpattern.sub(r'\1.', match) for match in matches]
+
",python +"Set subtraction while casting lists and string

I have two lists of strings. When I cast two lists into set() then subtraction works properly.

+
>>> A = ['One', 'Two', 'Three', 'Four']
+>>> B = ['One']
+>>> print(list(set(A) - set(B)))
+['Three', 'Two', 'Four']
+
+

However when variable B is a string and I cast it into set() then, the subtraction is not working.

+
>>> A = ['One', 'Two', 'Three', 'Four']
+>>> B = 'One'
+>>> print(list(set(A) - set(B)))
+['One', 'Two', 'Three', 'Four']
+
+

Is anyone able to explain me if its a bug or expected behavior?

","

The set() function, when operating on a string, will generate a set of all characters:

+
print(set("ABC"))  # set(['A', 'C', 'B'])
+
+

If you want a set with a single string ABC in it, then you need to pass a collection containing that string to set():

+
print(set(["ABC"]))  # set(['ABC'])
+
",python +"python re.sub problems backreferencing from a function

I want to 'join' certain numbers, that clearly should be together, although I don't want them to join every number.

+

What I have:

+
'Canesten 1 500 mg meka kapsula za rodnicui'
+'Clexane 10 000 IU (100 mg)/1 ml otopina za injekciju'
+'Humulin M3 100 IU/ml suspenzija za injekciju u ulošku'
+'Docile10 000 IU/ml oralne kapi, otopina'
+'POLYGYNAX 35 000 IU / 35 000 IU / 100 000 IU kapsula za rodnicu, meka'
+'Prostin E2 2 mg gel za rodnicu'
+'Silapen K 1 000 000 IU filmom obložene tablete'
+
+

I want to have:

+
'Canesten 1500 mg meka kapsula za rodnicui'
+'Clexane 10000 IU (100 mg)/1 ml otopina za injekciju'
+'Humulin M3 100 IU/ml suspenzija za injekciju u ulošku'
+'Docile10000 IU/ml oralne kapi, otopina'
+'POLYGYNAX 35000 IU / 35000 IU / 100000 IU kapsula za rodnicu, meka'
+'Prostin E2 2 mg gel za rodnicu'
+'Silapen K 1000000 IU filmom obložene tablete'
+
+

It may be easier to see which ones I'm trying to join here: https://regex101.com/r/Ht9ZVi/1

+

I can match each one of the numbers I want to join using ([^a-zA-Z](?:\d+\s+)*\d+\s\d+0{2}), but because this regex is not perfect regarding the blank spaces I thought about using a function to only remove the blank spaces between numbers.

+
def spaces(s):
+    return re.sub('(?<=\d) (?=\d)', '', s)
+
+cr['Name'].apply(lambda x: re.sub(r"([^a-zA-Z](?:\d+\s*)*\d+\s\d+0{2})", spaces(r'\1'), x))
+
+

This returns the strings unaltered, what am I doing wrong? +I know this is a common question, and the solution is probably really simple but I can't wrap my head around it..

","

In your pattern you want to match a leading single char other than a-zA-Z with [^a-zA-Z], but you can assert not an uppercase A-Z directly to the left instead to account for Docile10 000

+

Then you don't need a capture group and you could match the digits with at least 1 space in between followed by asserting one of the allowed units.

+

Then remove the spaces from the match with .group(0)

+

This part [^\S\n]+ matches whitespace chars without newlines. If you want to allow crossing newlines, you can use \s+ instead

+
(?<![A-Z])\d+(?:[^\S\n]+\d+)+(?=[^\S\n]*(?:mg|IU)\b)
+
+

Regex demo

+

You can also omit the assertion for the unit at the end for the current example data:

+
(?<![A-Z])\d+(?:[^\S\n]+\d+)+
+
+

Example

+
strings = [
+    'Canesten 1 500 mg meka kapsula za rodnicui',
+    'Clexane 10 000 IU (100 mg)/1 ml otopina za injekciju',
+    'Humulin M3 100 IU/ml suspenzija za injekciju u ulošku',
+    'Docile10 000 IU/ml oralne kapi, otopina',
+    'POLYGYNAX 35 000 IU / 35 000 IU / 100 000 IU kapsula za rodnicu, meka',
+    'Prostin E2 2 mg gel za rodnicu',
+    'Silapen K 1 000 000 IU filmom obložene tablete'
+]
+
+pattern = r"(?<![A-Z])\d+(?:[^\S\n]+\d+)+(?=[^\S\n]*(?:mg|IU)\b)"
+
+for s in strings:
+    print(re.sub(pattern, lambda x: re.sub(r"\s+", "", x.group()), s))
+
+

Output

+
Canesten 1500 mg meka kapsula za rodnicui
+Clexane 10000 IU (100 mg)/1 ml otopina za injekciju
+Humulin M3 100 IU/ml suspenzija za injekciju u ulošku
+Docile10000 IU/ml oralne kapi, otopina
+POLYGYNAX 35000 IU / 35000 IU / 100000 IU kapsula za rodnicu, meka
+Prostin E2 2 mg gel za rodnicu
+Silapen K 1000000 IU filmom obložene tablete
+
",python +"Concatenate 2 dataframes and repeat values from small one with pandas

I have these two dataframes:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Field1Field2
0.50.7
21
30.1
40.4
+
+

and

+
+ + + + + + + + + + + + + + + + + +
DateTime
2022-08-011
2022-08-012
+
+

and a I need to obtain the following:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Field1Field2DateTime
0.50.72022-08-011
212022-08-012
30.12022-08-011
40.42022-08-012
+
+

Thanks in advance

","

You can elongate your second dataframe to match dimentions, and then concatenate it with first dataframe.

+
import pandas as pd
+
+df1 = pd.DataFrame({'Field1': [0.5, 2, 3, 4], 'Field2': [0.7, 1, 0.1, 0.4]})
+print(df1)
+#    Field1  Field2
+# 0     0.5     0.7
+# 1     2.0     1.0
+# 2     3.0     0.1
+# 3     4.0     0.4
+
+df2 = pd.DataFrame({'Date': ['2022-08-01', '2022-08-01'], 'Time': [1, 2]})
+print(df2)
+#          Date  Time
+# 0  2022-08-01     1
+# 1  2022-08-01     2
+
+n = int(df1.size / df2.size)
+df3 = pd.concat([df2] * n, axis=0).reset_index(drop=True)
+print(df3)
+#          Date  Time
+# 0  2022-08-01     1
+# 1  2022-08-01     2
+# 2  2022-08-01     1
+# 3  2022-08-01     2
+
+df4 = pd.concat([df1, df3], axis=1)
+print(df4)
+#    Field1  Field2        Date  Time
+# 0     0.5     0.7  2022-08-01     1
+# 1     2.0     1.0  2022-08-01     2
+# 2     3.0     0.1  2022-08-01     1
+# 3     4.0     0.4  2022-08-01     2
+
+

or shorter:

+
df4 = pd.concat([
+    df1,
+    pd.concat(
+        [df2] * int(df1.size / df2.size),
+        axis=0
+    ).reset_index(drop=True)
+], axis=1)
+
",python +"problem with inserting data into the bar chart plotly graph_objects

so I'm trying to add the lists ( Internal, External ..) to the bar chart but the data goes to one column "internal"

+

+

it is supposed to be similar to this

+

+

here is the whole df and the work I did

+

","

In your case, the problem is:

+
    +
  1. You want to plot a bar chart with plotly.graph_objects
  2. +
  3. What exactly is data that go.Bar() needed. (status, escalation)
  4. +
+

Deduce from questions above,
+a) How do you fetch the minimum portion of data for the demo in Stack Overflow?
+b) How to prepare the data from your df and transform them available to plot. +
+
+

+

Preparing for the data we want to plot:

+
import random
+import pandas as pd
+import plotly.graph_objects as go
+random.seed(42)
+sample_quntity = 50
+status = [random.choice(['Not Done','Something Else','Done']) for i in range(sample_quntity)]
+escalation = [random.choice(['Internal','External','Unspecified']) for i in range(sample_quntity)]
+df = pd.DataFrame({
+    'status':status,
+    'escalation':escalation
+})
+df
+###
+            status   escalation
+0             Done  Unspecified
+1         Not Done     External
+2         Not Done     Internal
+3             Done  Unspecified
+4   Something Else     External
+5         Not Done  Unspecified
+⋮                ⋮            ⋮
+43  Something Else  Unspecified
+44        Not Done  Unspecified
+45        Not Done     Internal
+46  Something Else     Internal
+47        Not Done     External
+48  Something Else     External
+49  Something Else     External
+
+
+
+
+

Plot:

+
# plot bar chart grouping with status and escalation and color by status
+group_list = df['escalation'].unique()
+palette = {"Not Done": "#d89a9e","Something Else":"#e0c1b3", "Done": "#aeb4a9"}
+
+fig = go.Figure(data=[
+    go.Bar(name='Not Done',
+           x=group_list,
+           y=df[df['status'] == 'Not Done'].groupby('escalation').size(),
+           marker_color=palette['Not Done']),
+    go.Bar(name='Something Else',
+           x=group_list,
+           y=df[df['status'] == 'Something Else'].groupby('escalation').size(),
+           marker_color=palette['Something Else']),
+    go.Bar(name='Done',
+           x=group_list,
+           y=df[df['status'] == 'Done'].groupby('escalation').size(),
+           marker_color=palette['Done'])])
+
+fig.update_layout(title='Group by Escalation, Color by Status', barmode='stack')
+fig.show()
+
+
+

",python +"Increasing number of permutations of all possible combinations of a list with repetitions allowed

I am trying without success to understand how to use itertools to generate a list with all possible combinations of the elements of a list, with an increasing size of elements to pick and including repetitions. +I would like to add also a separator:

+
lis = ['a','b','c']
+separator = '/'
+total_number_of_combinations = 3
+permutation_list = ['a','b','c', 'a/a', 'a/b', 'a/c', 'b/a', 'b/b', 'b/c', 'c/a', 'c/b', 'c/c',
+                    'a/a/a', 'a/a/b', 'a/a/c', 'a/b/a', 'a/b/b', 'a/b/c', 'a/c/a', 'a/c/b', 'a/c/c'
+                    'b/a/a', 'b/a/b', 'b/a/c', 'b/b/a', 'b/b/b', 'b/b/c', 'b/c/a', 'b/c/b', 'b/c/c'
+                    'c/a/a', 'c/a/b', 'c/a/c', 'c/b/a', 'c/b/b', 'c/b/c', 'c/c/a', 'c/c/b', 'c/c/c']
+
+

The list will have then len(lis)+len(lis)**2+len(lis)**3+...++len(lis)**n elements, with n=total_number_of_combinations. +I need to keep the separator and the total_numbers_of_combinations changeables.

+

I need this in a list that can be check as a condition for filtering a pandas DataFrame (i will check dt[dt.my_col.isin(permutation_list)])

+

I appreciate any help or pointing to a duplicated topic or even an explanation of how to correctly state this problem, because I did not found any topic that answer this question (maybe I am using the wrong keywords...). Maybe also there is a function from another module that does that, but I don't know.

+

UPDATE: +Following the request of @Scott, here is my real case:

+
lis = ['BRUTELE','COCKPIT EST', 'CIRCET']
+separator = ' / '
+total_number_of_combinations = 10
+
+

so my final list need to have 88572 elements.

","

What you are trying to get is a product, not a combination.

+
lis = ["BRUTELE", "COCKPIT EST", "CIRCET"]
+separator = " / "
+total_number_of_combinations = 3
+
+result = list(
+    itertools.chain.from_iterable(
+        (separator.join(a) for a in itertools.product(lis, repeat=i))
+        for i in range(1, total_number_of_combinations + 1)
+    )
+)
+
+assert result == ['BRUTELE', 'COCKPIT EST', 'CIRCET', 'BRUTELE / BRUTELE', 'BRUTELE / COCKPIT EST', 'BRUTELE / CIRCET', 'COCKPIT EST / BRUTELE', 'COCKPIT EST / COCKPIT EST', 'COCKPIT EST / CIRCET', 'CIRCET / BRUTELE', 'CIRCET / COCKPIT EST', 'CIRCET / CIRCET', 'BRUTELE / BRUTELE / BRUTELE', 'BRUTELE / BRUTELE / COCKPIT EST', 'BRUTELE / BRUTELE / CIRCET', 'BRUTELE / COCKPIT EST / BRUTELE', 'BRUTELE / COCKPIT EST / COCKPIT EST', 'BRUTELE / COCKPIT EST / CIRCET', 'BRUTELE / CIRCET / BRUTELE', 'BRUTELE / CIRCET / COCKPIT EST', 'BRUTELE / CIRCET / CIRCET', 'COCKPIT EST / BRUTELE / BRUTELE', 'COCKPIT EST / BRUTELE / COCKPIT EST', 'COCKPIT EST / BRUTELE / CIRCET', 'COCKPIT EST / COCKPIT EST / BRUTELE', 'COCKPIT EST / COCKPIT EST / COCKPIT EST', 'COCKPIT EST / COCKPIT EST / CIRCET', 'COCKPIT EST / CIRCET / BRUTELE', 'COCKPIT EST / CIRCET / COCKPIT EST', 'COCKPIT EST / CIRCET / CIRCET', 'CIRCET / BRUTELE / BRUTELE', 'CIRCET / BRUTELE / COCKPIT EST', 'CIRCET / BRUTELE / CIRCET', 'CIRCET / COCKPIT EST / BRUTELE', 'CIRCET / COCKPIT EST / COCKPIT EST', 'CIRCET / COCKPIT EST / CIRCET', 'CIRCET / CIRCET / BRUTELE', 'CIRCET / CIRCET / COCKPIT EST', 'CIRCET / CIRCET / CIRCET']                                      
+
+

However, the number of resulting items is O(len(lis) ** total_number_of_combinations), which may be computationally expensive. A better method would be parsing a string by splitting at separators and testing the membership of each split string.

",python +"Python pytest: local variable 'length' referenced before assignment

I am not sure what is wrong in the following code snippet.

+

I have the following two versions of a function.

+

Version 1

+
def _check_array_lengths(self, data):
+    for i, values in data.items():
+        if i == 0:
+            length = len(values)
+        if length != len(values):
+            raise ValueError('All values must be the same length')
+
+

When I run test, the above function fails with a msg +"ERROR tests/test_dataframe.py - UnboundLocalError: local variable 'length' referenced before assignment"

+

Version 2

+
def _check_array_lengths(self, data):
+    for i, values in enumerate(data.values()):
+        if i == 0:
+            length = len(values)
+        if length != len(values):
+            raise ValueError('All values must be the same length')
+
+

The test for this function works fine and I wonder why I don't see the same error msg(mentioned above) here. How that "enumerate" is causing this change in behavior!

+

May be something really silly but I couldn't figure it out yet.

+

Here is my test function

+
def test_array_length(self):
+    with pytest.raises(ValueError):
+        pdc.DataFrame({'a': np.array([1, 2]), 
+                       'b': np.array([1])})
+
+

can you please help ?

","

In the second version, the first value of i is guaranteed to be 0. So the condition if i == 0: will be true, and length will be set. Then the comparison if length != len(values): will be able to use the length variable.

+

In the first version is i iterates over the dataframe indexes, not a numeric sequence. The values of i will be 'a' and 'b'. The if i == 0: condition will never be true, so you never set length, and get an error when you try to compare it.

",python +"Custom markdown parser not working properly

So I am making my own little script to detect some markdown notations in a variable. Now there are two issues.

+
    +
  • First of all, my current approach does not work when using the markdown as following (I am referring to the question mark):
  • +
+
**am I working**?
+
+
    +
  • Aside from that does the code look quite messy and I am pretty sure that it can be done more efficiently.
  • +
+

I was wondering as to what could be a better way to do what I am trying.
+I want to add that I have looked for packages but these wont work in my case as I only want to allow bold, italic, underline and escaping (**bold**, _italic_ and __underline__).
+My current code:

+
description = "**one more test** _just to be sure_ \*hi\* apparently __underline broke__?"
+
+for word in description.split(" "):
+    if word.startswith("**"):    
+        description = description.replace(word, f'<b>{word.replace("**", "", 1)}')
+        word = word.replace("**", "", 1)
+    if word.endswith("**") and not word.endswith("\**"):  
+        description = description.replace(word, f'{word.replace("**", "", 1)}</b>')
+        word = word.replace("**", "", 1)
+    if word.startswith("*"):
+        description = description.replace(word, f'<i>{word.replace("*", "", 1)}')
+        word = word.replace("*", "", 1)
+    if word.endswith("*") and not word.endswith("\*"):
+        description = description.replace(word, f'{word.replace("*", "", 1)}</i>')   
+        word = word.replace("*", "", 1) 
+    if word.startswith("__"):
+        description = description.replace(word, f'<u>{word.replace("__", "", 1)}')
+        word = word.replace("__", "", 1)
+    if word.endswith("__") and not word.endswith("\__"):
+        description = description.replace(word, f'{word.replace("__", "", 1)}</u>')    
+        word = word.replace("__", "", 1)
+    if word.startswith("_"):
+        description = description.replace(word, f'<i>{word.replace("_", "", 1)}')
+        word = word.replace("_", "", 1)
+    if word.endswith("_") and not word.endswith("\_"):
+        description = description.replace(word, f'{word.replace("_", "", 1)}</i>')     
+        word = word.replace("_", "", 1)   
+
+print(description) 
+
","

First of all, you should rely on regex expressions to be able to cover the different cases. Also, working with a clean code by defining functions and loops is better for future changes and readability.

+

So, to solve your special characters issue (like ?, !, ..etc.), we can have the function below:

+
import re
+
+def _check_match(text, chars, start_or_end="start", excluded_chars='()?!'):
+    # check if the text ends or starts with the required characters 
+    # but could have any of the excluded characters before (if start) or after (if end)
+    if start_or_end == "start":
+        pattern = re.compile(rf'([{excluded_chars}]*){re.escape(chars)}(.*)$')
+    elif start_or_end == "end":
+        pattern = re.compile(rf'(.*[^\\]){re.escape(chars)}([{excluded_chars}]*)$')
+    else:
+        return False, None, None
+    check = re.match(pattern, text)
+    if check:
+        return True, check.group(1), check.group(2)
+    return False, None, None
+
+def check_match_start(text, chars):
+    return _check_match(text, chars, "start")
+
+def check_match_end(text, chars):
+    return _check_match(text, chars, "end")
+
+

Examples:

+
check_match_start("**test", "**") >> (True, '', 'test')
+check_match_start("(**test", "**") >> (True, '(', 'test')
+check_match_end("test_?", "_") >> (True, 'test', '?')
+check_match_end("test__?", "*") >> (False, None, None)
+
+

Then, we can have another function that loops on all the required markdowns to apply:

+
def markdown_text(text):
+    markdown_criteria = [
+        ("**", ["<b>", '</b>']),
+        ("*", ["<i>", "</i>"]),
+        ("__", ["<u>", "</u>"]),
+        ("_", ["<i>", "</i>"])
+    ]
+    for m in markdown_criteria:
+        chars = m[0]
+        replacement_start = m[1][0]
+        replacement_end = m[1][1]
+        my_start_check, matched_special_chars, matched_text = check_match_start(text, chars)
+        if my_start_check:
+            text = f'{matched_special_chars}{replacement_start}{matched_text}'
+        my_end_check, matched_text, matched_special_chars = check_match_end(text, chars)
+        if my_end_check:
+            text = f'{matched_text}{replacement_end}{matched_special_chars}'
+    return text
+
+

Examples:

+
markdown_text("test__?") >> 'test</u>?' 
+markdown_text("*test") >> '<i>test' 
+markdown_text("**test**!") >> '<b>test</b>!'
+
+

It is time to execute:

+
description = "**one more test** _just to be sure_ \*hi\* apparently __underline broke__?"
+new_description = []
+for word in description.split(" "):
+    new_description.append(markdown_text(word))
+
+new_description = " ".join(new_description)
+print(new_description) >> <b>one more test</b> <i>just to be sure</i> \*hi\* apparently <u>underline broke</u>?
+
+

This solution provides more flexibility to:

+
    +
  • add any other needed markdowns by simply updating markdown_criteria list (for example, you can add ("***", ["<b><i>", '</i></b>']) to have bold and italic together, but make sure to add it in the beginning of the list not to be overriden by the next bold and italic criteria)
  • +
  • exclude more or less special characters by simply updating the parameter excluded_chars in _check_match function
  • +
+

Needed enhancements:

+

This solution doesn't cover the case for an instance if you have a word starting with ** in your phrase and there is no other word that ends with **, so you will end up having <b> without </b>. This can be solved if you can deal with your phrase also as a bulk in a regex expression instead of splitting the phrase with space and working with each word separately

",python +"Unable to do web scraping from URL using Python Alchemy

I have a script where I'm trying to web scraping the data into table. But I'm getting errors

+
  raise exc.with_traceback(traceback)
+ValueError: No tables found
+
+

Script :

+
import pandas as pd
+import logging
+from sqlalchemy import create engine
+from urlib.parse import quote
+
+db_connection = {mysql}://{username}:{quote'pwd'}@{DB:port}
+ds_connection = create_engine(db_connection)
+a = pd.read_html("https://www.centralbank.ae/en/forex-eibor/exchange-rates/")
+df = pd.Dataframe(a[0])
+df_final = df.loc[:,['Currency','Rate']]
+df_final.to_sql('rate_table',db_connection,if_exists = append,index=false)
+
+

Can anyone suggest on this

","

One easy way to obtain those exchange rates would be to scrape the API accessed to retrieve information in page (check Dev Tools - network tab):

+
import pandas as pd
+import requests
+from bs4 import BeautifulSoup
+
+headers = {'Accept-Language': 'en-US,en;q=0.9',
+          'Referer': 'https://www.centralbank.ae/en/forex-eibor/exchange-rates/'
+
+          }
+r = requests.post('https://www.centralbank.ae/umbraco/Surface/Exchange/GetExchangeRateAllCurrency', headers=headers)
+dfs = pd.read_html(r.text)
+print(dfs[0].loc[:,['Currency','Rates']])
+
+

This returns:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CurrencyRates
0US Dollar3.6725
1Argentine Peso0.026993
2Australian Dollar2.52753
3Bangladesh Taka0.038508
4Bahrani Dinar9.74293
5Brunei Dollar2.64095
6Brazilian Real0.706549
7Botswana Pula0.287552
8Belarus Rouble1.45526
9Canadian Dollar2.82565
10Swiss Franc3.83311
11Chilean Peso0.003884
12Chinese Yuan - Offshore0.536978
13Chinese Yuan0.538829
14Colombian Peso0.000832
15Czech Koruna0.149763
16Danish Krone0.496304
17Algerian Dinar0.025944
18Egypt Pound0.191775
19Euro3.69096
20GB Pound4.34256
21Hongkong Dollar0.468079
22Hungarian Forint0.009112
23Indonesia Rupiah0.000248
24Indian Rupee0.045976
25Iceland Krona0.026232
26Jordan Dinar5.17472
27Japanese Yen0.026818
28Kenya Shilling0.030681
29Korean Won0.002746
30Kuwaiti Dinar11.9423
31Kazakhstan Tenge0.007704
32Lebanon Pound0.002418
33Sri Lanka Rupee0.010201
34Moroccan Dirham0.353346
35Macedonia Denar0.059901
36Mexican Peso0.181874
37Malaysia Ringgit0.820395
38Nigerian Naira0.008737
39Norwegian Krone0.37486
40NewZealand Dollar2.27287
41Omani Rial9.53921
42Peru Sol0.952659
43Philippine Piso0.065562
44Pakistan Rupee0.017077
45Polish Zloty0.777446
46Qatari Riyal1.00254
47Serbian Dinar0.031445
48Russia Rouble0.06178
49Saudi Riyal0.977847
50Sudanese Pound0.006479
51Swedish Krona0.347245
52Singapore Dollar2.64038
53Thai Baht0.102612
54Tunisian Dinar1.1505
55Turkish Lira0.20272
56Trin Tob Dollar0.541411
57Taiwan Dollar0.121961
58Tanzania Shilling0.001575
59Uganda Shilling0.000959
60Vietnam Dong0.000157
61Yemen Rial0.01468
62South Africa Rand0.216405
63Zambian Kwacha0.227752
64Azerbaijan manat2.16157
65Bulgarian lev1.8873
66Croatian kuna0.491344
67Ethiopian birr0.069656
68Iraqi dinar0.002516
69Israeli new shekel1.12309
70Libyan dinar0.752115
71Mauritian rupee0.079837
72Romanian leu0.755612
73Syrian pound0.001462
74Turkmen manat1.05079
75Uzbekistani som0.000336
+
",python +"How to append item to match the length of two list in python

I am working on a python script which is connected to a server. Every x min, server returns two list but the length of these list is not same. For ex:

+
a = [8, 10, 1, 34]
+b = [4, 6, 8]
+
+

As you can see above that a is of length 4 and b is of length 3. Simillarly sometime it returns

+
a = [3, 6, 4, 5]
+b = [8, 3, 5, 2, 9, 3]
+
+

I have to write a logic where I have to check if length of these two list is not same, then add the 0 at the end of the list which is smaller than other list. So for ex, if input is:

+
a = [3, 6, 4, 5]
+b = [8, 3, 5, 2, 9, 3]
+
+

then output will be:

+
a = [3, 6, 4, 5, 0, 0]
+b = [8, 3, 5, 2, 9, 3]
+
+

Can anyone please help me with these. Thanks

","
def pad(list1, list2):
+    # make copies of the existing lists so that original lists remain intact
+    list1_copy = list1.copy()
+    list2_copy = list2.copy()
+
+    len_list1 = len(list1_copy)
+    len_list2 = len(list2_copy)
+    # find the difference in the element count between the two lists
+    diff = abs(len_list1 - len_list2)
+    
+    # add `diff` number of elements to the end of the list
+    if len_list1 < len_list2:
+        list1_copy += [0] * diff
+    elif len_list1 > len_list2:
+        list2_copy += [0] * diff
+
+    return list1_copy, list2_copy
+
+
+a = [3, 6, 4, 5]
+b = [8, 3, 5, 2, 9, 3]
+# prints: ([3, 6, 4, 5, 0, 0], [8, 3, 5, 2, 9, 3])
+print(pad(a, b))
+
+a = [8, 10, 1, 34]
+b = [4, 6, 8]
+# prints: ([8, 10, 1, 34], [4, 6, 8, 0])
+print(pad(a, b))
+
",python +"Generating a global connection in prisma python client

I'm using Prisma python client for my mysql database. I'm wondering if its possible to do a single global connection instead of having to open and close them whenever I make a query?

+
    @commands.has_permissions(manage_guild=True)
+    @commands.slash_command(description="Sets up the server for verification")
+    async def help(self, interaction: disnake.GuildCommandInteraction):
+        await self.client.prisma.connect()
+        response = await self.client.prisma.user.find_first(where={
+            "name": "benn",
+        })
+        print(dict(response))
+        await self.client.prisma.disconnect()
+
+

I tried doing the following:

+
client.prisma = Prisma(auto_register=True)
+async def connect_to_db():
+    await client.prisma.connect()
+
+asyncio.run(connect_to_db())
+
+

However, I get an error:

+
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Event loop is closed```
+
","

It is recommended that you create one instance of PrismaClient and reuse it across your application and you should only set it to a global variable in the development environment only and you do not need to explicitly $disconnect. You can learn more about Prisma connection management in the docs. Also, I’ll encourage you to ask your Prisma Python client questions in prisma-client-py repositories GitHub Discussion

",python +"How to Download a File after POSTing data using FastAPI?

I am creating a small web application that receives text, converts the text to speech, and returns an mp3 file, which is saved to a temporary directory.

+

I want to be able to download the file from the html page which will access the FastAPI server for the downloaded file, but I don't know how to do that properly.

+

I know with Flask you can do this with:

+
from app import app
+from flask import Flask, send_file, render_template
+    
+@app.route('/')
+def upload_form():
+    return render_template('download.html')
+
+@app.route('/download')
+def download_file():
+    path = "html2pdf.pdf"
+
+    return send_file(path, as_attachment=True)
+
+if __name__ == "__main__":
+    app.run()
+
+

HTML Example:

+
<!doctype html>
+<title>Python Flask File Download Example</title>
+<h2>Download a file</h2>
+<p>
+    <a href="{{ url_for('.download_file') }}">Download</a>
+</p>
+
+

So how do I replicate this with FastAPI?

+

FastAPI Code:

+
from fastapi import FastAPI, File, Request, Response, UploadFile
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
+from fastapi.templating import Jinja2Templates
+from gtts import gTTS
+
+templates = Jinja2Templates(directory="templates")
+
+
+def text_to_speech(language:str, text: str) -> str:
+    tts = gTTS(text=text, lang=language, slow=False)
+    tts.save("./temp/welcome.mp3")
+    #os.system("mpg321 /temp/welcome.mp3")
+    return "Text to speech conversion successful"
+
+
+@app.get("/")
+def home(request: Request):
+    return templates.TemplateResponse("index.html", {"request": request})
+
+@app.get("/text2speech")
+async def home(request: Request):
+    if request.method == "POST":
+        form = await request.form()
+        if form["message"] and form["language"]:
+            language = form["language"]
+            text = form["message"]
+            translate = text_to_speech(language, text)
+            path = './temp/welcome.mp3'
+            value = FileResponse("./temp/welcome.mp3", media_type="audio/mp3")
+            return value
+    # return templates.TemplateResponse(
+    #     "index.html",
+    #     {"request": request, "message": text, "language": language, "download": value},
+    # )
+
+
+

Sample HTML File:

+

+<!doctype html>
+<title>Download MP3 File</title>
+<h2>Download a file</h2>
+<p>
+    <a href="{{ url_for('text2speech') }}">Download</a>
+</p>
+
","

Use the Form keyword to define Form-data in your endpoint, and more specifically, use Form(...) to make a parameter required, instead of using await request.form() and manually checking if the user submitted the required parameters. After processing the received data and generating the audio file, you can use FileResponse to return the file to the user. Note: use the headers argument to set the 'Content-Disposition' header using the attachment parameter—as described in this answer—to have the file downloaded to your device. Failing to set the headers, or using the inline parameter isntead, would lead to 405 Method Not Allowed error, as the browser attempts to access the file using a GET request (however, only POST requests are allowed to the /text2speech endpoint). Have a look at Option 1 in the examples below.

+

If you wanted the /text2speech endpoint supporting both GET and POST requests (as shown in your question), you could either use @app.api_route("/text2speech", methods=["GET", "POST"]) and use request.method to check which one has been called, or define two different endpoints e.g., @app.post('/text2speech') and @app.get('/text2speech'). However, you don't necessarily need to do that in this case. Additionally, you have added a Download hyperlink to your template for the user to download the file. However, you haven't provided any information as to how you expect this to work. This wouldn't work in a scenario where you don't have static files, but dynamically generated audio files (as in your case), as well as multiple users accessing the API at the same time; unless, for example, you generated random UUIDs for the filenames and saved the files in a StaticFiles directory—or added that unique identifier as a query/path parameter (you could also use cookies instead, see here and here) to the URL in order to identify the file to be downloaded—and sent the URL back to the user. In that case, you would need a Javascript interface/library, such as Fetch API, to make an asynchronous HTTP request—as described in this answer—in order to get the URL to the file and display it in the Download hyperlink. Have a look at Option 2 below. Note: The example in Option 2 uses a simple dict to map the filepaths to UUIDs, for demo purposes. In a real-world scenario, where multiple users access the API and several workers might be used, you may consider using a database storage, or Key-Value stores (Caches), as described here and here. You would also need to have a mechanism for deleting the files from the database and disk, once they have been downloaded, as well as make sure that users do not have unauthorised access to other users' audio files.

+

Option 1

+

app.py

+
from fastapi import FastAPI, Request, Form
+from fastapi.templating import Jinja2Templates
+from fastapi.responses import FileResponse
+import os
+
+app = FastAPI()
+templates = Jinja2Templates(directory="templates")
+
+@app.get('/')
+def main(request: Request):
+    return templates.TemplateResponse("index.html", {"request": request})
+
+@app.post('/text2speech')
+def convert(request: Request, message: str = Form(...), language: str = Form(...)):
+    # do some processing here
+    filepath = './temp/welcome.mp3'
+    filename = os.path.basename(filepath)
+    headers = {'Content-Disposition': f'attachment; filename="{filename}"'}
+    return FileResponse(filepath, headers=headers, media_type="audio/mp3")
+
+

An alternative to the above would be to read the file data inside your endpoint (or if the data were already fully loaded into memory, such as here, here and here) and return a custom Response directly, as shown below:

+
from fastapi import Response
+
+@app.post('/text2speech')
+   ...
+    with open(filepath, "rb") as f:
+        contents = f.read() 
+    
+    headers = {'Content-Disposition': f'attachment; filename="{filename}"'}
+    return Response(contents, headers=headers, media_type='audio/mp3')
+
+

In case you had to return a file that is too large to fit into memory—e.g., if you have 8GB of RAM, you can’t load a 50GB file—you could use StreamingResponse, which would load the file into memory in chunks and process the data one chunk at a time:

+
from fastapi.responses import StreamingResponse
+
+@app.post('/text2speech')
+    ...
+    def iterfile():
+        with open(filepath, "rb") as f:
+            yield from f
+
+    headers = {'Content-Disposition': f'attachment; filename="{filename}"'}
+    return StreamingResponse(iterfile(), headers=headers, media_type="audio/mp3")
+
+

templates/index.html

+
<!DOCTYPE html>
+<html>
+   <head>
+      <title>Convert Text to Speech</title>
+   </head>
+   <body>
+      <form method="post" action="http://127.0.0.1:8000/text2speech">
+         message : <input type="text" name="message" value="This is a sample message"><br>
+         language : <input type="text" name="language" value="en"><br>
+         <input type="submit" value="submit">
+      </form>
+   </body>
+</html>
+
+

Option 2

+

app.py

+
from fastapi import FastAPI, Request, Form
+from fastapi.templating import Jinja2Templates
+from fastapi.responses import FileResponse
+import uuid
+import os
+
+app = FastAPI()
+templates = Jinja2Templates(directory="templates")
+
+files = {}
+
+@app.get('/')
+def main(request: Request):
+    return templates.TemplateResponse("index.html", {"request": request})
+
+@app.get('/download')
+def download_file(request: Request, fileId: str):
+    filepath = files.get(fileId)
+    if filepath:
+        filename = os.path.basename(filepath)
+        headers = {'Content-Disposition': f'attachment; filename="{filename}"'}
+        return FileResponse(filepath, headers=headers, media_type='audio/mp3')    
+    
+@app.post('/text2speech')
+def convert(request: Request, message: str = Form(...), language: str = Form(...)):
+    # do some processing here
+    filepath = './temp/welcome.mp3'
+    file_id = str(uuid.uuid4())
+    files[file_id] = filepath
+    file_url = f'/download?fileId={file_id}'
+    return {"fileURL": file_url}
+
+

templates/index.html

+
<!DOCTYPE html>
+<html>
+   <head>
+      <title>Convert Text to Speech</title>
+   </head>
+   <body>
+      <form method="post" id="myForm">
+         message : <input type="text" name="message" value="This is a sample message"><br>
+         language : <input type="text" name="language" value="en"><br>
+         <input type="button" value="Submit" onclick="submitForm()">
+      </form>
+
+      <a id="downloadLink" href=""></a>
+
+      <script type="text/javascript">
+         function submitForm() {
+             var formElement = document.getElementById('myForm');
+             var data = new FormData(formElement);
+             fetch('/text2speech', {
+                   method: 'POST',
+                   body: data,
+                 })
+                 .then(response => response.json())
+                 .then(data => {
+                   document.getElementById("downloadLink").href = data.fileURL;
+                   document.getElementById("downloadLink").innerHTML = "Download";
+                 })
+                 .catch(error => {
+                   console.error(error);
+                 });
+         }
+      </script>
+   </body>
+</html>
+
+

Removing a File after it has been downloaded

+

To remove a file after it has been downloaded by the user, you can simply define a BackgroundTask to be run after returning the response. For example, for Option 1 above:

+
from fastapi import BackgroundTasks
+import os
+
+@app.post('/text2speech')
+def convert(request: Request, background_tasks: BackgroundTasks, ...):
+    filepath = 'welcome.mp3'
+    # ...
+    background_tasks.add_task(os.remove, path=filepath)
+    return FileResponse(filepath, headers=headers, media_type="audio/mp3")
+
+

For Option 2, however, you would have to make sure to delete the key (i.e., file_id) pointing to the given filepath from the cache as well. Hence, you should create a task function, as shown below:

+
from fastapi import BackgroundTasks
+import os
+
+files = {}
+
+def remove_file(filepath, fileId):
+    os.remove(filepath)
+    del files[fileId]
+       
+@app.get('/download')
+def download_file(request: Request, fileId: str, background_tasks: BackgroundTasks):
+    filepath = files.get(fileId)
+    if filepath:
+        # ...
+        background_tasks.add_task(remove_file, filepath=filepath, fileId=fileId)
+        return FileResponse(filepath, headers=headers, media_type='audio/mp3')    
+
",python +"Average price of scraped item on ebay using python

How can I get the average price from a list of scraped items' prices from ebay?

+

This is my code:

+
from urllib.request import Request, urlopen
+from bs4 import BeautifulSoup
+import requests
+from requests_html import HTMLSession
+
+link = "https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=p2334524.m570.l1313&_nkw=5035224123933&_sacat=0&LH_TitleDesc=0&_odkw=EAN5035224123933&_osacat=0"
+
+req = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
+webpage = urlopen(req).read()
+with requests.Session() as c:
+    
+     soup = BeautifulSoup(webpage, 'html5lib')
+     lists = soup.find_all('li', class_="s-item s-item__pl-on-bottom s-item--watch-at-corner")
+     for list in(lists):
+        price=float(list.find('span', class_="s-item__price").text.replace('£',''))
+        avg = sum(price)/len(price)
+
+

I've tried:

+
avg = sum(price)/len(price)
+
+

But it gives an error:

+
TypeError: 'float' object is not iterable
+
","

Assuming that the rest of your code works correctly, and retrieves the prices you need, the problem is with this:

+
    for list in(lists):
+        price=float(list.find('span', class_="s-item__price").text.replace('£',''))
+        avg = sum(price)/len(price)
+
+

You say price=float(..) - so yes, price is a floating point number and thus trying to sum() and len() it on the next line doesn't make sense to Python. You probably wanted to put all those prices in a list (e.g. prices) and then compute sum(prices) / len(prices)

+

Something like:

+
    prices = []
+    for list in lists:
+        prices.append(float(list.find('span', class_="s-item__price").text.replace('£','')))
+    avg = sum(prices) / len(prices)
+
+

To understand why you got that error, consider:

+
>>> sum(1.0)
+Traceback (most recent call last):
+  File "<stdin>", line 1, in <module>
+TypeError: 'float' object is not iterable
+>>> len(1.0)
+Traceback (most recent call last):
+  File "<stdin>", line 1, in <module>
+TypeError: object of type 'float' has no len()
+
+

So, you see those operations don't work on invidual values, they work on an iterable with a length (like a list). Another clue about your original code is that the computation of the average was inside the loop (indented), but you only want to compute the average once, not for every price.

",python +"Fetching data using React to a Python backend

I am using python (bottle framework) as backend and React as frontend. I want to fetch data from React through "http://127.0.0.1:8080/" using useEffect Hook. The problem is I keep getting:

+

+

Here is my backend (python)

+
@get('/')
+def _():
+    data = {
+        'name': 'Alvin',
+        'lastname': 'Johnson'
+    }
+    return json.dumps(data)
+
+

And here is the frontend (react)

+
import React, { useEffect, useState } from 'react';
+
+import './App.css';
+
+function App() {
+
+  const [data, setdata] = useState({
+    name: '',
+    lastname: ''
+  });
+
+  useEffect(() => {
+    fetch('/').then((res) =>
+      res.json()).then((data) => {
+        console.log(data);
+        setdata({
+          name: data.name,
+          lastname: data.lastname
+        });
+      })
+  }, []);
+
+  return (
+    <div className="App">
+      <h1>Welcome to Python-React app</h1>
+      <p>{data.name}</p>
+      <p>{data.lastname}</p>
+    </div>
+  );
+}
+
+export default App;
+
+

I have also added "proxy" on package.json file

+
"proxy":"http://127.0.0.1:8080/",
+
+

Is there anything I am doing wrong? Thank you in advance.

","

consider using axios, thats what I use for my Flask backend.

+
import axios from 'axios';
+import React, { useEffect, useState } from 'react';
+import './App.css';
+
+function App() {
+
+  const [data, setdata] = useState({
+    name: '',
+    lastname: ''
+  });
+
+  const fetchData = async () => {
+      const response = await axios.get(`http://127.0.0.1:8080/`)
+      setdata(response.data);
+      }
+
+  useEffect(() => {
+    fetchData(); 
+      }, [])
+
+  return (
+    <div className="App">
+      <h1>Welcome to Python-React app</h1>
+      <p>{data.name}</p>
+      <p>{data.lastname}</p>
+    </div>
+  );
+}
+
+export default App;
+
",python +"How to get text data from a single tag without comma seperator using scrapy

below is the html snippet

+
<P class="subtitulo">
+ <b>
+  <a name="Editores"> Editorial </a>
+    "assistant"
+ </b>
+</p>
+
+

by using this scrapy code

+
response.css("p.subtitulo *::text").extract()
+
+

I get

+
+

['Editorial', ' Assistant']

+
+
response.css("p.subtitulo *::text").get()
+
+

I get only "

+
+

Assistant

+
+

" +I want the full string without any commas like

+
+

"Editorial Assistant"

+
+

Using Beautiful soup I am getting the text without comma. But how to do it with Scrapy. Since I have other roles separated by commas I don't want to use split().

+

This is the page url +http://www.scielo.org.co/revistas/zop/iedboard.htm

","

You can do that by invoking .join() and .getall() method as follows:

+
import scrapy
+class TestSpider(scrapy.Spider):
+    name = 'test'
+    start_urls = ['http://www.scielo.org.co/revistas/zop/iedboard.htm']
+        
+    def parse(self, response):
+        for p in response.css('.subtitulo')[1:]:
+            yield {
+            'Name': ''.join(p.css("::text").getall())
+            }
+
+

Output:

+
{'Name': 'Editorial Assistant'}
+2022-08-08 15:39:03 [scrapy.core.scraper] DEBUG: Scraped from <200 http://www.scielo.org.co/revistas/zop/iedboard.htm>
+{'Name': 'Editorial Committee '}
+2022-08-08 15:39:03 [scrapy.core.scraper] DEBUG: Scraped from <200 http://www.scielo.org.co/revistas/zop/iedboard.htm>
+{'Name': 'Scientific Committee'}
+2022-08-08 15:39:03 [scrapy.core.scraper] DEBUG: Scraped from <200 http://www.scielo.org.co/revistas/zop/iedboard.htm>
+{'Name': 'Editorial Universidad Del Norte'}
+
",python +"Parsing unusual data (chess data) in a dataframe column

I'm writing a function to put data from a chess website into a dataframe. +The code I was able to write almost got the job done but not quite.

+
import chessdotcom
+import pandas as pd
+import regex as re
+import json
+from io import StringIO
+#
+def cleandata(datacall):
+  data = datacall.text
+  x = json.loads(data)
+  df = pd.read_json(StringIO(json.dumps(x)))
+  df2 = pd.json_normalize(df['games'])
+  df2.to_csv(r'chessdataframegamesv3.csv')
+#
+datacall = chessdotcom.client.get_player_games_by_month("Player1", 2022, 7)
+cleandata(datacall)
+
+

This produced a csv file that had the columns url, pgn, time_control, etc. +The pgn column is the one that I'm having trouble working with. +It has a lot of information for each row. Just one row has Event: Live Chess, Site "Chess.com", Date "2022.07.01", Round "-", White "Player2",Black "Player1",Result "1-0",CurrentPosition "6Q1/5K1k/8/2p5/1p6/p7/1PN5/8 b - -",Timezone "UTC", ECO "B18", ECOUrl "https://www.chess.com/openings/Caro-Kann-Defense-Classical-Variation-5.Ng3-Bg6-6.Nf3-Nd7-7.Bd3", UTCDate "2022.07.01", UTCTime "13:37:42", WhiteElo "1611", BlackElo "1616", TimeControl "180+2", Termination "Player2 won on time", StartTime "13:37:42", EndDate "2022.07.01", EndTime "13:47:01", Link "https://www.chess.com/game/live/50421603881". These are each in square brackets. These are also followed by the moves played in the game

+

Ideally, this information should for the most part be separate columns. So there should be a column "Event" with value "Live Chess" for example. Also, it would be good to have a separate row for each move, in a "moves" column. However, having all the moves in the moves column would also be acceptable. Does anyone know how to do this? This is my first question here. So I hope I'm clear enough. Thanks.

","

I suggest to use python-chess for pgn parsing:

+
pip install chess
+
+

Then you can use it as follows:

+
import json
+from io import StringIO
+
+import chess.pgn
+from chessdotcom import client
+import pandas as pd
+
+def read_pgn(pgn_str):
+    game = chess.pgn.read_game(StringIO(pgn_str))
+    headers = game.headers
+    headers['moves'] = game.mainline_moves()
+    return headers
+
+# "erik" is taken as an example from here: https://www.chess.com/news/view/published-data-api
+player, year, month = "erik", 2022, 7
+r = client.get_player_games_by_month(player, year, month)
+
+games = json.loads(r.text)['games']
+df1 = pd.json_normalize(games)
+df2 = pd.DataFrame(list(df1.pgn.apply(read_pgn)))
+pd.concat([df1, df2], axis=1).drop(columns='pgn')
+
+

This will give you the following dataframe:

+
                                             url time_control    end_time  rated  ...   Variant        White WhiteElo                                              moves
+0     https://www.chess.com/game/daily/410529597     1/259200  1656675306  False  ...       NaN   TheMsquare     1592  3. Nc3 { [%clk 69:37:31] } 3... Bg7 { [%clk 71...
+1     https://www.chess.com/game/daily/387673189     1/604800  1656675605   True  ...  Chess960         erik     1434  1. b3 { [%clk 167:59:49] } 1... Ne6 { [%clk 16...
+2     https://www.chess.com/game/daily/410866161     1/259200  1656679900   True  ...       NaN          Lee     1356  1. e4 { [%clk 62:04:50] } 1... d6 { [%clk 71:3...
+3    https://www.chess.com/game/live/50449822647           60  1656711104   True  ...       NaN        rexzs     1744  1. e3 { [%clk 0:01:00] } 1... d6 { [%clk 0:01:...
+4    https://www.chess.com/game/live/50450421549           60  1656711671   True  ...       NaN         erik     1823  1. e4 { [%clk 0:01:00] } 1... c6 { [%clk 0:01:...
+..                                           ...          ...         ...    ...  ...       ...          ...      ...                                                ...
+214  https://www.chess.com/game/live/52974588839           60  1659235731   True  ...       NaN         erik     1741  1. e4 { [%clk 0:01:00] } 1... e6 { [%clk 0:01:...
+215  https://www.chess.com/game/live/52975772965           60  1659236887   True  ...       NaN  GeneralCoin     1672  1. d4 { [%clk 0:01:00] } 1... d6 { [%clk 0:01:...
+216  https://www.chess.com/game/live/52976977887           60  1659238132   True  ...       NaN    MarcosP99     1772  1. e4 { [%clk 0:01:00] } 1... d6 { [%clk 0:01:...
+217  https://www.chess.com/game/live/52977007497           60  1659238338   True  ...       NaN         erik     1730  1. e4 { [%clk 0:01:00] } 1... c5 { [%clk 0:01:...
+218  https://www.chess.com/game/live/53060949585           60  1659321932   True  ...       NaN         erik     1724  1. e4 { [%clk 0:01:00] } 1... c5 { [%clk 0:01:...
+
+[219 rows x 50 columns]
+
",python +"tkinter multiple buttons invoke same function, how to determine the clicked one?

I used for loop to render 15 buttons, and each button invokes the same function to do something. My question is how to determine which button is clicked? +My code snippet is like below:

+
for number in range(1, 16):
+    ttk.Button(bottom_frame, text='Read', command=read_one).grid(column=4, row=number, padx=5, pady=5)
+
+

I want to reuse the function read_one() for every button, but don't know how to determine which button is clicked. Any comment is appreciated! +Here's my test code: https://pastebin.com/fWyyNVw7

","

Since the command callback doesn't get passed any parameters by default (like the calling control), there's no easy option.

+

However, you could use something like this:

+
for number in range(1, 16):
+    ttk.Button(bottom_frame, text='Read', command=lambda number=number: read_one(number)
+        ).grid(column=4, row=number, padx=5, pady=5)
+
+

That way, read_one will be called with the number passed. Note that you'd need your read_one function to deal with it, e.g.:

+
def read_one(number):
+    # do something with number, since it tells you what button was pushed
+    ...
+
",python +"How do I compare two lists of pairs to see which pair combinations exist in both?

Here is a simple example of what I am trying to do. So with two lists of pairs, such as:

+
pairs1 = [(egg,dog),(apple,banana),(orange,chocolate),(elephant,gargoyle),(cat,lizard)]
+pairs2 = [(cat,lizard),(ice,hamster),(elephant,giraffe),(apple,gargoyle),(dog,egg)]
+
+

I want to be able to retrieve the pair combinations that the two lists have in common. So for these two lists, the pairs retrieved would be (cat,lizard) and (dog,egg). The order of the elements within in the pair don't matter, just the fact that the pair combination is within the same tuple.

","

Try:

+
pairs1 = [
+    ("egg", "dog"),
+    ("apple", "banana"),
+    ("orange", "chocolate"),
+    ("elephant", "gargoyle"),
+    ("cat", "lizard"),
+]
+pairs2 = [
+    ("cat", "lizard"),
+    ("ice", "hamster"),
+    ("elephant", "giraffe"),
+    ("apple", "gargoyle"),
+    ("dog", "egg"),
+]
+
+x = set(map(frozenset, pairs1)).intersection(map(frozenset, pairs2))
+print(list(map(tuple, x)))
+
+

Prints:

+
[('lizard', 'cat'), ('egg', 'dog')]
+
",python +"Camera is not Detecting the face and showing details

I am getting a type error in my Python Code

+

Code:

+
my_cursor.execute("select Gender from student where Id=" + str(id))
+          g = my_cursor.fetchone()
+          g = "+".join(g)
+
+

error:

+
+

n="+".join(n)

+
+
+

TypeError: can only join an iterable

+
","

you can use my_cursor as an iterable result

+
my_cursor.execute("select Gender from student where Id=" + str(id))
+result = "+".join(my_cursor)
+
+

You can see more in here

",python +"Shell - Pass env variable to Python Script

I have the shell script where I create a Python file on the fly:

+
#!/bin/bash
+
+args=("$@")
+
+GIT_PASSWORD=${args[0]}
+export $GIT_PASSWORD
+
+python - << EOF
+
+import os
+
+print(os.environ.get("GIT_PASSWORD"))
+                                                         
+EOF
+
+echo $GIT_PASSWORD
+
+echo "Back to bash"
+
+

I want to be able to access the variable GIT_PASSWORD, but unfortunately, I am not able to pass it to the python file.

+

Does anyone know what I am doing wrong and how I may fix that?

","

The thing is that you're not actually setting an env variable, you need to change the export:

+
export GIT_PASSWORD=$GIT_PASSWORD
+
+

please do read the comment interaction below

",python +"Change a variable given in a function

I want to make a function that checks if a random number is within a certain value and if it is then reroll the number for that variable.

+

But I don't know how to set the input variable without calling its name directly.

+

code:

+
def checkVal(value,max,min):
+    if value<max or value>min:
+        value=random.randrange((-30/10),(30/10))
+        checkVal(value,min,max)
+    else:
+        pass
+
","

You can't charge a variable from within a function without using a global, however this wouldn't be good practice here. Rather return your value.

+

Also your test would always be True if max>min, you probably meant to swap the conditions (lower > value or value > upper).

+
def checkVal(value, upper, lower):
+    if lower > value  or value > upper):
+        value = random.randrange((-30/10),(30/10))
+        return checkVal(value, upper, lower)
+    return value
+
+value = checkVal(value, upper, lower)
+
+

From an algorithmic point of view, using a recursive function as a loop is also not so good practice. Rather use a while loop:

+
def checkVal(value, upper, lower):
+    while lower > value  or value > upper:
+        value = random.randrange((-30/10),(30/10))
+    return value
+
+value = checkVal(value, upper, lower)
+
+

Finally, you can probably remove the loop entirely by choosing directly the correct bounds:

+
def checkVal(value, upper, lower):
+    if lower > value  or value > upper:
+        value = random.randrange(max(lower, (-30/10)), min(upper, (30/10)))
+    return value
+
+value = checkVal(value, upper, lower)
+
",python +"How to compute the kind of distance matrix with vectorization

I have an numpy array A of shape 4 X 3 X 2. Each line below is a 2D coordinate of a node. (Each three nodes compose a triangle in my finite element analysis.)

+
array([[[0., 2.],  #node00 
+        [2., 2.],  #node01
+        [1., 1.]], #node02
+
+       [[0., 2.],  #node10
+        [1., 1.],  #node11
+        [0., 0.]], #node12
+
+       [[2., 2.],  #node20
+        [1., 1.],  #node21
+        [2., 0.]], #node22
+
+       [[0., 0.], #node30
+        [1., 1.], #node31
+        [2., 0.]]]) #node32
+
+

I have another numpy array B of coordinates of pre-computed "centers":

+
array([[1.        , 1.66666667], # center0
+       [0.33333333, 1.        ], # center1
+       [1.66666667, 1.        ], # center2
+       [1.        , 0.33333333]])# center3
+
+

How can I efficiently calculate a matrix C of Euclidian distance like this

+
dist(center0, node00) dist(center0,node01) dist(center0, node02)
+dist(center1, node10) dist(center1,node11) dist(center1, node12)
+dist(center2, node20) dist(center2,node21) dist(center2, node22)
+dist(center3, node30) dist(center3,node31) dist(center3, node32)
+
+

where dist represents a Euclidian distance formula like math.dist or numpy.linalg.norm? Namely, the result matrix's i,j element is the distance between center-i to node-ij.

+

Vectorized code instead of loops is needed, as my actual data is from medical imaging which is very large. With a nested loop, one can obtain the expected output as follows:

+
In [63]: for i in range(4):
+    ...:     for j in range(3):
+    ...:         C[i,j]=math.dist(A[i,j], B[i]) 
+
+In [67]: C
+Out[67]:
+array([[1.05409255, 1.05409255, 0.66666667],
+       [1.05409255, 0.66666667, 1.05409255],
+       [1.05409255, 0.66666667, 1.05409255],
+       [1.05409255, 0.66666667, 1.05409255]])
+
+

[Edit] This is different question from Pairwise operations (distance) on two lists in numpy, as things like indexing needs to be properly addressed here.

","
a = np.reshape(A, [12, 2])
+b = B[np.repeat(np.arange(4), 3)]
+c = np.reshape(np.linalg.norm(a - b, axis=-1), (4, 3))
+c
+# array([[1.05409255, 1.05409255, 0.66666667],
+#        [1.05409255, 0.66666667, 1.05409255],
+#        [1.05409255, 0.66666667, 1.05409255],
+#        [1.05409255, 0.66666667, 1.05409255]])
+
",python +"How does python handle list unpacking, redefinition, and reference?

I am new to python and am trying to understand how it handles copies vs references in respect to list unpacking. I have a simple code snippet and am looking for an explanation as to why it is behaving the way it does.

+
arr = [1, 2, 3, 4]
+[one, two, three, four] = arr
+print(id(arr[0]), arr[0])
+print(id(one), one)
+one = 5
+print(id(one), one)
+
+

The output is:

+
(16274840, 1)
+(16274840, 1)
+(16274744, 5)
+
+

I am not sure why one is all the sudden moved to a different memory location when I try to modify its contents.

+

I am using python version 2.7.18.

+

This is my first post, so I apologize in advance if I am not adhering to the guidelines. Please let me know if I have violated them.

+

Thank you for all the responses. They have helped me boil down my misunderstanding to this code:

+
var = 1
+print(id(var), var)
+var = 5
+print(id(var), var)
+
+

With output:

+
(38073752, 1)
+(38073656, 5)
+
+

Asking about lists and unpacking them was completely obfuscatory.

+

This does a great job of explaining: +http://web.stanford.edu/class/archive/cs/cs106a/cs106a.1212/handouts/mutation.html

","

The id/address is not associated with the variable/name; it's associated with the data that the variable is referring to.

+

The 1 object is, in this instance, at address 16274840, and the 5 object is at address 16274744. one = 5 causes one to now refer to the 5 object which is at location 16274744.

+
+

Just to rephrase this in terms of C, I think your question essentially boils down to "why does the following not modify the first element of arr?" (I'm ignoring unpacking since it isn't actually relevant to the question):

+
arr = [1, 2, 3, 4]
+one = arr[0]
+one = 5
+
+

I would approximate that code to the following C which also does not modify arr:

+
int internedFive = 5;
+
+int arr[4] = {1, 2, 3, 4};
+
+int* one = &arr[0];
+one = &internedFive;
+
+printf("%d", arr[0]);  // Prints 1
+
+

one originally pointed to the first element of arr, but was reassigned to point to the 5. This reassignment of the pointer has no effect on the data location originally pointed to by one and arr[0].

",python +"Finding Value between two numbers in pandas dataframe

I have two pandas dataframe "A" and "B". I would like to find out row number from "B" where value of "A" lies in between two numbers of "B" data frame.

+

Table A

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Index0
00.084
10.169
20.252
30.337
40.419
50.504
60.589
+
+

Table B

+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Index0
00.071
10.167
20.244
30.320
+
+

In the case of the above tables let's take one example. The First Number from Table "A" is 0.084 it's Actually in between Table B 0 & 1 Index value i.e. 0.071 and 0.167. I am looking out for an output as [0,1] which is basically row numbers of two values.

","

First initialize empty array for result:

+
res = [[]] * len(A.iloc[:, 0])
+
+

Then we implement nested loop through A and B, and check each value in A is between B values and return the index

+

The condition return the start index only:

+
(A.iloc[:, 0][i] > B.iloc[:, 0][j]) & (A.iloc[:, 0][i] < B.iloc[:, 0][j+1])
+
+

So I get the value and add 1 to it later and add them to a list:

+
res[i]=([j , j+1])
+
+

The full code:

+
import pandas as pd
+
+A = [0.084, 0.169, 0.252, 0.337, 0.419, 0.504, 0.589]
+B = [0.071, 0.167, 0.244, 0.320]
+
+A = pd.DataFrame(A)
+B = pd.DataFrame(B)
+
+res = [[]] * len(A.iloc[:, 0])
+
+for i in range(0, len(A.iloc[:, 0])):
+    for j in range(0, len(B.iloc[:, 0])-1):
+        if (A.iloc[:, 0][i] > B.iloc[:, 0][j]) & (A.iloc[:, 0][i] < B.iloc[:, 0][j+1]):
+            res[i]=([j , j+1])
+
+print(res)
+
+

The output: +

+

Note: I assume that B is always sorted in ascending order

",python +"I get an [AttributeError: module 'code' has no attribute 'Main'] error, but the attribute is clearly there. Why?

I'm trying to link a Discord bot to a text-game I made, but when I attempt to call the Class of the game itself, it tells me,

+
AttributeError: module 'code' has no attribute 'Main'
+
+

Here's my code:

+
# bot.py
+import code # Import the code for the actual game
+
+main = code.Main() # Begin the game's processes
+
+
# code.py
+class Main:
+
+    def __init__(self):
+        self.otherModule() # This module is used to continue the flow throughout the class
+
+

I can't see what's wrong with it. When I try to look it up, I'm only told to "just give it a class."

","

Rename code. The module code already exists as a built-in module in Python3.

+
Python 3.10.4
+Type "help", "copyright", "credits" or "license" for more information.
+>>> import code
+>>> print(code)
+<module 'code' from '/usr/lib/python3.10/code.py'>
+
+

Source: https://docs.python.org/3/library/code.html#module-code

",python +"Django Generate cookie before loading page

I'm building an e-commerce website and I'm generating device cookie to store unauthorized users' UUID. If user is not authorized it searches for their cookie and to display quantity of items in cart for given device (at navbar.html). When I run any page I get a KeyError: 'device' as it tries to call function that searches for a cookie which doesn't exist yet. Is there any workaround?

+

base.html

+
<html lang="en">
+  <head>
+    <script>
+
+      function getCookie(name) {
+            var cookieValue = null;
+            if (document.cookie && document.cookie !== '') {
+                var cookies = document.cookie.split(';');
+                for (var i = 0; i < cookies.length; i++) {
+                    var cookie = cookies[i].trim();
+                    // Does this cookie string begin with the name we want?
+                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
+                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+                        break;
+                    }
+                }
+            }
+            return cookieValue;
+          }
+
+      let device = getCookie('device');
+
+      function uuidv4() {
+        return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
+          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
+        );
+      }
+
+      if (device == null || device == undefined) {
+        device = uuidv4();
+      }
+      
+      document.cookie = 'device=' + device + ';domain=;path=/'
+    </script>
+  </head>
+  {% include "navbar.html" %}
+</html>
+
+

navbar.html

+
<span class="badge red z-depth-1 mr-1"> {{ request|cart_item_count }} </span>
+
+

cart_tag.py

+
from django import template
+from store.models import Order, Customer
+register = template.Library()
+
+@register.filter
+def cart_item_count(request):
+    try:
+        customer = request.user.customer
+    except AttributeError:
+        device = request.COOKIES['device']
+        customer, _ = Customer.objects.get_or_create(device=device)
+    qs = Order.objects.filter(customer=customer, ordered=False)
+    if qs.exists():
+        return qs[0].items.count()
+    return 0
+
+
+

EDIT: +views.py

+
from django.views.generic import ListView
+from .models import ShopItem
+class HomeView(ListView):
+    model = ShopItem
+    paginate_by = 4
+    template_name = "home-page.html"
+
+

models.py

+
from django.db import models
+class ShopItem(models.Model):
+    id = models.AutoField(primary_key=True)
+    title = models.CharField(max_length=100)
+    description = models.TextField()
+
","

I think you should change your code like this maybe in cart_tag.py for initial None device cookie.

+
from django import template
+from store.models import Order, Customer
+
+register = template.Library()
+
+
+@register.filter
+def cart_item_count(request):
+    customer = None
+    try:
+        customer = request.user.customer
+    except AttributeError:
+        device = request.COOKIES.get('device', '')
+        if device:
+            customer, _ = Customer.objects.get_or_create(device=device)
+    if customer:
+        qs = Order.objects.filter(customer=customer, ordered=False)
+        if qs.exists():
+            return qs[0].items.count()
+    return 0
+
",python +"Disagreement in confusion matrix and accuracy when using data generator

I was working on a model +based on the following code

+
epoch=100
+model_history = model.fit(train_generator, 
+epochs=epoch,
+validation_data=test_generator,
+callbacks=[model_es, model_rlr, model_mcp])
+
+

After model training when I evaluated the model using the following code, I get an accuracy of 98.3%

+
model.evaluate(test_generator)
+
+

41/41 [==============================] - 3s 68ms/step - loss: 0.0396 - accuracy: 0.9893 +[0.039571091532707214, 0.9893211126327515]

+

In order to analyse the result, I tried to obtain a confusion matrix of the test_generator using the following code

+
y_pred = model.predict(test_generator)
+y_pred = np.argmax(y_pred, axis=1)
+print(confusion_matrix(test_generator.classes, y_pred))
+
+

However the output is

+
[[ 68  66  93  73]
+ [ 64  65  93  84]
+ [ 91 102 126  86]
+ [ 69  75  96  60]]
+
+

which highly disagrees with the model_evaluate

+

Can anyone help me out here to obtain the actual confusion matrix for the model

+

plot history of model accuracy

+

Entire code: https://colab.research.google.com/drive/1wpoPjnSoCqVaA--N04dcUG6A5NEVcufk?usp=sharing

","

From your code, change:

+
test_generator=train_datagen.flow_from_directory(
+    locat_testing,
+    class_mode='binary',
+    color_mode='grayscale',
+    batch_size=32,
+    target_size=(img_size,img_size)
+)
+
+

To include the shuffle parameter:

+
test_generator=train_datagen.flow_from_directory(
+    locat_testing,
+    class_mode='binary',
+    color_mode='grayscale',
+    batch_size=32,
+    target_size=(img_size,img_size),
+    shuffle=False
+)
+
+

Your confusion matrix will look a lot more accurate instead of what looks like randomly guessing.

",python +"iteratively retrieving information contained in different rows in pandas dataframe

I have a dataframe which contains post and comments. +Every comment has an id and a parent id (identifies the comment or post which the comment was a response to). +Posts only have an id, since they don't answer to anything.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
submissionidparent id
post11
comment121
comment231
comment342
comment454
post26
comment576
+
+

I would like to retrieve the id of the original post for every comment and obtain something like that:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
submissionidparent idancestor id
post11
comment1211
comment2311
comment3421
comment4541
post26
comment5762
+
+

to do so I tried to loop from the end of the dataframe to the beginning, iteratively tracing back the parent_id of the parent_id until I found an empty parent_id cell. +On the test dataframe it works, but on the main one is too slow. Is there a way to make it more efficient?

+

Here my original code:

+
#creating a column for the id of the original post
+df["ancestor"] = df.id
+#obtaining the id of the original post for every comment
+for i in reversed(range(len(df.id))): #looping trough the comments
+  id = df["parent_id"][i] #variable to initialize the future loop
+  parent = id
+  while parent != "": #only looping trough comments
+    df.ancestor[i] = id
+    parent = df.parent_id[df.id == id].values[0]
+    id = parent
+
","

I'm not sure if this speeds things up, but using the NetworkX library might be worth a try:

+
import networkx as nx
+
+G = nx.from_pandas_edgelist(
+    df[df["parent_id"].ne("")], source="parent_id", target="id"
+)
+
+roots = set(df.loc[df["parent_id"].eq(""), "id"])
+mapping = {}
+for comp in nx.connected_components(G):
+    root = (roots & comp).pop()
+    roots.discard(root)
+    mapping.update(dict.fromkeys(comp - {root}, root))
+
+df["ancestor_id"] = df["id"].map(mapping)
+
+
    +
  • First read the parent_id-id combos as edges in a graph G.
  • +
  • Identify the root nodes roots of the trees (G should be a forrest, from what I understand).
  • +
  • Then build a mapping nodes -> root (via the components of G), and apply it to the column id.
  • +
+

Result for the example:

+
  submission id parent_id ancestor_id
+0      post1  1                   NaN
+1   comment1  2         1           1
+2   comment2  3         1           1
+3   comment3  4         2           1
+4   comment4  5         4           1
+5      post2  6                   NaN
+6   comment5  7         6           6
+
",python +"Python BeautifulSoup finding table and parsing it

This one is an odd one I ran this code in the morning and it worked just fine on the html from page. Now when I run it the tables variable comes back 0 items so the for loop never happens and no data is collected or data frame created

+
def parseForclosure(pagesource):
+    data = []
+    soup = BeautifulSoup(pagesource,'html.parser')
+    tables = soup.find_all('table', attrs={'class':'ad_tab'})
+    print(len(tables))
+    df2 = pd.DataFrame()
+    for i in range(len(tables)):
+        print(i)
+        table_body = tables[i].find('tbody')
+
+        rows = table_body.find_all('tr')
+        for row in rows:
+            cols = row.find_all('td')
+            cols = [ele.text.strip() for ele in cols]
+            data.append([ele for ele in cols if ele])
+
+        data2 ={'AuctionType': [data[0]] ,
+                'CaseNo': [data[1]],
+                'FinalJudgmentAmount': [data[2]],
+                'ParcelID': [data[3]],
+                'PropertyAddress1': [data[4]],
+                'PropertyAddress2': [data[5]],
+                'AssessedValue': [data[6]],
+                'PlaintiffMaxBid': [data[7]]}
+
+        df = pd.DataFrame(data2, columns=['AuctionType','CaseNo','FinalJudgmentAmount','ParcelID','PropertyAddress1','PropertyAddress2','AssessedValue','PlaintiffMaxBid'] )
+        df2 = df2.append(df)
+    print(df)
+    return(df2)
+
+

Here is the call

+
 df = parseForclosure(source)
+
+

Here is a snippet of what the html look like

+
<table class="ad_tab" tabindex="0"><tbody><tr><th class="AD_LBL" scope="row">Auction Type:</th><td class="AD_DTA">FORECLOSURE</td></tr><tr><th aria-label="Case Number" class="AD_LBL" scope="row">Case #:</th><td class="AD_DTA"><a href="/index.cfm?zaction=auction&amp;zmethod=details&amp;AID=103757&amp;bypassPage=1">07009032CA01</a></td></tr><tr><th class="AD_LBL" scope="row">Final Judgment Amount:</th><td class="AD_DTA">$323,248.61</td></tr><tr><th class="AD_LBL" scope="row">Parcel ID:</th><td class="AD_DTA">30-6901-001-2470</td></tr><tr><th class="AD_LBL" scope="row">Property Address:</th><td class="AD_DTA">12260 SW 191 ST</td></tr><tr><th class="AD_LBL" scope="row"></th><td class="AD_DTA">MIAMI, FL- 33177</td></tr> <tr><th class="AD_LBL" scope="row">Assessed Value:</th><td class="AD_DTA">$184,791.00</td></tr><tr><th class="AD_LBL" scope="row">Plaintiff Max Bid:</th><td class="AD_DTA ASTAT_MSGPB">Hidden</td></tr></tbody></table>
+
+

You can see sample of all the tables in the link below.

+

https://projectcodesamples.s3.amazonaws.com/AuctionSample.html

+

My objective is place data points into a dataframe

+

Sample file with missing data points:

+

Sample_Missing_data_points

+

This is a sample file with all datapoints

+

Sample_file_with_no_missing_data_points

+

Ideally I should be able to extract from both without the dataframe size changing

","

Let's say that you have three HTML files with the data you provided since you first posted your question:

+
    +
  • Source.html
  • +
  • Source2.html
  • +
  • Source3.html
  • +
+

I have used this updated code to combine all the data in one dataframe:

+
import io
+import csv
+
+from bs4 import BeautifulSoup
+import pandas as pd
+
+input_files_names = [
+    'Source.html',
+    'Source2.html',
+    'Source3.html'
+]
+def setup_dataframes(files_names):
+    for current_file_name in files_names:
+        with open(current_file_name) as source_file:
+            soup = BeautifulSoup(source_file, 'html.parser')
+
+        field_labels = {
+            'AuctionType': 'Auction Type:',
+            'CaseNo': 'Case #:',
+            'JudgementAmount': 'Final Judgment Amount:',
+            'ParcelID': 'Parcel ID:',
+            'AssessedValue': 'Assessed Value:',
+            'PlaintiffMaxBid': "Plaintiff Max Bid:"
+        }
+
+        column_names = (
+            'AuctionType', 
+            'CaseNo', 
+            'JudgementAmount', 
+            'ParcelID', 
+            'PropertyAddress1', 
+            'PropertyAddress2',
+            'AssessedValue',
+            'PlaintiffMaxBid'
+        )
+
+        def extract_data(soup):
+            for current_table in soup.find_all('table', class_='ad_tab'):
+                current_auction = {}
+                for (current_field, current_labal) in field_labels.items():
+                    current_field_cell = current_table.tbody.find('th', string=current_labal)
+                    if current_field_cell is not None:
+                        current_data_cell = current_field_cell.next_sibling
+                        current_auction[current_field] = current_data_cell.get_text()
+                
+                address_row = current_table.tbody.find('th', string='Property Address:')
+                if address_row is not None:
+                    current_auction['PropertyAddress1'] = address_row.find_next_sibling('td').get_text()
+                
+                    address2_row = address_row.parent.next_sibling.td
+                    if address2_row is not None:
+                        current_auction['PropertyAddress2'] = address2_row.get_text()
+
+                yield tuple(current_auction.get(current_field, '') for current_field in column_names)
+
+        with io.StringIO() as intermediate_data:
+            intermediate_csv = csv.writer(intermediate_data)
+            intermediate_csv.writerows(extract_data(soup))
+            intermediate_data.seek(0, 0)
+            df = pd.read_csv(intermediate_data, header=None, names=column_names)
+
+        yield df
+
+df_composite = pd.concat(setup_dataframes(input_files_names), ignore_index=True)
+print(df_composite)
+
+

What has been done here is:

+
    +
  • Extracting the text from the source HTML file by finding each file before creating a output row
  • +
  • Creating a temporary, in memory, CSV file using io.StringIO and the csv module
  • +
  • Creating a Pandas dataframe from that CSV file using pd.read_csv()
  • +
+

If you are processing a lot of data you may consider writing to a real file instead instead of using an in-memory file.

",python +"Change how PyAD searches for Users

I am working on creating a python script that can connect to AD and search for user attributes such as (name, email, location, email, extension). Currently I am searching users by CN to find their AD account. The problem I am running into is that some users have a middle initial in their CN but not on their display name. Is it possible to search a user by their display name or sAMAccount name to then be able to pull the attributes from their AD account?

+

The script is below and works fine when search by CN.

+
from tkinter import N
+from pyad import*
+from pyad import adquery
+from pyad import aduser
+from nameparser import HumanName
+from nameparser.config import CONSTANTS
+
+from StatesFun import StatesL
+
+#connecting to AD
+pyad.set_defaults (ldap_server="", Adminusername="", password="")
+UserName = input("Please input the username of the user requesting a DAT account, (first lastname, not case sensitive)\n")
+
+#Searching user in AD
+user = pyad.aduser.ADUser.from_cn(UserName)
+
+#searching for user attributes
+#pop takes element out of list and converts to string 
+nameAD = user.get_attribute("cn")
+name = nameAD.pop(0)
+emailAD = user.get_attribute("mail")
+email = emailAD.pop(0)
+stAD = user.get_attribute("st")
+st = stAD.pop(0)
+extAD = user.get_attribute("telephoneNumber")
+ext = extAD.pop(0)
+
+#Parses name for initials
+def initials(full_name):
+  initial=""
+  if (len(full_name) == 0):
+   return
+    
+  first_middle_last = full_name.split(" ")
+  for name in first_middle_last:
+    initial=initial+name[0].upper()+""
+  return initial
+
+#Splits First / Last Name into own text values
+Hname = HumanName(name)
+Hname = Hname
+
+#Parses TQL Username from Email
+DatUsrNameAD = (email.split('@'))
+DatUsrName = DatUsrNameAD.pop(0)
+
+print(DatUsrName)
+print(Hname.first)
+print(Hname.last)
+print(initials(name))
+print(StatesL(st))
+print(ext)
+print(email)
+
","

You could use something like this to search by SamAccountName. Would just need to update the base_dn to match you company's domain settings.

+
import pyad.adquery
+
+q = pyad.adquery.ADQuery()
+
+user = 'abc123'
+
+q.execute_query(
+    attributes = ["departmentNumber"],
+    where_clause = f"SamAccountName = '{user}'",
+    base_dn="DC=*,DC=*,DC=*"
+)
+
+for row in q.get_results():
+    dept = row["departmentNumber"]
+    print (dept)
+
",python +"Turning column of list of lists (of unequal length) into separate variable columns (python, pandas)

I'm having trouble turning a column of lists of lists into separate columns. I have a bad solution that works by working on each row independently and then appending them to each other, but this takes far too long for ~500k rows. Wondering if someone has a better solution.

+

Here is the input:

+
>>> import pandas as pd 
+>>> import numpy as np 
+>>> pd.DataFrame({'feat': [[["str1","", 3], ["str3","", 5], ["str4","", 3]],[["str1","", 4], ["str2","", 5]] ]})
+
+
+ + + + + + + + + + + + + + + + + +
feat
0[[str1, , 3], [str3, , 5], [str4, , 3]]
1[[str1, , 4], [str2, , 5]]
+
+

Desired output:

+
>>> pd.DataFrame({'str1': [3, 4], 'str2': [np.nan,5] , 'str3': [5,np.nan], 'str4': [3,np.nan]})
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
str1str2str3str4
03NaN53
145NaNNaN
+
+

Update: Solved by @ifly6! Fastest solution by far. For 100k rows and 80 total variables, the total time taken was 8.9 seconds for my machine.

","

Loading your df, create df1 as follows:

+
df1 = pd.DataFrame.from_records(df.explode('feat').values.flatten()).replace('', np.nan)
+df1.index = df.explode('feat').index
+
+

Set index on df1 from the original data to preserve row markers (passing index=df.explode('feat').index does not work). (Alternatively, to get to the point where you have separated the lists into columns, you could use df.explode('feat')['feat'].apply(pd.Series). I prefer, however, to avoid apply so use the DataFrame constructor instead.)

+

Reset index on df1 then set multi-index (cannot set the column 0 index directly because it overwrites the original index):

+
df1.reset_index().set_index(['index', 0])
+# df1.set_index(0, append=True)  # alternatively should work
+
+

Then unstack. You can drop columns that are all NaN by appending .dropna(how='all', axis=1), yielding:

+
>>> df1.reset_index().set_index(['index', 0]).unstack().dropna(how='all', axis=1)
+         2               
+0     str1 str2 str3 str4
+index                    
+0      3.0  NaN  5.0  3.0
+1      4.0  5.0  NaN  NaN
+
+

This solution also largely avoids hard-coding which specific columns to look at or move about.

",python +"Optional positional argument, that only accepts values from a specified list

I'm rewriting a legacy C program in Python 3, using argparse. The program takes zero, one or more positional arguments, that have to be from a specified list. Let's say the possible values are 'A', 'B', 'C', 'D' and 'E', for simplicity's sake. There are no other arguments in the legacy program, and I don't expect them in the new version. But you never know. :-)

+

If I add the argument without choices, like this:

+
p.add_argument("action", help = "What to do", nargs='*')
+
+

It works perfectly, I can supply zero, one or more of that argument.

+

But if I specify the choice list, like this:

+
p.add_argument("action", help = "What to do", choices=["A", "B", "C", "D", "E"], nargs='*')
+
+

I can no longer specify zero arguments. I get this error:

+
+

error: argument action: invalid choice: [] (choose from 'A', 'B', 'C', +'D', 'E')

+
+

Is there any way to be able to add an argument that will accept zero, one or more arguments from a specified list?

","

You can use the add_argument method once for each option in your list, supplying the whole list as possible choices for each argument, and then use the '?' for the nargs field

+

for example here:

+
import sys
+import argparse
+
+parser = argparse.ArgumentParser(sys.argv[0])
+choices = ["A", "B", "C", "D", "E"]
+for i, choice in enumerate(choices):
+    parser.add_argument(choice, metavar=choice, 
+                        help="Help Message For Choice" + choice, 
+                        choices=choices, nargs='?')
+
+args = parser.parse_args()
+
+

This will accept 0, 1, 2, ... len(choices) arguments. You will probably want to override the usage string if you go this route.

+

python3 name_of_pythonfile.py -h

+
usage: name_of_pythonfile.py [-h] [A] [B] [C] [D] [E]
+
+positional arguments:
+  A           Help Message for ChoiceA
+  B           Help Message for ChoiceB
+  C           Help Message for ChoiceC
+  D           Help Message for ChoiceD
+  E           Help Message for ChoiceE
+
+options:
+  -h, --help  show this help message and exit
+
+
+

To override the default usage message you just need to pass a string to the usage keyword argument in the ArgumentParser constructor.

+
parser = ArgumentParser(prog, usage="My New Usage String")
+
+

argparse docs

",python +"Printing 2 dictionaries at the same line produces different output compared to separate

So when I print the dictionaries alone (price[1] and price[2]) they print the desired output (different outputs), but when I print both at the same time in the same line they produce the same output (both are literally the same)

+
price[1] = driver.find_elements(By.XPATH, """//div[contains(@aria-label, 'dollars')]""") # Get Prices from Calendar
+time.sleep(1.5)
+for i in range(3):
+    print(str(price[1][i].get_attribute("innerHTML")))
+#-----------------------------------------
+vero = driver.find_element(By.XPATH, """//span[contains(text(),'Next')]/following-sibling::button""") # Click The Next Button
+vero.click()
+time.sleep(3)
+print("\n")
+#-----------------------------------------
+price[2] = driver.find_elements(By.XPATH, """//div[contains(@aria-label, 'dollars')]""") # Get Prices from Calendar
+time.sleep(1.5)
+for i in range(3):
+    print(str(price[2][i].get_attribute("innerHTML")))
+
+

So separated from each other they produces an output like this:

+
$101
+$200
+$305
+
+$456
+$789
+$890
+
+

But when I try to print them in the same line at the end of the code:

+
for i in range(3):
+    print(str(price[1][i].get_attribute("innerHTML")) + " <><><>  " + str(price[2][i].get_attribute("innerHTML")))
+
+

It produces this repetition! :

+
$101 <><><> $101
+$200 <><><> $200
+$305 <><><> $305
+
+

How do I produce this desired outcome? :

+
$101 <><><> $456
+$200 <><><> $789
+$305 <><><> $890
+
","

If your print statements are OK. This should work, otherwise it seems your Web driver is fetching same data for the two prices.

+
Price_values_1 = [] 
+
+for i in range(3):
+    Price_values_1.append(str(price[1][i].get_attribute("innerHTML")))
+#-----------------------------------------
+Price_values_2 = [] 
+
+for i in range(3):
+    Price_values_2.append(str(price[2][i].get_attribute("innerHTML")))
+
",python +"Trying to make a leveling system, however it only works once and then stops working?

I'm making a leveling system and it only levels me up once and then stops working. Once it levels me the xp doesn't reset and my level does not go up. Here's the code!

+
level = int(1)
+crexp = int(260)
+reqxp = int(100)
+while crexp >= reqxp:
+    level = level+1
+    crexp = crexp-reqxp
+    reqxp = (reqxp/100)*120
+    continue
+while 3 > 2:
+    pinput = input()
+    if pinput == "1":
+        crexp = crexp + 60
+    elif pinput == "2":
+        print(level)
+    elif pinput == "3":
+        print(crexp)
+    elif pinput == "4":
+        print(reqxp)
+    elif pinput == "5":
+        break
+
","

The problem with your current code is that you are not rerunning the 'level up' part of the code. Python generally (when not in a while/for loop e.c.t) reads your code from top to bottom. This means by the time you get into the second while loop the first while loop has finished and will never be run again. +To fix this you want to tell python to recalculate the level and experience variables at certain points - the easiest way to do this is to make the first while loop into a function and call it at the start of the second while loop. You would get something like this -

+
def checkLevelUp(currentXp, requiredXp, currentLevel):
+    while currentXp >= requiredXp:
+        currentLevel = currentLevel+1
+        currentXp = currentXp-requiredXp
+        requiredXp = int(requiredXp * 1.2)
+    return currentLevel, currentXp, requiredXp
+
+
+level = 1
+crexp = 260
+reqxp = 100
+
+
+while True:
+    level, crexp, reqxp = checkLevelUp(crexp, reqxp, level)
+    pinput = input()
+    if pinput == "1":
+        crexp = crexp + 60
+    elif pinput == "2":
+        print(level)
+    elif pinput == "3":
+        print(crexp)
+    elif pinput == "4":
+        print(reqxp)
+    elif pinput == "5":
+        break
+
+

Note also the changes to calculating the next required xp - dividing by 100 and then multiplying by 120 is just the same as multiplying by 1.2.

",python +"Convert a string using regex_replace filter python and ansible

i would convert all the lines here @cat\n@chicken\napple\nfruit\njuice into + : @cat : all\n+ :@chicken: all\n+ :apple : all\n+ : fruit : all\njuice : all in other hand i would get this for every line + : value : all

+

i would use regex_replace filter to perform the task, i don't have too much knowledge on python, i am trying to do this:

+

{{ '@cat\n@chicken\napple\nfruit\njuice'| regex_replace('^(?P<name>)$', '\\g<name>: ALL' , multiline=True, ignorecase=True)}} but nothing happens, i am missing something here

","

You can use

+
regex_replace(r'.+', r'+ : \g<0> : all' )
+
+

to wrap each non-empty line with + : <line_here> : all text.

+

Note that . matches CR chars, too, and if the line endings are CRLF, you will have to replace . with [^\r\n].

+

Here, \g<0> is a replacement backreference to the whole match value, no need using named capturing groups.

",python +"is it possible to add code to a list in python
import PySimpleGUI as sg
+
+rows_needed = 2
+result = [['text1', 'text2'], ['text3']]
+menu_layout = []
+
+for x in range(0,rows_needed):
+    temp = []
+    try:
+        temp.append(sg.Button(c) for c in result[x])
+    finally:
+        pass
+    menu_layout.append(temp)
+    print(menu_layout)
+layout = [[sg.Button(c) for c in result]]
+window = sg.Window('', menu_layout)
+
+window.read()
+
+
+

so im attempting to create a nested list for menu layout, +the result i want would be for example

+
menu_layout = [[sg.Button('text1'), sg.Button('text2')], [sg.Button('text3')],]
+
+

im using pysimplegui

+

my current code at the top gives the following result in powershell

+
+
[[<generator object menu.<locals>.<genexpr> at 0x0000016308733AE0>]]
+[[<generator object menu.<locals>.<genexpr> at 0x0000016308733AE0>],
+[<generator object menu.<locals>.<genexpr> at 0x0000016308733C30>]]
+Traceback (most recent call last):   File
+"C:\Users\cafemax\projects\POS\POS\Client_Posv2.py", line 713, in
+<module>
+    menu()   File "C:\Users\cafemax\projects\POS\POS\Client_Posv2.py", line 532, in menu
+    window = sg.Window('', menu_layout)   File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py",
+line 9604, in __init__
+    self.Layout(layout)   File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py",
+line 9783, in layout
+    self.add_rows(new_rows)   File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py",
+line 9753, in add_rows
+    self.add_row(*row)   File "C:\Users\cafemax\.venvs\stockcontrol\lib\site-packages\PySimpleGUI\PySimpleGUI.py",
+line 9708, in add_row
+    if element.ParentContainer is not None: AttributeError: 'generator' object has no attribute 'ParentContainer'
+
+
+

the reason im trying to do this is because i need to be able to generate a variable amount of buttons based on the size of a list so i can't hard code this.

+

any help on how to fix this or change must make to my append

","

temp doesn't contain sg.Button objects, it contains generators because that's what you appended to it. You don't want to create temp and then append the generator to it, you want to extend your list with your generator. See What is the difference between Python's list methods append and extend?

+
for x in range(0, rows_needed):
+    temp = []
+    try:
+        temp.extend(sg.Button(c) for c in result[x])
+    finally:
+        pass
+    menu_layout.append(temp)
+
+

Alternatively, you can simply create temp using a list comprehension:

+
for x in range(0, rows_needed):
+    temp = []
+    try:
+        temp = [sg.Button(c) for c in result[x]]
+    finally:
+        pass
+    menu_layout.append(temp)
+
+

I'm not sure what the try..finally is for, it doesn't seem to be doing anything, but I left it in because that's not the question you're asking.

",python +"Cleaning string column that contains float number

I am trying to remove the point and zero from every float value within this dataset

+
  index     CIP
+    1        DF5TY34
+    2        12342.0
+    3        de44dW
+
+

(CIP is casted as String)

+

I wrote this line to resolve the problem but its not doing anything and I'm recieving only a warning no errors:

+
 pro1[pro1['CIP'].str.contains('\..')]["CIP"] = pro1.loc[pro1['CIP'].str.contains('\..')]["CIP"].astype(float).astype(int).astype(str)
+
+

this is the warning:

+
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
+A value is trying to be set on a copy of a slice from a DataFrame.
+Try using .loc[row_indexer,col_indexer] = value instead
+
+See the caveats in the documentation: https://pandas.pydata.org/pandas- 
+docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
+"""Entry point for launching an IPython kernel.
+
","

For a strict replacement of .0, you can use removesuffix:

+
df['CIP'] = df['CIP'].str.removesuffix('.0')
+
+

For a more flexible approach, use a regex with str.replace:

+
df['CIP'] = df['CIP'].str.replace('\.0*$', '', regex=True)
+
+

output:

+
   index      CIP
+0      1  DF5TY34
+1      2    12342
+2      3   de44dW
+
+

regex:

+
\.   # match a dot
+0*   # match any number of 0 (including none)
+$    # match end of line
+
",python +"How to find string with spaces between two characters using Regex?

Currently I have a string that I want to parse and pick up certain values.

+

The current regex findall pattern that I have is:

+
re.findall(r'(?P<key>\w+)\s+(?P<value>\w+)')
+
+

With this regex findall pattern I can pick up the key and values of the following:

+
--key1=value1 --key2=value2
+
+

But if the value is a string with spaces, it doesn't pick it up. Examples that doesn't work:

+
--key1=this is value 1 --key2=value2
+--key1=only kvp
+--key1=this/doesnt/work/
+
+

How can I adjust the regex pattern to pick up the string after the = sign?

","

I started by changing your regex to --(?P<key>\w+)=(?P<value>\w+). This way, it uses "=" instead of a whitespace as a separator between key and value. It also requires "--" to precede the key, which seems to be a rule in your data.

+

Now let tackle the main problem which is to capture as a value everything after the "=" sign unless it is the next key.

+

This can be done in three steps:

+
    +
  1. Change regex for the value from \w+ to .+. You want to capture all characters so you cannot limit yourself to just \w. . will capture everything. Of course this change caused a new problem: the value will now contain everything that follows the key, even if it is "value1 --key2=value2". This will be fixed in the remaining two steps.

    +
  2. +
  3. The next step is to make the regex non-greedy. Change the regex for value from .+ to .+? and it will capture the least characters it can instead of the most. This still doesn't solve the problem because the regex will capture only one character of the value. We are a step closer, though.

    +
  4. +
  5. The last step is to prevent the regex from stopping capturing the value until it encounter the next key or the end of the string. Add (?=$|\s--) at the end. (?=) is a positive lookahead. It means that the next part must follow the current position but it is not part of the match itself. $|\s-- is an alternation of either end of the string or a whitespace and two dashes.

    +
  6. +
+

The finished regex is:

+
re.findall(r'--(?P<key>\w+)=(?P<value>.+?)(?=$|\s--)', string)
+
+

It should handle everything other than a value that contains --. +For example:

+
import re
+string = "--key1=value 1 has--really .:weird:. characters --key2=value2"
+result = re.findall(r'--(?P<key>\w+)=(?P<value>.+?)(?=$|\s--)', string)
+print(result)
+
+

gives:

+
[('key1', 'value 1 has--really .:weird:. characters'), ('key2', 'value2')]
+
",python +"Airflow: unable to configure handler ""processor""

I'm very very new to Apache-airflow, just started a course in udemy (this course) .

+

We have recieved YAML file and were asked to follow instructions in order to install airflow. +I have been able to install airflow, I beleive, because I have gotten any error while doing the next steps:

+
    +
  1. create a new file new_file.env (Visual Studio)
  2. +
  3. add these lines inside new file and save it :
  4. +
+
AIRFLOW_IMAGE_NAME=apache/airflow:2.3.0
+AIRFLOW_UID=50000
+
+
    +
  1. open the terminal and run
  2. +
+
docker-compose up -d
+
+

Then when I tried to open localhost:8080 nothing was opened.

+

When I checked the containers, using

+
docker-compose ps
+
+

I have seen that some of the containers are not healthy.

+
docker logs materials_name_of_the_container #here I inserted every tome different container name
+
+

The most common error was "unable to configure handler "processor"

+

I have seen here post with similar problem that recommened to use pip to install Azure ,and I have tried to print this in the terminal:

+
pip install 'apache-airflow[azure_blob_storage,azure_data_lake,azure_cosmos,azure_container_instances]
+
+#also tried with one more '
+
+pip install 'apache-airflow[azure_blob_storage,azure_data_lake,azure_cosmos,azure_container_instances]'
+
+

I got an error that pip is not recognized: +

+

My goal is to complete the installation , and "on -the-way" to understand why these errors happened. I beleive the the YAML file is well (because it's an organized course), but no idea where or what happenned inside the contaienrs, and where these containers are located, so any "dummy" explaination for beginner is welcome.

","

In the end I could solve this issue , after reading this troubleshooting page. I was trying to configure the users&groups, then I have realized that for some reason, my user is not the administrator. I have changed it, uninstall everything (docker+visual studio) and then installed it again , and- yayyy! it worked and this error didn't appear.

+

so the steps I did: +~the foirst part of changing to administrator- I have done yesterday and I don't remember 100% how, I think it was this, if it's wrong please let me know...

+
    +
  1. Enter the users&groups - that was not available in my windows 10, if I remember correct, I have pressed "windows" +"R" on the keyboard, and then I typed "netplwiz" and pressed enter. +
    +2.double click on the username, and this tab was opened:
  2. +
+

+
    +
  1. select administraor (the screenshow is after the fix so maybe it doesn't have the docker options)
  2. +
+

4. restart the computer
+5. uninstalled docker and visual studio
+6. installed docker and visual studio again
+7. docker-compose up -d ....
+then after few minutes it worked.

+

Thanks for everyone who tried to help me :)

+

let me know if there is somethin g to improve in this answer.

",python +"Is there a vectorized way to find maxes within labeled areas in NumPy?

I have a 2D array representing tree heights, where 0 is the ground. I have another array that's always the same size showing segmented and labeled trees, where a 0 label means ground, and a positive integer value represents a unique tree. Here are some slices of the data:

+
heights = array([[37.5 , 41.82, 42.18, 42.18, 42.18, 39.23, 40.68, 40.71, 40.71,
+        40.19, 35.03, 41.41, 41.41, 41.41, 40.77, 32.23, 32.23, 32.23,
+        31.45, 25.6 , 25.63, 30.12, 30.78, 30.78, 30.92],
+       [37.5 , 37.5 , 41.82, 42.18, 41.78, 41.78, 40.68, 40.68, 40.68,
+        40.19, 41.04, 41.41, 41.41, 41.41, 41.03, 32.23, 32.23, 32.23,
+        31.25, 25.6 , 25.6 , 30.12, 30.12, 21.08, 30.88],
+       [37.5 , 37.5 , 34.61, 41.78, 41.78, 25.6 , 39.14, 40.68, 38.79,
+        38.79, 41.04, 41.04, 41.8 , 41.8 , 41.8 , 24.66, 24.66, 31.25,
+        25.63, 26.24, 26.2 , 25.2 , 24.93, 21.03, 21.03],
+       [34.53, 34.61, 34.61, 35.23, 35.23, 25.32, 25.32, 33.17, 33.17,
+        38.86, 39.4 , 40.31, 41.8 , 41.8 , 41.8 , 41.17, 25.37, 26.77,
+        27.32, 27.39, 27.39, 26.96, 25.2 , 28.68, 28.68],
+       [34.53, 34.52, 36.5 , 36.58, 36.67, 36.67, 25.15, 33.17, 38.65,
+        38.86, 39.4 , 39.53, 40.78, 41.17, 41.17,  0.  , 26.77, 27.09,
+        27.39, 27.6 , 27.6 , 28.  , 28.16, 28.68, 28.68],
+       [32.22, 36.45, 37.1 , 37.28, 37.28, 38.07, 30.98, 31.12, 38.65,
+        38.65, 39.12, 39.4 , 40.78, 40.78,  0.  ,  0.  , 27.41, 27.72,
+        27.72, 28.49, 28.49, 28.16, 28.34, 28.87, 28.68],
+       [36.45, 37.1 , 37.1 , 37.28, 38.23, 38.23, 38.23, 33.61, 32.31,
+        38.65, 38.65, 38.62, 39.01, 33.75, 34.65, 34.65, 27.41, 27.72,
+        27.72, 28.49, 28.49, 28.49, 28.87, 30.31, 30.31],
+       [35.71, 36.45, 37.1 , 30.96, 38.23, 38.23, 38.23, 33.61, 33.28,
+        33.42, 33.5 , 33.5 , 33.51, 34.07, 34.65, 34.65, 27.36, 27.83,
+        27.83, 28.49, 28.49, 28.43, 28.87, 31.82, 31.68],
+       [14.44,  0.  ,  0.  ,  0.  , 21.41, 32.98, 33.61, 33.61, 34.27,
+        34.8 , 34.8 , 33.5 , 33.4 , 34.07, 34.65, 34.65,  0.  , 27.83,
+        27.83, 28.7 , 29.18, 29.18, 31.82, 31.82, 31.98],
+       [13.46,  0.  ,  0.  , 21.41, 21.73, 31.36, 33.33, 33.33, 34.89,
+        34.99, 34.99, 32.72, 33.4 , 33.8 , 33.8 ,  0.  ,  0.  ,  0.  ,
+        28.7 , 28.7 , 29.64, 29.64, 31.82, 31.82, 35.82],
+       [13.46,  0.  ,  0.  ,  0.  , 21.73, 31.36, 31.46, 35.81, 36.33,
+        36.33, 36.33, 32.72, 33.37, 33.71, 33.71,  0.  ,  0.  ,  0.  ,
+        28.7 , 29.64, 29.64, 29.77, 29.77, 29.77, 35.95],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  , 24.07, 31.57, 35.9 , 36.33,
+        36.33, 36.33, 21.97, 32.72, 33.37, 33.37,  0.  ,  0.  ,  0.  ,
+        28.36, 29.04, 29.64, 29.77, 29.77, 29.77, 35.95],
+       [ 0.  ,  0.  ,  0.  ,  0.  , 22.09, 24.07, 23.92, 31.57, 35.9 ,
+        36.33,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+        28.38, 29.53, 28.96, 28.96, 28.69, 29.19, 35.49],
+       [ 0.  ,  0.  ,  0.  ,  0.  , 22.09, 22.09, 22.09,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+        29.53, 29.53, 29.82, 28.96, 28.73, 29.19, 29.19],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+        29.53, 30.12, 30.12, 29.82, 28.73,  0.  , 28.89],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  , 30.12, 30.12, 30.12, 28.94,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  , 30.12, 30.12, 29.82,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  , 28.65, 28.65,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
+       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,
+         0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ]], dtype=float32)
+
+
labeled_trees = array([[33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37,
+        37, 37, 37, 37, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37,
+        37, 37, 37, 37, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37,
+        37, 37, 37, 39, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37, 37,
+        37, 37, 39, 39, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37, 37,  0,
+        39, 39, 39, 39, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37,  0,  0,
+        39, 39, 39, 39, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37, 37,
+        37, 39, 39, 39, 39, 39, 39, 39, 39],
+       [33, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37, 37, 37, 37,
+        37, 39, 39, 39, 39, 39, 39, 39, 39],
+       [33,  0,  0,  0, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37, 37,
+         0, 39, 39, 39, 39, 39, 39, 39, 39],
+       [33,  0,  0, 33, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37,  0,
+         0,  0, 39, 39, 39, 39, 39, 39, 39],
+       [33,  0,  0,  0, 33, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37,  0,
+         0,  0, 39, 39, 39, 39, 39, 39, 39],
+       [ 0,  0,  0,  0,  0, 33, 33, 33, 33, 33, 33, 33, 37, 37, 37,  0,
+         0,  0, 39, 39, 39, 39, 39, 39, 39],
+       [ 0,  0,  0,  0, 33, 33, 33, 33, 33, 33,  0,  0,  0,  0,  0,  0,
+         0,  0, 39, 39, 39, 39, 39, 39, 39],
+       [ 0,  0,  0,  0, 33, 33, 33,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0, 39, 39, 39, 39, 39, 39, 39],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0, 39, 39, 39, 39, 39,  0, 39],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0, 39, 39, 39, 39,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0, 39, 39, 39,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0, 39, 39,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0],
+       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+         0,  0,  0,  0,  0,  0,  0,  0,  0]], dtype=int32)
+
+

I'd like to find the max height within each labeled region. I have done this successfully with a for loop, but it's slow.

+
max_heights = {}
+for label in list(np.unique(labeled_trees))[1:]:
+    tree_height = np.amax(heights[labeled_trees == label])
+    max_heights[str(label)] = tree_height
+
+# max_heights = {'33': 42.18, '37': 41.8, '39': 35.95}
+
+

Is there a faster/vectorized/more efficient way of finding the max values within labeled regions of a numpy array? The ideal output would be a boolean array where the location of each max is True.

+

[EDIT]

+

The maximum_position function from scipy.ndimage is promising, but it looks like the it only returns the first location where the pixel equals the local max. I need every location within a labeled region that equals its max.

","

Here is a much simpler use of np.maximum.reduceat:

+
idx = labeled_trees.argsort(None)
+sorted_labeled_trees = labeled_trees.ravel()[idx]
+sorted_heights = heights.ravel()[idx]
+bins = np.flatnonzero(np.diff(sorted_labeled_trees) != 0) + 1
+max_heights = np.maximum.reduceat(sorted_heights, bins)
+max_trees = sorted_labeled_trees[bins]
+
+

If you insist on a dictionary, you can make one with zip:

+
result = dict(zip(max_trees, max_heights))
+
+

If you want a mask of the positions where the maxima occur and the number of trees is relatively small, you can compute the mask more-or-less directly using broadcasting:

+
peak_mask = ((max_trees == labeled_trees[..., None]) & (max_height == heights[..., None])).any(-1)
+
+

If the number of trees is not small, you will be better off using a loop over the labels:

+
peak_mask = np.zeros(labeled_trees.shape, bool)
+for t, h in zip(max_trees, max_height):
+    peak_mask |= (labeled_trees == t) & (heights == h)
+
",python +"Why the sequence of data in a heap is not like what I thought

I'm learning the Heap data structure and found this link

+

I'm expecting the output of heapq.heapify([5, 7, 9, 1, 3]) to be

+
[1, 3, 9, 5, 7]
+
+

However, I saw it returns this:

+
[1, 3, 9, 7, 5]
+
+

As some suggested that the order on the same level does not matter, then I guess I just feel confused that how does the [5,7] in the original sequence swapped position since the order in the same level does not matter.

+

Could someone explain why it is like this?

","

Note that the Heap data structure only guarantees the top to be the minimum [or maximum]. It isn't anything like a Binary Search Tree, which I gather is what you're expecting with the order.

+

The invariant for a Binary Search Tree is that that for every node x, all the keys in the left subtree should be smaller than x and all the keys in the right subtree should be greater than x.

+

However, in a Heap, the invariant is just that that every node x should be greater [or smaller] than its children. Note how it doesn't specify anything about its left or right subtree.

+

The sequence [1, 3, 9, 7, 5] is a valid heap. Note how every parent is smaller than its children.

+
       1
+    3    9
+  7   5
+
",python +"Flask Rest API SQLAlchemy foreign key error

I got SQLALchemy error, when I tried "flask db migrate"

+
NoReferencedTableError: Foreign key associated with column 'user.menu_id' could not find table 'menu' with which to generate a foreign key to target column 'id
+
+

Menu table

+
class Menu(db.Model):
+   __tablename__ = 'menus'
+   id = db.Column(db.Integer(), primary_key=True)
+   name = db.Column(db.String(64), index=True, unique=True)
+   price = db.Column(db.String(64), index=True, unique=True)
+   description = db.Column(db.String(64), index=True, unique=True)
+   picture = db.Column(db.String(64), index=True, unique=True)
+   create_date = db.Column(db.DateTime, default=datetime.utcnow)
+   users = db.relationship('User', backref="menu", lazy=True)
+
+

User table

+
class User(Model):
+""" User model for storing user related data """
+
+   id = Column(db.Integer, primary_key=True)
+   email = Column(db.String(64), unique=True, index=True)
+   username = Column(db.String(15), unique=True, index=True)
+   name = Column(db.String(64))
+   password_hash = Column(db.String(128))
+   admin = Column(db.Boolean, default=False)
+
+   joined_date = Column(db.DateTime, default=datetime.utcnow)    
+   userdataset = db.relationship("Dataset", backref="user", lazy="dynamic")
+   menu_id = Column(db.Integer(), db.ForeignKey('menu.id'), nullable=False)
+   def __init__(self, **kwargs):
+      super(User, self).__init__(**kwargs)
+
+

How can ı solve this problem? Where am i doing wrong?

","

You have renamed your 'Menu' table to 'menus' with this __tablename__ property in your 'Menu' model:

+
__tablename__ = 'menus'
+
+

You then try to reference to the 'Menu' table, when in fact, its name has been changed to 'menus'. The simplest way to solve this would be to change your User.menu_id column to this:

+
menu_id = Column(db.Integer(), db.ForeignKey('menus.id'), nullable=False)
+
+

Another way of fixing this issue would be modifying the __tablename__ property to 'menu'. (You could also just delete it.)

",python +"Altair Grouped Bar Chart With Multiple Conditions

I have this DataFrame called table:

+
    TERM                        Bitcoin       S&P500    Real Estate Gold
+0   High-Inflation/ Short term  3097.94       -3700.78  761.23      6512.71
+1   High-Inflation/ Mid term    —             -3080.01  -8434.66    3242.40
+2   High-Inflation/ Long term   —             -2089.25  -9117.96    8174.43
+3   Low-Inflation/ Short term   780200.00     -273.71   1824.72     2214.51
+4   Low-Inflation/ Mid term     21013600.00   5331.40   35810.58    -2879.37
+5   Low-Inflation/ Long term    978017143.00. 15045.41  35895.81    861.90
+
+

And I want to make a grouped (or stacked) bar chart that distinguishes return on investments for each of these assets based on the TERM column. I have tried this:

+
alt.Chart(table).transform_fold(
+    ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
+).mark_bar().encode(
+        x="key:N",
+        y="value:Q",
+        color="key:N",
+        column="TERM",
+    )
+
+

But that doesn't work.

","

It seems to work fine, the only problem is that the values are at such vastly different scales that only the largest shows up on a linear scale. You can address this by switching to a symlog scale. For example:

+
import pandas as pd
+import io
+import altair as alt
+
+table = pd.read_csv(io.StringIO("""\
+row    TERM                        Bitcoin       S&P500   "Real Estate" Gold
+0   "High-Inflation/ Short term"  3097.94       -3700.78  761.23      6512.71
+1   "High-Inflation/ Mid term"    —             -3080.01  -8434.66    3242.40
+2   "High-Inflation/ Long term"   —             -2089.25  -9117.96    8174.43
+3   "Low-Inflation/ Short term"   780200.00     -273.71   1824.72     2214.51
+4   "Low-Inflation/ Mid term"     21013600.00   5331.40   35810.58    -2879.37
+5   "Low-Inflation/ Long term"    978017143.00. 15045.41  35895.81    861.90
+"""), delim_whitespace=True)
+
+alt.Chart(table).transform_fold(
+    ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
+).mark_bar().encode(
+    x="key:N",
+    y=alt.Y("value:Q", scale=alt.Scale(type='symlog')),
+    color="key:N",
+    column="TERM",
+)
+
+

",python +"Need help identifying right XPath

I'm trying to scrape all of the table from this website : https://qmjhldraft.rinknet.com/results.htm?year=2018

+

When the XPath is a simple td (like the names for example), I can scrape the table with the simple xpath being something like this :

+
players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')
+
+

And I can scrape the players name using this code :

+
from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+
+PATH = 'C:\Program Files (x86)\chromedriver.exe'
+driver = webdriver.Chrome(PATH)
+driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')
+
+try:
+    elements = WebDriverWait(driver, 10).until(
+        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
+    )
+finally:
+    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')
+    
+for player in players[:5]:
+    pl = player.text
+    print(pl)
+
+

But when I get to the "Height" section, I can't find the write XPath. I guess this has to do with the td having a class, "ht-itemVisibility1", changing the way to scrape it, I've tried a few different ways to scrape it, like :

+
('//tr/td[@class="ht-itemVisibility1"][1]')
+('//tr/td[@class="ht-itemVisibility1"][5]')
+('//tr[@rnid]/td[5]')
+
+

to no avail. Can someone enlighten me on the way to capature this XPath with td class? Thanks a lot.

","

Try this

+
from selenium import webdriver
+from webdriver_manager.chrome import ChromeDriverManager
+
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+
+driver = webdriver.Chrome(ChromeDriverManager().install())
+driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')
+
+try:
+    elements = WebDriverWait(driver, 10).until(
+        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
+    )
+finally:
+    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')
+    
+for player in players[:5]:
+    pl = player.text
+    print(pl)
+
+players_height = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][1]')
+
+for player in players_height[:5]:
+    pl = player.text
+    print(pl)
+
+players_last_team = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][5]')
+
+for player in players_last_team[:5]:
+    pl = player.text
+    print(pl)
+
+
+

don't know why it wasn't working for you but it's working fine with me.

+

Results: +

",python +"Output missing dates by group of columns

I have time series of y per store and product stored in the following dataframe:

+
            ds store  product y
+0   2016-01-01    a    salt   2
+1   2016-01-02    a    salt   5
+2   2016-01-04    a    salt   3
+3   2016-01-05    a    salt   3
+4   2016-01-06    a    salt   4
+5   2016-01-07    a    salt   3
+6   2016-01-01    b    pepper 2
+7   2016-01-02    b    pepper 2
+8   2016-01-03    b    pepper 1
+9   2016-01-04    b    pepper 2
+10  2016-01-06    b    pepper 4
+11  2016-01-07    b    pepper 2
+
+

I would like to output all the missing dates per store, product and return the following result:

+
    ds store  product
+0   2016-01-03    a    salt
+1   2016-01-05    b    pepper
+
","

Use groupby_resample:

+
# Assuming ds is datetime64 else use:
+# df['ds'] = pd.to_datetime(df['ds'])
+out = df.groupby(['store', 'product']).resample('D', on='ds')['y'] \
+        .first().loc[lambda x: x.isna()].index.to_frame(index=False)
+print(out)
+
+# Output
+  store product         ds
+0     a    salt 2016-01-03
+1     b  pepper 2016-01-05
+
+

Details:

+
>>> df.groupby(['store', 'product']).resample('D', on='ds')['y'].first()
+store  product  ds        
+a      salt     2016-01-01    2.0
+                2016-01-02    5.0
+                2016-01-03    NaN  # <- missing value == missing date
+                2016-01-04    3.0
+                2016-01-05    3.0
+                2016-01-06    4.0
+                2016-01-07    3.0
+b      pepper   2016-01-01    2.0
+                2016-01-02    2.0
+                2016-01-03    1.0
+                2016-01-04    2.0
+                2016-01-05    NaN  # <- missing value == missing date
+                2016-01-06    4.0
+                2016-01-07    2.0
+Name: y, dtype: float64
+
+

Update: If you have a date in the ds column without a value in the y column, just use fillna({'y': 0}) before groupby_resample

",python +"DRF: Can't create object null. Error: value in column ""network_from_id"" violates not-null constraint

I want to create Transaction object. But have error:

+
django/db/backends/utils.py", line 84, in _execute
+    return self.cursor.execute(sql, params)
+django.db.utils.IntegrityError: null value in column "network_from_id" violates not-null constraint
+DETAIL:  Failing row contains (6, 12, null, null).
+
+

What is wrong in my code? And what is the proper way to create object with ModelViewSet?

+

My code: +models.py

+
class Networks(models.Model):
+    Name = models.CharField(max_length=50)
+    ...
+
+class Transaction(models.Model):
+    network_from = models.ForeignKey(Networks, on_delete=models.DO_NOTHING)
+    network_to = models.ForeignKey(Networks, on_delete=models.DO_NOTHING)
+    ...
+
+

view.py

+
class TransactionView(viewsets.ModelViewSet):
+    serializer_class = TransactionSerializer
+    queryset = Transaction.objects.all()
+
+    def get_transaction_create_serializer(self, *args, **kwargs):
+        serializer_class = TransactionSerializer
+        kwargs["context"] = self.get_serializer_context()
+        return serializer_class(*args, **kwargs)
+
+
+    def create(self, request, *args, **kwargs):
+        serializer = self.get_transaction_create_serializer(data=request.data)
+        serializer.is_valid(raise_exception=True)
+        self.perform_create(serializer)
+        headers = self.get_success_headers(serializer.data)
+        response = {"result": serializer.data}
+        return Response(
+            response, status=status.HTTP_201_CREATED, headers=headers
+        )
+
+

serializers.py

+
class TransactionSerializer(serializers.ModelSerializer):
+    network_from = serializers.SerializerMethodField()
+    network_to = serializers.SerializerMethodField()
+
+    class Meta:
+        model = Fee
+        fields = '__all__'
+    
+    def create(self, validated_data):
+        instance = super().create(validated_data=validated_data)
+        return instance
+    
+
+

def get_network_from(self, obj): +network = obj.network_from +return NetworksSerializer(network).data

+
    def get_network_to(self, obj):
+        network = obj.network_to
+        return NetworksSerializer(network).data
+
","

Add null=True for field, if you accept None values in specific relation.

+
network_from = models.ForeignKey(Networks, on_delete=models.DO_NOTHING, null=True)
+network_to = models.ForeignKey(Networks, on_delete=models.DO_NOTHING, null=True)
+
",python +"How to access all the child table entries based on parent table entry in Flask-SQLAlchemy

I am developing a flask-based website, I have two tables in the database, Customer(PK=sno, ...) and Item(PK=iid, ..., FK=customer.sno). +I want to display all the Items corresponding to any customer at a time when I click Bill button corresponding to the customer.

+

File app.py contains code

+
@app.route("/show_bill/<int:sno>")
+def show_bill(sno):
+    customer = Customer.query.filter_by(sno=sno).first()
+    show_bill = Item.query.filter_by(cid=sno)
+    return render_template('show_bill.html', customer=customer, show_bill=show_bill)
+
+

And, show_bill.html contains

+
<div class="container my-3">
+    <h2>Bill for customer {{ customer.cname }}</h2>
+        {% if show_bill|length == 0 %}
+            <div class="alert alert-dark" role="alert">
+                No Item found. Add first Item now to appear for this customesr!
+            </div>
+        {% else %} 
+            <table class="table">
+                <thead>
+                    <tr>
+                    <th scope="col">SNo</th>
+                    <th scope="col">Customer ID</th>
+                    <th scope="col">Name of Item</th>
+                    <th scope="col">No. of Items</th>
+                    <th scope="col">Rate</th>
+                    <th scope="col">Discount(%)</th>
+                    <th scope="col">Time</th>
+                    <th scope="col">Actions(Edit)</th>
+                    </tr>
+                </thead>
+                        
+                <tbody>
+                {% for item in show_bill %}
+                <tr>
+                    <th scope="row">{{loop.index}}</th>
+                    <td>{{item.cid}}</td>
+                    <td>{{item.iname}}</td>
+                    <td>{{item.icount}}</td>
+                    <td>{{item.irate}}</td>
+                    <td>{{item.idiscount}}</td>
+                    <td>{{item.date_created}}</td>
+                    <td>
+                        <a href="/update_item/{{item.iid}}" type="button" class="btn btn-outline-dark btn-sm mx-1">Update</button>
+                        <a href="/delete_item/{{item.iid}}" type="button" class="btn btn-outline-dark btn-sm mx-1">Delete</button>
+                    </td>
+                </tr>
+                {% endfor %}
+                </tbody>
+            </table>
+        {% endif %}
+</div>
+
+

But, on clicking Bill button, I get an error: +TypeError: object of type 'BaseQuery' has no len() +Also if I remove show_bill=show_bill, It renders to show_bill.html page but do not show data as we are not fetching any (Probably the problem is here).
+Can someone help to resolve this? Or any alternative way to get the same thing.

+

Thanks in Advance.

","

You need to add the .all() query to return a list of all the desired items in your table, like this:

+
show_bill = Item.query.filter_by(cid=sno).all()
+
+

Without this part, SQL returns your query as an object instead of an iterable list.

",python +"I want to make button commands in one class in python tkinter

I am getting the following error:
+log_print() missing 1 required positional argument: 'self' +I would really appreciate it if you could tell me how to fix it. +''' +import tkinter as tk

+
class SimpleApp(tk.Frame):
+    def __init__(self, parent):
+        tk.Frame.__init__(self, parent)
+        self.parent = parent
+        self.btn1 = tk.Button(self.parent, text="start", width=10, height=5, command = Button1.log_print)
+        self.btn2 = tk.Button(self.parent, text="stop", width=10, height=5)                  
+        self.textbox = tk.Text(self.parent, height = 10)
+        self.btn1.grid(row = 0, column = 0,sticky = "news", padx= 5)
+        self.btn2.grid(row = 0, column = 1, sticky = "news", padx= 5)
+        self.textbox.grid(row = 1, column = 0, columnspan = 2, sticky = "news", padx= 5)
+    
+
+class Button1(SimpleApp):
+    def __init__(self, parent, textbox):
+        SimpleApp.__init__(self, parent, textbox)
+    
+    def log_print(self):
+        self.textbox.insert("end", "1")
+        self.textbox.update()
+        self.textbox.see("end")
+
+
+        
+if __name__ == "__main__":
+    root = tk.Tk()
+    SimpleApp(root).grid()
+    root.mainloop()
+
+

'''

","

You mean something like this ?

+
import tkinter as tk
+
+
+class SimpleApp(tk.Frame):
+    def __init__(self, parent):
+        tk.Frame.__init__(self, parent)
+        self.parent = parent
+        self.textbox = tk.Text(self.parent, height=10)
+        self.btn1 = tk.Button(self.parent, text="start", width=10, height=5, command=Button1(self).log_print)
+        self.btn2 = tk.Button(self.parent, text="stop", width=10, height=5)
+        self.btn1.grid(row=0, column=0, sticky="news", padx=5)
+        self.btn2.grid(row=0, column=1, sticky="news", padx=5)
+        self.textbox.grid(row=1, column=0, columnspan=2, sticky="news", padx=5)
+
+
+class Button1:
+    def __init__(self, simple_app_object):
+        self.simple_app = simple_app_object
+
+    def log_print(self):
+        self.simple_app.textbox.insert("end", "1")
+        self.simple_app.textbox.update()
+        self.simple_app.textbox.see("end")
+
+
+if __name__ == "__main__":
+    root = tk.Tk()
+    SimpleApp(root).grid()
+    root.mainloop()
+
",python +"get specific lags from plot_acf that are over the confidence interval

How do I get from this plot

+
import pandas as pd
+import matplotlib.pyplot as plt
+import statsmodels.api as sm
+
+dta = sm.datasets.sunspots.load_pandas().data
+dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
+del dta["YEAR"]
+sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40)
+plt.show()
+
+

the specific lags that are over/under the confidence interval?

","

You can use acf rather than the plot interface to get the numerical values. The key step is to center the confidence interval by subtracting the ACF from the confidence interval so that it is centered at 0. The CI that is returned from acf is centered around the estimated ACF value.

+
import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+import statsmodels.api as sm
+from statsmodels.tsa.stattools import acf
+
+dta = sm.datasets.sunspots.load_pandas().data
+dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
+nlags = 40
+alpha = 0.05
+fft=True
+adjusted = False
+missing = "none"
+bartlett_confint = True
+x = dta.SUNACTIVITY
+a, ci = acf(x, nlags=40, alpha=0.05)
+# Key step
+centered_ci = ci - a[:,None]
+outside = np.abs(a) >= centered_ci[:,1]
+inside = ~outside
+
+print(outside)
+
+

which shows

+
[ True  True  True False  True  True  True False False  True  True  True
+  True False False  True  True  True False False  True  True  True False
+ False False  True  True False False False False False False False False
+ False False False False False]
+
",python +"Empty plots when trying to adapt parallel coordinates example to my data

I'm trying to redo Parallel Coordinates in Altair but unfortunately i can't edit it so that it will work for me. When I run the code below, the plots show up empty without any lines. Could you please provide a pre-defined structure (perhaps with some explanation for beginners like me) so that we can change this code to pass it to our own goals . tnx.

+
from sklearn import datasets
+data_wine = datasets.load_wine (as_frame = True).frame
+new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
+new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
+base = alt.Chart(
+    new_data
+).transform_window(
+    index="count()"
+).transform_fold(
+    #[alcohol   malic_acid  ash alcalinity_of_ash   magnesium   total_phenols   flavanoids  nonflavanoid_phenols    proanthocyanins color_intensity hue od280/od315_of_diluted_wines    "proline    "]
+    ["alcohol","malic_acid","ash","alcalinity_of_ash","total_phenols","flavanoids","nonflavanoid_phenols","proanthocyanins","color_intensity","hue","od280/od315_of_diluted_wines"]
+).transform_joinaggregate(
+    min="min(value)",
+    max="max(value)",
+    groupby=["variable"]
+).transform_calculate(
+    norm_val="(datum.variable - datum.min) / (datum.max - datum.min)",
+    mid="(datum.min + datum.max) / 2"
+).properties(width=600, height=300)
+
+lines = base.mark_line(opacity=0.3).encode(
+    alt.Color ('target:N'),
+    alt.Detail ('index:N'),
+    x='variable:N',
+    y=alt.Y('norm_val:Q', axis=None),
+    #tooltip=["petalLength:N", "petalWidth:N", "sepalLength:N", "sepalWidth:N"]
+)
+
+rules = base.mark_rule(
+    color="#ccc", tooltip=None
+).encode(
+    x="variable:N",
+    detail="count():Q",
+)
+
+def ytick(yvalue, field):
+    scale = base.encode(x='variable:N', y=alt.value(yvalue), text=f"min({field}):Q")
+    return alt.layer(
+        scale.mark_text(baseline="middle", align="right", dx=-5, tooltip=None),
+        scale.mark_tick(size=8, color="#ccc", orient="horizontal", tooltip=None)
+    )
+
+alt.layer(
+    lines, rules, ytick(0, "max"), ytick(150, "mid"), ytick(300, "min")
+).configure_axisX(
+    domain=False, labelAngle=0, tickColor="#ccc", title=None
+).configure_view(
+    stroke=None
+)
+
","

The reason your plots are not showing up is because your input data does not have the same structure as in the example you are following. You have melted your wide data frame in pandas to long format. This is the same functionality performed by the transform_fold function in Altair, so in your example you are trying to do this twice. Below I have removed the manual pandas melt and changed the variable names back to the ones autmatically assigned by transform_fold (key and value):

+
from sklearn import datasets
+import altair as alt
+
+data_wine = datasets.load_wine (as_frame = True).frame
+new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
+
+base = alt.Chart(
+    new_data
+).transform_window(
+    index="count()"
+).transform_fold(
+    ["alcohol","malic_acid","ash","alcalinity_of_ash","total_phenols","flavanoids","nonflavanoid_phenols","proanthocyanins","color_intensity","hue","od280/od315_of_diluted_wines"]
+).transform_joinaggregate(
+    min="min(value)",
+    max="max(value)",
+    groupby=["key"]
+).transform_calculate(
+    norm_val="(datum.value - datum.min) / (datum.max - datum.min)",
+    mid="(datum.min + datum.max) / 2"
+).properties(width=1200, height=300)
+
+lines = base.mark_line(opacity=0.3).encode(
+    x='key:N',
+    y=alt.Y('norm_val:Q', axis=None),
+    color=alt.Color ('target:N'),
+    detail=alt.Detail ('index:N'),
+)
+
+rules = base.mark_rule(
+    color="#ccc", tooltip=None
+).encode(
+    x="key:N",
+    detail="count():Q",
+)
+
+def ytick(yvalue, field):
+    scale = base.encode(x='key:N', y=alt.value(yvalue), text=f"min({field}):Q")
+    return alt.layer(
+        scale.mark_text(baseline="middle", align="right", dx=-5, tooltip=None),
+        scale.mark_tick(size=8, color="#ccc", orient="horizontal", tooltip=None)
+    )
+
+alt.layer(
+    lines, rules, ytick(0, "max"), ytick(150, "mid"), ytick(300, "min")
+).configure_axisX(
+    domain=False, labelAngle=0, tickColor="#ccc", title=None
+).configure_view(
+    stroke=None
+)
+
+

+

You could create a simpler parallel coordinates plot like this if you are OK with not having a separate y-axis for each column in the data frame:

+
from sklearn import datasets
+import altair as alt
+
+data = datasets.load_wine (as_frame=True).frame
+
+num_cols = ["alcohol","malic_acid","ash","alcalinity_of_ash","total_phenols","flavanoids","nonflavanoid_phenols","proanthocyanins","color_intensity","hue","od280/od315_of_diluted_wines"]
+
+# You could skip this rescaling but it would compress the y-axis range for columns with smaller absolute values
+data[num_cols] = data[num_cols].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
+
+alt.Chart(data).transform_window(
+        index='count()'
+    ).transform_fold(
+        num_cols
+    ).mark_line().encode(
+        alt.X('key:O', title=None, scale=alt.Scale(nice=False, padding=0.05)),
+        alt.Y('value:Q', title=None),
+        alt.Color('target:N', title=None),
+        detail='index:N'
+).properties(
+    width=1200
+)
+
+

+

If you are using this for exploratory data analysis and don't need to customize the plot a lot, then you can also try out my experimental package [altair_ally][3] for quickly creating some common exploratory plots:

+
from sklearn import datasets
+import altair_ally as aly
+
+
+data_wine = datasets.load_wine (as_frame = True).frame
+data_wine['target'] = data_wine['target'].astype(str)
+aly.parcoord(data_wine, color='target')
+
+

",python +"Pandas - concating multi-indexed dataframes keeps duplicate indizes

Hello I'm trying to read in multiple dfs of the same structre and concating them into a single one however the combined df somehow keeps duplicates in the indizes....

+
df1 = processUSAdata(2223)
+df2 = processUSAdata(2224)
+
+print(df1)
+print(df2)
+
+test = pd.concat([df1,df2])
+test.set_index(['state','year'],inplace=True)
+print(test)
+
+

outputs

+
         state  population  violent_crime  ...    theft     gta  year
+0      ALABAMA     4903185         510.81  ...  1886.06  256.51  2223
+1       ALASKA      731545         867.07  ...  2066.04  357.74  2223
+2      ARIZONA     7278717         455.31  ...  1796.86  249.37  2223
+3     ARKANSAS     3017804         584.63  ...  2012.56  245.87  2223
+4   CALIFORNIA    39512223         441.21  ...  1586.35  358.77  2223
+5     COLORADO     5758736         380.95  ...  1858.26  383.99  2223
+6  CONNECTICUT     3565287         183.60  ...  1078.65  167.28  2223
+
+[7 rows x 12 columns]
+         state  population  violent_crime  ...    theft     gta  year
+0      ALABAMA     4903185         510.81  ...  1886.06  256.51  2224
+1       ALASKA      731545         867.07  ...  2066.04  357.74  2224
+2      ARIZONA     7278717         455.31  ...  1796.86  249.37  2224
+3     ARKANSAS     3017804         584.63  ...  2012.56  245.87  2224
+4   CALIFORNIA    39512223         441.21  ...  1586.35  358.77  2224
+5     COLORADO     5758736         380.95  ...  1858.26  383.99  2224
+6  CONNECTICUT     3565287         183.60  ...  1078.65  167.28  2224
+
+[7 rows x 12 columns]
+                  population  violent_crime  murder  ...  burglary    theft     gta
+state       year                                     ...                           
+ALABAMA     2223     4903185         510.81    7.30  ...    531.88  1886.06  256.51
+ALASKA      2223      731545         867.07    9.43  ...    487.05  2066.04  357.74
+ARIZONA     2223     7278717         455.31    5.01  ...    394.29  1796.86  249.37
+ARKANSAS    2223     3017804         584.63    8.02  ...    599.61  2012.56  245.87
+CALIFORNIA  2223    39512223         441.21    4.28  ...    386.10  1586.35  358.77
+COLORADO    2223     5758736         380.95    3.79  ...    348.41  1858.26  383.99
+CONNECTICUT 2223     3565287         183.60    2.92  ...    180.66  1078.65  167.28
+ALABAMA     2224     4903185         510.81    7.30  ...    531.88  1886.06  256.51
+ALASKA      2224      731545         867.07    9.43  ...    487.05  2066.04  357.74
+ARIZONA     2224     7278717         455.31    5.01  ...    394.29  1796.86  249.37
+ARKANSAS    2224     3017804         584.63    8.02  ...    599.61  2012.56  245.87
+CALIFORNIA  2224    39512223         441.21    4.28  ...    386.10  1586.35  358.77
+COLORADO    2224     5758736         380.95    3.79  ...    348.41  1858.26  383.99
+CONNECTICUT 2224     3565287         183.60    2.92  ...    180.66  1078.65  167.28
+
+

Hoping someone can help me out here. +Thanks in advance! :)

","

It's probably because your index is not sorted:

+
test = pd.concat([df1, df2]).set_index(['state', 'year']).sort_index()
+print(test)
+
+# Output
+                  population  violent_crime    theft     gta
+state       year                                            
+ALABAMA     2223     4903185         510.81  1886.06  256.51
+            2224     4903185         510.81  1886.06  256.51
+ALASKA      2223      731545         867.07  2066.04  357.74
+            2224      731545         867.07  2066.04  357.74
+ARIZONA     2223     7278717         455.31  1796.86  249.37
+            2224     7278717         455.31  1796.86  249.37
+ARKANSAS    2223     3017804         584.63  2012.56  245.87
+            2224     3017804         584.63  2012.56  245.87
+CALIFORNIA  2223    39512223         441.21  1586.35  358.77
+            2224    39512223         441.21  1586.35  358.77
+COLORADO    2223     5758736         380.95  1858.26  383.99
+            2224     5758736         380.95  1858.26  383.99
+CONNECTICUT 2223     3565287         183.60  1078.65  167.28
+            2224     3565287         183.60  1078.65  167.28
+
",python +"How to rename a subset of columns based on offset/index and variable range?

I am working with student test data. The data provided is in a new format and I need to align it with the older format for an existing BI application. Where a range of columns used to contain questions numbers, the column name now contains the correct answer (this includes duplicate column names as imported form the source XLSX - see the image below). Different year levels have a different number of questions (so the "Total" column is not fixed. I need to rename the answer columns back to the sequential question numbers starting at 1. What is the best way to achieve this?

+

NB the sample df is not quite right as there are duplicate column names as the column name represents the correct answer. I cannot provide a sample df without importing it from a CSV/XLSX.

+

Updated with some sample df data:

+

+
+
data = {
+        'StudentID': [10, 11, 12, 13],
+        'Year' : [2021,2021,2021,2021],
+        'TestName': ['Math83', 'Math83','Math83','Math83'],
+        'A' : ['C','A','C','B'],
+        'B' : ['D','C','C','C'],
+        'C' : ['D','D','C','D'],
+        'D' : ['B','C','C','C'],
+        'Total': [5,4,3,5,],
+        'Score': [3,3,4,2,],
+        'Error': [1,2,1,1]
+        }
+df = pd.DataFrame(data)
+
+
+

+

","

Here is a solution using set_axis()

+
cols = df.columns
+tn = cols.get_loc('TestName')+1
+total = cols.get_loc('Total')
+
+(df.set_axis(cols[:tn].tolist() + 
+             list(range(1,len(df.columns[tn:total+1]))) + 
+             cols[total:].tolist(),axis=1))
+
+

Output:

+
   StudentID  Year TestName  1  2  3  4  Total  Score  Error
+0         10  2021   Math83  C  D  D  B      5      3      1
+1         11  2021   Math83  A  C  D  C      4      3      2
+2         12  2021   Math83  C  C  C  C      3      4      1
+3         13  2021   Math83  B  C  D  C      5      2      1
+
",python +"How do you add dataclasses as valid index values to a plotly chart?

I am trying to switch from the matplotlib pandas plotting backend to plotly. However, I am being held back by a common occurrence of this error:

+
TypeError: Object of type Quarter is not JSON serializable
+
+

Where Quarter is a dataclass in my codebase.

+

For a minimal example, consider:

+
@dataclass
+class Foo:
+    val:int
+    
+df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
+
+df.plot.scatter(x='x', y='y')
+
+

As expected, the above returns:

+
TypeError: Object of type Foo is not JSON serializable
+
+

Now, I don't expect plotly to be magical, but adding a __float__ magic method allows the Foo objects to be used with the matplotlib backend:

+
# This works
+@dataclass
+class Foo:
+    val:int
+    
+    def __float__(self):
+        return float(self.val)
+    
+df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
+
+df.plot.scatter(x='x', y='y')
+
+

How can I update my dataclass to allow for it to be used with the plotly backend?

","

You can get pandas to cast to float before invoking plotting backend.

+
from dataclasses import dataclass
+import pandas as pd
+
+@dataclass
+class Foo:
+    val:int
+    
+    def __float__(self):
+        return float(self.val)
+    
+df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
+df["x"].astype(float)
+
+pd.options.plotting.backend = "plotly"
+
+df.assign(x=lambda d: d["x"].astype(float)).plot.scatter(x='x', y='y')
+
+

monkey patching

+ +
from dataclasses import dataclass
+import pandas as pd
+import wrapt, json
+import plotly
+
+@wrapt.patch_function_wrapper(plotly, 'plot')
+def new_plot(wrapped, instance, args, kwargs):
+    try:
+        json.dumps(args[0][kwargs["x"]])
+    except TypeError:
+        args[0][kwargs["x"]] = args[0][kwargs["x"]].astype(float)
+    return wrapped(*args, **kwargs)
+    
+
+
+@dataclass
+class Foo:
+    val:int
+    
+    def __float__(self):
+        return float(self.val)
+    
+df = pd.DataFrame({'x': [Foo(i) for i in range(10)], 'y':list(range(10))})
+df["x"].astype(float)
+
+pd.options.plotting.backend = "plotly"
+
+df.plot.scatter(x='x', y='y')
+
+
+
",python +"Same code does not work in venv despite installing dependencies from same requirements.txt

I am developing a web application and trying to migrate from Spyder to VS Code. +It was working with the default interpreter, so I created a new venv but when I start the server it does not work with the same code that was working without the venv. +Error description:

+
File "C:\Users\User\Desktop\Flask\app.py", line 77, in index
+measurement_mx = rs.all()
+AttributeError: 'ResultProxy' object has no attribute 'all' 
+
+

I installed exactly the same dependencies with pip install -r requirements.txt.

+

Can you help me what the solution could be, I could not find this problem unfortunately.

+

Relevant code snippet:

+
@app.route('/', methods=['POST', 'GET'])
+def index():  
+    with engine.connect() as con:
+        rs = con.execute(SQL_string)
+        measurement_mx = rs.all() #this is the error line
+        measurement_list = []
+        for row in measurement_mx:
+            measurement_list.append(row._data)
+        measurement_list = transpose(measurement_list)
+    return render_template('index.html', measurement_list=measurement_list )
+
+
+

Thank you in advance!

","

Welcome to StackOverflow!

+

The issue could be that your requirements.txt file may specify what packages to install, but not their exact version, so could you please:

+
    +
  • paste the content of your requirements file?
  • +
  • check the packages versions between your two virtual environments?
  • +
+

Some thoughts:

+ +

Now, concerning your exact issue: ResultProxy is not an object from flask but from SQLAlchemy, which SQLAchemy v1.4 replaced:

+
+

class sqlalchemy.engine.Result(cursor_metadata)

+

Represent a set of database results.

+
+

New in version 1.4: The Result object provides a completely updated usage model and calling facade for SQLAlchemy Core and SQLAlchemy ORM. In Core, it forms the basis of the CursorResult object which replaces the previous ResultProxy interface. When using the ORM, a higher level object called ChunkedIteratorResult is normally used.

+
+
+

(emphasis mine)

+

Which means you can:

+
    +
  • either fix SQLAlchemy version in your requirements.txt file,
  • +
  • or update your code to cope with current SQLAlchemy syntax.
  • +
",python +"Pandas Dataframe: Change each value's ones-digit

I am writing unit tests for 2 data frames to test for equality by converting them to dictionaries and using unittest's assertDictEqual(). The context is that I'm converting Excel functions to Python but due to their different rounding system, some values are off by merely +/- 1

+

I've attempted to use the DF.round(-1) to round to the nearest 10th but due to the +/- 1, some numbers may round the opposite way so for example 15 would round up but 14 would round down and the test would fail. All values in the 12x20 data frame are integers

+

What I'm looking for (feel free to suggest any alternate solution):

+
    +
  1. A CLEAN way to test for approximate equality of data frames or nested dictionaries
  2. +
  3. or a way to make the ones-digit of each element '0' to avoid the rounding issue
  4. +
+

Thank you, and please let me know if any additional context is required. Due to confidentiality issues and my NDA (non-disclosure agreement), I cannot share the code but I can formulate an example if necessary

","

You could take the element-wise absolute difference between the two DataFrames and check that all values are below a certain tolerance (in your case 1). For example, we can create two DataFrames with values in the interval [0.0, 1.0).

+
import numpy as np
+import pandas as pd
+
+np.random.seed(42)
+
+## df2 are 10x10 arrays with values in the interval [0.0, 1.0)
+df1 = pd.DataFrame(np.random.random_sample((10,10)))
+df2 = pd.DataFrame(np.random.random_sample((10,10)))
+
+

Then the following should return True:

+
(abs(df2-df1) < 1).all(axis=None)
+
+

And you can write an assert statement like:

+
assert((abs(df2-df1) < 1).all(axis=None) == True)
+
",python +"How to deal with ImmutableMultiDict

I'm trying to test my flask API with a POST request, but I have problems to deal with the ImmutableMultiDict.

+

The API:

+
@app.route("/df/", methods = ['GET', 'POST'])
+def get_df():
+    if request.method == 'POST':
+        select = request.form
+
+

request:

+
curl -X POST http://127.0.0.1:5000/df/ -d '{"ticker": "ETH-PERP"}'
+
+

print(select):

+
ImmutableMultiDict([('{"ticker": "ETH-PERP"}', '')])
+
+

How do I access the value ("ETH-PERP") ?

+

I tried:

+
select = request.form.getlist("ticker")
+
+

output: []

+
select = request.form.to_dict(flat=True)
+print(select[0])
+
+

output: keyError: 0

+
select = request.form.to_dict().values()[0]
+
+

output: 'dict_values' object is not subscriptable

+

any suggestions?

","

The problem is that the request data is not a form, it's JSON.

+

You should probably use request.json to read it, which should give you a regular dictionary.

",python +"Is there a way to convert array of bytes to array of floats

I did a python script that gets data from shared mem and convert it from bytes to floats. +The main problem is that it very slow.

+

This is how I init the shared memory:

+
  def _shared_mem_init(self):
+
+        warnings.filterwarnings("ignore")
+        path = "/tmp"
+
+        # shared memory header
+        key = ipc.ftok(path, 0x3110)
+        self.shm = ipc.SharedMemory(key, 0, 0)
+        self.shm.attach(0, 0)
+        # shared memory X values
+        key_x = ipc.ftok(path, 0x3111)
+        self.shm_x = ipc.SharedMemory(key_x, 0, 0)
+        self.shm_x.attach(0, 0)
+        # shared memory Y values
+        key_y = ipc.ftok(path, 0x3112)
+        self.shm_y = ipc.SharedMemory(key_y, 0, 0)
+        self.shm_y.attach(0, 0)
+        # shared memory Z values
+        key_z = ipc.ftok(path, 0x3113)
+        self.shm_z = ipc.SharedMemory(key_z, 0, 0)
+        self.shm_z.attach(0, 0)
+        # shared memory R values
+        key_r = ipc.ftok(path, 0x3114)
+        self.shm_r = ipc.SharedMemory(key_r, 0, 0)
+        self.shm_r.attach(0, 0)
+        # shared memory G values
+        key_g = ipc.ftok(path, 0x3115)
+        self.shm_g = ipc.SharedMemory(key_g, 0, 0)
+        self.shm_g.attach(0, 0)
+        # shared memory B values
+        key_b = ipc.ftok(path, 0x3116)
+        self.shm_b = ipc.SharedMemory(key_b, 0, 0)
+        self.shm_b.attach(0, 0)
+
+        self.shm.write(byte_true, 0)
+        print("shared Memory init")
+
+

it gets the xyzrgb from the shared memory. +and after I get the data I try to convert it from bytes to floats:

+
 def next_point_cloud(self):
+
+        # read 4 bytes from header - Data Lines
+        buf = self.shm.read(4, 5)
+        data_lines = int.from_bytes(buf, "little")
+
+        # read all data
+        buff_x2 = self.shm_x.read(4 * data_lines, 0)
+        buff_y2 = self.shm_y.read(4 * data_lines, 0)
+        buff_z2 = self.shm_z.read(4 * data_lines, 0)
+        buff_r2 = self.shm_r.read(data_lines, 0)
+        buff_g2 = self.shm_g.read(data_lines, 0)
+        buff_b2 = self.shm_b.read(data_lines, 0)
+
+        # split all data
+        buff_x_breakdown = [buff_x2[i:i + 4] for i in range(0, 4 * data_lines, 4)]
+        buff_y_breakdown = [buff_y2[i:i + 4] for i in range(0, 4 * data_lines, 4)]
+        buff_z_breakdown = [buff_z2[i:i + 4] for i in range(0, 4 * data_lines, 4)]
+        buff_r_breakdown = [buff_r2[i] for i in range(0, data_lines, 1)]
+        buff_g_breakdown = [buff_g2[i] for i in range(0, data_lines, 1)]
+        buff_b_breakdown = [buff_b2[i] for i in range(0, data_lines, 1)]
+
+        xyz = np.zeros((data_lines, 3))
+        colors = np.zeros((data_lines, 3))
+
+        for i in range(data_lines):
+            xyz[i, 0] = struct.unpack('f', buff_x_breakdown[i])[0]
+            xyz[i, 1] = struct.unpack('f', buff_y_breakdown[i])[0]
+            xyz[i, 2] = struct.unpack('f', buff_z_breakdown[i])[0]
+
+            colors[i, 0] = float(buff_r_breakdown[i]) / 255.0
+            colors[i, 1] = float(buff_g_breakdown[i]) / 255.0
+            colors[i, 2] = float(buff_b_breakdown[i]) / 255.0
+
+        self.pcdA.points = o3d.utility.Vector3dVector(xyz)
+        self.pcdA.colors = o3d.utility.Vector3dVector(colors)
+
+
+

So my question is: Is there a way in python to write a code that runs better then the for loop that I wrote?

","

You can use np.frombuffer to construct a Numpy array from a bytes object:

+
>>> buffer = b''.join(struct.pack('f', x) for x in [1.0, 2.0, 3.0])
+>>> np.frombuffer(buffer, dtype=np.float32, count=3)
+array([1., 2., 3.], dtype=float32)
+
+

So in your case this should be:

+
xyz = np.stack(
+    [
+        np.frombuffer(self.shm_x.read(4*data_lines, 0), dtype=np.float32, count=data_lines),
+        np.frombuffer(self.shm_y.read(4*data_lines, 0), dtype=np.float32, count=data_lines),
+        np.frombuffer(self.shm_z.read(4*data_lines, 0), dtype=np.float32, count=data_lines),
+    ],
+    axis=1,
+)
+
+

and the same for colors:

+
colors = (1./255) * np.stack(
+    [
+        np.frombuffer(self.shm_r.read(data_lines, 0), dtype=np.byte, count=data_lines),
+        np.frombuffer(self.shm_g.read(data_lines, 0), dtype=np.byte, count=data_lines),
+        np.frombuffer(self.shm_b.read(data_lines, 0), dtype=np.byte, count=data_lines),
+    ],
+    axis=1,
+)
+
",python +"Python program to convert infix to prefix notation

I keep on getting an IndexError: list index out of range, return self.data[-1] # the last element in the list; I think I know what is causing this but I have no clue how to fix it

+

Here is the Stack Class I used:

+
class Stack: 
+    # LIFO Stack implementation using a Python list as underlying storage.
+    def __init__(self): 
+        self.data =[]   
+
+    def __len__(self):  
+        return len(self.data)
+
+    def is_empty(self): 
+        return len(self.data)==0
+
+    def push(self, e):  
+        self.data.append(e) 
+
+    def top(self):       
+        return self.data[-1] 
+
+    def pop(self):      
+        return self.data.pop()
+
+

And the corresponding code I made:

+
def operatorpriority(x):
+    if x == "+" or x == "-":
+        return 1
+    elif x == "*" or x == "/":
+        return 2
+    else:
+        return 3
+    return 0
+
+def polishnotation(A):
+    # Converts Infix to Prefix Notation
+    stack = Stack()
+    stack.push(')')
+    A = A + '('
+    output = ""
+    for i in range(len(A)-1, -1, -1):
+        print(i)
+        if A[i].isnumeric() == True:
+            output+=A[i]
+        elif A[i] == ")":
+            stack.push(A[i])
+        elif A[i] == "-" or A[i] == "+" or A[i] == "*" or A[i] == "/" or A[i] == "^":
+            if A[i] == "^":
+                while operatorpriority(A[i]) <= operatorpriority(stack.top()):
+                    output+=stack.pop()
+            else:
+                while operatorpriority(A[i]) < operatorpriority(stack.top()):
+                    output+=stack.pop()
+            stack.push(A[i])
+        elif A[i] == "(":
+            while stack.is_empty()== False:
+                if stack.top() != "(":
+                    output+=stack.pop()
+                stack.pop()
+    while stack.is_empty()== False:
+        output+=stack.pop()
+    print(output)
+
+        
+
+

InfixInput = input("Input infix notation: ")

+

polishnotation(InfixInput)

+

Sample Input:

+

(a+b)*(c-d)

+

Expected Output:

+

*+ab-cd

","
    +
  1. You have A = A + '('. That adds at the wrong end. Just do A = '('+A+')' and skip the extra push.
  2. +
  3. You are giving ')' the same priority as '^'. In operatorpriority, your else: should be elif x =='^':.
  4. +
  5. In your elif A[i] == "(" clause, you are popping until '('. That's the wrong type of parens. And you don't break out of that loop until the stack is empty. You need to break when you get to a ')'.
  6. +
  7. Your example shows (a+b)*(c+d), but your code only allows digits. I haven't changed that.
  8. +
+

This works:

+
class Stack: 
+    # LIFO Stack implementation using a Python list as underlying storage.
+    def __init__(self): 
+        self.data =[]   
+
+    def __len__(self):  
+        return len(self.data)
+
+    def is_empty(self): 
+        return len(self.data)==0
+
+    def push(self, e):  
+        self.data.append(e) 
+
+    def top(self):       
+        return self.data[-1] 
+
+    def pop(self):      
+        return self.data.pop()
+
+def operatorpriority(x):
+    if x in "+-":
+        return 1
+    elif x in "*/":
+        return 2
+    elif x in "^":
+        return 3
+    return 0
+
+def polishnotation(A):
+    # Converts Infix to Prefix Notation
+    stack = Stack()
+    A = '(' + A + ')'
+    output = ""
+    for c in A[::-1]:
+        print(c)
+        if c.isnumeric():
+            output+=c
+        elif c == ")":
+            stack.push(c)
+        elif c in "+-*/^":
+            if c == "^":
+                while operatorpriority(c) <= operatorpriority(stack.top()):
+                    output+=stack.pop()
+            else:
+                while operatorpriority(c) < operatorpriority(stack.top()):
+                    output+=stack.pop()
+            stack.push(c)
+        elif c == "(":
+            while not stack.is_empty():
+                c1 = stack.pop()
+                if c1 == ')':
+                    break
+                output+=c1
+    while not stack.is_empty():
+        output+=stack.pop()
+    return output
+
+print(polishnotation('(3+4)*(5+6)'))
+
",python +"selenium.common.exceptions.NoSuchElementException error sending text to input fields using Selenium and Python

I'm trying to write a simple program to fill out a form (including order ID and zip code) to be submitted but I keep getting the following error:

+
selenium.common.exceptions.NoSuchElementException: Message: "  (without any text following "Message
+
+

Code trials:

+
from selenium import webdriver
+browser = webdriver.Safari()
+browser.get('https://knowledge.tonal.com/s/order-status')
+
+orderElm = browser.find_element_by_id('input-3')
+orderElm.send_keys('1000XXX')
+
+zipcodeElm = browser.find_element_by_id('input-4')
+zipcodeElm.send_keys('90210')
+zipcodeElm.submit()
+
+

I've double-checked my element ID several times and though I'm very new to this, I'm fairly confident I have the correct element IDs. What am I doing incorrectly?

","

To send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

+
    +
  • Using XPATH:

    +
    driver.get("https://knowledge.tonal.com/s/order-status")
    +WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@data-aura-class='cOrderSearch']//following::input[1]"))).send_keys('1000XXX')
    +driver.find_element(By.XPATH, "//div[@data-aura-class='cOrderSearch']//following::input[2]").send_keys("90210")
    +
    +
  • +
  • Note: You have to add the following imports :

    +
    from selenium.webdriver.support.ui import WebDriverWait
    +from selenium.webdriver.common.by import By
    +from selenium.webdriver.support import expected_conditions as EC
    +
    +
  • +
  • Browser Snapshot:

    +
  • +
+

",python +"How to reformat and modify a date string according to DIN standard: 5008:2020-03?

How can I reformat and modify a date string?

+
+

My code:

+
details = response.xpath('//div[@class="article-info"]')
+for detail in details:
+    released = detail.xpath('.//ul/li[1]/span[1]/span/text()').get()
+    item['released'] = released
+    yield item
+
+

My output:

+
+

Released 2021, September 24

+
+
+

Desired output:

+
+
    +
  1. September, 2021
  2. +
+
+

and:

+
+

24.09.2021

+
+
","

It has nothing to do with scrapy, as this is a simple string parsing problem.

+

For example, you might want to try this, provided that released is a string value like Released 2021, September 24:

+
import datetime
+
+released = "Released 2021, September 24".replace("Released ", "")
+print(datetime.datetime.strptime(released, '%Y, %B %d').strftime("%d.%m.%Y"))
+
+

Output:

+
24.09.2021
+
+

To get the longer output:

+
print(datetime.datetime.strptime(released, '%Y, %B %d').strftime("%d. %B, %Y"))
+
+

Output:

+
24. September, 2021
+
+

EDIT:

+

In order to apply it in your code, try this:

+
details = response.xpath('//div[@class="article-info"]')
+for detail in details:
+    released = detail.xpath('.//ul/li[1]/span[1]/span/text()').get()
+    item['released'] = datetime.datetime.strptime(released.replace("Released ", ""), '%Y, %B %d').strftime("%d.%m.%Y")
+    yield item
+
",python +"Tkinter IntVar attribute error when using radiobuttons

I am making a simple calculator using tkinter, and this error message keeps showing up.

+
+

AttributeError: type object 'Tk' has no attribute 'IntVar'

+
+

Traceback:

+
+

File "c:/Desktop/my programs/Calculator.py", line 9, in +v = Tk.IntVar() +AttributeError: type object 'Tk' has no attribute 'IntVar'

+
+

here is my code:

+
import tkinter as tk
+from tkinter import *
+import time
+
+root = Tk()
+tk = Tk()
+v = Tk.IntVar()
+v.set(1)  # initializing the choice   
+root.title('Calculator')
+root.geometry('600x400+50+50')
+def calucator():
+   value1 = tk.StringVar(root, Value= 'Number:' )
+   value1 = tk.Entry(root, textvariable=value1).pack()
+   time.sleep(1)
+   value2 = tk.StringVar(root, Value= 'Number:' )
+   value2 = tk.Entry(root, textvariable=value2).pack()
+   time.sleep(1)  
+
+   operations = [("Addition", 101),
+                 ("Subtraction", 102),
+                 ("Divison", 103),
+                 ("Mulitplication", 104)]
+
+   def ShowChoice():
+       print(v.get())
+
+       tk.Label(root, 
+            text="""Choose your Operation""",
+            justify = tk.LEFT,
+            padx = 20).pack()
+
+            for operations, val in operations:
+               tk.Radiobutton(root, 
+               text=operations,
+               padx = 20, 
+               variable=v, 
+               command=ShowChoice,
+               value=val).pack(anchor=tk.W)  
+         
+
+if val==101:
+    print('value1 + value2')
+
+elif val==102:
+    print('value1 - value2')
+
+elif val==103:
+    print('value1 * value2')
+
+elif val==104:
+    print('value1 / value2')
+
+else:
+    close
+
+

I have looked everywhere and are yet to find a fix. I am aware that there are other threads on stack overflow with similar problems to mine however all the solutions I have tried have not worked.

+

Any help would be great! +mrt

","

You've imported a module and named it tk. Then you create a new object and named it tk. You can only have one thing with that name.

+

The solution is to choose a different name for the instance of Tk, or choose a different name for your import.

+

You need to remove tk=Tk(). Also, v = Tk.IntVar() needs to be v = tk.IntVar().

",python +"Map column lists to dictionary and create new column with padded strings

Given this dataframe and word_index dictionary:

+
import pandas as pd
+
+df = pd.DataFrame(data={'text_ids': [
+                                     [1, 2, 3, 2, 7, 2, 8, 2, 0],
+                                     [1, 2, 4, 2, 7, 2, 8, 2, 0],
+                                     [1, 2, 5, 2, 6, 2, 8, 2, 0],
+                                     [1, 2, 9, 2, 6, 2, 10, 2, 11, 2, 8, 0]
+                                    ]})
+
+word_index = {0: '<eos>', 1: '<sos>', 2: '/s', 3: 'he', 4: 'she', 5:'they', 6:'love', 7:'loves', 8: 'cats', 9: 'we', 10: 'talking', 11: 'about', 12: '<pad>'}
+
+

How can I map each sequence in text_ids to its corresponding value(s) in word_index, while making sure that \s really creates spaces in each string? Also, I need to add <pad> tokens to each string that has a length smaller than the largest integer sequence.

+

Expected output:

+
                                 text_ids                                       text
+0             [1, 2, 3, 2, 7, 2, 8, 2, 0]   <sos> he loves cats <eos><pad><pad><pad>
+1             [1, 2, 4, 2, 7, 2, 8, 2, 0]  <sos> she loves cats <eos><pad><pad><pad>
+2             [1, 2, 5, 2, 6, 2, 8, 2, 0]  <sos> they love cats <eos><pad><pad><pad>
+3  [1, 2, 9, 2, 6, 2, 10, 2, 11, 2, 8, 0]     <sos> we love talking about cats <eos>
+
","

You could use map to assign the values from your dictionary. Ensure to first replace '\s' with ' '.

+

Then reshape your dataframe to wide format with pivot to ensure the same number of items and fillna the missing spots with "<pad>".

+

Finally aggregate to a string with apply and join to the original dataframe:

+
word_index[2] = ' '
+
+df2 = df['text_ids'].explode().map(word_index).reset_index()
+
+df.join(
+ df2.assign(col=df2.groupby('index').cumcount())
+    .pivot('col', 'index', 'text_ids')
+    .fillna('<pad>')
+    .apply(''.join)
+    .rename('text')
+)
+
+

output:

+
                                 text_ids                                       text
+0             [1, 2, 3, 2, 7, 2, 8, 2, 0]   <sos> he loves cats <eos><pad><pad><pad>
+1             [1, 2, 4, 2, 7, 2, 8, 2, 0]  <sos> she loves cats <eos><pad><pad><pad>
+2             [1, 2, 5, 2, 6, 2, 8, 2, 0]  <sos> they love cats <eos><pad><pad><pad>
+3  [1, 2, 9, 2, 6, 2, 10, 2, 11, 2, 8, 0]      <sos> we love talking about cats<eos>
+
+

Another option using apply:

+
word_index[2] = ' '
+
+# padding values
+l = df['text_ids'].str.len()
+pad = (l.max()-l).mul(pd.Series(['<pre>']*len(l)))
+
+df['text'] = df['text_ids'].apply(lambda s: ''.join(word_index[e] for e in s))+pad
+
",python +"How to convert a dictionary according to a json scheme, Python3

I have a json scheme, which specifies the format of a dictionary in Python 3.

+
INPUT_SCHEME = {
+    "type": "object",
+    "properties": {
+        "a1": {
+            "type": "object",
+            "properties": {
+                "a1_1": {"type": ["string", "null"]},
+                "a1_2": {"type": ["number", "null"]},
+            },
+            "additionalProperties": False,
+            "minProperties": 2,
+        },
+        "a2": {
+            "type": "array",
+            "items": {"type": ["number", "null"]},
+        },
+        "a3": {
+            "type": ["number", "null"],
+        },
+        "a4": {
+            "type": "object",
+            "properties": {
+                "a4_1": {"type": ["string", "null"]},
+                "a4_2": {
+                    "type": "object",
+                    "properties": {
+                        "a4_2_1": {"type": ["string", "null"]},
+                        "a4_2_2": {"type": ["number", "null"]},
+                    },
+                    "additionalProperties": False,
+                    "minProperties": 2,
+                },
+            },
+            "additionalProperties": False,
+            "minProperties": 2,
+        },
+        "a5": {
+            "type": "array",
+            "items": {
+                "type": "object",
+                "properties": {
+                    "a5_1": {"type": ["string", "null"]},
+                    "a5_2": {"type": ["number", "null"]},
+                },
+                "additionalProperties": False,
+                "minProperties": 2,
+            },
+        },
+    },
+    "additionalProperties": False,
+    "minProperties": 5,
+}
+
+

And I want to write a function which can convert an arbitrary input dictionary to the format defined by the INPUT_SCHEME.

+

The rules are:

+
    +
  1. if the input dict misses a filed, then fill the filed with None or empty list in the output dict.
  2. +
  3. if the input dict has a key that is not defined in the INPUT_SCHEME, then remove it in the output dict.
  4. +
+

For example, suppose I have a_input, where only 'a1' is correct. 'a2', 'a3', and 'a4' are missing. Each element in 'a5' misses one property. And 'a6' is an un-defined field. +The function I want to write should convert a_input to a_output. And you can use jsonschema.validate to check.

+
a_input = {
+    'a1': {'a1_1': 'apple', 'a1_2': 20.5},
+    'a5': [{'a5_1': 'pear'}, {'a5_2': 18.5}],
+    'a6': [1, 2, 3, 4],
+}
+
+a_output = {
+    'a1': {'a1_1': 'apple', 'a1_2': 20.5},
+    'a2': [],
+    'a3': None,
+    'a4': {
+        'a4_1': None,
+        'a4_2': {
+            'a4_2_1': None,
+            'a4_2_2': None,
+        }
+    },
+    'a5': [
+        {
+            'a5_1': 'pear',
+            'a5_2': None,
+        },
+        {
+            'a5_1': None,
+            'a5_2': 18.5,
+        }
+    ]
+}
+
+jsonschema.validate(a_output, schema=INPUT_SCHEME)
+
+

I tried to write the function, but could not make it. Mainly because there are too many if-else check plus the nested structure, and I got lost. Could you please help me?

+

Thanks.

+
def my_func(a_from):
+    a_to = dict()
+    for key_1 in INPUT_SCHEME['properties'].keys():
+        if key_1 not in a_from:
+            a_to[key_1] = None  # This is incorrect, since the structure of a_to[key_1] depends on INPUT_SCHEME.
+            continue
+
+        layer_1 = INPUT_SCHEME['properties'][key_1]
+        if 'properties' in layer_1:  # like a1, a4
+            for key_2 in layer_1['properties'].keys():
+                layer_2 = layer_1['properties'][key_2]
+                ...
+
+                # but it can be a nest of layers. Like a4, there are 3 layers. In real case, it can have more layers.
+
+        elif 'items' in layer_1:
+            if 'properties' in layer_1['items']:  # like a5
+                ...
+            else:  # like a2
+                ...
+        else:  # like 3
+            ...
+    return a_to
+
","

A recursive algorithm suits this.

+

I divided it into 2 different functions as removing undefined properties and filling non-existent ones from the schema are 2 different tasks. You can merge them into one if you wish.

+

For filling nonexistent properties, I just create arrays, objects and Nones, and then recurse inwards.

+

For removing the undefined properties, I compare the schema keys and remove unmatched keys, again, recursing inwards.

+

You may see comments and type checks in code:

+
def fill_nonexistent_properties(input_dictionary, schema):
+    """
+    Fill missing properties in input_dictionary according to the schema.
+    """
+    properties = schema['properties']
+    missing_properties = set(properties).difference(input_dictionary)
+
+    # Fill all missing properties.
+    for key in missing_properties:
+        value = properties[key]
+        if value['type'] == 'array':
+            input_dictionary[key] = []
+        elif value['type'] == 'object':
+            input_dictionary[key] = {}
+        else:
+            input_dictionary[key] = None
+    
+    # Recurse inside all properties.
+    for key, value in properties.items():
+        
+        # If it's an array of objects, recurse inside each item.
+        if value['type'] == 'array' and value['items']['type'] == 'object':
+            object_list = input_dictionary[key]
+
+            if not isinstance(object_list, list):
+                raise ValueError(
+                    f"Invalid JSON object: {key} is not a list.")
+
+            for item in object_list:
+                if not isinstance(item, dict):
+                    raise ValueError(
+                        f"Invalid JSON object: {key} is not a list of objects.")
+                fill_nonexistent_properties(item, value['items'])
+
+        # If it's an object, recurse inside it.
+        elif value['type'] == 'object':
+            obj = input_dictionary[key]
+            if not isinstance(obj, dict):
+                raise ValueError(
+                    f"Invalid JSON object: {key} is not a dictionary.")
+            fill_nonexistent_properties(obj, value)
+
+def remove_undefined_properties(input_dictionary, schema):
+    """
+    Remove properties in input_dictionary that are not defined in the schema.
+    """
+    properties = schema['properties']
+    undefined_properties = set(input_dictionary).difference(properties)
+
+    # Remove all undefined properties.
+    for key in undefined_properties:
+        del input_dictionary[key]
+    
+    # Recurse inside all existing sproperties.
+    for key, value in input_dictionary.items():
+        property_shcema = properties[key]
+
+        # If it's an array of objects, recurse inside each item.
+        if isinstance(value, list):
+            if not property_shcema['type'] == 'array':
+                raise ValueError(
+                    f"Invalid JSON object: {key} is not a list.")
+
+            # We're only dealing with objects inside arrays.
+            if not property_shcema['items']['type'] == 'object':
+                continue
+            
+            for item in value:
+                # Make sure each item is an object.
+                if not isinstance(item, dict):
+                    raise ValueError(
+                        f"Invalid JSON object: {key} is not a list of objects.")
+                remove_undefined_properties(item, property_shcema['items'])
+        
+        # If it's an object, recurse inside it.
+        elif isinstance(value, dict):
+            # Make sure the object is supposed to be an object.
+            if not property_shcema['type'] == 'object':
+                raise ValueError(
+                    f"Invalid JSON object: {key} is not an object.")
+
+            remove_undefined_properties(value, property_shcema)
+
+
+import pprint
+pprint.pprint(a_input)
+fill_nonexistent_properties(a_input, INPUT_SCHEME)
+remove_undefined_properties(a_input, INPUT_SCHEME)
+print("-"*10, "OUTPUT", "-"*10)
+pprint.pprint(a_input)
+
+

Output:

+
{'a1': {'a1_1': 'apple', 'a1_2': 20.5},
+ 'a5': [{'a5_1': 'pear'}, {'a5_2': 18.5}],
+ 'a6': [1, 2, 3, 4]}
+---------- OUTPUT ----------
+{'a1': {'a1_1': 'apple', 'a1_2': 20.5},
+ 'a2': [],
+ 'a3': None,
+ 'a4': {'a4_1': None, 'a4_2': {'a4_2_1': None, 'a4_2_2': None}},
+ 'a5': [{'a5_1': 'pear', 'a5_2': None}, {'a5_1': None, 'a5_2': 18.5}]}
+
",python +"Stop auto rounding in numpy

I have this code but in the result, the values are converted to integers. I want the real value. How? Thank you for your help.

+

+import numpy as np
+
+a=np.array([1,2,3,4])
+
+f=np.array([0.00020,0.0001])
+
+for i in range(2):
+    a[i]=f[i]
+print(a)
+# [0 0 3 4]
+
","

a is an array of integers, you have to set it to a float array

+
a=np.array([1,2,3,4], dtype=float)
+
",python +"Pyinstaller --hidden-imports not wirking

I'm trying to build an exe file from a python game using PyBox2D and Pyglet.

+

When I build the exe there occurs an error that a module cannot be imported:
+Unable to import the back-end pyglet: module 'gui.backends' has no attribute 'pyglet_framework'
+I guess this happens because this file only gets imported indirectly/hidden from another file with __import__()

+

This is my project hierarchy:
+

+

I've tried to add the file to pyinstaller on multiple ways. From the directory /SpaceJam/building I've tried calling:

+
pyinstaller.exe --onefile "../game/spacejam.py" --hidden-import="gui/framework/backends/pyglet_framework.py"
+pyinstaller.exe --onefile "../game/spacejam.py" --hidden-import="../gui/framework/backends/pyglet_framework.py"
+pyinstaller.exe --onefile "../game/spacejam.py" --hidden-import="../gui/framework/backends/pyglet_framework"
+pyinstaller.exe --onefile "../game/spacejam.py" --hidden-import="../gui/framework/backends/*"
+
+

but none of that seemed to change anything in the error message.

+

I feel like I'm missing something obvious. Does somebody have an idea what I might be doing wrong or why the --hidden-import argument doesn't seem to work?

","

That argument expects a module name, not a filesystem path. How would you import it?

+

I'm not totally clear on how your project is set up, but try

+
--hidden-import gui.backends.pyglet_framework
+
",python +"How to extract text from multiple pdf in a location with specific line and store in Excel?

I have 100 pdf stored in a location and I want to extract text from them and store in excel +below is pdf image +in this i want (stored in page1)

+
bid no,end date,item category,organisation name 
+
+

+

+

needed

+
OEM Average Turnover (Last 3 Years),Years of Past Experience required,MSE Exemption for Years Of Experience
+and Turnover,Startup Exemption for Years of Experience
+and Turnover,Estimated Bid Value,EMD Required
+
+

+

Consignee address only) +

","

Tika is one of the Python packages that you can use to extract the data from your PDF files.

+

In the example below I'm using Tika and regular expressions to extract these five data elements:

+
    +
  • bid no
  • +
  • end date
  • +
  • item category
  • +
  • organisation name
  • +
  • total quantity
  • +
+
import re as regex
+from tika import parser
+
+parse_entire_pdf = parser.from_file('2022251527199.pdf', xmlContent=True)
+for key, values in parse_entire_pdf.items():
+    if key == 'content':
+        bid_number = regex.search(r'(Bid Number:)\W(GEM\W\d{4}\W[A-Z]\W\d+)', values)
+        print(bid_number.group(2))
+        GEM/2022/B/1916455
+
+        bid_end_date = regex.search(r'(Bid End Date\WTime)\W(\d{2}-\d{2}-\d{4}\W\d{2}:\d{2}:\d{2})', values)
+        print(bid_end_date.group(2))
+        21-02-2022 15:00:00
+
+        org_name = regex.search(r'(Organisation Name)\W(.*)', values)
+        print(org_name.group(2))
+        State Election Commission (sec), Gujarat
+
+        item_category = regex.search(r'(Item Category)\W(.*)', values)
+        print(item_category.group(2))
+        Desktop Computers (Q2) , Computer Printers (Q2)
+ 
+        total_quantity = regex.search(r'(Total Quantity)\W(\d+)', values)
+        print(total_quantity.group(2))
+        18
+
+
+

Here is one way to write out the extracted data to a CSV file:

+
import csv
+import re as regex
+from tika import parser
+
+document_elements = []
+
+# processing 2 documents 
+documents = ['202225114747453.pdf', '2022251527199.pdf']
+for doc in documents:
+    parse_entire_pdf = parser.from_file(doc, xmlContent=True)
+    for key, values in parse_entire_pdf.items():
+        if key == 'content':
+            bid_number = regex.search(r'(Bid Number:)\W(GEM\W\d{4}\W[A-Z]\W\d+)', values)
+
+            bid_end_date = regex.search(r'(Bid End Date\WTime)\W(\d{2}-\d{2}-\d{4}\W\d{2}:\d{2}:\d{2})', values)
+
+            org_name = regex.search(r'(Organisation Name)\W(.*)', values)
+
+            item_category = regex.search(r'(Item Category)\W(.*)', values)
+
+            total_quantity = regex.search(r'(Total Quantity)\W(\d+)', values)
+            
+            document_elements.append([bid_number.group(2),
+                                      bid_end_date.group(2), 
+                                      org_name.group(2), 
+                                      item_category.group(2),
+                                      total_quantity.group(2)])
+
+
+with open("out.csv", "w", newline="") as f:
+    headerList = ['bid_number', 'bid_end_date', 'org_name', 'item_category', 'total_quantity']
+    writer = csv.writer(f)
+    writer.writerow(headerList)
+    writer.writerows(document_elements)
+
+

+

Here is the additional code that you asked for in the comments.

+
import os
+import re as regex
+from tika import parser
+
+document_elements = []
+
+image_directory = "pdf_files"
+image_directory_abspath = os.path.abspath(image_directory)
+for dirpath, dirnames, filenames in os.walk(image_directory_abspath):
+    for filename in [f for f in filenames if f.endswith(".pdf")]:
+        parse_entire_pdf = parser.from_file(os.path.join(dirpath, filename), xmlContent=True)
+        for key, values in parse_entire_pdf.items():
+            if key == 'content':
+                bid_number = regex.search(r'(Bid Number:)\W(GEM\W\d{4}\W[A-Z]\W\d+)', values)
+
+                bid_end_date = regex.search(r'(Bid End Date\WTime)\W(\d{2}-\d{2}-\d{4}\W\d{2}:\d{2}:\d{2})', values)
+
+                org_name = regex.search(r'(Organisation Name)\W(.*)', values)
+
+                item_category = regex.search(r'(Item Category)\W(.*)', values)
+
+                total_quantity = regex.search(r'(Total Quantity)\W(\d+)', values)
+
+                document_elements.append([bid_number.group(2),
+                                          bid_end_date.group(2),
+                                          org_name.group(2),
+                                          item_category.group(2),
+                                          total_quantity.group(2)])
+
+with open("out.csv", "w", newline="") as f:
+    headerList = ['bid_number', 'bid_end_date', 'org_name', 'item_category', 'total_quantity']
+    writer = csv.writer(f)
+    writer.writerow(headerList)
+    writer.writerows(document_elements)
+
+
+

SPECIAL NOTE: I noted that some PDFs don't have an org_name, so you will have to figure out how to handle these with either a N/A, None, or Null

",python +"How to pull comments from individual Youtube videos instead of random videos

I'm building a project using the Youtube API where I want to pull comments from each video in a specific youtuber's channel. However, when I pull the comments, it only pulls one comment from each video instead of pulling 100 comments from each video like I want it to.

+
def get_video_comments(video_id):
+    url_video_comments ='https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId='+video_id+'&maxResults=100&key='+API_KEY
+    response_video_comments = requests.get(url_video_comments).json()
+    
+    for comment in response_video_comments['items']:
+        if comment['kind'] == 'youtube#commentThread':
+            comment_text = comment['snippet']['topLevelComment']['snippet']['textOriginal']
+            comment_likes = comment['snippet']['topLevelComment']['snippet']['likeCount']
+    
+    return comment_text, comment_likes
+
+def get_videos(df,df_comments,pageToken):
+    url = 'https://www.googleapis.com/youtube/v3/search?key='+API_KEY+'&channelId='+channel_id+'&pageToken='+pageToken+'&part=snippet,id&order=date&maxResults=10000'
+    
+    response = requests.get(url).json()
+    # wait 1 second before executing for loop in order to get all of the data
+    time.sleep(1)
+    # create loop to get information on every video
+    for video in response['items']:
+        # makes sure that we only get information on videos
+        if video['id']['kind'] == 'youtube#video':
+            video_id = video['id']['videoId']
+            video_title = video['snippet']['title']
+            upload_date = video['snippet']['publishedAt']
+            upload_date = str(upload_date).split('T')[0]
+
+            view_count, like_count, comment_count = get_video_details(video_id)
+            comment_text, comment_likes = get_video_comments(video_id)
+            # save data in pandas DF
+            df = df.append({'video_id':video_id,'video_title':video_title, 'upload_date':upload_date, 'view_count':view_count,
+                            'like_count':like_count,'comment_count':comment_count}
+                          , ignore_index=True)
+            df_comments = df_comments.append({'video_id':video_id, 'comment_text':comment_text,
+                                             'comment_likes':comment_likes},ignore_index=True)
+    return df, df_comments
+
+

Below is the output.

+
    video_id    comment_text    comment_likes
+0   0faCad2kKeg Basically, this video describes how you are ab...   0
+1   9dnN82DsQ2k thanks for using metric 0
+2   Y413Czri6qw "Another way to fight climate change is to eat...   0
+3   W3qZIPiWKc4 6:00    0
+4   ggUduBmvQ_4 should be illegal to pull loans for speculation 0
+5   xhxo2oXRiio Man, this is really getting to me :(    0
+6   8d5d_HXGeMA Not sure how you can fail to bring up powerful...   0
+7   8egszLpKMWU africa is not the next anything.    0
+8   WNrobOYWZQE For space exploration to happen, war needs to ...   0
+9   ZZ3F3zWiEmc Taxes themselves are Legalized theft. Moreover...   0
+10  V16GdzRvhRU Saudi Arabia and the other Islamic oil kingdom...   0
+11  o4tuhWvKduU This video makes getting out of Afganistan see...   0
+12  1-uNMj57Y4c Meanwhile, I am not in the air travel market a...   0
+13  SR7BA3xEmDo rather trains...... 0
+14  iO5mfbpq16A Because the Southern hemisphere is mostly wate...   0
+15  B3FKtBNEBRc The annoying playground cytomorphologically sm...   0
+16  VJtFgte1GKc 10:36 the ruthless pursuit of a fish in sea 0
+17  J5PLyYVIEpg "Indian nation" Indians are in India    1
+18  LHhJuAOK3CI This is really great, but I hope you do more p...   0
+19  aH4b3sAs-l8 What would happen if lightning hit it mid flight?   0
+20  b1JlYZQG3lI You actually can't be more wrong. We shut down...   1
+21  BNpk_OGEGlA We control the supply chain by how involved we...   0
+22  4p0fRlCHYyg Hey did you see the “new” united supersonic pl...   0
+23  N4dOCfWlgBw I hope the cruise industry dies 0
+24  3CuPqeIJr3U You westerners your days are up..Just get lost  0
+25  DlTq8DbRs4k Maggie's dead now :)    0
+26  VjiH3mpxyrQ What you’ve missed about ‘Crisis’ stress testi...   0
+27  pLcqJ2DclEg If I were to buy a Tesla Today, I would also h...   0
+28  3gdCH1XUIlE I’m glad I live in a civilized country where t...   0
+29  2qanMpnYsjk I just had this recommended to me and I can al...   0
+30  7R7jNWHp0D0 Another unequal biased Biden loving Trump hat...    0
+31  GIFV_Z7Y9_w Hello from Kazakhstan   0
+32  KXRtNwUju5g This is sexist, why was it women that throws t...   0
+33  fTyUE162lrw What's the point of these subscription based l...   0
+34  ZAEydOjNWyQ So if Covid is stoping it, just get everybody ...   0
+35  _BCY0SPOFpE Great observation   0
+36  v_rXhuaI0W8 13:50 Such a lie. 1) The two have nothing to d...   0
+37  Ongqf93rAcM This works but it’s still gambling so don’t ex...   0
+38  byW1GExQB84 Can we have an update?\nAstra Zeneca seems rea...   1
+39  DTIDCA7mjZs My dad be like: Gracias por las instrucciones ...   1
+40  H_akzwzghWQ Why are you showing us graphs of "percent devi...   0
+41  7C1fPocIFgU There is a (partial) solution in the middle. C...   0
+42  3J06af5xHD0 Her speech bought me to tears.  0
+43  YgiMqePRp0Y There is a problem with pooled testing. The th...   0
+44  Rtmhv5qEBg0 Great work good game    0
+45  6GMoUmvw8kU 9:48 yo, wtf is wrong with that man`s face? 0
+46  QlPrAKtegFQ Follow along as a west bound autonomous 80,000...   0
+47  uAG4zCsiA_w development of tiltrotor aircraft has almost s...   1
+48  NtX-Ibi21tU Wait there is a risk of 1:55 000 by walking ou...   0
+49  r2oPk20OHBE 2:41 The street where I live was the last thin...   0
+
+

The video_id matches the video that I want to pull the comments from. I'm just struggling to understand how I can pull more than one comment. Any help would be greatly appreciated.

","

It seems that your get_video_comments function is quite well designed with the for loop for comment in response_video_comments['items']: however at each iteration you overwrite the previous comment that was in comment_text your get_video_comments function should instead returns an array of comment_text and comment_likes and at each iteration you should happend to this array the current working comment.

+

The algorithm to grab all comments from a video is very common, deepen your searches if you are still stuck.

",python +"Gstreamer how to get element information from STATE_CHANGED message from the bus

I am working with Gstreamer and its Python bindings. Consider the following bus_call function:

+
import sys
+from gi.repository import Gst
+
+
+def bus_call(bus, message, loop):
+    t = message.type
+    if t == Gst.MessageType.EOS:
+        print("Bus call: End-of-stream\n")
+        # loop.quit()
+    elif t == Gst.MessageType.WARNING:
+        err, debug = message.parse_warning()
+        sys.stderr.write("Bus call: Warning: %s: %s\n" % (err, debug))
+    elif t == Gst.MessageType.ERROR:
+        err, debug = message.parse_error()
+        sys.stderr.write("Bus call: Error: %s: %s\n" % (err, debug))
+        # loop.quit()
+    elif t == Gst.MessageType.BUFFERING:
+        print("Bus call: Buffering\n")
+    elif t == Gst.MessageType.STATE_CHANGED:
+        old_state, new_state, pending_state = message.parse_state_changed()
+        print((
+            f"Bus call: Pipeline state changed from {old_state.value_nick} to {new_state.value_nick} "
+            f"(pending {pending_state.value_nick})"
+        ))
+    else:
+        print(f"Bus call: {message}\n")
+    return True
+
+

When the message type is Gst.MessageType.STATE_CHANGED, how can I retrieve the element that has changed the state?

","

Not sure I correctly understand, but you may try something like:

+
old_state, new_state, pending_state = message.parse_state_changed()
+print('%s : State changed from %s to %s' % (message.src.get_name(), old_state, new_state))
+
",python +"Multiply two Dataframes if the column names and the condition on a column value matches

I have two dataframes(namely a and b):

+

a =

+

+

and b =

+

+

And I am looking for a way to multiply the values in each column of Dataframe a with the corresponding column value of Dataframe b if the dates are matching. For example:values in column aa_10 of Dataframe a for the date 2021-01-19 with the corresponding value in column aa_10 of Dataframe b for the date 2021_01_19 (i.e., the column- NaN, 2.0, 3.0,4.0 of Dataframe a to be multiplied with the value 4 in Dataframe b) and so on.

+

Desired result:

+

+

Sample Data:

+
import numpy as np
+import pandas as pd
+  
+d = {'Date'  : pd.Series([20210119, 20210119, 20210119, 20210119, 20210122, 20210122, 20210122, 20210122]),
+     'To'  : pd.Series(['aa', 'bb', 'cc', 'dd', 'aa', 'bb', 'cc', 'dd']),
+     'aa_10' : pd.Series([np.nan, 2, 3, 4, np.nan, 4, 3, 2]),
+     'bb_11' : pd.Series([6, np.nan, 8, 9, 9, np.nan, 7, 8]),
+     'cc_12' : pd.Series([1, 2, np.nan, 4, 4, 3, np.nan, 5]),
+     'dd_13' : pd.Series([6, 7, 8, np.nan, 8, 6, 9, np.nan])}
+  
+# creates Dataframe.
+a = pd.DataFrame(d)
+a['Date'] = pd.to_datetime(a['Date'], format='%Y%m%d')
+# print the data.
+display (a)
+
+# Initialize data to Dicts of series.
+d = {'Date'  : pd.Series([20190110, 20210119, 20210121, 20210122]),
+     'aa_10' : pd.Series([2, 4, 1, 2]),
+     'bb_11' : pd.Series([1, 3, 5, 4]),
+     'cc_12' : pd.Series([10, 12, 4, 2]),
+     'dd_13' : pd.Series([2, 1, 2, 5])}
+  
+# creates Dataframe.
+b = pd.DataFrame(d)
+b['Date'] = pd.to_datetime(b['Date'], format='%Y%m%d')  
+# print the data.
+display(b)
+
","

Set_index as date and multiply

+
s=a.set_index(['Date', 'To']).mul(b.set_index(['Date'])).reset_index()
+
+
+
+
+   Date  To  aa_10  bb_11  cc_12  dd_13
+0 2021-01-19  aa    NaN   18.0   12.0    6.0
+1 2021-01-19  bb    8.0    NaN   24.0    7.0
+2 2021-01-19  cc   12.0   24.0    NaN    8.0
+3 2021-01-19  dd   16.0   27.0   48.0    NaN
+4 2021-01-22  aa    NaN   36.0    8.0   40.0
+5 2021-01-22  bb    8.0    NaN    6.0   30.0
+6 2021-01-22  cc    6.0   28.0    NaN   45.0
+7 2021-01-22  dd    4.0   32.0   10.0    NaN
+
",python +"iterating through pandas dataframe and create new columns using custom function

I have a pandas dataframe which (obviously) contain some data. I have created a function that outputs a number new columns. How can I iterate or apply that function?

+

I have created a minimum example below ( not the actual problem), with a dataframe and function.

+

EDIT: Think of the function as a "black box". We don't now what is in, but based on the input it returns a dataframe, that should be added to the existing dataframe.

+
import pandas as pd
+a=pd.DataFrame({"input1": ["a","b"], "input2":[3,2]})
+
+  input1  input2
+0      a       3
+1      b       2
+
+def f(i1,i2):
+    return(pd.DataFrame([{"repeat" : [i1]*i2, "square":i2**2 }]))
+
+
+

So in this case the function returns two new columns "repeat" and "square"

+
f(a.iloc[0,0],a.iloc[0,1])
+
+      repeat  square
+0  [a, a, a]       9
+
+f(a.iloc[1,0],a.iloc[1,1])
+   repeat  square
+0  [b, b]       4
+
+

What I would like to end up with a data frame like this

+
  input1  input2     repeat  square
+0      a       3  [a, a, a]       9
+1      b       2     [b, b]       4
+
+

Does anyone have an elegant solution to this?

","

How about using pd.concat?

+
generated_df = pd.concat([f(*args) for args in a.to_numpy()], ignore_index=True)
+out = pd.concat([a, generated_df], axis=1)
+
+

Output:

+
>>> out
+  input1  input2     repeat  square
+0      a       3  [a, a, a]       9
+1      b       2     [b, b]       4
+
",python +"How to submit data using HTML in the frontend and get the results from FastAPI backend?

I am using FastAPI for the backend and HTML/CSS for the frontend. I want to click the button and get the wanted value in return (mt means when I put node1 and node2 it gets me its prediction from the JSON array.

+

This is my code:

+

This is the data list

+
prediction_data = [
+  { "node1": 0, "node2": 1, "pred": 0},
+  { "node1": 0, "node2": 476, "pred":0.352956 },
+  { "node1": 0, "node2": 494, "pred":0.769988 },
+  { "node1": 1, "node2": 505, "pred":0.463901 },
+  { "node1": 9, "node2": 68 , "pred":1.238807},
+  { "node1": 15, "node2": 408, "pred":0.204171 },
+  { "node1": 18, "node2":549 , "pred":0.204171 },
+  { "node1": 60, "node2": 227, "pred":0.204171 },
+  { "node1": 199, "node2": 220, "pred":0.245246 },
+  { "node1": 170, "node2": 570, "pred":0.509272 },
+  { "node1": 148, "node2": 570, "pred":0.204171 },
+  { "node1": 151, "node2": 384, "pred":0.204114 },
+  { "node1": 232, "node2": 337, "pred":0.285999 },
+  { "node1": 446, "node2": 509, "pred":0.291206 },
+  { "node1": 510, "node2":576 , "pred":0.495378 },
+  { "node1": 571, "node2":589 , "pred":0 },
+  { "node1": 585, "node2":596 , "pred":0.245243 },
+  { "node1": 446, "node2":509 , "pred":0.291206 },
+  { "node1": 375, "node2":383 , "pred":0.46390 },
+  { "node1": 461, "node2":462 , "pred":0 }
+    ]
+
+

This the getter function of the wanted value

+
# Prediction
+@app.get("/prediction/{node1,node2}", response_class=HTMLResponse)
+async def gets(request: Request, node1: int, node2: int):
+    matching = list(filter(lambda x: x['node1'] == node1 and x['node2'] == node2, prediction_data))
+    mt = matching[0]['pred'] if matching else None
+    return templates.TemplateResponse("Interface.html", {"request": request, "mt": mt})
+
+

This is the interface

+

+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+
+    <title>Link Prediction</title>
+    <link href="{{ url_for('static', path='/style.css') }}" rel="stylesheet">
+</head>
+
+<body>
+    <div class="container" >
+        <h1>Link Prediction </h1>
+        <h2>In Social Network</h2>
+        <form class="form" action="#">
+          <fieldset class="form-fieldset ui-input __first">
+            <input type="number" id="Node1" tabindex="0" /> {{node1}}
+            <label for="Node1">
+              <span data-text="Node 1">Node 1</span>
+            </label>
+          </fieldset>
+          
+          <fieldset class="form-fieldset ui-input __second">
+            <input  type="number" id="Node2" tabindex="0" /> {{node2}}
+            <label for="Node2">
+              <span data-text="Node 2">Node 2 </span>
+            </label>
+          </fieldset>
+
+          <div class="form-footer">
+            <button  onclick="myfunctionName(Node1, Node2)" class="btn">Predict Now</button>
+          </div>
+
+          <script type="text/javascript">
+              
+              function myfunctionName( n1,n2 ){
+          
+                  document.getElementById("Node1").innerHTML += n1;
+                  document.getElementById("Node2").innerHTML += n2;
+                  document.getElementById("Prediction") = mt;
+              }
+          
+          </script>
+
+<fieldset class="form-fieldset ui-input __third">
+    <input type="text" id="Prediction" readonly/> {{mt}}
+    <label for="Prediction">
+      <span data-text="Prediction Result" >Prediction Result</span>
+    </label>
+  </fieldset>
+          
+        </form>
+      </div>
+</body>
+</html>
+
+
+
","

To start with, you should have a look at how Path parameters work in FastAPI. The following in your code @app.get("/prediction/{node1,node2}" is not a valid route for passing path parameters. It will instead be recognised as a single path name. You can verify this by opening Swagger UI +at http://127.0.0.1:8000/docs, which shows that the endpoint expects node1 and node2 to be query params, not path params. When submitting form data, one should use Form for that purpose, and POST HTTP method (your endpoint should be using @app.post()). Please take the time to read the documentation, as well as have a look at this answer. If you still, however, need this to be a GET request, you can use a GET operation @app.get() in your API, as well as define the method for your HTML form being method="GET". Below is an example demonstrating this.

+

In your API (access the main page at http://127.0.0.1:8000):

+
@app.get("/", response_class=HTMLResponse)
+def main(request: Request):
+    return templates.TemplateResponse("predict.html", {"request": request})
+    
+@app.get("/predict", response_class=HTMLResponse)
+def predict(request: Request, node1: int, node2: int):
+    matching = list(filter(lambda x: x['node1'] == node1 and x['node2'] == node2, prediction_data))
+    mt = matching[0]['pred'] if matching else None
+    return templates.TemplateResponse("predict.html", {"request": request, "node1": node1, "node2": node2, "mt": mt})
+
+

In your template (i.e., predict.html in the case above)

+
<!DOCTYPE html>
+<html lang="en">
+   <body>
+      <h1>Link Prediction </h1>
+      <h2>In Social Network</h2>
+      <form method="GET" action="/predict" id="myForm">
+         node1 : <input type="text" name="node1" value={{node1}}> <br>
+         node2 : <input type="text" name="node2" value={{node2}}><br>
+         <input type="submit" value="Predict" >
+      </form>
+      Prediction Result: <b>{{mt}}</b>
+   </body>
+</html>
+
",python +"python - calculate a new column in pandas using 2 numpy arrays

I have a pandas dataframe : +column header is called "Location" +example contents: +"London Arndale Centre" +"Manchester Arndale" +"Birmingham Central Station" +"Newcastle Metro Centre"

+

2 numpy arrays :

+
originalLocation = np.array(["London Arndale Centre","Manchester Arndale","Birmingham Central Station","Newcastle Metro Centre")
+
+newLocation = np.array(["London","Manchester","Birmingham","Newcastle"]
+
+

i want to create a new column in the pandas : newLocation

+

the result needs to be the matching column in newLocation, where the location field matches the original location numpy.

+

example : "London Arndale Centre" needs to be "London" +"Manchester Arndale" needs to be "Manchester"

+

i have tried this , but it throw back errors

+
df['newLocation'] = newLocation[int(np.where(originalLocation == df['Location'])[0])]
+
+

errors : ValueError: ('Lengths must match to compare', (159,), (12,))

+

what am i doing wrong here ?

","

It seems like you forgot the commas in your originalLocation array. Also, the int() is not necessary. Updated code:

+
df_data = ["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"]
+df = pd.DataFrame(df_data, columns=['Location'])
+
+originalLocation = np.array(["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"])
+
+newLocation = np.array(["London","Manchester","Birmingham","Newcastle"])      
+
+df['newLocation'] = newLocation[np.where(originalLocation == df['Location'])[0]]
+
+df
+
+

Output:

+
    Location    newLocation
+0   London Arndale Centre   London
+1   Manchester Arndale  Manchester
+2   Birmingham Central Station  Birmingham
+3   Newcastle Metro Centre  Newcastle
+
+

EDIT: As you mentioned merge works even if not all values are included in the new locations. I create a small example using merge:

+
df_data = ["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"]
+df = pd.DataFrame(df_data, columns=['Location'])
+
+originalLocation = ["London Arndale Centre", "Birmingham Central Station", "Newcastle Metro Centre"]
+newLocation = ["London", "Birmingham", "Newcastle"]   
+
+df_new = pd.DataFrame({'Location': originalLocation,
+                       'newLocation': newLocation})
+
+df.merge(df_new, on='Location', how='left')
+
+

Output with Manchester entry missing:

+
Location    newLocation
+0   London Arndale Centre   London
+1   Manchester Arndale  NaN
+2   Birmingham Central Station  Birmingham
+3   Newcastle Metro Centre  
+
",python +"get count of all positive values at each row - pandas

I have dataset with values above and below 0 and I want to calculate count of +ve and -ve with sum and count of values above a threshold added as new column. This dataset has 60 columns.

+

Dataset

+
A  B       C  D  E
+0  foo   1.2 -1  2
+1  bar   1.3 -2 -4
+2  baz   2.1  2  5
+
+

The desired result,

+
A  B         C  D  E    postive_count   negative_count sum_pos   sum_neg    above_2
+0  foo     1.2 -1  2                2               1      3.2        -1          1
+1  bar     1.3 -2 -4                1               2      1.3        -6          0
+2  baz     2.1  2  5                3               3      9.1         0          3
+
+

I have tried [1] 2 but these add it for columns and not full row. Any ideas would be appreciated!

","

You need to use axis to apply the operation row-wise: +df['positive_count'] = df[df>0].count(axis=1)

",python +"OnnxRuntime vs OnnxRuntime+OpenVinoEP inference time difference

I'm trying to accelerate my model's performance by converting it to OnnxRuntime. However, I'm getting weird results, when trying to measure inference time.

+

While running only 1 iteration OnnxRuntime's CPUExecutionProvider greatly outperforms OpenVINOExecutionProvider:

+
    +
  • CPUExecutionProvider - 0.72 seconds
  • +
  • OpenVINOExecutionProvider - 4.47 seconds
  • +
+

But if I run let's say 5 iterations the result is different:

+
    +
  • CPUExecutionProvider - 3.83 seconds
  • +
  • OpenVINOExecutionProvider - 14.13 seconds
  • +
+

And if I run 100 iterations, the result is drastically different:

+
    +
  • CPUExecutionProvider - 74.19 seconds
  • +
  • OpenVINOExecutionProvider - 46.96seconds
  • +
+

It seems to me, that the inference time of OpenVinoEP is not linear, but I don't understand why. +So my questions are:

+
    +
  • Why does OpenVINOExecutionProvider behave this way?
  • +
  • What ExecutionProvider should I use?
  • +
+

The code is very basic:

+
import onnxruntime as rt
+import numpy as np
+import time 
+from tqdm import tqdm
+
+limit = 5
+# MODEL
+device = 'CPU_FP32'
+model_file_path = 'road.onnx'
+
+image = np.random.rand(1, 3, 512, 512).astype(np.float32)
+
+# OnnxRuntime
+sess = rt.InferenceSession(model_file_path, providers=['CPUExecutionProvider'], provider_options=[{'device_type' : device}])
+input_name = sess.get_inputs()[0].name
+
+start = time.time()
+for i in tqdm(range(limit)):
+    out = sess.run(None, {input_name: image})
+end = time.time()
+inference_time = end - start
+print(inference_time)
+
+# OnnxRuntime + OpenVinoEP
+sess = rt.InferenceSession(model_file_path, providers=['OpenVINOExecutionProvider'], provider_options=[{'device_type' : device}])
+input_name = sess.get_inputs()[0].name
+
+start = time.time()
+for i in tqdm(range(limit)):
+    out = sess.run(None, {input_name: image})
+end = time.time()
+inference_time = end - start
+print(inference_time)
+
","

The use of ONNX Runtime with OpenVINO Execution Provider enables the inferencing of ONNX models using ONNX Runtime API while the OpenVINO toolkit runs in the backend. +This accelerates ONNX model's performance on the same hardware compared to generic acceleration on Intel® CPU, GPU, VPU and FPGA.

+

Generally, CPU Execution Provider works best with small iteration since its intention is to keep the binary size small. Meanwhile, the OpenVINO Execution Provider is intended for Deep Learning inference on Intel CPUs, Intel integrated GPUs, and Intel® MovidiusTM Vision Processing Units (VPUs).

+

This is why the OpenVINO Execution Provider outperforms the CPU Execution Provider during larger iterations.

+

You should choose Execution Provider that would suffice your own requirements. If you going to execute complex DL with large iteration, then go for OpenVINO Execution Provider. For a simpler use case, where you need the binary size to be smaller with smaller iterations, you can choose the CPU Execution Provider instead.

+

For more information, you may refer to this ONNX Runtime Performance Tuning

",python +"How to pass a parameter into bigquery query on colab

I have a Bigquery query on colab:

+
from google.colab import auth
+auth.authenticate_user()
+print('Authenticated')
+project_id = '[your project ID]'
+
+sample_count = 2000
+df = pd.io.gbq.read_gbq('''
+  SELECT name, SUM(number) as count
+  FROM `bigquery-public-data.usa_names.usa_1910_2013`
+  WHERE state = 'TX'
+  AND year BETWEEN 1910 AND 1920
+  GROUP BY name
+  ORDER BY count DESC
+  LIMIT 100
+''', project_id=project_id, dialect='standard')
+
+df.head()
+
+

It works, but now I try to pass a parameter into the query and replace '1920' in the query WHERE clause. this parameter is dependent on another file

+
end_year = max(record.year) # set end_year
+
+df = pd.io.gbq.read_gbq('''
+  SELECT name, SUM(number) as count
+  FROM `bigquery-public-data.usa_names.usa_1910_2013`
+  WHERE state = 'TX'
+  AND year BETWEEN 1910 AND end_year
+  GROUP BY name
+  ORDER BY count DESC
+  LIMIT 100
+''', project_id=project_id, dialect='standard')
+
+df.head()
+
+

But I get an error:

+
BadRequest: 400 Syntax error: Unexpected identifier "end_year"
+
+

I guess the parameter doesn't pass into the query successfully, but I don't know how to fix it.

","

As @Mike Karp mentioned, the query in your code is a String that is why you are encountering an error whenever you are passing your variable directly to the query.

+

You may also use python's f string to format your string and be able to pass the variable inside your query.

+
from google.colab import auth
+import pandas as pd
+auth.authenticate_user()
+print('Authenticated')
+project_id = 'PROJECT_ID'
+
+end_year = max(record.year) # set end_year
+
+query = (f" SELECT name, SUM(number) as count \
+  FROM `bigquery-public-data.usa_names.usa_1910_2013` \
+  WHERE state = 'TX' \
+  AND year BETWEEN 1910 AND {end_year} \
+   GROUP BY name \
+  ORDER BY count DESC \
+  LIMIT 100")
+
+df = pd.io.gbq.read_gbq(query=query, project_id=project_id, dialect='standard')
+
+df.head()
+
",python +"Run out of memory trying to create a tensor of size [2191, 512] with pytorch to save data from movie frames using CLIP

I'm using pytorch for the first time and I'm facing a problem I don't think I should. I currently have selected 2919 frames of a movie in jpg. I'm trying to transform all those images into a single tensor. I'm using CLIP to transform each image into a tensor of size [1, 512]. In the end, I expected to have a tensor of size [2919, 512], which should not use that much memory. But my code never finishes running and I can only assume I'm doing something terribly wrong.

+

First I'm doing my import and loading the model:

+
import torch
+import clip
+from glob import glob
+from PIL import Image
+
+device = "cuda" if torch.cuda.is_available() else "cpu"
+model, preprocess = clip.load("ViT-B/32", device=device)
+
+

Secondly, I'm reading the path for all the images and initializing the "film" tensor with random value to overwrite them. I tried generating an empty one and concatenate but that also consumed too much memory:

+
path_names = glob(r"Films/**/*.jpg")
+film = torch.rand((len(files), 512), dtype=torch.float32, device = device)
+film_frame_count = 0
+    for file in files:
+        print("Frame " + str(film_frame_count) + " out of " + str(len(files)))
+        film[film_frame_count] = model.encode_image(preprocess(Image.open(file)).unsqueeze(0).to(device))[0]
+        film_frame_count += 1
+    torch.save(film, 'output_tensor/'+ film_code[1])
+
+

If anyone could point it out what I'm doing wrong I would appreciate.

","

The problem ended up being caused because pytorch was saving the gradiants for the graph, so I needed to indicate that I didn't want them to be stored with this indicator on top:

+
with torch.no_grad():
+    /*my code*/
+
",python +"python regex to read text file and split row to column

My text file format is like below

+
ID  col_A   col_B   col_C
+1   0.26    0.11    0.18
+2   0.27    0.12    0.17
+3   0.21    0.10    0.15
+----------------------------
+AVG 0.25    0.11    0.17
+----------------------------
+ID  col_D   col_E   col_F
+1   0.23    0.18    0.20
+2   0.24    0.14    0.17
+3   0.23    0.10    0.13
+----------------------------
+AVG 0.23    0.14    0.17
+----------------------------
+
+

I'm attempting to use python and regex to export two separate csv files with the format like below

+

Table 1

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDcol_Acol_Bcol_Ccol_Dcol_Ecol_F
10.260.110.180.230.180.20
20.270.120.170.240.140.17
30.210.100.150.230.100.13
+
+

Table 2

+
+ + + + + + + + + + + + + + + + + + + + + + + +
col_Acol_Bcol_Ccol_Dcol_Ecol_F
AVG0.250.110.170.230.140.17
+
+

Here's my code:

+
import re
+import pandas as pd
+
+
+with open('test.txt') as file:
+        lines = file.readlines()
+        regex = r'\A(?P<ID>\S+)\s*(?P<COL_A>\S+)\s*(?P<COL_B>\S+)\s*(?P<COL_C>\S+)'
+        data = []
+        
+        for line in lines:
+            m = re.search(regex, line)
+            if m != None:
+                data.append([m.group(1),m.group(2),m.group(3),m.group(4)])
+        
+        df = pd.DataFrame(data)
+        
+df.to_csv('test.csv', index = False)
+
+

My code would result in a strange format like

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
0123
IDcol_Acol_Bcol_C
10.260.110.18
20.270.120.17
30.210.100.15
---------------------------------
AVG0.250.110.17
---------------------------------
IDcol_Dcol_Ecol_F
10.230.180.20
20.240.140.17
30.230.100.13
---------------------------------
AVG0.230.140.17
---------------------------------
+
+

How can I modify my code to achieve my request? Thank you!

","

You can use

+
import re, itertools
+import pandas as pd
+
+data = []
+colnames = []
+avg = []
+start = True
+is_next_avg = False
+id_start_label = ''
+
+with open('test.txt', 'r') as file:
+    for line in file:
+        line = line.strip()
+        if start and line.replace('-', '').strip():
+            id_start_label = line.split()[0]
+            colnames.extend(line.split()[1:])
+            start = False
+        elif '---' in line and not line.replace('-', '').strip():
+            if start:
+                continue
+            is_next_avg = not is_next_avg
+        elif is_next_avg:
+            avg.extend(line.split()[1:])
+            is_next_avg = not is_next_avg
+            start = not start
+        else:
+            data.append(line.split())
+
+colnames.insert(0, id_start_label)
+data = sorted(data, key=lambda x: x[0])
+new_data = []
+for key, g in itertools.groupby(data, key=lambda x: x[0]):
+    entry = [key]
+    entry.extend( [i for x in g for i in x[1:]] )
+    new_data.append(entry)
+
+df = pd.DataFrame(new_data, columns=colnames)
+df2 = pd.DataFrame(avg, columns=['AVG'])
+df2 = df2.transpose()
+df2.columns = df.columns[1:]
+
+

Output:

+
>>> df
+  ID col_A col_B col_C col_D col_E col_F
+0  1  0.26  0.11  0.18  0.23  0.18  0.20
+1  2  0.27  0.12  0.17  0.24  0.14  0.17
+2  3  0.21  0.10  0.15  0.23  0.10  0.13
+
+>>> df2
+    col_A col_B col_C col_D col_E col_F
+AVG  0.25  0.11  0.17  0.23  0.14  0.17
+
",python +"Selenium: ""Unable to find session with ID"" after a few minutes of idling

I started a Docker container with: +docker run -d --shm-size="4g" --hostname selenium_firefox selenium/standalone-firefox

+

In another container with Python:

+
...
+>>> driver = webdriver.Remote(command_executor="http://" +selenium_host+":4444/w
+d/hub", desired_capabilities=DesiredCapabilities.FIREFOX, keep_alive=True)      
+                                                                             
+>>> driver.title                                                                
+''                                                                              
+>>> driver.title                                                                
+Traceback (most recent call last):                                              
+  File "<stdin>", line 1, in <module>                                           
+  File "/usr/local/lib/python3.10/site-packages/selenium/webdriver/remote/webdri
+ver.py", line 447, in title                                                     
+    resp = self.execute(Command.GET_TITLE)                                      
+  File "/usr/local/lib/python3.10/site-packages/selenium/webdriver/remote/webdri
+ver.py", line 424, in execute                                                   
+    self.error_handler.check_response(response)                                 
+  File "/usr/local/lib/python3.10/site-packages/selenium/webdriver/remote/errorh
+andler.py", line 247, in check_response                                         
+    raise exception_class(message, screen, stacktrace)                          
+selenium.common.exceptions.WebDriverException: Message: Unable to execute reques
+t for an existing session: Unable to find session with ID: 5c619451-8361-4ec9-9b
+7e-58b7afac15ff                                                                 
+Build info: version: '4.1.1', revision: 'e8fcc2cecf'                            
+System info: host: 'selenium_firefox', ip: '172.17.0.3', os.name: 'Linux', os.ar
+ch: 'amd64', os.version: '5.4.0-89-generic', java.version: '11.0.13'            
+Driver info: driver.version: unknown
+
+

The first driver.title I ran it immediately after creating the remote webdriver.

+

Then I waited for some time (around 15 minutes) and ran driver.title again, and it seem that the Python console has lost connection to the corresponding browser.

+

Why does this happen and how do I avoid it? It doesn't happen if I don't use a remote webdriver.

","

Option 1: Override Docker Selenium Grid default session timeout

+

From docker/selenium documentation:

+
+

Grid has a default session timeout of 300 seconds, where the session can be on a stale state until it is killed. You can use SE_NODE_SESSION_TIMEOUT to overwrite that value in seconds.

+
+
docker run -d -e SE_NODE_SESSION_TIMEOUT=1000 --shm-size="4g" --hostname selenium_firefox selenium/standalone-firefox
+
+

Option 2: Ping your session once in 60 (any < 300) seconds

+

You may execute some driver command in a loop during the idle time

+
for x in range(15):
+    time.sleep(60)
+    driver.current_url
+
+
+

Reference

+

https://github.com/SeleniumHQ/docker-selenium#grid-url-and-session-timeout

",python +"ImportError: cannot import name '_obtain_input_shape' in keras

When I try to import keras_squeezenet I get this error:

+
Traceback (most recent call last):
+  File "C:/Users/belog/drone_sees/train_model.py", line 3, in <module>
+    from keras_squeezenet import SqueezeNet
+  File "C:\Users\belog\AppData\Local\Programs\Python\Python36\lib\site-packages\keras_squeezenet\__init__.py", line 1, in <module>
+    from keras_squeezenet.squeezenet import SqueezeNet
+  File "C:\Users\belog\AppData\Local\Programs\Python\Python36\lib\site-packages\keras_squeezenet\squeezenet.py", line 1, in <module>
+    from keras.applications.imagenet_utils import _obtain_input_shape
+ImportError: cannot import name '_obtain_input_shape'
+
+

Here is the import code:

+
import tensorflow as tf
+from keras_squeezenet import SqueezeNet
+from keras.optimizers import Adam
+from keras.utils import np_utils
+from keras.layers import Activation, Dropout, Convolution2D, GlobalAveragePooling2D
+from keras.models import Sequential
+
+

How to fix it? (I'm using tensorflow==2.6.2, keras==2.6.0, keras-squeezenet==0.4).

","

Did you tried the new version ? (see : https://github.com/rcmalli/keras-squeezenet)

+

you can install it with :
+pip install git+https://github.com/rcmalli/keras-squeezenet.git

",python +"how to check if value in a DataFrame is a type Decimal

I am writing a data test for some api calls that return a DataFrame with a date type and a type Decimal. I can't find a way to verify the Decimal

+

the DataFrame is returned as 2022-01-18 12:35:00 2856.8430

+

So I have

+
result = ds.DataService.get_recent(5, 24)
+assert not result.empty
+assert ptypes.is_datetime64_any_dtype(result['foo'])
+
+

but if I try

+
assert all(ptypes.is_float_dtype(result[col]) for col in result["foo1"])
+
+ raise KeyError(key) from err
+KeyError: Decimal('2873.6408')
+
","

So given a series like result["foo1"], you can check that with

+
from decimal import Decimal
+
+import pandas as pd
+
+is_decimal: bool = pd.core.dtypes.common.is_dtype_equal(result["foo1"], Decimal)
+
",python +"how does one match EOL (newline) with lark?

I'm using the lark parser with python. I'd like to use EOL as part of the grammar since it is line oriented. I'm getting an error when I try to put the regex in for matching EOL. I see some examples like this:

+
CR : /\r/
+LF : /\n/
+NEWLINE: (CR? LF)+
+
+

but they don't work for me. this is my code:

+
import sys
+import lark
+
+class Parser:
+    grammar = '''
+        start : STRING EOL
+        STRING : /\w+/
+        EOL : /\n/x
+    '''
+
+    parser = lark.Lark(grammar)
+
+    def __init__(self, fname):
+        self.fname = fname
+        self.ast(open(fname))
+
+    def ast(self, fh):
+        tree = self.parser.parse(fh.read())
+        print(tree.pretty())
+
+def main():
+    x = Parser(sys.argv[1])
+
+main()
+
+

and here's the error I get:

+
Traceback (most recent call last):
+  File "./p2.py", line 6, in <module>
+    class Parser:
+  File "./p2.py", line 13, in Parser
+    parser = lark.Lark(grammar)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 413, in __init__
+    self.parser = self._build_parser()
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 456, in _build_parser
+    return parser_class(self.lexer_conf, parser_conf, options=self.options)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 242, in __call__
+    return ParsingFrontend(lexer_conf, parser_conf, options)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 61, in __init__
+    self.parser = create_parser(lexer_conf, parser_conf, options)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 209, in create_earley_parser
+    return f(lexer_conf, parser_conf, options, resolve_ambiguity=resolve_ambiguity, debug=debug, tree_class=tree_class, **extra)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 186, in create_earley_parser__dynamic
+    earley_matcher = EarleyRegexpMatcher(lexer_conf)
+  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 172, in __init__
+    raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
+lark.exceptions.GrammarError: ("Dynamic Earley doesn't allow zero-width regexps", TerminalDef('EOL', '(?x:\n)'))
+
","

I forgot about needing to use raw strings. had to add an "r". the new code looks like:

+
class Parser:
+    grammar = r'''
+        start : STRING EOL
+        STRING : /\w+/
+        EOL : /\n/
+    '''
+
",python +"python: How to read file independent from entry point (both notebook and .py files)

I'm working on a python project that looks like this

+
app
+├── data
+│   └── my_data.csv
+├── utils
+│   └── reader.py
+├── scripts
+│   └── s0.py
+├── notebooks
+│   └── n0.ipynb
+└── main.py
+
+
+

In reader.py:

+
def read_file():
+    with open('./data/my_data.csv'):
+        print('I can read the file !')
+
+
+

I test.py, main.py and n0.ipynb files:

+
from utils.reader import read_file
+read_file()
+
+

To run s0 and main, I use the command: python -m scripts.s0 and python -m main and it works fine.

+

But when I try to run the notebook, it does not. I understnd why (it looks at ./data/my_data.csv but since it's not at root level, it does not work)

+

Is there a way to make file reading independent from entry point in python ?

+

In javascript for instance, it would be esay to do, I would use path ../data/my_data.csv in reader file and it would work independently from the file location the function is called.

","

You can find the path of the current file with the __file__ variable (also see this answer).
+From that, you can construct the required path. In reader.py:

+
from pathlib import Path
+
+APPDIR = Path(__file__).parent.parent.resolve()
+
+def read_file()
+    with open(APPDIR / "data" / "my_data.csv"):
+        print('I can read the file !')
+
",python +"How to plot number of events occurring at each hour of the day in a pandas dataframe?

Say I have the following data:

+
import pandas as pd
+data = {'time':[7, 1, 2, 7, 2, 2, 1, 2, 7, 3, 5], 'event':['a', 'b', 'a', 'a', 'b', 'a', 'a', 'b', 'b', 'b', 'a']}
+df = pd.DataFrame(data)
+
+

I want to display how many events of each type occurred at each hour of the day. However, there are only 5 unique times present in the "time" column of the dataset.

+

Plotting a histogram with bins=24 works when all the 24 unique hours of the day (1 to 24) are present in the dataset. But if only a few hours of the day are present, histogram doesn't do this task.

+

For example, with the above data, the code df.hist() produces this chart:

+

+

It is unclear where the x-axis ticks are located exactly - what I want is, that the 5 spikes in this chart should be located at x = 1, 2, 3, 5 and 7, and there should be no spikes present at x = 4, 6 and 8 through 24.

+

With df.time.hist(bins=24), the following chart is produced:

+

+

Here, it is a bit better as we can see that at least the first 4 spikes are located at x = 1, 2, 3, and 5, with x = 4 and x = 6 being left blank. However, at x=7, the spike is drawn to the left of the grid lines, while the other 4 spikes are drawn to the right of the grid lines. Also, this doesn't display the empty spikes at x = 8 through 24.

+

So, how do I do it?

","

Try this:

+
import pandas as pd
+import matplotlib.pyplot as plt
+import numpy as np
+data = {'time':[7, 1, 2, 7, 2, 2, 1, 2, 7, 3, 5], 'event':['a', 'b', 'a', 'a', 'b', 'a', 'a', 'b', 'b', 'b', 'a']}
+df = pd.DataFrame(data)
+fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(16, 10))
+
+df.hist(ax=axes, bins=range(24))
+
+# offset the xticks
+axes.set_xticks(np.arange(24) + .5)
+
+# name the label accordingly
+axes.set_xticklabels(range(24))
+
",python +"Python Overridden __add__ Doesn't Work for a += b

I've been working on a Vector object class to allow me to solve math problems quickly using Python.

+

For Example: +If we set vector = Vector(1, 2, 3) and we run vector *= 2, then vector will be equal to <2, 4, 6>

+

The Issue: Whenever I run vector += 2, it errors saying

+
Traceback (most recent call last):
+  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 149, in <module>
+    main()
+  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 139, in main
+    vector += 2
+TypeError: 'int' object is not iterable
+
+Process finished with exit code 1
+
+

Here is my Vector class

+
class Vector(list):
+    def __init__(self, *args):
+        super().__init__()
+        for arg in args:
+            self.append(arg)
+
+    def __mul__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row * other for row in self])
+
+    def __truediv__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row / other for row in self])
+
+    def __add__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        print(type(other))
+        return Vector(*[row + other for row in self])
+
+    def __sub__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row - other for row in self])
+
+    def __str__(self):
+        return "<" + ", ".join([str(e) for e in self]) + ">"
+
+

Here is my main function

+
def main():
+    vector = Vector(1, 2, 3)
+    vector *= 2
+    print(vector)
+    vector += 2
+    print(vector)
+
+

What I've done to find the solution:

+
    +
  • I've tried to do vector = vector + 2 and that works, but I would +rather understand why it's not working and be able to fix it.
  • +
  • I've tried googling how operator overloading works in Python
  • +
  • I've tried looking through operator overloading threads on StackOverflow, but I don't see any that answer my question. They're all about how a = a + b, not a += b.
  • +
  • I've tried using iadd, but it doesn't work.
  • +
","

Just add the line __iadd__ = __add__:

+
class Vector(list):
+    def __init__(self, *args):
+        super().__init__()
+        for arg in args:
+            self.append(arg)
+
+    def __mul__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row * other for row in self])
+
+    def __truediv__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row / other for row in self])
+
+    def __add__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        print(type(other))
+        return Vector(*[row + other for row in self])
+
+    __iadd__ = __add__
+
+    def __sub__(self, other):
+        assert isinstance(other, float) or isinstance(other, int)
+        return Vector(*[row - other for row in self])
+
+    def __str__(self):
+        return "<" + ", ".join([str(e) for e in self]) + ">"
+
+
+vector = Vector(1, 2, 3)
+vector *= 2
+print(vector)
+vector += 2
+print(vector)
+
+

Prints:

+
<2, 4, 6>
+<class 'int'>
+<4, 6, 8>
+
",python +"Selection of columns

I work with Pandas dataframe.I want to aggregate data by one column and after that to summarize other columns.You can see example below:

+
    data = {'name': ['Company1', 'Company2', 'Company1', 'Company2', 'Company5'], 
+            'income': [0, 180395, 4543168, 7543168, 73], 
+            'turnover': [4, 24, 31, 2, 3]}
+    df = pd.DataFrame(data, columns = ['name', 'income', 'turnover'])
+    df
+
+INCOME_GROUPED = df.groupby(['name']).agg({'income':sum,'turnover':sum})
+
+

So this code above work well and give good result. Now next step is selection. I want to select only to columns from INCOME_GROUPED dataframe.

+
INCOME_SELECT =  INCOME_GROUPED[['name','income']]
+
+

But after execution this line of code I got this error:

+
"None of [Index(['name', 'income'], dtype='object')] are in the [columns]"
+
+

So can anybody help me how to solve this problem ?

","

You need to call reset_index() after agg():

+
INCOME_GROUPED = df.groupby(['name']).agg({'income':sum,'turnover':sum}).reset_index()
+#                                                                       ^^^^^^^^^^^^^^ add this
+
+

Output:

+
>>> INCOME_GROUPED[['name', 'income']]
+       name   income
+0  Company1  4543168
+1  Company2  7723563
+2  Company5       73
+
",python +"python: write a dataframe groupby to a file

I have a file with the following that I am reading with python

+
Item Master Primary Spec/Common Information/Contract Number||Contract Master Primary Spec/cage code
+8AND3||SP47W117D0015
+8AND3||SP47W117D0015
+8AND3||SP47W117D0015
+8AND3||SP47W117D0015
+8AND3||SP47W117D0015
+8C1C2||N6247820D2401
+8C1C2||N6247820D2401
+8C1C2||N6247820D2401
+
+

I am trying to get a count of the number of contracts. The below code seems to work when I print it (although the header columns are reversed for some reason), but not when I try to output it to a file.

+
import pandas as pd
+
+fname="mdm.export.item.master.delta.1335.20220120011500_125_125.csv"
+fdir="./data/"
+df = pd.read_csv(fdir+fname, sep='\|\|', keep_default_na=False, engine='python')
+
+uniqContract=df.groupby(['Item Master Primary Spec/Common Information/Contract Number']).count()
+print(uniqContract)
+
+file = open("testfile.txt","w") 
+for items in uniqContract:
+    file.writelines(items+'\n')
+file.close() 
+
+

This is the print output

+
(base) PS D:\02-MyLocalFiles> python .\helloworld.py
+Contract Master Primary Spec/cage code Item Master Primary Spec/Common Information/Con...
+8AND3                                                                                    5
+8C1C2                                                                                    3
+(base) PS D:\02-MyLocalFiles\python\backlog_report>
+
+

But this is the output to the file

+
Contract Master Primary Spec/cage code
+
+

What am I doing wrong?

","
uniqContract=df.groupby(['Item Master Primary Spec/Common Information/Contract Number']).count().reset_index()
+uniqContract.to_csv('testfile.txt', delimiter='\t')
+
+

You can call .reset_index() on your groupby count aggregation, then write that to a (text) csv file directly. You can specify the delimiter (this is tabs).

",python +"Implement mask for anchor-negative in list of triplets

I have a generator in producing my TensorFlow data, as triplets (anchor, positive, negative), in batches. Each batch is a list of such triplets, making up the list labels. Using code from Moindrot's blog on triplet loss we get a mask for positives and negatives: With

+
labels_equal = tf.equal(tf.expand_dims(labels, 0), tf.expand_dims(labels, 1))
+mask = tf.logical_not(labels_equal)
+
+

we get a mask of negatives (non-equal labels). If I have labels=[1,1,2,3,3,4] the mask will be:

+
[[ F F T T T T ],
+ [ F F T T T T ],
+ [ T T F T T T ],
+ [ T T T F F T ],
+ [ T T T F F T ],
+ [ T T T T T F ]]
+
+

The labels are set up such that in groups of 3 they form anchor, positive and negative (triplet).

+

I'm trying to implement a negative mask for balanced triplets. I.e. a mask where only the negative to its anchor is True for each line. How do I find this negative mask such that only the anchor-negative entries percolate through?

+

Expected output for labels=[1,1,2,3,3,4]:

+
[[ F F T F F F ],
+ [ F F F F F F ],
+ [ T F F F F F ],
+ [ F F F F F T ],
+ [ F F F F F F ],
+ [ F F F T F F ]]
+
+
+

Notes:

+
    +
  • I have tried to use tfa's triplet loss, but it's not balanced (bad for testing accuracy, recall, etc.).
  • +
  • Labels have been relabeled, such that the labels of each triplet is batch-unique and won't match other triplets in the batch.
  • +
","

If you really only want anchor-negative True in the negative mask, you can accomplish this with a mix of tf.tile, tf.linalg.band_part and tf.transpose:

+
labels_equal = tf.equal(tf.expand_dims(labels, 0), tf.expand_dims(labels, 1))
+mask = tf.logical_not(labels_equal)
+triplet_mask = tf.tile(
+    [
+        [False, False, True],
+        [False, False, False],
+        [False, False, False],
+    ],
+    multiples=[d // 3 for d in mask.shape],
+)
+triplet_mask = tf.linalg.band_part(triplet_mask, 0, 2)
+triplet_mask = triplet_mask | tf.transpose(triplet_mask)
+
+

I would suggest, however, you rather change the model to accept a list of triplets. It simplifies both training and testing.

",python +"Selenium Python >> get a value of an attribute from the console log of the webpage

How do we get a value of an attribute from the console log of the webpage?enter image description here For example in the screenshot (link above) I have highlighted the following:

+

page_renderer: "articleRenderer"

+

When the webpage loads I would like to verify if the value for page_renderer is "articleRenderer" or if it is "articleRenderer2".

+

Could you please let me know? Thanks.

","

Based on your screenshot:

+
page_renderer_value = driver.execute_script('return rtech.visitor.page_renderer')
+
",python +"Iterating within groups until a column changes in pandas

I have the following input df:

+
    domain      ip      timestamp
+0   Google      101     2020-04-01 23:01:41
+1   Google      101     2020-04-01 23:01:59
+2   Google      101     2020-04-02 12:01:41
+3   Facebook    101     2020-04-02 13:11:33
+4   Facebook    101     2020-04-02 13:11:35
+5   Youtube     103     2020-04-21 13:01:41
+6   Youtube     103     2020-04-21 13:11:46
+7   Youtube     103     2020-04-22 01:01:01
+8   Google      103     2020-04-22 02:11:23
+9   Facebook    103     2020-04-23 14:11:13
+10  Youtube     103     2020-04-23 14:11:55
+
+

How can I get this output? Where domain_num is an iterator that increases everytime a domain switches within an IP.

+

+    domain      ip      timestamp             domain_num
+0   Google      101     2020-04-01 23:01:41   1
+1   Google      101     2020-04-01 23:01:59   1
+2   Google      101     2020-04-02 12:01:41   1
+3   Facebook    101     2020-04-02 13:11:33   2
+4   Facebook    101     2020-04-02 13:11:35   2
+5   Youtube     103     2020-04-21 13:01:41   1
+6   Youtube     103     2020-04-21 13:11:46   1
+7   Youtube     103     2020-04-22 01:01:01   1
+8   Google      103     2020-04-22 02:11:23   2
+9   Facebook    103     2020-04-23 14:11:13   3
+10  Youtube     103     2020-04-23 14:11:55   4
+
+

I tried something like this which gets the counts but I need to group it by ip

+
df['domain'].ne(df['domain'].shift()).cumsum()
+
+

This code below errors out

+
df.groupby('ip').apply(lambda x : x[x.domain.ne(x.domain.shift().cumsum())])
+
+

Data

+
import pandas as pd
+
+data = {'domain':['Google', 'Google', 'Google', 'Facebook', 'Facebook', 'Youtube', 'Youtube', 'Youtube', 'Google', 'Facebook', 'Youtube'],
+        'ip':[101, 101, 101, 101, 101, 103, 103, 103, 103, 103, 103],
+        'timestamp' : ['2020-04-01 23:01:41', '2020-04-01 23:01:59', '2020-04-02 12:01:41', '2020-04-02 13:11:33',
+        '2020-04-02 13:11:35', '2020-04-21 13:01:41', '2020-04-21 13:11:46', 
+                       '2020-04-22 01:01:01', '2020-04-22 02:11:23','2020-04-23 14:11:13', '2020-04-23 14:11:55' ]}
+
+df = pd.DataFrame(data)
+df['timestamp']= pd.to_datetime(df['timestamp'])
+
","

Assume your dataframe is sorted by timestamp column:

+
inc_domain_num = lambda x: x.ne(x.shift()).cumsum()
+df['domain_num'] = df.groupby('ip')['domain'].apply(inc_domain_num)
+print(df)
+
+# Output
+      domain   ip           timestamp  domain_num
+0     Google  101 2020-04-01 23:01:41           1
+1     Google  101 2020-04-01 23:01:59           1
+2     Google  101 2020-04-02 12:01:41           1
+3   Facebook  101 2020-04-02 13:11:33           2
+4   Facebook  101 2020-04-02 13:11:35           2
+5    Youtube  103 2020-04-21 13:01:41           1
+6    Youtube  103 2020-04-21 13:11:46           1
+7    Youtube  103 2020-04-22 01:01:01           1
+8     Google  103 2020-04-22 02:11:23           2
+9   Facebook  103 2020-04-23 14:11:13           3
+10   Youtube  103 2020-04-23 14:11:55           4
+
",python +"RPM installation Trino throws python dependency

I'm trying to install Trino using RPM on Red Hat Enterprise Linux distribution. I install the Trino dependencies using the following commands:

+
$ sudo yum update -y
+$ sudo yum install -y java-11-openjdk.x86_64 python3
+$ sudo alternatives --set python /usr/bin/python3
+
+

Then I try to install Trino from archive in single-node mode. This however gives a dependency error:

+
$ sudo rpm -i trino-server-rpm-368.rpm
+error: Failed dependencies:
+    python >= 2.4 is needed by trino-server-rpm-0:368-1.noarch
+
+

This error doesn't make sense to me given that this dependency is actually satisfied when checking my python version:

+
$ python -V
+Python 3.6.8
+
","

An answers has been provided by @hashhar on this Github Issue if you actually have the correct dependencies installed:

+
$ sudo rpm -i --nodeps trino-server-rpm-368.rpm
+
",python +"Sorting Algorithm output at end of pass 3

Given the following initially unsorted list:

+

[77, 101, 40, 43, 81, 129, 85, 144]

+

Which sorting algorithm produces the following list at the end of Pass Number 3? Is it Bubble, Insertion or Selection?

+

[40, 43, 77, 81, 85, 101, 129, 144]

+

Can someone give me a clue on how I can solve this please.

","

Insertion sort:

+
def insertion_sort(array):
+    for i in range(1, len(array)):
+        key_item = array[i]
+        j = i - 1
+        while j >= 0 and array[j] > key_item:
+            array[j + 1] = array[j]
+            j -= 1
+        array[j + 1] = key_item
+        print("Step",i,":",array)
+    return array
+
+data=[77, 101, 40, 43, 81, 129, 85, 144]
+insertion_sort(data)
+
+

Output:

+
Step 1 : [77, 101, 40, 43, 81, 129, 85, 144]
+Step 2 : [40, 77, 101, 43, 81, 129, 85, 144]
+Step 3 : [40, 43, 77, 101, 81, 129, 85, 144]
+Step 4 : [40, 43, 77, 81, 101, 129, 85, 144]
+Step 5 : [40, 43, 77, 81, 101, 129, 85, 144]
+Step 6 : [40, 43, 77, 81, 85, 101, 129, 144]
+Step 7 : [40, 43, 77, 81, 85, 101, 129, 144]
+
+

Bubble sort:

+
def bubble_sort(array):
+    n = len(array)
+    for i in range(n):
+        already_sorted = True
+        for j in range(n - i - 1):
+            if array[j] > array[j + 1]:
+                array[j], array[j + 1] = array[j + 1], array[j]
+                already_sorted = False
+        if already_sorted:
+            break
+        print("Step:",n-j-1)
+        print(array)
+    return array
+
+data = [77, 101, 40, 43, 81, 129, 85, 144]
+bubble_sort(data)
+
+

Output:

+
Step: 1
+[77, 40, 43, 81, 101, 85, 129, 144]
+Step: 2
+[40, 43, 77, 81, 85, 101, 129, 144]
+
+

Selection Sort:

+
def selectionSort(array, size):
+    for step in range(size):
+        min_idx = step
+
+        for i in range(step + 1, size):
+            if array[i] < array[min_idx]:
+                min_idx = i
+        (array[step], array[min_idx]) = (array[min_idx], array[step])
+        print("step",step+1,":",end="")
+
+        print(array)
+
+data = [77, 101, 40, 43, 81, 129, 85, 144]
+size = len(data)
+selectionSort(data, size)
+
+

Output:

+
step 1 :[40, 101, 77, 43, 81, 129, 85, 144]
+step 2 :[40, 43, 77, 101, 81, 129, 85, 144]
+step 3 :[40, 43, 77, 101, 81, 129, 85, 144]
+step 4 :[40, 43, 77, 81, 101, 129, 85, 144]
+step 5 :[40, 43, 77, 81, 85, 129, 101, 144]
+step 6 :[40, 43, 77, 81, 85, 101, 129, 144]
+step 7 :[40, 43, 77, 81, 85, 101, 129, 144]
+step 8 :[40, 43, 77, 81, 85, 101, 129, 144]
+
+

You can also get more guidelines from the link below how to run algorithms: +https://realpython.com/sorting-algorithms-python/

",python +"How can I convert a gpa calculator to use upper and lower case grade arguments?

I am creating a GPA calculator which takes in 4 grades and gives the GPA. I want it to be able to use upper case letters 'A' and lower case letters 'a' and so on through 'F' 'f'. Right now it will only use upper case letters. How can I convert it to use both without changing the dictionary?

+
import sys
+def gpa_calculator(grade1, grade2, grade3, grade4):
+    points = 0
+    i = 0
+    grade_c ={'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0,
+      'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00}
+
+    if grades != []:
+        for grade in grades:
+            points += grade_c[grade]
+        gpa = points / len(grades)
+        return gpa
+    else:
+        return None
+
+    grade1 = sys.argv[1]
+    grade2 = sys.argv[2]
+    grade3 = sys.argv[3]
+    grade4 = sys.argv[4]
+
+    grades = grade1, grade2, grade3, grade4
+    grades = gpa_calculator(grade1, grade2, grade3, grade4)
+    print('My GPA is',(grades))
+
","

You have at least two options

+

1 Add the "lower case" version of the keys to the dictionary as the dictionary key is case-sensitive. Thereby creating a larger dictionary and somewhat unnecessary repeated code.

+
grade_c = {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00, 'a':4.0, 'a-':3.66, 'b+':3.33, 'b':3.0, 'b-':2.66,'c+':2.33,'c':2.0,'c-':1.66,'d+':1.33,'d':1.00,'d-':.66,'f':0.00 }
+
+
    +
  1. Keep your dictionary as is and take the passed in command line arguments and use the str.upper() method to convert and store them as uppercase. The user can pass in either any case and it will be converted to uppercase for handling by your current dictionary and code.
  2. +
+
    grade1 = sys.argv[1].upper()
+    grade2 = sys.argv[2].upper()
+    grade3 = sys.argv[3].upper()
+    grade4 = sys.argv[4].upper() 
+
",python +"Python: How to dynamically set inner class class variable

I am working with peewee and SQLite on a project. I have two files:

+

file1.py

+
if __name__ == '__main__':
+    db = Thing()
+
+

file2.py

+
DB_FILENAME = 'db_name.db'
+DB_FILE_PATH = f'/tmp/{DB_FILENAME}'
+db = SqliteDatabase(DB_FILE_PATH)
+
+class Thing(Model):
+    field1 = CharField(primary_key=True)
+    field2 = CharField()
+
+    class Meta:
+        database = db
+
+

The Thing class needs to be able to write into several different databases so I need a clean way of making DB_FILENAME configurable so that the inner class database field will be initialized to the appropriate name.

+

The inner Meta class appears to be required and this setup is what is referenced in the documentation (the db declared globally). +Additional Note: This code is being run in AWS Lambda.

+

EDIT: Working solution in fact did not work.

","

Write a function that creates the class, and call it with the environment variable as an argument.

+
# file2.py
+
+def make_model(db_file_name):
+    class Thing(Model):
+        field1 = CharField(primary_key=True)
+        field2 = CharField()
+
+        class Meta:
+            database = SqliteDatabase(f'/tmp/{db_file_name}')
+
+    return Thing
+
+
+# script
+
+from file2 import make_model
+
+if __name__ == '__main__':
+    db = make_model(f'db_name_{os.getenv("SUFFIX")}.db')
+
",python +"Python Selenium Do-While Loop

I am trying to complete a do-while loop with the below code. We are waiting for a report to process, and it only shows on the webpage once completed and after clicking the retrieve button. The code,

+
# Go to list and click retrieve
+driver.find_element(By.CSS_SELECTOR, "#j_idt40Lbl").click()
+time.sleep(20) # takes a while for their side to run
+retrieve = driver.find_element_by_css_selector("#tab_reportList\:listPgFrm\:listPgRetrBtn")
+retrieve.click() ### Do this action ###
+time.sleep(5)
+retrieve.click()
+time.sleep(5)
+retrieve.click()
+time.sleep(3)
+
+# Click report file
+WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#tab_reportList\:listPgFrm\:listDataTable_0\:0\:reportLink"))).click() 
+### Until this is visible ###
+
","

In case the element finally becoming visible is not initially presents on the page your code can be something like this:

+
driver.find_element(By.CSS_SELECTOR, "#j_idt40Lbl").click()
+time.sleep(20)
+while True:
+    driver.find_element_by_css_selector("#tab_reportList\:listPgFrm\:listPgRetrBtn").click()
+    time.sleep(5)
+    if driver.find_elements_by_css_selector("#tab_reportList\:listPgFrm\:listDataTable_0\:0\:reportLink"):
+        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#tab_reportList\:listPgFrm\:listDataTable_0\:0\:reportLink"))).click()
+        break
+
+

Hardcoded sleeps of 5 and 20 seconds are not looking good. If possibly they should be changed by Expected Conditions explicit waits

",python +"Pandas dataframe custom columns and rows

I have been stuck here I don't know why but this is the code:

+
import pandas as pd
+import random as R
+n = int(input("How many columns : "))
+list1 = []
+list2=[]
+nilaiRand = R.randint(1,30)
+for i in range(0,n):
+    print("Column-",i+1 ,sep="",end=": ")
+    kolom = input()
+    list1.append(kolom)
+print(list1)
+ind = int(input("Total random number : "))
+inde = range(1,ind+1)
+list2.append(nilaiRand)
+print(list2)
+dataframe = pd.DataFrame(list1,list2)
+
+

'list1' is the name of the columns, 'list2' is the random number which is the rows.

+

I need to input how many columns you want to make,and it will request the name of each columns and listed in 'list1'. and I want to make the rows as much as ind = int(input("Total random number : ")) and the fill of the line is random number nilaiRand = R.randint(1,30)

+

The output should be like

+
How many columns : 3
+Column-1 : Eli
+Column-2 :Chick
+Column-3 :You
+Total random number : 4
+
+Result 
+
+   Eli   Chick   You
+1   12    22       3
+2   21    12       11
+3   4     11       21
+4   13    14       5
+
+

Any solution?

","

This should do the trick:

+
import pandas as pd
+import random as R
+n = int(input("How much columns: "))
+dict1 = {}
+for i in range(0,n):
+    column = input()
+    dict1[column] = []
+ind = int(input("Number of rows: "))
+for column in dict1.keys():
+    for _ in range(ind):
+        dict1[column].append(R.randint(1,30))
+dataframe = pd.DataFrame(dict1)
+
+

Input:

+
    +
  • 5
  • +
  • A
  • +
  • B
  • +
  • C
  • +
  • D
  • +
  • E
  • +
  • 8
  • +
+

Output:

+
    A   B   C   D   E
+0   21  1   6   1   1
+1   21  18  17  3   5
+2   25  3   6   17  23
+3   5   8   16  25  23
+4   6   16  22  30  27
+5   25  17  14  11  13
+6   13  26  30  24  11
+7   4   21  29  14  2
+
+

However, please up your question-writing game. Do not upload images of code/errors when asking a question. Also give a clear desired output and tell us at what point in your code you stumble unto problems.

+

Update

+

If you want to start your index at 1, try:

+
dataframe = pd.DataFrame(dict1, index=range(1, ind+1))
+
",python +"How to convert a nested list of keys to a dummies-like dataframe

How to convert following list to a pandas dataframe?

+
my_list = [["A","B","C"],["A","B","D"]]
+
+

And as an output I would like to have a dataframe like:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
IndexABCD
11110
21101
+
","

You can craft Series and concatenate them:

+
my_list = [["A","B","C"],["A","B","D"]]
+
+df = (pd.concat([pd.Series(1, index=l, name=i+1)
+                for i,l in enumerate(my_list)], axis=1)
+        .T
+        .fillna(0, downcast='infer') # optional
+      )
+
+

or with get_dummies:

+
df = pd.get_dummies(pd.DataFrame(my_list))
+df = df.groupby(df.columns.str.split('_', 1).str[-1], axis=1).max()
+
+

output:

+
   A  B  C  D
+1  1  1  1  0
+2  1  1  0  1
+
",python +"Discord py Global Mute command

So, I am trying to create a global mute / unmute command which would be used to mute a specific user in multiple servers. This command is being made only for a community that owns multiple servers so it would be useful to mute someone across all servers where the bot is running.

+

I based this mute command on a global ban command which is able to ban a user from multiple servers where the bot is running.

+

The first command "gban" in the below code runs beautifully, whenever I ban a user in one server, it bans them from any other servers the bot is running in. I am trying to see how I can use this same setup to create a global mute command. the command "gmute" is what I have created so far. It works, but it only mutes the user in the server the command is ran in and DOES NOT mute the user in all the servers that the bot is running in. I am trying to make it to where "gmute" is a global command and applies to all servers that the bot is running in.

+
# global ban command
+
+async def gban(ctx, user: discord.User):
+  for guild in client.guilds:
+    await guild.ban(user)
+    embed = discord.Embed(title="**Global Ban:**", description=f"{user} Has been globally banned from all servers!:no_pedestrians:",colour=discord.Colour.light_gray())
+    await ctx.send(embed = embed)
+
+
+# Global Mute Command
+
+@client.command()
+@commands.has_permissions(manage_messages=True)
+async def gmute(ctx, user: discord.User):
+    for guild in client.guilds:
+        mutedRole = discord.utils.get(guild.roles, name="Coventry")
+
+    if not mutedRole:
+        mutedRole = await ctx.guild.create_role(name="Coventry")
+
+        for guild in client.guilds:
+            await guild.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
+    embed = discord.Embed(title="**Global Mute:**", description=f"**{user} has been globablly muted frm all servers! :zipper_mouth:**", colour=discord.Colour.light_gray())
+    await ctx.send(embed=embed)
+    await user.add_roles(mutedRole)
+    await user.send(f"**you have been globally muted!**") ```
+
","

you have to add_roles inside the loop.
+Your indentation is wrong. the if not mutedRole: part should be inside the loop too.
+You are creating a new mute role in ctx.guild (the guild that the command was done in) and not in guild (the guild you got from the loop)
+Also, if you create a new mute role, you'd be setting it's permissions only in the guild the role is in, not in all the servers. Instead of doing 2 api calls (create_role and set_permissions), you can just use the permissions keyword argument in create_role. So instead of

+
mutedRole = await ctx.guild.create_role(name="Coventry")
+
+for guild in client.guilds:
+    await guild.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
+
+

You'd do

+
mutedRole = await ctx.guild.create_role(name="Coventry", permissions=discord.Permissions(speak=False, send_messages=False, read_message_history=True, read_messages=False))
+
+

Your final code will be

+
@client.command()
+@commands.has_permissions(manage_messages=True)
+async def gmute(ctx, user: discord.User):
+    for guild in client.guilds:
+        mutedRole = discord.utils.get(guild.roles, name="Coventry")
+
+        if not mutedRole:
+            mutedRole = await guild.create_role(name="Coventry", permissions=discord.Permissions(speak=False, send_messages=False, read_message_history=True, read_messages=False))
+
+        member = guild.get_member(user.id)
+        await member.add_roles(mutedRole)
+
+    embed = discord.Embed(title="**Global Mute:**", description=f"**{user} has been globablly muted frm all servers! :zipper_mouth:**", colour=discord.Colour.light_gray())
+    await ctx.send(embed=embed)
+    await user.send(f"**you have been globally muted!**")
+
",python +"find pairs of numbers where cube is equal to square

We are given a number N and we have to find pairs i and j where i^3=j^2

+

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27) +basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

+

the constraint is

+
    +
  • 1<=N<10^6
  • +
  • 1<=i,j<N
  • +
+

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

+
def get_pair(N):
+    for i in range(1,N):
+        for j in range(1,N):
+            if i*i*i==j*j:
+                print(i,j)
+N=50
+get_pair(N)
+
+

what will be an optimal way to solve this problem with a better time complexity?

","

Since you're working with integers, if there exists some number M = i^3 = j^2 for i and j between 1 and N, then that means there exists a k such that M = k^6. To find i and j, simply compare the representations of M:

+

(1) M = k^6 = i^3 = (k^2)^3 therefore i = k^2

+

(2) M = k^6 = j^2 = (k^3)^2 therefore j = k^3

+

Since j is always greater than or equal to i, you only need to check if 1 < k^3 < N. In other words, k should be less than the cube root of N.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
kM = k^6i = k^2j = k^3
26448
3729927
44,0961664
515,62525125
646,65636216
............
978.329x10^119409912,673
988.858x10^119604941,192
999.415x10^119801970,299
+
+

Note that 100 isn't a valid candidate for k because that would make j less than or equal to N instead of strictly less than N (if we're going with N = 10^6).

+

So to get the list of tuples that satisfy your problem, find the values of k such that 1 < k^3 < N and return its square and cube in a tuple.

+
import math
+from typing import List, Tuple
+
+N: int = 10**6
+pairs: List[Tuple[int, int]] = [(k * k, k * k * k) for k in range(2, math.ceil(N**(1 / 3)))]
+print(pairs)
+
+

This is a list comprehension, a shorthand for a for-loop.

+

I'm basically asking Python to generate a list of tuples over an index k that falls in the range defined as range(2, math.ceil(N**(1 / 3)). That range is exactly the first column of the table above.

+

Then, for every k in that range I make a tuple of which the first item is k^2 and the second item is k^3, just like the last two columns of the table.

+

Also threw in the typing library in there for good measure. Clear code is good code, even for something as small as this. Python can figure out that pairs is a list of tuples without anyone telling it, but this way I've explicitly enforced that variable to be a list of tuples to avoid any confusion when someone tries to give it a different value or isn't sure what the variable contains.

",python +"Can't update plotly go.Table column order and cell color using dropdown buttons

I have two pandas dataframes, scores containing a set of scores I would like to display in a table, and colours mapping a set of colours I would like the cells in the table to be. Both share the same column headers and index.

+

I am trying to generate a dropdown menu for a table created in plotly using go.Table. Without dropdown options I am able to set up a table with cells coloured according to their value in the following way:

+
    table = go.Figure(data=[go.Table(
+    header=dict(values= scores_cols,
+                fill_color='paleturquoise',
+                align='center'),
+    cells=dict(values= [scores[x] for x in scores_cols],
+            fill_color=[colours[x] for x in scores_cols],
+            align='center'))
+            ])
+
+

In order to add dropdown buttons to sort columns and their corresponding cell colours I am using the following:

+
buttons = []
+
+for score in scores_cols:
+    scores = scores.sort_values(by = [score])
+    colours = colours.reindex(scores.index)
+    buttons.append(dict(
+           label = score,
+           method = 'restyle',
+           args = [
+                    {"cells": 
+                        {"values": [scores[x] for x in scores_cols],
+                        "fill_color": [colours[x] for x in scores_cols]},
+                    }]))
+table.update_layout(
+    updatemenus=[
+        dict(
+            buttons=buttons,
+            direction="down",
+            pad={"r": 10, "t": 10},
+            showactive=True,
+            x = 0.01,
+            y = 1.3,
+            xanchor="left",
+            yanchor="top")
+            ])
+
+

The colour mapping works for the initial table, however when a dropdown button is clicked, the table is updated to reflect the new row ordering according to the selected column, but no colour mapping is present at all. Any advice with this would be great as I am running out of ideas !

","

Found the answer to this. When updating the fill colour, a dict of params for the fill should be passed with fill as one of them, rather than trying to directly assign fill_color:

+
    buttons.append(dict(
+            label = score,
+            method = 'restyle',
+            args = [
+                {"cells": {
+                    "values": [sorted_scores[x] for x in displayed_scores_cols], 
+                    "fill": dict(color = [sorted_colours[x] for x in displayed_scores_cols])}}]))
+
",python +"Concatenate pyton tuples in numba

I'm looking to fill up an arrays of zeros with numbers taken from some tuples, easy as that.

+

Now normally this is not a problem even when the tuples are not the same length (witch is the point here). but it seems it wont compile and I cannot figure out a solution.

+
from numba import jit    
+
+def cant_jit(ls):
+
+    # Array total lenth
+    tl = 6
+    # Type
+    typ = np.int64
+
+    # Array to modify and return
+    start = np.zeros((len(ls), tl), dtype=typ)
+
+    for i in range(len(ls)):
+
+        a = np.array((ls[i]), dtype=typ)
+        z = np.zeros((tl - len(ls[i]),), dtype=typ)
+        c = np.concatenate((a, z))
+        start[i] = c
+
+    return start
+
+# Uneven tuples would be no problem in vanilla
+cant_jit(((2, 4), (6, 8, 4)))
+
+
+jt = jit(cant_jit)    
+# working fine
+jt(((2, 4), (6, 8)))
+# non working
+jt(((2, 4), (6, 8, 4)))
+
+

Within the error.

+

getitem(Tuple(UniTuple(int64 x 3), UniTuple(int64 x 2)), int64) +There are 22 candidate implementations: +- Of which 22 did not match due to: +Overload of function 'getitem': File: : Line N/A. +With argument(s): '(Tuple(UniTuple(int64 x 3), UniTuple(int64 x 2)), int64)': +No match.

+

I tried some things here to no success. Does someone know a way around this so the function can be compiled and still do it's thing ?

","

This isn't possible as far as I can tell, numba documentation tells us that nested tuples that aren't of equal length aren't legal unless you use forceobj=True. You can't even unpack *args which is frustrating. You will always receive that warning/error:

+

Just add that argument to jit() like this:

+

+
+
from numba import jit    
+import numpy as np
+
+def cant_jit(ls):
+
+    # Array total lenth
+    tl = 6
+    # Type
+    typ = np.int64
+
+    # Array to modify and return
+    start = np.zeros((len(ls), tl), dtype=typ)
+
+    for i in range(len(ls)):
+
+        a = np.array((ls[i]), dtype=typ)
+        z = np.zeros((tl - len(ls[i]),), dtype=typ)
+        c = np.concatenate((a, z))
+        start[i] = c
+
+    return start
+
+# Uneven tuples would be no problem in vanilla
+cant_jit(((2, 4), (6, 8, 4)))
+
+
+jt = jit(cant_jit, forceobj=True)    
+# working fine
+jt(((2, 4), (6, 8)))
+# now working
+jt(((2, 4), (6, 8, 4)))
+
+
+

+

This works but it's kind of pointless and you may as well use core python.

",python +"Replace each line containing a specific word from the first file with the line from the second file

I have two txt files, the first one contains duplicated word "PACKAGES", i want to replace each "PACKAGES" word with a line from file 2

+

Ex of file 1:

+
NEW FUSTAT TOURS
+City
+USA
+Address
+napolean
+PACKAGES
+Test TOURS
+City
+UK
+Address
+napolean
+PACKAGES
+
+

Ex of file 2:

+
First Company
+Second Company
+
+

Expected Output:

+
NEW FUSTAT TOURS
+City
+USA
+Address
+napolean
+First Company
+Test TOURS
+City
+UK
+Address
+napolean
+Second Company
+
+

I tried:

+
with open("file1.txt", encoding="utf-8") as first, open("file2.txt", encoding="utf-8") as second:
+        first_file = first.read()
+        second_file = second.readline()
+        print(first_file.replace('PACKAGES', second_file))
+
+

Result:

+
NEW FUSTAT TOURS
+City
+USA
+Addres
+napolean
+Phone Number
+************
+Email
+***************
+First Company
+Test TOURS
+City
+UK
+Addres
+napolean
+Phone Number
+************
+Email
+***************
+First Company
+
+

Any kind of help please?

","

Here's one way you could do it:

+
with open('file1.txt', encoding='utf-8') as f1:
+    with open('file2.txt', encoding='utf-8') as f2:
+        f2lines = iter(f2.readlines())
+        for f1line in f1:
+            if f1line.startswith('PACKAGES'):
+                print(next(f2lines), end='')
+            else:
+                print(f1line, end='')
+
+

Output:

+
NEW FUSTAT TOURS
+City
+USA
+Address
+napolean
+First Company
+Test TOURS
+City
+UK
+Address
+napolean
+Second Company
+
",python +"How to apply recursion over this problem and solve this problem

The Problem is:-

+
Given a digit string, return all possible letter combinations of each digits according to the buttons on a telephone, that the number could represent.
+The returned strings must be lexicographically sorted.
+
+Example-1 :-
+Input : “23”  
+Output : ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]   
+
+Example-2 :-
+Input : “9”
+Output: [“w”, “x”, “y”, “z”]
+
+Example-3 :-
+Input : “246”
+Output : ["agm", "agn", "ago", "ahm", ..., "cho", "cim", "cin" "cio"] {27 elements}
+
+

I've squeezed my brain on this, and I've tried a lot but I'm not getting ahead of this part, what I've tried is to use a recursive function that zips the individual letters of each digit with each other letters and use itertools.combinations() over it, but I'm unable to complete this function and I'm unable to get ahead of this.

+

What I've tried is :-

+
times, str_res = 0, ""
+
+def getval(lst, times):
+    if times==len(lst)-1:
+        for i in lst[times]:
+            yield i
+    else:
+        for i in lst[times]:
+            yield i + getval(lst, times+1)
+
+dct = {"2":("a","b","c"), "3":("d","e","f"), "4":("g","h","i"),
+     "5":("j","k","l"), "6":("m","n","o"), "7":("p","q","r","s"),
+     "8":("t","u","v"), "9":("w","x","y","z"), "1":("")}
+
+str1, res = "23", []
+
+if len(str1)==1:
+    print(dct[str1[0]])
+else:
+    temp = [dct[i] for i in str1]
+    str_res = getval(temp, times)
+    print(str_res)
+
+

Please suggest me your ideas over this problem or in completing the function...

","

It's not itertools.combinations that you need, it's itertools.product.

+
from itertools import product
+
+def all_letter_comb(s, dct):
+    for p in product(*map(dct.get, s)):
+        yield ''.join(p)
+
+dct = {"2":("a","b","c"), "3":("d","e","f"), "4":("g","h","i"),
+     "5":("j","k","l"), "6":("m","n","o"), "7":("p","q","r","s"),
+     "8":("t","u","v"), "9":("w","x","y","z"), "1":("")}
+
+for s in ['23', '9', '246']:
+    print(s)
+    print(list(all_letter_comb(s, dct)))
+    print()
+
+

Output:

+
23
+['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
+
+9
+['w', 'x', 'y', 'z']
+
+246
+['agm', 'agn', 'ago', 'ahm', 'ahn', 'aho', 'aim', 'ain', 'aio', 'bgm', 'bgn', 'bgo', 'bhm', 'bhn', 'bho', 'bim', 'bin', 'bio', 'cgm', 'cgn', 'cgo', 'chm', 'chn', 'cho', 'cim', 'cin', 'cio']
+
",python +"In Python, How do you use a loop to create a dataframe?

I recently pulled data from youtube API, and I'm trying to create a data frame using that information.

+

When I loop through each item with the "print" function, I get 25 rows output for each variable (which is what I want in the data frame I create).

+

How can I create a new data frame that contains 25 rows using this information instead of just 1 line in the data frame?

+

When I loop through each item like this:

+

df = pd.DataFrame(columns = ['video_title', 'video_id', 'date_created'])

+
#For Loop to Create columns for DataFrame    
+
+x=0
+
+while x < len(response['items']):
+    video_title= response['items'][x]['snippet']['title']
+    video_id= response['items'][x]['id']['videoId']
+    date_created= response['items'][x]['snippet']['publishedAt']
+    x=x+1
+
+#print(video_title, video_id)
+df = df.append({'video_title': video_title,'video_id': video_id,
+            'date_created': date_created}, ignore_index=True)
+
+

=========ANSWER UPDATE========== +THANK YOU TO EVERYONE THAT GAVE INPUT !!!

+

The code that created the Dataframe was:

+
import pandas as pd
+
+x=0
+video_title = []
+video_id = []
+date_created = []
+
+while x < len(response['items']):
+    video_title.append (response['items'][x]['snippet'] 
+    ['title'])
+    video_id.append (response['items'][x]['id']['videoId'])
+    date_created.append (response['items'][x]['snippet']. 
+    ['publishedAt'])
+    x=x+1
+
+#print(video_title, video_id)
+df = pd.DataFrame({'video_title': video_title,'video_id': 
+video_id, 'date_created': date_created})
+
","

Based on what I know about youtube APIs return objects, the values of 'title' , 'videoId' and 'publishedAt' are strings. +A strategy of making a single df from these strings are:

+
    +
  1. Store these strings in a list. So you will have three lists.
  2. +
  3. Convert the lists into a df
  4. +
+

You will get a df with x rows, based on x values that are retrieved.

+

Example:

+
import pandas as pd
+
+x=0
+video_title = []
+video_id = []
+date_created = []
+
+while x < len(response['items']):
+    video_title.append (response['items'][x]['snippet']['title'])
+    video_id.append (response['items'][x]['id']['videoId'])
+    date_created.append (response['items'][x]['snippet']['publishedAt'])
+    x=x+1
+
+#print(video_title, video_id)
+df = pd.DataFrame({'video_title': video_title,'video_id': 
+video_id, 'date_created': date_created})
+
",python +"Explanation about Garbage collection python

Hi im not sure if this is related to garbage collection in python but im looking for some guidance in how it works under the hood. +Below is a part of my program.

+
def get_data():
+
+ templist = []
+
+ '''
+ does stuff to fill templist with newest data
+ '''
+
+ return templist
+
+def save_data(new_list, old_list):
+
+ '''
+ loops to check for updates.
+ if update, write to file
+ '''
+ if not old_list:
+    for n in new_list:
+        write_file(n)
+ else:
+    for n, o in zip(new_list,old_list):
+        if n[1] != o[1]:
+            write_file(n)
+ return new_list
+
+comparelist = []
+
+while True:
+
+ newlist = get_data()
+ comparelist = (save_data(newlist, comparelist))
+
+

I have checked with the id() function, and newlist gets passed as a new object each time to newlist, which then gets passed to comparelist (still memomery reference to templist.

+

My questions is this:

+
    +
  • each lap, is the lists that are no longer used destroyed?
  • +
  • Is there a better way to do this?
  • +
","

How and when objects are collected is generally a non issue, you should only care about how long you keep strong references to them around, which is mostly solved by scoping and knowing which objects you are keeping alive yourself.

+

When the object's reference count drops to zero, it's marked for deletion, when that deletion occurs is implementation dependent. In the reference CPython implementation, it runs immediately after it reaches 0 https://docs.python.org/3/c-api/refcounting.html#c.Py_DECREF

+

To save on a bit of time CPython will keep a few lists alive after they are deallocated, to be reused later to prevent creating completely new objects every time, so there's really nothing to worry about.

",python +"Data Manipulation in multiple columns(absolute, percentage, and categorical) in pandas dataframe

I need to make a function, which takes input as dataframe, and dictionary{"Col_1" :% change,"Col_2":absolute change,"Col_3": 0/1(Categorical)} and it should make the changes to the dataframe.

+

I Have data frame like this

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Datecol_1col_2col_3
01/01/2022901000
01/02/2022801101
01/03/2022921200
01/04/2022961300
01/05/2022991501
01/06/20221051551
+
+

Now I pass the dictionary say,

+
{"Date":["01/01/2022","01/02/2022"],"col_1":[-10,-10],"col_2":10,"col_3":[1,0]}
+
+
    +
  • for "col_1" I am passing -10,-10 percentage change to its previous values on specified date.
  • +
  • for "col_2" I am passing an absolute number that is 10 (it should replace previous values by 10) +specified date.
  • +
  • for "col_3" I am passing a binary number and it updated in dataframe on specified date.
  • +
+

Then my desired out would look like this

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Datecol_1col_2col_3
01/01/202281101
01/02/202272100
01/03/2022921200
01/04/2022961200
01/05/2022991501
01/06/20221051551
+
+

I followed tried this code:

+
def per_change(df,cols,d):
+    df[cols] = df[cols].add(df[cols].div(100).mul(pd.Series(d)), fill_value=0)
+    return df
+
+

but it didn't worked out. Please help!!

","

You could use dic["Date"] as a boolean mask and update values in df using the values under the other keys in dic:

+
msk = df['Date'].isin(dic['Date'])
+df.loc[msk, 'col_1'] *= (1 + np.array(dic['col_1']) / 100)
+df.loc[msk, 'col_2'] = dic['col_2']
+df.loc[msk, 'col_3'] = dic['col_3']
+
+

Output:

+
         Date  col_1  col_2  col_3
+0  01/01/2022   81.0     10      1
+1  01/02/2022   72.0     10      0
+2  01/03/2022   92.0    120      0
+3  01/04/2022   96.0    130      0
+4  01/05/2022   99.0    150      1
+5  01/06/2022  105.0    155      1
+
",python +"How can I convert all values in a column like '€226.5M' or '€100.1K' (type object) to 226.5 or 0.1001 (type float) while working with Pandas?

I have this DataFrame and I know I should use the replace method, but I don't in which way. +I want all values in the column to be floats in million euros, so I would erase the '€', also the 'M' and if a value has a 'K' instead of an 'M', erase the K and make the number 1000 times smaller. +Thanks!

+

https://i.stack.imgur.com/lqbvU.png

","

Create a custom function to convert string values to numeric:

+
mappings = {'M': 1, 'K': 0.001}
+
+def to_numeric(sr):
+    df = sr.str.extract('([^€KM]+)([KM]?)')
+    return df[0].astype(float) * df[1].map(mappings).astype(float)
+
+# Convert your columns
+df['Value'] = to_numeric(df['Value'])
+df['Wage'] = to_numeric(df['Wage'])
+df['Release Clause'] = to_numeric(df['Release Clause'])
+
",python +"How can I clean html code data in a DataFrame?


I called an api, and put it in a DataFrame. +
There is a column with a lot of rows and the values are HTML code. I would like to clean the HTML code, only the wording itself. How can I do that?

+

Example:

+
<p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶,及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>
+
","

Firstly, run this in a terminal:
+pip install beautifulsoup4

+

Afterwards, apply a proper function to the html column of your pandas dataframe (See below).

+

Code:

+
from bs4 import BeautifulSoup
+import pandas as pd
+
+# Create a sample dataframe
+html = '<p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶,及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>'
+df = pd.DataFrame([{'html': html}])
+
+# Extract text from html
+df['extracted'] = df.html.apply(lambda s: BeautifulSoup(s).text)
+
+

Output:

+
+ + + + + + + + + + + + + + + +
htmlextracted
0<p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶,及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>家庭旅遊保險計劃包括申請人及配偶,及免費最多其四名18歲以下之同行子女每人每次最高賠償額* (港元)金計劃 醫療費用 $1,000,000 個人意外 $1,000,000 手機意外損毀或遺失 $3,000銅計劃 醫療費用 $250,000 個人意外 $250,000*18歲以下及75歲以上之受保人於計劃內的保障額將會減少
+
",python +"Why does Matplotlib shows an incorrect image?

I am trying to divide an image into patches and visualize it but matplotlib keep showing totally incorrect output.

+
from PIL import Image
+import os
+def imgcrop(input, xPieces, yPieces):
+    filename, file_extension = os.path.splitext(input)
+    im = Image.open(input)
+    imgwidth, imgheight = im.size
+    height = imgheight // yPieces
+    width = imgwidth // xPieces
+    for i in range(0, yPieces):
+        for j in range(0, xPieces):
+            box = (j * width, i * height, (j + 1) * width, (i + 1) * height)
+            a = im.crop(box)
+            np_img = np.asarray(a)
+            plt.imshow(np_img)
+
+

I used the method as follows:

+
imgcrop("cats.jpeg", 14, 14)
+
+

I got a 16 x 16 patches but in different colours entirely different from the image

+

code credit: #How to Split Image Into Multiple Pieces in Python

+

Input:

+

+

Output:

+

","

Your issue is not that the color is wrong, but that you are only seeing the very last patch of your image being displayed (at least when run in jupyter notebook)

+

This results in the only patch visible being one of the ground (lower right corner), which is completely in shades of brown and does therefore look very different to your initial picture.

+

The easiest fix is to use plt.subplots to plot all patches:

+
from PIL import Image
+import os
+import numpy as np
+import matplotlib.pyplot as plt
+def imgcrop(input, xPieces, yPieces):
+    filename, file_extension = os.path.splitext(input)
+    im = Image.open(input)
+    imgwidth, imgheight = im.size
+    height = imgheight // yPieces
+    width = imgwidth // xPieces
+    fig, axs = plt.subplots(yPieces, xPieces)
+    for i in range(0, yPieces):
+        for j in range(0, xPieces):
+            box = (j * width, i * height, (j + 1) * width, (i + 1) * height)
+            a = im.crop(box)
+            np_img = np.asarray(a)
+            axs[i][j].imshow(np_img)
+    [axi.set_axis_off() for axi in axs.ravel()]
+imgcrop("cat.jpg", 14, 14)
+
+

Input:

+

+

Output:

+

",python +"How to destroy tkinter mainloop when exception occurs in any module running in daemon thread

I wrote a Python (3.7) application that uses tkinter as GUI and runs the main function in a daemon thread. Is there a way to destroy the tkinter mainloop when an exception occurs in that daemon thread?

+

The issue is that the program has multiple modules. Is there a way to kill the mainloop if that happens in any of them? Otherwise the user will be left with a frozen GUI.

+

Here is the piece of code starting the thread:

+

+import logging
+import threading
+from tkinter import *
+from tkinter import ttk
+
+
+def main_thread():
+
+    if check_input():  # user provided necessary input
+        program_thread = threading.Thread(target=program_pipeline)  # runs main
+        program_thread.daemon = True  # daemon thread can be killed anytime?
+        program_thread.start()
+        block_user_entries()
+        clear_results()  # from a previous run
+
+    else:
+        logging.info("\n--------------- TRY AGAIN -------------------\n")
+        ublock_user_entries()
+
+
+
+

The program_pipeline communicates with multiple modules and packages

+

The thread starts when user clicks a button

+

+analyze_button = ttk.Button(frame, text="Analyze", state="normal", command=main_thread)
+analyze_button.grid(column=2, row=0, pady=2, sticky=(W))
+
+root.mainloop()
+
+
+
","

If I am interpreting this correctly, you are looking for a way to interrupting main thread from a daemon.

+

Now, generally this is not a recommended option, you can do the same using low level _thread.interrupt_main().

+

If you provide more information a better solution can be thought of.

+
import _thread
+import threading
+import tkinter as tk
+
+
+def program_pipeline():
+    try:
+        # DO STUFF
+        # calling other modules that may raise exception/error
+        raise ValueError("Error")
+    except BaseException as be:
+        print("Exception in daemon", be)
+        _thread.interrupt_main()
+
+
+def main_thread():
+
+    program_thread = threading.Thread(target=program_pipeline)
+    program_thread.daemon = True
+    program_thread.start()
+
+
+root = tk.Tk()
+analyze_button = tk.Button(root, text="Analyze", state="normal", command=main_thread)
+analyze_button.grid(column=2, row=0, pady=2, sticky=tk.W)
+
+try:
+    root.mainloop()
+except KeyboardInterrupt as kie:
+    print("exception in main", kie)
+
",python +"Looping through each cell of a column in Excel using Python

I have an Excel file with data in column A. I want to loop through each cell and stop once i reach the first cell that has a formula.

+

This is my code:

+
wb = openpyxl.load_workbook(r"path\filename.xlsx")
+
+sheet = wb['Sheet1'] 
+
+names=sheet['A'] 
+
+for cellObj in names:
+
+  if cellObj.value.str[0] == '=':
+     print(cellObj.value)
+
+

But i get an error...

+

The response from @John Giorgio worked for that part.

+

Now what i'm trying to do next is to select the entire row and paste special.

+

Here's my code:

+
import openpyxl 
+wb=openpyxl.load_workbook(path1)
+sheet = wb['Sheet1']
+
+names=sheet['A']
+
+for cellObj in names:
+    val = str(cellObj.value)
+    if val[0] == "=":
+        #print(val)
+
+        excel.Range("A10:TM10").Select() #PART I WANT TO SELECT IF TRUE 
+        excel.Selection.PasteSpecial(Paste=-4163)
+
+

So once I come across the first cell with '=' i want to select the entire row or at least from column A to TM and hardcode it / pasteSpecial

","
wb = openpyxl.load_workbook(r"path\filename.xlsx")
+
+sheet = wb['Sheet1'] 
+
+names=sheet['A'] 
+
+for cellObj in names:
+    val = str(cellObj.value)
+    if val[0] == "=":
+        print(val)
+
",python +"How to turn an *.RDS file into a *.FEATHER file?

I am trying to covert an *.rds file in R into a *.feather file for use in Python.

+
library(feather)
+data = readRDS("file.rds")
+write_feather(data,"file.feather")
+
+

However, I receive the following error:

+
> write_feather(data,"file.feather")
+Error: `x` must be a data frame
+
+

How can I turn the *.rds file/matrix into a *.feather file to read with Pandas (or any other Pandas-compatible file that can handle a 24000*24000 matrix)?

+

","

Coerce matrix obeject to data.frame object:

+
library(feather)
+data = readRDS("file.rds")
+as.data.frame(as.matrix(data))
+write_feather(data,"file.feather")
+
",python +"Slash commands on nextcord

I wanted to add slash commands but unsuccessfully. After hours of documentation reading, examples checking I finally left the idea to try it on my current code. So I've litterally try the example code from the nextcord documentation. I copy/paste the code add the token and the guild ID. But that wasn't more successful. +My bot have admin permission (8 on the scope), intents are all check on the bot dev pannel and after hours of waiting... Nothing on the slash list. I thought that was a refresh problem on my discord client, so I tested run discord on several devices (pc, mac, phone, ...) but nope.

+

As I said I tried the example code with only the server id changed (and also the token correctely edited, the bot himself is running well)

+
import nextcord
+
+client = nextcord.Client()
+server = numberfromguildid
+
+
+@client.slash_command(guild_ids=[server])  # limits guilds with this command.
+async def ping(
+    interaction: nextcord.Interaction,
+):
+    await interaction.response.send_message("Pong!")
+
+
+client.run("TOKEN")
+
+

If anyone have a solution that would be life saver !

","

Did you enable applications command while generating OAuth2 link? and you still need to import modules from nextcord and nextcord.abc, Your code should look like this:

+
from nextcord import Interaction, SlashOption, ChannelType
+from nextcord.abc import GuildChannel
+from nextcord.ext import commands
+import nextcord
+
+

The way you initiate the client seems to be wrong also I guess

+
client = commands.Bot(command_prefix='YOUR_PREFIX')
+
",python +"How can I convert an array of dates into a Pandas DataFrame?

I have a Python array in the form:

+
K = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]
+
+

This array contains dates within sub-arrays.

+

How can I turn it into a Pandas DataFrame with 1 column of dates in standard format (%d/%m/%Y)?

","
import pandas as pd
+date_array = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]
+date_df = pd.DataFrame(date_array, columns=['year', 'month', 'day'])
+date_df['date'] = pd.to_datetime(date_df[['year', 'month', 'day']], format='%d/%m/%Y')
+
+

And if you'd like you can drop extra columns

",python +"Problems installing vtk Python

I can't install vtk in python project with this command:

+
python -m pip install vtk
+
+

I'm getting this error:

+
ERROR: No matching distribution found for vtk
+ERROR: Could not find a version that satisfies the requirement vtk (from versions: none)
+
+

I tried to update my pip package :

+
python -m pip install --upgrade pip
+
+

I tried to install the .whl file directly from the project directory:

+
python -m pip install .\vtk-9.1.0-cp39-cp39-win_amd64.whl
+
+

I tried all vtk .whl file versions but I keep getting this error:

+
ERROR: vtk-9.1.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.
+
+

PS: I use Python 3.10.0

","

It looks like a problem that was reported 3 months ago. My recommendation is using python 3.9 for vtk, until it is resolved. I verified it works fine using python 3.9.10

",python +"Why is the scrollbar not working in the canvas (tkinter)?

I want the window frame to expand the whole canvas AND have a scrollbar. Now the scrollbar is there visually but is not working as a scrollbar.

+
root = Tk()
+
+def onCanvasConfigure(e):
+    my_canvas.configure(scrollregion = my_canvas.bbox("all")) #make the scrollfunction work
+    my_canvas.itemconfig('window', height=(my_canvas.winfo_height()-100), width=(my_canvas.winfo_width()-100)) #set the frame window to canvas size
+
+
+#Below code to add scrollbar to app. 
+# Layers (root -> main_frame -> my_canvas -> window (frame))
+
+# Create A Main Frame
+main_frame = Frame(root)
+main_frame.pack(fill=BOTH, expand=1)
+
+# Create A Canvas
+my_canvas = Canvas(main_frame)
+my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
+
+# Add A Scrollbar To The Canvas
+my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
+my_scrollbar.pack(side=RIGHT, fill=Y)
+
+# Configure The Canvas
+my_canvas.configure(yscrollcommand=my_scrollbar.set)
+
+
+# Create ANOTHER Frame INSIDE the Canvas
+window = Frame(my_canvas)
+
+# Add that New frame To a Window In The Canvas
+my_canvas.create_window((0,0), window=window, anchor="nw", tags="window")
+
+my_canvas.bind("<Configure>", onCanvasConfigure)
+
+

See clip: https://jumpshare.com/v/TJlbWJac5d4rwp3DwnFw

","

Since you resize the internal frame window to the same size of canvas, so the scrollregion will be around the same as the size of the canvas which makes the scrollbar not activated.

+

If you set the height of the frame larger than that of canvas, the scrollbar will be activated:

+
def onCanvasConfigure(e):
+    # resize the frame with double height of canvas
+    my_canvas.itemconfig('window', height=e.height*2, width=e.width)
+    # update scrollregion
+    my_canvas.configure(scrollregion=my_canvas.bbox("all"))
+
",python +"Matrix size-incompatible: In[0]: [47,1000], In[1]: [4096,256]

I'm new to TensorFlow and am following a tutorial. I'm trying to do image captioning using VGG. I am getting an error that says:

+

enter image description here

+

This is my code:

+
model = define_model(vocab_size, max_length)  
+epochs = 20
+
+steps = len(train_descriptions)
+
+for i in range(epochs):
+    generator = data_generator(train_descriptions, train_features, tokenizer, max_length)
+    model.fit_generator(generator, epochs=1, steps_per_epoch=steps, verbose=1)
+    model.save('model_' + str(i) + '.h5')
+
+

I'm just following the tutorial but that video was taken a long time ago. Since I'm new to this I don't understand this error. I tried model.fit() also. But, nothing works. Please, help me to rectify this.

+

https://github.com/nitinkaushik01/Deep_and_Machine_Learning_Projects/blob/master/Image_Caption_Project/Image_caption_Project.ipynb - This is the tutorial I'm following.

","
    +
  1. solved after apply the below modification inputs1 --> 1000 instead +of 4096 se1 --> 47 instead of 256 decoder2 --> 47 instead of 256 +fe2 --> 47 instead of 256 se3 --> 47 instead of 256
  2. +
  3. or just update inputs1 to 1000 i think it will solve the issue
  4. +
",python +"Python - Expanding a group using selenium

I'm new to python and I'm trying to automate a few tasks.

+

My issue is when I log in to my server I need to expand the group and select the form inside the group, I'm using find_element By Xpath and ID and keep getting this error "Unable to locate element:", I tried to use sleep or WebDriverWait but didn't work.

+

My element code in image now (the arrow):

+ +

When I open it manual the aria-expanded changed to ="true"

+

My group code:

+ +

Main group

+

Forms

+
+

The website login details (dummy server): +server: https://new2001.surveycto.com/ +user: taevion.ezrael@alldrys.com +password: Stackoverflow_example

","
driver.get(" https://new2001.surveycto.com/")
+time.sleep(5)
+driver.find_element(By.ID, "login-username").send_keys("taevion.ezrael@alldrys.com")
+driver.find_element(By.XPATH, "//button[text()='Next']").click()
+time.sleep(1)
+driver.find_element(By.ID, "login-password").send_keys("Stackoverflow_example")
+time.sleep(1)
+driver.find_element(By.XPATH, "//button[text()='Log in']").click()
+time.sleep(10)
+ActionChains(driver).move_to_element(driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]")).perform()
+time.sleep(1)
+driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//button[@data-original-title='Add form, group or dataset']").click()
+time.sleep(1)
+driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//div[@class='primary-actions']//a[contains(@data-original-title, 'start from scratch')]").click()
+time.sleep(5)
+x = driver.find_element(By.XPATH, "//form[@method='post']//h3").text
+print(x)
+driver.save_screenshot('snapshot.png')
+driver.quit()
+
+

This code logs in to the website with the credentials and then clicks on the + icon of the Foundation form, and after the expansion occurs, it clicks on the Start New Form button, and just to verify for you, it takes the snapshot of the screen and extracts the form header.

+

Output:

+
Start new form - Step 1
+
+Process finished with exit code 0
+
+

Form Snapshot

",python +"How to get input entered in QLineEdit by clicking QPushButton and then print result in QLabel?

first of all, I want to completely explain what I'm going to do exactly. I have a simple script and I want to convert it to an executable file or whatever you call it but first I should start with interface stuff.

+

here is the simple python script:

+
for i in range(4):
+    a = False
+    while not a:
+        text = input("enter a word")
+        
+        # a condition for accepting input. I mean input should satisfy this condition
+        if len(text) == 5:
+            a = True
+    
+    # just print the word, simple and easy
+    print(text)
+
+

I want to put this process in PyQt5 to create an extremely simple user enter face. but how should I do that? I want to add a QLineEdit to get input! input is a string-like text! and I want to trigger and enter the word by clicking QPushButton! and while the input doesn't satisfy the condition (len(text) == 5) I should be able to type another input in QLineEdit and enter it using QPushButton till the input satisfies the condition! then the program should print(text) in a QLabel(i think QLabel is okay since I can adjust its dimension and size...). and the important thing is I should be able to write and enter 4 correct words(words that satisfy the condition) in the program (since I wrote for i in range(4):). so here is what I expect step by step:

+
    +
  1. being able to enter 4 correct words
  2. +
  3. getting input by a QLineEdit
  4. +
  5. enter input by clicking on a QPushButton
  6. +
  7. if the length of the word is 5, then print it, else: wait for next input
  8. +
  9. do this process for 4 valid inputs
  10. +
+

I'm not much familiar with pyqt5, but I'm doing my best. here is what I wrote for this purpose:

+
from PyQt5.QtWidgets import QApplication , QWidget , QPushButton , QLabel , QLineEdit
+import sys
+
+app = QApplication(sys.argv)
+
+class APP(QWidget):
+    def __init__(self):
+        super().__init__()
+
+        self.button = QPushButton("Enter" , self)
+        self.button.setGeometry(500 , 400 , 100 , 50)
+        self.button.clicked.connect(self.clicked)
+        self.Line_edit()
+
+        self.label = QLabel("place of ouput prints" , self)
+        self.label.move(40 , 60)
+        self.label.setGeometry(50 , 50 , 150 , 50)
+
+    def Line_edit(self):
+        self.input_text = QLineEdit(self)
+        self.input_text.setPlaceholderText("Enter The Word")
+    
+    def clicked(self):
+        # if QLineEdit contains a word
+        if self.input_text.text():
+            for i in range(4):
+                a = False
+                while not a:
+                    text = self.input_text.text()
+
+                    # a condition for accepting input. I mean input should satisfy this condition
+                    if len(text) == 5:
+                        a = True
+
+                # just print the word in QLable, simple and easy
+                self.label = QLabel(text , self)
+                # then it should be waiting for new input untill i == 3 (since i wrote for i in range(4))
+
+
+window = APP()
+window.show()
+sys.exit(app.exec_()) 
+
+

when I try to run this code, it doesn't even react and nothing happens. how should I modify the code to get what I am supposed to?

","

I figured out the solution by myself. I was totally wrong with signal implication when you click a QPushButton! and I figured out that a QLabel can be updated using .setText()! so here is the solution:

+
from PyQt5.QtWidgets import QApplication , QWidget , QPushButton , QLabel , QLineEdit
+import sys
+
+app = QApplication(sys.argv)
+
+class APP(QWidget):
+    def __init__(self):
+        super().__init__()
+
+        self.button = QPushButton("Enter" , self)
+        self.button.setGeometry(500 , 400 , 100 , 50)
+        self.button.clicked.connect(self.clicked)
+        self._submit_counter = 0
+        
+        self.button2 = QPushButton("RESET" , self)
+        self.button2.setGeometry(500 , 600 , 100 , 50)
+        self.button2.clicked.connect(self.reset_clicked)
+        
+        self.Line_edit()
+
+        self.label = QLabel("place of ouput prints" , self)
+        self.label.move(40 , 60)
+        self.label.setGeometry(50 , 50 , 150 , 50)
+
+    def Line_edit(self):
+        self.input_text = QLineEdit(self)
+        self.input_text.setPlaceholderText("Enter The Word")
+
+    def reset_clicked(self):
+        self._submit_counter = 0
+    
+    def clicked(self):
+
+        if self._submit_counter<4:
+
+            # if QLineEdit contains a word
+            if self.input_text.text():
+                
+                text = self.input_text.text()
+
+                # a condition for accepting input. I mean input should satisfy this condition
+                if len(text) == 5:
+                    
+                    self._submit_counter += 1
+                    # just print the word in QLable, simple and easy
+                    self.label.setText(text)
+
+
+window = APP()
+window.show()
+sys.exit(app.exec_()) 
+
",python +"Remove the black border and keep the image size same in python

I am rotating an image 45 degree. When I rotate the image it has a black border and the image size changes from 256x256 to 364x364. I want to remove the values of this black border and keep the size 256. In pillow if I put fill color then the black border will go away but the size is still the same. Is there any way that I can remove the black border and retain the original shape

+

code to rotate

+
path = "E:\\download\\1.jpeg"
+image = cv2.imread(path)
+rotated = imutils.rotate_bound(image, -33)
+
+

Original Image

+

+

Rotate image

+

","

you can try to crop the image as much as part of the image you want. Although the cropping in python is possible in the form of pixels. Hence, you can try to crop the image as much is required. +The following code might help you to crop

+
im=Image.open(r"specify the path of the image")`
+
+

width, height = im.size

+
left = "specify the value in pixels"
+top = "specify the value in pixels"
+right = "specify the value in pixels"
+bottom = "specify the value in pixels"
+# Cropped image of above dimension
+# (It will not change original image)
+im1 = im.crop((left, top, right, bottom))
+#im1.show()
+im1.save('specify destination path')
+
",python +"Walking through python list comprehension

I'm trying to understand list comprehension in python using this example -

+
async def on_member_update(before, after):
+    stream = [i for i in after.activities if str(i.type) == "ActivityType.streaming"]
+    if stream:
+
+

The above example is using the api from discord.py. Streaming is a member activity - https://discordpy.readthedocs.io/en/stable/api.html#activity . ActivityType.streaming is a type - https://discordpy.readthedocs.io/en/stable/api.html#discord.ActivityType

+

What's going on in this loop? I'll try and walkthrough what I may know. So if (i.type) returns as a string then it would be looping through the characters in the stream list? I'm confused. after.activites is the member's CURRENT activity. So it'd be streaming. What exactly does (i.type) represent what how is the loop interacting with after.activites?

+

Getting lost. Could someone walk me through the steps of what's happening here? Thank you!

","

List comprehensions can be mechanically transformed into loops. This comprehension is equivalent to the code

+
stream = []
+for i in after.activities:
+    if str(i.type) == "ActivityType.streaming":
+        stream.append(i)
+
+
+

Unrelated, it is somewhat atypical to compare the type of something by first converting it to a string and then comparing the resulting string. Knowing nothing else, I would expect to see instead the line

+
    if i.type == ActivityType.streaming
+
+

or perhaps a isinstance() instead of direct type comparison if there can be meaningful subtypes.

",python +"Python pandas sample without mixing index

I want to apply the sample function from Pandas independently for each value of the index for a data frame. This can be done with a for loop like this:

+
import pandas
+
+df = pandas.DataFrame({'something': [3,4,2,2,6,7], 'n': [1,1,2,2,3,3]})
+df.set_index(['n'], inplace=True)
+
+resampled_as_I_want_df = df[0:0]
+for i in sorted(set(df.index)):
+    resampled_as_I_want_df = resampled_as_I_want_df.append(
+        df.loc[i].sample(frac=1, replace=True),
+    )
+
+print(resampled_as_I_want_df)
+
+

Let me explain this in a human-friendly way. The df data frame looks like this:

+
   something
+n           
+1          3
+1          4
+2          2
+2          2
+3          6
+3          7
+
+

Now we see that there are three "index groups" which have the values 1, 2 and 3. What I want to do is to apply the sample function in a way that the new data frame will have the same index, without random sampling, and the sampling is performed within each group as if they were independent data frames.

+

Is there a way to avoid the for loop? For large data frames it is a bottle neck.

","

Use df.groupby(level=0).sample(frac=1, replace=True).

",python +"How to extract date from a string?

I have this weird string:

+
'": "1899-12-30 14:50:00.000"": " "'
+
+

I need to just extract the date. +I have looked at all the different python string manipulation functions but I just can't seem to find one that works for this interesting format.

+

Thanks

","

Based on your string if you just want 1899-12-30 you could do:

+
'": "1899-12-30 14:50:00.000"": " "'.split(' ')[1][1:]
+
+

if you want the full 1899-12-30 14:50:00.000 you could do

+
'": "1899-12-30 14:50:00.000"": " "'.split('"')[2]
+
+

Explanation:

+

taking the string we are splitting the string by its characters in the first example a space and in the second a double quote as those characters surround the date element. The split function creates a list in which we access the element that we would like in the first case the second element (0 index list) while the second list we grab the third element. For the first Example printing out the output before we do a slice of the sting would give an extra double quote before the date, therefore we take the first element off of the string to only get the date.

",python +"How can I get the symbolic gradient [Tensorflow 2.x]

I want to get the symbolic expression for gradient estimation. When I see the output it's quite difficult to understand what's going on.

+
import tensorflow as tf
+@tf.function
+def f_k(input_dat):
+    y = tf.matmul(tf.sin(input_dat[0]), input_dat[1])
+    grads = tf.gradients([y], input_dat)
+    # grads = tape.gradient([y], input_dat)
+    tf.print('tf >>', grads)
+    print('print >>', grads)
+    return y, grads
+
+
+a = tf.Variable([[1., 3.0], [2., 6.0]])
+b = tf.Variable([[1.], [2.]])
+input_data = [a, b]
+y, z = f_k(input_data)
+print(y, z)
+
+

Output: inside the function

+
print >> [<tf.Tensor 'gradients/Sin_grad/mul:0' shape=(2, 2) dtype=float32>, <tf.Tensor 'gradients/MatMul_grad/MatMul_1:0' shape=(2, 1) dtype=float32>]
+tf >> [[[0.540302277 -1.979985]
+ [-0.416146845 1.92034054]], [[1.75076842]
+ [-0.138295487]]
+
+

As the output, I want which is shown with print:

+
[<tf.Tensor 'gradients/Sin_grad/mul:0' shape=(2, 2) dtype=float32>, <tf.Tensor 'gradients/MatMul_grad/MatMul_1:0' shape=(2, 1) dtype=float32>]
+
+

However, the function always returns the numerical result. Could someone help me to get this symbolic representation of the gradient?

","

The symbolic representation you want will only work in graph mode. Outside of graph mode, eager execution is enabled by default. What you can do is create a new function to print the values and wrap it with the @tf.function decorator like you are already doing for f_k:

+
import tensorflow as tf
+
+@tf.function
+def f_k(input_dat):
+    y = tf.matmul(tf.sin(input_dat[0]), input_dat[1])
+    grads = tf.gradients([y], input_dat)
+    # grads = tape.gradient([y], input_dat)
+    tf.print('tf >>', grads)
+    print('print >>', grads)
+    return y, grads
+
+a = tf.Variable([[1., 3.0], [2., 6.0]])
+b = tf.Variable([[1.], [2.]])
+input_data = [a, b]
+y, z = f_k(input_data)
+
+@tf.function
+def print_symbolic(y, z):
+  print(y,z)
+  return y, z
+y, z = print_symbolic(y, z)
+
+
print >> [<tf.Tensor 'gradients/Sin_grad/mul:0' shape=(2, 2) dtype=float32>, <tf.Tensor 'gradients/MatMul_grad/MatMul_1:0' shape=(2, 1) dtype=float32>]
+tf >> [[[0.540302277 -1.979985]
+ [-0.416146845 1.92034054]], [[1.75076842]
+ [-0.138295487]]]
+Tensor("y:0", shape=(2, 1), dtype=float32) [<tf.Tensor 'z:0' shape=(2, 2) dtype=float32>, <tf.Tensor 'z_1:0' shape=(2, 1) dtype=float32>]
+
+

You could also just access the tensors of your graph:

+
graph = f_k.get_concrete_function(input_data).graph
+print(*[tensor for op in graph.get_operations() for tensor in op.values()], sep="\n")
+
+
Tensor("input_dat:0", shape=(), dtype=resource)
+Tensor("input_dat_1:0", shape=(), dtype=resource)
+Tensor("Sin/ReadVariableOp:0", shape=(2, 2), dtype=float32)
+Tensor("Sin:0", shape=(2, 2), dtype=float32)
+Tensor("MatMul/ReadVariableOp:0", shape=(2, 1), dtype=float32)
+Tensor("MatMul:0", shape=(2, 1), dtype=float32)
+Tensor("gradients/Shape:0", shape=(2,), dtype=int32)
+Tensor("gradients/grad_ys_0/Const:0", shape=(), dtype=float32)
+Tensor("gradients/grad_ys_0:0", shape=(2, 1), dtype=float32)
+Tensor("gradients/MatMul_grad/MatMul:0", shape=(2, 2), dtype=float32)
+Tensor("gradients/MatMul_grad/MatMul_1:0", shape=(2, 1), dtype=float32)
+Tensor("gradients/Sin_grad/Cos:0", shape=(2, 2), dtype=float32)
+Tensor("gradients/Sin_grad/mul:0", shape=(2, 2), dtype=float32)
+Tensor("StringFormat:0", shape=(), dtype=string)
+Tensor("Identity:0", shape=(2, 1), dtype=float32)
+Tensor("Identity_1:0", shape=(2, 2), dtype=float32)
+Tensor("Identity_2:0", shape=(2, 1), dtype=float32)
+
+

Check the docs for more information.

",python +"Replacing all functions with 'pass', syncing private to public github repo

I'd like to create a repository for a proprietary python module, similarly how this python package mlfinlabs. They have emptied out all functions like this:

+
    def bet_size_dynamic(current_pos, max_pos, market_price, forecast_price, cal_divergence=10, cal_bet_size=0.95,
+                         func='sigmoid'):
+        pass
+    
+    
+    def bet_size_budget(events_t1, sides):   
+        pass
+
+

I found the libcst module, that parses the source code and you can do operations on it.

+

Is there a better practice of doing this? eg.: github actions? I can't find any other good solution.

","
    +
  1. Github action to sync from private to public repo. +Using this github action: https://github.com/marketplace/actions/github-repo-sync

    +
  2. +
  3. libcst (project site) to strip functions afterwards (also as a github action step). Below is the codemod that you should put either

    +
  4. +
+
    +
  • in the libcst folder (\Lib\site-packages\libcst\codemod\commands)
  • +
  • in your repo directory and then specify it .libcst.codemod.yaml (this is needed if you run the codemod on github actions):
  • +
+
# String that LibCST should look for in code which indicates that the
+# module is generated code.
+
+generated_code_marker: '@generated'
+
+# Command line and arguments for invoking a code formatter. Anything
+# specified here must be capable of taking code via stdin and returning
+# formatted code via stdout.
+
+formatter: ['black', '-']
+
+# List of regex patterns which LibCST will evaluate against filenames to
+# determine if the module should be touched.
+
+blacklist_patterns: ['.*replace_functions\.py']
+
+# List of modules that contain codemods inside of them.
+
+modules:
+
+- 'libcst.codemod.commands'
+- 'mycodemod' # THIS IS THE NAME OF THE FOLDER
+
+# Absolute or relative path of the repository root, used for providing
+# full-repo metadata. Relative paths should be specified with this file
+# location as the base.
+
+repo_root: '.'
+
+

put your codemod then under:

+
project_root
+|--- mycodemod
+         |--- __init__.py    (this is an empty file)
+         |--- replace_functions.py (the codemod pasted below)
+
+

In replace_functions.py put this snippet:

+
from ast import Expression, literal_eval
+from typing import Union
+
+import libcst as cst
+from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand
+from libcst.codemod.visitors import AddImportsVisitor
+
+
+class ReplaceFunctionCommand(VisitorBasedCodemodCommand):
+    # Add a description so that future codemodders can see what this does.
+    DESCRIPTION: str = "Replaces the body of a function with pass."
+
+    def __init__(self, context: CodemodContext) -> None:
+        # Initialize the base class with context, and save our args.
+        print("this happens")
+        super().__init__(context)
+
+
+    def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef:
+        replace_function = cst.FunctionDef(
+            name=updated_node.name, 
+            params=cst.Parameters(), 
+            body= cst.SimpleStatementSuite((cst.Pass(),)), 
+            returns=None)
+        
+        return replace_function
+
",python +"Pytorch - Problem with fine tune training from custom features and classes

The core of my problem is the fact that my features come from NumPy files (.npy).

+

Therefore I need the following class in my code

+
import torch
+import torchvision
+import torchvision.transforms as transforms
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.optim as optim
+import numpy as np
+from torch.utils.data import Dataset, DataLoader
+from torchvision.models import resnet50
+import time
+import copy
+
+class MyDataSet(torch.utils.data.Dataset):
+    def __init__(self, x, y, transform=None):
+        super(MyDataSet, self).__init__()
+        # store the raw tensors
+        self._x = np.load(x)
+        self._y = np.load(y)
+        self.transform = transform
+    
+    def __len__(self):
+        # a DataSet must know it size
+        return self._x.shape[0]
+
+    def __getitem__(self, index):
+        x = self._x[index, :]
+        y = self._y[index, :]
+        return x, y
+
+

To convert my NumPy files to DataLoaders I do the following. The code below seems to work (at least, no errors are returned)

+
#Transform dataset 
+transform = transforms.Compose([transforms.ToTensor()])
+dataset = MyDataSet("train1-features.npy","train1-classes.npy",transform=transform)
+dataloader = DataLoader(dataset, batch_size=32)
+
+

I am trying to fine-tune a RESNET-50 network in these data with 12 classes. Here is what I do

+
def set_parameter_requires_grad(model, feature_extracting):
+    if feature_extracting:
+        for param in model.parameters():
+            param.requires_grad = False
+
+feature_extract = True
+batch_size = 8
+num_epochs = 15
+num_classes=12
+
+model_ft = resnet50(pretrained=True)
+set_parameter_requires_grad(model_ft, feature_extract)
+num_ftrs = model_ft.fc.in_features
+model_ft.fc = nn.Linear(num_ftrs, num_classes)
+input_size = 224
+
+if torch.cuda.is_available():
+    model_ft.cuda()
+
+params_to_update = model_ft.parameters()
+
+print("Params to learn:")
+if feature_extract:
+    params_to_update = []
+    for name,param in model_ft.named_parameters():
+        if param.requires_grad == True:
+            params_to_update.append(param)
+            print("\t",name)
+else:
+    for name,param in model_ft.named_parameters():
+        if param.requires_grad == True:
+            print("\t",name)
+
+# Observe that all parameters are being optimized
+optimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)
+
+# Setup the loss fxn
+criterion = nn.CrossEntropyLoss()
+
+

Finally, here is the problematic training function

+
for epoch in range(num_epochs):  # loop over the dataset multiple times
+
+    running_loss = 0.0
+    for i, data in enumerate(dataloader, 0):
+          
+        # get the inputs; data is a list of [inputs, labels]
+        inputs, labels = data
+            
+        #transfer labels and inputs to cuda()
+        inputs,labels=inputs.cuda(), labels.cuda()
+    
+        # zero the parameter gradients
+        optimizer.zero_grad()
+
+        # forward + backward + optimize
+        outputs = model_ft(inputs)
+        loss = loss_func(outputs, labels)
+        loss.backward()
+        optimizer.step()
+
+        # print statistics
+        running_loss += loss.item()
+        if i % 2000 == 1999:    # print every 2000 mini-batches
+            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
+            running_loss = 0.0
+
+

This returns me the following error once I execute the code:

+
Traceback (most recent call last):
+  File "train_my_data_example.py", line 89, in <module>
+    for i, data in enumerate(dataloader, 0):
+  File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/dataloader.py", line 517, in __next__
+    data = self._next_data()
+  File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/dataloader.py", line 557, in _next_data
+    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
+  File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
+    data = [self.dataset[idx] for idx in possibly_batched_index]
+  File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
+    data = [self.dataset[idx] for idx in possibly_batched_index]
+  File "train_my_data_example.py", line 29, in __getitem__
+    y = self._y[index, :]
+IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
+
+

The error is clearly the dataloader variable, so is this creation ok? I mean, I am loading NumPy data and transforming it to a data loader as below:

+
transform = transforms.Compose([transforms.ToTensor()])
+dataset = MyDataSet("train1-features.npy","train1-classes.npy",transform=transform)
+dataloader = DataLoader(dataset, batch_size=32)
+
+

Is there any error in my data loader or is the problem the training loop of Pytorch?

+

P.s: you can reproduce my code by downloading the classes and features here

","

You are trying to index the second axis of an array which only has a single dimension. Simply replace y = self._y[index, :] with y = self._y[index].

+

Actually when positioned last, : is not required as all dimensions are selected by default.

",python +"Github action deploy-cloud-functions not building in dependencies?

Yesterday, I was trying to restructure some Github CI/CD, because the actions from Google were throwing warnings about deprecated usages.

+

One of the steps is the (build and) deployment of a GCP function. +The repository of the function to be deployed was structured like this:

+
my_proj
+  |- .github
+  |- src
+     |- my_proj
+        |- __init__.py
+        |- main.py
+        |- requirements.txt
+...
+
+

,with the requirements.txt holding

+
boto3==1.16.54
+
+

The important bit here is the requirements.txt, that holds some dependencies, that I need to ship as well.

+

Before, I had to build the package uploaded to GCP myself, but with the "deploy-cloud-functions" action this seemed to be obsolete now. I set up the actions in Github according to documentation:

+
steps:
+  - name: Login to GCP
+    uses: google-github-actions/auth@v0
+    with:
+      credentials_json: ...
+
+  - name: Deploy GCP Function image
+    uses: google-github-actions/deploy-cloud-functions@v0
+    with:
+      name: my_function_name
+      runtime: python37
+      project_id: ...
+      source_dir: ./src/my_proj
+      env_vars:
+        ...
+
+

Now, the deployment worked. However, when inspecting the function now in GCP or downloading it, none of the dependencies were contained there and the logs upon triggering the function similarly showed a function crash due to missing dependencies.

+

I also tried to move the requirements.txt file to the project root, but apparently to no avail. I was not very lucky in finding extensive documentation about the work with GCP functions from within Github beyond the above linked Google-owned action repository.

+

Can anyone spot my error here?

","

While deploying to Cloud Functions using github actions all the dependencies also get uploaded. But, as already mentioned by Danyel Cabello, you won’t be able to see the dependencies in the source tab of the Cloud Functions in Google Cloud Console.

+

To see the build logs you can search for resource.type=“build” in the Cloud Logging of Google Cloud Console.

",python +"Filter by CharField pretending it is DateField in Django ORM/mySql

I am working with a already-done mySQL Database using Django ORM and I need to filter rows by date - if it wasn't that dates are not in Date type but normal Varchar(20) stored as dd/mm/yyyy hh:mm(:ss). +With a free query I would transform the field into date and I would use > and < operators to filter the results but before doing this I was wondering whether Django ORM provides a more elegant way to do so without writing raw SQL queries.

+

I look forward to any suggestion.

+

EDIT: my raw query would look like

+
SELECT * FROM table WHERE STR_TO_DATE(mydate,'%d/%m/%Y %H:%i') > STR_TO_DATE('30/12/2020 00:00', '%d/%m/%Y %H:%i')
+
+

Thank you.

","

I will assume your model looks like this:

+
from django.db import models
+
+class Event(models.Model):
+    mydate = models.CharField(max_length=20)
+
+    def __str__(self):
+        return f'Event at {self.mydate}'
+
+

You can construct a Django query expression to represent this computation. This expression consists of:

+
    +
  • Func objects representing your STR_TO_DATE function calls.
  • +
  • An F object representing your field name.
  • +
  • A GreaterThan function to represent your > comparison.
  • +
+
from django.db.models import F, Func, Value
+from django.db.models.lookups import GreaterThan
+from .models import Event
+
+# Create some events for this example
+Event(mydate="29/12/2020 00:00").save()
+Event(mydate="30/12/2020 00:00").save()
+Event(mydate="31/12/2020 00:00").save()
+
+class STR_TO_DATE(Func):
+    "Lets us use the STR_TO_DATE() function from SQLite directly in Python"
+    function = 'STR_TO_DATE'
+
+# This Django query expression converts the mydate field
+# from a string into a date, using the STR_TO_DATE function.
+mydate = STR_TO_DATE(F('mydate'), Value('%d/%m/%Y %H:%i'))
+
+# This Django query expression represents the value 30/12/2020
+# as a date.
+date_30_12_2020 = STR_TO_DATE(Value('30/12/2020 00:00'), Value('%d/%m/%Y %H:%i'))
+
+# This Django query expression puts the other two together,
+# creating a query like this: mydate < 30/12/2020
+expr = GreaterThan(mydate, date_30_12_2020)
+
+# Use the expression as a filter
+events = Event.objects.filter(expr)
+print(events)
+
+# You can also use the annotate function to add a calculated
+# column to your query...
+events_with_date = Event.objects.annotate(date=mydate)
+
+# Then, you just treat your calculated column like any other
+# field in your database. This example uses a range filter
+# (see https://docs.djangoproject.com/en/4.0/ref/models/querysets/#range)
+events = events_with_date.filter(date__range=["2020-12-30", "2020-12-31"])
+print(events)
+
+

I tested this answer with Django 4.0.1 and MySQL 8.0.

",python +"How to set default python3 to python 3.9 instead of python 3.8 in Ubuntu 20.04 LTS

I have installed Python 3.9 in the Ubuntu 20.04 LTS. Now the system has both Python 3.8 and Python 3.9.

+
# which python
+# which python3
+/usr/bin/python3
+# which python3.8
+/usr/bin/python3.8
+# which python3.9
+/usr/bin/python3.9
+# ls -alith /usr/bin/python3
+12583916 lrwxrwxrwx 1 root root 9 Jul 19  2021 /usr/bin/python3 -> python3.8
+
+

But the pip3 command will still install everything into the Python 3.8 directory.

+
# pip3 install --upgrade --find-links file:///path/to/directory <...>
+
+

I want to change that default pip3 behavior by updating the symbolic link /usr/bin/python3 to /usr/bin/python3.9.

+

How to do that?

+
# update-alternatives --set python3 /usr/bin/python3.9
+This command will not work as expected.
+
+

Here is the pip3 info:

+
# which pip3
+/usr/bin/pip3
+# ls -alith /usr/bin/pip3
+12589712 -rwxr-xr-x 1 root root 367 Jul 13  2021 /usr/bin/pip3
+# pip3 -V
+pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
+# 
+
+

The alias command will not work:

+
# alias python3=python3.9
+# ls -alith /usr/bin/python3
+12583916 lrwxrwxrwx 1 root root 9 Jul 19  2021 /usr/bin/python3 -> python3.8
+
","

You should be able to use python3.9 -m pip install <package> to run pip with a specific python version, in this case 3.9.

+

The full docs on this are here: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

+

If you want python3 to point to python3.9 you could use the quick and dirty.

+
alias python3=python3.9
+
+

EDIT:

+

Tried to recreate your problem,

+
# which python3
+/usr/bin/python3
+# python3 --version
+Python 3.8.10
+# which python3.8
+/usr/bin/python3.8
+# which python3.9
+/usr/bin/python3.9
+
+

Then update the alternatives, and set new priority:

+
# sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1
+# sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2
+# sudo update-alternatives --config python3
+There are 2 choices for the alternative python3 (providing /usr/bin/python3).
+
+  Selection    Path                Priority   Status
+------------------------------------------------------------
+  0            /usr/bin/python3.9   2         auto mode
+  1            /usr/bin/python3.8   2         manual mode
+* 2            /usr/bin/python3.9   2         manual mode
+
+Press <enter> to keep the current choice[*], or type selection number: 0
+
+

Check new version:

+
# ls -alith /usr/bin/python3
+3338 lrwxrwxrwx 1 root root 25 Feb  8 14:33 /usr/bin/python3 -> /etc/alternatives/python3
+# python3 -V
+Python 3.9.5
+# ls -alith /usr/bin/pip3
+48482 -rwxr-xr-x 1 root root 367 Jul 13  2021 /usr/bin/pip3
+# pip3 -V
+pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.9)
+
+

Hope this helps (tried it in wsl2 Ubuntu 20.04 LTS)

",python +"How to get nodes credentials using jenkinsapi

I need to get credentials information (which credentials used) for node. +

+

Currently I use this code that prints LOT of information but no credentials info that used for the node:

+
for node in get_server_instance().nodes._data['computer']:
+    for i in node:
+        print (i, node[i])
+
+

Is there any way to reach credentials ?

+

Thanks

",

The only way is run grep "credentials" */config.xml on the server inside nodes directory

,python +"come back to tree view when user click on save button in odoo 13.0

I override the write function in my model for calling my function that is manually set changing in DB, actually I delete this record from table in this function after that I want comeback to tree view automatically and I don't have the changed record anymore to return +because of that I stuck in write function and it doesn't finished by the way without calling my function I still can't comeback to tree view with return action(I tried any form of return action it didn't work at all) :

+
def write(self, vals):
+     self.changing_status(vals)
+     action = {
+    'name': _('Cash Control'),
+    'view_mode': 'tree',
+    'view_type': 'form',
+    'res_model': 'wfwodoovitemsstatuscurrent',
+    'view_id': self.env.ref('nmdi_workflow.list').id,
+    'type': 'ir.actions.act_window',
+    'target': 'current'
+}
+return action
+
","

I solved this by adding a button on the tree view and adding a wizard instead of form view.so, I considered a transient model for this wizard and then added the default values using a function then I added a button with the save name, then I manually made the changes to the table and set an action to return for come back to tree view and update that again.

+
class WfwU1001W1(models.TransientModel):
+    _name = 'wfwu1001wizard1'
+
+    field1 = fields.Integer( default=lambda self: self._get_data('field1'))
+    field2 = fields.Integer( default=lambda self: self._get_data('field2'))
+
+ @api.model
+    def _get_data(self, field_name):
+        id = self.env.context.get("active_id")
+        if id:
+            return self.env['wfwodoovitemsstatuscurrent'].browse(id).mapped(field_name)[0]
+
+
+ def save_changing_action(self):
+# do some logic and save manually
+
+        return {
+            'name': 'closewizard',
+            'view_type': 'tree',
+            'view_mode': 'tree',
+            'res_model': 'wfwodoovitemsstatuscurrent',
+            'view_id': False,
+            'views': [(self.env.ref('nmdi_workflow.list').id, 'tree')],
+            'type': 'ir.actions.act_window'
+        }
+
",python +"Call MongoDB stored function from pymongo

I have the following function stored in mongodb:

+
db.system.js.save({
+    _id: "testFunc",
+    value: function() {
+        return db.clients.find_one({}, {"_id" : False});
+    }
+});
+
+

How do I call the function above from python using pymongo? +I have already tried db.eval('testFunc') and it doesn't work. The method is deprecated.

","

eval, system_js etc. are all deprecated.

+

While you can still create javascript functions on the server, it comes with a clear warning:

+
+

Do not store application logic in the database. There are performance +limitations to running JavaScript inside of MongoDB. Application code +also is typically most effective when it shares version control with +the application itself.

+
",python +"Why does float() not ""unstring"" a string formatted list element?

I need to parse a comma delimited string that is part of a dict into values. I receive the data originally as a (huge) JSON formatted string and am loading it into a dict with json.loads().

+

Some of the values split from the string will always be floats and I just want to float() those, while others can be either strings, null, or empty and will need to be treated separately (not the topic of this question).

+

Bizarrely, after splitting the string, the resulting list appears to contain some non-float()-able version of a string.

+

Consider this small python3 example code

+
# construct the sample dict
+var = {}
+var['abc'] = '"123.456","zzz"'
+
+# JSONify it
+var_json = json.dumps(var)
+
+print("var_json: %s" % json.loads(var_json))
+
+# var_json now exemplifies the input data
+# deJSONify it:
+data_in = json.loads(var_json)
+
+a = data_in['abc'].split(",")
+print(a[0])
+print("this works:", float("123.456"))
+print("this borks:", float(a[0]))
+
+

This results in the following output:

+
var_json: {'abc': '"123.456","456"'}
+"123.456"
+this works: 123.456
+Traceback (most recent call last):
+  File "./test.py", line 26, in <module>
+    print("this borks:", float(a[0]))
+ValueError: could not convert string to float: '"123.456"'
+
+

So: Clearly, to python the value in the list resulting from the split is a string (has double quotes around it in the output). But using float() on that string doesn't work.

+

Changing that last line to manually replace the quotes works:

+
print(float(a[0].replace("\"", "")))
+
+

So it looks like a[0] is in fact a string containing double quotes.

+

The same error occurs even without the json.dumps/loads roundtrip, e.g. just accessing the split list from the dict directly:

+
print("This also borks: ", float(var['abc'].split(",")[0]))
+
+

Why does float() not "unstring" what very clearly is a string and a valid float conversion input? How can I avoid that .replace() call?

","

It's not enough to just split on commas; you also need to remove the literal quotation marks from the content of the string.

+

Quotation marks are not numbers. Thus, a string that contains quotation marks as part of the data within it is not a string that contains only a number. Just as the Python string 'a123a' cannot be parsed as a number, neither can '"123"': The "s are just as out-of-place in the second example as the as are in the first.

+

For example, you could use:

+
float(a[0].replace('"', ''))
+
+
+

Insofar as your JSON document is encapsulating CSV data, you can use the Python csv module to parse it in a way that will remove those quotes:

+
data_in = {'abc': '"123.456","zzz"'}
+a = csv.reader([data_in['abc']]).__next__()
+print("this now works:", float(a[0]))
+
",python +"""return"" with Ternary and warlus operators

Why when I try to return value with warlus and ternary operators := like this:

+
def get_index(elements: List[int], i: int, boundary: int) -> tp.Optional[int]:
+    return x := elements[i] if elements[i] > boundary else None
+
+

I get an error.

","

The comments suggest that you can't use the walrus operator in a return statement, that's incorrect - you just have a syntax error.

+

This works, but is pointless, as also pointed out in the comments:

+
from typing import List, Optional
+
+
+def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
+    return (x := elements[i] if elements[i] > boundary else None)
+
+
+print(get_index([1, 2, 3], 2, 1))
+
+

All you need is parentheses around the walrus assignment and the value of the expression will be the assigned value.

+

But why assign to x if all you do is return that value. Instead:

+
from typing import List, Optional
+
+
+def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
+    return elements[i] if elements[i] > boundary else None
+
+
+print(get_index([1, 2, 3], 2, 1))
+
",python +"How to send file from Nodejs to Flask Python?

Hope you are doing well. +I'm trying to send pdfs file from Nodejs to Flask using Axios. +I read files from a directory (in the form of buffer array) and add them into formData (an npm package) and send an Axios request.

+
 const existingFile = fs.readFileSync(path)                                
+    console.log(existingFile)
+    const formData = new nodeFormData()
+    formData.append("file", existingFile)
+    formData.append("fileName", documentData.docuName)
+    try {
+         const getFile = await axios.post("http://127.0.0.1:5000/pdf-slicer", formData,
+                        {
+                          headers: {
+                                      ...formData.getHeaders()
+                                   }
+                           })
+         console.log(getFile)} catch (e) {console.log(e, "getFileError")}
+
+

On flask side:

+

I'm trying to get data from the request.

+
    print(request.files)
+    
+    if (request.method == "POST"):
+        file=request.form["file"]
+        if file:
+            print(file)
+
+

in request.file, I'm getting ImmutableMultiDict([])

+

but in request.form["file"], I'm getting data something like this:

+

+

how can I handle this type of file format or how can I convert this file format to python fileObject.

","

I solved this issue by updating my Nodejs code. +We need to convert formData file into octet/stream format.

+

so I did minor change in my formData code :

+

before: formData.append("file", existingFile)

+

after: formData.append("file", fs.createReadStream(existingFile)

+
+

Note: fs.createReadStream only accepts string or uint8array +without null bytes. we cannot pass the buffer array.

+
",python +"Matplotlib colorbar: __init__() got an unexpected keyword argument 'location'

I was trying to plot a matplotlib colorbar to the left of my axis following the example given here: https://matplotlib.org/stable/gallery/axes_grid1/simple_colorbar.html#sphx-glr-gallery-axes-grid1-simple-colorbar-py

+

But as I wanted to have the colorbar on the left side of the axis, I tried:

+
import matplotlib.pyplot as plt
+import numpy as np
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+
+fig, ax = plt.subplots(1, 1)
+
+im = plt.imshow(np.arange(0, 100).reshape(10, 10))
+ax.set_xticklabels([])
+ax.set_yticklabels([])
+
+divider = make_axes_locatable(ax)
+cax = divider.append_axes("left", size="5%", pad=0.05)
+colorbar = fig.colorbar(im, cax=cax, location='left')
+colorbar.set_label('y label')
+
+

which gives me the following exception:

+
---------------------------------------------------------------------------
+TypeError                                 Traceback (most recent call last)
+<ipython-input-6-89d8edf2c11c> in <module>
+     11 divider = make_axes_locatable(ax)
+     12 cax = divider.append_axes("left", size = "5%", pad = 0.05)
+---> 13 colorbar = fig.colorbar(im, cax = cax, location = 'left')
+     14 colorbar.set_label('y label')
+     15 
+
+~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\figure.py in colorbar(self, mappable, cax, ax, use_gridspec, **kw)
+   1171                              'panchor']
+   1172         cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
+-> 1173         cb = cbar.Colorbar(cax, mappable, **cb_kw)
+   1174 
+   1175         self.sca(current_ax)
+
+~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\colorbar.py in __init__(self, ax, mappable, **kwargs)
+   1195             if isinstance(mappable, martist.Artist):
+   1196                 _add_disjoint_kwargs(kwargs, alpha=mappable.get_alpha())
+-> 1197             super().__init__(ax, **kwargs)
+   1198 
+   1199         mappable.colorbar = self
+
+~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*args, **kwargs)
+    469                 "parameter will become keyword-only %(removal)s.",
+    470                 name=name, obj_type=f"parameter of {func.__name__}()")
+--> 471         return func(*args, **kwargs)
+    472 
+    473     return wrapper
+
+TypeError: __init__() got an unexpected keyword argument 'location'
+
+

Why is that? If I use:

+
colorbar = fig.colorbar(im, ax=ax, location='left')
+colorbar.set_label('y label')
+
+

instead of divider, it seems to work, but the padding between the axis and colorbar is not as small as I want it.

","

The example you cite does not use a location argument to colorbar:

+
colorbar = fig.colorbar(im, cax=cax)
+
+

That's because you are asking it to plot the colorbar in the new axes, which you already placed on the left with the statement cax = divider.append_axes("left", size="5%", pad=0.05). You can see that an empty axis is being generated for the colorbar before the error is thrown.

+

Keep in mind that doing it this way will invert the placement of your colorbar ticks and label:

+

+

You can avoid this by adding the following after the colorbar has been drawn (since the colorbar will undo the change):

+
cax.yaxis.tick_left()
+cax.yaxis.set_label_position('left')
+
+

",python +"I´m trying to implement: np.maximum.outer in Python 3x but I´m getting this error: NotImplementedError

I have a matrix like this:

+
RCA = pd.DataFrame(
+  data=[
+    (1,0,0,0),
+    (1,1,1,0),
+    (0,0,1,0),
+    (0,1,0,1),
+    (1,0,1,0)],
+    columns=['ct1','ct2','ct3','ct4'],
+    index=['ind_1','ind_2','ind_3','ind_4','ind_5'])
+
+

I´m trying to calculate:

+
norms = RCA.sum()
+norm = np.maximum.outer(norms, norms)
+
+

And I´m getting this error:

+
---------------------------------------------------------------------------
+NotImplementedError                       Traceback (most recent call last)
+<ipython-input-9-4fd04a55ad8c> in <module>
+      4 
+      5 norms = RCA.sum()
+----> 6 norm = np.maximum.outer(norms, norms)
+      7 proximity = RCA.T.dot(RCA).div(norm)
+      8 
+
+~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/series.py in __array_ufunc__(self, ufunc, method, *inputs, **kwargs)
+    746             return None
+    747         else:
+--> 748             return construct_return(result)
+    749 
+    750     def __array__(self, dtype=None) -> np.ndarray:
+
+~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/series.py in construct_return(result)
+    735                 if method == "outer":
+    736                     # GH#27198
+--> 737                     raise NotImplementedError
+    738                 return result
+    739             return self._constructor(result, index=index, name=name, copy=False)
+
+NotImplementedError: 
+
+

This works perfect in Python 2.7, but I need to run it in Python 3.x

+

I need to find a way around this issue. Thanks a lot.

","
In [181]: RCA
+Out[181]: 
+       ct1  ct2  ct3  ct4
+ind_1    1    0    0    0
+ind_2    1    1    1    0
+ind_3    0    0    1    0
+ind_4    0    1    0    1
+ind_5    1    0    1    0
+In [182]: norms = RCA.sum()
+In [183]: norms
+Out[183]: 
+ct1    3
+ct2    2
+ct3    3
+ct4    1
+dtype: int64
+In [184]: np.maximum.outer(norms,norms)
+Traceback (most recent call last):
+  File "<ipython-input-184-d24a173874f6>", line 1, in <module>
+    np.maximum.outer(norms,norms)
+  File "/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py", line 2032, in __array_ufunc__
+    return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs)
+  File "/usr/local/lib/python3.8/dist-packages/pandas/core/arraylike.py", line 381, in array_ufunc
+    result = reconstruct(result)
+  File "/usr/local/lib/python3.8/dist-packages/pandas/core/arraylike.py", line 334, in reconstruct
+    raise NotImplementedError
+NotImplementedError
+
+

Sometimes passing a dataframe (or Series) to a numpy function works ok, but apparently here we need to explicitly use the array values:

+
In [185]: norms.values
+Out[185]: array([3, 2, 3, 1])
+In [186]: np.maximum.outer(norms.values,norms.values)
+Out[186]: 
+array([[3, 3, 3, 3],
+       [3, 2, 3, 2],
+       [3, 3, 3, 3],
+       [3, 2, 3, 1]])
+
+

Actually looking at the traceback, apparently pandas adapts ufunc to its own uses. np.maximum(norms,norms) works, but apparently pandas has not adapted the outer method. [186] is pure numpy, returning an array.

+

Plain np.maximum returns a Series:

+
In [192]: np.maximum(norms,norms)
+Out[192]: 
+ct1    3
+ct2    2
+ct3    3
+ct4    1
+dtype: int64
+
+

outer returns a 2d array, which in pandas terms would be a dataframe, not a Series. That could explain why pandas does not implement outer.

",python +"How to stop my rect from leaving a trail when moving over my background image
+

I am making a pong game and the ball object leaves a trail when it moves and I was wondering how to stop it from doing this any help would be greatly appreciated. Thank you in advance. +Here is my code:

+
+
import sys
+import pygame
+pygame.init()
+clock = pygame.time.Clock()
+# screen setup
+screen_width = 1200
+screen_height = 700
+screen = pygame.display.set_mode((screen_width, screen_height))
+background = pygame.image.load("spacebackground.png").convert_alpha()
+pygame.mouse.set_visible(False)
+pygame.display.set_caption('pong')
+
+
+# set up player and opponent and ball rect
+player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
+opponent = pygame.Rect(10,screen_height/2 - 70,10,140 )
+ball = pygame.Rect(screen_width/2-15, screen_height/2 - 15,30, 30)
+
+ball_speed_x = 7
+ball_speed_y = 7
+# defining clock and colour
+red = (0,0,0)
+
+clock = pygame.time.Clock()
+
+while True:
+
+    pygame.display.update(ball)
+    pygame.display.flip()
+    screen.blit(background, (0, 0))
+    for event in pygame.event.get():
+        if event.type == pygame.QUIT:
+            pygame.quit()
+            sys.exit()
+
+    ball.x += ball_speed_x
+    ball.y += ball_speed_y
+    # Drawing the rects
+    pygame.draw.rect(background, red, player)
+    pygame.draw.rect(background, red, opponent)
+    pygame.draw.ellipse(background, red, ball)
+    pygame.display.update(ball)
+
+    clock.tick(60)
+
+
+    
+
","

Draw the objects on the screen instead of on the background:

+
run = True
+while run:
+    for event in pygame.event.get():
+        if event.type == pygame.QUIT:
+            run = False 
+
+    ball.x += ball_speed_x
+    ball.y += ball_speed_y
+   
+    # draw background on the screen
+    screen.blit(background, (0, 0))
+
+    # draw objects on the screen
+    pygame.draw.rect(screen, red, player)
+    pygame.draw.rect(screen, red, opponent)
+    pygame.draw.ellipse(screen, red, ball)
+    
+    # update the display
+    pygame.display.flip()
+
+    clock.tick(60)
+
+pygame.quit()
+sys.exit()
+
",python +"Removing duplicates from the list of pydantic objects

I tried to remove duplicates from the list of pydantic objects, but faced a problem that I could not solve. The only working method is very slow.

+

Is there a faster way to remove duplicates than my method?

+

Code:

+

Pydantic model (a.py)

+
from pydantic import BaseModel
+
+
+class Photo(BaseModel):
+    title: str
+    url: str
+
+

Main file (b.py)

+
from collections import OrderedDict
+from a import Photo
+
+#  3 objects, 2 duplicates
+a_obj = {
+    'title': 'SOME TITLE v1',
+    'url': 'http://some.url'
+}
+b_obj = {
+    'title': 'SOME TITLE v2',
+    'url': 'http://different.url'
+}
+c_obj = {
+    'title': 'SOME TITLE v1',
+    'url': 'http://some.url'
+}
+
+#  Creating list of pydantic objects
+pd_obj_list = list()
+pd_obj_list += [Photo(**a_obj)]
+pd_obj_list += [Photo(**b_obj)]
+pd_obj_list += [Photo(**c_obj)]
+
+#  My Attempts to Remove Duplicates
+
+#  Using OrderedDict.fromkeys
+final_list_0 = list(OrderedDict.fromkeys(pd_obj_list))
+#  returns TypeError: unhashable type: 'Photo'
+
+#  Using Set
+final_list_1 = list(set(pd_obj_list))
+#  returns TypeError: unhashable type: 'Photo'
+
+#  Using enumerate
+final_list_2 = [i for n, i in enumerate(pd_obj_list) if i not in pd_obj_list[:n]]
+#  It works but too slow when I have ~10k objects in the list
+
","

Use:

+
pd_obj_list = [Photo(**a_obj), Photo(**b_obj), Photo(**c_obj)]
+final_list_0 = list(OrderedDict(((photo.title, photo.url), photo) for photo in pd_obj_list).values())
+print(final_list_0)
+
+

Output

+
[Photo(title='SOME TITLE v1', url='http://some.url'), Photo(title='SOME TITLE v2', url='http://different.url')]
+
+

If Photo is inmutable you could define __hash__ as follows:

+
from collections import OrderedDict
+
+from pydantic import BaseModel
+
+
+class Photo(BaseModel):
+    title: str
+    url: str
+
+    def __hash__(self):
+        return hash((self.title, self.url))
+
+
+#  3 objects, 2 duplicates
+a_obj = {
+    'title': 'SOME TITLE v1',
+    'url': 'http://some.url'
+}
+b_obj = {
+    'title': 'SOME TITLE v2',
+    'url': 'http://different.url'
+}
+c_obj = {
+    'title': 'SOME TITLE v1',
+    'url': 'http://some.url'
+}
+
+pd_obj_list = [Photo(**a_obj), Photo(**b_obj), Photo(**c_obj)]
+final_list_0 = list(OrderedDict.fromkeys(pd_obj_list))
+print(final_list_0)
+
+

Output

+
[Photo(title='SOME TITLE v1', url='http://some.url'), Photo(title='SOME TITLE v2', url='http://different.url')]
+
",python +"How to set hidden_layer_sizes in sklearn MLPRegressor using optuna trial

I would like to use [OPTUNA][1] with sklearn [MLPRegressor][1] model.

+

For almost all hyperparameters it is quite straightforward how to set OPTUNA for them. +For example, to set the learning rate: +learning_rate_init = trial.suggest_float('learning_rate_init ',0.0001, 0.1001, step=0.005)

+

My problem is how to set it for hidden_layer_sizes since it is a tuple. So let's say I would like to have two hidden layers where the first will have 100 neurons and the second will have 50 neurons. Without OPTUNA I would do:

+

MLPRegressor( hidden_layer_sizes =(100,50))

+

But what if I want OPTUNA to try different neurons in each layer? e.g., from 100 to 500, how can I set it? the MLPRegressor expects a tuple

","

You could set up your objective function as follows:

+
import optuna
+import warnings
+from sklearn.datasets import make_regression
+from sklearn.model_selection import train_test_split
+from sklearn.neural_network import MLPRegressor
+from sklearn.metrics import mean_squared_error
+warnings.filterwarnings('ignore')
+
+X, y = make_regression(random_state=1)
+
+X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=1)
+
+def objective(trial):
+
+    params = {
+        'learning_rate_init': trial.suggest_float('learning_rate_init ', 0.0001, 0.1, step=0.005),
+        'first_layer_neurons': trial.suggest_int('first_layer_neurons', 10, 100, step=10),
+        'second_layer_neurons': trial.suggest_int('second_layer_neurons', 10, 100, step=10),
+        'activation': trial.suggest_categorical('activation', ['identity', 'tanh', 'relu']),
+    }
+
+    model = MLPRegressor(
+        hidden_layer_sizes=(params['first_layer_neurons'], params['second_layer_neurons']),
+        learning_rate_init=params['learning_rate_init'],
+        activation=params['activation'],
+        random_state=1,
+        max_iter=100
+    )
+
+    model.fit(X_train, y_train)
+
+    return mean_squared_error(y_valid, model.predict(X_valid), squared=False)
+
+study = optuna.create_study(direction='minimize')
+study.optimize(objective, n_trials=3)
+# [I 2021-11-11 18:04:02,216] A new study created in memory with name: no-name-14c92e38-b8cd-4b8d-8a95-77158d996f20
+# [I 2021-11-11 18:04:02,283] Trial 0 finished with value: 161.8347337123744 and parameters: {'learning_rate_init ': 0.0651, 'first_layer_neurons': 20, 'second_layer_neurons': 40, 'activation': 'tanh'}. Best is trial 0 with value: 161.8347337123744.
+# [I 2021-11-11 18:04:02,368] Trial 1 finished with value: 159.55535852658082 and parameters: {'learning_rate_init ': 0.0551, 'first_layer_neurons': 90, 'second_layer_neurons': 70, 'activation': 'relu'}. Best is trial 1 with value: 159.55535852658082.
+# [I 2021-11-11 18:04:02,440] Trial 2 finished with value: 161.73980822730888 and parameters: {'learning_rate_init ': 0.0051, 'first_layer_neurons': 100, 'second_layer_neurons': 30, 'activation': 'identity'}. Best is trial 1 with value: 159.55535852658082.
+
",python +"Merge should adopt Nan values if not existing value

However, I have the following problem:

+
    +
  • If a year or date does not exist in df2 then a price and a listing_id is automatically added during the merge. But that should be NaN

    +
  • +
  • The second problem is when merging, as soon as I have multiple data that were on the same day and year then the temperature is also merged to the second, for example:

    +
  • +
+
d = {'id': [1], 'day': [1], 'temperature': [20], 'year': [2001]}
+df = pd.DataFrame(data=d)
+print(df)
+
+   id  day  temperature  year
+0   1    1           20  2001
+
+d2 = {'id': [122, 244], 'day': [1, 1],
+     'listing_id': [2, 4], 'price': [20, 440], 'year': [2001, 2001]}
+df2 = pd.DataFrame(data=d2)
+print(df2)
+
+    id  day  listing_id  price  year
+0  122    1           2     20  2001
+1  244    1           4    440  2001
+
+df3 = pd.merge(df,df2[['day', 'listing_id', 'price']],
+              left_on='day', right_on = 'day',how='left')
+print(df3)
+
+   id  day  temperature  year  listing_id  price
+0   1    1           20  2001           2     20
+1   1    1           20  2001           4    440 # <-- The second temperature is wrong :/
+
+

This should not be so, because if I later still have a date from year 2002 which was in day 1 with a temperature of 30 and I want to calculate the average. Then I get the following formula: 20 + 20 + 30 = 23.3. The formula should be 20 + 30 = 25. Therefore, if a value has already been filled, there should be a NaN value in it.

+

Code Snippet

+
d = {'id': [1, 2, 3, 4, 5], 'day': [1, 2, 3, 4, 2], 
+     'temperature': [20, 40, 50, 60, 20], 'year': [2001, 2002, 2004, 2005, 1999]}
+df = pd.DataFrame(data=d)
+print(df)
+
+   id  day  temperature  year
+0   1    1           20  2001
+1   2    2           40  2002
+2   3    3           50  2004
+3   4    4           60  2005
+4   5    2           20  1999
+
+
+d2 = {'id': [122, 244, 387, 4454, 521], 'day': [1, 2, 3, 4, 2],
+     'listing_id': [2, 4, 5, 6, 7], 'price': [20, 440, 500, 6600, 500], 
+      'year': [2001, 2002, 2004, 2005, 2005]}
+df2 = pd.DataFrame(data=d2)
+print(df2)
+
+     id  day  listing_id  price  year
+0   122    1           2     20  2001
+1   244    2           4    440  2002
+2   387    3           5    500  2004
+3  4454    4           6   6600  2005
+4   521    2           7    500  2005
+
+
+df3 = pd.merge(df,df2[['day','listing_id', 'price']],
+              left_on='day', right_on = 'day',how='left').drop('day',axis=1)
+print(df3)
+
+   id  day  temperature  year  listing_id  price
+0   1    1           20  2001           2     20
+1   2    2           40  2002           4    440
+2   2    2           40  2002           7    500
+3   3    3           50  2004           5    500
+4   4    4           60  2005           6   6600
+5   5    2           20  1999           4    440
+6   5    2           20  1999           7    500
+
+
+
+

What I want

+
   id  day  temperature  year  listing_id  price
+0   1    1           20  2001           2     20
+1   2    2           40  2002           4    440
+2   2    2          NaN  2005           7    500
+3   3    3           50  2004           5    500
+4   4    4           60  2005           6   6600
+5   5    2           20  1999         NaN    NaN
+
","

IIUC:

+
>>> df1.merge(df2[['day', 'listing_id', 'price', 'year']],
+              on=['day', 'year'], how='outer')
+
+    id  day  temperature  year  listing_id   price
+0  1.0    1         20.0  2001         2.0    20.0
+1  2.0    2         40.0  2002         4.0   440.0
+2  3.0    3         50.0  2004         5.0   500.0
+3  4.0    4         60.0  2005         6.0  6600.0
+4  5.0    2         20.0  1999         NaN     NaN
+5  NaN    2          NaN  2005         7.0   500.0
+
",python +"Button Not Adding Up
def login_button():
+    wrong_value_count = 0
+    username = username_entry.get()
+    password = password_entry.get()
+    if username == user1_username and password == user1_password:
+        redirecting_text = canvas.create_text(40, 90, text="Credentials Match, Please Wait While " 
+        "We Redirect You To Your Vault", fill="red", anchor=NW)
+        canvas.after(2500, lambda: delete_text(redirecting_text))
+        print("ESHTA")
+    elif username == user2_username and password == user2_password:
+        redirecting_text2 = canvas.create_text(40, 90, text="Credentials Match, Please Wait While " 
+        "We Redirect You To Your Vault", fill="red", anchor=NW)
+        canvas.after(2500, lambda: delete_text3(redirecting_text2))
+        print("ESHTA")
+    else:
+        wrong_value_count += 1
+        if wrong_value_count <= 3:
+            print("NOT ESHTA")
+            wrong_credentials_text = canvas.create_text(40, 90, text="Wrong Credentials, Try again",
+             fill="red", anchor=NW)
+            canvas.after(2500, lambda: delete_text2(wrong_credentials_text))
+        elif wrong_value_count > 3:
+            lock_text = canvas.create_text(40, 90, text="Sorry, You've Reached the Max Number of Trials"
+            " Please Try Again Later", fill="red", anchor=NW)
+            canvas.after(2500, lambda: delete_text4(lock_text))
+        print(wrong_value_count)
+
+

Alright, so I'm trying to add to the wrong value count, but every time I click the button, it shows that it's still 1. How do make it add up till it reaches 3 as written?

","

wrong_value_count must be outside the button because when login_button is called it resets the count to 0, which you don't want.

+
wrong_value_count = 0
+def login_button():
+    global wrong_value_count 
+    username = username_entry.get()
+    password = password_entry.get()
+    if username == user1_username and password == user1_password:
+        redirecting_text = canvas.create_text(40, 90, text="Credentials Match, Please Wait While " 
+        "We Redirect You To Your Vault", fill="red", anchor=NW)
+        canvas.after(2500, lambda: delete_text(redirecting_text))
+        print("ESHTA")
+    elif username == user2_username and password == user2_password:
+        redirecting_text2 = canvas.create_text(40, 90, text="Credentials Match, Please Wait While " 
+        "We Redirect You To Your Vault", fill="red", anchor=NW)
+        canvas.after(2500, lambda: delete_text3(redirecting_text2))
+        print("ESHTA")
+    else:
+        wrong_value_count += 1
+        if wrong_value_count <= 3:
+            print("NOT ESHTA")
+            wrong_credentials_text = canvas.create_text(40, 90, text="Wrong Credentials, Try again",
+             fill="red", anchor=NW)
+            canvas.after(2500, lambda: delete_text2(wrong_credentials_text))
+        elif wrong_value_count > 3:
+            lock_text = canvas.create_text(40, 90, text="Sorry, You've Reached the Max Number of Trials"
+            " Please Try Again Later", fill="red", anchor=NW)
+            canvas.after(2500, lambda: delete_text4(lock_text))
+        print(wrong_value_count)
+
",python +"python request to get html page is missing the article element contents

im trying to record data from this website using python , but the data that i get is missing the "dashboard" data , +the article element containing it comes back empty , +like this :

+
<article id="dashboard"></article>
+
+

im making a request like this :

+
import requests
+page = requests.get(url)
+
+

how can i get the data in the website consistently and quickly ?

","

What you're seeing here is a javscript+web-socket driven web-app.

+

When you connect to the page javascript starts a websocket connection to server is established that constantly sends the data to the javascript client. Then the client unpacks it to html content that you see.

+

If you fire up a web inspector you can see this web socket connection open:

+

+

Now how do we replicate this in a scraper?

+

We need a websocket client and send those green messages to start receiving the data you want. For example websocket-client package we can do:

+
from websocket import create_connection
+ws = create_connection("wss://bitcoin.clarkmoody.com/dashboard/ws")
+
+# replicate the green messages
+ws.send("""{"op":"c","ch":"","pl":{"c":"4de43be4236035c5","s":"9f6e08f07c263998"}}""")
+ws.send("""{"op":"sub","ch":"mod"}""")
+ws.send("""{"op":"sub","ch":"sta"}""")
+ws.send("""{"op":"sub","ch":"sys"}""")
+ws.send("""{"op":"sub","ch":"upd"}""")
+
+# then you can start receiving the data
+
+while True:
+    print(ws.recv())
+
+

Now it's up to you to figure out the rest of reverse-engineering. For the initial messages it seems to be some sort of subscription (op: sub, ch:upd probably means operation subscribe channel UPD). Either way the above script should output this as first response message then continue spewing price adjustments:

+
{"op":"dat","ch":"mod","pl":[{"rows":[{"slug":"p-row","cells":[{"type":"label","slug":"p-label","quiet":true,"label":"Price"},{"type":"price","slug":"p","def":"Market price of Bitcoin","sep":true,"unit":"$","prefix":true,"places":2}]},{"slug":"sd-row","cells":[{"type":"label","slug":"sd-label","quiet":true,"label":"Sats per Dollar"},{"type":"integer","slug":"sd","def":"Value of one US Dollar, expressed in Satoshis","sep":true,"places":0}]},{"slug":"c-row","cells":[{"type":"label","slug":"c-label","quiet":true,"label":"Market Capitalization"},{"type":"price","slug":"c","def":"Product of market price times total mined supply","sep":true,"unit":"$","prefix":true,"places":2}]}],"slug":"markets","name":"Markets","order":10,"help":"Bitcoin spot price and futures information","feature":false,"headless":false},{"rows":[{"slug":"links-row","noInfo":true,"cells":<..TOO LONG FOR SO..>
+
",python +"pygame - rects collision detection issue

I'm learning pygame and I have an issue with detection of rect's collisions. I'm using colliderect() function now but it works only when rects overlap, and the question is "How to detect even edges collisions?". General comments about the whole are welcome. First post btw.

+

Here is my code:

+
import pygame
+
+
+#####SETTINGS#####
+HEIGHT = 1080
+WIDTH = 1920
+BLOCK_SIZE = 60
+##################
+
+
+class Level():
+    def __init__(self, file):
+        self.file = file
+        self.blocks = []
+        self.map = self.load_from_file()
+
+    def load_from_file(self):
+        map = []
+        file = open(self.file + '.txt', 'r')
+        data = file.read()
+        file.close()
+        data = data.split('\n')
+        for x in data:
+            map.append(list(x))
+        return map
+     
+    def render(self, screen):
+        self.blocks = []
+        y = 0
+        for row in self.map:
+            x = 0
+            for block in row:
+                if block != '0':
+                    self.blocks.append(pygame.Rect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
+                    if block == '1':
+                        pygame.draw.rect(screen, (56,24,0), (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
+                    elif block == '2':
+                        pygame.draw.rect(screen, (18,115,81), (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
+                x += 1
+            y += 1
+
+
+class Player():
+    def __init__(self, x, y, color):
+        self.x = x
+        self.y = y
+        self.color = color
+        self.rect = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
+        self.go_left = False
+        self.go_right = False
+        self.go_up = False
+        self.go_down = False
+        self.collisions = {'left' : False, 'right' : False, 'top' : False, 'bottom' : False}
+
+    def move(self):
+        self.collisions = test_collisions(self.rect, level.blocks) 
+        if self.go_left and not self.collisions['left']:
+            self.x -= 10
+            self.go_left = False
+        if self.go_right and not self.collisions['right']:
+            self.x += 10
+            self.go_right = False
+        if self.go_up and not self.collisions['top']:
+            self.y -= 10
+            self.go_up = False
+        if self.go_down and not self.collisions['bottom']:
+            self.y += 10
+            self.go_down = False
+        self.rect = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
+
+    def render(self, screen):
+        pygame.draw.rect(screen, self.color, self.rect)
+
+
+def render(screen, player, level):
+    screen.fill((49, 113, 181))
+    level.render(screen)
+    player.render(screen)
+    pygame.display.update()
+
+
+def handle_events(player):
+    for event in pygame.event.get():
+        if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+            run = False
+            pygame.quit()
+    keys = pygame.key.get_pressed()
+    if keys[pygame.K_a]:
+        player.go_left = True
+    if keys[pygame.K_d]:
+        player.go_right = True
+    if keys[pygame.K_w]:
+        player.go_up = True
+    if keys[pygame.K_s]:
+        player.go_down = True
+
+
+def test_collisions(object, rects):
+    collisions = {'left' : False, 'right' : False, 'top' : False, 'bottom' : False}
+    for rect in rects:
+        if object.colliderect(rect):
+            if object.x <= rect.x:
+                collisions['right'] = True
+            if object.x >= rect.x:
+                collisions['left'] = True
+            if object.y >= rect.y:
+                collisions['top'] = True
+            if object.y <= rect.y:
+                collisions['bottom'] = True
+    return(collisions)
+
+    
+def main_loop():
+    clock = pygame.time.Clock()
+    while run:
+        clock.tick(60)
+        handle_events(player)
+        player.move()
+        render(screen, player, level)
+
+
+if __name__ == "__main__":
+    run = True
+    screen = pygame.display.set_mode((WIDTH, HEIGHT))
+    level = Level('assets/level_one')
+    player = Player(0,0,(255,255,0))
+    main_loop()
+
+

And here is level_one.txt file content:

+
00000000000000000000000000000000
+00000000000000000000000000000000
+00000000000000000000000000000000
+00000000000000000000000000000000
+00000000000000000000000000000000
+00000000000000000000000000000000
+00000000000000002222222222200000
+00000000000000000000000000000000
+00000000000000000000000000000000
+00022222222200000000000000000000
+00000000000000000000000000000000
+00000000000000000000000000000000
+22222222222222222222222222222222
+11111111111111111111111111111111
+11111111111111111111111111111111
+11111111111111111111111111111111
+11111111111111111111111111111111
+11111111111111111111111111111111
+
","

You can enlarge the rectangles for the collision detection with [pygame.Rect.inflate`](builtins.TypeError: argument 1 must be pygame.Surface, not function). e.g.:

+
if object.colliderect(rect.inflate(1, 1)):
+    # [...]
+
",python +"concat lines from several .txt file using python?

Im using python 3.6 on windows 10, i have a task to take data from 1.txt and concat them with some string and put the results on 2.txt file .

+

this is my code:

+
full_url = "https://mysite/images/pic_person/small/"
+
+#file read from
+pic_name = open("test.txt","r")
+#file write to it 
+full_name = open("full_name.txt","a")
+while True:
+    line = pic_name.readline()
+    link = line+full_url
+    print(link)
+    full_name.write(link)
+    if ("" == line):
+        print("file finished")
+        break;
+pic_name.close()
+full_name.close()
+
+

after executing the code it gives me this result:

+
+
p100003.jpg
+https://mysite/images/pic_person/small/p100026.jpg
+https://mysite/images/pic_person/small/p100951.jpg
+https://mysite/images/pic_person/small/p100970.jpg
+https://mysite/images/pic_person/small/p101144.jpghttps://mysite/images/pic_person/small/https://mysite/images/pic_person/small/
+
+
+

and except results will be like this :

+
+
https://mysite/images/pic_person/small/p100026.jpg
+https://mysite/images/pic_person/small/p100951.jpg
+https://mysite/images/pic_person/small/p100970.jpg
+https://mysite/images/pic_person/small/p101144.jpg
+
+
+

the file test.txt contains these lines :

+
p100026.jpg
+p100951.jpg
+p100970.jpg
+p101144.jpg
+
","

to append file on the bottom you need to use 'a' flag in the open file and put "\n" as enter

+
full_url = "https://mysite/images/pic_person/small/"
+
+# file read from test.txt
+f = open("test.txt", "r")
+
+# iterating each file on pict and write it
+with open("text2.txt", "a") as file_object:
+    for item in f:
+        file_object.write(full_url+item.splitlines()[0]+"\n")
+
+f.close()
+
",python +"PyQt6: app shows permanetly Gnome taskbar

Running a simple PyQt6 app Gnome desktop environment shows the taskbar permanently:

+

+

OS information:

+
+Distributor ID: Kali 
+
+Description: Kali GNU/Linux
+
+Rolling Release: 2021.3
+
+Codename: kali-rolling
+
+

Code:

+
import sys
+from PyQt6.QtWidgets import QApplication, QWidget
+
+
+def main():
+
+    app = QApplication(sys.argv)
+
+    w = QWidget()
+    w.resize(250, 200)
+    w.move(300, 300)
+
+    w.setWindowTitle('Simple')
+    w.show()
+
+    sys.exit(app.exec())
+
+
+if __name__ == '__main__':
+    main()
+
+

How can this behaviour be prevented?

","

I observed this is normal behaviour on any application when the window is not maximized. When I maximize, the taskbar disappears.

",python +"Pandas: Determine if columns are matched

I'm trying to eliminate all rows that match in col0 and col1, but don't have a pair of -1, 1 between rows (for example in the dataframe below there isn't a a2, b1, -1 row). I was trying to come up with someway to do this, but was groupby and getting multiindex and not getting anywhere...

+
#   no a2, b1, -1
+df = pd.DataFrame([
+    ['a1', 'b1', -1, 0/1],
+    ['a1', 'b1',  1, 1/1],
+    ['a1', 'b2', -1, 2/1],
+    ['a1', 'b2',  1, 1/2],
+    ['a2', 'b1',  1, 1/3],
+    ['a2', 'b2', -1, 2/3],
+    ['a2', 'b2',  1, 4/1]
+], columns=['col0', 'col1', 'col2', 'val'])
+
+# desired output
+# a1, b1, -1, 0.0
+# a1, b1,  1, 1.0
+# a1, b2, -1, 2.0
+# a1, b2,  1, 0.5
+# a2, b2, -1, 0.66667
+# a2, b2,  1, 4.0
+
","

We can use groupby filter to test if there are at least 1 (any) of each value (-1 and 1) per group with Series.any:

+
result_df = df.groupby(['col0', 'col1']).filter(
+    lambda x: x['col2'].eq(-1).any() and x['col2'].eq(1).any()
+)
+
+

result_df:

+
  col0 col1  col2       val
+0   a1   b1    -1  0.000000
+1   a1   b1     1  1.000000
+2   a1   b2    -1  2.000000
+3   a1   b2     1  0.500000
+5   a2   b2    -1  0.666667
+6   a2   b2     1  4.000000
+
",python +"How to generate a line plot for data in column on condition of data in 2 other columns

In my df I have 4 columns. The 1st two describe test conditions. Columns 3 & 4 are test data. Column 3 data is my fixed x axis data. I want a line overlay plot with legend for my Column 4 INL data, y axis data, for conditions based in Column 1 & 2. +The below code shows an example df. I can Group test_no and temperature columns to get min/max data from the INL data for the values of the group data that I want. I can't use the same group set-up to plot INL data for test_no=0,1 & Temperature=25,50. How can I achieve this? Thanks

+
import pandas as pd
+
+import matplotlib.pyplot as plt
+
+data = {'Test_no': [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1], 'Temperature': [25, 25, 25, 25, 50, 50, 50, 50, 25, 25, 25, 25, 50, 50, 50, 50], 'Codes': [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,], 'INL':[0,1.1,-0.9,0, 0,1.0,-0.8,0, 0,0.9,-0.7,0, 0,1.2,-0.6,0]}
+
+df = pd.DataFrame(data)
+
+groups = df.groupby(['Test_no','Temperature'])
+
+#group data and get min,max,mean per Col1/2 group
+
+result = groups.agg({'INL': ['min', 'max', 'mean']})
+print(result)
+
+#Plot data per Col1/2 group (start with C1:0,C2:25)
+
+d = df.loc[df["Temperature"] == 25]
+
+d = df.loc[df["Test_no"] == 0]
+
+d['INL'].plot()
+
+
","

I am relatively new to python but I was able to resolve my issue using the groupby() function to split the data into the groups that I required and then use matplotlib.pyplot to index and plot each group of data. +I'm sure there are more efficient solutions but this works! +Using the same DF as I used in the question I added the below code:

+
Tests = [g for _, g in df.groupby(['Test_no','Temperature'])]
+
+plt.plot(Tests[0].Codes, Tests[0].INL, label='T0 25C') 
+plt.plot(Tests[1].Codes, Tests[1].INL, label='T0 50C') 
+plt.plot(Tests[2].Codes, Tests[2].INL, label='T1 25C') 
+plt.plot(Tests[3].Codes, Tests[3].INL, label='T1 50C')
+
+plt.xlabel("Codes") 
+plt.ylabel("INL") 
+plt.title("INL Data")
+plt.legend() 
+plt.show()
+
+
+

Or you can use a more compact code to plot:

+
for (n, temp), Test in df.groupby(['Test_no','Temperature']):
+    plt.plot(Test.Codes, Test.INL, label=f"T{n} {temp}C")
+
",python +"Why does python's SharedMemory seem to initialize arrays to zeros

I'm initializing a SharedMemory in python to be shared between multiple processes and I've noticed that it always seems to be filled with zeros (which is fine), but I don't understand why this is occurring as the documentation doesn't state there is a default value to fill the memory with.

+

This is my test code, opened in two seperate power shells, shell 1:

+
import numpy as np
+from multiprocessing.shared_memory import SharedMemory
+def get_array_nbytes(rows, cols, dtype):
+    array = np.zeros((rows, cols), dtype=dtype)
+    nbytes = array.nbytes
+    del array
+    return nbytes
+
+rows = 10000000
+depths_columns = 18
+array_sm = SharedMemory(create=True, size=get_array_nbytes(rows, depths_columns, np.float32), name='array_sm')
+
+

shell 2:

+
from multiprocessing.shared_memory import SharedMemory
+import numpy as np
+array_sm = SharedMemory("depths_array")
+array = np.ndarray((rows, 18), dtype=np.float32, buffer=array_sm.buf)
+
+

now in the second shell you can follow this up with:

+
array[0]
+array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+       0.], dtype=float32)
+
+

or

+
np.where(array != 0)
+(array([], dtype=int64), array([], dtype=int64))
+
+

Is this behavior always going to be the case or is this a fluke? Is there some sort of undocumented initialization to zero happening in the background?

","

This is operating system dependent. Python doesn't initialize the memory - it just takes the virtual memory address offered by the operating system. On posix systems it uses shm_open, while on Windows its CreateFileMapping. On linux and windows, these calls guarantee that memory is initialized to zero.

+

It would be a security leak to let the application see whatever left over data happens to be in the RAM from the previous user, so it needs to be filled with something. But this isn't a guarantee from python and its possible that some operating systems (embedded OS perhaps) don't do things that way.

",python +"How to pass cards to another player and so on. Say P1 draws 4 of clubs, how do I pass to P2

I'm assuming I would want to put it under the Player class where I've started, but no matter what I've done I don't understand how to go about it. I'd prefer to be pointed in the right direction as opposed to just giving me code.

+
import random
+
+class Card(object):
+    def __init__(self, suit, val):
+        self.suit = suit
+        self.value = val
+
+    def show(self):
+        print("{} of {}".format(self.value, self.suit))
+
+class Deck(object):
+    def __init__(self):
+        self.cards = []
+        self.build()
+#suits of the cards
+    def build(self):
+        for s in ["Spades", "Clubs", "Diamonds", "Hearts"]:
+            for v in range(1, 14):
+                self.cards.append(Card(s, v))
+
+    def show(self):
+        for c in self.cards:
+            c.show()
+
+#shuffle the deck
+    def shuffle(self):
+        for i in range(len(self.cards)-1, 0, -1):
+            r = random.randint(0, i)
+            self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
+
+    def draw(self):
+        return self.cards.pop()
+
+class Player(object):
+
+    def __init__(self):
+       self.hand = []
+
+#draw cards
+    def draw(self, deck):
+        self.hand.append(deck.draw())
+        return self
+
+#show the cards in the players hand
+    def showHand(self):
+        for card in self.hand:
+            card.show()
+
+#Pass card to next player
+    def passCard(self):
+        self.hand.pop()
+
+
+deck = Deck()
+deck.shuffle()
+
+bob = Player()
+bob.draw(deck).draw(deck).draw(deck).draw(deck)
+bob.showHand()
+
","

I would have two methods in the player class:

+
# In Python, prefer snake_case over camelCase
+def give_card(self, index):
+    return self.hand.pop(index)
+
+def take_card(self, card):
+    self.hand.append(card)
+
+

And then anytime you want to pass one card from one player to another, you would do something like:

+
player_2.take_card(player_1.give_card(0))
+
",python +"numpy array with inequality sign?
mask = np.stack([robject_mask, rshadow_mask, mask], axis=1).astype('float')   
+   
+    mask[mask >= 128] = 255
+    mask[mask < 128] = 0
+
+

i'm practicing making attention network with pytorch, and i have a question in the code. i think it's about normalizing images to [-1,1], but i cannot understand what it exactly means. anyone know what is this operation's name? what does it mean? or maybe giving me a keyword that i can search?

","

You're question is not clear, but I'll try explaining what's going on.

+
mask >= 128
+
+

Will output an array of the form of [True, True, False, ...] each true correspond to an index where mask had a value greater than 127.

+

Then mask[mask >= 128] means any index of mask where the inner array had true in it. Same goes for < 128 just the opposite.

+

In the end of the proccess, mask will contain either 255 or 0 in each index, depending if the value prior to it was greater than 128 or not.

",python +"Pandas: Most computationally efficient way to combine consecutive rows with conditions

Say I have dataframe like this

+
df = pd.DataFrame({
+'position': ['head', 'tail', 'head', 'head', 'head', 'tail', 'tail', 'head'], 
+        'start': [2, 13, 54, 320, 654, 677, 3430, 9000],
+        'end': [4, 15, 564, 390, 674, 679, 6000, 9010],
+    })        #s.  e.   k    k.   s.        e.    k 
+df.head(10)
+
+

+  position  start   end
+0     head      2     4
+1     tail     13    15
+2     head     54   564
+3     head    320   390
+4     head    654   674
+5     tail    677   679
+6     tail   3430  6000
+7     head   9000  9010
+
+

I want to combine rows such that if the position label if the row is 'head' and then consecutive position is 'tail', then those rows should be combined in such a way that the 'start' value from 'head' is used, and 'end' value of 'tail' is used. And there are multiple consecutive 'tail' rows that follow a 'head' row, then the middle 'tail' rows will be skipped.

+

It's tricky to explain, but here's an example dataframe of what the desired result should look like

+
    position    start   end
+0   tail            2    15
+1   head           54   564
+2   head          320   390
+3   tail          654   6000
+4   head         9000   9010
+
+

I came up with this solution using iterrows

+
previous = None
+list_dicts = []
+for idx, row in df.iterrows():
+    if row['position'] == 'head':
+        if previous:
+            package = {'position': previous, 'start':previous_start, 'end':previous_end}
+            list_dicts.append(package)
+        previous = 'head'
+        previous_start = row['start']
+        previous_end = row['end']
+    elif row['position'] == 'tail':
+        previous = 'tail'
+        previous_start = previous_start
+        previous_end = row['end']
+if row['position'] == 'head':
+    package = {'position': row['position'], 'start':row['start'], 'end':row['end']}
+elif row['position'] == 'tail':
+    package = {'position': row['position'], 'start':previous_start, 'end':row['end']}
+list_dicts.append(package)
+
+pd.DataFrame(list_dicts).head(10)
+
+

But I have read that iterrows should be avoided because it's not the most computationally efficient way to manipulate dataframes. And in this case, I am resorting to creating a brand new dataframe. But in the case of using conditionals based on consecutive rows, it's the only solution I can think of.

","

One way using pandas.groupby:

+
m = df["position"].eq("head").cumsum()
+new_df = df.groupby(m, as_index=False).agg({"position": "last", 
+                                            "start": "first", 
+                                            "end": "last"})
+print(new_df)
+
+

Output:

+
  position  start   end
+0     tail      2    15
+1     head     54   564
+2     head    320   390
+3     tail    654  6000
+4     head   9000  9010
+
",python +"output from bert gives str not tensor in forward function
class BertModel(nn.Module):
+    def __init__(self,pre_trained='bert-base-uncased'):
+        super().__init__()        
+        self.bert = AutoModel.from_pretrained(pre_trained)
+        self.dropout = nn.Dropout(0.1)
+        self.relu =  nn.ReLU()
+        self.fc1 = nn.Linear(768,512)
+        self.fc2 = nn.Linear(512,6)
+      
+    
+        
+    def forward(self,inputs, mask, labels):
+        
+        pooled, cls_hs = self.bert(input_ids=inputs,attention_mask=mask)
+        print(pooled)
+        print(cls_hs)  
+        print(inputs) 
+        print(mask)   
+        x = self.fc1(cls_hs)
+        print(1) 
+        x = self.relu(x)
+        print(2) 
+        x = self.dropout(x)
+        print(3) 
+      # output layer
+        x = self.fc2(x)
+        print(4)
+      # apply softmax activation
+        x = self.softmax(x)
+        print(5)
+
+
+

last_hidden_state +pooler_output

+
+
+

tensor([[ 101, 2342, 2393, ..., 0, 0, 0], +[ 101, 14477, 4779, ..., 4839, 6513, 102], +[ 101, 14777, 2111, ..., 13677, 3613, 102], +..., +[ 101, 2113, 14047, ..., 0, 0, 0], +[ 101, 5683, 3008, ..., 0, 0, 0], +[ 101, 19046, 2075, ..., 2050, 3308, 102]]) +tensor([[1, 1, 1, ..., 0, 0, 0], +[1, 1, 1, ..., 1, 1, 1], +[1, 1, 1, ..., 1, 1, 1], +..., +[1, 1, 1, ..., 0, 0, 0], +[1, 1, 1, ..., 0, 0, 0], +[1, 1, 1, ..., 1, 1, 1]])

+
+

in linear(input, weight, bias) +if has_torch_function_variadic(input, weight, bias): +return handle_torch_function(linear, (input, weight, bias), input, weight, +bias=bias) +return torch._C._nn.linear(input, weight, bias)

+

TypeError: linear(): argument 'input' (position 1) must be Tensor, not str

+
+

pooled, cls_hs printed as string last_hidden_state, pooler_output tensor +with out any tensor

+
","

Try to replace the line where you downloaded the pretrained bert model with:

+
self.model = AutoModel.from_pretrained(pre_trained, return_dict=False)
+
",python +"How to group a list into a dataframe with four columns?

Let's assume I have a list similar to the one below:

+
l = ['A','B','C','D','E','F','G','H','I','L','M','N']
+
+
+

I want to create a dataframe that has 4 columns from the fact that every 4 objects in the list is a row. The outcome should be a dataframe with the following form:

+
Col1   Col2   Col3   Col4
+
+  A     B       C     D
+  
+  E     F       G     H
+
+  I     L       M      N
+
+

Can anyone help me do it?

+

Thanks!

","

Convert values to numpy array and then use reshape:

+
l = ['A','B','C','D','E','F','G','H','I','L','M','N']
+df = pd.DataFrame(np.array(l).reshape(-1, 4)).add_prefix('col')
+print(df)
+  col0 col1 col2 col3
+0    A    B    C    D
+1    E    F    G    H
+2    I    L    M    N
+
",python +"Web-scraping with python3.9 with a Load more button

I am very new to python. I am trying to extract the full list of countries + districts from this website : +https://www.expo2020dubai.com/en/understanding-expo/participants/country-pavilions

+

To get the full list, there is a javascript Load More button. The URL doesn't change when clicking on LOAD MORE Button.

+Mobility

+Albania Pavilion

+

I want to extract the District that is on the "content__subtitle" class and the Country that is on the "content__title" class.

+

Here is my full script. I can extract from the first page but I don't know how to get the other pages.

+

Also, I am writing the result to a CSV file but for some reason nothing is written with my code.

+
import requests
+from pprint import pprint
+from bs4 import BeautifulSoup
+import csv
+
+url = "https://www.expo2020dubai.com/en/understanding-expo/participants/country-pavilions"
+
+liste = []
+
+def extract_pavillons(url):
+    r = requests.get(url)
+    soup = BeautifulSoup(r.content, 'html.parser')
+
+    with open('pavillons.csv', 'w', encoding='UTF8') as f:
+        for item in soup.find_all(class_=["c-innovator-card -filter-list","c-innovator-card__container"]):
+            country = item.find(class_='content__title').text
+            country = country[:len(country) - 9]
+            district = item.find(class_='content__subtitle').text
+
+            liste.append([country, district])
+
+
+def write_pavillons(liste):
+    with open('pavillons.csv', 'w', newline='') as f:
+        writer = csv.writer(f)
+        writer.writerows(liste)
+
+extract_pavillons(url)
+
+write_pavillons(liste)
+
","

Option I

+

Use their api -> developer tools xhr requests:

+

https://www.expo2020dubai.com/api/CardFilter/CardFilterLoadMore?ds=%7B1D599577-83BF-4AD3-ADDF-8409AC9CC359%7D&currentCount=8&LoadMoreCount=8&filters=%2C%2C&typeCategory=Country%2C&pageItemId=%7B91F63910-2B2D-45B7-BAA0-9338BBB101C7%7D&_=1636012101921

+

With parameter currentCount and LoadMoreCount you can fetch additional items.

+

Option II

+

Use selenium to click on the button and grab the next items

",python +"How to transition from M2M created with 'through' to a M2M managed by Django

I'm working in a Project where there were multiple fields created as M2M using the through related model, however they were wrongly created by then and the related models have no additional fields, so I would like to use a regular M2M managed by Django.

+

The existing models I have are:

+
cass Student(models.Model):
+    # ... other fields..."
+    courses = models.ManyToManyField(
+        Course,
+        related_name='students',
+        through='StudentCourse'
+    )
+
+class StudentCourse(models.Model):
+    student = models.ForeignKey(Student, on_delete=models.CASCADE)
+    course = models.ForeignKey(Course, on_delete=models.CASCADE)
+
+cass Course(models.Model):
+    # ... other fields..."
+
+
+

And I would like to have:

+
class Student(models.Model):
+    # ... other fields..."
+    course = models.ManyToManyField(Course, related_name='students')
+
+class Course(models.Model):
+    # ... other fields..."
+
+

I'm not able to find a way in Django to do this without losing the data that was already inserted.

+

I was thinking of renaming the tables in the same way Django does and manipulate the Django migration metadata but it is an ugly way to solve it.

+

Is there a Django way to solve this without losing the data (or creating backup tables)?

","

To do this you need to create a migration file that copies the data from the old through table to the new one.

+

First create an empty migration file that will be populated with our migration operations

+
python manage.py makemigrations <app> --empty
+
+

Then that migration needs to be populated with the following (<app> should be replaced with the app name of the app)

+
from django.db import migrations, models
+
+
+def move_courses(apps, schema_editor):
+    Student = apps.get_model('<app>', 'Student')
+    StudentCourse = apps.get_model('<app>', 'StudentCourse')
+    for student in Student.objects.all():
+        student.courses.set(
+            StudentCourse.objects.filter(student=student).values_list('course', flat=True)
+        )
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('<app>', '<XXXX_previous_migration_name>'),
+    ]
+
+    operations = [
+        # Remove the old ManyToManyField
+        # This won't delete the through table or it's data
+        migrations.RemoveField(
+            model_name='Student',
+            name='courses',
+        ),
+        # Add the new ManyToManyField
+        migrations.AddField(
+            model_name='Student',
+            name='courses',
+            field=models.ManyToManyField(related_name='students', to='<app>.Course'),
+        ),
+        # Run a script that copies data from the old through table to the new one
+        migrations.RunPython(move_courses),
+        # Delete the old through table
+        migrations.DeleteModel(
+            name='StudentCourse',
+        ),
+    ]
+
+

Then update your models in the way you like:

+
class Student(models.Model):
+    # ... other fields..."
+    courses = models.ManyToManyField(
+        Course,
+        related_name='students',
+    )
+
+# Since through='StudentCourse' was removed, below is removed to (keeping it as comment to represent the removal)
+# class StudentCourse(models.Model):
+#    student = models.ForeignKey(Student, on_delete=models.CASCADE)
+#    course = models.ForeignKey(Course, on_delete=models.CASCADE)
+
+class Course(models.Model):
+    # ... other fields..."
+
+
+

After models and the empty created migration is updated, you can run migrate

+
python manage.py migrate
+
+

Important: don't run makemigrations again, only migrate in order for Django to run the migration that moves the data.

",python +"How to include $id fields in Pydantic.schema()

According to json-schema.org, it is best practice to include the $id field with objects.

+

I'm struggling with how to get this at the top level, for example;

+
class MySchema(BaseModel):
+
+    id: str = Field(default="http://my_url/my_schema.json", alias="$id")
+
+
+if __name__ == '__main__':
+    pprint(MySchema.schema())
+
+

yields

+
{'properties': {'$id': {'default': 'http://my_url/my_schema.json',
+                        'title': '$Id',
+                        'type': 'string'}},
+ 'title': 'MySchema',
+ 'type': 'object'}
+
+

How do I get $id at the top level, with title and type, not as a nested property?

","

Pydantic provides a number of ways of schema customization. For example, using schema_extra config option:

+
from pydantic import BaseModel
+
+
+class Person(BaseModel):
+    name: str
+    age: int
+
+    class Config:
+        schema_extra = {
+            '$id': "my.custom.schema"
+        }
+
+
+print(Person.schema_json(indent=2))
+
+

Output:

+
{
+  "title": "Person",
+  "type": "object",
+  "properties": {
+    "name": {
+      "title": "Name",
+      "type": "string"
+    },
+    "age": {
+      "title": "Age",
+      "type": "integer"
+    }
+  },
+  "required": [
+    "name",
+    "age"
+  ],
+  "$id": "my.custom.schema"
+}
+
",python +"How to define the include & lib path when building pybind11 proj

I am building a pybind11 project with Visual Studio (2017). The setup file is like below:

+

+from setuptools import setup, Extension
+import pybind11
+
+# The following is for GCC compiler only.
+#cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
+cpp_args = []
+
+sfc_module = Extension(
+    'test_sample',
+    sources=['Test.cpp'],
+    include_dirs=[pybind11.get_include()],
+    language='c++',
+    extra_compile_args=cpp_args,
+    )
+
+setup(
+    name='test_sample',
+    version='1.0',
+    description='Python package with Test C++ extension (PyBind11)',
+    ext_modules=[sfc_module],
+)
+
+
+

Then in the windows power shell, I will run

+
+

python setup.py build

+
+

However it complains cannot find multiple include files, I believe it will complain about missing library files later too:

+
C:\VS2017Pro\VC\Tools\MSVC\xxxx\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Anaconda3_CS\lib\site-packages\pybind11\include -IC:\Anaconda3_CS\include -IC:\Anaconda3_CS\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\ATLMFC\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\include /EHsc /TpCppPython.cpp /Fobuild\temp.win-amd64-3.7\Release\Test.obj
+Test.cpp
+
+Z:\test_pybind11\stdafx.h(8): fatal error C1083: Cannot open include file: 'targetver.h': No such file or directory
+
+

I know where this targetver.h is, just don't know how to add its location to the include path.

+

Your help will be greatly appreciated.

","

I know where to add more include paths, and the lib paths. One need to add them in the system environment variables: INCLUDE and LIB. +Control Panel->Edit Environment Variable. Then add all the intended paths for include files to the variable INCLUDE, and add all the library paths to the variable LIB. +Then the rebuild should be successful.

",python +How to install two python versions in one computer

I have Python 3.10 (64-bit) on my computer. And I use VS Code. I need to install Python 3.8 (64-bit) because I need to work with curses and it only works with Python 3.8.

,"

For that, you can use virtual environments for example using Conda.

+
    +
  1. Create a virtual environment for python 3.8. In the project folder run the following command
  2. +
+
    conda create --name "your-desired-environment-name" python="python-version"
+
+

e.g. to create a virtual environment for Python 3.8, run

+
   conda create --name env_python3.8 python=3.8
+
+
    +
  1. Activate the created environment
  2. +
+
    conda activate env_python3.8
+
+

Then, in visual studio Code, you can easily switch from a virtual environment to another. That depends on the project that you are working on.

+

The following How-to guide from VS Code can also be helpful.

",python +"Shift multiple daily value columns forward by one year in Pandas

Given a dataframe df as follows:

+
import pandas as pd
+import numpy as np
+
+np.random.seed(2021)
+dates = pd.date_range('20130101', periods=720)
+df = pd.DataFrame(np.random.randint(0, 100, size=(720, 3)), index=dates, columns=list('ABC'))
+df
+
+

Out:

+
             A   B   C
+2013-01-01  85  57   0
+2013-01-02  94  86  44
+2013-01-03  62  91  29
+2013-01-04  21  93  24
+2013-01-05  12  70  70
+         ..  ..  ..
+2014-12-17  38  42  20
+2014-12-18  67  93  47
+2014-12-19  27  10  74
+2014-12-20  18  92  62
+2014-12-21  90  40  31
+
+

How could I shift column B and C forward by one year? Thanks. Please note leap year issue.

+

The code below seems works for example data, but for real data with NaNs inside B and C, it generates: ValueError: cannot reindex from a duplicate axis:

+
df[['B', 'C']] = df[['B', 'C']].shift(freq=pd.DateOffset(years=1))
+print(df)
+
+

Out:

+
             A     B     C
+2013-01-01  85   NaN   NaN
+2013-01-02  94   NaN   NaN
+2013-01-03  62   NaN   NaN
+2013-01-04  21   NaN   NaN
+2013-01-05  12   NaN   NaN
+         ..   ...   ...
+2014-12-17  38  33.0  79.0
+2014-12-18  67  24.0  53.0
+2014-12-19  27  54.0  39.0
+2014-12-20  18  68.0  80.0
+2014-12-21  90  65.0  65.0
+
","

Code below seems works:

+
df[['B', 'C']] = df[['B', 'C']].shift(freq=pd.DateOffset(years=1))
+print(df)
+
+

Out:

+
             A     B     C
+2013-01-01  85   NaN   NaN
+2013-01-02  94   NaN   NaN
+2013-01-03  62   NaN   NaN
+2013-01-04  21   NaN   NaN
+2013-01-05  12   NaN   NaN
+         ..   ...   ...
+2014-12-17  38  33.0  79.0
+2014-12-18  67  24.0  53.0
+2014-12-19  27  54.0  39.0
+2014-12-20  18  68.0  80.0
+2014-12-21  90  65.0  65.0
+
",python +"Python Datetime Timezone Shift

I have a time string disseminated from a MQTT broker that I would like to read and convert from its native timezone (U.S. Central Time) to Coordinated Universal Time (UTC). I am currently using Python 3.8.5 in Ubuntu 20.04 Focal Fossa, with the machine timezone set to UTC.

+

The time string is as follows: 1636039288.815212

+

To work with this time in Python, I am using a combination of the datetime and pytz libraries. My current core of code is as follows:

+
from datetime import datetime, timedelta
+import pytz
+
+input = 1636039288.815212
+srctime = datetime.fromtimestamp(input, tz=pytz.timezone('US/Central'))
+
+

After running this chunk, I receive the following undesired time output:

+
datetime.datetime(2021, 11, 4, 10, 21, 28, 815212, tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST>)
+
+

It appears that despite explicitly defining 'US/Central' inside the initial timestamp conversion, 5 hours were subsequently subtracted the initial time provided.

+

What additional steps/alterations can I make to ensure that the initial time provided is unchanged, defined as US/Central, and that I can subsequently change to UTC?

","

Python's fromtimestamp assumes that your input is UNIX time, which should refer to 1970-01-01 UTC, not some arbitrary time zone. If you encounter such a thing nevertheless (another epoch time zone), you'll need to set UTC and then replace the tzinfo:

+
from datetime import datetime
+from dateutil import tz # pip install python-dateutil
+
+ts = 1636039288.815212
+
+dt = datetime.fromtimestamp(ts, tz=tz.UTC).replace(tzinfo=tz.gettz("US/Central"))
+
+print(dt)
+# 2021-11-04 16:21:28.815212-05:00
+
+# or in UTC:
+print(dt.astimezone(tz.UTC))
+# 2021-11-04 20:21:28.815212+00:00
+
+

Note that I'm using dateutil here so that the replace operation is safe. Don't do that with pytz (you must use localize there). Once you upgrade to Python 3.9 or higher, use zoneinfo instead, so you only need the standard library.

",python +"Get specific value from function

i was trying to do this:

+
def get_sum_col(col):
+    val = ""
+    cont = ""
+    for x in range(1, mxrw1):
+        if type(ws_Sheet1.cell(row=x, column=col).value) == int or type(
+                ws_Sheet1.cell(row=x, column=col).value) == float:
+            if val == "":
+                cont = 1
+                val = ws_Sheet1.cell(row=x, column=col).value
+            else:
+                cont += 1
+                val = int(val) + int(ws_Sheet1.cell(row=x, column=col).value)
+    media = int(val) / int(cont)
+    return val, media
+
+

And then to get the value i need something like

+
print(get_sum_col(3).media
+print(get_sum_col(3).val
+
+

is this possible? +what am i doing wrong?

","

Yes, you can do something like this:

+
def get_sum_col(col):
+    ...
+    return {'val': val, 'media': media}
+
+print(get_sum_col(3).get('media', None) # None will print if media is bull
+
",python +"Run multiple async loops in separate processes within a main async app

Ok so this is a bit convoluted but I have a async class with a lot of async code.

+

I wish to parallelize a task inside that class and I want to spawn multiple processes to run a blocking task and also within each of this processes I want to create an asyncio loop to handle various subtasks.

+

SO I short of managed to do this with a ThreadPollExecutor but when I try to use a ProcessPoolExecutor I get a Can't pickle local object error.

+

This is a simplified version of my code that runs with ThreadPoolExecutor. How can this be parallelized with ProcessPoolExecutor?

+
import asyncio
+import time
+from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
+
+
+class MyClass:
+    def __init__(self) -> None:
+        self.event_loop = None
+        # self.pool_executor = ProcessPoolExecutor(max_workers=8)
+        self.pool_executor = ThreadPoolExecutor(max_workers=8)
+        self.words = ["one", "two", "three", "four", "five"]
+        self.multiplier = int(2)
+
+async def subtask(self, letter: str):
+    await asyncio.sleep(1)
+    return letter * self.multiplier
+
+async def task_gatherer(self, subtasks: list):
+    return await asyncio.gather(*subtasks)
+
+def blocking_task(self, word: str):
+    time.sleep(1)
+    subtasks = [self.subtask(letter) for letter in word]
+    result = asyncio.run(self.task_gatherer(subtasks))
+    return result
+
+async def master_method(self):
+    self.event_loop = asyncio.get_running_loop()
+    master_tasks = [
+        self.event_loop.run_in_executor(
+            self.pool_executor,
+            self.blocking_task,
+            word,
+        )
+        for word in self.words
+    ]
+
+    results = await asyncio.gather(*master_tasks)
+    print(results)
+
+
+if __name__ == "__main__":
+    my_class = MyClass()
+    asyncio.run(my_class.master_method())
+
","

This is a very good question. Both the problem and the solution are quite interesting.

+

The Problem

+

One difference between multithreading and multiprocessing is how memory is handled. Threads share a memory space. Processes do not (in general, see below).

+

Objects are passed to a ThreadPoolExecutor simply by reference. There is no need to create new objects.

+

But a ProcessPoolExecutor lives in a separate memory space. To pass objects to it, the implementation pickles the objects and unpickles them again on the other side. This detail is often important.

+

Look carefully at the arguments to blocking_task in the original question. I don't mean word - I mean the first argument: self. The one that's always there. We've seen it a million times and hardly even think about it. To execute the function blocking_task, a value is required for the argument named "self." To run this function in a ProcessPoolExecutor, "self" must get pickled and unpickled. Now look at some of the member objects of "self": there's an event loop and also the executor itself. Neither of which is pickleable. That's the problem.

+

There is no way we can run that function, as is, in another Process.

+

Admittedly, the traceback message "Cannot pickle local object" leaves a lot to be desired. So does the documentation. But it actually makes total sense that the program works with a ThreadPool but not with a ProcessPool.

+

Note: There are mechanisms for sharing ctypes objects between Processes. However, as far as I'm aware, there is no way to share Python objects directly. That's why the pickle/unpickle mechanism is used.

+

The Solution

+

Refactor MyClass to separate the data from the multiprocessing framework. I created a second class, MyTask, which can be pickled and unpickled. I moved a few of the functions from MyClass into it. Nothing of importance has been modified from the original listing - just rearranged.

+

The script runs successfully with both ProcessPoolExecutor and ThreadPoolExecutor.

+
import asyncio
+import time
+# from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import ProcessPoolExecutor
+
+# Refactored MyClass to break out MyTask
+
+class MyTask:
+    def __init__(self):
+        self.multiplier = 2
+
+    async def subtask(self, letter: str):
+        await asyncio.sleep(1)
+        return letter * self.multiplier
+    
+    async def task_gatherer(self, subtasks: list):
+        return await asyncio.gather(*subtasks)
+    
+    def blocking_task(self, word: str):
+        time.sleep(1)
+        subtasks = [self.subtask(letter) for letter in word]
+        result = asyncio.run(self.task_gatherer(subtasks))
+        return result
+    
+class MyClass:
+    def __init__(self):
+        self.task = MyTask()
+        self.event_loop: asyncio.AbstractEventLoop = None
+        self.pool_executor = ProcessPoolExecutor(max_workers=8)
+        # self.pool_executor = ThreadPoolExecutor(max_workers=8)
+        self.words = ["one", "two", "three", "four", "five"]
+
+    async def master_method(self):
+        self.event_loop = asyncio.get_running_loop()
+        master_tasks = [
+            self.event_loop.run_in_executor(
+                self.pool_executor,
+                self.task.blocking_task,
+                word,
+            )
+            for word in self.words
+        ]
+    
+        results = await asyncio.gather(*master_tasks)
+        print(results)
+
+if __name__ == "__main__":
+    my_class = MyClass()
+    asyncio.run(my_class.master_method())
+
",python +"Is there a simple way to use Oange3 with an Nvidia GPU?

I need to compute a high dimension dataset, with clustering on Orange3 app. So, there's too many time spent to calculate the Distance Matrix between the objects. If I could use a graphic card for this tasks it will take much less time to complete the task. Anyone know, let's say, a workaround to do this?

","

No. Orange uses numpy arrays and computes distances on CPU. Short of reimplementing the routine for calculation of distances (which in itself is rather short and simple), there's nothing you can do about it.

+

Orange will start using Dask in some not too distant future, but until then try reducing your data set. You may not need all dimensions and/or objects for your clustering.

",python +"Extract EPSG code from GeoDataFrame.crs result

Let's say I have a GeoDataFrame with a CRS set.

+
gdf.crs
+
+

gives me

+
<Projected CRS: EPSG:25833>
+Name: ETRS89 / UTM zone 33N
+Axis Info [cartesian]:
+- [east]: Easting (metre)
+- [north]: Northing (metre)
+Area of Use:
+- undefined
+Coordinate Operation:
+- name: UTM zone 33N
+- method: Transverse Mercator
+Datum: European Terrestrial Reference System 1989
+- Ellipsoid: GRS 1980
+- Prime Meridian: Greenwich
+
+

This is of type <class 'pyproj.crs.crs.CRS'>. +Is there a way to extract the EPSG Code from this, thus 25833?

","

.crs returns a pyroj.CRS object. This should get you the EPSG code from the object:

+
gdf.crs.to_epsg()
+
+

pyproj docs

",python +"How To Fetch Projec quotas using OpenstackSDK?

I am looking for a small code to fetch all my projects quotas limits. From openstacksdk dev repository i can see there is connection called compute.v2.limits, but using that i m getting blank output like below.

+
import openstack
+import openstack.compute.v2.limits
+import os
+import datetime
+
+################## getting limits ##########################
+ip='10.6.X.X'
+auth_url_domain="https://10.6.X.X:13000/v3"
+conn = openstack.connect(auth_url=auth_url_domain, project_name="admin", username="admin", domain_name="default",password="XXXXXX", cacert="/root/app/cacrt/cacrt/ca.crt10.6.X.X.pem")
+data=openstack.compute.v2.limits.AbsoluteLimits(session=conn)
+print(data.to_dict())
+
+

Output i m getting ( key is ok but values are none . I want values should be as per values set for all projects):

+
{'server_groups': None, 'keypairs': None, 'total_ram_used': None,
+ 'total_cores': None, 'instances_used': None, 'total_cores_used': None,
+ 'instances': None, 'id': None, 'security_groups': None,
+ 'total_ram': None, 'floating_ips': None, 'location': None,
+ 'personality_size': None, 'server_groups_used': None,
+ 'personality': None, 'security_group_rules': None,
+ 'name': None, 'server_group_members': None, 'floating_ips_used': None,
+ 'image_meta': None, 'server_meta': None, 'security_groups_used': None}
+
","

You could get the project quota only by openstack.connection, like this:

+
conn = openstack.connect(auth_url=auth_url_domain...)
+quotas = conn.get_compute_quotas(project_name_or_id)
+
+

And there is more other common methods, you could check it while you need.

+
+

I want values should be as per values set for all projects

+
+

If you want to get all projects quotas, you should create the consistent connection because of the connection bind the project as the parameter of openstack.connect method. But if you are the admin role, you could get all projects info.

",python +"Parse a multi-layered JSON from INSEE API

I'm sending a request to an API. This API is INSEE, it is the French official repositories of registered companies.

+

Here is my request:

+
headers = {
+    'Accept': 'application/json',
+    'Authorization': 'xxx'
+}
+
+params = (
+    ('q', 'siren:530085802'),
+    ('date', '2021-10-01'),
+    ('champs', 'siret, denominationUniteLegale, codePostalEtablissement, libelleCommuneEtablissement, denominationUsuelleEtablissement'),
+    ('debut', 1)
+    # ('nombre', 1)
+)
+
+response = requests.get('https://api.insee.fr/entreprises/sirene/V3/siret', headers=headers, params=params)
+
+

For this example, I'm requesting Facebook's legal entity by its number : siren:530085802 (this is Open Data, nothing here is confidential).

+

Now I get a response:

+
reponse.text
+
+

This :

+
'{"header":{"statut":200,"message":"OK","total":3,"debut":1,"nombre":2},"etablissements":[{"siret":"53008580200011","uniteLegale":{"denominationUniteLegale":"FACEBOOK FRANCE"},"adresseEtablissement":{"codePostalEtablissement":"75116","libelleCommuneEtablissement":"PARIS 16"},"periodesEtablissement":[{"dateFin":null,"dateDebut":"2012-06-14","denominationUsuelleEtablissement":null},{"dateFin":"2012-06-13","dateDebut":"2011-02-17","denominationUsuelleEtablissement":null},{"dateFin":"2011-02-16","dateDebut":"2011-01-01","denominationUsuelleEtablissement":null}]},{"siret":"53008580200037","uniteLegale":{"denominationUniteLegale":"FACEBOOK FRANCE"},"adresseEtablissement":{"codePostalEtablissement":"75002","libelleCommuneEtablissement":"PARIS 2"},"periodesEtablissement":[{"dateFin":null,"dateDebut":"2018-06-26","denominationUsuelleEtablissement":null},{"dateFin":"2018-06-25","dateDebut":"2016-04-18","denominationUsuelleEtablissement":null}]}]}'
+
+

As per the official documentation, there are multiple layers :

+
    +
  • Legal entity : Identified by a siren
  • +
  • Establishment : Identified by a siret – which is the SIREN + 5 characters. Basically here I'm getting a list of establishments, since I'm requesting only one SIREN
  • +
  • Periods : Which is archived/change tracking of several attributes. With a dateDebut (starting date) and a dateFin (end date) and attributes, among which the denominationUsuelleEtablissement I'd like to have the current values.
  • +
+

Despite putting a date in my request, the API responded with several periods, not only the one that includes the date I'm providing. Hence adding a layer.

+

What I'm trying to do is to flatten the response and convert it to a dataframe for easier use.

+

What I've done is the following. Using json.normalize:

+
import json
+import pandas as pd
+
+contenuReponse = json.loads(response.text)
+etablissements = contenuReponse['etablissements']
+ 
+df = pd.json_normalize(etablissements)
+df
+
+

I get this:

+
+ + + + + + + + + + + + + + + + + + + + + + + +
siretperiodesEtablissementsuniteLegale.denominationUniteLegale
053008580200011[{'dateFin': None, 'dateDebut': '2012-06-14', ...FACEBOOK FRANCE
153008580200037[{'dateFin': None, 'dateDebut': '2018-06-26', ...FACEBOOK FRANCE
+
+

json_normalize ignores the layer below periodesEtablissement.

+

Is there a way to flatten successfully the whole response. Or, use only the periodesEtablissement relevant to my request. Meaning the one with no dateFin?

","

You could try using this function:

+
def flatten_nested_json_df(df):
+    df = df.reset_index()
+    s = (df.applymap(type) == list).all()
+    list_columns = s[s].index.tolist()
+    
+    s = (df.applymap(type) == dict).all()
+    dict_columns = s[s].index.tolist()
+
+    
+    while len(list_columns) > 0 or len(dict_columns) > 0:
+        new_columns = []
+
+        for col in dict_columns:
+            horiz_exploded = pd.json_normalize(df[col]).add_prefix(f'{col}.')
+            horiz_exploded.index = df.index
+            df = pd.concat([df, horiz_exploded], axis=1).drop(columns=[col])
+            new_columns.extend(horiz_exploded.columns) # inplace
+
+        for col in list_columns:
+            print(f"exploding: {col}")
+            df = df.drop(columns=[col]).join(df[col].explode().to_frame())
+            new_columns.append(col)
+
+        s = (df[new_columns].applymap(type) == list).all()
+        list_columns = s[s].index.tolist()
+
+        s = (df[new_columns].applymap(type) == dict).all()
+        dict_columns = s[s].index.tolist()
+    return df
+
+

and do this:

+
flatten_nested_json_df(df)
+
+

which gives:

+
  index           siret uniteLegale.denominationUniteLegale  \
+0      0  53008580200011                     FACEBOOK FRANCE   
+0      0  53008580200011                     FACEBOOK FRANCE   
+0      0  53008580200011                     FACEBOOK FRANCE   
+1      1  53008580200037                     FACEBOOK FRANCE   
+1      1  53008580200037                     FACEBOOK FRANCE   
+
+  adresseEtablissement.codePostalEtablissement  \
+0                                        75116   
+0                                        75116   
+0                                        75116   
+1                                        75002   
+1                                        75002   
+
+  adresseEtablissement.libelleCommuneEtablissement  \
+0                                         PARIS 16   
+0                                         PARIS 16   
+0                                         PARIS 16   
+1                                          PARIS 2   
+1                                          PARIS 2   
+
+  periodesEtablissement.dateFin periodesEtablissement.dateDebut  \
+0                          None                      2012-06-14   
+0                    2012-06-13                      2011-02-17   
+0                    2011-02-16                      2011-01-01   
+1                          None                      2018-06-26   
+1                    2018-06-25                      2016-04-18   
+
+  periodesEtablissement.denominationUsuelleEtablissement  
+0                                               None      
+0                                               None      
+0                                               None      
+1                                               None      
+1                                               None      
+
+
",python +"Python Pandas: Best way to find local maximums in large DF

I have a large dataframe that consitsts of many cycles, each cycle has 2 maximum peak values inside that I need to capture into another dataframe.

+

I have created a sample data frame that mimics the data I am seeing:

+
import pandas as pd
+
+data = {'Cycle':[1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3], 'Pressure':[100,110,140,180,185,160,120,110,189,183,103,115,140,180,200,162,125,110,196,183,100,110,140,180,185,160,120,180,201,190]}
+    
+df = pd.DataFrame(data)
+
+

As you can see in each cycle there are two maxes but the part I was having trouble with was that the 2nd peak is usaully higher than the first peak, so there could be rows of numbers technicially higher than the other peaks max in the cycle. The results should look something like this:

+
data2 = {'Cycle':[1,1,2,2,3,3], 'Peak Maxs': [185,189,200,196,185,201]}
+
+df2= pd.DataFrame(data2)
+
+

I have tried a couple methods including .nlargest(2) per cycle, but the problem is that since one of the peaks is usually higher it will pull the 2nd highest number in the data, which isnt necesssarily the other peak.

+

This graph shows the peak pressures from each cycle that I would like to be able to find. +

+

Thanks for any help.

","

From scipy argrelextrema

+
from scipy.signal import argrelextrema
+out = df.groupby('Cycle')['Pressure'].apply(lambda x : x.iloc[argrelextrema(x.values, np.greater)])
+Out[124]: 
+Cycle    
+1      4     185
+       8     189
+2      14    200
+       18    196
+3      24    185
+       28    201
+Name: Pressure, dtype: int64
+
+out = out.sort_values().groupby(level=0).tail(2).sort_index() 
+out
+Out[138]: 
+Cycle    
+1      4     185
+       8     189
+2      14    200
+       18    196
+3      24    185
+       28    201
+Name: Pressure, dtype: int64
+
",python +"Logistic regression (from scratch) predicts 0.5 for everything

Need help on writing my own logistic regression model. +Input data (generated via sklearn.datasets.make_classification) looks like this (printed for 10 entries):

+
[[ 0.74186571 -1.69239663  2.06965145]
+ [-1.80076727  0.59700581 -1.57159523]
+ [ 1.0328198   0.62274582  0.90241322]
+ [-0.63972474  2.12054103  1.30124807]
+ [ 1.04275475 -0.86879077  1.08399317]
+ [-1.12772782  0.26396098 -1.68130012]
+ [ 0.92281318 -1.15431326  0.23868389]
+ [-0.37260971 -0.97979894  1.65890322]
+ [ 0.4513904   0.30502349  2.46449598]
+ [-2.79502998  0.05500871 -2.47725562]]
+
+

Output like this:

+
[0. 0. 1. 1. 0. 1. 0. 0. 0. 0.]
+
+

Here is my code:

+
import numpy
+import math
+
+# import data
+path = r"C:\Users\felix\sciebo2\Atom_working_dir\ML_sandbox\\" # put in global path here
+x_logregdata = numpy.genfromtxt(path+"x_logregdata.csv", delimiter=",")
+y_logregdata = numpy.genfromtxt(path+"y_logregdata.csv", delimiter=",")
+
+class MyLogReg:
+
+    def __init__(self, n):
+        self._numinputs = n
+        self._weights = numpy.random.rand(n)
+        self._bias = 0 # or = numpy.random.rand(1)
+        self._lam = 0.01 # lambda parameter for regularization
+
+    def pred(self, x):
+
+        return sigmoid(numpy.matmul(x, self._weights) + self._bias)
+
+# -----------------------------------------------------------------------------
+# functions
+
+def logloss(net,x,y): # p=prediction, t=target
+    p = sigmoid(numpy.matmul(x, net._weights) + net._bias) # (1000,3)x(3,1) becomes (1000,1)
+    logloss_term = (numpy.matmul(-y.T, numpy.log(p)) - numpy.matmul((1-y.T),numpy.log(1-p)))/len(p) # transpose, so (1,1000)x(1000,1) becomes (1)
+    regularization_term = numpy.mean(net._weights**2 * net._lam/2)
+    J = logloss_term + regularization_term
+    return J
+
+def sigmoid(z):
+    # z = b + w1x1 + w2x2 + ... + wnxn
+    return 1/(1+numpy.exp(-z))
+
+def train(net,x,t,epochs,lr):
+    for epoch in range(epochs):
+        # x comes in the shape of {n_samples, n_features}
+        p = net.pred(x) # make predictions
+        e = logloss(net,x,t)
+        grad_w = (numpy.matmul(x.T,(p-t)) + net._lam*net._weights)/len(p) # dim: (3,1)
+        grad_b = delta_bi = numpy.mean(p-t)
+        if (epoch+1)%100 == 0:
+            print(f"Epoch {epoch+1} | Error: {e} with weights {NN._weights} and bias {NN._bias}")
+            print(f"grad_w: {grad_w} --- grad_b: {grad_b}")
+        # update weights and bias
+        NN._weights += lr*(-grad_w)
+        NN._bias += lr*(-grad_b)
+
+NN = MyLogReg(3)
+
+# # -----------------------------------------------------------------------------
+# # training process
+print(80*"--")
+print("Training process started!\n")
+print(numpy.shape(x_combined),numpy.shape(x_logregdata))
+train(NN, x_logregdata, y_logregdata, 100, 0.5)
+
+

Training output at last epoch:

+
Epoch 1000 | Error: 0.6919551095870804 with weights [ 0.01013472  0.04960763 -0.06680454] and bias -0.012293556999268884
+grad_w: [-4.62077479e-18  6.62621000e-18  7.92638524e-18] --- grad_b: -1.3322676295501879e-18
+
+

After training on the entire data set, predictions look random and are all close to 0.5, even though gradients have become very small:

+
for i in range(10):
+    print((NN.pred(x_logregdata[i,:]), y_logregdata[i]))
+
+
+OUT:
+(0.4434940888958877, 0.0)
+(0.5259920670963649, 0.0)
+(0.49219604260551786, 1.0)
+(0.4998723781629637, 1.0)
+(0.4707235000047709, 0.0)
+(0.525400671366715, 1.0)
+(0.48097184157406053, 0.0)
+(0.4562378027506945, 0.0)
+(0.46077410720140005, 0.0)
+(0.531856873614567, 0.0)
+
+

Github repo is here: Click.

","

It's unclear why you want to initialize your features with random integer weights, if you pass equal weights to them, it converges pretty ok with 100 epochs:

+
class MyLogReg:
+
+    def __init__(self, n):
+        self._numinputs = n
+        self._weights = numpy.repeat(1.0,n)
+        self._bias = 0 # or = numpy.random.rand(1)
+        self._lam = 0.01 # lambda parameter for regularization
+
+    def pred(self, x):
+
+        return sigmoid(numpy.matmul(x, self._weights) + self._bias)
+
+import numpy as np
+from sklearn.datasets import make_classification
+
+X,y = make_classification(n_features=3,n_redundant=1,n_informative=2,
+class_sep=0.7,random_state=22)
+
+NN = MyLogReg(3)
+train(NN, X, y, 100, 0.5)
+
+Epoch 100 | Error: 0.3930719987698364 with weights [0.08555415 1.38852617 1.65479616] and bias 0.27656565660444704
+grad_w: [ 7.85974808e-05 -8.63304471e-04 -1.02206054e-03] --- grad_b: -0.00022828688162301436
+
+NN.pred(X)[:20]
+ 
+array([0.04147539, 0.75444612, 0.92599311, 0.92906995, 0.330026  ,
+       0.96483765, 0.90184527, 0.21597661, 0.43732915, 0.17307697,
+       0.98569769, 0.11334725, 0.90186428, 0.96431985, 0.27836055,
+       0.05338276, 0.02682678, 0.96073064, 0.32182455, 0.57531559])
+
+

We can check the training accuracy:

+
from sklearn.metrics import confusion_matrix
+confusion_matrix(y,(NN.pred(X)>0.5).astype(int))
+
+array([[43,  7],
+       [ 6, 44]])
+
+

If you would really want to initialize with weights from a random uniform, I suspect you need to increase the learning rate for it to converge.

",python +"Fill merged columns with 0 instead of NaN

I have a problem. I want to merge two dataframes, but instead of NaN it should be filled with 0. But only the "new" columns. How could I do that?

+

What I tried

+
df3 = pd.merge(df2, grouped_df_one,on=['id', 'host_id'], how='left', fill = 0)
+[OUT]
+TypeError: merge() got an unexpected keyword argument 'fill'
+
+
d = {'host_id': [1, 1, 2],
+     'id': [10, 11, 20],
+     'value': ["Hot Water,Cold Water,Kitchen,Coffee", 
+               "Hot Water,Coffee,Something",
+               "Hot Water,Coffee"]}
+df = pd.DataFrame(data=d)
+print(df)
+
+
+d2 = {'host_id': [1, 1, 2, 3],
+     'id': [10, 11, 20, 30],
+     'some': ['test1', "test2", "test3", np.nan]}
+df2 = pd.DataFrame(data=d2)
+print(df2)
+
+df_path = df.copy()
+df_path.index = pd.MultiIndex.from_arrays(df_path[['host_id', 'id']].values.T, names=['host_id', 'id'])
+df_path = df_path['value'].str.split(',', expand=True)
+df_path = df_path.melt(ignore_index=False).dropna()
+df_path.reset_index(inplace=True)
+
+one_hot = pd.get_dummies(df_path['value'])
+df_one = df_path.drop('value',axis = 1)
+df_one = df_path.join(one_hot)
+
+grouped_df_one = df_one.groupby(['id']).max()
+grouped_df_one = grouped_df_one.drop(columns=['value', 'variable']).reset_index()
+
+df3 = pd.merge(df2, grouped_df_one,on=['id', 'host_id'], how='left')
+df3
+
+
   host_id  id                                value
+0        1  10  Hot Water,Cold Water,Kitchen,Coffee
+1        1  11           Hot Water,Coffee,Something
+2        2  20                     Hot Water,Coffee
+
+   host_id  id   some
+0        1  10  test1
+1        1  11  test2
+2        2  20  test3
+3        3  30    NaN
+
+
+

What I got

+
   host_id  id   some  Coffee  Cold Water  Hot Water  Kitchen  Something
+0        1  10  test1     1.0         1.0        1.0      1.0        0.0
+1        1  11  test2     1.0         0.0        1.0      0.0        1.0
+2        2  20  test3     1.0         0.0        1.0      0.0        0.0
+3        3  30    NaN     NaN         NaN        NaN      NaN        NaN
+
+

What I want

+
   host_id  id   some  Coffee  Cold Water  Hot Water  Kitchen  Something
+0        1  10  test1     1.0         1.0        1.0      1.0        0.0
+1        1  11  test2     1.0         0.0        1.0      0.0        1.0
+2        2  20  test3     1.0         0.0        1.0      0.0        0.0
+3        3  30    NaN       0           0          0        0          0
+
","

You can fill specific columns using

+
df[list_cols] = df[list_cols].fillna(0)
+
+

where list_cols is e.g.

+
list_cols = ["Coffee", "Cold Water", "Hot Water", "Kitchen", "Something"]
+
+

See: Pandas fill multiple columns with 0 when null

",python +"Keras multivariate time series forecasting model returns NaN as MAE and loss

I have multivariate time series data, collected every 5 seconds for a few days. +This includes columns of standardized data, which looks like below (few example values). "P1" is the label-column.

+
|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+|       | P1                    | P2                    | P3                   | AI_T_MOWA             | AI_T_OEL              | AI_T_KAT_EIN           | AI_T_KAT_AUS           | P-Oel                | P-Motorwasser        |
+|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+| 0     | 0.8631193380009695    | 0.8964414887167506    | 0.8840858759128901   | -0.523186057460264    | -0.6599697679790338   | 0.8195843978382326     | 0.6536355179773343     | 2.0167991331023862   | 1.966765280217274    |
+|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+| 1     | 2.375731412346451     | 2.416190921505275     | 2.3921080971495456   | 1.2838015319452019    | 0.6783070711474897    | 2.204838829646018      | 2.250184559609546      | 2.752702514412287    | 2.7863834647854797   |
+|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+| 2     | 2.375731412346451     | 2.416190921505275     | 2.3921080971495456   | 1.2838015319452019    | 1.2914092683827934    | 2.2484584825559955     | 2.2968465552769324     | 2.4571347629025726   | 2.743245665597679    |
+|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+| 3     | 2.3933199248388406    | 2.416190921505275     | 2.3753522946913606   | 1.2838015319452019    | 1.5485166414169536    | 2.2557284247076588     | 2.3039344533529906     | 2.31839887954087     | 2.7863834647854797   |
+|-------|-----------------------|-----------------------|----------------------|-----------------------|-----------------------|------------------------|------------------------|----------------------|----------------------|
+
+

Corresponding graphs of the standardized data show nothing out of the ordinary.

+

+

I have split this data into train, validation and test sets, so that my training data is the first 70% of overall data, the validation are the next 20% and the test are the last 10%.

+
train_df_st = df[0:int(self._n*0.7)]
+val_df_st = df[int(self._n*0.7):int(self._n*0.9)]
+test_df_st = df[int(self._n*0.9):]
+
+

I then generate windows through the WindowGenerator class from tensorflows tutorial like here.

+

Using a simple Baseline model that predicts the ouput the same as the input I get actual predictions, so I assume my generated windows are fine. +The shapes of my batches are

+
Input shape: (32, 24, 193)
+Output shape: (32, 24, 1)
+
+

Now to the tricky part: +I obviously want to use another model for better predictions. I have tried out using Conv1D using only one column and that worked, so I wanted to try it with this as well. +My windows look like:

+
CONV_WIDTH = 3
+LABEL_WIDTH = 24
+INPUT_WIDTH = LABEL_WIDTH + (CONV_WIDTH - 1)
+conv_window = WindowGenerator(
+    input_width=INPUT_WIDTH,
+    label_width=LABEL_WIDTH,
+    shift=1,
+    train_df=train_df_st, val_df=val_df_st, test_df=test_df_st, label_columns=["P1"])
+
+
Total window size: 25
+Input indices: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
+Label indices: [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
+Label column name(s): ['P1']
+
+

I then define my model and use the compile_and_fit() method as used here.

+
conv_model = tf.keras.Sequential([
+    tf.keras.layers.Conv1D(filters=32,
+                           kernel_size=(CONV_WIDTH,),
+                           activation='relu'),
+    tf.keras.layers.Dense(units=32, activation='relu'),
+    tf.keras.layers.Dense(units=1),
+])
+
+MAX_EPOCHS = 20
+
+def compile_and_fit(model, window, patience=2):
+  early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',
+                                                    patience=patience,
+                                                    mode='min')
+
+  model.compile(loss=tf.losses.MeanSquaredError(),
+                optimizer=tf.optimizers.Adam(),
+                metrics=[tf.metrics.MeanAbsoluteError()])
+
+  history = model.fit(window.train, epochs=MAX_EPOCHS,
+                      validation_data=window.val,
+                      callbacks=[early_stopping])
+  return history
+
+history = compile_and_fit(window=conv_window, model=conv_model)
+
+

Input and Output shapes are:

+
Input shape: (32, 26, 193)
+Output shape: (32, 24, 1)
+
+

My final output however is only two epochs that show nan as mean absolute error as well as loss:

+
Epoch 1/20
+382/382 [==============================] - 2s 4ms/step - loss: nan - mean_absolute_error: nan - val_loss: nan - val_mean_absolute_error: nan
+Epoch 2/20
+382/382 [==============================] - 1s 3ms/step - loss: nan - mean_absolute_error: nan - val_loss: nan - val_mean_absolute_error: nan
+
+

And if I plot some example windows I see that I get labels, but no predictions:

+

+

I have tried implementing yet another model (LSTM) with slightly different windows, but a similar approach, but I get the same NaN's, so I believe it is not my models problem, but something in my data?.

","

Turns out my standarization of the data was faulty, normalizing it, I get actual values instead of NaN.

",python +"How to locate a checkbox to verify its state using Selenium and Python

I am trying to figure out if a checkbox on our website is in a checked state or not. The HTML for the checkbox is as follows:

+
<input id="ID_StaffIsRostered" name="ID_Rostering" type="checkbox" checked="" data-toggle="toggle" data-onstyle="success" data-size="sm" data-on="Yes" data-off="No" onchange="toggleRosteredStaff()">
+
+

I've tried finding this via these locators:

+
    +
  1. (By.ID, "ID_StaffIsRostered")
  2. +
  3. (By.XPATH, "input[@name='ID_Rostering']"
  4. +
  5. (By.XPATH,"//*[@id='ID_StaffIsRostered']")
  6. +
  7. (By.XPATH,"/html/body/div[1]/div/div[2]/div/div/div/div[2]/table[3]/tbody/tr/td/div[1]/div[2]/div/form/div/div[1]/div/label/div/input")
  8. +
  9. (By.CSS_SELECTOR,"label:nth-child(1) > .btn-light .toggle-off")
  10. +
  11. (By.XPATH,"//form[@id='ID_Form_Rostering']/div/div/div/label/div/div/label[2]")
  12. +
  13. (By.XPATH,"//div/div/div/label/div/div/label[2]")
  14. +
+

Nothing has worked so far. I can however select the div containing the checkbox, and the labels that the checkboxes switch between depending on what it is toggle to, the HTML is:

+
<div class="toggle btn btn-success btn-sm" data-toggle="toggle" style="width: 7.5px; height: 26px; min-width: 38px;">
+
+

and for the labels:

+
<div class="toggle-group"><label class="btn btn-success btn-sm toggle-on">Yes</label><label class="btn btn-light btn-sm toggle-off">No</label><span class="toggle-handle btn btn-light btn-sm"></span></div>
+
+

What are some alternative ways I can achiever this? Currently I'm using Selenium 4.0.0 with Python 3.9

","

As per the HTML Specification for Boolean attributes:

+
+

A number of attributes are Boolean attributes. The presence of a +boolean attribute on an element represents the true value, and the +absence of the attribute represents the false value.

+

If the attribute is present, its value must either be the empty string +or a value that is an ASCII case-insensitive match for the attribute's +canonical name, with no leading or trailing whitespace.

+
+

The checked attribute can be represented in either of the ways:

+
<input name=name id=id type=checkbox checked>
+<input name=name id=id type=checkbox checked="">
+<input name=name id=id type=checkbox checked="checked">
+
+
+

Solution

+

To verify the state of the checkbox you can probe the checked attribute and you can use the following code block:

+
try:
+  WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#ID_StaffIsRostered[name='ID_Rostering'][checked]")))
+  print("Checkbox is in checked state")
+except:
+  print("Checkbox is in unchecked state")
+
",python +extract channel names from a multi-channel image

I am using skimage.io.imread (which uses tifffile) to read a QPTIFF file. Multiple channels are successfully read as multiple dimensions. Is it possible to extract the channel names and other metadata?

,"

PerkinElmer QPI metadata are stored as XML in the ImageDescription TIFF tags. To read the XML metadata, use the tifffile.TiffFile class, e.g.:

+
from xml.etree import ElementTree
+from tifffile import TiffFile
+
+with TiffFile('LuCa-7color_Scan1.tiff') as tif:
+    for page in tif.series[0].pages:
+        print(ElementTree.fromstring(page.description).find('Name').text)
+
",python +"Pandas assign value based on next row(s)

Consider this simple pandas DataFrame with columns 'record', 'start', and 'param'. There can be multiple rows with the same record value, and each unique record value corresponds to the same start value. However, the 'param' value can be different for the same 'record' and 'start' combination:

+
pd.DataFrame({'record':[1,2,3,4,4,5,6,7,7,7,8], 'start':[0,5,7,13,13,19,27,38,38,38,54], 'param':['t','t','t','u','v','t','t','t','u','v','t']})
+
+

I'd like to make a column 'end' that takes the value of 'start' in the row with the next unique value of 'record'. The values of column 'end' should be:

+
[5,7,13,19,19,27,38,54,54,54,NaN]
+
+

I'm able to do this using a for loop, but I know this is not preferred when using pandas:

+
max_end = 100
+for idx, row in df.iterrows():
+    try:
+        n = 1
+        next_row = df.iloc[idx+n]
+        while next_row['start'] == row['start']:
+            n = n+1
+            next_row = df.iloc[idx+n]
+        end = next_row['start']
+    except:
+        end = max_end
+    df.at[idx, 'end'] = end
+
+

Is there an easy way to achieve this without a for loop?

","

I have no doubt there is a smarter solution but here is mine.

+
df1['end'] = df1.drop_duplicates(subset = ['record', 'start'])['start'].shift(-1).reindex(index = df1.index, method = 'ffill')
+
+

-=EDIT=- +Added subset into drop_duplicates to account for question amendment

",python +"Creating Start & End Date features out from one date column

I'm trying to make a new feature out from one date column to provide start and end date.

+

Here's what it looks like:

+
unique_id = ["001", "001", "001",
+             "002",
+             "003", "003"
+            ]
+end_dates = ["2018-10-31 12:43:03 PM", "2018-10-31 12:44:23 PM", "2018-10-31 1:01:42 PM",
+             "2018-11-23 03:33:13 PM",
+             "2018-11-23 04:10:45 PM", "2018-11-23 04:13:58 PM"
+             
+            ]
+activity_class = ["step 1", "step 2", "step 3",
+                  "step 1",
+                  "step 1", "step 2"
+                 ]
+
+df = \
+pd.DataFrame({"ID": unique_id,
+              "Edit Date": end_dates,
+              "Activity": activity_class
+             })
+
+df["Edit Date"] = pd.to_datetime(df["Edit Date"])
+
+

Here's how I want it to look like:

+
unique_id = ["001", "001", "001",
+             "002",
+             "003", "003"
+            ]
+
+
+start_date = ["2018-10-31 12:43:03 PM", "2018-10-31 12:43:03 PM", "2018-10-31 12:44:23 PM",
+              "2018-11-23 03:33:13 PM",
+              "2018-11-23 04:10:45 PM", "2018-11-23 04:10:45 PM"
+             ]
+
+end_date = ["2018-10-31 12:43:03 PM", "2018-10-31 12:44:23 PM", "2018-10-31 1:01:42 PM",
+             "2018-11-23 03:33:13 PM",
+             "2018-11-23 04:10:45 PM", "2018-11-23 04:13:58 PM"
+           ]
+
+activity_class = ["step 1", "step 2", "step 3",
+                  "step 1",
+                  "step 1", "step 2"
+                 ]
+
+df = \
+pd.DataFrame({"ID": unique_id,
+              "Start_Date": start_date,
+              "End_Date": end_date,
+              "Activity": activity_class
+             })
+
+df["Start_Date"] = pd.to_datetime(df["Start_Date"])
+df["End_Date"] = pd.to_datetime(df["End_Date"])
+
+

What I tried so far:

+
df["Start_Date"] = df["Edit Date"].shift(1).backfill()
+
+

Some of the rules:

+
    +
  • Data is sorted ascending by unique id and date
  • +
  • regardless of the label in "activity" as long as it's the first one, it the date should be the same for start and end
  • +
  • next activity's start date should copy the previous activity's end date
  • +
","

You are looking for groupby().shift()?

+
df['Start_Date'] = df['Edit Date']
+df['End_Date'] = df.groupby('ID')['Edit Date'].shift().fillna(df['Edit Date'])
+
+

Output:

+
    ID           Edit Date Activity          Start_Date            End_Date
+0  001 2018-10-31 12:43:03   step 1 2018-10-31 12:43:03 2018-10-31 12:43:03
+1  001 2018-10-31 12:44:23   step 2 2018-10-31 12:44:23 2018-10-31 12:43:03
+2  001 2018-10-31 13:01:42   step 3 2018-10-31 13:01:42 2018-10-31 12:44:23
+3  002 2018-11-23 15:33:13   step 1 2018-11-23 15:33:13 2018-11-23 15:33:13
+4  003 2018-11-23 16:10:45   step 1 2018-11-23 16:10:45 2018-11-23 16:10:45
+5  003 2018-11-23 16:13:58   step 2 2018-11-23 16:13:58 2018-11-23 16:10:45
+
",python +"How to extract from text digits and calculate them in a specific order?

I'm scraping data from website which I want to analyze. In the section about job experience, I extract text which specifies how long someone works at the company - this information looks like this:

+
+

Employment period \n2years 2 mon.

+
+

It would be easier to analyze the period of employment expressed in months. Now I wonder how to extract this information from the text and calculate this properly. +Calculation of the given example should be:

+
+

2 x 12 + 2

+
+

I try to do this in that way:

+
def text_format(text: str):
+    digits = []
+    text = text.replace('\\n', ' ')
+    text = text.replace('.', '')
+    text = text.split()
+    for word in text:
+        if word.isalpha():
+            pass
+        else:
+            word = int(word)
+            digits.append(word)
+    
+    total = digits[0] * 12 + digits[1]
+    
+    return total
+
+

In this particular case, the function above works well, but I may have other situations, e.g.

+
+

Employment period \n3years

+
+

OR

+
+

Employment period 11 mon.

+
+

I have no idea how to handle all possible scenarios.

","

You can use a regex to tackle this problem and cover all possible scenarios. For example, a one like below should make this task much easier:

+
Employment period(?:[ \\n]+(\d+)[ ]*years?)?(?:[ \\n]+(\d+)[ ]*mon\.)?
+
+

You can try it out here on the Regex Demo as well.

+

Here's a Python example that runs through the specific use cases mentioned, along with some additional edge cases that I added:

+
import re
+
+pattern = re.compile(r'Employment period(?:[ \\n]+(\d+)[ ]*years?)?(?:[ \\n]+(\d+)[ ]*mon\.)?')
+
+string = r"""\
+Employment period \n2years 2 mon.
+Employment period \n3years
+Employment period 11 mon.
+Employment period 010 years
+Employment period 1 year
+Employment period
+testing\
+"""
+
+for x in pattern.finditer(string):
+    print('Found a match:', x.group(0))
+    years, months = x.groups()
+    if years or months:
+        total_months = int(years or 0) * 12 + int(months or 0)
+        print(f'Total months: {total_months}')
+
+

Output:

+
Found a match: Employment period \n2years 2 mon.
+Total months: 26
+Found a match: Employment period \n3years
+Total months: 36
+Found a match: Employment period 11 mon.
+Total months: 11
+Found a match: Employment period 010 years
+Total months: 120
+Found a match: Employment period 1 year
+Total months: 12
+Found a match: Employment period
+
",python +"Print just the value of one json key response with python

I'm new on it all. +I have a url that returns me a token, in a json format. This token changes all the time I call this url. It's something like this:

+
{
+"token": {
+    "token": "randomtoken",
+    "result": 1,
+    "resultCode": "2",
+    "requestId": "3"
+}}
+
+

I want to print just the result of token key when I call my python code, which is like this:

+
import requests as req
+
+resp = req.get("http://myurl.com.br")
+
+print(resp.text)
+
+

This python code is returning me the following result:

+
{"token":{"token":"randomtoken","result":1,"resultCode":"2","requestId":"3"}}
+
+

How can I print just the token key result? Like just:

+
"randomtoken" 
+
+

It's possible?

","

You have a dict so you may access it with its keys as string

+
import requests as req
+
+resp = req.get("http://myurl.com.br")
+token_key = resp.json()['token']['token']
+print(token_key)
+
+
+

Note that

+
    +
  • resp.text returns a string, you would need json.loads(resp.text) to get a dict
  • +
  • resp.json() does the loading from the text
  • +
",python +"How to limit the amount of a string in a text file

I have some code that records an Input name and score and I want to make it so that there can only be 3 entries of that same name therefore I am trying to figure out how to check for a certain string in a file and make sure there is only 3 of that string. This is a code i previously found but I want to make it so once it recognises 3 names (if there are 3 names) kill the program.

+
# checks for multiple name entries max 3
+def maxNamesA1():
+count = 0
+with open('testResultA1.txt') as myfile:
+    if name in myfile.read():
+        count += 1
+        print(count)
+
","

You need to iterate through the lines to get a count, as of now you are only increasing the account for any match.

+
# checks for multiple name entries max 3
+def maxNamesA1():
+    count = 0
+    with open('testResultA1.txt') as myfile:
+        count = sum([1 for line in myfile if name in line])
+    
+    # to terminate 
+    if count > 3: exit()
+    return count
+
",python +"How do I add to a list in python using via inputs

I'm a rookie at programming. I want to create an open list that I can add to via inputs. The if statement I created does not work. It prints the list even if I enter Y in my response to the second input. I'm sure there are many issues with this but if someone could tell me what I'm doing wrong or if there is a better alternative it would be greatly appreciated.

+
tickers = []
+print(f'current tickers list {tickers}')
+f = input("please enter a ticker symbol you would like to watch:\n")
+tickers.append(f)
+q = input("would you like to add another ticker symbol Y or N: ")
+if q == 'Y':
+    print(f)
+    tickers.append(f)
+else: 
+    print(f'Updated tickers list {tickers}')
+
","
tickers = []
+
+while True:
+  print(f'current tickers list {tickers}')
+  f = input("please enter a ticker symbol you would like to watch:\n")
+  tickers.append(f)
+  q = input("would you like to add another ticker symbol Y or N: ")
+  if q == 'Y':
+    pass
+  else: 
+    print(f'Updated tickers list {tickers}')
+    break
+
",python +"How to have integer subtract from a string in python?

I'm currently working on a chatbot from scratch as an assignment for my intro to python class. In my assignment I need to have at least one "mathematical component". I cant seem to find out how to have my input integer subtract from a string.

+

Attached is a screen shot, My goal is to have them input how many days a week they cook at home and have that subtract from 7 automatically.

+
print('Hello! What is your name? ')
+my_name = input ()
+print('Nice to meet you ' + my_name)
+print('So, ' + my_name + ' What is your favorite veggie?')
+favorite_veggie = input ()
+print('Thats nuts! ' +favorite_veggie + ' is mine too!')
+print('How many days a week do you have cook at home? ')
+day = input ()
+print('So what do you do the other ' + ????? 'days?')
+
","

You are looking for this

+
day = input()
+required_days = 7 - int(day)
+print('So what do you do the other ' + str(required_days) + ' days?')
+
",python +"Numpy array indexing with another matrix

I looked into other posts related to indexing numpy array with another numpy array, but still could not wrap my head around to accomplish the following:

+
a = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]],
+b = [[[1,0],[0,1]],[[1,1],[0,1]]]
+a[b] = [[[7,8,9],[4,5,6]],[[10,11,12],[4,5,6]]]
+
+

a is an image represented by 3D numpy array, with dimension 2 * 2 * 3 with RGB values for the last dimension. b contains the index that will match to the image. For instance for pixel index (0,0), it should map to index (1,0) of the original image, which should give pixel values [7,8,9]. I wonder if there's a way to achieve this. Thanks!

","

Here's one way:

+
In [54]: a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
+
+In [55]: b = np.array([[[1, 0], [0, 1]], [[1, 1], [0, 1]]])
+
+In [56]: a[b[:, :, 0], b[:, :, 1]]
+Out[56]: 
+array([[[ 7,  8,  9],
+        [ 4,  5,  6]],
+
+       [[10, 11, 12],
+        [ 4,  5,  6]]])
+
",python +"getting python to print out the rows from my csv that are between 2 numbers

I have code at the moment that prints out the rows of data from a csv based on user input, this code is displayed below:

+
#allows user input to select a column and then select a value from that 
+
+    column data = pd.read_csv('/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/Locations.csv')
+   rowcol = 0 #the colum that is being searched is column 0 row1 =
+    int(input("Enter Number: ")) #enter in your first point on the map Eg
+    15 row2 = int(input("Enter Number: ")) #enter in your 2nd point on the
+    graph eg 18 result = data.iloc[[row1, row2]]
+
+

But now I want my code to also print out the rows that are between these 2 values that are entered (e.g if the user puts in 12 and 15 it prints out the rows for 12, 13, 14 and 15)

+

this is what I have at the moment but I'm not sure how to go further:

+
num_list = []
+for i in range(row1+1, row2):
+    num_list.append(i)
+    
+print(f'Numbers between 2 points are:\n{btwpoints}')
+
","

You could use range:

+
df.iloc[range(row1, row2)]
+
+

If you need to include row2 as well:

+
df.iloc[range(row1, row2 + 1)]
+
+

You should manage obvious exceptions anyway (like row2 < row1, or out of bounds situations).

+

Out of bounds situations could be mananged like this:

+
df.iloc[range(max(0, row1), min(df.shape[0], row2+1))]
+
+

Having row2 <= row1 will return an empty DataFrame which can be an acceptable output

",python +"Python Selenium. Scraping web page

I want to get the data from the box inside 'Stock Style - Weight' from the url 'https://www.morningstar.co.uk/uk/funds/snapshot/snapshot.aspx?id=F00000NF9P&tab=3' using Selenium

+

This data is in an iframe. I´m able to switch to the iframe and click the button = 'Weight' but i can´t get the nine figures

+

Below is my code

+
driver = webdriver.Chrome(chromedriver)
+driver.get("https://www.morningstar.co.uk/uk/funds/snapshot/snapshot.aspx?id=F00000NF9P&tab=3")
+
+iframe = WebDriverWait(driver, 10).until(
+    EC.presence_of_element_located((By.XPATH, "//iframe[@id='portfolio']")))
+driver.switch_to.frame(iframe)
+
+element1=driver.find_element_by_xpath('/html/body/div/sal-components-pillar-cards-process/div/div[2]/div/div[2]/div[2]')
+element2=element1.find_element_by_css_selector("input[type='radio'][value='Weight']").click()
+
+

I´ve tried several options

+
driver.find_element_by_xpath('*//div/div[2]/div/div[2]/div/svg/g/g[3]/g[2]/g[1]/text')
+
+
driver.find_element_by_css_selector("mbc-chart-group> g.style-box-text-layer > g:nth-child(1)")
+
+

but i get the same error

+
NoSuchElementException: no such element: Unable to locate element
+
","

The Elements are in svg and text tags. To access the same you need to use:

+
//*[local-name()='svg'] or //*[name()='svg']
+
+

Link to refer

+

Xpath for those number would be:

+
//div[@class='sal-stock-style__weight']//*[name()='svg' and @role='chart']//*[name()='g' and @class='style-box-text-layer']//*[name()='text']
+
+

Try like below and confirm:

+
numbers = driver.find_elements_by_xpath("//div[@class='sal-stock-style__weight']//*[name()='svg' and @role='chart']//*[name()='g' and @class='style-box-text-layer']//*[name()='text']")
+for num in numbers:
+    print(num.text)
+
+
15
+6
+4
+22
+14
+2
+19
+13
+2
+
",python +file structure and init method for webjob/function using python

am a beginner in python and wants to test some code in webjob and function app. usually i write code using c# so in visual studio we have templates to create webjob/function app so that we get all required files and init code. Now using python i need the required file structure and init code.

,"

The folder/file structure for a Python Functions project looks like:

+
<project_root>/
+ | - .venv/
+ | - .vscode/
+ | - my_first_function/
+ | | - __init__.py
+ | | - function.json
+ | | - example.py
+ | - my_second_function/
+ | | - __init__.py
+ | | - function.json
+ | - shared_code/
+ | | - __init__.py
+ | | - my_first_helper_function.py
+ | | - my_second_helper_function.py
+ | - tests/
+ | | - test_my_second_function.py
+ | - .funcignore
+ | - host.json
+ | - local.settings.json
+ | - requirements.txt
+ | - Dockerfile
+
+

init method for webjob/function using python

+
init__.py
+import azure.functions as func
+import logging
+
+
+def main(req: func.HttpRequest,
+         obj: func.InputStream):
+logging.info(f'Python HTTP triggered function processed: {obj.read()}')
+
+

Please follow developer guide of Azure functions using python and Python Azure Functions using VS Code.

",python +"AttributeError: module ' ' has no attribute 'Command'

In my Django project ,there is a file(module) which is used to load csv data.

+
project/apps/patients/management/commands/load_patient_data.py
+
+

Inside the file(module):

+
import psycopg2
+import csv
+conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='')
+cur = conn.cursor()
+
+with open(r'apps/patients/management/commands/events.csv') as csvfile:
+        spamreader = csv.DictReader(csvfile, delimiter=',' ,quotechar=' ')
+        for row in spamreader:
+            cur.execute(f"""INSERT INTO patients_event (patient_id, event_type_id , event_value ,event_unit, event_time) VALUES
+                  ('{row['PATIENT ID']}','{row['EVENT TYPE']}','{row['EVENT VALUE']}',
+                   '{row['EVENT UNIT']}','{row['EVENT TIME']}')""")
+conn.commit()
+
+

When I run:

+
 python manage.py load_patient_data
+
+

Error:

+
AttributeError: module 'apps.patients.management.commands.load_patient_data' has no attribute 'Command'
+
+

Any friend can help?

","

In load_patient_data.py file

+

Write follwing

+
from django.core.management.base import BaseCommand, CommandError
+
+class Command(BaseCommand):
+
+    def handle(self, *args, **options):
+        import psycopg2
+        import csv
+        conn = psycopg2.connect(host='localhost', dbname='patientdb', user='username', password='password', port='')
+        cur = conn.cursor()
+    
+        with open(r'apps/patients/management/commands/events.csv') as csvfile:
+            spamreader = csv.DictReader(csvfile, delimiter=',', quotechar=' ')
+            for row in spamreader:
+                cur.execute(f"""INSERT INTO patients_event (patient_id, event_type_id , event_value ,event_unit, event_time) VALUES
+                          ('{row['PATIENT ID']}','{row['EVENT TYPE']}','{row['EVENT VALUE']}',
+                           '{row['EVENT UNIT']}','{row['EVENT TIME']}')""")
+        conn.commit()
+
+

Then simply run python manage.py load_patient_data

",python +"Quadratic equation: TypeError: bad operand type for unary -: 'str'

I´m new to Python and have been trying to code the quadratic equation, but i keep running into this error: +TypeError: bad operand type for unary -: 'str'

+
def quad_gleichung():
+a = input('a:')
+b = input('b:')
+c = input('c:')
+
+x1 = int(-b + (b**2 - (4*a*c))**(0.5)) / (2*a)
+x2 = int(-b - (b**2 - (4*a*c))**(0.5)) / (2*a)
+
+
+print('Lösung 1:', x1)
+print('Lösung 2:', x2)
+
+quad_gleichung()
+
+

Can anyone please help me?

+

Thanks!

","

The return type of input is string. It needs to be converted to some number type, float or int, depending on use case.

+

Therefore, change the assignments to a, b, c to:

+
a = int(input("a: ")) # or float(input("a: "))
+b = int(input("b: ")) # or float(input("b: "))
+c = int(input("c: ")) # or float(input("c: "))
+
",python +"In abaqus, how to output the maximum stress value at each time point without selecting an object

During the compression test, how to output the maximum stress value at each time point without selecting an object

+

Step&question +I created a field output,MISESMAX maximum mises equivalent stress-submit this job-creat XY data-click ODB field output- select MISESMAX(i chorse intergration point in this part)then I save,but abaqus hint “At least one entity should be selscted”.

+

Goal +I want to output Maximum stress value of each step in XY data,but the area of maximum stress value in each step will be different,so how to How to output XY value without selecting an area.

","

I found an effective method in the help document +Finding the maximum value of von Mises stress +https://help.3ds.com/2020/english/dssimulia_established/simacaecmdrefmap/simacmd-c-odbintroexamaxmisespyc.htm?contextscope=all

",python +"Scraping Hotel Info by using the existing list of urls in csv file

I have scraped urls of 3 hotel information pages from TripAdvisor and stored in a csv file. After importing the csv file, I have to use these 3 urls to scrape each hotel name, get the price range of each hotel and their hotel class. The tool of Selenium is used.

+ +

Here is my code. When using the URL of single hotel, I can scrape the name of hotel. However, when it comes to a lot of hotels to scrape, it doesn't work. It seems there are problems in "for" loop.

+
!pip install selenium
+
+from selenium import webdriver
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.common.keys import Keys
+import csv
+from time import sleep
+from time import time
+from random import randint
+
+browser = webdriver.Chrome(executable_path= 'C:\ProgramData\Anaconda3\Lib\site-packages\jupyterlab\chromedriver.exe')
+result_list=[]
+
+def start_request(q):
+   r = browser.get(q)
+   print("crlawling "+q)
+   return r
+
+def parse(text):
+   container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
+   mydict = {}
+
+   for results in container1:
+        try:
+            mydict['name'] = results.find_element_by_xpath('//*[@id="HEADING"]')
+
+         except Exception as e:
+            print(e)
+            print('not____________________________found')
+            mydict['name'] = 'null'
+            result_list.append(mydict)
+
+with open('Best3HotelsLink.csv') as f:
+    reader = csv.DictReader(f)
+    for row in reader:
+          req = row['Link']
+          text = start_request(req)
+          parse(text)
+          sleep(randint(1,3))
+
+import pandas as pd
+df = pd.DataFrame(result_list)
+df.to_csv('Detailed Hotelinfo.csv')
+df
+
+

I also have tried to scrape the hotel class and the price range of the hotels, but in vain. +Hotel Class +Price Range

+

I would like to seek your advice on how to fix the above problems. Many thanks.

","

if you have lot informations to scrape i suggest you to reload informations each time:

+

try this code:

+
def parse(text):
+   time.sleep(2)   # i suggzest you to add some time to wait to load the page
+   container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
+   nbrcontainer = len(container1)
+   mydict = {}
+
+   for i in range(0, nbrcontainer):
+        container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
+        results = container1[i]
+        try:
+            mydict['name'] = results.find_element_by_xpath('//*[@id="HEADING"]')
+
+         except Exception as e:
+            print(e)
+            print('not____________________________found')
+            mydict['name'] = 'null'
+            result_list.append(mydict)
+
",python +"Float of each element in a matrix python ::

I am trying the convert the elements in a matrix to a float number, wanna the output to be 0.200, instead of 0.2 ? +(as the numerical precision is not the same as in Matlab for example, and it affects the results on what i want ? +When I tried float() I got the following error: +"TypeError: only size-1 arrays can be converted to Python scalars"

+

Any help, +I attached the code:

+
import numpy as np
+
+ A=np.array([[ 0.0186428,  -0.0056,         -0.0056,          0,          0,
+            0],
+             [-.1263,  0.42087542, -.1263,          0,          0,
+             0],
+             [-.1263, -.1263, 0.42087542,  0,          0,
+             0],
+            [0,         0,          0,          0.2,        -0,
+             0        ],
+            [ 0,          0,          0,         -0,          0.2,
+              0        ],
+            [-0,         -0,          0,          0,          0,
+              0.2       ]])
+
+            B=np.array([[1,0,0,0,0,0],[0,1,0,0,0,0],[0,0,1,0,0,0],[0,0,0,1,0,0],[0,0,0,0,1,0], 
+            [0,0,0,0,0,1]])
+
+           C=B*A*B  # float(C) NOT working ?
+           print(C)
+
","

Your variable C is already a numpy array with float valued numbers. You can check it yourself by printing

+
In [23]: C.dtype
+Out[23]: dtype('float64')
+
+

If you want to change how the numpy arrays are printed to the console, you can edit the settings with np.set_printoptions. For example:

+
In [21]: np.set_printoptions(precision=3, floatmode='fixed')
+
+In [22]: C
+Out[22]:
+array([[ 0.019, -0.000, -0.000,  0.000,  0.000,  0.000],
+       [-0.000,  0.421, -0.000,  0.000,  0.000,  0.000],
+       [-0.000, -0.000,  0.421,  0.000,  0.000,  0.000],
+       [ 0.000,  0.000,  0.000,  0.200,  0.000,  0.000],
+       [ 0.000,  0.000,  0.000,  0.000,  0.200,  0.000],
+       [ 0.000,  0.000,  0.000,  0.000,  0.000,  0.200]])
+
+
    +
  • The precision of 3 sets the values to be printed with three digits of precision
  • +
  • The floatmode of 'fixed' means:
  • +
+
+

Always print exactly precision fractional digits, even if this would +print more or fewer digits than necessary to specify the value +uniquely.

+
+

Note about multiplication

+

Based on your comment, it seems that what you are trying to achieve is matrix multiplication of matrices A and B. The * operator is element-wise multiplication. For matrix multiplication, you would want to use np.matmul(np.matmul(B,A), B).

",python +"How to fill NaN for categorical data randomly?

I have a table like this one:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
SexSchGend
MBoys
FGirls
NaNMixed
NaNBoys
+
+

And I want to fill the NaNs values within this table (there are 100 hundred of them). The SchGend tells if the school is only for boys, only for girls or for both. Thus, to fill the 4th row I want to put M as the sex, but to fill the NaN for the mixed school I want to do it with random value. I have no idea on how to put a condition in the fillna method for pandas.

+

So that is my question: how can I do that? Any tips?

","

First, fill the values for known values from the school information. Then fill the remaining randomly. +You can use random.choices to generate a random sequence of "M" and "F" (There should be alternative functions in numpy.random if you prefer).

+

If you run the below, you will get different outcomes for the third record.

+
from io import StringIO
+import random
+import pandas as pd
+
+data = """
+Sex SchGend
+M   Boys
+F   Girls
+NaN Mixed
+NaN Boys
+"""
+
+x = pd.read_csv(StringIO(data), sep="\t")
+
+# fill cases of boys or girls school
+x.loc[x.SchGend == "Boys", "Sex"] = "M"
+x.loc[x.SchGend == "Girls", "Sex"] = "F"
+
+num_na = x.Sex.isna().sum()  # number of missing cases
+x.loc[x.Sex.isna(), "Sex"] = random.choices(["M", "F"], k=num_na)
+x
+
",python +"Python threading.Semaphore vs asyncio.Semaphore

I recently noticed there are two different Semaphore implementations in different packages in python, one is in threading package and another is in asyncio package. And I am curious what is the difference between these two implementation? If in async function I try to use Semaphore from threading package, would that cause any potential problems?

+

And by checking python official documentation, it wrote

+
asyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use threading for that)
+
+

But what does that mean by saying asyncio primitives are not thread-safe and should not be used for OS thread sync?

+

Thanks in advance

","

The whole goal of a semaphore is to provide exclusive access to something. Only one "piece of code" can access own the semaphore at any one time.

+

What I mean by "piece of code" in the previous statement depends on whether I'm using multi-threading, multi-processing, or asyncio. And the means by which you guarantee exclusive access depends on what I'm using.

+

Asyncio is the most restricted kind of multi-threading. Everything is running within a single Python thread. The Python interpreter is only executing one thing at a time. Each "piece of code" runs until it voluntarily waits for something to happen. Then another "piece of code" is allowed to run. Eventually the original piece of code runs again when the thing it was waiting on happens.

+

With multithreading, multiple pieces of code are running within the Python interpreter. Only one piece of code runs at any time, but they are not politely waiting for each other. Python switches from "piece of code" to "piece of code" as it wants.

+

With multiprocessing, multiple Pythons are running simultaneously. +There is no sharing between the pieces of code, other than what is provided by the operating system. To set up a semaphore usually requires some support from the operating system to create a shared variable that all threads/processes can access.

+

So. Asyncio primitives are designed so that they are all run within a single Python process with the processes cooperating. They are not designed to work if multiple pieces of code try to use it simultaneously.

+

I hope this helps.

",python +"To Find Vowel-Substring From a String

I have a string of lowercase English letters and an integer of the substring length. I have to find the substring of that length that contains the most vowels.

+

Example:

+

s = 'azerdii'

+

k = 5

+

The possible 5 character substrings are:

+
    +
  1. 'azerd' No. of vowels = 2
  2. +
  3. 'zerdi' No. of vowels = 2
  4. +
  5. 'erdii' No. of vowels = 3
  6. +
+

So the answer should be 'erdii'

+

Here is my code:

+
def findSubstring(s, k):
+    i = 0
+    lst = []
+    count = 0
+    tempL = []
+    
+    while(i != len(s)):
+        a = i+k
+        temp = s[i:a]
+        lst.append(temp)
+        if a != len(s):
+            i+=1
+        else:
+            break
+    
+    for word in lst:
+        for alphabet in word:
+            if alphabet in 'aeiou':
+                count += 1
+        tempL.append(count)
+    print(lst)
+    print(tempL)
+    return 
+
+s = input()
+
+k = int(input().strip())
+
+print(findSubstring(s, k))
+
+I'm getting 
+
+['azerd', 'zerdi', 'erdii']
+[2, 4, 7]
+
+

But the count should be

+
[2, 2, 3]
+
+

Please forgive any stupid errors I may have. I will certainly appreciate any help.

","

Try the following:

+
def find_substr(s, k):
+    substrings = [s[i:i+k] for i in range(len(s) - k + 1)] # list of substrings
+    # vowels = [sum(c in 'aeiou' for c in s) for s in substrings]
+    # print(vowels) # [2, 2, 3]
+    return max(substrings, key=lambda s: sum(c in 'aeiou' for c in s))
+
+print(find_substr('azerdii', 5)) # 'erdii'
+
+

If you un-comment the lines that are commented out, you will see the number of vowels is correctly computed as [2, 2, 3].

+
+

Here, sum(c in 'aeiou' for c in s) gets the number of vowels in a string s, which is equivalent to

+
count = 0
+for alphabet in word:
+    if alphabet in 'aeiou':
+        count += 1
+
+

which in turn is the same as your code, except the line count = 0. After processing each word, you need to reset count. So try adding count = 0 in your code.

",python +"How to run seperate folder of pytests in VScode

I'm trying to run a pytests for my code in VSCode from a separate folder, but I keep getting the following error:

+
ModuleNotFoundError: No module named 'src'
+
+

My basic file structure is:

+
Root
+|
+|- src
+| |- file1.py
+|
+|- tests
+| |- test_file.py
+
+

My code in test_file.py is:

+
from src import file1
+
+

I saw How to run tests without installing package? and all of the millions of other import questions but I still can't figure it out. I've also tried

+
from ..src import file1
+
+

but then I get an ImportError: attempted relative import beyond top-level package

+

How do I use imports in this way to run tests on my code?

","

You can modify the PYTHONPATH to avoid this problem. You can refer to the official docs.

+
+

An example of when to use PYTHONPATH would be if you have source code +in a src folder and tests in a tests folder. When running tests, +however, those tests can't normally access modules in src unless you +hard-code relative paths.

+

To solve this problem, you could add the path to src to PYTHONPATH by +creating an .env file within your VS Code workspace.

+

PYTHONPATH=src Then set python.envFile in your settings.json file to +point to the .env file you just created. For example, if the .env file +was in your workspace root, your settings.json would be set as shown:

+

"python.envFile": "${workspaceFolder}/.env"

+
+

And the Test is not routed through the terminal, so setting the terminal.integrated.env.* will not work.

",python +"Count the number of atoms of each element

I have to access a file and count the number of atoms of each element. That is, count the number of times of the last character.

+

For example, I have a file named 14ly.pdb with the following lines:

+
ATOM 211 N TYR A 27 4.697 8.290 -3.031 1.00 13.35 N
+
+ATOM 212 CA TYR A 27 5.025 8.033 -1.616 0.51 11.29 C
+
+ATOM 214 C TYR A 27 4.189 8.932 -0.730 1.00 10.87 C 
+
+ATOM 215 O TYR A 27 3.774 10.030 -1.101 1.00 12.90 O
+
+

I should get as a result: 'N':1, 'C':2, 'O':1, that is, 1 atom of type N, 2 of type C and 1 of type O.

+

I have the following incomplete code that I need to complete:

+
import os
+
+def count_atoms(pdb_file_name):
+  num_atoms = dict()
+  with open(pdb_file_name) as file_content:
+
+##Here should go the code I need## 
+
+return num_atoms
+result = count_atoms('14ly.pdb')
+print(result)
+
","
number_of_atoms = dict()
+with open("14ly.pdb", "r") as f:
+    for line in f:
+        line_words = line.split(" ")
+        last_char = line_words[-1].rstrip('\n')
+        if last_char in number_of_atoms.keys():
+            number_of_atoms[last_char] += 1
+        else:
+            number_of_atoms[last_char] = 1
+print(number_of_atoms)
+
+

I think this should be enough

",python +"Specifying steps in y-axis of Pandas plot()

I use the following plot function to create a line chart of a Pandas dataframe

+
row = df.iloc[0].astype(int)
+plt.subplot(1, 2, 1)
+row.plot(marker='o', fontsize=20, ylabel=yax_label)
+plt.show()
+
+

Problem is that, the y steps are shown in float (0.5 steps). Is there any way to control that? For example, 3,4,5,6,7 as integers.

+

","

You can use .set_yticks():

+

(I can't run your code, send an example)

+
import matplotlib.pyplot as plt
+
+fig, axe = plt.subplots(1, 3, constrained_layout=True)
+
+axe[0].plot(range(10))
+axe[0].set_yticks(np.arange(0,10,0.5))
+
+axe[1].plot(range(10))
+axe[1].set_yticks(np.arange(0,10))
+
+axe[2].plot(range(10))
+axe[2].set_yticks(np.arange(0,10,2))
+plt.show()
+
+

Output:

+

",python +"How can I enumerate and add margin_titles to each subplot in a seaborn lmplot facetgrid?

I have the following attached lmplot facetgrid

+

To start with, I want to simplify the title of each subplot, to only have corpus = {corpus name}.

+

I am generating these plots using the lmplot as per

+
g=sns.lmplot('x', 'y', data=test_plot, col='corpus', hue = 'monotonicity', row='measure', sharey=True, sharex=True, height=2.5,aspect=1.25, truncate=False, scatter_kws={"marker": "D", "s": 20})
+
+g=(g.set_axis_labels("Max-Min (measure)", "Max-Min (comp measure)")
+        .set(xlim=(0, 1), ylim=(-.1, 1))
+        .fig.subplots_adjust(wspace=.02))
+
+

I want to use the facetgrid margin_title option to put the measure value on the right y-axis, but get lmplot() got an unexpected keyword argument 'margin_titles'

+

I then tried using a facetgrid, as per:

+
p = sns.FacetGrid(data = test_plot,
+                           col = 'corpus',
+                           hue = 'monotonicity',
+                           row = 'measure',
+                           margin_titles=True)
+    
+
+p.map(sns.lmplot, 'diff_', 'score_diff',  data=test_plot, he='monotonicity', truncate=False, scatter_kws={"marker": "D", "s": 20})
+
+

but then I get an error about lmplot() got an unexpected keyword argument 'color' (cannot figure out why that is being thrown?).

+

My second problem is that I want to add a letter/enumeration to each subplot's title, as in (a), ..., (i), but for the life of me cannot figure out how to do this.

","

Because of your custom needs, consider iterating through all the axes of the FacetGrid after running your lmplot. Regarding your specific error, seaborn.lmplot is a FacetGrid so will conflict if nested in another FacetGrid as tried in your second attempt. Also, in below solution, do not re-assign g to axes setup which returns NoneType:

+
#... SAME lmplot ...
+
+(
+  g.set_axis_labels("Max-Min (measure)", "Max-Min (comp measure)")
+   .set(xlim=(0, 1), ylim=(-.1, 1))
+   .fig.subplots_adjust(wspace=.02)
+)
+
+alpha = list('abcdefghijklmnopqrstuvwxyz')
+axes = g.axes.flatten()
+
+# ADJUST ALL AXES TITLES
+for ax, letter in zip(axes, alpha[:len(axes)]):
+    ttl = ax.get_title().split("|")[1].strip()   # GET CURRENT TITLE
+    ax.set_title(f"({letter}) {ttl}")            # SET NEW TITLE
+
+# ADJUST SELECT AXES Y LABELS
+for i, m in zip(range(0, len(axes), 3), test_plot["measure"].unique()):
+    axes[i].set_ylabel(m)
+
+

Input (purely random data for demonstration)

+
import numpy as np
+import pandas as pd
+
+np.random.seed(1172021)
+
+test_plot = pd.DataFrame({
+    'measure': np.random.choice(["precision", "recall", "F1-score"], 500),
+    'corpus': np.random.choice(["Fairview", "i2b2", "MiPACQ"], 500),
+    'monotonicity': np.random.choice(["increasing", "non", "decreasing"], 500),
+    'x': np.random.uniform(0, 1, 500),
+    'y': np.random.uniform(0, 1, 500)
+})
+
+
+

Output

+

",python +"Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X

Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X.

+
    Input:
+        n = 5, X = 10
+        arr[] = [1 2 4 3 6]
+        
+    Output:
+        Yes
+        
+    Explanation:
+        The triplet {1, 3, 6} in 
+        the array sums up to 10.
+
","

the line of reasoning is: +Get all the possible combinations of 3 numbers in the array arr. Find which has sum=X, print only these triplets

+
import numpy as np
+import itertools
+arr=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+X=10
+combinations=np.array(list(itertools.combinations(arr, 3)))
+triplets=combinations[combinations.sum(axis=1)==X]
+
+print(f'Triplets with sum equal to {X} are:\n{triplets}')
+
+

output:

+
Triplets with sum equal to 10 are:
+[[0 1 9]
+ [0 2 8]
+ [0 3 7]
+ [0 4 6]
+ [1 2 7]
+ [1 3 6]
+ [1 4 5]
+ [2 3 5]]
+
",python +"Problem with rotating a two-dimensional array in python

How to to make this array rotate by 90 degrees to right without using numpy.

+
multiarray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+auxiliaryArray = []
+colLength = len(multiarray[0])
+rowLength = len(multiarray)
+for indexRow in range(len(multiarray)):
+    for indexCol in range(len(multiarray[0])):
+        auxiliaryArray[indexCol][rowLength - 1 - indexRow] = multiarray[indexRow][indexCol]
+
+print(auxiliaryArray)
+
+

Error: +IndexError: list index out of range

+

Desired Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

","

You can use zip on the reversed array:

+
auxiliaryArray = list(zip(*multiarray[::-1]))
+
+

or

+
auxiliaryArray = list(zip(*reversed(multiarray)))
+
+

output: [(7, 4, 1), (8, 5, 2), (9, 6, 3)]

+

If you need lists and not tuples:

+
auxiliaryArray = list(map(list, zip(*reversed(multiarray))))
+
+

output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

",python +"Manipulating Dataframes in different sub directories

I have many subdirecotries in which I have unique datasets. I want to do some manipulations on this df individually. Something like: Access to each subdirectory, do manipulation, go to next directory and do the same. For illustrative purposes I can provide the code:

+
import pandas as pd
+import numpy as np
+import os 
+
+
+os.mkdir('folder1')
+
+d = {'column1': ['a', 'a', 'b', 'b', 'c'], 'column2': [10, 8, 6, 4, 2], 'column3': [1, 2, 3, 4, 5]}
+test_a  = pd.DataFrame(data=d)
+test_a.to_csv('folder1/test_a.csv')
+
+os.mkdir('folder2')
+g = {'column1': ['a', 'a', 'b', 'b', 'c'], 'column2': [10, 8, 6, 4, 2], 'column3': [1, 2, 3, 4, 5]}
+test_b = pd.DataFrame(data=g)
+test_b.to_csv('folder2/test_b.csv')
+
+

The code above creates the subdirectories and then saves example df in this subdirectory.

+

Let's say I want to achieve the following:

+

Grouby (count) each dataset in each folder by column1, and save it in the corresponding subdirectory as a separate data frame. Better to call each data frame by the starting letters (test in this case), rather than its extension (csv).

+

I can write the general function on how to grouby the datasets, but I don't know how to access each subdirectory. (probably using the for loop and os/glob package).

+

Thanks in advance.

","

Use pathlib:

+
import pandas as pd
+import pathlib
+
+# directory where data files are stored
+data_dir = pathlib.Path('data')
+
+for csvfile in data_dir.glob('**/*.csv'):
+    print(f"Processing '{csvfile.name}' in '{csvfile.parent}'")
+    df = pd.read_csv(csvfile)
+    # do stuff here
+    out = df.groupby('column1').mean()  # mean or whatever you want
+    out.to_csv(csvfile.parent / f"{csvfile.stem}_grp.csv")
+    print(f"Saved as '{csvfile.stem}_grp.csv' in '{csvfile.parent}'")
+    print()
+
+

Output:

+
Processing 'test_a.csv' in 'data/folder1'
+Saved as 'test_a_grp.csv' in 'data/folder1'
+
+Processing 'test_b.csv' in 'data/folder2'
+Saved as 'test_b_grp.csv' in 'data/folder2'
+
+

Directory tree:

+
data
+├── folder1
+│   ├── test_a.csv
+│   └── test_a_grp.csv
+└── folder2
+    ├── test_b.csv
+    └── test_b_grp.csv
+
",python +"How can I take a list input from a file and turn it into a dictionary?

So I've been looking all over StackOverflow for a way to properly solve my issue, but I haven't found anything suitable.

+

I am taking in a file that has words with associated values in the format of:

+
alone,1  
+amazed,10  
+amazing,10  
+bad,1  
+etc.  
+
+

I am taking in this text file and reading the lines, which breaks each of the lines into a list. I then need to transfer this list into a dictionary type, where the keyword and value are kept associated.

+

I found a solution for this problem in another question, but it currently gives an output that includes \n within the value part of the dictionary.
+Here is the code:

+
keywords_file = open('keywords.txt')
+keywords = keywords_file.readlines()
+
+def keyword_to_dictionary(keywords):
+    result = [{}]
+    for item in keywords:
+        key, val = item.split(",", 1)
+        if key in result[-1]:
+            result.append({})
+        result[-1][key] = val
+    return result
+
+

Output:

+
[{'alone': '1\n', 'amazed': '10\n', 'amazing': '10\n', 'bad': '1\n', 'best': '10\n',
+'better': '10\n', 'excellent': '10\n', 'excited': '10\n', 'excite': '10\n', 'excites':
+'10\n', 'exciting': '10\n', 'glad': '10\n', 'god': '5\n', 'good': '7\n', 'great': '7\n',
+'greatest': '10\n', 'haha': '5\n', 'hahaha': '5\n', 'happy': '10\n', 'hate': '1\n',
+'hurt': '1\n', 'hurts': '1\n'}]
+
+

The output is longer but I hope that gives a decent idea of what is happening. I understand the issue, but I'm not sure how to go about solving it.

+

To give some context in how this is going to be used, I have a comp sci assignment that requires me to equate a few thousand lines of twitter data with keywords in this file, outputting a sort of happiness level average that is going to be associated with the geographical area that the tweet was sent in, determined by timezones. I need to be able to access the keywords and equated value in order to do this and figured a dictionary was the best way to do that.

+

context tldr: need to access the keyword and value associated with it when iterating through thousands of lines of Twitter data.

+

Any help would be greatly appreciated.

+

Apologies if there is anything wrong with this post or more information is required which I didn't provide.

+

Thanks in advance.

","

You can use a dictionary comprehension:

+
with open('keywords.txt') as f:
+    result = {k: int(v) for line in f for k,v in [line.strip().split(',')]}
+
",python +"Python project - Writing contents of .txt file to Pandas dataframe

I'm currently working on a Python project where I want to:

+
    +
  1. Loop through subdirectories of a root directory
  2. +
  3. Find .txt files with names starting with 'memory_'. Txt files are: +newline-separated, lines consist of: 'colName: Value' pairs. Like this.
  4. +
+
Memory dump
+
+Serialnr: 1412b23990
+
+Date/time: 24-11-2016 08:10
+
+
+
+mode: version
+
+Hardware release: ic2kkit01*P131113*
+
+Software release: V3.82
+
+Rom test 1 checksum: e0251fda
+
+Rom test 2 checksum: cae0351f
+
+
+
+mode: statistics
+
+Line power connected (hours): 360
+
+Line power disconnected (number of times): 2
+
+Ch function(hours): 54
+
+Dhw function(hours): 4
+
+Burnerstarts (number of times): 604
+
+Ignition failed (number of times): 0
+
+Flame lost (number of times): 0
+
+Reset (number of times): 0
+
+
+
+mode: status
+
+T1: 17.42
+
+T2: 17.4
+
+T3: 16.38
+
+T4: -35.0
+
+T5: -35.0
+
+T6: 17.4
+
+Temp_set: 0.0
+
+Fanspeed_set: 0.0
+
+Fanspeed: 0.0
+
+Fan_pwm: 0.0
+
+Opentherm: 0
+
+Roomtherm: 0
+
+Tap_switch: 0
+
+
+
    +
  1. Appending the contents of the .txt file to a Pandas data frame with predefined column names. I.e.: I would like to write each .txt file into a data frame row, using the colName:Value pairs. See attached image for how (a part of) the data frame should look like.
  2. +
+

Current .py code:

+
import os
+import pandas as pd
+
+# Set rootdir for os.walk
+rootdir = 'K:/Retouren' 
+
+## Create empty Pandas dataframe with just column names
+column_names = ["Memory dump", "Serialnr", "Date/time", "mode", "Hardware release", "Software release", "Rom test 1 checksum", "Rom test 2 checksum", 
+    "mode", "Line power connected (hours)", "Line power disconnected (number of times)", "Ch function(hours)", "Dhw function(hours)", "Burnerstarts (number of times)", 
+    "Ignition failed (number of times)", "Flame lost (number of times)", "Reset (number of times)", "Gasmeter_ch", "Gasmeter_dhw", "Watermeter", "Burnerstarts_dhw", 
+    "mode", "T1", "T2", "T3", "T4", "T5", "T6", "Temp_set", "Fanspeed_set", "Fanspeed", "Fan_pwm", "Opentherm", "Roomtherm", "Tap_switch", "Gp_switch", "Pump", "Dwk", 
+    "Gasvalve", "Io_signal", "Spark", "Io_curr", "Displ_code", "Ch_pressure", "Rf_rth_bound", "Rf_rth_communication", "Rf_rth_battery_info", "Rf_rth_battery_ok", 
+    "Bc_tapflow", "Pump_pwm", "Room_override_zone1", "Room_set_zone1", "Room_temp_zone1", "Room_override_zone2", "Room_set_zone2", "Room_temp_zone2", "Outside_temp", 
+    "Ot_master_member_id", "Ot_therm_prod_version", "Ot_therm_prod_type", "mode", "Node nr", "Cloud id0", "Cloud id1", "Cloud id2", "Rf cloud nr", "Rssi_lower", 
+    "Rssi_upper", "Rssi_wait", "Attention_period", "Attention_number", "Info10", "Info11", "Info12", "Info13", "Info14", "Info15", "Info16", "Info17", "Info18", 
+    "Ramses_thermostat_idh", "Ramses_thermostat_idm", "Ramses_thermostat_idl", "Ramses_boiler_idh", "Ramses_boiler_idm", "Ramses_boiler_idl", "Prod. token", 
+    "Year", "Month", "Line number", "Serial1", "Serial2", "Serial3", "mode", "Id_dongle0", "Id_dongle1", "Id_dongle2", "Id_dongle3", "Id_lan0", "Id_lan1", 
+    "Id_lan2", "Id_lan3", "Info2_7", "Info2_8", "Info2_9", "Info2_10", "Info2_11", "Info2_12", "Info2_13", "Info2_14", "mode", "Interrupt_time", 
+    "Interrupt_load (%)", "Main_load (%)", "Net fequency (hz)", "Voltage ref. (v)", "Checksum1", "Checksum2", "nmode", "Fault 0", "Fault 1", "Fault 2", 
+    "Fault 3", "Fault 4", "Fault 5", "Fault 6", "Fault 7", "Fault 8", "Fault 9", "Fault 10", "Fault 11", "Fault 12", "Fault 13", "Fault 14", "Fault 15", 
+    "Fault 16", "Fault 17", "Fault 18", "Fault 19", "Fault 20", "Fault 21", "Fault 22", "Fault 23", "Fault 24", "Fault 25", "Fault 26", "Fault 27", "Fault 28", 
+    "Fault 29", "Fault 30", "Fault 31", "mode", "Heater_on", "Comfort_mode", "Ch_set_max", "Dhw_set", "Eco_days", "Comfort_set", "Dhw_at_night", "Ch_at_night", 
+    "Parameter 1", "Parameter 2", "Parameter 3", "Parameter 4", "Parameter 5", "Parameter 6", "Parameter 7", "Parameter 8", "Parameter 9", "Parameter a", 
+    "Parameter b", "Parameter c", "Parameter c", "Parameter d", "Parameter e", "Parameter e.", "Parameter f", "Parameter h", "Parameter n", "Parameter o", 
+    "Parameter p", "Parameter r", "Parameter f.", "mode", "Param31", "Param32", "Param33", "Param34", "Param35", "Param36", "Param37", "Param38", "Param39", 
+    "Param40", "Param41", "Param42", "Param43", "Param44", "Param45", "Param46", "Param47", "Param48", "Param49", "Param50", "Param51", "Param52", "Param53", 
+    "Param54", "Param55", "Param56", "Param57", "Param58", "Param59", "Param60", "Param61", "Param62", "Param63"]
+data = pd.DataFrame(columns = column_names)
+
+for subdir, dirs, files in os.walk(rootdir):
+    for file in files:
+        if file.startswith('memory_') and os.path.splitext(file)[1] == '.txt':
+            filepath = os.path.join(subdir, file)
+            with open (filepath, "r") as curfile:
+                data.append()  
+                ## Here is where I would like to append the .txt data as a row in the data frame
+ 
+
+

I have the first two steps down, but the third is exceeding my programming knowledge. Any tips would be greatly appreciated.

+

Example of the desired dataframe:

+

","

I suggest reading the file with readlines(), which will return a list of lines. Then loop over the lines and process only those that contain : in the string. Split by the colon (and trailing whitespace) while wrapping everything in dict() will create a dictionary with the strings before the colon as keys and the strings after the colons as values:

+
dict(i.split(': ',1) for i in curfile.readlines() if ':' in i)
+
+

for your sample data this would make:

+
{'Serialnr': '1412b23990', 'Date/time': '24-11-2016 08:10', 'mode': 'status', 'Hardware release': 'ic2kkit01*P131113*', 'Software release': 'V3.82', 'Rom test 1 checksum': 'e0251fda', 'Rom test 2 checksum': 'cae0351f', 'Line power connected (hours)': '360', 'Line power disconnected (number of times)': '2', 'Ch function(hours)': '54', 'Dhw function(hours)': '4', 'Burnerstarts (number of times)': '604', 'Ignition failed (number of times)': '0', 'Flame lost (number of times)': '0', 'Reset (number of times)': '0', 'T1': '17.42', 'T2': '17.4', 'T3': '16.38', 'T4': '-35.0', 'T5': '-35.0', 'T6': '17.4', 'Temp_set': '0.0', 'Fanspeed_set': '0.0', 'Fanspeed': '0.0', 'Fan_pwm': '0.0', 'Opentherm': '0', 'Roomtherm': '0', 'Tap_switch': '0'}
+
+

If you create an empty list before the loop, and append the dictionaries to that list within the loop, you'll end up with a list of dicts that you can load with pandas in one go:

+
import os
+import pandas as pd
+
+# Set rootdir for os.walk
+rootdir = 'K:/Retouren' 
+
+## Create empty list
+data = []
+
+for subdir, dirs, files in os.walk(rootdir):
+    for file in files:
+        if file.startswith('memory_') and os.path.splitext(file)[1] == '.txt':
+            filepath = os.path.join(subdir, file)
+            with open (filepath, "r") as curfile:
+                data.append(dict(i.split(': ',1) for i in curfile.readlines() if ':' in i))  
+            
+df = pd.DataFrame(data)
+
+

An added advantage is that you don't need to set the column names manually, because pandas will use the dict keys for that. DataFrame:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SerialnrDate/timemodeHardware releaseSoftware releaseRom test 1 checksumRom test 2 checksumLine power connected (hours)Line power disconnected (number of times)Ch function(hours)Dhw function(hours)Burnerstarts (number of times)Ignition failed (number of times)Flame lost (number of times)Reset (number of times)T1T2T3T4T5T6Temp_setFanspeed_setFanspeedFan_pwmOpenthermRoomthermTap_switch
01412b2399024-11-2016 08:10statusic2kkit01P131113V3.82e0251fdacae0351f360254460400017.4217.416.38-35-3517.40000000
+
+

There is one disadvantage: as a dict can only contain unique keys you will lose two mode values. I'll leave it as they seem to be headers rather than containers of information. Otherwise it would require some additional renaming.

",python +"Poetry installed but `poetry: command not found`

I've had a million and one issues with Poetry recently.

+

I got it fully installed and working yesterday, but after a restart of my machine I'm back to having issues with it ;(

+

Is there anyway to have Poetry consistently recognised in my Terminal, even after reboot?

+
+

System Specs:

+
    +
  • Windows 10,
  • +
  • Visual Studio Code,
  • +
  • Bash - WSL Ubuntu CLI,
  • +
  • Python 3.8.
  • +
+
+

Terminal:

+
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/workers-python/workers/data_simulator/src$ poetry run python3 cli.py
+poetry: command not found
+me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/workers-python/workers/data_simulator/src$ curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3
+Retrieving Poetry metadata
+
+This installer is deprecated. Poetry versions installed using this script will not be able to use 'self update' command to upgrade to 1.2.0a1 or later.
+Latest version already installed.
+me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/workers-python/workers/data_simulator/src$ poetry run python3 cli.py
+poetry: command not found
+me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/workers-python/workers/data_simulator/src$ 
+
+

Please let me know if there is anything else I can add to post to help further clarify.

","

When I run this, after shutdown of bash Terminal:

+
export PATH="$HOME/.poetry/bin:$PATH"
+
+

poetry command is then recognised.

+

However, this isn't enough alone; as every time I shutdown the terminal I need to run the export.

+

Possibly needs to be saved in a file.

",python +"How to re-arrange only certain columns of a Pyspark Dataframe without listing out all the column names?

I have a Pyspark Dataframe having 100 columns (shown only 5 below for explaining):

+

+

I need to re-arrange the index of around 30 specific columns only, and leave the rest as it is. +The sequence (i.e. index) in which the specific columns need to be arranged is listed out in an Excel table as below (shown only 3 below for explaining):

+

+

Now, I could have used df = df.select('C', 'E', 'B',...and so on)

+

But it becomes too tedious to write down all 100 column names in the correct sequence above.

+

So is there any efficient way to do this by simply reading the sequence from the table as a list and using it as a reference to do the re-arrangement of columns?

+

To continue with the example to be clear, if there were just these 5 columns out of which 3 had to be re-arranged, then the output would like this: +

+

Note: I'm using Python 2.7.5 & Spark 2.4.0

","

you can access all the columns with the property df.columns (which is a python list) and simply plays with it in a list comprehension :

+
# assuming you can create the object sequence from the excel
+sequence = ["C", "E", "B"]
+
+df = df.select(sequence + [col for col in df.columns if col not in sequence])
+
+df
+> DataFrame[C: string, E: string, B: string, A: string, D: string]
+
",python +"How do i remove the .0 from an integer?

I have an integer in my code and want to connect it with other integers.

+
str1 = ''
+int1 = 4
+int2 = 16
+int3 = 32
+int4 = 64
+
+int5 = int4 / int3
+int6 = int2 / int1
+
+str1 += str(int5)
+str1 += str(int6)
+
+print(str1)
+
+

now the output would be 2.04.0, but i want it to be 24. How do i remove the .0?

","

You need to get values as int so you need to change these two lines:

+
int5 = int4 // int3
+int6 = int2 // int1
+
+

Then you can use f-string:

+
print(f'{int5}{int6}')
+
+

Or use your own code:

+
str1 += str(int5)
+str1 += str(int6)
+print(str1)
+
",python +"Write a function to reduce duplicate code

I have two very similar for loops, I want to have an inner function to reduce the duplicate codes, they look like this:

+
team_members = TeamMember.objects.all()
+managers = Manager.objects.all()
+for m in managers:
+        name = f"{m.name.first_name} {m.name.last_name}"
+//reset of the code are the same
+for t in team_members:
+        name = f"{t.member.first_name} {t.member.last_name}"
+//reset of the code are the same
+
+

So the problem is managers and team_members querysets have different field names for people's names. +If I want to write an inner function, how to solve the different field names?

","

Here is the inner function which will take objs as input and fetch the values based on objects attribute.

+
def inner_fun(objs):
+    for obj in objs:
+        if hasattr(obj, 'name'):
+            name_obj = getattr(obj, 'name')
+        else:
+            name = getattr(obj, 'member')
+        name = f"{name_obj.first_name} {name_obj.last_name}"
+    return name
+
+team_members = TeamMember.objects.all()
+managers = Manager.objects.all()
+
+team_name = inner_fun(team_members)
+manager_name = inner_fun(managers)
+
",python +"Pandas - Loop through sheets

I have 5 sheets and created a script to do numerous formatting, I tested it per sheet, and it works perfectly.

+
import numpy as np
+import pandas as pd
+           
+FileLoc = r'C:\T.xlsx'
+Sheets = ['Alex','Elvin','Gerwin','Jeff','Joshua',]
+
+df = pd.read_excel(FileLoc, sheet_name= 'Alex', skiprows=6) 
+df = df[df['ENDING'] != 0]
+df = df.head(30).T
+df = df[~df.index.isin(['Unnamed: 2','Unnamed: 3','Unnamed: 4','ENDING' ,3])]
+df.index.rename('STORE', inplace=True)
+df['index'] = df.index
+
+df2 = df.melt(id_vars=['index', 2 ,0, 1] ,value_name='SKU' )
+df2 = df2[df2['variable']!= 3]
+
+df2['SKU2'] = np.where(df2['SKU'].astype(str).fillna('0').str.contains('ALF|NOB|MET'),df2.SKU, None)
+df2['SKU2'] = df2['SKU2'].ffill()
+df2 = df2[~df2[0].isnull()]
+df2 = df2[df2['SKU'] != 0]
+
+df2[1] = pd.to_datetime(df2[1]).dt.date
+df2.to_excel(r'C:\test.xlsx', index=False)
+
+

but when I assigned a list in Sheet_name = Sheets it always produced an error KeyError: 'ENDING'. This part of the code:

+
Sheets = ['Alex','Elvin','Gerwin','Jeff','Joshua',]
+df = pd.read_excel(FileLoc,sheet_name='Sheets',skiprows=6) 
+
+

Is there a proper way to do this, like looping?

+

My expected result is to execute the formatting that I have created and consolidate it into one excel file.

+

NOTE: All sheets have the same format.

+

","

In using the read_excel method, if you give the parameter sheet_name=None, this will give you a OrderedDict with the sheet names as keys and the relevant DataFrame as the value. So, you could apply this and loop through the dictionary using .items().

+

The code would look something like this,

+
dfs = pd.read_excel('your-excel.xlsx', sheet_name=None)
+for key, value in dfs.items():
+  # apply logic to value
+
+

If you wish to combine the data in the sheets, you could use .append(). We can append the data after the logic has been applied to the data in each sheet. That would look something like this,

+
combined_df = pd.DataFrame()
+dfs = pd.read_excel('your-excel.xlsx', sheet_name=None)
+for key, value in dfs.items():
+  # apply logic to value, which is a DataFrame
+  combined_df = combined_df.append(sheet_df)
+
",python +"How do I make an if statement in with multiple parameter using excel columns in python csv

So basically I am trying to write a statement where if a value in Col1 = 1 or Col2 = 1 than create a new column with the value 10 and if both Col1 and Col2 = 0 the new column should print 0 or just skip.

+

so far this is what I did

+
if df.Col1 == 1 or df.Col2 == 1:
+    df['newCol'] = 10
+else: pass
+
+

This is giving me an error.

","

You can do this:

+
df['newCol'] = np.where(((df['Col1']==1)|(df['Col2']==1)), 10,np.nan)
+
",python +"Field data disappears in Django REST framework

I have a field "plugins" (see below) in my serializer and this is a serializer which also contains a file upload which is why the MultiPartParser is used. My view is pretty much standard, and the plugins field data also shows up in the request.data, however it doesn't show up in the validated_data of the serializer. To bring a minimalistic example, this would be my serializer:

+
class CreationSerializer(serializers.ModelSerializer, FileUploadSerializer):
+    plugins = serializers.ListSerializer(
+        child=serializers.CharField(), required=False, write_only=True)
+
+    class Meta:
+        fields = ['plugins'] + FileUploadSerializer.Meta.fields
+        model = Company
+
+    def create(self, validated_data):
+        print(validated_data)
+
+

While this would be my views.py:

+
@swagger_auto_schema(request_body=CreationSerializer(), responses={201: CreationSerializer()}, operation_id='the_post')
+def create(self, request, *args, **kwargs):
+    print(request.data)
+    return super().create(request, *args, **kwargs) # which uses mixins.CreateModelMixin
+
+

I tried adding another parser (i.e. JSONParser) to the parsers list, but this doesn't change anything.

","

Does it work if you replace with this? I'm not sure but maybe drf doesn't recognize ListSerializer as a field, I've always used a Serializer with many=True:

+
plugins = serializers.ListField(child=serializers.CharField(), required=False, write_only=True)
+
",python +"TypeError: can only concatenate str (not ""float"") to str

my code:

+
def média_harmonica(x,y):
+    média_harmonica = 2/((1/x)+(1/y))
+    return média_harmonica
+
+x = float(input("Informe um número para x: "))
+y = float(input("Informe um número para y: "))
+
+média_harmonica = (2/((1/x)+(1/y)))
+mensagem = "A média harmonica de "+x+" e "+y+" é: "+float(média_harmonica)
+print(mensagem)
+
","

As the error suggests, you cannot concatenate a float to a string. You can add that variable to the string in a few ways:

+
    +
  1. F-strings: +mensagem = f"A média harmonica de {x} e {y} é: {média_harmonica}"

    +
  2. +
  3. casting: mensagem = "A média harmonica de " + str(x) + " e " + str(y) + " é:" + str(média_harmonica)

    +
  4. +
",python +"Genetic algorithm: problem of convergence

I'm trying to find the solution of the one-max problem with a genetic algorithm, but it is not converging, instead the maximum fitness is getting lower. I can't see why it's not working; I tried to execute the functions on their own and they worked, I'm not sure about the calling in the main though.the one max problem is when you have a population N of binary individuals (1/0) of length m, and you want to optimize your population so you generate at least one individual containing only 1s (in my case 0s)

+

Here's my code:

+
import random
+
+def fitness(individual):
+    i = 0
+    for m in individual:
+        if m == 0:
+            i += 1
+    return i
+
+def selection(pop):
+    chosen = []
+    for i in range(len(pop)):
+        aspirants = []
+        macs = []
+        for j in range(3):
+            aspirants.append(random.choice(pop))
+        if fitness(aspirants[0]) > fitness(aspirants[1]):
+            if fitness(aspirants[0]) > fitness(aspirants[2]):
+                macs = aspirants[0]
+            else: macs = aspirants[2]
+        else:
+            if fitness(aspirants[1]) > fitness(aspirants[2]):
+                macs = aspirants[1]
+            else: macs = aspirants[2]
+        chosen.append(macs)
+    return chosen
+
+def crossover(offspring):
+    for child1, child2 in zip(offspring[::2], offspring[1::2]):
+        if random.random() < 0.7:
+            child1[50:100], child2[50:100]=child2[50:100], child1[50:100]
+
+def mutate(offspring):
+    for mut in offspring:
+        if random.random() < 0.3:
+            for i in range(len(mut)):
+                if random.random() < 0.05:
+                    mut[i] = type(mut[i])(not mut[i])
+
+def gen_individ():
+    ind = []
+    for s in range(100):
+        ind.append(random.randint(0, 1))
+    return ind
+
+def gen_pop():
+    pop = []  
+    for s in range(300):
+        pop.append(gen_individ())
+    return pop
+
+g = 0
+popul = gen_pop()
+print("length of pop = %i "% len(popul))
+fits = []
+for k in popul:
+    fits.append(fitness(k))    
+print("best fitness before = %i"% max(fits))
+while(max(fits) < 100 and g < 100):   
+    g += 1
+    offspring = []
+    offspring = selection(popul)
+    crossover(offspring)
+    mutate(offspring)
+    popul.clear()
+    popul[:] = offspring
+    fits.clear()
+    for k in popul:
+    fits.append(fitness(k))
+print("lenght of pop = %i "% len(popul))
+print("best fitness after = %i"% max(fits))  
+print("generation : %i"%g)
+
","

The problem seems to be that in all your functions, you always just modify the same individuals instead of creating copies. For instance, in the selection function you repeatedly select the best-out-of-three (in a rather convoluted way), and then insert multiple references to that same list into the chosen list. Later, when you mutate any of those, you mutate all the references. In the end you might even end up with just N references to the same list, at which point obviously no more actual selection can take place.

+

Instead, you should create copies of the lists. This can happen in different places: in your main method, in mutate and recombine, or in the selection for the next iteration. I'll put it into selection, mainly for the reason that this function can be improved in other ways, too:

+
def selection(pop):
+    chosen = []
+    for i in range(len(pop)):
+        # a lot shorter
+        aspirants = random.sample(pop, 3)
+        macs = max(aspirants, key=fitness)
+        # create COPIES of the individual, not multiple references
+        chosen.append(macs[:])
+    return chosen
+
+

With this, you should get a quality of 100 each time.

",python +"Connect to MariaDB database on Synology NAS from SQLalchemy in python issue

furthering my question here, I am trying to put this question in a simpler way.

+

Following this tutorial, I am trying to start a connection to my Mariadb database in my NAS with SQLalchemy remotely. Here is the code:

+
# Module Imports
+import mariadb
+import sys
+
+
+user = "my_name"
+passwd = "my_pass"
+host = "192.168.1.111"
+db = "test"
+port= "3307"
+
+# Connect to MariaDB Platform
+try:
+    conn = mariadb.connect(
+        user=user,
+        password=passwd,
+        host=host,
+        port=3307,
+        database=db
+
+    )
+except mariadb.Error as e:
+    print(f"Error connecting to MariaDB Platform: {e}")
+    sys.exit(1)
+
+# Get Cursor
+cur = conn.cursor()
+
+

then I get this error:

+
ERROR:root:Internal Python error in the inspect module.
+Below is the traceback from this internal error.
+
+Error connecting to MariaDB Platform: Can't connect to server on '192.168.1.111' (36)
+Traceback (most recent call last):
+  File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 14, in <module>
+    conn = mariadb.connect(
+mariadb.OperationalError: Can't connect to server on '192.168.1.111' (36)
+
+During handling of the above exception, another exception occurred:
+
+Traceback (most recent call last):
+  File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3444, in run_code
+    exec(code_obj, self.user_global_ns, self.user_ns)
+  File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 24, in <module>
+    sys.exit(1)
+SystemExit: 1
+
+During handling of the above exception, another exception occurred:
+
+Traceback (most recent call last):
+  File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1101, in get_records
+    return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
+  File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 248, in wrapped
+    return f(*args, **kwargs)
+  File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
+    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
+  File "/Users/user/miniforge3/lib/python3.9/inspect.py", line 1541, in getinnerframes
+    frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
+AttributeError: 'tuple' object has no attribute 'tb_frame'
+
+

I have brew installed mariadb-connector-cand ; +brew installed mariadb; and +pip installed PyMySQL.

+

Would anyone please help?

","

I echo with @Tim Roberts. Go to your NAS "Installed Package", click the MariaDB 10 app. In it please make sure the databases are sharable over the intranet or internet. It is called TCP/IP connection. Check it and your connection will be working.

+

This is a point lots of people forget about when they first start up Mariadb.

",python +"How to print a specific line/row from a text file?

I have a text file as following:

+
1, Max Mustermann, Male, 1000.0
+2, Nora Mustermann, Female, 790.0
+3, Tomas Mustermann, Male, 400.0
+
+

i want to read the last value from the fourth column if i type the persons number and the number 1 to show the value. Unfortunately, I can't get any further from here. How can i do this?

+
data_next = []
+for data in open("my_data.txt"):
+    liste = data.split(",")
+    number = int(liste[0])
+    name = liste[1]
+    sex = liste[2]
+    value = liste[3]
+    data_next.append(number)
+    print(f" [{number}] {name} {sex} {value}")
+
+
+which_person = int(input("WHICH PERSON?: "))
+
+if which_person in data_next:
+    print("Do you want to know the value? Press 1 for YES or 2 for NO")
+    next_input = int(input("YOUR INPUT: "))
+    if next_input == 1:
+        print(value)
+    elif next_input == 2:
+        print("THX")
+
","

The for-loop at the beginning of your code succeeds in placing all of the 'values' from the text file into one list.

+
data_next = ["1000.0", "790.0", "400.0"]
+
+

However, that list isn't useful for what you are trying to do below, which is to take input for one of the names from the data file and print the corresponding number. What you want for this is a dictionary, which links from one value to another. To achieve this, use the following code:

+
# set data_next to an empty dictionary
+data_next = {}
+for data in open("my_data.txt"):
+    liste = data.split(",")
+    number = int(liste[0])
+    name = liste[1]
+    sex = liste[2]
+    value = liste[3]
+    # set the current number equal to the current value in the dictionary
+    data_next[number] = value
+    print(f" [{number}] {name} {sex} {value}")
+
+
+which_person = int(input("WHICH PERSON?: "))
+
+# data_next.keys() will return an iterable of all of the id numbers in the dictionary
+if which_person in data_next.keys():
+    print("Do you want to know the value? Press 1 for YES or 2 for NO")
+    next_input = int(input("YOUR INPUT: "))
+    if next_input == 1:
+        # data_next[which_person] will return the value in the dictionary assigned to the number which_person    
+        print(data_next[which_person])
+    elif next_input == 2:
+        print("THX")
+
+

Another thing: +This code will perform slightly differently than you expect because of how the file is formatted When you split each line by ",".

+
"1, Max Mustermann, Male, 1000.0".split(",") == ["1", " Max Mustermann", " Male", " 1000.0"]
+
+

As you can see, the spaces after each comma are included with the next value. To fix this, change the split statement to split(", ") instead of split(",") OR remove the spaces after the commas in the file.

",python +"How to convert the last number of Str = (2021GC110) in Int on Python

I'm begginer in Django and i trying convert Str where the base for this is (2021(year) - CG(product name) - 1(ID product) -101 (var the product).

+

But I need the last number for variable.

+

exemple: +product 1: 2021CG1101 +product 2: 2021CG1102

+

this is my view.py

+
    if serialNumberForm.is_valid():
+        os = serialNumberForm.save(commit=False)
+        Produto.numeroSerie = NumeroSerie.id
+        os.numeroSerie = id
+        lastProduct = NumeroSerie.objects.last()
+        
+        if lastProduct == None:
+            prefix = datetime.date.today().year
+            fix = product.nome[3:6]
+            sufix = Produto.id
+            var = 10
+            os.serialNumber = str(prefix) + fix + str(sufix) + str(var)
+            
+        elif int(lastProduct.serialNumber[0:3]) != datetime.date.today().year:
+            prefix = datetime.date.today().year
+            fix = product.nome[3:6]
+            sufix = Produto.id
+            var = 10
+            os.serialNumber = str(prefix) + fix + str(sufix) + str(var)
+       
+        else:
+            prefix = datetime.date.today().year
+            fix = product.nome[3:6]
+            sufix = NumeroSerie.produto(os)
+            var = (lastProduct.serialNumber[-1]) =+ 1
+            os.serialNumber = str(prefix) + fix + str(sufix) + str(var)
+        
+        os.save()
+        
+
","

This looks like a task for regular expressions:

+
import re
+reg = re.compile(r"(?P<year>\d{4})(?P<group>[A-Z]{2})(?P<number>\d+)")
+match = reg.match("2021CG1101")
+if match is not None:
+    result = match.groupdict()
+    print(result['year'])
+    print(result['group'])
+    print(result['number'])
+
",python +"I keep getting positional argument errors when trying to use a method from another class in a new class

I have a ball class defined in Python, as follows, which is initialised with a mass = 1, radius = 1, and then we can set its position and velocity vectors as 2d numpy arrays.

+
class Ball():
+    
+    def __init__(self, pos = np.array([0,0]), vel = np.array([0,0]), mass = 1, radius = 1):
+        self.mass = mass
+        self.radius = radius
+        self.pos = pos
+        self.vel = vel
+
+

I also have a daughter class of Ball, called Container, which is essentially a large ball of radius 10, as follows:

+
class Container(Ball):
+    def __init__(self, radius = 10):
+        self.radius = radius
+
+

The ball class also has three methods which I would like to use in a new class, called Simulation. These methods are defined in the ball class, as follows (with the parameter other simply being another ball that the self ball collides with):

+
    def move(self, dt):
+        self.dt = dt
+        return np.add((self.pos),(np.dot((self.vel),self.dt)))
+    
+    def time_to_collision(self, other):
+        self.other = other
+        self.posdif = np.subtract(self.pos, other.pos)
+        self.veldif = np.subtract(self.vel, other.vel)
+        self.posdif = np.subtract(self.pos, other.pos)
+        self.veldif = np.subtract (self.vel, other.vel)
+        self.raddif = self.radius - other.radius
+        return (-2*np.dot(self.posdif, self.veldif) + np.sqrt(4*(np.dot(self.posdif, self.veldif)**2)-4*np.dot(self.veldif, self.veldif)*(np.dot(self.posdif, self.posdif)-np.dot(self.raddif, self.raddif))))/(2*np.dot(self.veldif, self.veldif))
+
+    def collide(self, other):
+        self.other = other
+        return self.vel - (np.dot(self.veldif, self.posdif)*self.posdif)/(np.dot(self.posdif,self.posdif))
+
+

Apologies for the long calculation, but I do not think that calculation line is relevant to the problem necessarily, just included it for completeness. These methods, move, time_to_collision and collide are to be used in another class, Simulation. The simulation class is defined as follows:

+
class Simulation():
+    def __init__(self, ball = Ball(), container = Container()):
+        self._container = container
+        self._ball = ball
+
+    def next_collision(self):
+        return self._ball.move(self._ball.time_to_collision(self._ball, self._container)) 
+
+

The simulation class aims to be initialised with a Ball object, and a Container object. It then has a method, next_collision, (with the only parameter being self) which uses the methods time_to_collision to work out the time between the collision of the ball and the container, and then it will use move to move the system to that moment in time, and then perform the collision using collide. The situation looks like this if a visualisation might help: +

+

I have tried to achieve this in my next_collision(self): method, but I am always getting the same type error:

+
TypeError: time_to_collision() takes 2 positional arguments but 3 were given
+
","

Your next_collision method takes just two arguments and you are passing three, just like an error says.

+

The self argument is passed automatically when you call the method on an object. So you should use it as self._ball.time_to_collision(self._container) to achieve what you want.

",python +"Z3: Find if variable is multiple of some other number

I would like to create a constraint that makes sure that a Real value is quantized to some tick value.

+
TICK = 0.5
+x = Real('x')
+solve(x % TICK == 0)
+
+

Unfortunately, this does not work with Real numbers (it works with Int and FP). +Another solution that I thought of was to create a set of valid numbers and check whether the number is part of the set, however the set would need to be really big.

+

Is there any other solution?

","

As Christoph mentioned, computing the modulus of a real-number isn't really meaningful. But your question is still valid: You're asking if x is an integer multiple of TICK. You can do this as follows:

+
from z3 import *
+
+TICK = 0.5
+x = Real('x')
+k = Int('k')
+solve(x == 1,   ToReal(k) * TICK == x)
+solve(x == 1.2, ToReal(k) * TICK == x)
+
+

This prints:

+
[k = 2, x = 1]
+no solution
+
+

Note that unless x is a constant, this'll lead to a mixed integer-real arithmetic, and it might give rise to non-linear constraints. This can make it hard for the solver to answer your query, i.e., it can return unknown or take too long to respond. It all depends on what other constraints you have on x.

",python +"Pyside2 trigger messagebox from button click closes whole application

i want to trigger a messagebox from a button click without closing the entire application, I managed to do this in my previous project, but this time, the behavior is really unexpected. as soon as I clicked ok or the cross sign on the messagebox, the app also closing too without any error. here's the minimal example

+
class MainWindow(QtWidgets.QMainWindow):
+    def __init__(self):
+        super(MainWindow, self).__init__()
+        self.set_and_load_ui()
+
+    def set_and_load_ui(self):
+        self.ui = QUiLoader().load('main.ui', self)
+
+    def trigger_messagebox(self):
+        self.messagebox()
+
+    def messagebox(self,x=""):
+        msg = QMessageBox(self)
+        msg.setIcon(QMessageBox.Information)
+        msg.setText("{}".format(x))
+        msg.setInformativeText("test")
+        msg.setWindowTitle("test")
+        msg.exec_()
+
+app = QtWidgets.QApplication(sys.argv)
+mainWindow = MainWindow()
+mainWindow.ui.show()
+# mainWindow.trigger_messagebox() #this is fine
+mainWindow.ui.mainmenuButton.clicked.connect(lambda: mainWindow.trigger_messagebox()) #this is not fine
+exit_code = (app.exec_())
+
+

just to check, if the messagebox itself is causing the problem, I tried to call it directly on my code, but turns out it just fine, but not when I tried to trigger it by a button click

","

The problem is related to the fact that QUiLoader loads the UI using the parent given as argument, and since the UI is already a QMainWindow, you're practically loading a QMainWindow into another, which is unsupported: QMainWindows are very special types of QWidgets, and are intended to be used as top level widgets.

+

It's unclear to me the technical reason for the silent quit, but it's certainly related to the fact that the loaded window actually has a parent (the MainWindow instance), even if that parent is not shown (since you're showing the ui).

+

Unfortunately, PySide doesn't provide a way to "install" a UI file to an existing instance unlike PyQt does (through the uic.loadUi function), so if you want to keep using PySide there are only two options:

+
    +
  1. do not use a main window in Designer, but a plain widget ("Widget" in the "New Form" dialog of Designer), load it using QUiLoader and use setCentralWidget() (which is mandatory, since, as the documentation also notes, "creating a main window without a central widget is not supported"):

    +
     self.ui = QUiLoader().load('main.ui', self)
    + self.setCentralWidget(self.ui)
    +
    +

    The downside of this approach is that you cannot use the main window features anymore in Designer (so, no menus, status bar, dock widgets or toolbars).

    +
  2. +
  3. use pyside-uic to generate the python code and use the multiple inheritance method to "install" it; the following assumes that you exported the ui file as mainWindow.py:

    +
     from mainWindow import ui_mainWindow
    +
    + class MainWindow(QtWidgets.QMainWindow, ui_mainWindow):
    +     def __init__(self):
    +         super(MainWindow, self).__init__()
    +         self.setupUi(self)
    +         # no "set_and_load_ui"
    +         self.mainmenuButton.clicked.connect(self.trigger_messagebox)
    +
    +     # ...
    +
    + app = QtWidgets.QApplication(sys.argv)
    + mainWindow = MainWindow()
    + mainWindow.show()
    + exit_code = (app.exec_())
    +
    +

    As you can see, now you can access widgets directly (there's no ui object). The downside of this approach is that you must remember to always generate the python file everytime you modify the related ui.

    +
  4. +
",python +"os. commands & open() on AWS S3 object

i want to implement an aws lambda function that will execute the following python script:

+
directory = os.fsencode(directory_in_string)
+
+def transform_csv(csv):
+
+   for file in os.listdir(directory):
+       filename = os.fsdecode(file)
+
+       d = open(r'C:\Users\r.reibold\Documents\GitHub\groovy_dynamodb_api\historische_wetterdaten\{}'.format(filename))
+
+       data = json.load(d)
+
+       df_historical = pd.json_normalize(data)
+
+       #Transform to datetime
+       df_historical["dt"] = pd.to_datetime(df_historical["dt"], unit='s', errors='coerce').dt.strftime("%m/%d/%Y %H:%M:%S")
+
+       df_historical["dt"] = pd.to_datetime(df_historical["dt"])
+
+.
+.
+.
+.
+  
+
+

My question is now:

+

How do i have to change the os. commands because i need to reference to the s3 bucket and not my local directory?

+

My first attempt looks like this

+
DIRECTORY = 's3://weatherdata-templates/historische_wetterdaten/New/'
+BUCKET = 'weatherdata-templates'
+
+s3 = boto3.client('s3')
+paginator = s3.get_paginator('list_objects_v2')
+pages = paginator.paginate(Bucket=BUCKET, Prefix=DIRECTORY)
+
+def lambda_handler(event, context):
+
+    for page in pages:
+        for obj in page['Contents']:
+
+            filename = s3.fsdecode(obj)
+
+            d = open(r's3://102135091842-weatherdata-templates/historische_wetterdaten/New/{}'.format(filename))
+
+            data = json.load(d)
+
+            df_historical = pd.json_normalize(data)
+.
+.
+.
+
+
+

Am i on the right track or completely wrong? +Thx.

","

Not quite there yet :)

+

Unfortunately, you can't do open(...) directly on an S3 URL as it's not a file object.

+

To load the object contents without storing the file locally, try using the S3 Boto3 resource which provides higher-level access to the S3 SDK.

+
    +
  1. Get the key of the object from obj['Key'].
  2. +
  3. Use obj.get()['Body'] to get the contents as a StreamingBody
  4. +
  5. Call .read() on the StreamingBody to get the object in byte format & decode it to a UTF-8 string (or any other encoding that your file(s) is in)
  6. +
  7. Convert JSON string to a JSON object using json.loads(...)
  8. +
+
import boto3
+s3_resource = boto3.resource('s3')
+...
+def lambda_handler(event, context):
+    for page in pages:
+        for obj in page['Contents']:
+            obj_reference = s3_resource.Object(BUCKET, obj['Key'])
+            body = obj_reference.get()['Body'].read().decode('utf-8')
+            data = json.loads(body)
+            df_historical = pd.json_normalize(data)
+            ...
+
",python +"How to make the tkinter Treeview row entries icon appear as default?

I have a strange Treeview behaviour that I can't resolve.

+

I created a widget using a ttk.Frame widget and grid a ttk.Treeview in it as its child. The #0 column shows a directory tree. For each row entry, i.e. tree node, an icon would appear. The option open=True in the .insert() method was used.

+

When this script is executed, all the icons appear in the Treeview as a default.

+

However, when this same widget is imported into another script and added into a ttk.PanedWindow widget, the icons in the Treeview does not appear immediately. The icons would only appear when the Treeview row entry is opened by clicking on it. A second click would close the Treeview row entry and the icons would disappear.

+

I would like the icons in the ttk.Treeview to appear as a default. How do I do this?

","

I found the cause of this phenomenon. When I customised the style of the ttk.Treeview widget in the other script, I discovered the value of the background option was missing a # symbol. The phenomenon of the ttk.Treeview icon not appearing as a default is caused by an incorrect syntax in the value of the background option.

+

OS: Linux

+

Test code reproducing the phenomenon caused by incorrect syntax.

+
#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+
+import tkinter as tk
+import tkinter.ttk as ttk
+
+
+class App(ttk.Frame):
+
+    def __init__(self, parent=None, *args, **kwargs):
+        super().__init__(parent)
+        self.parent = parent
+
+        # Create Treeview
+        self.tree = ttk.Treeview(self, column=('A', 'B'), selectmode='none', height=7)
+        self.tree.grid(row=0, column=0, sticky='nsew')
+
+        # Setup column heading
+        self.tree.heading('#0', text=' Pic directory', anchor='center')
+        self.tree.heading('#1', text=' A', anchor='center')
+        self.tree.heading('#2', text=' B', anchor='center')
+        # #0, #01, #02 denotes the 0, 1st, 2nd columns
+
+        # Setup column
+        self.tree.column('A', anchor='center', width=100)
+        self.tree.column('B', anchor='center', width=100)
+
+        # Insert image to #0
+        # change to your file path
+        self._img = tk.PhotoImage(file="./imagename.png")
+        self.tree.insert('', 'end', text="#0's text", image=self._img,
+                         value=("A's value", "B's value"))
+
+
+if __name__ == '__main__':
+    # Works
+    root = tk.Tk()
+    root.geometry('400x180+300+300')
+    app = App(root)
+    app.grid(row=0, column=0, sticky='nsew')
+    root.rowconfigure(0, weight=1)
+    root.columnconfigure(0, weight=1)
+    root.mainloop()
+
+    # Don't Works - syntax error in value of background causing missing icon
+    # in Treeview.
+    root = tk.Tk()
+    root.geometry('400x180+300+300')
+    style = ttk.Style()
+    style.configure('Treeview', background='303495')  # should be '#303495'
+    app = App(root)
+    app.grid(row=0, column=0, sticky='nsew')
+    root.rowconfigure(0, weight=1)
+    root.columnconfigure(0, weight=1)
+    root.mainloop()
+
",python +"Efficient deduplication in Python

I have coded a little code who attribute, to each element of a list, a score... To do this, I need to do this (simplified code):

+
group={1:["Jack", "Jones", "Mike"],
+       2:["Leo", "Theo", "Jones", "Leo"],
+       3:["Tom", "Jack"]}
+
+already_chose=["Tom","Mike"]
+result=[]
+
+for group_id in group:
+    name_list = group[group_id]
+    y=0;x=0
+    repeat=[]
+    for name in name_list:
+        if name in already_chose:
+            y+=1
+        elif name not in repeat:
+            x+=1
+            repeat.append(name)
+    score_group=x-y
+    result.append([group_id,score_group])
+
+

output: [[1, 1], [2, 3], [3, 0]]

+

The issue is, if you read this code, that it's not optimized to a big enumeration (more than 7000 groups and 100 names by groups)...

+

I hope someone can help me ? Thanks a lot

","

IIUC, you want to get the length of the set of the unique names not in already_chose minus the number of names in already_chose.

+

This is easily achieved with python sets and a list comprehension. The advantage in using python sets, is that operations are very fast due to hashing of the elements.

+
[[k, len(set(v).difference(already_chose))-len(set(v).intersection(already_chose))]
+ for k,v in group.items()]
+
+

output: [[1, 1], [2, 3], [3, 0]]

+

NB. might be more useful as dictionary comprehension:

+
{k: len(set(v).difference(already_chose))-len(set(v).intersection(already_chose))
+ for k,v in group.items()}
+
+

output: {1: 1, 2: 3, 3: 0}

",python +"Initializing python object using different object types as arguments

I'v read how to overload... and multiple constructors in python and a few more on this topic, however I'm looking for something more specific.
+I'm given a list of Content objects and a list of Data objects:

+
class Content:
+    def __init__(self):
+        self._title = 'movie title'
+        self._url = 'http://movie-url'
+
+    @property
+    def title(self):
+        return self._title
+
+    @property
+    def url(self):
+        return self._url
+
+
+class Data:
+    def __init__(self):
+        self._title = 'movie title'
+        self._year = 2021
+        self._rating = 7.6
+
+    @property
+    def title(self):
+        return self._title
+
+    @property
+    def year(self):
+        return self._year
+
+    @property
+    def rating(self):
+        return self._rating
+
+

I want to match each Content with it's corresponding Data by the title property and combine everything under one class Movie, by passing one of the other objects to Movie's init argument:

+
movie_content = Movie(Content())
+movie_data = Movie(Data())
+
+

From what I'v read so far my options are:

+
    +
  • Default arguments: Doesn't seem to fit here (correct me if I'm wrong) since I want to pass only one argument anyway.
  • +
  • *args: I prefer to avoid passing a long line of arguments (there will be at least 12).
  • +
  • @classmethod: This approach is the most appealing to me, but I'm struggling with the implementation:
  • +
+
class Movie:
+    def __init__(self, object):
+        self.object = object
+
+    @classmethod
+    def by_content(cls, content):
+        _title = content.title
+        _url = content.url
+
+        return cls( # what goes here?)
+
+    @classmethod
+    def by_data(cls, data):
+        _title = data.title
+        _year = data.year
+        _rating = data.rating
+
+        return cls( # what goes here?)
+
+
    +
  • Using methods as multi-setters, which I'm currently using (not the most pythonic from my understanding):
  • +
+
class Movie:
+    def __init__(self):
+        self._title = ''
+        self._url = ''
+        self._year = 0
+        self._rating = 0.0
+
+    def by_content(self, content):
+        self._title = content.title
+        self._url = content.url
+
+    def by_data(self, data):
+        self._title = data.title
+        self._year = data.year
+        self._rating = data.rating
+
+

Any thoughts or suggestions would be greatly appreciated.

","

You can use the classmethods as secondary constructors - where you will use the values from the second parameter in the function to fill out the attributes in your Movie class's constructor.

+

I have made the example using dataclasses since that makes the code shorter, with the same functionality. (or more)

+
from dataclasses import dataclass
+
+@dataclass
+class Content:
+    title: str
+    url: str
+
+@dataclass
+class Data:
+    title: str
+    year: str
+    rating: float
+
+@dataclass
+class Movie:
+    title: str
+    year: str
+    rating: float
+    url: str
+
+    @classmethod
+    def by_content(cls, content: Content): return cls(
+        title = content.title,
+        url = content.url,
+        rating = 0,
+        year = 0,
+    )
+
+    @classmethod
+    def by_content(cls, data: Data): return cls(
+        title = data.title,
+        url = 'https://null.com',
+        rating = data.rating,
+        year = data.year,
+    )
+
",python +"ModuleNotFoundError: No module named 'flask_mail'

I am creating a web application where the user will receive a confirmation mail after they've registered. +But I am getting an error in the command line, Traceback (most recent call last): +File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app +import(module_name) +File "/home/ubuntu/flask/registration/application.py", line 3, in +from flask_mail import Mail, Message +ModuleNotFoundError: No module named 'flask_mail' and an error on the web page, Internal Server Error +The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

+

application.py

+
import os
+from flask import Flask, redirect, render_template, request
+from flask_mail import Mail, Message
+from cs50 import SQL
+
+app = Flask(__name__)
+app.config["MAIL_DEFAULT_SENDER"] = os.getenv("MAIL_DEFAULT_SENDER")
+app.config["MAIL_PASSWORD"] = os.getenv("MAIL_PASSWORD")
+app.config["MAIL_PORT"] = 587
+app.config["MAIL_SERVER"] = smtp.gmail.com
+app.config["MAIL_USE_TLS"] = True
+app.config["MAIL_USERNAME"] = os.getenv("MAIL_USERNAME")
+mail = Mail(app)
+
+
+db = SQL("sqlite:///froshims.db")
+REGISTRANTS = {}
+
+SPORT=["Cricket", "Football", "Badminton", "Kho-Kho", "Kabaddi"]
+
+@app.route("/", methods = ["GET", "POST"])
+def index():
+    if request.method == "GET":
+        return render_template("index.html", sports = SPORT)
+    email = request.form.get("email")
+    sport = request.form.get("sport")
+    if not email:
+        return render_template("failure.html", message="E-mail not entered")
+    if not sport:
+        return render_template("failure.html", message="Sport not selected")
+    if sport not in SPORT:
+        return render_template("failure.html", message="Sport not in list. Don't try to hack our website.")
+    if request.method == "POST":
+        REGISTRANTS[name]=sport
+        print("yes")
+        db.execute("INSERT INTO registrants (name, sport) VALUES (?,?)", name, sport)
+        message = Message("You are registered!", recipients=[email])
+        mail.send(message)
+        return redirect("success")
+
+@app.route("/success")
+def success():
+    print("kaam kar na")
+    registrants = db.execute("SELECT * FROM registrants")
+    return render_template("success.html", registrants = registrants)
+
+

I am unable to figure out the issue. I am new to Flask. Please guide me.

","

I had the same problem with flask_mail import. pip installing Flask-Mail in a virtual environment on a code editor alone might not cause a module import error. +Go to your command line into the app directory +Also, make sure the pip version in your venv environment is up to date.

+
pip install Flask-Mail
+
+

This worked for me.

",python +"Vectorization of Product Over

I am seeking a vectorized form of the following computation:

+
import numpy as np
+D = 100
+N = 1000
+K = 10
+
+X = np.random.uniform(0, 1, (K, N))
+T = np.random.uniform(0, 1000, (D, N))
+out = np.zeros((D, K))
+
+for i in range(D):
+    for j in range(K):
+        out[i, j] = np.prod(X[j, :] ** T[i, :])        
+
+
+

There are einsum-style things I've tried, but the presence of the np.prod is throwing me off a bit.

+

EDIT: Reduced size of matrices.

","

I'm trying to make the broadcasting as explicit as possible - the None introduces an additional dummy dimension of size 1:

+
out = np.prod(X[None, :, :] ** T[:, None, :], axis=2)
+
+

It is easy to see how it works if we recall the shapes: X.shape = (K, N), T.shape = (D, N) and out.shape = (D, K). With the dummy dimension we basically take something of (1, K, N) to the power of (D, 1, N) which results in (D, K, N). Finally if we reduce via product over the last dimension we get our desired output of (D, K).

",python +"matching query does not exist. Django Error

this is my code for my project, I just get this error I tried to figure it out but I don't get it,

+

Django Error:

+
+

DoesNotExist at /save_post/

+

Profile matching query does not exist.

+

views.py, line 75, in save_post +form.authore = Profile.objects.get(user=request.user)

+
+

views.py

+
    @login_required
+    def save_post(request):
+        if request.method == "POST":
+            form = Post(content=request.POST['content'])
+            form.authore = Profile.objects.get(user=request.user)
+            form.save()
+        elif request.method == "PUT":
+            data = json.loads(request.body)
+            post_id = int(data["post_id"])
+            new_content = data["new_content"]
+            post = Post.objects.filter(id=post_id).first()
+            if post.authore.user != request.user:
+                return HttpResponse(status=401)
+            post.content = new_content
+            post.save()
+            return JsonResponse({
+                "result": True
+            }, status=200)
+        else:
+            return JsonResponse({
+                "error": "post not found"
+            }, status=400)
+        return index(request)
+
+

models.py

+
    class User(AbstractUser):
+    pass
+
+
+class Profile(models.Model):
+    user = models.ForeignKey(User, on_delete=models.CASCADE)
+
+
+class Post(models.Model):
+    content = models.TextField()
+    timestamp = models.DateTimeField(default=timezone.now)
+    authore = models.ForeignKey(Profile, on_delete=models.CASCADE)
+    likes = models.PositiveIntegerField(default=0, blank=True, null=True)
+
+    def serialize(self):
+        return {
+            "id": self.id,
+            "content": self.content,
+            "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"),
+            "authore": self.authore.id,
+            "username": self.authore.user.username,
+            "likes": self.likes.count(),
+        }
+
","

this seems correct but you already this user you are using doesn't have profile +so here my notes :

+

You can use get_object_or_404 this if profile not found will return not found

+
from django.shortcuts import  get_object_or_404
+form.authore =  get_object_or_404(Profile, user=request.user)
+
+

when user-created no logic here profile must created so it is logical user doesn't have profile

+

it is better to use one_to_one relation ship when creating user profile as each user has only one profile and vice versa

+

to make it correct working refer here +https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

+
+

go to Extending User Model Using a One-To-One Link in previous link

+
+

field execute this tutorial and user profile will created auto when user created

",python +"How can I say to Python to do an instruction at a given time?

I want that a specific time of the day (for example 10:00:00), one of my if condition activates.

+

For example:

+

if time is 10:00:00: +print("Hello world")

+

Imortant: I already read this: Python script to do something at the same time every day

+

But I don't want to use a function!

","

You could easy use datetime to help you with that.

+
import datetime
+from time import sleep
+
+timing = [10, 0, 0] # Hour, minute, second, in 24 hour time
+
+while True: # Repeat forever
+    now = datetime.datetime.now()
+    data = [now.hour, now.minute, now.second]
+    if data == timing:
+        # Code to be executed
+        print("Hello World")
+        #######
+        sleep(1) # To ensure the command is not repeated again
+        # break # Uncomment this if you want to execute the command only once
+
+

Make sure that I indented it properly, because one space can tick python off :).

+

The way that it works: +import datetime and from time import sleep import the necessary modules and functions that you will need.

+

Modules needed: +datetime +time.sleep

+

Now we're set. +timing = [10,0,0] sets the time that you want to use (you'll see why later)

+

while True repeats the loop... on and on and on.

+

now = datetime.datetime.now() creates a shortcut for such a long piece of text.

+

data == timing makes sure the time matches the timing you asked.

+
+

Note that the timing is in UTC +Go to Getting the correct timezone offset in Python using local timezone to know how to find your offset.

+
+

An offset of UTC-0200 (Or -7200 seconds) means that you need to ADD 2 hours to your time to get UTC. Or, if your time zone is UTC+0200, SUBSTRACT 2 hours from your time.

",python +"Using dict values to count iterations over a list to insert
import random
+from itertools import repeat
+
+races_per_season = {
+    '2015' : "19",
+    '2016' : "21",
+    '20116' : "21",
+    '2017' : "20",
+    '2018' : "21",
+    '2019' : "21",
+    '2020' : "17",
+    '2021' : "16"
+}
+
+tmp_list = list(repeat(random.sample(range(80),10), 156))
+total_races = 0
+for k,v in races_per_season.items(): 
+    while total_races < int(v):
+        tmp_list[total_races].insert(1, k)
+        total_races += 1
+        break # inserting breaks here and below, somewhat works, but only gives me the first year throughout the list
+    break
+
+
+for x in tmp_list:
+    print(x)
+
+

I am trying to use the dict values to iterate over a list of list and insert the key into the list at index 1. However, no matter how I try, it seems to iterate and insert all keys into the list then moves on to the next...

+

This is the result I am seeing.... however by adding the breaks above, this continues throughout the list of 156 lists.. and doesn't change at list 19

+
[[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015',  56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015',  56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73]]
+
+

but my desired result is the following.

+
[[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
+ [29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73]...
+
+

and continuing with '2015' 19 times, then inserting '2016' into the following 21 etc.. When I just print out the k,v pairs it works as I want it to, but I can't somehow convert that into a list. All values in the dict sum to the value of the len(tmp_list) 156

+

ANY help would be more than appreciated. Thanks

","

Check this

+
import random
+from itertools import repeat
+
+races_per_season = {
+    '2015' : "19",
+    '2016' : "21",
+    '20116' : "21",
+    '2017' : "20",
+    '2018' : "21",
+    '2019' : "21",
+    '2020' : "17",
+    '2021' : "16"
+}
+# this line to create 156 lists that are not sharing the same reference
+tmp_list = [list(arr) for arr in repeat(random.sample(range(80),10), 156)]
+i = 0
+for k,v in races_per_season.items():
+    total_races = 0
+    while total_races < int(v):
+        tmp_list[i].insert(0, k)
+        tmp_list[i].insert(0, int(v))
+        total_races += 1
+        i+=1
+
+for x in tmp_list:
+    print(x)
+
",python +"staticmethod decorator seems pointless

I was reading about the @staticmethod in Python when I came across tge following code:

+
class MyClass:
+    my_var = 0
+
+    @staticmethod
+    def static_method():
+        MyClass.my_var += 1
+
+

I just don't understand exactly why you can write a code like this... Doesn't it defeat the purpose of this method to be static?

+

I get it that there's also the fact that the first parameter won't be a class/instance reference, but... Still weird to call this decorator like that if I still can access class variables, no?

+

And if I can access class variables, why everywhere I read about it says that I cannot, even though I just clearly did with the code above? Is it just because I'm doing it wrong?

","

The idea that a static method can't modify class state is based on the idea that the static method doesn't receive a reference to the class as an argument like a class method does. However, in this case, a reference to the class is provided as a hard-coded value.

+

One reason for defining a static method rather than a class method is to guarantee that you modify the attribute of a specific class, rather than a possible subclass.

+
class A:
+   my_var = 0
+
+   @classmethod
+   def foo(cls):
+       cls.my_var += 1
+
+   @staticmethod
+   def bar():
+       A.my_var += 1
+
+
+class B(A):
+    my_var = 0
+
+

A call to B.foo will modify B.my_var, not A.my_var. A call to B.bar will modify A.my_var.

",python +"How resize dataset label in albumentations label to work with tensorflow image_dataset_from_directory function?

I am running the following code: +[https://pastebin.com/LK8tKZtN] +The error obtained is following:

+
+

File "C:\Users\Admin\PycharmProjects\BugsClassfications\main2.py", +line 45, in set_shapes * +label.set_shape([])

+
ValueError: Shapes must be equal rank, but are 1 and 0
+
+
+

How correct function set_shape to work with image_dataset_from_directory?

+

Here is my code:

+
import tensorflow as tf
+import numpy as np
+import matplotlib.pyplot as plt
+from functools import partial
+from albumentations import (Compose, HorizontalFlip,Rotate)
+ 
+AUTOTUNE = tf.data.experimental.AUTOTUNE
+ 
+def process_image(image, label, img_size):
+  # cast and normalize image
+  image = tf.image.convert_image_dtype(image, tf.float32)
+  # apply simple augmentations
+  image = tf.image.random_flip_left_right(image)
+  image = tf.image.resize(image,[img_size, img_size])
+  return image, label
+ 
+transforms = Compose([
+Rotate(limit=40),
+HorizontalFlip()
+])
+ 
+ 
+def aug_fn(image, img_size):
+  data = {"image":image}
+  aug_data = transforms(**data)
+  aug_img = aug_data["image"]
+  aug_img = tf.cast(aug_img/255.0, tf.float32)
+  aug_img = tf.image.resize(aug_img, size=[img_size, img_size])
+  return aug_img
+ 
+ 
+def process_data(image, label, img_size):
+  aug_img = tf.numpy_function(func=aug_fn, inp=[image, img_size], Tout=tf.float32)
+  return aug_img, label
+ 
+ 
+def set_shapes(img, label, img_shape=(128,128,3)):
+  img.set_shape(img_shape)
+  label.set_shape([])
+  return img, label
+ 
+ 
+def view_image(ds):
+  image, label = next(iter(ds))  # extract 1 batch from the dataset
+  image = image.numpy()
+  label = label.numpy()
+  
+  fig = plt.figure(figsize=(22, 22))
+  for i in range(20):
+    ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
+    ax.imshow(image[i].astype(dtype=np.uint8))
+    ax.set_title(f"Label: {label[i]}")
+  plt.show()
+ 
+ 
+train_dir = './dataset/train'
+img_size = 128
+data = tf.keras.utils.image_dataset_from_directory(train_dir, image_size=(img_size, img_size))
+print(data)
+ 
+#augmentation
+ds_alb = data.map(partial(process_data, img_size = 128), num_parallel_calls=AUTOTUNE).prefetch(AUTOTUNE)
+#resize
+ds_alb = ds_alb.map(set_shapes, num_parallel_calls=AUTOTUNE).batch(32)
+ 
+print(ds_alb)
+
","

If you change the shape of your labels, it should work:

+
def set_shapes(img, label, img_shape=(128,128,3)):
+  img.set_shape(img_shape)
+  label.set_shape([1,])
+  return img, label
+
+

But you should ask yourself why you are even explicitly setting the shape of your data. Check this post.

",python +"Can python cursor.execute accept multiple queries in one go?

Can the cursor.execute call below execute multiple SQL queries in one go?

+
cursor.execute("use testdb;CREATE USER MyLogin")
+
+

I don't have python setup yet but want to know if above form is supported by cursor.execute?

+
import pyodbc 
+# Some other example server values are
+# server = 'localhost\sqlexpress' # for a named instance
+# server = 'myserver,port' # to specify an alternate port
+server = 'tcp:myserver.database.windows.net' 
+database = 'mydb' 
+username = 'myusername' 
+password = 'mypassword' 
+cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
+cursor = cnxn.cursor()
+#Sample select query
+cursor.execute("SELECT @@version;") 
+row = cursor.fetchone() 
+while row: 
+    print(row[0])
+    row = cursor.fetchone()
+
","

Multiple SQL statements in a single string is often referred to as an "anonymous code block".

+

There is nothing in pyodbc (or pypyodbc) to prevent you from passing a string containing an anonymous code block to the Cursor.execute() method. They simply pass the string to the ODBC Driver Manager (DM) which in turn passes it to the ODBC Driver.

+

However, not all ODBC drivers accept anonymous code blocks by default. Some databases default to allowing only a single SQL statement per .execute() to protect us from SQL injection issues.

+

For example, MySQL/Connector ODBC defaults MULTI_STATEMENTS to 0 (off) so if you want to run an anonymous code block you will have to include MULTI_STATEMENTS=1 in your connection string.

+

Note also that changing the current database by including a USE … statement in an anonymous code block can sometimes cause problems because the database context changes in the middle of a transaction. It is often better to execute a USE … statement by itself and then continue executing other SQL statements.

",python +"Matplotlib pie chart wedges using color gradient

I am trying to create a pie chart with each wedge having a different color gradient (e.g., yellow-green) instead of a single color (e.g., green). To further explain, the gradient should be set along the radius and not the circumference of the pie.

+

Tried many options and did some research online but couldn't find a direct solution to this.

+

Is there a library or approach I should take to achieve this?

+

Thanks in advance.

","

You can create an image with the desired gradient, and position and clip it via each wedge. LinearSegmentedColormap.from_list() interpolates between given colors.

+

Here is an example:

+
import matplotlib.pyplot as plt
+from matplotlib.colors import LinearSegmentedColormap
+import numpy as np
+
+fig, ax = plt.subplots()
+
+sizes = np.random.uniform(10, 20, 4)
+color_combos = [('yellow', 'green'), ('red', 'navy'), ('yellow', 'crimson'), ('lime', 'red')]
+wedges, texts = ax.pie(sizes, labels=['alpha', 'beta', 'gamma', 'delta'])
+xlim = ax.get_xlim()
+ylim = ax.get_ylim()
+for wedge, color_combo in zip(wedges, color_combos):
+    wedge.set_facecolor('none')
+    wedge.set_edgecolor('black')
+    print(wedge.theta1, wedge.theta2)
+    bbox = wedge.get_path().get_extents()
+    x0, x1, y0, y1 = bbox.xmin, bbox.xmax, bbox.ymin, bbox.ymax
+    x = np.linspace(x0, x1, 256)[np.newaxis, :]
+    y = np.linspace(y0, y1, 256)[:, np.newaxis]
+    # fill = np.sqrt(x ** 2 + y ** 2) # for a gradient along the radius, needs vmin=0, vmax=1
+    fill = np.degrees(np.pi - np.arctan2(y, -x))
+    gradient = ax.imshow(fill, extent=[x0, x1, y0, y1], aspect='auto', origin='lower',
+                         cmap=LinearSegmentedColormap.from_list('', color_combo),
+                         vmin=wedge.theta1, vmax=wedge.theta2)
+    gradient.set_clip_path(wedge)
+ax.set_xlim(xlim)
+ax.set_ylim(ylim)
+ax.set_aspect('equal')
+plt.show()
+
+

At the left an example of a gradient along the angle, at the right a gradient along the radius.

+

",python +"Problem with Python module ""Schedule"" for timed fan control

I wrote the code below to control a fan.

+
import schedule
+import time
+import RPi.GPIO as GPIO
+
+GPIO.setmode(GPIO.BCM)              
+GPIO.setup(14, GPIO.OUT) #set pin 14 as output
+
+def aan(): 
+    GPIO.output(14,0)    #set pin 14 to "low", fan comes on
+    print(time.strftime("%H:%M")+" aan") #print time in hours and minutes, aan=on in Dutch
+
+def uit():
+    GPIO.output(14,1)    #set pin 14 to "high", fan goes off
+    print(time.strftime("%H:%M")+" uit") #print time in hours and minutes, uit=off in Dutch
+    
+schedule.every().hour.at(":00").do(aan)
+schedule.every().hour.at(":01").do(uit)
+schedule.every().hour.at(":15").do(aan)
+schedule.every().hour.at(":16").do(uit)
+schedule.every().hour.at(":30").do(aan)
+schedule.every().hour.at(":31").do(uit)
+schedule.every().hour.at(":45").do(aan)
+schedule.every().hour.at(":46").do(uit)
+
+try:
+    while True:
+        if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
+            schedule.run_pending()
+            time.sleep(1)
+        else:
+            time.sleep(1)
+
+finally:
+   print("clean up") 
+   GPIO.cleanup() # cleanup all GPIO pins
+
+

It is supposed to run for 1 minute at the 4 specified times in the schedule. The code works, but I've noticed from the print in the terminal that it also comes on 4 times on 09:00 (see below).

+
09:00 aan
+09:00 uit
+09:00 aan
+09:00 uit
+09:00 aan
+09:00 uit
+09:00 aan
+09:00 uit
+
+

I've tried changing the :00 "on" and :01 "off" schedules, but this doesn't seem to make a difference. It would be greatly appreciated if someone could help me!

","

I would address the problem a little differently as illustrated below:

+
def fan():
+    # Operate the fan 
+    on_time = 60  # Runtime in seconds
+    if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
+        GPIO.output(14,0)    #set pin 14 to "low", fan comes on
+        print(f'Turn on Fan at {time.strftime("%H:%M")}') 
+        time.sleep(on_time)
+        GPIO.output(14,1)    #set pin 14 to "high", fan goes off
+        print(f'Turn Off Fan at {time.strftime("%H:%M")}')   
+
+

Then:

+
schedule.every().hour.at(":00").do(fan)
+while True:
+        run_pending()
+        time.sleep(1)
+
+else:
+   print("clean up") 
+   GPIO.cleanup() # cleanup all GPIO pins
+
+

I can't fully test this code because I don't have your fan device, but this seems to work with just print statements.

",python +"How to store the result from loop into the variable or the list

I have the code below that runs on the active excel sheet to check specified cells. +If the specified cell shows "Fail", it will print out the failed person and the time.

+
import xlwings as xw
+import xlrd
+
+def check_result():
+    sheet = xw.books.active.sheets.active
+    for x in range(1, 5): 
+        if sheet['B' + str(x)].value =="Fail":
+            print(sheet['A' + str(x)].value, xlrd.xldate_as_datetime(sheet['C' + str(x)].value, 0))
+
+check_result()
+
+

Sample Data +How can I save this printed result into the variable or the list? +The excel file (.xlsm) is connecting to the third party software, and this file needs to be opened to generate the data.

","

From the print statement, it looks like that there are three outputs. You can have a list or tuple to save the printed data like this.

+

With List

+
List = []
+List.append([sheet['A' + str(x)].value, xlrd.xldate_as_datetime(sheet['C' + str(x)].value, 0])
+
+

NOTE: define List outside of your for loop.

+

Let me know if there is any problem with the code.

",python +"Find all partitions of n of length less-than-or-equal to L

How might I find all the partitions of n that have length less-than-or-equal-to L?

","

Based on the code given here, we can include an additional argument L (which defaults to n).

+

We might naively include if len((i,) + p) <= L: before yield (i,) + p. However, since len((i,) + p) = 1 + len(p), any partitions of n-i that are longer than L-1 are discarded. Thus time is wasted by finding them. Instead, we should include L=L-1 as an argument when finding partitions of n-1. We then need to deal with the L=0 case properly, by not running the main body:

+
def partitions(n, L=None, I=1):
+    if L is None:
+        L = n
+    
+    if L:
+        yield (n,)
+        for i in range(I, n//2 + 1):
+            for p in partitions(n-i, L-1, i):
+                yield (i,) + p
+
+

Now if L=1, the for i loop will be executed, but none of the for p loops will since the partitions calls won't yield anything; we need not execute the for i loop at all in this case, which can save a lot of time:

+
def partitions(n, L=None, I=1):
+    if L is None:
+        L = n
+    
+    if L == 1:
+        yield (n,)
+    elif L > 1:
+        yield (n,)
+        for i in range(I, n//2 + 1):
+            for p in partitions(n-i, L-1, i):
+                yield (i,) + p
+
",python +"How to split sentence in a list based on two words?

I have a list of string like this lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin'], and I would like to split the words in list if they have and or with as separators such that the final outcome is ['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']. How do I achieve this? My try was:

+
to_ret = []
+for words in lst:
+ splitted = words.split(' and')
+ to_ret.extend(splitted)
+new_ret = []
+for words in to_ret:
+ splitted = words.split(' with')
+ new_ret.extend(splitted)
+
+

but this looks very repetitive. Any suggestions for cleaner code?

","

You could use regular expressions to handle the multiple delimiters, and chain to put all of the sublists into one.

+
import re
+from itertools import chain
+lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
+
+output = [w.strip() for w in chain.from_iterable([re.split(r'and|with',x) for x in lst])]
+print(output)
+
+

Output

+
['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']
+
",python +"Creating a cube that is normal to an eigenspace in Matplotlib.pyplot

I am trying to make a cube where all the sides are normal to each of the eigenvectors, as a way to visualize principle stresses given any possible normal and shear stresses in 3d. I've tried using simple rotation matrices and applying them to a list of points but there always seems to be some error and I'm not sure if it is in how I apply the rotation matrices, the angles I give them, or the order I use.

+
import numpy as np
+import math
+import matplotlib.pyplot as plt
+from math import cos, sin
+
+ax = plt.axes(projection="3d")
+
+# normal and shear stresses
+Fx = float(input("Sigma X: "))
+Fy = float(input("Sigma Y: "))
+Fz = float(input("Sigma Z: "))
+Vxy = float(input("Tau xy: "))
+Vxz = float(input("Tau xz: "))
+Vyz = float(input("Tau yz: "))
+
+A = [[Fx, Vxy, Vxz], 
+     [Vxy, Fy, Vyz], 
+     [Vxz, Vyz, Fz]]
+
+eigval, eigvect = np.linalg.eig(A) # finding principle stresses and their directions
+
+# rounding off error
+eigvect = np.round(eigvect, 5)
+eigval = np.round (eigval, 5)
+
+# drawing eigenvectors or principle force directions
+ax.quiver(0, 0, 0, eigvect[0, 0] * 2, eigvect[1, 0] * 2, eigvect[2, 0] * 2, color="orange")
+ax.quiver(0, 0, 0, eigvect[0, 1] * 2, eigvect[1, 1] * 2, eigvect[2, 1] * 2, color="blue")
+ax.quiver(0, 0, 0, eigvect[0, 2] * 2, eigvect[1, 2] * 2, eigvect[2, 2] * 2, color="red")
+
+# drawing original normal force directions
+ax.quiver(0, 0, 0, 2 * Fx / np.abs(Fx), 0, 0, color="orange", linestyle="dashed")
+ax.quiver(0, 0, 0, 0, 2 * Fy / np.abs(Fy), 0, color="blue", linestyle="dashed")
+ax.quiver(0, 0, 0, 0, 0, 2 * Fz / np.abs(Fz),  color="red", linestyle="dashed")
+
+# points used to draw the cube
+points = np.array([[1.0, 1.0, 1.0], 
+                   [1.0, -1.0, 1.0], 
+                   [-1.0, -1.0, 1.0], 
+                   [-1.0, 1.0, 1.0], 
+                   [1.0, 1.0, 1.0], 
+                   [1.0, 1.0, -1.0], 
+                   [1.0, -1.0, -1.0], 
+                   [1.0, -1.0, 1.0],
+                   [1.0, -1.0, -1.0],
+                   [-1.0, -1.0, -1.0], 
+                   [-1.0, -1.0, 1.0],
+                   [-1.0, -1.0, -1.0],
+                   [-1.0, 1.0, -1.0],
+                   [-1.0, 1.0, 1.0],
+                   [-1.0, 1.0, -1.0], 
+                   [1.0, 1.0, -1.0]])
+
+# finding the angles that i need to rotate the cube
+x = np.arctan2(eigvect[1, 2], eigvect[2, 2])
+y = np.arctan2(eigvect[2, 0], eigvect[0, 0])
+z = np.arctan2(eigvect[0, 1], eigvect[1, 1])
+
+# rotation matrices
+xrot = np.matrix([[1, 0, 0], [0, cos(y), -sin(y)], [0, sin(y), cos(y)]])
+yrot = np.matrix([[cos(x), 0, sin(x)], [0, 1, 0], [-sin(x), 0, cos(x)]])
+zrot = np.matrix([[cos(z), -sin(z), 0], [sin(z), cos(z), 0], [0, 0, 1]])
+
+# updating the points list to rotate the cube
+for i in range(len(points)):
+    points[i] = np.dot(points[i], xrot)
+    points[i] = np.dot(points[i], yrot)
+    points[i] = np.dot(points[i], zrot)
+   
+# plotting the rotated cube
+ax.plot(points[:, 0], points[:, 1], points[:, 2], color="blue")
+
+ax.set_xlabel("X")
+ax.set_ylabel("Y")
+ax.set_zlabel("Z")
+
+plt.show() 
+
+

The most likely spot for the error is I think in either the angles that im using, variables x, y, and z, (in radians) or in the method I apply the rotation matrices. I could however be going about this completely wrong and maybe I should be using some other method of rotating the points.

+

My main goal is to just align the cube with the eigenvectors as the cube is just a visual representation. If you have any ideas or know of a different way i could do this it would be greatly appreciated!

","

I figured it out, so basicaly the angles were wrong and the rotation matrices were not general enough.

+

What I first needed to do was align the cube with one of the axies, I did this by rotating it only about the z axis to one of my vectors, then rotate it along a new vector perpendicular to the first on the xy plane, and finaly along the vector its self. Heres the code I used to fix this: (I'll also add a link to the wikapedia article with the rotation matrices as that was where i figured it out) https://en.wikipedia.org/wiki/Rotation_matrix

+
# angles used
+theta = - np.arctan2(eigvect[1, 0], eigvect[0, 0])
+Vxy = np.arccos(eigvect[2, 0])
+Uxyz = - np.arctan2(eigvect[1, 2], eigvect[2, 2])
+
+# z-axis rotation
+z_rot = np.matrix([[cos(theta), -sin(theta), 0], 
+                   [sin(theta), cos(theta),  0], 
+                   [0,      0,       1]])
+
+# making the perpendicular unit vector
+magnetude = np.sqrt(eigvect[1, 0] ** 2 + eigvect[0, 0] ** 2)
+vx = eigvect[1, 0] / magnetude
+vy = - eigvect[0, 0] / magnetude
+vz = 0
+
+# xy-plane rotation
+Vxy_rot = np.matrix([[cos(Vxy) + (vx ** 2) * (1 - cos(Vxy)), vx * vy * (1 - cos(Vxy)) - vz * sin(Vxy), vx * vz * (1 - cos(Vxy)) + vy * sin(Vxy)],
+                     [vy * vx * (1 - cos(Vxy)) + vz * sin(Vxy), cos(Vxy) + (vy ** 2) * (1 - cos(Vxy)), vy * vz * (1 - cos(Vxy)) - vx * sin(Vxy)],
+                     [vz * vx * (1 - cos(Vxy)) - vy * sin(Vxy), vz * vy * (1 - cos(Vxy)) + vx * sin(Vxy), cos(Vxy) + (vz ** 2) * (1 - cos(Vxy))]])
+
+# x, y, z components
+ux = eigvect[0, 0]
+uy = eigvect[1, 0]
+uz = eigvect[2, 0]
+
+# xyz rotation
+Uxyz_rot = np.matrix([[cos(Uxyz) + (ux ** 2) * (1 - cos(Uxyz)), ux * uy * (1 - cos(Uxyz)) - uz * sin(Uxyz), ux * uz * (1 - cos(Uxyz)) + uy * sin(Uxyz)],
+                     [uy * ux * (1 - cos(Uxyz)) + uz * sin(Uxyz), cos(Uxyz) + (uy ** 2) * (1 - cos(Uxyz)), uy * uz * (1 - cos(Uxyz)) - ux * sin(Uxyz)],
+                     [uz * ux * (1 - cos(Uxyz)) - uy * sin(Uxyz), uz * uy * (1 - cos(Uxyz)) + ux * sin(Uxyz), cos(Uxyz) + (uz ** 2) * (1 - cos(Uxyz))]])
+
+# applying the rotations
+for i in range(len(points)):
+    points[i] = np.dot(points[i], z_rot)
+    points[i] = np.dot(points[i], Vxy_rot)
+    points[i] = np.dot(points[i], Uxyz_rot)
+
",python +"Creating relationship between models when in separate files FLASK, SQLalchemy

How can I properly establish a foreign key relationship between these two models when they are currently in separate folders?

+
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
+from testserver.database import Base
+from datetime import datetime
+
+
+class Service(Base):
+    __tablename__ = 'services'
+
+    id = Column(Integer(), primary_key=True)
+    name = Column(String(25), nullable=False, unique=True)
+    description = Column(String(80), nullable=False)
+    date_created = Column(DateTime(), default=datetime.utcnow)
+    provider_id = Column(String, ForeignKey('provider.id'))
+
+
from sqlalchemy import Column, String, Integer, DateTime
+from sqlalchemy.orm import relationship
+from testserver.database import Base
+from datetime import datetime
+from testserver.database import db_session
+
+
+class Provider(Base):
+    __tablename__ = 'providers'
+
+    id = Column(Integer(), primary_key=True)
+    name = Column(String(25), nullable=False, unique=True)
+    description = Column(String(80), nullable=False)
+    date_created = Column(DateTime(), default=datetime.utcnow)
+    services = relationship(
+        'Service', cascade='all, delete-orphan', backref='provided_by')
+
+
+
from sqlalchemy.ext.declarative import declared_attr
+
+
+class Base(object):
+    __abstract__ = True
+
+    @declared_attr
+    def __tablename__(cls):
+        return cls.__name__.lower()
+
+
+

the code above currently throws an err:

+
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'services.provider_id' could not find table 'provider' with which to generate a foreign key to target column 'id'
+
+

any recommendations or solutions would be greatly apprecieted

","

I assume that you have a typo here:

+
provider_id = Column(String, ForeignKey('provider.id'))
+
+

In relationship you provided lowercased model name, instead of table name. If you replace provider with providers (because it is a name of your table) it should fix your problem

+
provider_id = Column(String, ForeignKey('providers.id'))
+
",python +"Error converting datetime string to datetime object

I get an error when I try to convert a datetime string to a datetime object:

+
df['R_DATE'] = pd.to_datetime(df['R_DATE'], format='%a %b %d %H:%M:%S %Z %Y')
+
+

Error is:

+
...
+File "pandas\_libs\tslibs\strptime.pyx", line 141, in pandas._libs.tslibs.strptime.array_strptime
+  ValueError: time data 'Mon Oct 18 00:00:00 EDT 2021' 
+    does not match format '%a %b %d %H:%M:%S %Z %Y' (match)
+
+

From what I can tell format appears to match the datetime string value. I'm not sure if the timezone value (EDT) is causing issues.

","

nvm. found the answer I was looking for.

+
import dateutil
+
+tzdict = {'EST': dateutil.tz.gettz('America/New_York'),
+      'EDT': dateutil.tz.gettz('America/New_York')}
+
+df['R_DATE'] = df['R_DATE'].apply(dateutil.parser.parse, tzinfos=tzdict)
+
",python +"How is the most efficient way to intersect a list of strings with a numpy array of matches?

I am using aho corasick to performing some string searches on documents. +The original code uses numpy array to store in an efficient way the matches of each string of a string list:

+
import ahocorasick
+import numpy as np
+
+def ahocorasickFind(search_list, input):
+    A = ahocorasick.Automaton()
+    for idx, s in enumerate(search_list):
+        A.add_word(s, (idx, s))
+    A.make_automaton()
+
+    index_list = []
+    for item in A.iter(input):
+        print(item)
+        index_list.append(item[1][0])
+
+    output_list = np.array([0] * len(search_list))
+    output_list[index_list] = 1
+    return output_list.tolist()
+
+search_list = ['joão','maria','thiago'] # thousands of words in the real code
+result = ahocorasickFind(search_list,'asdasdasd joão 1231231 thiago') # huge text in the real code
+for index, element in enumerate(result):
+    if(element == 1):
+        print(search_list[index])
+
+

Using the above approach took to much time and memory to iterate and test (if == 1). +So, how to get "original" strings found in the input text in a perfomatic way?

","

If you are only interested in matching for words (i.e. separated by a white space), rather than using a full search text, it might be faster to use a set of words. Note, however, that this uses some additional memory. One straightforward solution to replicate your behaviour would be:

+
words = set(text.split())
+for w in search_list:
+    if w in words:
+        print(w)
+
+

or even shorter (but changing the order of the result, and deleting duplicates from the search list):

+
for w in set(search_list).intersection(text.split()):
+    print(w)
+
+

I've quickly tested it on relatively large text object (143M characters, 23M words) and a rather short search_list object (606 words, of which 295 unique ones), and the times I got are:

+
    +
  • corasick: 14.5s
  • +
  • first version above: 4.6s
  • +
  • second version above: 2.6s (this speedup is just due to doing half the work only by skipping duplicates)
  • +
+

However the first version uses a (relatively) negligible amount of additional memory, while the other versions use quite a lot of it (for the data I was using, could be almost 2GB of additional memory)

",python +"Keep sub-sequences of a binary list if they surpass a given length

I want to create a function that takes as input a list (or numpy array) A and a number L. A is full of 0 and 1 and the goal is to keep the sub-sequences of 1 if they surpass L in length. I wrote a function to do it fix(A,L) but it takes to long to run so I wanted to know if their is a faster way of doing this.

+
def fix(A,L):
+    i=0
+    while True:
+        if i==len(A):
+            return(A)
+        if A[i]==1:
+            s=0
+            for j in range(i,len(A)):
+                if A[j]==1:
+                    s+=1
+                    continue
+                else:
+                    if s>=L:
+                        break
+                    else:
+                        A[i:j]=[0]*len(A[i:j])
+                        break
+            if A[j]==1 and s<L:
+                A[i:j+1]=[0]*len(A[i:j+1])
+            i=j+1
+        else:
+            i+=1
+            continue
+
+

if I call fix([1,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1], 3) it returns [0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,0] which is the correct answer.

","

If you're working with 2D numpy arrays, what you want to achieve can be done using binary erosion and dilation. We can use scipy.ndimage.binary_erosion and binary_dilation

+

We're doing it here only on a single dimension:

+
np.random.seed(0)
+A = np.random.randint(0, 2, (10, 20))
+
+from scipy.ndimage import binary_dilation, binary_erosion
+
+L = 3
+mask = np.ones((1, L))
+binary_dilation(binary_erosion(A, mask), mask).astype(int)
+
+

example input:

+
array([[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
+       [0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0],
+       [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1],
+       [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0],
+       [0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0],
+       [1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0],
+       [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0],
+       [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1],
+       [0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
+       [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0]])
+
+

output:

+
array([[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0],
+       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
+       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
+
+

Visual input/output:

+

",python +"Python bs4 .find not detecting article

i'm trying to get names of products but when it gets to the sponsored products it returns None. Here's my code;

+
    next_page_url = 'https://www.jumia.com.ng/catalog/?q=oraimo&shipped_from=country_local&page=1#catalog-listing'
+    result_nextpage = requests.get(next_page_url, headers=headers).text # headers are generated from default python 'fake_headers' module.
+    doc_nextpage = BeautifulSoup(result_nextpage, 'lxml') # I also tried other parsers
+    divs = doc_nextpage.find('div', class_='-paxs row _no-g _4cl-3cm-shs')
+    result_articles = divs.select('h3.name')
+    for i in result_articles:
+        print(i.string)
+
+

Result;

+
Oraimo FreePods-3 2Baba Edition BT 5.2 Wireless Stereo Earbuds
+Oraimo 27000mAh Massive Power Charing Bank Traveller 3 Byte
+Oraimo OPB-P116DN 10000 Mah Power-Bank Dual Fast Charging
+Oraimo FreePods3 True Wireless Stereo Earbuds IPX5 & Sweat Proof
+Oraimo Smart Watch 1.69'' IPS Screen IP68 Waterproof
+Oraimo FreePods-2 2Baba-version True Wireless Earbuds
+Oraimo Silver Edition Smart Watch 1.69'' IPS Screen IP68 Waterproof
+Oraimo Charger UKDualUSB OCW-U63D White
+Oraimo Portable Wireless Speaker Subwoofer Outdoor Sound Box
+Oraimo Charger Oraimo UKDualUSB OCW-U81F White
+Oraimo Power Oraimo Bank OPB-P206DN 20KmAh
+Oraimo SoundPro Wireless Speaker Muti-Model Music Play
+Oraimo Tempo-W3 Smart Watch Health Monitor IP67 Waterproof
+Oraimo Car Charger Oraimo OCC-21DML Black
+Oraimo SoundPro-2C 10W Portable Wireless Bluetooth Speaker
+Oraimo Necklace 5C Neckband Wireless Earphone
+Oraimo COMPACT 10000mAh Ultra Slim Fast Charging Power Bank
+Oraimo 10000mAh OPTIMIZED SLIM Power-bank With LED Light
+Oraimo Mermaid Half In-ear Earphone With Mic
+Oraimo Necklace 3 Lite Neckband BT 5.0 Wireless Earphone
+Oraimo Senior BT5.0 Single Wireless Bluetooth Headsets
+Oraimo True Wireless Bluetooth Earbuds- Freepods 2
+Oraimo FreePods-2 2Baba-version True Wireless Earbuds
+Oraimo Air-Buds-2S Super Bass Wireless Stereo Earbuds
+Oraimo 20000MAH Powerbank -long Lasting PowerBank
+Oraimo Bluetooth Wireless SOUNDBAR SPEAKER
+Oraimo Shark-2 BT5.0 In-Ear Wireless Bluetooth Headphones
+Oraimo BoomPop Over-Ear Bluetooth Wireless Headphone
+Oraimo  20000MAH Powerbank -long Lasting Power For Days
+Oraimo FreePods-2 2Baba-Version  True Wireless Stereo Earbud
+Oraimo 2021 Latest Edition Smart Function Waterproof Smart Watch
+Oraimo OCW-U36S Efficient And Durable USB Charger - Black
+Oraimo FreePods-2 2Baba-Version  True Wireless Stereo Earbud-white
+Oraimo 10000MAh Ultimate Slim Power Bank - Black
+Oraimo 20000MAH Powerbank - Power For Days
+Oraimo 10000mAh Ultra Slim Fast Charging Power Bank
+Oraimo 2020 Edition Tempo S - OSW-11 Multi Function Smart Watch
+Oraimo SOLID 27000mAh Massive Powerbank OPB-P271D Traveller 3 Byte
+Oraimo FreePods-3 2Baba Edition BT 5.2 Wireless Stereo Earbuds
+Oraimo Tempo-S IP67 Waterproof Smart Watch WITH AMAZING FUNCTIONS
+None
+None
+None
+None
+None
+None
+None
+None
+
+

The article tag 41-48 are sponsored products which the names of the product are showing from the inspect element in the browser but bs4 isn't detecting it but it detects other non-sponspored. +Please kindly help.

","

Note First of all, take a look into your soup /doc_nextpage - There is the truth you processing the data on.

+

What happens?

+

In your doc_nextpage the html for your sponsored products is empty and thats why you get these None.

+

They are empty because they will be provided dynamically by website and requests could not handle this. It is no browser, that will interpret / manipulate data.

+

How to fix?

+

One option is to simulate browser behavior with selenium and get page_source to process it with beautifulsoup or with selenium itself.

+

Example (selenium 4)

+
from bs4 import BeautifulSoup 
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.chrome.service import Service as ChromeService
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+
+options = webdriver.ChromeOptions()
+service = ChromeService(executable_path='ENTER YOUR PATH TO CHROMEDRIVER')
+driver = webdriver.Chrome(service=service, options=options)
+driver.get('https://www.jumia.com.ng/catalog/?q=oraimo&shipped_from=country_local&page=1#catalog-listing')
+
+WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '[data-list="sponsored"]')))
+
+soup = BeautifulSoup(driver.page_source, 'lxml')
+
+print([x.text for x in soup.select('article h3.name')])
+
+driver.close()
+
+

Output

+
['Oraimo FreePods-3 2Baba Edition BT 5.2 Wireless Stereo Earbuds',
+ 'Oraimo 27000mAh Massive Power Charing Bank Traveller 3 Byte',
+ 'Oraimo OPB-P116DN 10000 Mah Power-Bank Dual Fast Charging',
+ 'Oraimo FreePods3 True Wireless Stereo Earbuds IPX5 & Sweat Proof',
+ "Oraimo Smart Watch 1.69'' IPS Screen IP68 Waterproof",
+ 'Oraimo FreePods-2 2Baba-version True Wireless Earbuds',
+ "Oraimo Silver Edition Smart Watch 1.69'' IPS Screen IP68 Waterproof",
+ 'Oraimo Charger UKDualUSB OCW-U63D White',
+ 'Oraimo Portable Wireless Speaker Subwoofer Outdoor Sound Box',
+ 'Oraimo Charger Oraimo UKDualUSB OCW-U81F White',
+ 'Oraimo Portable Source 10000mAh Po Wer Ba Nk Oraimo OPB-P110D',
+ 'Oraimo Power Oraimo Bank OPB-P206DN 20KmAh',
+ 'Oraimo SoundPro Wireless Speaker Muti-Model Music Play',
+ 'Oraimo Tempo-W3 Smart Watch Health Monitor IP67 Waterproof',
+ 'Oraimo Car Charger Oraimo OCC-21DML Black',
+ 'Oraimo SoundPro-2C 10W Portable Wireless Bluetooth Speaker',
+ 'Oraimo Necklace 5C Neckband Wireless Earphone',
+ 'Oraimo 10000mAh OPTIMIZED SLIM Power-bank With LED Light',
+ 'Oraimo COMPACT 10000mAh Ultra Slim Power Fast Charging Bank',
+ 'Oraimo Mermaid Half In-ear Earphone With Mic',
+ 'Oraimo Necklace 3 Lite Neckband BT 5.0 Wireless Earphone',
+ 'Oraimo Senior BT5.0 Single Wireless Bluetooth Headsets',
+ 'Oraimo True Wireless Bluetooth Earbuds- Freepods 2',
+ 'Oraimo Pilot 20000mAh 2.1A Fast  Power Charging Bank',
+ 'Oraimo FreePods-2 2Baba-version True Wireless Earbuds',
+ 'Oraimo Air-Buds-2S Super Bass Wireless Stereo Earbuds',
+ 'Oraimo 20000MAH Powerbank -long Lasting PowerBank',
+ 'Oraimo Bluetooth Wireless SOUNDBAR SPEAKER',
+ 'Oraimo Shark-2 BT5.0 In-Ear Wireless Bluetooth Headphones',
+ 'Oraimo BoomPop Over-Ear Bluetooth Wireless Headphone',
+ 'Oraimo  20000MAH Powerbank -long Lasting Power For Days',
+ 'Oraimo FreePods-2 2Baba-Version  True Wireless Stereo Earbud',
+ 'Oraimo OCW-U36S Efficient And Durable USB Charger - Black',
+ 'Oraimo 2021 Latest Edition Smart Function Waterproof Smart Watch',
+ 'Oraimo OCW-U36S Efficient And Durable USB Charger - Black',
+ 'Oraimo Firefly-2 5.0V/2.1A Dual USB Fast Wall Charger',
+ 'Oraimo FreePods-2 2Baba-Version  True Wireless Stereo Earbud-white',
+ 'Oraimo 10000MAh Ultimate Slim Power Bank - Black',
+ 'Oraimo SOLID 27000mAh Massive Powerbank OPB-P271D Traveller 3 Byte',
+ 'Oraimo FreePods-3 2Baba Edition BT 5.2 Wireless Stereo Earbuds',
+ 'Oraimo Massive 27000mAh Travellers 3 Byte OPB-P271D Power Bank',
+ 'Oraimo 1.69" IPS Screen IP68 Waterproof Smart Watch Pro-Silver',
+ 'Oraimo Tempo-S IP67 Waterproof Smart Watch WITH AMAZING FUNCTIONS',
+ 'Oraimo FreePods-3 E104D 2Baba Edition BT 5.2 Wireless Earbuds',
+ 'Oraimo Tempo-S IP67 Waterproof Smart Watch',
+ 'Oraimo 2020 Edition Tempo S - OSW-11 Multi Function Smart Watch',
+ 'Oraimo 10000mAh Ultra Slim Fast Charging Power Bank',
+ 'Oraimo 20000MAH Powerbank - Power For Days']
+
",python +"FacetGrid returned seaborn's relplot does not respect hue

I am encountering a problem in which seaborn's relplot function creates a FacetGrid that is different from creating the FacetGrid manually. I find this unintuitive and would like the relplot function to give me a FacetGrid that behaves similarly to the manually created one.

+

The issue is that when using the map function on the FacetGrid returned from relplot, it does not consider a specified hue anymore. Here is a minimal example that explains my point:

+
import numpy as np
+import seaborn as sns
+import pandas as pd
+
+def foo(color=None, label=None, tag=None):
+    print(tag, color, label)
+
+x = np.random.randn(100)
+df = pd.DataFrame({
+    'x' : x,
+    'y' : 2 * x,
+    'row' : np.random.randn(x.shape[0]) > 0,
+    'col' : np.random.randn(x.shape[0]) > 0,
+    'hue' : np.random.randn(x.shape[0]) > 0,
+})
+g = sns.relplot(data = df, x = 'x', y = 'y', row='row', col='col', hue='hue')
+g.map(foo, tag='relplot')
+
+g2 = sns.FacetGrid(data = df, row = 'row', col = 'col', hue='hue')
+g2.map(foo, tag='FacetGrid')
+
+

When calling the map function on the facet grid returned by relplot, it will only be called four times (once per row and column) but will not respect the fact that I also specified a hue. The output is:

+
relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
+relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
+relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
+relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
+
+

If I map the same function to the FacetGrid that is manually created, it will result in the expected behaviour:

+
FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
+FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
+FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
+FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
+FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
+FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
+FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
+FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
+
+

Is there any explanation as to why that happens? Is there a way to change relplot's behaviour to match the expected one, i.e. to respect the hue parameter I set?

","
+

Is there any explanation as to why that happens?

+
+

Yes, in relplot the hue logic is all handled within scatterplot, not by the FacetGrid.

+
+

Is there a way to change relplot's behaviour to match the expected one?

+
+

No, in this case you'll want to make your custom function handle the hue logic internally or start with FacetGrid directly.

",python +"Getting back property of object in a query list SQLAlchemy

I have a join table called UserServices. Which has a FK of service_id and makes a back ref to a service. Below I get all the userServices in which the id in the route param matches the user_id (another FK) +I am then trying to access all the service properties on the all_user_services list.

+

My current code only returns one dict instead of a list of dicts. What am i doing wrong?

+
@bp.route('/user/<id>/services', methods=['GET'])
+def get_services_from_user(id):
+    all_user_services = db_session.query(UserService).filter(UserService.user_id == id).all()
+
+    for service in all_user_services:
+        result = service_schema.dump(service.service)
+        return jsonify(result)
+
","

You just return on first for iteration. You need to create result list:

+
dumped = [service_schema.dump(s.service) for s in all_user_services]
+return jsonify(dumped)
+
",python +"big data in pytorch, help for tuning steps

I've previously splitted my bigdata:

+
# X_train.shape : 4M samples x 2K features
+# X_test.shape : 2M samples x 2K features
+
+

I've prepared the dataloaders

+
target = torch.tensor(y_train.to_numpy())
+features = torch.tensor(X_train.values)
+train = data_utils.TensorDataset(features, target)
+train_loader = data_utils.DataLoader(train, batch_size=10000, shuffle=True) 
+
+testtarget = torch.tensor(y_test.to_numpy())
+testfeatures = torch.tensor(X_test.values)
+test = data_utils.TensorDataset(testfeatures, testtarget)
+validation_generator = data_utils.DataLoader(test, batch_size=20000, shuffle=True) 
+
+

I copied from an online course this example for a network (no idea if other model are better)

+
base_elastic_model = ElasticNet()
+param_grid = {'alpha':[0.1,1,5,10,50,100],
+              'l1_ratio':[.1, .5, .7, .9, .95, .99, 1]}
+grid_model = GridSearchCV(estimator=base_elastic_model,
+                          param_grid=param_grid,
+                          scoring='neg_mean_squared_error',
+                          cv=5,
+                          verbose=0)
+
+

I've built this fitting

+
for epoch in range(1):
+    # Training
+    cont=0
+    total = 0
+    correct = 0
+    for local_batch, local_labels in train_loader:
+        cont+=1
+        with torch.set_grad_enabled(True):
+            grid_model.fit(local_batch,local_labels)
+        with torch.set_grad_enabled(False):
+            predicted = grid_model.predict(local_batch)
+            total += len(local_labels)
+            correct += ((1*(predicted>.5)) == np.array(local_labels)).sum()
+        #print stats
+
+    # Validation
+    total = 0
+    correct = 0
+
+    with torch.set_grad_enabled(False):
+        for local_batch, local_labels in validation_generator:
+            predicted = grid_model.predict(local_batch)
+            total += len(local_labels)
+            correct += ((1*(predicted>.5)) == np.array(local_labels)).sum()
+            #print stats
+
+

Maybe my grandchildren will have the results for 1 epoch!

+

I need some advises:

+
    +
  1. how/where (in the code) can I use quickly less data for a first tuning?
  2. +
  3. some advise for the steps to have a result in the 2022?
  4. +
  5. because I've added "with torch.set_grad_enabled(False):" for stats printing, have I to add (as done) "with torch.set_grad_enabled(True):" ?
  6. +
  7. I have got a GPU (useful without images??). I've the function "get_device()". Where have I to put ".to(get_device())" to use CUDA?
  8. +
  9. I'm learning putting together pieces of information, do you have general advising for my exercise?
  10. +
","
    +
  1. To shorten the training process by simply stopping the training for loop after a certain number like so.

    +
    for local_batch, local_labels in train_loader:
    +
    +   cont+=1
    +   if cont== number_u_want_to_stop:
    +      break #Breaks out of the for Loop and continues with the rest.
    +
    +
  2. +
  3. Always use your GPU for training and "inferencing" aka (using a model to make predictions) bs it is more than 20 faster than even the best CPU.

    +
  4. +
  5. No you don't have to make it true again. That's the main point of using the "with" syntax so after the code that is in the with the block is finished the properties will just dissolve into air :). So u can delete this line with a torch.set_grad_enabled(False):

    +
  6. +
  7. Like I said in the 2nd point use your GPU for all your projects but keep in mind u will have to use a graphics card with at least 4GB to train even little models.

    +

    here the install cmd for using the GPU on windows:

    +

    pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

    +

    and here is the one for Linux

    +

    pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

    +
  8. +
+

and here is a link to the PyTorch doc that explains to you how to use the GPU in PyTorch

+
    +
  1. A very nice starter project that probably everyone has done when he started with machine learning especially those who want to use computer vision. The Implementation of the image classification using the MNIST Dataset. There are many great tutorials out there. So at first, it will be very overwhelming with all those new words but I will promise it will get better when you start to speak the same language as the guys writing those tutorials. So first follow the tutorial and if u don't understand any word just google it by itself and work through it in little pieces bc otherwise, it will be very hard to comprehend. After u gained some basic knowledge u can start to build your own little projects. Start with something little. So keep grinding :)
  2. +
",python +"Dynamic attribute in a Python C module

I have a custom Python module written in C, and I want to add an attribute to the module which is dynamically populated. E.g.:

+
import mymod
+print(mymod.x)     # At this point, the value of x is computed
+
+

The name of the attribute is known in advance.

+

From what I understand, this should be possible using descriptors, but it is not working as expected. I implemented a custom type, implemented the tp_descr_get function for the type, and assigned an instance of the type to my module, but the tp_descr_get function is never called.

+

Here is my test module:

+
#define PY_SSIZE_T_CLEAN
+#include <Python.h>
+#include <stdio.h>
+
+static struct PyModuleDef testmod = {
+  PyModuleDef_HEAD_INIT,
+  "testmod",
+  NULL,
+  -1
+};
+
+typedef struct testattrib_s {
+  PyObject_HEAD
+} testattrib;
+
+static PyObject *testattrib_descr_get(PyObject *self, PyObject *obj, PyObject *type);
+static int       testattrib_descr_set(PyObject *self, PyObject *obj, PyObject *value);
+
+PyTypeObject testattribtype = {
+  PyVarObject_HEAD_INIT (NULL, 0)
+  "testattrib",                 /* tp_name */
+  sizeof (testattrib),          /* tp_basicsize */
+  /* lots of zeros omitted for brevity */
+  testattrib_descr_get,         /* tp_descr_get */
+  testattrib_descr_set          /* tp_descr_set */
+};
+
+PyMODINIT_FUNC
+PyInit_testmod(void)
+{
+  if (PyType_Ready(&testattribtype)) {
+    return NULL;
+  }
+
+  testattrib *attrib = PyObject_New(testattrib, &testattribtype);
+  if (attrib == NULL) {
+    return NULL;
+  }
+
+  PyObject *m = PyModule_Create(&testmod);
+  if (m == NULL) {
+    return NULL;
+  }
+
+  if (PyModule_AddObject(m, "myattrib", (PyObject *) attrib)) {
+    return NULL;
+  }
+
+  return m;
+}
+
+static PyObject *testattrib_descr_get(PyObject *self, PyObject *obj, PyObject *type)
+{
+  printf("testattrib_descr_get called\n");
+  Py_INCREF(self);
+  return self;
+}
+
+static int testattrib_descr_set(PyObject *self, PyObject *obj, PyObject *value)
+{
+  printf("testattrib_descr_set called\n");
+  return 0;
+}
+
+

I test it like this:

+
import testmod
+
+print(testmod.myattrib)   # should call tp_descr_get
+testmod.myattrib = 1      # should call tp_descr_set
+
+

The getter/setter functions are never called. What am I doing wrong?

+

I am running Python 3.8.5 on macOS 12.0.1 with a build from Anaconda:

+
>>> sys.version
+'3.8.5 (default, Sep  4 2020, 02:22:02) \n[Clang 10.0.0 ]'
+
","

Descriptors operate only as attributes on a type. You would have to create your module as an instance of a module subclass equipped with the descriptor. The easiest way to do that is to use the Py_mod_create slot (not to be confused with __slots__).

",python +"Can't use csv pipelines and images pipelines within a spider correctly

I'm trying to figure out any way to write first two fields in a csv file and to use the last two fields to download images in a folder simultaneously. I've created two custom pipelines to achieve that.

+

This is the spider:

+
import scrapy
+
+class PagalWorldSpider(scrapy.Spider):
+    name = 'pagalworld'
+    start_urls = ['https://www.pagalworld.pw/indian-pop-mp3-songs-2021/files.html']
+
+    custom_settings = {
+        'ITEM_PIPELINES': {
+            'my_project.pipelines.PagalWorldImagePipeline': 1,
+            'my_project.pipelines.CSVExportPipeline': 300
+        },
+        'IMAGES_STORE': r"C:\Users\WCS\Desktop\Images",
+    }
+
+    def start_requests(self):
+        for start_url in self.start_urls:
+            yield scrapy.Request(start_url,callback=self.parse)
+
+    def parse(self, response):
+        for item in response.css(".files-list .listbox a[href]::attr(href)").getall():
+            inner_page_link = response.urljoin(item)
+            yield scrapy.Request(inner_page_link,callback=self.parse_download_links)
+
+    def parse_download_links(self,response):
+        title = response.css("h1.title::text").get()
+        categories = ', '.join(response.css("ul.breadcrumb > li > a::text").getall())
+
+        file_link = response.css(".file-details audio > source::attr(src)").get()
+        image_link = response.urljoin(response.css(".alb-img-det > img[data-src]::attr('data-src')").get())
+        image_name = file_link.split("-")[-1].strip().replace(" ","_").replace(".mp3","")
+        
+        yield {"Title":title,"categories":categories,"image_urls":[image_link],"image_name":image_name}
+
+

If I execute the script as is, I get all four fields in a csv file, the fields that I'm yielding within parse_download_links method. The script is also downloading and renaming images accurately.

+

The first two fields Title and categories are what I wish to write to the csv file, not image_urls and image_name. However, this two fields image_urls and image_name are meant to download and rename images.

+

How can I use both of the pipelines correctly?

","

You don't have to create a CSV pipeline just for this purpose. Read this.

+
import scrapy
+
+
+class PagalWorldSpider(scrapy.Spider):
+    name = 'pagalworld'
+    start_urls = ['https://www.pagalworld.pw/indian-pop-mp3-songs-2021/files.html']
+
+    custom_settings = {
+        'ITEM_PIPELINES': {
+            'my_project.pipelines.PagalWorldImagePipeline': 1,
+            # 'my_project.pipelines.CSVExportPipeline': 300
+        },
+        'IMAGES_STORE':  r'C:\Users\WCS\Desktop\Images',
+        'FEEDS': {
+            r'file:///C:\Users\WCS\Desktop\output.csv': {'format': 'csv', 'overwrite': True}
+        },
+        'FEED_EXPORT_FIELDS': ['Title', 'categories']
+    }
+
+    def start_requests(self):
+        for start_url in self.start_urls:
+            yield scrapy.Request(start_url, callback=self.parse)
+
+    def parse(self, response):
+        for item in response.css(".files-list .listbox a[href]::attr(href)").getall():
+            inner_page_link = response.urljoin(item)
+            yield scrapy.Request(inner_page_link, callback=self.parse_download_links)
+
+    def parse_download_links(self,response):
+        title = response.css("h1.title::text").get()
+        categories = ', '.join(response.css("ul.breadcrumb > li > a::text").getall())
+
+        file_link = response.css(".file-details audio > source::attr(src)").get()
+        image_link = response.urljoin(response.css(".alb-img-det > img[data-src]::attr('data-src')").get())
+        image_name = file_link.split("-")[-1].strip().replace(" ", "_").replace(".mp3", "")
+
+        yield {"Title": title, "categories": categories, "image_urls": [image_link], "image_name": image_name}
+
+

Output:

+
Heartfail - Mika Singh mp3 song Download PagalWorld.com,"Home, MUSIC, INDIPOP, Indian Pop Mp3 Songs 2021"
+Fakir - Hansraj Raghuwanshi mp3 song Download PagalWorld.com,"Home, MUSIC, INDIPOP, Indian Pop Mp3 Songs 2021"
+Humsafar - Suyyash Rai mp3 song Download PagalWorld.com,"Home, MUSIC, INDIPOP, Indian Pop Mp3 Songs 2021"
+...
+...
+...
+
+

EDIT:

+

main.py:

+
from scrapy.crawler import CrawlerProcess
+from scrapy.utils.project import get_project_settings
+
+
+if __name__ == "__main__":
+    spider = 'pagalworld'
+    settings = get_project_settings()
+    settings['USER_AGENT'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
+    process = CrawlerProcess(settings)
+    process.crawl(spider)
+    process.start()
+
",python +"Python - why the print result is repeated and ""write to a text"" only has one line

Lovely people! I'm totally new with Python. I tried to scrape several URLs and encountered a problem with "print".

+

I tried to print and write the "shipment status". +I have two URLs, so ideally I get two results.

+

This is my code:

+
from bs4 import BeautifulSoup 
+import re 
+import urllib.request
+import urllib.error
+import urllib 
+ 
+# read urls of websites from text file 
+list_open = open("c:/Users/***/Downloads/web list.txt") 
+read_list = list_open.read() 
+line_in_list = read_list.split("\n") 
+ 
+for url in line_in_list: 
+    soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html') 
+    # parse something special in the file 
+    shipment = soup.find_all('span')
+    Preparation=shipment[0] 
+    Sent=shipment[1]
+    InTransit=shipment[2]
+    Delivered=shipment[3]
+    for p in shipment: 
+# extract information 
+        print (url,';',"Preparation",Preparation.getText(),";","Sent",Sent.getText(),";","InTransit",InTransit.getText(),";","Delivered",Delivered.getText())
+     
+import sys
+ 
+file_path = 'randomfile.txt'
+sys.stdout = open(file_path, "w")
+print(url,';',"Preparation",Preparation.getText(),";","Sent",Sent.getText(),";","InTransit",InTransit.getText(),";","Delivered",Delivered.getText())`
+
+

I have two problems here:

+
    +
  1. Problem one: I have only two URLs, and when I print the results, every "span" is repeated 4 times (as there are four "span"s). +The result in the "output" is as below:
  2. +
+

(I deleted the result example to protect privacy.)

+
    +
  1. Problem two: I tried to write the "print" to a text file, but only one line appeared in the file:
  2. +
+

(I deleted the result example to protect privacy.)

+

I want to know what is wrong in the code. I want to print 2 url results only.

+

Your help is really appreciated! +Thank you in advance!

","

First point is caused by iterating over shipment - Just delete the for loop and correct indent of print():

+
for url in line_in_list: 
+    soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html') 
+    # parse something special in the file 
+    shipment = soup.find_all('span')
+    Preparation=shipment[0] 
+    Sent=shipment[1]
+    InTransit=shipment[2]
+    Delivered=shipment[3]
+
+    print (url,';',"Preparation",Preparation.getText(),";","Sent",Sent.getText(),";","InTransit",InTransit.getText(),";","Delivered",Delivered.getText())
+
+

Second issue is caused while you call the writing outside the loop and not in append mode - You will end up with this as your loop:

+
#open file in append mode
+with open('somefile.txt', 'a') as f:
+    #start iterating your urls
+    for url in line_in_list: 
+        soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html') 
+        # parse something special in the file 
+        shipment = soup.find_all('span')
+        Preparation=shipment[0] 
+        Sent=shipment[1]
+        InTransit=shipment[2]
+        Delivered=shipment[3]
+        #create output text
+        line = f'{url};Preparation{Preparation.getText()};Sent{Sent.getText()};InTransit{InTransit.getText()};Delivered{Delivered.getText()}'
+        #print output text
+        print (line)
+        #append output text to file
+        f.write(line+'\n')
+
+

And you can delete:

+
import sys
+file_path = 'randomfile.txt'
+sys.stdout = open(file_path, "w")
+print(url,';',"Preparation",Preparation.getText(),";","Sent",Sent.getText(),";","InTransit",InTransit.getText(),";","Delivered",Delivered.getText())`
+
+

Example of a bit optimized code:

+
from bs4 import BeautifulSoup
+import urllib.request
+import urllib.error
+import urllib
+
+# read urls of websites from text file
+list_open = open("c:/Users/***/Downloads/web list.txt")
+read_list = list_open.read()
+line_in_list = read_list.split("\n")
+file_path = "randomfile.txt"
+
+with open('somefile.txt', 'a', encoding='utf-8') as f:
+    for url in line_in_list:
+        soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html') 
+        # parse something special in the file 
+        shipment = list(soup.select_one('#progress').stripped_strings)
+        line = f"{url},{';'.join([':'.join(x) for x in list(zip(shipment[::2], shipment[1::2]))])}"
+        print (line)
+        f.write(line+'\n')
+
",python +"Python : Get information from multiple tables sql, and fill Dash

I have multiple tables in a db SQL. +I am trying to do Join so that I can have a several information from each table. +The select works, the data also ( when I print it, It has data), but I cannot fill the table in Dash. It goes empty with the columns that I created

+

Something is wrong... Thank you in advance

+
conn = script.connect_to_db(host, user, psw, db_name, port)
+cursor = conn.cursor()
+sql_statement ="""SELECT li.book_name,au.autor_name,bo.references
+FROM library li
+INNER JOIN autors au ON au.id=li.id_autors
+INNER JOIN books bo ON bo.id_references=au.id
+"""
+cursor.execute(sql_statement)
+
+data=cursor.fetchall()
+print('data',data)
+
+columslist = [
+    {"name": ["book name"], "id": "book_name", "type": 'text'},
+    {"name": ["autors"], "id": "autors", "type": 'text'},
+    {"name": ["references"], "id": "references", "type": 'text'},
+
+]
+
+layout = html.Div([
+    html.Br(),
+    html.Div([dash_table.DataTable(
+        id='datatable-library',
+        columns=columslist ,
+        data=data,
+
","

data should be in dictionry datatype :

+
layout = html.Div([
+    html.Br(),
+    html.Div([dash_table.DataTable(
+        id='datatable-library',
+        columns=columslist ,
+        data=dict(data),
+
",python +"How to normalize a JSON file into a Pandas dataframe

I have a JSON file named stocks.json that looks as follows (note the lack of square brackets in the source file):

+
{"MSFT": {"exchange": "Nasdaq", "price": 275.79}, "FB": {"exchange": "Nasdaq", "price": 320.22}, "TSLA": {"exchange": "Nasdaq", "price": 990.83}, "GE": {"exchange": "Nasdaq", "price": 83.20}}
+
+

I would like to transform this data into a Pandas dataframe that looks as follows:

+
symbol     exchange     price
+MSFT       Nasdaq       275.79
+FB         Nasdaq       320.22
+TSLA       Nasdaq       990.83
+GE         NYSE          83.20
+
+

My attempt is:

+
import pandas as pd
+
+stock_data = pd.read_json('stocks.json', lines=True)
+stock_data_normalized = pd.json_normalize(stock_data)
+
+

Unfortunately, I get the following when calling stock_data_normalized:

+
0
+1
+2
+3
+
+

Any assistance would be most appreciated. Thanks!

","

You can just using the pd.DataFrame() constructor, and then transpose and reset the index:

+
df = pd.DataFrame(d).T.reset_index().rename({'index': 'symbol'}, axis=1)
+
+

Output:

+
>>> df
+  symbol exchange   price
+0   MSFT   Nasdaq  275.79
+1     FB   Nasdaq  320.22
+2   TSLA   Nasdaq  990.83
+3     GE   Nasdaq    83.2
+
",python +"Connecting to random points in a 2d numpy array based on distance

I have a 2d numpy array and select a random coordinate position (say 10x10 array and start at position 2,3). I want to randomly connect to 40% of the other points in the 2d array effectively generating a list of tuples [(x1, y1), (x2, y2) ...] where the list is 40% of the other coordinates.
+An additional constraint, however, is the goal is to reduce connection probability the farther the points are away from one another (so point 2,3 is far more likely to connect to 2,2 than 9, 8 but yet still be random so there is a chance albeit small of connecting to 9, 8).

+

I believe I need to create some sort of Guassian function centered on 2,3 and use this to select the points, but any Gaussian I create will generate non-integer values - requiring additional logic as well as presents problem of needing to handle x and y dimensions separately.

+

Currently, I am trying to use np.meshgrid with +gauss = np.exp(-(dst2 / (2.0 * sigma2)))

+

Is there an easier way to do this or a different approach someone might recommend?

","

This problem is well suited for rejection sampling. +Basically you randomly choose a point, and select if a connection should be made based on a defined probability. You have to take in account that there are many more points at further distance than at # closer distances (its number grows with radius), so maybe you have to introduce an extra weighing in the probability function. In this case I choose to use an exponential decay probability.

+

This code is not optimal in terms of speed, particularly for higher connectivity percents, but the ideas are better presented this way: see below for a better option.

+
import numpy as np
+from numpy.random import default_rng
+
+rng = default_rng()
+board = np.zeros((100, 100), dtype=bool)
+percent_connected = 4
+N_points = round((board.size - 1) * percent_connected/100)
+center = np.array((20, 30))
+board[tuple(center)] = True # remove the center point from the pool
+dist_char = 35  # characteristic distance where probability decays to 1/e
+
+endpoints = []
+while N_points:
+    point = rng.integers(board.shape)
+    if not board[tuple(point)]:
+        dist = np.sqrt(np.sum((center-point)**2))
+        P = np.exp(-dist / dist_char)
+        if rng.random() < P:
+            board[tuple(point)] = True
+            endpoints.append(point)
+            N_points -= 1
+board[tuple(center)] = False # clear the center point
+
+# Graphical test
+import matplotlib.pyplot as plt
+
+plt.figure()
+for ep in endpoints:
+    plt.plot(*zip(center, ep), c="blue")
+
+
+

A slightly faster approach is much faster at higher connectivity:

+
rng = default_rng()
+board = np.zeros((100, 100), dtype=bool)
+percent_connected = 4
+N_points = round((board.size - 1) * percent_connected/100)
+center = np.array((20, 30))
+board[tuple(center)] = True # remove the center point from the pool
+dist_char = 35  # characteristic distance where probability decays to 1/e
+flat_board = board.ravel()
+endpoints = []
+while N_points:
+    idx = rng.integers(flat_board.size)
+    while flat_board[idx]:
+        idx += 1
+        if idx >= flat_board.size:
+            idx = 0
+    if not flat_board[idx]:
+        point = np.array((idx // board.shape[0], idx % board.shape[0]))
+        dist = np.sqrt(np.sum((center-point)**2))
+        P = np.exp(-dist / dist_char)
+        if rng.random() < P:
+            flat_board[idx] = True
+            endpoints.append(point)
+            N_points -= 1
+board[tuple(center)] = False # clear the center point
+
+
+plt.figure()
+for ep in endpoints:
+    plt.plot(*zip(center, ep), c="blue")
+
",python +"Get indexes of Pandas Rolling window

I would like to get the indexes of the elements in each rolling window of a Pandas Series.

+

A solution that works for me is from this answer to an existing question: I get the window.index for each window obtained from the rolling function described in the answer. I am only interested in step=1 for the aforementioned function.

+

But this function is not specific for DataFrames and Series, it would work on basic Python lists. +Isn't there some functionality that takes advantage of Pandas rolling operations?

+

I tried the Rolling.apply method:

+
s = pd.Series([1, 2, 3, 4, 5, 6, 7])
+
+rolling = s.rolling(window=3)
+indexes = rolling.apply(lambda x: x.index)
+
+

But it result in a TypeError: must be real number, not RangeIndex. Apparently, the Rolling.apply method only accepts functions that return a number based on each window. The functions cannot return other kinds of objects.

+

Are there other methods of the Pandas Rolling class I could use? Even private methods.

+

Or are there any other Pandas-specific functionalities to get the indexes of overlapping rolling windows?

+

Expected output

+

As output, I expect some kind of list-of-lists object. Each inner list should countain the index values of each window. +The original s Series has [0, 1, 2, 3, 4, 5, 6] as index. +So, rolling with a window=3, I expect as outcome something like:

+
[
+    [0, 1, 2],
+    [1, 2, 3],
+    [2, 3, 4],
+    [3, 4, 5],
+    [4, 5, 6],
+]
+
","

The apply function after rolling must return a numeric value for each window. One possible workaround is to use a list comprehension to iterate over each window and apply the custom transformation as required:

+
[[*l.index] for l in s.rolling(3) if len(l) == 3]
+
+

Alternatively you can also use sliding_window_view to accomplish the same:

+
np.lib.stride_tricks.sliding_window_view(s.index, 3)
+
+

Or even an list comprehension would do the job just fine:

+
w = 3
+[[*s.index[i : i + w]] for i in range(len(s) - w + 1)]
+
+

Result

+
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
+
",python +"having trouble with function and asyncio

here is my Code so far:

+
import discord
+from discord import Webhook, AsyncWebhookAdapter
+from discord.ext import commands
+from discord import Activity, ActivityType
+import aiohttp
+from bs4 import BeautifulSoup
+from requests_html import AsyncHTMLSession
+intents = discord.Intents.default()
+intents.members = True
+
+client = commands.Bot(command_prefix="$", intents=intents, case_insensitive=True)
+
+async def amazon():
+  URL = "https://www.amazon.com/s?k=gaming"
+
+  with AsyncHTMLSession() as session:
+    response = await session.get(URL)
+    response.html.arender(timeout=20)
+
+    soup = BeautifulSoup(response.html.html, "lxml")
+    results = soup.select("a.a-size-base.a-link-normal.s-link-style.a-text-normal")
+
+    max_price = 10
+    
+    for result in results:
+      price = result.text.split('$')[1].replace(",", "")
+      if float(price) < max_price:
+        print(f"Price: ${price}\nLink: https://www.amazon.com{result['href'].split('?')[0]}")
+
+
+
+@client.command()
+async def amaz(ctx):
+  await amazon()
+  await ctx.send("hello")
+
+      
+
+client.run("iputmytokenhere")
+
+
+

here is the error I get when doing $amaz:

+
RuntimeWarning: coroutine 'HTML.arender' was never awaited
+  response.html.arender(timeout=20)
+RuntimeWarning: Enable tracemalloc to get the object allocation traceback
+C:\Users\CK\AppData\Roaming\Python\Python37\site-packages\requests\sessions.py:428: RuntimeWarning: coroutine 'AsyncHTMLSession.close' was never awaited
+  self.close()
+RuntimeWarning: Enable tracemalloc to get the object allocation traceback
+
+

I am using this as a fun project, any help is greatly appreciated. I tried many things but nothing seems to be working. I want the bot to send the scraped data to a discord webhook.

","

+You can use the following code for the amazon() function.

+
async def amazon():
+  URL = "https://www.amazon.com/s?k=gaming"
+  # add the string of the webhook url
+  WEBHOOK_URL = "https://your_webhook_url"
+
+  # change the with statement to assignment following the documentation
+  session = AsyncHTMLSession()
+  response = await session.get(URL)
+  # add await to prevent the "was not awaited" error
+  await response.html.arender(timeout=20)
+  # create the webhook object
+  webhook = Webhook.from_url(WEBHOOK_URL, adapter=AsyncWebhookAdapter(session))
+
+  soup = BeautifulSoup(response.html.html, "lxml")
+  results = soup.select("a.a-size-base.a-link-normal.s-link-style.a-text-normal")
+
+  max_price = 10
+   
+  for result in results:
+    price = result.text.split('$')[1].replace(",", "")
+    if float(price) < max_price:
+      # change print() to webhook.send() to send the data from a webhook
+      await webhook.send(f"Price: ${price}\nLink: https://www.amazon.com{result['href'].split('?')[0]}")
+
",python +"How to create and annotate a stacked proportional bar chart

I'm struggling to create a stacked bar chart derived from value_counts() of a columns from a dataframe.

+

Assume a dataframe like the following, where responder is not important, but would like to stack the count of [1,2,3,4,5] for all q# columns.

+
responder, q1, q2, q3, q4, q5
+------------------------------
+r1, 5, 3, 2, 4, 1
+r2, 3, 5, 1, 4, 2
+r3, 2, 1, 3, 4, 5
+r4, 1, 4, 5, 3, 2
+r5, 1, 2, 5, 3, 4
+r6, 2, 3, 4, 5, 1
+r7, 4, 3, 2, 1, 5
+
+

Look something like, except each bar would be labled by q# and it would include 5 sections for count of [1,2,3,4,5] from the data:

+

+

Ideally, all bars will be "100%" wide, showing the count as a proportion of the bar. But it's gauranteed that each responder row will have one entry for each, so the percentage is just a bonus if possible.

+

Any help would be much appreciated, with a slight preference for matplotlib solution.

","

You can calculate the heights of bars using percentages and obtain the stacked bar plot using ax = percents.T.plot(kind='barh', stacked=True) where percents is a DataFrame with q1,...q5 as columns and 1,...,5 as indices.

+
>>> percents
+         q1        q2        q3        q4        q5
+1  0.196873  0.199316  0.206644  0.194919  0.202247
+2  0.205357  0.188988  0.205357  0.205357  0.194940
+3  0.202265  0.217705  0.184766  0.196089  0.199177
+4  0.199494  0.199494  0.190886  0.198481  0.211646
+5  0.196137  0.195146  0.211491  0.205052  0.192174
+
+

Then you can use ax.patches to add labels for every bar. Labels can be generated from the original counts DataFrame: counts = df.apply(lambda x: x.value_counts())

+
>>> counts
+    q1   q2   q3   q4   q5
+1  403  408  423  399  414
+2  414  381  414  414  393
+3  393  423  359  381  387
+4  394  394  377  392  418
+5  396  394  427  414  388
+
+
+
import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+## create some data similar to yours
+np.random.seed(42)
+categories = ['q1','q2','q3','q4','q5']
+df = pd.DataFrame(np.random.randint(1,6,size=(2000, 5)), columns=categories)
+
+## counts will be used for the labels
+counts = df.apply(lambda x: x.value_counts())
+
+## percents will be used to determine the height of each bar
+percents = counts.div(counts.sum(axis=1), axis=0)
+
+counts_array = counts.values
+nrows, ncols = counts_array.shape
+indices = [(i,j) for i in range(0,nrows) for j in range(0,ncols)]
+percents_array = percents.values
+
+ax = percents.T.plot(kind='barh', stacked=True)
+ax.legend(bbox_to_anchor=(1, 1.01), loc='upper right')
+for i, p in enumerate(ax.patches):
+    ax.annotate(f"({p.get_width():.2f}%)", (p.get_x() + p.get_width() - 0.15, p.get_y() - 0.10), xytext=(5, 10), textcoords='offset points')
+    ax.annotate(str(counts_array[indices[i]]), (p.get_x() + p.get_width() - 0.15, p.get_y() + 0.10), xytext=(5, 10), textcoords='offset points')
+plt.show()
+
+

",python +"How to make middleware object callable in Django 2.2

I'm trying to update a django/mezzanine application from python 2.7 to python 3.7. Can you help me in fixing the error below (CTypeError: 'CheckNewsDateStatus' object is not callable)?

+

Seems that this class is not used at all; if I grep through all code only the attached settings.py and middleware.py match. Is it something partly implemented in django/mezzanine or it it so that the whole class can be removed as unnecessary ?

+

I don't know how the code was planned to work and I don't know is the feature has been used at all... and I don't know how the callable objects should be presented in settings.py-file.

+
(python-3.7) miettinj@ramen:~/pika-py-3.7/pika> python manage.py runserver 0:8034
+BASE_DIR /srv/work/miettinj/pika-py-3.7/pika
+PROJECT_ROOT /srv/work/miettinj/pika-py-3.7/pika/pika
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. 
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki
+  warn("TIME_ZONE setting is not set, using closest match: %s" % tz)
+BASE_DIR /srv/work/miettinj/pika-py-3.7/pika
+PROJECT_ROOT /srv/work/miettinj/pika-py-3.7/pika/pika
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. 
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki
+  warn("TIME_ZONE setting is not set, using closest match: %s" % tz)
+Watching for file changes with StatReloader
+              .....
+          _d^^^^^^^^^b_
+       .d''           ``b.
+     .p'                `q.
+    .d'                   `b.
+   .d'                     `b.   * Mezzanine 5.0.0
+   ::                       ::   * Django 2.2
+  ::    M E Z Z A N I N E    ::  * Python 3.7.10
+   ::                       ::   * PostgreSQL 9.3.0
+   `p.                     .q'   * Linux 5.3.18-lp152.102-default
+    `p.                   .q'
+     `b.                 .d'
+       `q..          ..p'
+          ^q........p^
+              ''''
+
+Performing system checks...
+
+System check identified no issues (0 silenced).
+December 31, 2021 - 14:08:56
+Django version 2.2, using settings 'pika.settings'
+Starting development server at http://0:8034/
+Quit the server with CONTROL-C.
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/django/core/handlers/base.py:37: 
+/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/django/core/handlers/base.py:37: FutureWarning: `TemplateForDeviceMiddleware` is deprecated. Please remove it from your middleware settings.
+  mw_instance = middleware(handler)
+Internal Server Error: /admin/
+Traceback (most recent call last):
+  File "/srv/work/miettinj/python-3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
+    response = get_response(request)
+TypeError: 'CheckNewsDateStatus' object is not callable
+
+

middlewary.py:

+
class CheckNewsDateStatus:
+    def __init__(self, get_response):
+        self.get_response = get_response 
+
+    def process_request(self, request):
+        if '/uutinen/' in request.path:
+            try:
+                path_to_go_raw = request.path
+                true_slug = path_to_go_raw.split('/uutinen/')[1:]
+                news_obj = Uutinen.objects.get(slug=true_slug[0])
+                now_utc = pytz.utc.localize(datetime.now())
+                
+                hel = pytz.timezone("Europe/Helsinki")
+                foo = news_obj.publish_date.astimezone(hel)
+                
+                if foo.date() < now_utc.date() and news_obj.status == 2:
+                    pass
+                elif foo.date() == now_utc.date() and foo.time() < now_utc.time()  and news_obj.status == 2:
+                    pass
+                else:
+                    print("authenticated-->", request.user.is_authenticated())
+                    if request.user.is_authenticated():
+                        pass
+                    elif news_obj.status == 1:
+                        return HttpResponseNotFound('404')
+                    else:
+                        return HttpResponseNotFound('404')
+            except:
+                pass
+                             
+ 
+
+

settings.py:

+
    # List of middleware classes to use. Order is important; in the request phase,
+    # these middleware classes will be applied in the order given, and in the
+    # response phase the middleware will be applied in reverse order.
+    MIDDLEWARE = (
+        'page_types.middleware.CheckNewsDateStatus', 
+        'page_types.middleware.SetDynamicSite',
+    #    'debug_toolbar.middleware.DebugToolbarMiddleware',
+        "mezzanine.core.middleware.UpdateCacheMiddleware",
+        "django.contrib.sessions.middleware.SessionMiddleware",
+        #"django.middleware.locale.LocaleMiddleware",
+        "statfi_search.middleware.locale.LocaleMiddleware",
+        "django.contrib.auth.middleware.AuthenticationMiddleware",
+        "django.middleware.common.CommonMiddleware",
+        "django.middleware.csrf.CsrfViewMiddleware",
+        "django.contrib.messages.middleware.MessageMiddleware",
+        "mezzanine.core.request.CurrentRequestMiddleware",
+        "mezzanine.core.middleware.RedirectFallbackMiddleware",
+        "mezzanine.core.middleware.TemplateForDeviceMiddleware",
+        "mezzanine.core.middleware.TemplateForHostMiddleware",
+        "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
+        "mezzanine.core.middleware.SitePermissionMiddleware",
+        # Uncomment the following if using any of the SSL settings:
+        # "mezzanine.core.middleware.SSLRedirectMiddleware",
+        "mezzanine.pages.middleware.PageMiddleware",
+        "mezzanine.core.middleware.FetchFromCacheMiddleware",
+        'page_types.middleware.RedirectMiddleware',
+    )
+
","

You have an old style mixin here, you need to inherit from MiddlewareMixin

+

Change your code so that CheckNewsDateStatus object inherits from MiddlewareMixin like this

+
# this will probably be in page_types/middleware.py file 
+class CheckNewsDateStatus(MiddlewareMixin):
+    def __init__(self, get_response):
+        self.get_response = get_response 
+
+    def process_request(self, request):
+        if '/uutinen/' in request.path:
+            # rest of code
+
",python +"How to compare two schema in Databricks notebook in python

I'm going to ingest data using databricks notebook. I want to validate the schema of the data ingested against what I'm expecting the schema of these data to be.

+

So basically I have:

+
    validation_schema = StructType([
+      StructField("a", StringType(), True),
+      StructField("b", IntegerType(), False),
+      StructField("c", StringType(), False),
+      StructField("d", StringType(), False)
+    ])
+
+    data_ingested_good = [("foo",1,"blabla","36636"),
+     ("foo",2,"booboo","40288"),
+     ("bar",3,"fafa","42114"),
+     ("bar",4,"jojo","39192"),
+     ("baz",5,"jiji","32432")
+    ]
+
+    data_ingested_bad = [("foo","1","blabla","36636"),
+     ("foo","2","booboo","40288"),
+     ("bar","3","fafa","42114"),
+     ("bar","4","jojo","39192"),
+     ("baz","5","jiji","32432")
+    ]
+     
+    data_ingested_good.printSchema()
+    data_ingested_bad.printSchema()
+    validation_schema.printSchema()
+
+

I've seen similar questions but answers are always in scala.

","

it's really depends on your exact requirements & complexities of schemas that you want to compare - for example, ignore nullability flag vs. taking it into account, order of columns, support for maps/structs/arrays, etc. Also, do you want to see difference or just a flag if schemas are matching or not.

+

In the simplest case it could be as simple as following - just compare string representations of schemas:

+
def compare_schemas(df1, df2):
+  return df1.schema.simpleString() == df2.schema.simpleString()
+
+

I personally would recommend to take an existing library, like Chispa that has more advanced schema comparison functions - you can tune checks, it will show differences, etc. After installation (you can just do %pip install chispa) - this will throw an exception if schemas are different:

+
from chispa.schema_comparer import assert_schema_equality
+
+assert_schema_equality(df1.schema, df2.schema)
+
",python +"Adding data to an existing JSON file without overwriting it

The idea: +
I want to add a JSON object to an existing JSON file, but not overwrite the existing data in the file. +
The uid-003 object should come subordinate to uID after the existing uid-xxx entries.

+

The problem: +
No solution approach works as it should. The append() approach also returns the error: AttributeError: 'dict' object has no attribute 'append'.

+

The current code +
Python code:

+ +
user = {
+    "uid-003": {
+        "username": "username-3",
+        "pinned": "pinned",
+        "created": {
+            "date": "DD/MM/YYYY",
+            "time": "HH:MM:SS"
+        },
+        "verified": {
+            "checked": False
+        }
+    }
+}
+
+with open("path/to/json", "r+") as file:
+    data = json.load(file)
+    
+    temp = data['uID']
+    temp.append(user)
+
+    json.dump(data, file)
+
+

JSON file:

+
{
+    "uID": {
+        "uid-001": {
+            "username": "username-1",
+            "pinned": false,
+            "created": {
+                "date": "20-12-2021",
+                "time": "21:13:39"
+            },
+            "verified": {
+                "checked": false
+            }
+        },
+        "uid-002": {
+            "username": "username-2",
+            "pinned": true,
+            "created": {
+                "date": "20-12-2021",
+                "time": "21:13:39"
+            },
+            "verified": {
+                "checked": false
+            }
+        }
+    }
+}
+
","

All you need to do is add your user dictionary to the existing 'uID' key. If you update a file that's been opened with r+ and you're increasing the amount of data in the file, you'll need to seek to the beginning before writing. This should help:

+
import json
+
+THE_FILE = 'the_file.json'
+
+user = {
+    "uid-003": {
+        "username": "username-3",
+        "pinned": "pinned",
+        "created": {
+            "date": "DD/MM/YYYY",
+            "time": "HH:MM:SS"
+        },
+        "verified": {
+            "checked": False
+        }
+    }
+}
+
+with open(THE_FILE, 'r+') as jfile:
+    j = json.load(jfile)
+    for k, v in user.items():
+        j['uID'][k] = v
+    jfile.seek(0)
+    json.dump(j, jfile, indent=4)
+
+

Note: The iteration over user.items() isn't really necessary in this case but serves to show how you might use this pattern when user contains more dictionaries than just the one in your example

",python +"ValueError: time data does not match format '%y/%m/%d'

I am trying to convert a string to a DateTime object but an error occurs.

+

This is my code:

+
from datetime import datetime
+
+string = "2021/12/18"
+
+final_check_date = datetime.strptime(string, '%y/%m/%d')
+
+print(final_check_date)
+
+

And the error is: ValueError: time data '2021/12/18' does not match format '%y/%m/%d'

","

It is just a format error. I have attached the code with its solution. a date string '2021-12-18' is parsed by this function if the format given is '%Y-%m-%d'. +Code with the solution

",python +"Why is Colab still running Python 3.7?

I saw on this tweet that Google Colab move to Python 3.7 on February 2021. As of today however (January 2022), Python 3.10 is out, but Colab still runs Python 3.7.
+My (voluntarily) naive take is that this is quite a significant lag.

+

Why are they not at least on Python 3.8 or even 3.9?
+Is it simply to make sure that some compatibility criteria are met?

","

The only reason is they want to have the most compatible version of Python worldwide. Based on the Python Readiness report (Python 3.7 Readiness), version 3.7 supports almost 80.6% of the most used packages so far. Still, this coverage is 78.3% for version 3.8, 70.6% for version 3.9 and 49.7% for version 3.10 (as of March 29, 2022).

+

Frankly, if Python 3.6 was not in its EOL, they still used this version today. Lucky us, which python.org decide to rid of versions below 3.7.

+

On the other hand, You can update the Python version in your Colab by running some Linux commands in the notebook. But the problem is that whenever you start a new notebook, google ignores the updates and will turn back to the original version.

+

The best action that google can have is to have options to select the python version. Because of this, I am not using Colab in most cases, especially when I am teaching Python to my students.

",python +"FastAPI not loading static files

So, I'm swapping my project from node.js to python FastAPI. Everything has been working fine with node, but here it says that my static files are not present, so here's the code:

+
from fastapi import FastAPI, Request, WebSocket
+from fastapi.responses import HTMLResponse
+from fastapi.staticfiles import StaticFiles
+from fastapi.templating import Jinja2Templates
+
+app = FastAPI()
+
+app.mount("/static", StaticFiles(directory="../static"), name="static")
+templates = Jinja2Templates(directory='../templates')
+
+@app.get('/')
+async def index_loader(request: Request):
+    return templates.TemplateResponse('index.html', {"request": request})
+
+

The project's structure looks like this:
+

+

Files clearly are where they should be, but when I connect to website the following error is raised:

+
←[32mINFO←[0m:     connection closed
+←[32mINFO←[0m:     127.0.0.1:54295 - "←[1mGET /img/separator.png HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54296 - "←[1mGET /css/rajdhani.css HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54295 - "←[1mGET /js/pixi.min.js HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54296 - "←[1mGET /js/ease.js HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54298 - "←[1mGET / HTTP/1.1←[0m" ←[32m200 OK←[0m
+←[32mINFO←[0m:     127.0.0.1:54298 - "←[1mGET /img/separator.png HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54299 - "←[1mGET /css/rajdhani.css HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54298 - "←[1mGET /js/pixi.min.js HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+←[32mINFO←[0m:     127.0.0.1:54299 - "←[1mGET /js/ease.js HTTP/1.1←[0m" ←[31m404 Not Found←[0m
+
+

So, basically, any static file that I'm using is missing, and I have no idea what am I doing wrong. How to fix it?

","

Here:

+
app.mount("/static", StaticFiles(directory="../static"), name="static")
+
+

You mount your static directory under /static path. That means, if you want access static files in your html you need to use static prefix, e.g. <img src="static/img/separator.png"/>

",python +"Parquet with null columns on Pyarrow

I'm reading a table on PostgreSQL using pandas.read_sql, then I'm converting it as a Pyarrow table and saving it partitioned in local filesystem.

+
# Retrieve schema.table data from database
+def basename_file(date_partition):
+    basename_file = f"{table_schema}.{table_name}-{date}.parquet"
+    return basename_file
+
+def get_table_data(table_schema, table_name, date):
+    s  = ""
+    s += "SELECT"
+    s += " *"
+    s += " , date(created_on) as date_partition"
+    s += " FROM {table_schema}.{table_name}"
+    s += " WHERE created_on = '{date}';" 
+    sql = s.format(table_schema = table_schema, table_name = table_name, date = date)
+#     print(sql)
+
+    df = pd.read_sql(sql, db_conn)
+    result = pa.Table.from_pandas(df)
+    pq.write_to_dataset(result,
+                        root_path = f"{dir_name}",
+                        partition_cols = ['date_partition'],
+                        partition_filename_cb = basename_file,
+                        use_legacy_dataset = True
+                       )
+#     print(result)
+    return df
+
+

Problem is that my SELECT has a column with some rows as null. +When I partition this to write (write_to_dataset) in local filesystem, a few files has only rows with that column as null, so the partitioned Parquet files doesn't have this column.

+

When I try to read that by multiple partitions, I get a schema error, because one of the columns cannot be casted correctly.

+

Why is that? Is there any setting I could apply to write_to_dataset to manage this? +I've been looking for a workaround for this without success... +My main goal here is to export data daily, partitioned by transaction date and read data from any period needed, not caring about schema evolution: that way, row value for null columns will appear as null, simply put.

","

If you can post the exact error message that might be more helpful. I did some experiments with pyarrow 6.0.1 and I found that things work ok as long as the first file contains some valid values for all columns (pyarrow will use this first file to infer the schema for the entire dataset).

+

The "first" file is not technically well defined when doing dataset discovery but, at the moment, for a local dataset it should be the first file in alphabetical order.

+

If the first file does not have values for all columns then I get the following error:

+

Error: Unsupported cast from string to null using function cast_null

+

I'm a bit surprised as this sort of cast should be pretty easy (to cast to null just throw away all the data). That being said, you probably don't want all your data thrown away anyways.

+

The easiest solution is to provide the full expected schema when you are creating your dataset. If you do not know this ahead of time you can figure it out yourself by inspecting all of the files in the dataset and using pyarrow's unify_schemas. I have an example of doing this in this answer.

+

Here is some code demonstrating my findings:

+
import os
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+import pyarrow.dataset as ds
+
+tab = pa.Table.from_pydict({'x': [1, 2, 3], 'y': [None, None, None]})
+tab2 = pa.Table.from_pydict({'x': [4, 5, 6], 'y': ['x', 'y', 'z']})
+
+os.makedirs('/tmp/null_first_dataset', exist_ok=True)
+pq.write_table(tab, '/tmp/null_first_dataset/0.parquet')
+pq.write_table(tab2, '/tmp/null_first_dataset/1.parquet')
+
+os.makedirs('/tmp/null_second_dataset', exist_ok=True)
+pq.write_table(tab, '/tmp/null_second_dataset/1.parquet')
+pq.write_table(tab2, '/tmp/null_second_dataset/0.parquet')
+
+try:
+    dataset = ds.dataset('/tmp/null_first_dataset')
+    tab = dataset.to_table()
+    print(f'Was able to read in null_first_dataset without schema.')
+    print(tab)
+except Exception as ex:
+    print('Was not able to read in null_first_dataset without schema')
+    print(f'  Error: {ex}')
+print()
+
+try:
+    dataset = ds.dataset('/tmp/null_second_dataset')
+    tab = dataset.to_table()
+    print(f'Was able to read in null_second_dataset without schema.')
+    print(tab)
+except:
+    print('Was not able to read in null_second_dataset without schema')
+    print(f'  Error: {ex}')
+print()
+
+dataset = ds.dataset('/tmp/null_first_dataset', schema=tab2.schema)
+tab = dataset.to_table()
+print(f'Was able to read in null_first_dataset by specifying schema.')
+print(tab)
+
",python +"fastapi get header parameter is none in basemodel use Header cant get token but in function its ok why?

in basemodel use Header cant get token but in function its ok why?

+
   class Test(BaseModel):
+        name: str
+        token: str= Header(None)
+
+def login(t: Test):
+    print(t.dict())
+    return 'test'
+
+output  {'name': '123', 'token': None} 
+
+

if i do this is ok

+
def login(t: Test,token: str= Header(None)):
+        print(t.dict(),token)
+        return 'test'
+    
+    output  {'name': '123', 'token': None} 123456
+
+

who can help me plz !

","

The Pydantic model here represents the validation of the request payload.

+

The values mentioned in the "Test" model should be available in request payload. Since the header is not the payload, we cannot use that in Basemodel.

+

Yet you can use that in api function. When you call the api, then the request params can be used in the function. So, it is possible to use this

",python +"How to load in graph from networkx into PyTorch geometric and set node features and labels?

Goal: I am trying to import a graph FROM networkx into PyTorch geometric and set labels and node features.

+

(This is in Python)

+

Question(s):

+
    +
  1. How do I do this [the conversion from networkx to PyTorch geometric]? (presumably by using the from_networkx function)
  2. +
  3. How do I transfer over node features and labels? (more important question)
  4. +
+

I have seen some other/previous posts with this question but they weren't answered (correct me if I am wrong).

+

Attempt: (I have just used an unrealistic example below, as I cannot post anything real on here)

+

Let us imagine we are trying to do a graph learning task (e.g. node classification) on a group of cars (not very realistic as I said). That is, we have a group of cars, an adjacency matrix, and some features (e.g. price at the end of the year). We want to predict the node label (i.e. brand of the car).

+

I will be using the following adjacency matrix: (apologies, cannot use latex to format this)

+

A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)]

+

Here is the code (for Google Colab environment):

+
import pandas as pd
+import numpy as np
+import matplotlib.pyplot as plt
+import networkx as nx
+from torch_geometric.utils.convert import to_networkx, from_networkx
+import torch
+
+!pip install torch-scatter torch-sparse torch-cluster torch-spline-conv torch-geometric -f https://data.pyg.org/whl/torch-1.10.0+cpu.html
+
+# Make the networkx graph
+G = nx.Graph()
+
+# Add some cars (just do 4 for now)
+G.add_nodes_from([
+      (1, {'Brand': 'Ford'}),
+      (2, {'Brand': 'Audi'}),
+      (3, {'Brand': 'BMW'}),
+      (4, {'Brand': 'Peugot'}),
+      (5, {'Brand': 'Lexus'}),
+])
+
+# Add some edges
+G.add_edges_from([
+                  (1, 2), (1, 4), (1, 5),
+                  (2, 3), (2, 4),
+                  (3, 2), (3, 5), 
+                  (4, 1), (4, 2),
+                  (5, 1), (5, 3)
+])
+
+# Convert the graph into PyTorch geometric
+pyg_graph = from_networkx(G)
+
+

So this correctly converts the networkx graph to PyTorch Geometric. However, I still don't know how to properly set the labels.

+

The brand values for each node have been converted and are stored within:

+
pyg_graph.Brand
+
+

Below, I have just made some random numpy arrays of length 5 for each node (just pretend that these are realistic).

+
ford_prices = np.random.randint(100, size = 5)
+lexus_prices = np.random.randint(100, size = 5)
+audi_prices = np.random.randint(100, size = 5)
+bmw_prices = np.random.randint(100, size = 5)
+peugot_prices = np.random.randint(100, size = 5)
+
+

This brings me to the main question:

+
    +
  • How do I set the prices to be the node features of this graph?
  • +
  • How do I set the labels of the nodes? (and will I need to remove the labels from pyg_graph.Brand when training the network?)
  • +
+

Thanks in advance and happy holidays.

","

The easiest way is to add all information to the networkx graph and directly create it in the way you need it. I guess you want to use some Graph Neural Networks. Then you want to have something like below.

+
    +
  1. Instead of text as labels, you probably want to have a categorial representation, e.g. 1 stands for Ford.
  2. +
  3. If you want to match the "usual convention". Then you name your input features x and your labels/ground truth y.
  4. +
  5. The splitting of the data into train and test is done via mask. So the graph still contains all information, but only part of it is used for training. Check the PyTorch Geometric introduction for an example, which uses the Cora dataset.
  6. +
+
import networkx as nx
+import numpy as np
+import torch
+from torch_geometric.utils.convert import from_networkx
+
+
+# Make the networkx graph
+G = nx.Graph()
+
+# Add some cars (just do 4 for now)
+G.add_nodes_from([
+      (1, {'y': 1, 'x': 0.5}),
+      (2, {'y': 2, 'x': 0.2}),
+      (3, {'y': 3, 'x': 0.3}),
+      (4, {'y': 4, 'x': 0.1}),
+      (5, {'y': 5, 'x': 0.2}),
+])
+
+# Add some edges
+G.add_edges_from([
+                  (1, 2), (1, 4), (1, 5),
+                  (2, 3), (2, 4),
+                  (3, 2), (3, 5),
+                  (4, 1), (4, 2),
+                  (5, 1), (5, 3)
+])
+
+# Convert the graph into PyTorch geometric
+pyg_graph = from_networkx(G)
+
+print(pyg_graph)
+# Data(edge_index=[2, 12], x=[5], y=[5])
+print(pyg_graph.x)
+# tensor([0.5000, 0.2000, 0.3000, 0.1000, 0.2000])
+print(pyg_graph.y)
+# tensor([1, 2, 3, 4, 5])
+print(pyg_graph.edge_index)
+# tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4],
+#         [1, 3, 4, 0, 2, 3, 1, 4, 0, 1, 0, 2]])
+
+
+# Split the data 
+train_ratio = 0.2
+num_nodes = pyg_graph.x.shape[0]
+num_train = int(num_nodes * train_ratio)
+idx = [i for i in range(num_nodes)]
+
+np.random.shuffle(idx)
+train_mask = torch.full_like(pyg_graph.y, False, dtype=bool)
+train_mask[idx[:num_train]] = True
+test_mask = torch.full_like(pyg_graph.y, False, dtype=bool)
+test_mask[idx[num_train:]] = True
+
+print(train_mask)
+# tensor([ True, False, False, False, False])
+print(test_mask)
+# tensor([False,  True,  True,  True,  True])
+
",python +"Best way to remove specific words from column in pandas dataframe?

I'm working with a huge set of data that I can't work with in excel so I'm using Pandas/Python, but I'm relatively new to it. I have this column of book titles that also include genres, both before and after the title. I only want the column to contain book titles, so what would be the easiest way to remove the genres?

+

Here is an example of what the column contains:

+
Book Labels
+Science Fiction | Drama | Dune
+Thriller | Mystery | The Day I Died
+Thriller | Razorblade Tears | Family | Drama
+Comedy | How To Marry Keanu Reeves In 90 Days | Drama
+...
+
+

So above, the book titles would be Dune, The Day I Died, Razorblade Tears, and How To Marry Keanu Reeves In 90 Days, but as you can see the genres precede as well as succeed the titles.

+

I was thinking I could create a list of all the genres (as there are only so many) and remove those from the column along with the "|" characters, but if anyone has suggestions on a simpler way to remove the genres and "|" key, please help me out.

","

It is an enhancement to @tdy Regex solution. The original regex Family|Drama will match the words "Family" and "Drama" in the string. If the book title contains the words in gernes, the words will be removed as well.

+

Supposed that the labels are separated by " | ", there are three match conditions we want to remove.

+
    +
  1. Gerne at start of string. e.g. Drama | ...
  2. +
  3. Gerne in the middle. e.g. ... | Drama | ...
  4. +
  5. Gerne at end of string. e.g. ... | Drama
  6. +
+

Use regex (^|\| )(?:Family|Drama)(?=( \||$)) to match one of three conditions. Note that | Drama | Family has 2 overlapped matches, here I use ?=( \||$) to avoid matching once only. See this problem [Use regular expressions to replace overlapping subpatterns] for more details.

+
>>> genres = ["Family", "Drama"]
+
+>>> df
+
+#                       Book Labels
+# 0      Drama | Drama 123 | Family
+# 1      Drama 123 | Drama | Family
+# 2      Drama | Family | Drama 123
+# 3  123 Drama 123 | Family | Drama
+# 4      Drama | Family | 123 Drama
+
+>>> re_str = "(^|\| )(?:{})(?=( \||$))".format("|".join(genres))
+
+>>> df['Book Labels'] = df['Book Labels'].str.replace(re_str, "", regex=True)
+
+# 0       | Drama 123
+# 1        Drama 123
+# 2        | Drama 123
+# 3    123 Drama 123
+# 4        | 123 Drama
+
+>>> df["Book Labels"] = df["Book Labels"].str.strip("| ")
+
+# 0        Drama 123
+# 1        Drama 123
+# 2        Drama 123
+# 3    123 Drama 123
+# 4        123 Drama
+
",python +"RabbitMQ and Celery: subscribe to job done event

I have a simple Celery task.py running with RabbitMQ message broker and Redis data storage

+
from celery import Celery
+
+app = Celery('tasks', broker='pyamqp://guest@localhost//', backend="redis://localhost:6379/0")
+
+@app.task
+def add(x, y):
+    return x + y
+
+

and a listener.py service, with a trivial function

+
def on_add(result):
+    # Do something with the result.
+
+

I want to invoke add() with a fire-and-forget style, and let another service implementing on_add() handle results.

+

This is the diagram of the workflow:

+

+

How can I create a listener that subscribes to task completion events on Celery's backend, Redis?

","

You have at least two options here:

+
    +
  1. Use signals - task-postrun for instance:
  2. +
+
@task_postrun.connect
+def task_postrun_handler(task_id, task, args, retval, **kwargs):
+    if task.name == "add":
+        on_add(retval)
+
+

note that it will run in the same celery worker.

+
    +
  1. If you need it in a separate process, you can take flower's approach and listen to the broker's events (more complicated).
  2. +
",python +"Receiving an ""PRECONDITION_FAILED - invalid property 'auto-delete' for queue 'test.queue' in vhost '/'"" error message for Pika

I am attempting to declare a Queue on my RabbitMQ broker. I had no issue before this until I tried adding "auto_delete=True" parameter to the queue declaration. The Queue is meant to consume messsages from a fanout Exchange.

+

I have already deleted the Queue before declaring it again. I even tried renaming the Queue. Nevertheless, I keep receiving the same error "PRECONDITION_FAILED - invalid property 'auto-delete' for queue 'test.queue' in vhost '/'". Below is my code for declaring the queue:

+
def setup_queue(self, queue_name):
+        LOGGER.info('Declaring queue %s', queue_name)
+        cb = functools.partial(self.on_queue_declareok, userdata=queue_name)
+        self._channel.queue_declare(
+            queue=queue_name,
+            callback=cb,
+            durable=True,
+            auto_delete=True,
+            arguments={"x-queue-type": "quorum", "x-max-length": MAX_QUEUE_LENGTH})
+
","

you can't set auto_delete=True feature for Quorum queues.

+

See the features for more details: +https://www.rabbitmq.com/quorum-queues.html

",python +"A way to blit multiple buttons from a list with working alpha and color?

I wanted to blit several button choices depending on the number that a list gives, but putting them in a for loop makes the alpha() and fill() function stop working. Is there a way to fix this or there's a better alternative to code multiple buttons?

+

Starting code:

+
import pygame, sys
+pygame.init()
+
+WIDTH, HEIGHT = 900, 600
+screen = pygame.display.set_mode((WIDTH,HEIGHT),0,32)
+clock = pygame.time.Clock() 
+font = pygame.font.Font('freesansbold.ttf', 32) 
+
+

Button and Scene class:

+
class Button():
+    def __init__(self, text, x, y):
+        self.rect = pygame.Rect(x, y, 0, 0)
+        self.updateText(text)
+        self.clicked = False  
+
+    def updateText(self, text):
+        self.text = text   
+        self.render = font.render(self.text, True, 'white')
+        self.text_width = self.render.get_width()
+        self.text_height = self.render.get_height()
+        self.box = pygame.Surface((self.text_width, self.text_height)) 
+        self.rect = self.render.get_rect(topleft = self.rect.topleft)
+
+    def draw(self):
+        action = False
+        screen.blit(self.box, (self.rect.x, self.rect.y))
+        screen.blit(self.render, (self.rect.x, self.rect.y))   
+
+        pos = pygame.mouse.get_pos()
+        if self.rect.collidepoint(pos):
+            self.box.set_alpha(100) 
+            self.box.fill((255, 255, 255))
+
+            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
+                self.clicked = True
+                action = True
+
+            if pygame.mouse.get_pressed()[0] == 0:
+                action = False
+                self.clicked = False
+        else:
+            self.box.set_alpha(0) 
+
+        return action
+
+
+class Scene():
+    def __init__(self):
+        pass
+
+    def on_start(self):
+        self.count = 0
+        self.blitcount = 0
+        self.optionList = []
+
+        for button in range(5): 
+            self.optionList.append(Button("button", WIDTH/3*2, 60 *(button + 1)))
+            self.count += 1
+
+        self.altButton = Button("Button without for loop", 100, 100)
+        self.buttons = None
+
+    def update(self, events):
+        screen.fill('gray')
+
+        for i in range(4):
+
+            self.buttons = self.optionList[self.blitcount]
+            self.buttons.updateText(str(i))        
+
+            if self.buttons.draw():
+                 print(i)
+
+            self.blitcount += 1
+
+        if self.altButton.draw():
+            print("Alt")
+
+        self.blitcount = 0
+
+        return self
+
+

The rest of the code:

+
game = Scene()
+game.on_start()
+
+while True:
+    clock.tick(30)
+
+    events = pygame.event.get()
+    for event in events:
+        if event.type == pygame.QUIT:
+            pygame.quit() 
+            sys.exit() 
+
+    game.update(events)
+
+    pygame.display.update()
+
","

You have to change the order. You need to set the alpha channel of the box before drawing the box. Note that the box is drawn with the currently set alpha channel.
+(See also the answer to your previous question How do I change the text in a Button class for Pygame?)

+
class Button():
+    # [...]
+
+    def draw(self):
+        action = False
+        
+        pos = pygame.mouse.get_pos()
+        if self.rect.collidepoint(pos):
+            self.box.set_alpha(100) 
+            self.box.fill((255, 255, 255))
+
+            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
+                self.clicked = True
+                action = True
+
+            if pygame.mouse.get_pressed()[0] == 0:
+                action = False
+                self.clicked = False
+        else:
+            self.box.set_alpha(0) 
+
+        screen.blit(self.box, (self.rect.x, self.rect.y))
+        screen.blit(self.render, (self.rect.x, self.rect.y))  
+
+        return action
+
",python +"How can I pick specific ranged value from np array?

My code is this.

+
a = cv2.imread('img_directory',0)/255
+a0 = np.zeros_like(a)
+a0[a<0.9] = 1.0
+a0[a>0.5] = 0.0
+
+

Here, I want to take values of a that is larger than 0.5, and smaller than 0.9. +But I see that this code does not work properly. +First I tried

+
a=[a<0.9 and a>0.5] =1.0
+
+

and this did not work. How should I make a code to fulfill my task ?

","

If you want to logical and of two numpy array, use np.logical_and(), you can refer to document for more information.

+

Therefore, a=[np.logical_and((a<0.9), (a>0.5))] = 1.0 will work.

",python +"How can I put labels in two charts using matplotlib

I'm trying to plot two histogram using the result of a group by. But the labels just appear in one of the labels. +How can I put the label in both charts? +And how can I put different title for the charts (e.g. first as Men's grade and Second as Woman's grade)

+
import pandas as pd
+import matplotlib.pyplot as plt
+
+microdataEnem = pd.read_csv('C:\\Users\\Lucas\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\Data Science\\Data Analysis\\Projects\\ENEM\\DADOS\\MICRODADOS_ENEM_2019.csv', sep = ';', encoding = 'ISO-8859-1', nrows=10000)
+
+sex_essaygrade = ['TP_SEXO', 'NU_NOTA_REDACAO']
+
+filter_sex_essaygrade = microdataEnem.filter(items = sex_essaygrade)
+
+filter_sex_essaygrade.dropna(subset = ['NU_NOTA_REDACAO'], inplace = True)
+       
+filter_sex_essaygrade.groupby('TP_SEXO').hist()
+plt.xlabel('Grade')
+plt.ylabel('Number of students')
+
+
+plt.show()
+
+

","

Instead of using filter_sex_essaygrade.groupby('TP_SEXO').hist() you can try the following format: axs = filter_sex_essaygrade['NU_NOTA_REDACAO'].hist(by=filter_sex_essaygrade['TP_SEXO']). This will automatically title each histogram with the group name.

+

You'll want to set an the variable axs equal to this histogram object so that you can modify the x and y labels for both plots.

+

I created some data similar to yours, and I get the following result:

+
import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+np.random.seed(42)
+
+sex_essaygrade = ['TP_SEXO', 'NU_NOTA_REDACAO']
+
+## create two distinct sets of grades
+sample_grades = np.concatenate((np.random.randint(low=70,high=100,size=100), np.random.randint(low=80,high=100,size=100)))
+
+filter_sex_essaygrade = pd.DataFrame({
+    'NU_NOTA_REDACAO': sample_grades,
+    'TP_SEXO': ['Men']*100 + ['Women']*100
+})
+       
+axs = filter_sex_essaygrade['NU_NOTA_REDACAO'].hist(by=filter_sex_essaygrade['TP_SEXO'])
+for ax in axs.flatten():
+    ax.set_xlabel("Grade")
+    ax.set_ylabel("Number of students")
+
+plt.show()
+
+

",python +"Not able to connect to AWS Aurora DB server-less -- mysql engine

I have created an AWS Aurora DB serverless publically available, and I am trying to connect to the DB using python. But I am unable to connect and I suspect the VPC.

+

Please suggest if I have to check anything else, also I have these below queries;

+
    +
  • Is AWS Aurora serverless with min configuration a free tire DB?
  • +
  • My VPC while creating the DB is Public already, yet I am not able to connect so do I need to perform any additional configuration changes?
  • +
+

Code Snippets:

+
import mysql.connector as mysq
+import sys, os, boto3 as aws, pandas as pd, pymysql
+from sqlalchemy import create_engine, inspect
+
+ENDPOINT = "random.cluster-random.ap-south-1.rds.amazonaws.com"
+PORT = "3306"
+USER = "random"
+REGION = "ap-south-1"
+DBNAME = "random"
+PASSWORD = "random"
+
+
+

Method 1:

+
client = aws.client('rds')
+token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USER, Region=REGION)
+print(token)
+
+try:
+    conn =  mysq.connect(host=ENDPOINT, user=USER, passwd=token, port=PORT, database=DBNAME)
+
+    cur = conn.cursor()
+    cur.execute("""SELECT now()""")
+    query_results = cur.fetchall()
+    print(query_results)
+except Exception as e:
+    print("Database connection failed due to {}".format(e))
+
+

Method 2:

+
CONNECTION_STRING = 'mssql+pymssql' + '://' + USER + ':' + PASSWORD + '@' + ENDPOINT + ':' + str(PORT) + '/' + DBNAME
+engine = create_engine(CONNECTION_STRING)
+print(inspect(engine).get_table_names())
+
+

Method 3:

+
conn = pymysql.connect(host=ENDPOINT, user=USER,port=int(PORT), passwd=PASSWORD, db=DBNAME)
+
+

Thanks, +Nikhil

","

Aurora serverless does not have public ip. Form docs.

+
+

You can't give an Aurora Serverless v1 DB cluster a public IP address. You can access an Aurora Serverless v1 DB cluster only from within a VPC.

+
+

Same for Aurora v2.

+

So you have to setup a VPN between your home/work network and your VPC, or use SSH tunneling through some ec2 instance bastion host.

",python +"Script fails to produce descriptions from a webpage when hardcoded delay is not in place

I'm trying to fetch titles and descriptions of results from a webpage. The descriptions are revealed when the titles are clicked. The script below works only when I define a hardcoded delay after the click. However, I wish to get rid of the hardcoded delay from the script.

+
import time
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+
+link = 'https://innovation.ised-isde.canada.ca/s/list-liste?language=en_CA&token=a0B5W000000WsFSUA0'
+
+driver = webdriver.Chrome()
+wait = WebDriverWait(driver,10)
+driver.get(link)
+
+for i,item in enumerate(wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".advanced-results .h4")))):
+    driver.execute_script("arguments[0].click();",item)
+    title = item.text
+    time.sleep(2)
+    desc = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"p.program-dov-description")))[i].text
+    print(title,desc)
+    print()
+
+driver.quit()
+
+
+

How to fetch titles and descriptions from that webpage without using hardcoded delay?

+
","

This should work. The thing is I couldn't figure out how to get multiple elements with css_selector, so I trusted my old friend, the xpath, and so I fetched the result, without using time.sleep as required. I get an error with this line of yours, stating that the element is not subscriptable because of [i], but my xpath works.

+
desc = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"p.program-dov-description")))[i].text
+    print(title,desc)
+
+

Here is the refactored code:

+
import time
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+from webdriver_manager.chrome import ChromeDriverManager
+
+link = 'https://innovation.ised-isde.canada.ca/s/list-liste?language=en_CA&token=a0B5W000000WsFSUA0'
+
+driver = webdriver.Chrome(ChromeDriverManager().install())
+wait = WebDriverWait(driver,10)
+driver.get(link)
+
+for i,item in enumerate(wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".advanced-results .h4")))):
+    # print(i, item)
+    driver.execute_script("arguments[0].click();",item)
+    title = item.text
+    desc_text = "//*[@class='program-dov-description']"
+    desc = wait.until(EC.visibility_of_element_located((By.XPATH,'(' + desc_text + ')' + '[' + str(i+1) + ']' ))).text
+    print(title,desc)
+    print()
+
+driver.quit()
+
+

Output (pasting partial output to save space)

+
Income support for sick or self-isolating workers Get up to $500 per week for six weeks if you are employed or self-employed and need to take time off because you’re sick or need to self-isolate due to COVID-19 or have an underlying medical condition that puts you at higher risks of getting COVID-19.
+
+Income support to care for dependent family members Get up to $500 per week for up to 44 weeks, per household, if you haven’t been able to work for at least 50% of your normal work week because you are caring for children under 12 years old or other dependent family members because of COVID-19.
+
+Support for businesses to avoid layoffs If your employees are eligible for Employment Insurance (EI) benefits, and your business is suffering a downturn due to COVID-19, you can apply for a work-sharing agreement. The agreement would allow your employees to work a temporarily reduced work week while receiving EI benefits.
+
",python +"How should I filter one dataframe by entries from another one in pandas with isin?

I have two dataframes (df1, df2). The columns names and indices are the same (the difference in columns entries). Also, df2 has only 20 entries (which also existed in df1 as i said). +I want to filter df1 by df2 entries, but when i try to do it with isin but nothing happens.

+
df1.isin(df2) or df1.index.isin(df2.index)
+
+

Tell me please what I'm doing wrong and how should I do it..

","

If you want to select the entries in df1 with an index that is also present in df2, you should be able to do it with:

+
df1.loc[df2.index]
+
+

or if you really want to use isin:

+
df1[df1.index.isin(df2.index)]
+
",python +"how do I manage deletion with multiple foreign keys to the same table in Django?

Say I have a model with a Things table and a table of relationships between the things called ThingRelations. It should not be possible to delete a Thing when there are ThingRelations that point to it. This is how I'm trying to implement that:

+
from django.db import models
+
+class ThingRelation(models.Model):
+    first_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)
+    second_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)
+
+class Thing(models.Model):
+    name = CharField(max_length=260)
+
+
+

How do I automatically delete a Thing when there are no more ThingRelations pointing to it?

","

You have such options:

+
    +
  • A routine. It can be made as a Command and something like crontab. Or it could be designed as a periodiq routine. This way you can repeatedly select all Thing models which have no relations with ThingRelation.
  • +
  • signals.py action. This way when entry of ThingRelation is deleted, you should check both the first_thing and second_thing in order to know whether the have any more ThingRelation relations pointing to them.
  • +
  • DB trigger (e.g. for PostgreSQL). The same idea as signal.py solution, but on DB level.
  • +
+

Which one should you choose? Depends on details of your exact objective. As for me, I use periodiq option on simple cases and DB trigger if I aim on high performance.

",python +"Seperate folder for django models

I am working on Django project that will utilize different apps to fulfill certain task. Since these apps will be referring to much same data to complete these task I figure it makes since to create a separate folder with the models like this:

+
--Project
+ --App1
+ --App2
+ --models
+  ---model1.py
+  ---model2.py
+
+

Right now I'm having trouble with Django recognizing the models as existing, every time I run a makemigrations Django does not detect that any changes have been made +I attempted to put a __init__.py file in the /models folder but this doesn't seem to do anything.

","

You should not seperate models in django projects dude! models.py file must be in app folder, That's why you can not migrate.

",python +"TypeError: 'str' object is not callable matplotlib

I encountered with this error: TypeError: 'str' object is not callable when trying to add a label on Y axis for my bar chart. Why? please help. Here's the code:

+
import pandas as pd 
+import matplotlib.pyplot as plt 
+# TODO: Plot company with the most stock and the lowest stock
+data = pd.read_csv("c:\\users\\HP\\Downloads\\Stock.csv")
+
+plt.bar(1,data['Stock'].max(), label=data['Company'].max())
+plt.bar(1,data['Stock'].min(), label=data['Company'].min())
+plt.ylabel("Stock")
+plt.legend()
+
+

Full error:

+
 TypeError                                 Traceback (most recent call last)
+<ipython-input-32-136cc5c2aaf2> in <module>
+      5 plt.bar(1,data['Stock'].max(), label=data['Company'].max())
+      6 plt.bar(1,data['Stock'].min(), label=data['Company'].min())
+----> 7 plt.ylabel("Stock")
+      8 plt.legend()
+
+TypeError: 'str' object is not callable
+
",

Try restarting the Kernel. This sometimes help

,python +"operands could not be broadcast together with shapes (100,3) (100,) , why?

This is my first question in stackoverlow, and My English is really poor, so I'm grateful to all those who read my poor English and help me^_^

+

My question is about broadcasting. enter image description here +What I want to do is mutiply each row of X by the number in the same row of B……

+

X is a (100,3) array and XW is a column vector, (100,). Why They can't broadcast?

+

After I add "XW = XW.reshape((X.shape[0],1))", Then, they can broadcast. Why…… Are there any difference between (100,1) and (100,)?

+

I think my picture have clearly described my question...My code really long.... I think it's not convenient to watch my code...

+

Here is the code..

+
import numpy as np
+import matplotlib.pyplot as plt
+
+class MyFirstMachineLeaningAlgorithm():
+    def StochasticGradientDescent(self, W, X, count=100, a=0.1):
+
+        n = X.shape[0]
+        for i in range(count):  # 学习count次
+            gradient = np.zeros(3)
+            for j in range(n):
+                gradient += X[j, :] * (1 - 2 * (X[j, :] @ W))
+
+            W = W + a * gradient
+            # 修复模长
+            W = W / np.sqrt((W @ W))
+
+        return W
+
+    def BatchGraidentDescent(self, W, X, count=100, a=0.1):
+        for i in range(count):
+            XW = X @ W
+            XW = 1 - 2 * XW
+
+            #XW = XW.reshape((X.shape[0],1))
+            gradient = X*XW
+            gradient = np.sum(gradient,axis = 0)
+
+            W = W + a * gradient
+            # 修复模长
+            W = W / np.sqrt((W @ W))
+
+    def train(self, count=100):
+        self.W = self.BatchGraidentDescent(self.W, self.X, count)
+
+    def draw(self):
+        draw_x = np.arange(-120, 120, 0.01)
+        draw_y = -self.W[0] / self.W[1] * draw_x
+        draw_y = [-self.W[2] / self.W[1] + draw_y[i] for i in range(len(draw_y))]
+        plt.plot(draw_x, draw_y)
+        plt.show()
+
+    def __init__(self):
+        array_size = (50, 2)
+        array1 = np.random.randint(50, 100, size=array_size)
+        array2 = np.random.randint(-100, -50, size=array_size)
+        array = np.vstack((array1, array2))
+        column = np.ones(100)
+        self.X = np.column_stack((array, column))
+        plt.scatter(array[:, 0], array[0:, 1])
+        self.W = np.array([1, 2, 3])
+        self.W = self.W / np.sqrt((self.W @ self.W))
+
+g = MyFirstMachineLeaningAlgorithm()
+g.train()
+g.draw()
+
+
","

It's best to post error information with copy-n-paste, not an image. Still the image is better than nothing.

+

So the error occurs in the last line of this clip:

+
        XW = X @ W
+        XW = 1 - 2 * XW
+
+        #XW = XW.reshape((X.shape[0],1))
+        gradient = X*XW
+
+

Just from the function definition I can't tell the shape of X and W. Apparently X is 2d (100,n). If W is (n,), then XW will be (100,), with the sum-of-products on the n dimension. Read the np.matmul docs if that isn't clear.

+

By the rules of broadcasting (look them up), if one array doesn't have as many dimensions as the other, it will add leading dimensions as needed. Thus (100,) can become (1,100). But to avoid ambiguity, it will not add a trailing dimension. You have to provide that yourself. So the last line should become

+
 gradient = X * XW[:,None]
+
+

or the equivalent using XW.reshape(-1,1) or your version.

+

Because arrays can be 1d (or even 0d), terms like row vector or column vector have limited value. A 1d array can thought of as a row vector in some cases - where this auto-leading dimension applies.

+
+

In init,

+
    self.X = np.column_stack((array, column))
+    self.W = np.array([1, 2, 3])
+
+

X is (100,3) and W is (3,). X@W is then (100,).

+
In [45]: X=np.ones((100,3)); W=np.array([1,2,3])
+In [46]: (X@W).shape
+Out[46]: (100,)
+In [47]: X * (1+(X@W)[:,None]);
+
",python +"change line color in middle of plot - plotly

Creating 12 subplots with plotly from a csv containing rows with 13 values. The last value indicates that the data in that row is estimated from this point until the status changes back in a later row.
+Trying to make line graphs that plots a line, changes to red when the status changes to 1, then back to original color when the status changes back to 0. Is this possible?

+
with lock:
+    df = pd.read_csv(OCcsvFile, delimiter=',')
+
+# plotly setup
+plot_rows = 4
+plot_cols = 3
+# Create plot figure
+fig = make_subplots(rows=plot_rows, cols=plot_cols, subplot_titles=("Header1", "Header2", "Header3", "Header4", "Header5",
+                                                                    "Header6", "Header7", "Header8", "Header9", "Header10",
+                                                                    "Header11", "Header12"))
+
+# add traces
+x = 1  # column counter
+for i in range(1, plot_rows+1):
+    for j in range(1, plot_cols+1):
+        #print(str(i)+ ', ' + str(j))
+        fig.add_trace(go.Scatter(x=df.iloc[:, 0], y=df.iloc[:, x],
+                                 name=df.columns[x],
+                                 mode='lines'),
+                      row=i,
+                      col=j)
+        x = x+1
+
","
    +
  • taken approach of reshaping dataframe to be ready for plotly express
  • +
  • have worked out starting dataframe from description, a sample would be better
  • +
+
import pandas as pd
+import plotly.express as px
+
+df = pd.DataFrame(
+    np.random.randint(1, 10, [100, 12]), columns=[f"c{i+1}" for i in range(12)]
+).assign(status=np.repeat(np.random.randint(0, 2, 20), 5))
+
+# restructure dataframe for px
+# 1. preserve status in index
+# 2. make columns another level of index
+# 3. make index columns and make column names meaningful
+dfp = (
+    df.set_index("status", append=True)
+    .stack()
+    .reset_index()
+    .rename(columns={"level_0": "x", "level_2": "facet", 0: "value"})
+)
+
+# make sure missing values are present as NaN
+dfp = dfp.merge(
+    pd.DataFrame(index=pd.MultiIndex.from_product(
+        [dfp["x"].unique(), dfp["facet"].unique(), dfp["status"].unique()]
+    )),
+    left_on=["x", "facet", "status"],
+    right_index=True,
+    how="right"
+)
+
+# now it's a very simple plot
+px.line(dfp, x="x", y="value", color="status", facet_col="facet", facet_col_wrap=4)
+
+
+
+

+

expected structure or df

+
    +
  • 13 columns, last column indicating the status
  • +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
c1c2c3c4c5c6c7c8c9c10c11c12status
107317281396381
114589543637481
126326564353971
134248633588141
144993182515141
154962941661610
168597731125290
176142859824840
181613855989290
191411782356640
+
",python +"Discord.py How do I split a bots message?

So, I have a discord information bot I am working on and this is one of the commands.

+
@client.command()
+async def rd(ctx):
+    embed = discord.Embed(title="**[R&D Cost at every level]:**")
+    embed.add_field(name="**Level//All Units ATK Bonus//March Size Increase//R&D Cost**", value= "|", inline=False)
+    embed.add_field(name="6    0.6%    0    10", value='.', inline=False)
+    embed.add_field(name="7    0.7%    0    20", value='.', inline=False)
+    embed.add_field(name="8    0.8%    0    30", value='.', inline=False)
+    embed.add_field(name="9    0.9%    0    35", value='.', inline=False)
+    embed.add_field(name="10    1.0%    0    40", value='.', inline=False)
+    embed.add_field(name="11    1.2%    0    45", value='.', inline=False)
+    embed.add_field(name="12    1.5%    0    50", value='.', inline=False)
+    embed.add_field(name="13    2.0%    0    60", value='.', inline=False)
+    embed.add_field(name="14    2.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="15    3.0%    0    TBD", value='.', inline=False)
+    embed.add_field(name="16    3.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="17    4.0%    0    TBD", value='.', inline=False)
+    embed.add_field(name="18    4.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="19    5.0%    0    TBD", value='.', inline=False)
+    embed.add_field(name="20    5.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="21    6.0%    0    TBD", value='.', inline=False)
+    embed.add_field(name="22    6.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="23    7.0%    0    TBD", value='.', inline=False)
+    embed.add_field(name="24    7.5%    0    TBD", value='.', inline=False)
+    embed.add_field(name="25    8.0%    1    TBD", value='.', inline=False)
+    embed.add_field(name="26    8.5%    1    TBD", value='.', inline=False)
+    embed.add_field(name="27    9.0%    1    TBD", value='.', inline=False)
+    embed.add_field(name="28    9.5%    1    TBD", value='.', inline=False)
+    embed.add_field(name="29    10.0%    1    TBD", value='.', inline=False)
+    embed.add_field(name="30    10.5%    2    TBD", value='.', inline=False)
+    embed.add_field(name="31    11.0%    2    TBD", value='.', inline=False)
+    embed.add_field(name="32    11.5%    2    TBD", value='.', inline=False)
+    embed.add_field(name="33    12.0%    2    1.27K", value='.', inline=False)
+    embed.add_field(name="34    12.5%    2    1.46K", value='.', inline=False)
+    embed.add_field(name="35    13.0%    3    1.87K", value='.', inline=False)
+    embed.add_field(name="36    13.5%    3    2.02K", value='.', inline=False)
+    embed.add_field(name="37    14.0%    3    2.18K", value='.', inline=False)
+    embed.add_field(name="38    14.5%    3    2.36K", value='.', inline=False)
+    embed.add_field(name="39    15.0%    3    2.54K", value='.', inline=False)
+    embed.add_field(name="40    15.5%    4    2.73K", value='.', inline=False)
+    embed.add_field(name="41    16.0%    4    2.87K", value='.', inline=False)
+    embed.add_field(name="42    16.5%    4    3.07K", value='.', inline=False)
+    embed.add_field(name="43    17.0%    4    3.29K", value='.', inline=False)
+    embed.add_field(name="44    17.5%    4    3.51K", value='.', inline=False)
+    embed.add_field(name="45    18.0%    5    3.74K", value='.', inline=False)
+    embed.add_field(name="46    18.5%    5    3.99K", value='.', inline=False)
+    embed.add_field(name="47    19.0%    5    4.09K", value='.', inline=False)
+    embed.add_field(name="48    19.5%    5    4.34K", value='.', inline=False)
+    embed.add_field(name="49    20.0%    5    4.44K", value='.', inline=False)
+    embed.add_field(name="50    20.5%    6    4.54K", value='.', inline=False)
+
+

The command works great, except that discord cuts the message off on "embed.add_field(name="29 10.0% 1 TBD", value='.', inline=False)", due to the max character limit in a single message.

+

+

How would I go about splitting this message into pages? I have seen where you can have emojis that scroll through information, but I am unsure on how to apply that to this command here.

+

Or how could I make it to where it posts into multiple messages instead of it attempting to post into one whole message?

+

Any help is much appreciated!

","

This is the code I used to work with pagination before I started implementing buttons

+
async def paginate(
+    ctx: discord.ext.commands.context.Context,
+    *embed_pages: typing.Union[discord.Embed, list[discord.Embed]],
+    content=None,
+    overwrite_footer=True,
+    timeout=None,
+):
+
+    if isinstance(embed_pages[0], list):
+        embed_pages = embed_pages[0]
+
+    every_embed = list()
+    if overwrite_footer:
+        for index, each_embed in enumerate(embed_pages):
+            each_embed.remove_footer()
+            each_embed.set_footer(text=f"Page {index + 1} of {len(embed_pages)}")
+            every_embed.append(each_embed)
+    else:
+        every_embed = embed_pages[:]
+
+    sent_embed = await ctx.send(
+        content=content, embed=every_embed[0]
+    )  # Send the first page
+    page_index = 0  # Set the starting index
+
+    reactions = ["⬅️", "", "➡️"]
+    for each_reaction in reactions:
+        await sent_embed.add_reaction(each_reaction)
+
+    while True:
+        try:
+            payload = await bot.wait_for(
+                "raw_reaction_add",
+                check=lambda payload: payload.message_id == sent_embed.id
+                and not payload.member == bot.user
+                and payload.member.id
+                == ctx.author.id,  # Do this if you want it to be author-only
+                timeout=timeout,
+            )
+        except asyncio.TimeoutError:
+            # timeout has been hit
+            if overwrite_footer:
+                every_embed[page_index].remove_footer()
+                every_embed[page_index].set_footer(
+                    text="Pagination traversal has timed out."
+                )
+                await sent_embed.edit(embed=every_embed[page_index])
+                try:
+                    await every_embed.clear_reactions()
+                except:
+                    pass
+            return
+        else:
+            try:
+                await sent_embed.remove_reaction(payload.emoji, payload.member)
+            except discord.Forbidden:
+                # Bot does not have permission
+                pass
+
+            if (
+                str(payload.emoji.name) not in reactions
+            ):  # Some user reacted with something else
+                pass
+
+            elif str(payload.emoji.name) == reactions[0]:  # Previous page
+                if not page_index == 0:
+                    page_index -= 1
+                else:
+                    page_index = len(every_embed) - 1
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+            elif str(payload.emoji.name) == reactions[1]:  # Goto page 0
+                page_index = 0
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+            else:
+                if not page_index == (len(every_embed) - 1):
+                    page_index += 1
+                else:
+                    page_index = 0
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+
+

This function is a coroutine and has to be awaited, the first argument must be ctx (context), rest of the arguments may be discord.Embed objects or a single list that contain instances of aforementioned discord.Embed.

+

The rest of the arguments are optional and self-explanatory.

+

Here's an use-case :

+
import discord
+import os
+import asyncio
+import typing
+import Lorem  # Custom module
+from discord.ext import commands
+from dotenv import load_dotenv
+
+load_dotenv()
+bot = commands.Bot(command_prefix=">")
+
+
+async def paginate(
+    ctx: discord.ext.commands.context.Context,
+    *embed_pages: typing.Union[discord.Embed, list[discord.Embed]],
+    content=None,
+    overwrite_footer=True,
+    timeout=None,
+):
+
+    if isinstance(embed_pages[0], list):
+        embed_pages = embed_pages[0]
+
+    every_embed = list()
+    if overwrite_footer:
+        for index, each_embed in enumerate(embed_pages):
+            each_embed.remove_footer()
+            each_embed.set_footer(text=f"Page {index + 1} of {len(embed_pages)}")
+            every_embed.append(each_embed)
+    else:
+        every_embed = embed_pages[:]
+
+    sent_embed = await ctx.send(
+        content=content, embed=every_embed[0]
+    )  # Send the first page
+    page_index = 0  # Set the starting index
+
+    reactions = ["⬅️", "", "➡️"]
+    for each_reaction in reactions:
+        await sent_embed.add_reaction(each_reaction)
+
+    while True:
+        try:
+            payload = await bot.wait_for(
+                "raw_reaction_add",
+                check=lambda payload: payload.message_id == sent_embed.id
+                and not payload.member == bot.user
+                and payload.member.id
+                == ctx.author.id,  # Do this if you want it to be author-only
+                timeout=timeout,
+            )
+        except asyncio.TimeoutError:
+            # timeout has been hit
+            if overwrite_footer:
+                every_embed[page_index].remove_footer()
+                every_embed[page_index].set_footer(
+                    text="Pagination traversal has timed out."
+                )
+                await sent_embed.edit(embed=every_embed[page_index])
+                try:
+                    await every_embed.clear_reactions()
+                except:
+                    pass
+            return
+        else:
+            try:
+                await sent_embed.remove_reaction(payload.emoji, payload.member)
+            except discord.Forbidden:
+                # Bot does not have permission
+                pass
+
+            if (
+                str(payload.emoji.name) not in reactions
+            ):  # Some user reacted with something else
+                pass
+
+            elif str(payload.emoji.name) == reactions[0]:  # Previous page
+                if not page_index == 0:
+                    page_index -= 1
+                else:
+                    page_index = len(every_embed) - 1
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+            elif str(payload.emoji.name) == reactions[1]:  # Goto page 0
+                page_index = 0
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+            else:
+                if not page_index == (len(every_embed) - 1):
+                    page_index += 1
+                else:
+                    page_index = 0
+                await sent_embed.edit(embed=every_embed[page_index], content=content)
+
+
+@bot.event
+async def on_ready():
+    print(f"Sucessfully logged in as {bot.user}")
+
+
+@bot.command()
+async def start(ctx):
+
+    await paginate(
+        ctx,
+        [
+            discord.Embed(title="Answered by Achxy!", description=Lorem.lorem(6))
+            for _ in range(100)
+        ],
+    )
+    # We just generated 100 pages of Lorem Ipsum :D
+
+
+@bot.command()
+async def ping(ctx):
+    # I made this command just to prove that the while loop earlier isn't blocking.
+    embed = discord.Embed(
+        title="Pong! ",
+        description=f"Current Latency of the bot is {round(bot.latency * 1000)}ms",
+    )
+    await ctx.reply(embed=embed)
+
+
+bot.run(os.getenv("DISCORD_TOKEN"))
+
+

This code will bring the following paginated output :

+

https://imgur.com/a/tmwGhpc

",python +"Apply a function to each element of an array in Python

I am trying to do two things in Python:

+
    +
  1. Simulate 100 random draws from a Poisson distribution. I have done this by:
  2. +
+
sample100 = poisson.rvs(mu=5,size=100)
+
+
    +
  1. Take the above sample, and apply an UMP test I've generated to each individual observation (e.g., test the hypothesis against each individual observation). The test should accept the null hypothesis if the observation has a value < 8; reject with probability ~50% if observation has value = 8; reject if observation has value > 8
  2. +
+

I cannot figure out how to do the second part of this. The function code I've made is:

+
    def optionaltest(y,k,g):
+    
+        if (y > k):
+            return 1
+        if (y == k):
+            if rand(uniform(0,1)) >= 0.4885: return 1
+            else: return 0
+        if (y < k):
+            return 0
+
+

But there are two issues - apparently if (y==k) is invalid syntax. Second, even if I remove that part, I can't actually apply the function to sample100 since it is an array.

+

How can I modify this to make it work? Clearly, I'm very new to Python but I have been scouring the internet for hours. Perhaps I should change how I'm generating my sample data so I can apply a function to it? Maybe there's a way to apply a function to each element of an array? How do I make the test logic work when the output = k (which I will set to 8 in this case)?

+

EDIT/UPDATE: +Here's how I ended up doing it:

+
    def optionaltest(y):
+    
+        if (y > 8):
+            return 1
+        if (y == 8):
+            if np.random.uniform(0,1) >= 0.4885: return 1
+            else: return 0
+        if (y < 8):
+            return 0
+
+

I was able to apply that test to my array data via:

+
results_sample100 = list(map(optimaltest, sample100))
+cl.Counter(results_sample100)
+
","

This is invalid python syntax

+
if rand(uniform(0,1)) >= 0.4885 then 1
+    else 0
+
+

Instead, you could do this:

+
return 1 if rand(uniform(0,1)) >= 0.4885 else 0
+
+

You could also do something more verbose but potentially more straightforward (this is often a matter of taste), like this:

+
def optionaltest(y,k,g):
+
+    if (y > k):
+        return 1
+    if (y == k):
+        if rand(uniform(0,1)) >= 0.4885:
+            return 1
+        else:
+            return 0
+    if (y < k):
+        return 0
+
+

Or even like this:

+
def optionaltest(y,k,g):
+
+    if (y > k):
+        return 1
+    if (y == k) and rand(uniform(0,1)) >= 0.4885:
+        return 1
+    else:
+        return 0
+
+

For this question:

+
+

Maybe there's a way to apply a function to each element of an array?

+
+

You can use a for-loop or map a function over a list:

+
results = []
+for elem in somelist:
+     results.append(my_function(elem))
+
+

Alternately:

+
results = list(map(my_function, somelist))
+
+

Your function takes three arguments, though, and it's not clear to me where those are coming from. Is your list a list of tuples?

",python +"Trying to filter one list according to whether elements are in another list in Python

I am trying to filter a list of genes I have obtained according to whether they are in a reference list. I have looked at these questions, which have been helpful, but they haven't helped me resolve the trouble I'm having (if/else in a list comprehension, +List comprehension with else pass, if pass and if continue in python, Remove all the elements that occur in one list from another). Some of the answers from the last question in particular seemed very helpful but they didn't seem to work with my data.

+

I've tried to simplify what I'm doing, and this is a little toy example I have now:

+
head = genes_9.head()
+diff_expressed_tf = [gene for gene in genes_9 if gene in head]
+diff_expressed_tf
+
+# This returns 
+[]
+
+

I'm thinking that if I can get this to work with "genes_9.head()" it should work with my actual reference data.

+

Would someone be able to help me rewrite this to do what I want it to do? Alternatively, if someone could point me towards other relevant questions, I would also appreciate that greatly.

+

For reference, here is a little snippet of my data:

+
genes_9.head(10)
+
+
+0      Tnfrsf4
+2     Tnfrsf18
+14       Il2ra
+5         Odc1
+7        Foxp3
+36       Ctla4
+3        Ikzf2
+1          Cd5
+8         Ccr8
+24     Tnfrsf9
+
","

If your datatype is a Pandas Series, then you can use 'iteritems()' instead of 'iterrows()' like this:

+

diff_expressed_tf = [gene for index, gene in genes_9.iteritems() if gene in head]

",python +"Is there a method to aggregate time series in pandas based on the sequential count of an occurrence?

I am looking for a way in pandas to count the number of sequential of occurrences of a particular value in a time series.

+

Suppose I am performing an experiment where I flip a coin and get heads or tails (1 or 0). I record my results in a pandas series, and I wish to see how many instances (a count) I had with two sequential heads, three sequential heads, four sequential heads, and so on. Moreover, I wish it to be something of a rolling count, meaning that a sequence of the form (tails, heads, heads, heads, tails) will return a count of two instances of heads occurring in pairs, and a single count of a series of three heads.

+

Is there a natural way to do this with methods in a Series/DataFrame? I could do it with some for loops, but I am concerned about the cost of that.

+

Thanks.

+

Edit: requested input/output.

+

Input:

+
a = pd.DataFrame({'coin' : [0,1,1,1,0]})
+print(a.summary_of_windows())
+
+

Output:

+
{1: 3
+ 2: 2,
+ 3: 1}
+
+

The output could be a dictionary: the key 1 means heads occurrences, of which three occurred. Key 2 means pairs of sequential heads (there are two of those), and Key 3 means sequences of length 3 of heads (happened once).

","

You can use DataFrame.rolling:

+
>>> df
+   coin
+0     0
+1     1
+2     1
+3     1
+4     0
+
+# Compute how many sequences of two heads there are:
+>>> df['coin'].rolling(2).sum().eq(2).sum()
+2
+
+# Do it for three sequences:
+#   remember to change v    AND    v
+>>> df['coin'].rolling(3).sum().eq(3).sum()
+1
+
+# Find total number of heads occurences:
+>>> df['coin'].sum()
+3
+
",python +"How to get the duplicates from the lists based on name

I am accessing some files from the server and printing the results but how can I get the duplicates based on the name from the printed results.

+
from datetime import datetime
+class EsriApiMaps:
+
+    def __init__(self, portal, item_type, query):
+        self.item_type = item_type
+        self.query_ = query
+        self.portal = portal
+
+    def query_maps(self):
+        api_query_result = self.portal.content.search(query=self.query_, item_type=self.item_type)
+        l = [] # we will store all the services e,g url,id,owner etc
+
+
+        for l in api_query_result:
+            l_created_time = datetime.fromtimestamp(round(l.created / 1000))
+            l_modified_time = datetime.fromtimestamp(round(l.modified / 1000))
+            df = ("Name: " + l.title + "ID: " + l.id + ", Owner: " + l.owner + ", Created: " + str(l_created_time) + ", Modified: " + str(l_modified_time))
+            print(df)
+
+

I have tried this to get the below results,

+
Name: KL, ID: af57c454, Owner: Scripter, Created: 2019-10-08 12:57:45, Modified: 2019-10-08 12:57:45
+Name: KL, ID: dfsjd5s4, Owner: d011, Created: 2020-10-27 21:02:54, Modified: 2020-10-27 21:02:54
+Name: TEAM, ID: b8djx8, Owner: j277, Created: 2019-10-08 12:52:54, Modified: 2019-10-08 12:52:54
+Name: ALL, ID: b896sfd, Owner: rp10, Created: 2019-10-11 14:51:38, Modified: 2019-10-11 14:51:38
+Name: MD, ID: dhx865, Owner: ws07, Created: 2019-10-08 15:17:59, Modified: 2019-10-08 15:17:59
+Name: AJKL, ID: dhsa88, Owner: fsdd, Created: 2020-07-23 16:04:20, Modified: 2020-07-23 16:04:20
+Name: MD, ID: sd5425, Owner: fsdd, Created: 2021-02-02 11:43:15, Modified: 2021-02-02 11:43:15
+Name: MD, ID: vcxb65, Owner: dsff1, Created: 2020-06-17 10:56:36, Modified: 2020-06-17 10:56:36
+
+

I have tried using,

+
names = df.Name.value_counts()
+names[names>1] 
+
+

But I am getting this error AttributeError: 'str' object has no attribute 'Name'

+

How can I get the duplicates based on its name ?

+

The expected result is

+
Name: KL, ID: af57c454, Owner: Scripter, Created: 2019-10-08 12:57:45, Modified: 2019-10-08 12:57:45
+Name: KL, ID: dfsjd5s4, Owner: d011, Created: 2020-10-27 21:02:54, Modified: 2020-10-27 21:02:54
+Name: MD, ID: sd5425, Owner: fsdd, Created: 2021-02-02 11:43:15, Modified: 2021-02-02 11:43:15
+Name: MD, ID: vcxb65, Owner: dsff1, Created: 2020-06-17 10:56:36, Modified: 2020-06-17 10:56:36
+Name: MD, ID: dhx865, Owner: ws07, Created: 2019-10-08 15:17:59, Modified: 2019-10-08 15:17:59
+
","

df it's a string, not a dataframe, you should create a dataframe with the results of the API query and then you could use de dataframe methods.

+

You can create a list with the results and then initialize the dataframe witht it.

+
def query_maps(self):
+        api_query_result = self.portal.content.search(query=self.query_, item_type=self.item_type)
+        data = []
+
+        for l in api_query_result:
+            l_created_time = datetime.fromtimestamp(round(l.created / 1000))
+            l_modified_time = datetime.fromtimestamp(round(l.modified / 1000))
+            data.append({"Name": l.title, "ID": l.id, "Owner": l.owner, "Created": str(l_created_time), "Modified": str(l_modified_time)})
+        df = pd.Dataframe(data)
+
",python +"Not getting number when crawling number of new COVID cases through BeautifulSoup

Good evening,

+

I am currently trying to crawl the South Australia's covid case number from the website (https://www.covid-19.sa.gov.au/home/dashboard).

+

I found the the numbers are under

+
<div id="convid19-data-visual" class="twbs">
+<div class="container">
+    <div class="row southaus">
+        <div clsass="col-md-6 col-lg-4" style="padding:10px 25px">
+            <div class="st">
+                "New Cases"
+                <span class="nCasesa majorNum">64</span>
+            </div>
+        </div>
+    </div>
+</div>
+
+ +

Thus, I tried to crawl the number by applying the following code:

+
import requests
+from bs4 import BeautifulSoup
+
+result = requests.get("https://www.covid-19.sa.gov.au/home/dashboard")
+soup = BeautifulSoup(result.text, "html.parser")
+cases = soup.find("div", {"class" : "st"}
+st = cases.find_all("span")
+print(st)
+
+

and I got result of

+
[<span class="nCasesa majorNum"> </span>]
+
+

which does not include the case number.

+

I had tried with selenium as well, but I was not able to get the case number either. I'm now confused whether the HTML tag that I found is right.

+

If possible, would it be able to be fixed by getting right HTML tag?

+

Thanks!

","

The text associated with the span element of class nCasesa is loaded dynamically (JavaScript) and there is a delay in rendering the actual value in your browser. What you need to do (with Selenium) is to detect a change to the text. You can do it like this:

+
from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+
+CLASS = 'nCasesa'
+options = webdriver.ChromeOptions()
+options.add_argument('--headless')
+
+class detect():
+    def __init__(self, locator, params):
+        self.locator = locator
+        self.params = params
+        self.text = None
+
+    def gettext(self, driver):
+        return driver.find_element(self.locator, self.params).text
+
+    def __call__(self, driver):
+        if self.text is None:
+            self.text = self.gettext(driver)
+        else:
+            current = self.gettext(driver)
+            if current != self.text:
+                self.text = current
+                return True
+        return False
+
+with webdriver.Chrome(options=options) as driver:
+    driver.get(f'https://www.covid-19.sa.gov.au/home/dashboard')
+    detector = detect(By.CLASS_NAME, CLASS)
+    WebDriverWait(driver, 10).until(detector)
+    print(detector.text)
+
+

Output:

+
73
+
",python +"Adding XML Source to xlsx file in python

I am trying to create a xlsx from a template exported from Microsoft dynamics NAV, so I can upload my file to the system.

+

I am able to recreate and fill the template using the library xlsxwriter, but unfortunately I have figured out that the template file also have an attached XML source code file(visible in the developer tab in Excel).

+

I can easily modify the XML file to match what I want, but I can't seem to find a way to add the XML source code to the xlsx file. +I have searched for "python adding xlsx xml source" but it doesn't seem to give me anything I can use.

+

Any help would be greatly appreciated.

+

Best regards +Martin

","

Xlsx file is basically a zip archive. Open it as archive and you'll probably be able to find the XML file and modify it. – +Mak Sim +yesterday

",python +"How do I Anchor Text and Shrink it to fit it on an Image

I fount this code off of the PIL API(here is the link: https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html) and I wanted to also shrink it depending on the size of the text while it is centered.

+

here is the anchoring code

+
from PIL import Image, ImageDraw, ImageFont
+
+font = ImageFont.truetype("mont.ttf", 48)
+im = Image.new("RGB", (200, 200), "white")
+d = ImageDraw.Draw(im)
+d.text((100, 100), "Quick", fill="black", anchor="ms", font=font)
+im.save('text.png')
+
+

And the outcome looks like this:

+

+

But if you increase the word size it looks like this:

+

+

So I just want the text to be centered and shrunk to fit the image

","

No detail about the requirements, so here only for result image with fixed size (200, 200), so font size will be changed.

+
    +
  • Find the size of text by ImageDraw.textsize
  • +
  • Draw on an image with same width as the text by ImageDraw.text
  • +
  • Resize image to (200-2*border, 200-2*border) by Image.resize
  • +
  • Paste the resized image to a 200x200 image by Image.paste
  • +
+
from PIL import Image, ImageDraw, ImageFont
+
+def text_to_image(text, filename='text.png', border=20):
+    im = Image.new("RGB", (1, 1), "white")
+    font = ImageFont.truetype("calibri.ttf", 48)
+    draw = ImageDraw.Draw(im)
+    size = draw.textsize(text, font=font)
+    width = max(size)
+    im = Image.new("RGB", (width, width), "white")
+    draw = ImageDraw.Draw(im)
+    draw.text((width//2, width//2), text, anchor='mm', fill="black", font=font)
+    im = im.resize((200-2*border, 200-2*border), resample=Image.LANCZOS)
+    new_im = Image.new("RGB", (200, 200), "white")
+    new_im.paste(im, (border, border))
+    new_im.show()
+    # new_im.save(filename)
+
+text_to_image("Hello World")
+
+

",python +"Measure image sharpness with opencv using gpu

I created a small script that extract the most sharp image from a set of images using Laplacian like that:

+
sharpness = cv2.Laplacian(cv2.imread(path), cv2.CV_64F).var()
+
+

However the code is a bit slow and it seems to only use CPU, then I'm wondering if there's a method that uses the gpu to calculate that value, but only find example to sharpen an image.

","

Don't optimize before you know what is taking time.

+

Most time is spent on loading the image. Time it, you'll see. This involves accessing mass storage and decoding the image format. PNG isn't the most complex out there, so it could be worse.

+

The laplacian calculation uses a specific kernel. Convolving the picture with an arbitrary 3x3 kernel would cost 9 multiplications and 9 additions. This kernel costs one shift and five adds/subs. The CPU's SIMD will eat this for breakfast.

+

A GPU won't help at all. It takes time to transfer this data to the GPU. Then there are other constant costs (latency, "warm-up") to starting any calculations on a GPU. A CPU would already be done calculating. If you had a ton of pictures, at least the transfer could be pipelined and the upload of kernel code would only be required once.

+

Both the GPU and the CPU are likely memory-bound in this entire operation, meaning compute capability is far from challenged by this.

+

If you really wanted to get a GPU involved, the easiest way would be to wrap the numpy array in a cv.UMat and pass the UMat object in instead. OpenCV will then use OpenCL. The result will be a UMat again, so you would need to see what OpenCV function can calculate the variance for you.

+
h_im = cv.imread(...) # hostside data
+d_im = cv.UMat(im) # usable on "device"
+d_lap = cv.Laplacian(d_im, cv.CV_32F) # single floats are usually faster than doubles
+h_lap = d_lap.get() # retrieve data
+# numpy functions unavailable on UMat, hence hostside calculation
+var = h_lap.var()
+# try cv.meanStdDev, calculates for each channel
+
",python +"Modifying the Grid in matplotlib.pyplot graph

I am a newbie to Python but slowly getting there. I am having a problem trying to increase the number of grid lines on a graph. Basically, the Graph is labelled 0-24 (Hours) but the x axis only generates a label every 5 hours (O,5,10,15,20) with a grid line at each of those majors. Ideally, I would like a grid line every hour as I am collecting real time data.

+

Most of this code has been lifted from various sources, but the one thing that has stumped me is how to configure the grid..

+

Edit - As requested my simplified code is below..

+
import numpy as np
+import matplotlib.pyplot as plt
+import time
+
+timedata=[0.01,1.1,2.2,3.3,4.4,5.55,6.6,7.7,8.8,9.1,10.2,11.2,12.2,13.2,14.1,15.2,16.1,17.2,18.1,19.2,20.1,21.1,22.2,23.1]
+#timedata is in decimal hours
+bxdata=[10,10,20,20,20,30,30,30,40,40,40,30,30,30,20,20,30,30,20,20,40,50,30,24]
+bydata=[20,10,20,30,20,30,30,30,5,40,40,30,5,30,20,20,30,35,20,20,5,50,30,24]
+
+#draw the graph
+fig, ax = plt.subplots(sharex=True, figsize=(12, 6))
+x=np.arange(0,24,1)
+
+ax.plot(timedata,bxdata, color='red', label='Bx',lw=1)
+ax.plot (timedata, bydata, color='blue', label = 'By',lw=1)
+ax.set_xlim(0,24)
+ax.set_ylim(-250,250)
+
+plt.ion()
+plt.xlabel("Time (Hours)")
+plt.ylabel("nT")
+plt.grid(True, which='both')
+plt.legend()
+plt.show()
+image = "test.png"
+time.sleep(2)
+plt.savefig(image)
+plt.close('all')
+
+

and this is the graph that I get.

+

","

The idea is to associate a locator to the minor x-axis ticks, the locator you need is MultipleLocator and we use it also to fix the major ticks' spacing (for hours, 6 is better than 5, isn't it?)

+

+
import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.ticker import MultipleLocator
+
+y = np.random.rand(25)
+plt.plot(y)
+
+plt.gca().xaxis.set_major_locator(MultipleLocator(6))
+plt.gca().xaxis.set_minor_locator(MultipleLocator(1))
+
+plt.grid()
+plt.grid(True, 'minor', color='#ddddee') # use a lighter color
+
+plt.show()
+
",python +"Speeding up python when using nested for and if loops

I have a csv file that has a column called "Authors". In that column, each row has a couple of authors separated by commas. In the code below the function, getAuthorNames gets all the author names in that column and returns an array with all their names.

+

Then the function authCount counts how many times an individual name appears in the Author column. At first, I was doing it with a couple of hundred rows and had no issues. Now I am trying to do it with 20,000 rows+ and it has taken a couple of hours and still no results. I believe it is the nested for loops and if statement that is causing it to take so long. Any advice on how to speed up the process would help. Should I be using lambda? Is there a built it pandas function that could help?

+

This is what the input data looks like:

+
Title,Authors,ID
+XXX,"Wang J, Wang H",XXX
+XXX,"Wang J,Han H",XXX
+
+

And this is what the output would look like

+
Author,Count
+Wang J,2
+Wang H,1
+Han H,1
+
+

Here is the code:

+
    import pandas as pd
+
+
+    df = pd.read_csv (r'C:\Users\amos.epelman\Desktop\Pubmedpull3GC.csv')
+
+
+    def getAuthorNames(dataFrame):
+        arrayOfAuthors = []
+        numRows = dataFrame.shape[0]
+
+        cleanDF = dataFrame.fillna("0")
+
+        for i in range (0,numRows):
+            miniArray = cleanDF.at[i,"Authors"].split(",")
+            arrayOfAuthors += miniArray
+    
+        return arrayOfAuthors
+
+
+    def authCount(dataFrame):
+        authArray = getAuthorNames(dataFrame)
+        numAuthors = len(authArray)
+        countOfAuth = [0] * numAuthors
+
+        newDF = pd.DataFrame({"Author Name": authArray, "Count": countOfAuth})
+        refDF = dataFrame.fillna("0")
+
+
+        numRows= refDF.shape[0]
+
+
+        for i in range (0,numAuthors):
+            for j in range (0,numRows):
+                if newDF.at[i, "Author Name"] in refDF.at[j,"Authors"]:
+                    newDF.at[i,"Count"] += 1
+            
+        sortedDF = newDF.sort_values(["Count"], ascending = False)
+
+        noDupsDF = sortedDF.drop_duplicates(subset ="Author Name", keep = False)
+
+        return noDupsDF
+
+
+
+
+    finalDF = authCount(df)
+    file_name = 'GC Pubmed Pull3 Author Names with Count.xlsx'
+    finalDF.to_excel(file_name)
+
","

you could try using Counter and a lambda function to eliminate your nested for loop over two dataframes, which seems like it would be a slow way to add a new column

+
from collections import Counter
+
+

Then to get the "Counts" column

+
author_counts = Counter(list(refDF["Authors"]))
+
+newDF["Count"] = newDF.apply(lambda r: author_counts[r["Author Name"]], axis=1)
+
",python +"JSON serialization of dictionary with complex objects

I am trying to serialize the dictionary playersElo for saving/loading it as/from JSON.

+

But as it's not a serializable object and I can't find a way to do it.

+
playersElo={} # dictionary of {<int> : <PlayerElo>}
+playersElo[1] = PlayerElo()
+playersElo[2] = PlayerElo()
+...
+
+class PlayerElo:
+    """
+    A class to represent a player in the Elo Rating System
+    """
+    def __init__(self, name: str, id: str, rating):
+        self.id = id
+        self.name = name
+        # comment the 2 lines below in order to start with a rating associated
+        # to current player rank
+        self.eloratings = {0: 1500}
+        self.elomatches = {0: 0}
+        self.initialrating = rating
+
+
","

Maybe this can be a starting spot for you. The serializer grabs the __dict__ attribute from the object and makes a new dict-of-dicts, then writes it to JSON. The deserializer creates a dummy object, then updates the __dict__ on the way in.

+
import json
+
+class PlayerElo:
+    """
+    A class to represent a player in the Elo Rating System
+    """
+    def __init__(self, name: str, id: str, rating):
+        self.id = id
+        self.name = name
+        self.eloratings = {0: 1500}
+        self.elomatches = {0: 0}
+        self.initialrating = rating
+
+
+playersElo={} # dictionary of {<int> : <PlayerElo>}
+playersElo[1] = PlayerElo('Joe','123',999)
+playersElo[2] = PlayerElo('Bill','456',1999)
+
+def serialize(ratings):
+    newdict = {i:j.__dict__ for i,j in ratings.items()}
+    json.dump( newdict, open('x.json','w') )
+
+def deserialize():
+    o = json.load(open('x.json'))
+    pe = {}
+    for k,v in o.items():
+        obj = PlayerElo('0','0',0)
+        obj.__dict__.update( v )
+        pe[int(k)] = obj
+    return pe
+
+print(playersElo)
+serialize( playersElo )
+pe = deserialize( )
+print(pe)
+
",python +"await vs yield from for python

https://stackoverflow.com/a/44273861/433570 +says 'yield from' is old and we should learn 'await'.
+But It doesn't say they are the same thing or they are different.

+

But I have some good book and videos which talks about yield from

+

Can I think yield from was replaced by await? and they are essentially the same thing?

+

https://www.youtube.com/watch?v=MCs5OvhV9S4

+

I have a book fluent python which also talks about yield from

+
    +
  • Edit
  • +
+

When I see some good books/videos like the above talking about yield from, could I substitute yield from with await in my mind?

","

Yes they are the same thing. Yield is the manual way of doing async await. See https://www.python.org/dev/peps/pep-0492/#new-coroutine-declaration-syntax where they detail that async await is just a coroutine (yield) underneath

",python +"How to convert list of jsons in a nested list of jsons to csv in python?

How do I convert a list of jsons in a nested list of jsons to be in the following format? Can't seem to get this right and many examples use pandas where as I'd prefer to use csv.DictWriter. My thoughts are to (in a loop) read the json - in this case data, transpose it for it to be horizontal.

+
{"rows": [
+        {
+          "data": [
+            {
+              "A": "1",
+              "B": "2"
+            },
+            {
+              "C": "3",
+              "D": "4"
+            },
+            {
+              "E": "5",
+              "F": "6"
+            }
+          ]
+        },
+       ...
+       ...
+       ...
+        {
+          "data": [
+            {
+              "A": "7",
+              "B": "8"
+            },
+            {
+              "C": "9",
+              "D": "10"
+            },
+            {
+              "E": "11",
+              "F": "12"
+            }
+          ]
+        }
+]
+}
+
+

Desired format:

+
A, B, C, D, E, F
+1, 2, 3, 4, 5, 6
+...
+7, 8, 9, 10, 11, 12
+
+
+

I've read the json already using json.loads. Just stuck on converting this bit.

","

DictWriter is pretty straightforward with a dict comprehension to generate the row data:

+
import json
+import csv
+
+json_str = '''{"rows": [{"data": [{"A": "1", "B": "2"},
+                                  {"C": "3", "D": "4"},
+                                  {"E": "5", "F": "6"}]},
+                        {"data": [{"A": "7", "B": "8"},
+                                  {"C": "9", "D": "10"},
+                                  {"E": "11", "F": "12"}]}]}'''
+
+data = json.loads(json_str)
+with open('out.csv','w',newline='') as f:
+    w = csv.DictWriter(f,fieldnames='ABCDEF')
+    w.writeheader()
+    for row in data['rows']:
+        data = {k:v for d in row['data'] for k,v in d.items()}
+        print(data)
+        w.writerow(data)
+
+

Output (dict comprehension result):

+
{'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'}
+{'A': '7', 'B': '8', 'C': '9', 'D': '10', 'E': '11', 'F': '12'}
+
+

out.csv:

+
A,B,C,D,E,F
+1,2,3,4,5,6
+7,8,9,10,11,12
+
",python +"I keep getting ""Ran out of input"" error in for() function to open and adjust pickle file

I was making stock data MACD calculator in python. The way of my approach is using 'for()' to access pickle datas in certain directory and calculate MACD values one by one. However, I got 'Ran out of input error' everytime. I checked my directory where pickle datas are stored and it was not empty. Funny thing is, If I just put numbers in i position without using 'for()', I could get data of the pickle file. Please help me to get free from this error.

+

Here's my code:

+

'''

+
import pickle
+import os
+import pathlib
+from pathlib import Path
+
+file_list = os.listdir('/home/sejahui/projects/pickle_data') 
+os.chdir('/home/sejahui/projects/pickle_data')
+
+for i in range(2):
+    odd = file_list[i]
+    with open(odd,'rb') as stock:
+        data = pickle.load(stock)
+    print(data)
+
+

'''

","

In this case, actually, you create a list with file_list = os.listdir('/home/sejahui/projects/pickle_data'). You do not need range to iterate.

+

The error is because sometimes there is only 1 file so it will be out of the index. The correct way is like this:

+
import pickle
+import os
+import pathlib
+from pathlib import Path
+
+file_list = os.listdir('/home/sejahui/projects/pickle_data') 
+os.chdir('/home/sejahui/projects/pickle_data')
+
+for str in file_list:
+   
+    with open(str,'rb') as stock:
+        data = pickle.load(stock)
+    print(data)
+
+

You can even add an if statement to the filter based on a regex or pattern

+
if str == "something":
+    with open(str,'rb') as stock:
+        data = pickle.load(stock)
+
",python +"Understanding .fork() with multiprocessing and logging

I am running a multiprocessing pool which logs to a logger that is configured by the main parent process. In one scenario, I have

+
def init():
+  global LOG
+  LOG = logging.getLogger(__name__)
+  LOG.setLevel(logging.DEBUG)
+
+def main():
+  LOG.info("test")
+
+if __name__ == '__main__':
+  fmt = "%(asctime)s %(name)s %(levelname)s: %(message)s"
+  logging.basicConfig(format=fmt, datefmt='%m/%d/%Y %I:%M:%S %p')
+  with multiprocessing.Pool(initializer = init) as pool:
+    pool.map(main, inputs)
+
+

Nothing gets printed to the stdout of my main calling thread. However, if I do this:

+
fmt = "%(asctime)s %(name)s %(levelname)s: %(message)s"
+logging.basicConfig(format=fmt, datefmt='%m/%d/%Y %I:%M:%S %p')
+
+def init():
+  global LOG
+  LOG = logging.getLogger(__name__)
+  LOG.setLevel(logging.DEBUG)
+
+def main():
+  LOG.info("test")
+
+if __name__ == '__main__':
+  with multiprocessing.Pool(initializer = init) as pool:
+    pool.map(main, inputs)
+
+

Then I do have proper logging. I don't see why these two things are different. When python forks into worker processes, the child process should be identical to the parent process so there shouldn't be a distinction between whether we called logging.basicConfig in the global namespace vs the main execution block. Can someone clarify?

","

Your code is perfectly fine for Linux-es (except the fact that it won't even run, haha)

+

However for Windows and OSX multiprocessing would spawn a fresh interpeter (see the docs) and would try to import the target module. This is the fork (pun intended) point where your __name__ == '__main__' guard makes a difference -- your logging setup is not done at all in the spawned workers!

",python +"Is there a way to know the width of a character in turtle graphics?

I'm currently making a typing game in turtle graphics. As the user types, an arrow above the sentence they are typing moves. This is used to show the user where they are in the sentence. However, I'm having trouble making the arrow stay above the letter that the user is actually on. It seems that the width of each letter isn't a constant measurement. Therefore, this will not work:t.forward(any number here) Is there any way to know the width of every single letter in a sentence? Or is there a certain font type that has a constant width no matter the character? I apologize if this does not make sense. Thanks

","

There are a couple of ways you can look at this:

+

To know width of character you just wrote

+

You can do this by always lifting the pen prior to writing a character, and asking the turtle to move with the character. If you record the turtle position before and after writing, then you can work out and return the width:

+
    import turtle
+    def write_character(t: turtle, char: str, font: str = "Arial") -> float:
+        """Write character and return width"""
+        pen_was_down = t.isdown()
+        if pen_was_down:
+            t.penup()
+        x_start, _ = t.position()
+        t.write(char, move=True, font=(font, 50, "normal"))
+        x_end, _ = t.position()
+        if pen_was_down:
+            t.pendown()
+        return x_end - x_start
+
+

This way you can then move your arrow forward by the width returned.

+

To use a fixed width character

+

As you've found out some fonts do not have a fixed with. Some do however - these are called monospaced. One commonly used example of this is Courier. The following snippet uses the previous method to examine the distribution of character widths for both Arial and Courier fonts:

+
print("Arial", Counter(
+    [write_character(turtle.Turtle(), c, "Arial") for c in string.ascii_lowercase]
+))
+print("Courier", Counter(
+    [write_character(turtle.Turtle(), c, "Courier") for c in string.ascii_lowercase]
+))
+
+

which outputs:

+
Arial Counter({27.0: 11, 24.0: 7, 11.0: 3, 13.0: 2, 41.0: 1, 16.0: 1, 36.0: 1})
+Courier Counter({30.0: 26})
+
+

Here we can see that Arial has 7 different character widths, whilst Courier has only a single character width.

",python +"Traversing a BST in an in-order fashion and storing the nodes in an array, but the output is not sorted?

I am traversing a Binary Tree in an in-order manner to determine if it is a Binary Search Tree. Here is my code:

+
class T:
+    def __init__(self, value, left=None, right=None):
+        self.value = value
+        self.left = left
+        self.right = right
+
+def is_bst(node):  
+    if not node:
+        return 
+
+    output = []
+    
+    is_bst(node.left)
+    output.append(node.value) 
+    is_bst(node.right)
+    print(output)
+
+

+

For the above example, the output = [1,3,2,9,7,5]

+

But this is clearly not correct! - I would usually debug but I am not familiar with running trees/binary trees as inputs. Any idea where my code is going wrong???

+
+

Updated code:

+
class T:
+    def __init__(self, value, left=None, right=None):
+        self.value = value
+        self.left = left
+        self.right = right
+
+        
+def inOrderTraversal(node,output): 
+        if not node: 
+            return None
+        
+        is_bst(node.left)
+        output.append(node.value) 
+        is_bst(node.right)
+        return 
+    
+def is_bst(node):  
+    
+    output = []
+    
+    inOrderTraversal(node,output)
+    
+    print(output)
+
+

For the same example, the output = [1,3,2,9,7,5] is still wrong

","

You create your output inside the routine, so it's always empty. Then you add the current node's value but you print it at the end of the routine. The result is postorder, not inorder - each node is printed after both its subtrees.

+

Apart from the code structure your function has wrong name - you actually don't want it to answer whether the tree is BST, you just want it to return the contents:

+
def dump_tree_inorder(node, output):  
+    if not node:
+        return 
+    
+    dump_tree_inorder(node.left, output)
+    output.append(node.value) 
+    dump_tree_inorder(node.right, output)
+
",python +"How to convert a NetworkX graph with complex weights to a matrix?

I have a graph whose weights are complex numbers. networkx has a few functions for converting the graph to a matrix of edge weights, however, it doesn't seem to work for complex numbers (though the reverse conversion works fine). It seems to require either int or float edge weights in order to convert them into a NumPy array/matrix.

+
Python 3.9.7 | packaged by conda-forge | (default, Sep 29 2021, 19:20:46) 
+Type 'copyright', 'credits' or 'license' for more information
+IPython 7.29.0 -- An enhanced Interactive Python. Type '?' for help.
+
+In [1]: import numpy as np
+
+In [2]: import networkx as nx
+
+In [3]: X = np.random.normal(size=(5,5)) + 1j*np.random.normal(size=(5,5))
+
+In [4]: X
+Out[4]: 
+array([[ 1.64351378-0.83369888j, -2.29785353-0.86089473j,
+...
+...   
+         0.50504368-0.67854997j, -0.29049118-0.48822688j,
+         0.22752377-1.38491981j]])
+
+In [5]: g = nx.DiGraph(X)
+
+In [6]: for i,j in g.edges(): print(f"{(i,j)}: {g[i][j]['weight']}")
+(0, 0): (1.6435137789271903-0.833698877745345j)
+...
+(4, 4): (0.2275237661137745-1.3849198099771993j)
+
+# So conversion from matrix to nx.DiGraph works just fine.
+# But the other way around gives an error.
+
+In [7]: Z = nx.to_numpy_array(g, dtype=np.complex128)
+---------------------------------------------------------------------------
+TypeError                                 Traceback (most recent call last)
+<ipython-input-7-b0b717e5ec8a> in <module>
+----> 1 Z = nx.to_numpy_array(g, dtype=np.complex128)
+
+~/miniconda3/envs/coupling/lib/python3.9/site-packages/networkx/convert_matrix.py in to_numpy_array(G, nodelist, dtype, order, multigraph_weight, weight, nonedge)
+   1242             for v, d in nbrdict.items():
+   1243                 try:
+-> 1244                     A[index[u], index[v]] = d.get(weight, 1)
+   1245                 except KeyError:
+   1246                     # This occurs when there are fewer desired nodes than
+
+TypeError: can't convert complex to float
+
+

I have looked at the documentation and all it seems to say is that this works only for a simple NumPy datatype and for compound types, one should use recarrays. I don't understand recarrays well and using np.to_numpy_recarray also yields an error.

+
In [8]: Z = nx.to_numpy_recarray(g, dtype=np.complex128)
+...
+TypeError: 'NoneType' object is not iterable
+
+

So the question is how to convert the graph into a matrix of edge weights correctly?

","

Below is a quick hack that could be useful until a fix is implemented:

+
import networkx as nx
+import numpy as np
+
+
+def to_numpy_complex(G):
+
+    # create an empty array
+    N_size = len(G.nodes())
+    E = np.empty(shape=(N_size, N_size), dtype=np.complex128)
+
+    for i, j, attr in G.edges(data=True):
+        E[i, j] = attr.get("weight")
+
+    return E
+
+
+X = np.random.normal(size=(5, 5)) + 1j * np.random.normal(size=(5, 5))
+
+g = nx.DiGraph(X)
+
+Y = to_numpy_complex(g)
+
+print(np.allclose(X, Y)) # True
+
",python +"Python Virtualenv not creating the new environment in the directory I am

First of all, to put in context:

+
    +
  • I have installed Python 3.9 which comes from Visual Studio 2019

    +
  • +
  • I have installed Python 3.8 from Microsoft Store which installs it in the path:

    +

    C:\Users\username\AppData\Local\Microsoft\WindowsApps

    +
  • +
+

Now I want to create a virtual environment for Python 3.8 so I can switch to it whenever I need. So I follow below steps (below commands are all executed from path C:\Users\username\AppData\Local):

+
    +
  1. Installing virtualenv:

    +

    py -3.8 -m pip install virtualenv

    +
  2. +
+

+
    +
  1. Creating new virtual environment for Python 3.8:

    +

    py -3.8 -m virtualenv _venv38.win32

    +
  2. +
+

+

And what's the surprise? Folder _venv38.win32 is not created within the directory I am which is C:\Users\username\AppData\Local

+

Instead _venv38.win32 is created in:

+
C:\Users\username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\Local\_venv38.win32
+
+

So why? I want it to be created in:

+
C:\Users\username\AppData\Local\_venv38.win32
+
+

which is the path from where I have executed the command (step 2)

","

use

+
py -3.8 -m venv _venv38.win32
+
+

this will create venv at cwd.

+

virtualenv has a custom "remote" location for virtual environments somewhere outside your project

",python +"Adding a list of strings to an existing key in a dict

I am trying to add strings to a list(adding new strings in each loop with .append()), after that adding the list to an existing key. The problem is after adding the new string to the list and than to a key in console get printed [...](how to get rid of this [...]) example:

+
x = {}
+y = ["going home"]
+x["key"].append(y)
+y.append("after lunch")
+x["key"].append(y)
+print(x)
+{'key' : ['going home', 'after lunch', [...]]}
+
+

Thank you for your time

","

Maybe the correct behavior is:

+
x = {}
+y = ["going home"]
+x["key"] = y
+y.append("after lunch")
+print(x)
+
+
{'key': ['going home', 'after lunch']}
+
",python +"Error in getting values from python dictionary

I've created a python dictionary

+
user = input('enter a letter: ')
+d = {'a': '1', 'b': '2', 'c':'3'}
+print(d.get(d))
+
+

I run that and enterned

+
a 
+
+

But I always get an error like this

+
er a letter: a
+Traceback (most recent call last):
+  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
+    start(fakepyfile,mainpyfile)
+  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
+    exec(open(mainpyfile).read(),  __main__.__dict__)
+  File "<string>", line 3, in <module>
+TypeError: unhashable type: 'dict'
+
+[Program finished]
+
+

Help me to slove!

","

You have to use the variable with user's input:

+
user = input('enter a letter: ')
+d = {'a': '1', 'b': '2', 'c':'3'}
+print(d.get(user))
+
",python +"Update Global Variables Input as Parameters Rather Than Returning Results From Function

Goal

+

I am trying to write a function where one or more of the input parameters is a global variable that is updated by the function, without having to return values from within the function. I am aware I could just return a tuple or two separate values from the function, but I think updating the global variables from within the function would be another interesting method if it is possible.

+

Reason to do this

+

Updating global variables with a function is easy when the global variable is known (ie. defined previously in the python script). However, I want to define the function in a separate .py file to easily use the function within other python scripts. Therefore, I need to be able to support different variable names to update.

+

While this is not at all necessary, I am just interested if this is even possible.

+

Example Pseudocode

+

I'm thinking something like this:

+
def math_function(input_val, squared_result, cubed_result):
+    squared_result = input_val**2 #update the var input as the squared_result parameter
+    cubed_result = input_val**3 #update the var input as the cubed_result parameter
+
+

where you would input a number for input_val and then global variables for squared_result and cubed_result that the function updates with the result. It would then theoretically work like:

+
#Declare global variables
+b = 0
+c = 0
+
+#then somewhere in the code, call the function
+math_function(2, b, c)
+
+#check the new values
+print(b) #Output: b = 4
+print(c) #Output: c = 8
+
+

This would allow me to use the function in different python scripts without having to worry about what order the results are returned in.

","

First: I am in no way advocating this.

+

You could use the globals builtin function to access a global variable by name:

+
def gtest(name,value):
+    globals()[name] = value
+
+gtest('new_global','new_value')
+print(new_global)
+
",python +"How to prefill django form Dynamically

I am trying to display a form in django and pre-filling it dynamically. +I want the user of my sample news gathering site to modify an entry.

+

I have my Manual Input form class

+
#forms.py
+class ManualInputForm(forms.Form):
+    source = forms.CharField(label="Source:", widget = forms.TextInput(attrs={'size': 97}))
+    topic  = forms.CharField(label="Topic:", widget = forms.TextInput(attrs={'size': 97}))
+    news   = forms.CharField(widget = forms.Textarea(attrs={"rows":5, "cols":100}))
+    link   = forms.CharField(label="Link (optional):", required = False, widget = forms.TextInput(attrs={'size': 97}))
+
+

In the HTML I am going manually because I would like to pre-fill all fields with data coming in from the related function in views.py.

+
#html file
+<form method="post" class="form-group">
+    {% csrf_token %}
+    <div class="input-group mb-3">
+        <div class="container">
+            {% for field in form  %}
+                <div class="fieldWrapper">
+                    {{ field.errors }}
+                    {{ field.label_tag }}
+                    <br>
+                    {{ field }}
+                </div>
+            {% endfor %}
+        </div>
+
+        <div class="input-group">
+            <p> </p>
+            <button type="submit" class="btn btn-success" name="Submit">Save</button>
+        </div>
+    </div>
+</form>
+
+

How do I do it? It's driving me crazy o.O +I would like to keep using django's forms because of its integrated error manager (not all fields are required but some are and I'd like for django to keep managing it).

+

Thank your for your suggestions!

+

EDIT: +as requested I'll post the views.py related function:

+
#views.py
+def editnews(response, id):
+    form = ManualInputForm(response.POST or None)
+
+    #tableToView is a dataframe retrieved by querying an external DB
+    #data cannot be stored in django's buit in because of reasons ;-)
+
+    #checking the dataframe is correct and it is:
+    #IT IS MADE OF A SINGLE LINE
+    
+    print(tableToView)
+
+    #THIS IS PROBABLY NOT THE WAY TO DO IT
+    form.source = tableToView.loc[0, 'Source']
+    form.topic  = tableToView.loc[0, 'Topic']
+    form.news   = tableToView.loc[0, 'News']
+    form.link   = tableToView.loc[0, 'Link']
+
+    return render(response, 'manual/editnews.html', {"form":form})
+
+

In the image the text should be pre-filled.

+

","

Try something like that:

+
def editnews(response, id):
+    data = {k.lower(): v for k, v in tableToView.loc[0].to_dict().items()}
+    form = ManualInputForm(response.POST or None, initial=data)
+    return render(response, 'manual/editnews.html', {'form': form})
+
",python +"Matplotlib background matches vscode theme on dark mode and can't see axis

I just got a new PC and downloaded visual studio code. I'm trying to run the exact same plots as the code I had on my other PC (just plt.plot(losses)) but now matplotlib seems to have a dark background instead of white:

+

+

I found this and this that had opposite problems. +To clarify, I'm asking how to change the matplotlib background plots to white (note that in my other machine I didn't have to hard code any matplotlib background information so I think it's a visual studio problem, but couldn't figure it out)

","

Difficult to be sure since I cannot reproduce your problem.

+

Two things to try (both presume that you import matplotlib using import matplotlib.pyplot as plt):

+
    +
  1. if you use plt.figure, add facecolor='white' parameter. Or try to run fig.set_facecolor('white') (fig here is the variable that stored the figure which facecolor you are changing. If you don't have any, use plt.gcf().set_facecolor('white') once the figure is created; gcf() returns current figure, see this doc).
  2. +
  3. Try to change plt.style.context as in this matplotlib example.
  4. +
",python +"RuntimeError: Found dtype Double but expected Float - PyTorch

I am new to pytorch and I am working on DQN for a timeseries using Reinforcement Learning and I needed to have a complex observation of timeseries and some sensor readings, so I merged two neural networks and I am not sure if that's what is ruining my loss.backward or something else. +I know there is multiple questions with the same title but none worked for me, maybe I am missing something.
+First of all, this is my network:

+
class DQN(nn.Module):
+  def __init__(self, list_shape, score_shape, n_actions):
+    super(DQN, self).__init__()
+
+    self.FeatureList =  nn.Sequential(
+            nn.Conv1d(list_shape[1], 32, kernel_size=8, stride=4),
+            nn.ReLU(),
+            nn.Conv1d(32, 64, kernel_size=4, stride=2),
+            nn.ReLU(),
+            nn.Conv1d(64, 64, kernel_size=3, stride=1),
+            nn.ReLU(),
+            nn.Flatten()
+        )
+    
+    self.FeatureScore = nn.Sequential(
+            nn.Linear(score_shape[1], 512),
+            nn.ReLU(),
+            nn.Linear(512, 128)
+        )
+    
+    t_list_test = torch.zeros(list_shape)
+    t_score_test = torch.zeros(score_shape)
+    merge_shape = self.FeatureList(t_list_test).shape[1] + self.FeatureScore(t_score_test).shape[1]
+    
+    self.FinalNN =  nn.Sequential(
+            nn.Linear(merge_shape, 512),
+            nn.ReLU(),
+            nn.Linear(512, 128),
+            nn.ReLU(),
+            nn.Linear(128, n_actions),
+    )
+    
+  def forward(self, list, score):
+    listOut = self.FeatureList(list)
+    scoreOut = self.FeatureScore(score)
+    MergedTensor = torch.cat((listOut,scoreOut),1)
+    return self.FinalNN(MergedTensor)
+
+

I have a function called calc_loss, and at its end it return the MSE loss as below

+
  print(state_action_values.dtype)
+  print(expected_state_action_values.dtype) 
+  return nn.MSELoss()(state_action_values, expected_state_action_values)
+
+

and the print shows float32 and float64 respectively.
+I get the error when I run the loss.backward() as below

+
LEARNING_RATE = 0.01
+optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE)
+
+for i in range(50):
+  optimizer.zero_grad()
+  loss_v = calc_loss(sample(obs, 500, 200, 64), net, tgt_net)
+  print(loss_v.dtype)
+  print(loss_v)
+  loss_v.backward()
+  optimizer.step()
+
+

and the print output is as below:
+torch.float64
+tensor(1887.4831, dtype=torch.float64, grad_fn=)

+

Update 1:
+I tried using a simpler model, yet the same issue, when I tried to cast the inputs to Float, I got an error:

+
RuntimeError: expected scalar type Double but found Float
+
+

What makes the model expects double ?

+

Update 2:
+I tried to add the below line on top after the torch import but same issue of RuntimeError: Found dtype Double but expected Float

+
>>> torch.set_default_tensor_type(torch.FloatTensor)
+
+

But when I used the DoubleTensor I got: +RuntimeError: Input type (torch.FloatTensor) and weight type (torch.DoubleTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor

","

The issue wasn't in the input to the network but the criterion of the MSELoss, so it worked fine after casting the criterion to float as below

+
return nn.MSELoss()(state_action_values.float(), expected_state_action_values.float())
+
+

I decided to leave the answer for beginners like me who might be stuck and didn't expect to check the datatype of the loss criterion

",python +"Python random module: How can I generate a random number which includes certain digits?

I am trying to generate a random number in Python, but I need it to include certain digits.

+

Let's say the range I want for it is between 100000 and 999999, so I want it to be in that range but also include digits like 1, 4, and 5.

+

Is there a way to do this?

","

you can build the number digit by digit

+
>>> import random
+>>> def fun(required=(),size=6):
+        result = list(required)
+        n = size-len(result)
+        result.extend( random.randint(0,10) for _ in range(n)) # fill in the remaining digits
+        random.shuffle(result) 
+        assert any(result) #make sure that there is at least one non zero digit
+        while not result[0]: #make sure that the first digit is non zero so the resulting number be of the required size
+            random.shuffle(result)
+        return int("".join(map(str,result)))
+
+>>> fun([1,4,5])
+471505
+>>> fun([1,4,5])
+457310
+>>> fun([1,4,5])
+912457
+>>> fun([1,4,5])
+542961
+>>> fun([1,4,5])
+145079
+>>> 
+
",python +"Column names are not recognized? How to set the column names?

I have a dataset for which I am not able to call the columns. In the screen shoot below, I have marked in yellow what I need to be recognized as column (Vale On, Petroleo etc.) and the Date column, which I need to recognize as date since I am working with time series data.

+

I have tried to reset index and some solutions related but nothing worked. I am new to Python, so I am sorry if it is too obvious.

+

","
# use first row as column names
+df.columns = df.iloc[0]
+
+# and then drop it
+df = df.iloc[1:]
+
+# convert first col to date
+# if it doesnt work, try passing format=... refer https://strftime.org/
+# also https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html
+df['Date'] = pd.to_datetime(df['Date'])
+
+

A debugging hint if parsing the date keeps failing is to check if your date strings are consistent, perhaps like so: df['Date'].str.len().value_counts(). That should hopefully return only one length. If that returns multiple rows, that means you have inconsistent and anomalous data which you'll have to clean.

",python +"how made cross-validation with python?

Hi i made a neural network and i need to do a cross validation. +I don't know how made that, specifically how train or made that.

+

if someone knows made that please write or give me some indications.

+

here is my code:

+
###Division Train / Test
+X = df.drop('Peso secado',axis=1)  #Variables de entrada, menos la variable de salida
+y = df['Peso secado']              #Variable de salida
+
+from sklearn.model_selection import train_test_split
+X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=101)
+
+###
+
+from sklearn.preprocessing import MinMaxScaler
+scaler = MinMaxScaler()
+X_train= scaler.fit_transform(X_train)
+X_train
+X_test = scaler.transform(X_test)
+X_test
+
+
+
+###Creacion del modelo###
+from tensorflow.keras.models import Sequential
+from tensorflow.keras.layers import Dense, Activation
+from tensorflow.keras.optimizers import Adam
+import tensorflow as tf
+
+model = Sequential()
+num_neuronas = 50
+model.add(tf.keras.layers.Dense(units=6, activation='sigmoid', input_shape=(6, )))
+model.add(Dense(num_neuronas,activation='relu'))
+model.add(tf.keras.layers.Dense(units=1, activation='linear')) 
+
+#Buscar mejor funcion de activacion para capa de salida sigmoid? o linear?
+model.summary()
+model.compile(optimizer='adam',loss='mse')
+
+###Entrenamiento###
+model.fit(x = X_train, y = y_train.values,
+          validation_data=(X_test,y_test.values), batch_size=10, epochs=1000) 
+
+losses = pd.DataFrame(model.history.history)  
+losses
+losses.plot()
+   
+###Evaluacion###
+from sklearn.metrics import mean_squared_error,mean_absolute_error,explained_variance_score,mean_absolute_percentage_error
+X_test
+predictions = model.predict(X_test)
+mean_absolute_error(y_test,predictions)
+mean_absolute_percentage_error(y_test,predictions)
+
+mean_squared_error(y_test,predictions)
+explained_variance_score(y_test,predictions)  
+
+mean_absolute_error(y_test,predictions)/df['Peso secado'].mean() 
+mean_absolute_error(y_test,predictions)/df['Peso secado'].median()
+
+

Some recomendation for training or validation would be helpful

","

My first observation is that the code is pretty ugly and unstructured. You should import the modules on the top part of your code

+

For performing cross validation first import the module from sklearn (and all other modules that you need)

+
from sklearn.model_selection import StratifiedKFold
+
+

I'd put the model definition in a separate function as such:

+
def get_model():
+  model = Sequential()
+  model.add(Dense(4, input_dim=8, activation='relu'))
+  model.add(Dense(1, activation='sigmoid'))
+  model.compile(loss='binary_crossentropy', optimizer='adam')
+  return model
+
+

Define your variables and if you are working with tensorflow / Keras, do something like this:

+
BATCH_SIZE = 64  #  128
+EPOCHS = 100
+
+k = 10
+# Use stratified k-fold if the data is imbalanced
+kf = StratifiedKFold(n_splits=k, shuffle=False, random_state=None)
+
+# here comes the Cross validation
+fold_index = 1
+for train_index, test_index in kf.split(X, y):
+            X_train = X[train_index]
+            y_train = y[train_index]
+
+            X_test = X[test_index]
+            y_test = y[test_index]
+
+            # fit the model on the training set
+            model = get_model()
+
+            model.fit(
+                X_train,
+                y_train,
+                batch_size=BATCH_SIZE,
+                epochs=EPOCHS,
+                verbose=0,
+                validation_data=(X_test, y_test),
+            )
+
+            # predict values
+            # pred_values = model.predict(X_test)
+            pred_values_prob = np.array(model(X_test))
+
+

Note: when working with tensorflow you need to define a new model every time in the loop. This is not the case with sklearn as sklearn starts with fresh initialized weights when called. Here you need to do that separately.

",python +"boto3 gives error when trying to stop an AWS EC2 instance using Ansible

I am trying to create an ansible playbook to install docker & docker-compose on the host server, stop and start the AWS EC2 instance and then restart docker.

+

Everything goes well until I try to stop the instance, then this happens:

+
TASK [docker_setup : Gather facts] ******************************************************************************************************************************************
+[DEPRECATION WARNING]: The 'ec2_instance_facts' module has been renamed to 'ec2_instance_info'. This feature will be removed in version 2.13. Deprecation warnings can be 
+disabled by setting deprecation_warnings=False in ansible.cfg.
+fatal: [172.31.25.50]: FAILED! => {"changed": false, "msg": "boto3 required for this module"} 
+
+

Those steps to stop the instance look like this on the playbook:

+
- name: Install boto3 and botocore with pip3 module for Gather facts
+  pip:
+    name:
+      - boto3
+      - botocore
+    executable: pip-3.7
+
+- name: Gather facts
+  action: ec2_instance_facts
+
+- name: Stop myserver instance
+  local_action:
+    module: ec2
+    region: "{{region}}"
+    instance_ids: "{{ansible_ec2_instance_id}}"
+    state: stopped
+
+

The reason I installed boto3 is because it was complaining for not being installed but even when installed it still gives an error. I also read around the Internet that I should add ansible_python_interpreter=/usr/bin/python on the host file next to each host and so I did. But it didn`t work. It looks like this:

+
[webservers]
+172.31.25.50 ansible_python_interpreter=/usr/bin/python
+
+
+

Any ideas? Thank you!

","

What I did to solve this:

+

Instead of using the ansible_python_interpreter in the hosts file, I learned that you can actually add it to a specific action of the task via vars:

+
- name: Stop instance(s)
+  vars:
+    ansible_python_interpreter: /usr/bin/python3
+  ec2_instance:
+    aws_access_key: xxxxx
+    aws_secret_key: xxxxx
+    region: "{{region}}"
+    instance_ids: "{{ansible_ec2_instance_id}}"
+    state: stopped
+
+

Also used python3 instead of python on the ansible_python_interpreter. If I used ansible_python_interpreter: /usr/bin/python3 on the hosts file as I was doing, it would give another error because the default interpreter for the whole task was using it, but this way you can direct it to when you want to use it.

",python +"Which line has an error in this for loop?

This question is from a python course on freeCodeCamp.com

+
smallest = None
+print("Before:", smallest)
+for itervar in [3, 41, 12, 9, 74, 15]:
+    if smallest is None or itervar < smallest:
+        smallest = itervar
+        break
+    print("Loop:", itervar, smallest)
+print("Smallest:", smallest)
+
+

There is a mistake in one of these lines. I thought it's the fourth line because the variable 'smallest' is already written as None in the first line but it's not the right answer. Also, what type of value is None and what is it for?

","

You don't need a break on 5th line. It interrupts the loop which is not needed there.

+

Without it everything works okay.

+
+

Also, what type of value is None and what is it for?

+
+

The None keyword is used to define a null value, or no value at all.

",python +"pivot in pandas: how to edit the columns and rows

i face a problem with pivot in pandas , +the total_profit and numberofgoodsold columns are located above company row. +i need the company row to be at the top.

+

in each company the total_profit and the goodsold columns should came under.

+

this is my code:

+
data = {'company': ['AMC', 'ER','CRR' , 'TYU'], 'Reg-ID': ['1222','2334','3444', '4566'], 'Total_provit': ['123300','12233', '3444444', '412222'], 'numberofgoodsold':['44','23','67','34']}
+
+d = pd.DataFrame(data)
+
+
+

+d.pivot(index = 'Reg-ID', columns = 'company')
+
+
","

Update, ok then I think this is what you need:

+
data = {'company': ['AMC', 'ER','CRR' , 'TYU'], 'Reg-ID': ['1222','2334','3444', '4566'], 'Total_provit': ['123300','12233', '3444444', '412222'], 'numberofgoodsold':['44','23','67','34']}
+
+d = pd.DataFrame(data)
+
+d2 = d.pivot(index = 'Reg-ID', columns = 'company')
+
+d2.columns = d2.columns.swaplevel(0, 1)
+d2.sort_index(axis=1, level=0, inplace=True)
+
+d2
+
+

Output:

+

",python +"How to avoid the QueuePool limit error using Flask-SQLAlchemy?

I'm developing a webapp using Flask-SQLAlchemy and a Postgre DB, then I have this dropdown list in my webpage which is populated from a select to the DB, after selecting different values for a couple of times I get the "sqlalchemy.exc.TimeoutError:".

+

My package's versions are:

+
Flask-SQLAlchemy==2.5.1
+psycopg2-binary==2.8.6
+SQLAlchemy==1.4.15
+
+

My parameters for the DB connection are set as:

+
app.config['SQLALCHEMY_POOL_SIZE'] = 20
+app.config['SQLALCHEMY_MAX_OVERFLOW'] = 20
+app.config['SQLALCHEMY_POOL_TIMEOUT'] = 5
+app.config['SQLALCHEMY_POOL_RECYCLE'] = 10
+
+

The error I'm getting is:

+
sqlalchemy.exc.TimeoutError: QueuePool limit of size 20 overflow 20 reached, connection timed out, timeout 5.00 (Background on this error at: https://sqlalche.me/e/14/3o7r)
+
+

After changing the value of the 'SQLALCHEMY_MAX_OVERFLOW' from 20 to 100 I get the following error after some value changes on the dropdown list.

+
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  sorry, too many clients already
+
+

Every time a new value is selected from the dropdown list, four queries are triggered to the database and they are used to populate four corresponding tables in my HTML with the results from that query.

+

I have a 'db.session.commit()' statement after every single query to the DB, but even though I have it, I get this error after a few value changes to my dropdown list.

+

I know that I should be looking to correctly manage my connection sessions, but I'm strugling with this. I thought about setting the pool timeout to 5s, instead of the default 30s in hopes that the session would be closed and returned to the pool in a faster way, but it seems it didn't help.

+

As a suggestion from @snakecharmerb, I checked the output of:

+
select * from pg_stat_activity;
+
+

I ran the webapp for 10 different values before it showed me an error, which means all the 20+20 sessions where used and are left in an 'idle in transaction' state.

+

Do anybody have any idea suggestion on what should I change or look for?

","

I found a solution to the issue I was facing, in another post from StackOverFlow.

+

When you assign your flask app to your db variable, on top of indicating which Flask app it should use, you can also pass on session options, as below:

+
from flask_sqlalchemy import SQLAlchemy
+db = SQLAlchemy(app, session_options={'autocommit': True})
+
+

The usage of 'autocommit' solved my issue.

+

Now, as suggested, I'm using:

+
app.config['SQLALCHEMY_POOL_SIZE'] = 1
+app.config['SQLALCHEMY_MAX_OVERFLOW'] = 0
+
+

Now everything is working as it should.

+

The original post which helped me is: Autocommit in Flask-SQLAlchemy

+

@snakecharmerb, @jorzel, @J_H -> Thanks for the help!

",python +"Returning list of different results that are created recursively in Python

Lately I've been working with some recursive problems in Python where I have to generate a list of possible configurations (i.e list of permutations of a given string, list of substrings, etc..) using recursion. I'm having a very hard time in finding the best practice and also in understanding how to manage this sort of variable in recursion.

+

I'll give the example of the generate binary trees problem. I more-or-less know what I have to implement in the recursion:

+
    +
  1. If n=1, return just one node.
  2. +
  3. If n=3, return the only possible binary tree.
  4. +
  5. For n>3, crate one node and then explore the possibilities: left node is childless, right node is childless, neither node is childless. Explore these possibilites recursively.
  6. +
+

Now the thing I'm having the most trouble visualising is how exactly I am going to arrive to the list of trees. Currently the practice I do is pass along a list in the function call (as an argument) and the function would return this list, but then the problem is in case 3 when calling the recursive function to explore the possibilites for the nodes it would be returning a list and not appending nodes to a tree that I am building. When I picture the recursion tree in my head I imagine a "tree" variable that is unique to each of the tree leaves, and these trees are added to a list which is returned by the "root" (i.e first) call. But I don't know if that is possible. I thought of a global list and the recursive function not returning anything (just appending to it) but the problem I believe is that at each call the function would receive a copy of the variable.

+

How can I deal with generating combinations and returning lists of configurations in these cases in recursion? While I gave an example, the more general the answer the better. I would also like to know if there is a "best practice" when it comes to that.

","
+

Currently the practice I do is pass along a list in the function call (as an argument) and the function would return this list

+
+

This is not the purest way to attack a recursive problem. It would be better if you can make the recursive function such that it solves the sub problem without an extra parameter variable that it must use. So the recursive function should just return a result as if it was the only call that was ever made (by the testing framework). So in the example, that recursive call should return a list with trees.

+

Alternatively the recursive function could be a sub-function that doesn't return a list, but yields the individual values (in this case: trees). The caller can then decide whether to pack that into a list or not. This is more pythonic.

+

As to the example problem, it is also important to identify some invariants. For instance, it is clear that there are no solutions when n is even. As to recursive aspect: once you have decided to create a root, then both its left and right sided subtree will have an odd number of nodes. Of course, this is an observation that is specific to this problem, but it is important to look for such problem properties.

+

Finally, it is equally important to see if the same sub problems can reoccur multiple times. This surely is the case in the example problem: for instance, the left subtree may sometimes have the same number of nodes as the right subtree. In such cases memoization will improve efficiency (dynamic programming).

+

When the recursive function returns a list, the caller can then iterate that list to retrieve its elements (trees in the example), and use them to build an extended result that satisfies the caller's task. In the example case that means that the tree taken from the recursively retrieved list, is appended as a child to a new root. Then this new tree is appended to a new list (not related to the one returned from the recursive call). This new list will in many cases be longer, although this depends on the type of problem.

+

To further illustrate the way to tackle these problems, here is a solution for the example problem: one which uses the main function for the recursive calls, and using memoization:

+
class Solution:
+    memo = { 1: [TreeNode()] }
+    
+    def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
+        # If we didn't solve this problem before...
+        if n not in self.memo:
+            # Create a list for storing the results (the trees)
+            results = []
+            # Before creating any root node, 
+            #    decide the size of the left subtree.
+            #    It must be odd
+            for num_left in range(1, n, 2):
+                # Make the recursive call to get all shapes of the
+                # left subtree
+                left_shapes = self.allPossibleFBT(num_left)
+                # The remainder of the nodes must be in the right subtree
+                num_right = n - 1 - num_left  # The root also counts as 1
+                right_shapes = self.allPossibleFBT(num_right)
+                # Now iterate the results we got from recursion and 
+                #    combine them in all possible ways to create new trees
+                for left in left_shapes:
+                    for right in right_shapes:
+                        # We have a combination. Now create a new tree from it
+                        # by putting a root node on top of the two subtrees:
+                        tree = TreeNode(0, left, right)
+                        # Append this possible shape to our results
+                        results.append(tree)
+            # All done. Save this for later re-use
+            self.memo[n] = results
+        return self.memo[n]
+
+

This code can be made more compact using list comprehension, but it may make the code less readable.

",python +"why can't I send messages from flask html to flask python?

I have been working on a program in flask that allows you to search a database. I have not coded the actual finding stuff in the data base or anything but I don't need that right now, and the database does not effect anything right now. I have not been able to get past how to get what the user types in the form to the python program. It runs with no errors but when I check what I received I get None. Is there something I'm doing wrong? This is my code, it is very messy and just one file.

+

main.py

+
from flask import Flask, render_template
+from flask import request
+import pdfkit, time
+
+
+
+
+def go(letters):
+  data = open('data.txt','r')
+  return letters
+  
+   
+app = Flask(__name__)
+       
+@app.route("/path/", methods=['GET','POST'])
+def search():
+  time.sleep(1)
+  data=request.get_data()
+  print(data)
+  return go(data)
+
+@app.route('/')
+def index():
+  
+  return render_template('index.html')
+
+if __name__ == "__main__":
+    from waitress import serve
+    serve(app, host="0.0.0.0", port=8080)
+    app.run(debug=True)
+
+

templates/index.html

+
<!Doctype html!>
+
+<html land=en>
+<h1>Welcome!</h1><br>
+<p>Type to search the database.</p>
+<br><form name='this' onsubmit='letsgo()' class='text' action='/path/' method='post'><input id='hey' type='text'> <input type='submit' value='search'></form>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
+<script>
+var test = document.getElementById('hey').value;
+  const xhr = new XMLHttpRequest();
+function letsgo() { 
+  
+  const data = document.getElementById("hey").value
+  alert(data)
+$.ajax({
+  type : 'POST',
+  url : "{{'https://file-encrypter.ashwinchera.repl.co/path/'}}",
+  dataType: 'data',
+  datas : {'data':data}
+});
+            
+
+};      
+</script>
+
+

also I am working with a friend, so I don't know what some of this stuff is here for. Can someone tell me how I can send this data? I have been trying things from other questions, but they don't work. +Thank you in advance!

","

There are multiple issues here. As mentioned in the comments, I recommend working slowly and breaking the problem down into small pieces. Check that each piece works before rushing ahead and accumulating many errors that are hard to unravel.

+

Most of the problems are on the front-end, so you'll want to use the browser console to inspect errors. You can also use an HTML validator tool to make sure your HTML makes sense and catches typos like land=en.

+

Since it sounds like you want to POST without a page refresh and you're using jQuery, many properties on your form are unnecessary:

+
onsubmit='letsgo()' action='/path/' method='post'
+
+

can all be removed. While you're at it, remove any unused noise like:

+
var test = document.getElementById('hey').value;
+  const xhr = new XMLHttpRequest();
+
+

and unnecessary ids and classes. These are just adding to the confusion. When things don't make sense and aren't working, try stripping out code rather than adding it.

+

"{{'https://file-encrypter.ashwinchera.repl.co/path/'}}" should just be /path so that it'll work on any domain such as a localhost. If you're working cross-origin, that's another story, but I don't think you are.

+

In the $.ajax call, datas is a typo. That should be data.

+

const data = document.getElementById("hey").value isn't necessary. If you're bothering to import jQuery, you might as well use it all the way: $("#hey").val(). #hey and letsgo are unclear names that don't make it any easier to debug the app.

+

Use event.preventDefault() to prevent the form submission.

+

On the backend, once again, remove any cruft and noise like the file read and import pdfkit, time. It seems strange to add GET to the list of accepted verbs for the /path route (which is too generically-named, as is go).

+

Since you're using form data, request.get_data() can be request.form.get("data") where "data" is the key you want to retrieve from the parsed form.

+

Here's a minimal AJAX example to get you moving:

+

templates/index.html:

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
+</head>
+<body>
+  <h1>Welcome!</h1>
+  <p>Type to search the database.</p>
+  <form>
+    <input id="search-term">
+    <input type="submit" value="search">
+  </form>
+  <div id="result"></div>
+
+<script>
+$("form").submit(function (event) {
+  event.preventDefault();
+  var data = $("#search-term").val();
+  $.ajax({
+    type: "POST",
+    url: "search",
+    data: {data},
+    success: data => $("#result").text(data),
+    error: res => console.error(res),
+  });
+});      
+</script>
+</body>
+</html>
+
+

app.py:

+
from flask import Flask, render_template, request
+
+app = Flask(__name__)
+
+@app.route("/search", methods=["POST"])
+def search():
+    data = request.form.get("data")
+    print(data)
+    return data
+
+@app.route("/")
+def index():
+    return render_template("index.html")
+
+if __name__ == "__main__":
+    app.run(host="127.0.0.1", port=8080, debug=True)
+
+
+

If you want to submit and render a new page, you don't need jQuery:

+

templates/index.html:

+
<!DOCTYPE html>
+<html lang="en">
+<body>
+  <h1>Welcome!</h1>
+  <p>Type to search the database.</p>
+  <form action="/" method="post">
+    <input name="search-term">
+    <input type="submit" value="search">
+  </form>
+  <div>{{search_term}}</div>
+</body>
+</html>
+
+

app.py:

+
from flask import Flask, render_template, request
+
+app = Flask(__name__)
+
+@app.route("/", methods=["GET", "POST"])
+def index():
+    search_term = request.form.get("search-term", "")
+    return render_template("index.html", search_term=search_term) 
+
+if __name__ == "__main__":
+    app.run(host="127.0.0.1", port=8080, debug=True)
+
+

Or point to another page:

+

templates/index.html:

+
<!DOCTYPE html>
+<html lang="en">
+<body>
+  <h1>Welcome!</h1>
+  <p>Type to search the database.</p>
+  <form action="/search" method="post">
+    <input name="search-term">
+    <input type="submit" value="search">
+  </form>
+</body>
+</html>
+
+

templates/search.html:

+
<!DOCTYPE html>
+<html lang="en">
+<body>
+  <p>You searched: '{{search_term}}'</p>
+</body>
+</html>
+
+

app.py:

+
from flask import Flask, render_template, request
+
+app = Flask(__name__)
+
+@app.route("/search", methods=["POST"])
+def search():
+    search_term = request.form.get("search-term", "")
+    return render_template("search.html", search_term=search_term) 
+
+@app.route("/")
+def index():
+    return render_template("index.html")
+
+if __name__ == "__main__":
+    app.run(host="127.0.0.1", port=8080, debug=True)
+
",python +"Ptython - how to write '\\n' to a file

I need to write \\n into a file. +The problem I have is I get only \n

+
def read_file(input_path):
+    f = open(input_path, "r")
+    read_lines = f.readlines()
+    read_lines_length = len(read_lines)
+    r = 0 
+    while r < read_lines_length:
+        read_lines[r]= read_lines[r].replace('\n','')
+        r+=1
+    f.close()
+
+    for element in range(len(read_lines)):
+        read_lines[element].replace('\n', '\\n').replace('\r', '\\r')
+
+    return read_lines
+
+

With this I am able to store \\n in a List but when I use f.write() it only prints \n. Normally would you just make: prin(\\\\n) to get \\n but when I make .replace("\n", "\\\\n") it stays \\n in the List

+
['print("Enter: \'stop\' --> exit function.\\n"']
+
+

The Output:

+
read = read_file(input_path)
+for element in range(len(read)):
+    print(read[element])
+
+---> print("Enter: 'stop' --> exit function.\n"
+
+

What I want to accomplish is a file which will create automatic from my normal Python file an encrypted python file.

+

Here some files to work with:

+

Core.py

+

packager.py

+

what I want to have

+

And here the folder Structure: imgur

","

I think your problem is just the different view of text in the lists by print function. In fact the \n in list are really \n not \\n. Please pay attention to the following example. The \n is used between Hello and World, after print(a), two words appear in different lines. In b variable a is inserted in the list ([]); now print(b) show \n.

+
a = "Hello\nWorld"
+print(a)
+b = [a]
+print(b)
+print(b[0])
+
+

The output:

+
Hello
+World
+['Hello\nWorld']
+Hello
+World
+
+

Edit based on question changes:

+

Changing read_file as the following code can help:

+
def read_file(input_path):
+    f = open(input_path, "r")
+    read_lines = f.readlines()
+    read_lines = [r.replace("\\n",'\\\\n').replace('\n','') for r in read_lines] 
+    f.close()
+    return read_lines
+
",python +"Django view to download a file from server

I have a views.py that:

+
    +
  • creates some .xlsx files
  • +
  • select the correct .zip and place the file inside
  • +
+

After that, I want this .zip to be automatically downloaded. I did some research and tested some codes but none worked.

+

I created a "temp" folder in the root of the app where the created files are stored.

+

simplified view.py

+
def generate_ws(request,cource,ca_id):
+    ca = get_object_or_404(CreditAnalysis,pk=ca_id)
+    ca_owners = CAOwner.objects.filter(ca_operation=ca)
+    mo_farms = MOFarm.objects.filter(ca_operation=ca)
+    misses = []
+
+    generate_owner_mo(ca_owner,misses,city)
+    zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip'
+    zf = zipfile.ZipFile(zip_name,'w')
+    zf.close()
+
+    generate_farm_mo(mo_farm,misses,city)
+    generate_production_mo(ca,misses,city,production_city,pks)
+
+    files = glob.glob('temp/*.xlsx')       #SELECT FILES AND PUT IN .ZIP
+    for file in files:
+        file_key = file.split('.')[0]
+        file_key=file_key.split(' - ')
+        for ca_owner in ca_owners:
+            zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip'
+            if str(ca_owner.owner) in file_key:
+                zf = zipfile.ZipFile(zip_name,'a')
+                new_file_name = file[5:]
+                zf.write(file,new_file_name)
+                zf.close()                
+                break
+     files = glob.glob('temp/*.zip')             # GET .ZIP FILES
+     for file in files:
+         download_mo(request,file)               # CREATE A DOWNLOAD FOR EACH .ZIP FILE
+
+    misses = list(set(misses))
+
+    return render(request,'generate_mo.html',{'misses':misses,})
+
+

download_mo

+
def download_mo(request,file):
+    path_to_file = os.path.realpath(file)
+    with open(path_to_file,'rb') as fh:
+        response = HttpResponse(fh.read())
+        file_name = file[5:]                       #WITHDRAW "temp/"
+        response['Content-Disposition'] = 'inline; filename=' + file_name
+        return response
+
+

Everything works correctly except the download which never starts

","

In order to download a file, you need to return a FileResponse to the user. However, calling an external function that returns a FileResponse won't work because you're not actually returning the FileResponse to the user, in your case the user only receives the render(request, 'generate_mo.html', {'misses':misses,}) so that won't download the files.

+

You can't download several files one after the others, so I suggest putting them all in a .zip or .tar file so that you can download them as only one file, and only need to return one FileResponse.

+

As you also need to render your template, what you can do is redirect to your download_mo view on template loading so that your file is downloaded while your template is rendered.

+

Now, for your download_mo view, just replace your HttpResponse with a FileResponse :

+
from django.http import FileResponse
+def download_mo(request,file):
+    path_to_file = os.path.realpath(file)
+    response = FileResponse(open(path_to_file, 'rb'))
+    file_name = file[5:]
+    response['Content-Disposition'] = 'inline; filename=' + file_name
+    return response
+
",python +"How can I change the source of background image in Kivy?

Here is how i set the background:

+
Builder.load_string('''
+<AppInterface>:
+    orientation: 'vertical'
+    canvas.before:
+        Rectangle:
+            id: backg # im not sure if i can set an id for this
+            pos: self.pos
+            size: self.size
+            source: 'assets/background.jpg'
+#rest of the code goes here
+''')
+
+

and then later i want to change the source of the image, when the user presses the button, but I don't know how to do that. I tried a few stuff like

+
self.ids.backg.source = 'assets/background2.jpg'
+
+

but this didn't work. I am using FloatLayout. Any idea how can I do this?

","

Referancing by StringProperty()

+

.py side, in AppInterface class:

+
background_source = StringProperty('assets/background.jpg')
+
+

.kv side:

+
source: root.background_source
+
+

Now, if you want to change that image, just set new path like: (in .py side)

+
background_source = 'assets/background2.jpg'
+
",python +"Concatenate different values that belong to the same group

I have a data frame like this

+

+import pandas as pd
+
+
+data = [
+    ['ACOT', '00001', '', '', 1.5, 20, 30, 'AA'],
+    ['ACOT', '00002', '', '', 1.7, 20, 33,'BB'],
+    ['ACOT', '00003', '','NA_0001' ,1.4, 20, 40,'AA'],
+    ['PAN', '000090', 'canonical', '', 0.5, 10, 30,'DD'],
+    ['PAN', '000091', '', '', 0.4, 10, 30,'CC'],
+    ['TOM', '000080', 'canonical', '', 0.4, 10, 15,'EE'],
+    ['TOM', '000040', '', '', 1.7, 10, 300,'EE']
+]
+
+df = pd.DataFrame(data, columns=[
+    'Gene_name', 'Transcript_ID', 'canonical', 'mane', 'metrics','start','end', 'Example_extra_col'])
+
+
+
+Gene_name   Transcript_ID   canonical   mane    metrics start   end Example_extra_col  
+0   ACOT    00001                               1.5 20  30   AA
+1   ACOT    00002                       NA_0001 1.7 20  33   BB
+2   ACOT    00003                               1.4 20  40   AA
+3   PAN     000090          canonical   NA_00090    0.5 10  30   DD
+4   PAN     000091                              0.4 10  30   CC
+5   TOM     000080          canonical           0.4 10  15   EE
+6   TOM     000040                              1.7 10  300   EE
+
+
+

And I am reducing row trying not loosing data with these lines

+
out = (df
+ .groupby('Gene_name', as_index=False)
+ .agg({'canonical': 'any',
+       'mane': 'any',
+       'metrics': lambda x: f'{x.min()}-{x.max()}',
+       'Example_extra_col': 'first',  # Here is the one I want to change
+      })
+ .replace({True: 'Yes', False: 'No'})
+)
+
+

However, for the last column, I want to concatenate data if values belonging to the dame group are different

+
  Gene_name canonical mane  metrics Example_extra_col
+0      ACOT        No  Yes  1.4-1.7           AA,BB
+1       PAN       Yes   No  0.4-0.5           DD,CC
+2       TOM       Yes   No  0.4-1.7           EE
+
+

How can I do this with .gg ?

","

Try this:

+
# Custom aggregation function
+func = lambda x: ", ".join([y for y in x.fillna("").unique() if y])
+
+(
+    df.groupby("Gene_name", as_index=False)
+    .agg(
+        {
+            "canonical": "any",
+            "mane": "any",
+            "metrics": lambda x: f"{x.min()}-{x.max()}",
+            "Example_extra_col": func,
+        }
+    )
+    .replace({True: "Yes", False: "No"})
+)
+
+

(Edited to support NANs in the column)

",python +"I Want to get 2 types of Events, that are, Past Events and Future Events from my Events Model in a Debating Society Website made using Django

I have made a Website for the Debating Society of our College using Django.

+

I would like to have 2 types of events Past and Upcoming (Future) according to the date_of_competition, i.e., if the date and time of competition is past current date and time then return it in past events, and if the date and time of competition is in future of the current date and time then return it in future events

+

Here are my views.py file and models.py file for events

+

models.py:

+
from django.db import models
+
+
+class Format(models.Model):
+    format_name = models.CharField(max_length=100, null=False, unique=True)
+
+    def __str__(self):
+        return self.format_name
+
+
+class Organiser(models.Model):
+    organiser_name = models.CharField(max_length=140, null=False, unique=True)
+
+    def __str__(self):
+        return self.organiser_name
+
+
+class Event(models.Model):
+    banner_image = models.ImageField(upload_to="events")
+    event_name = models.CharField(max_length=150, null=False)
+    organiser_of_event = models.ForeignKey(Organiser, on_delete=models.CASCADE)
+    format_of_event = models.ForeignKey(Format, on_delete=models.CASCADE)
+    date_of_event = models.DateTimeField(auto_now_add=False)
+    registration_fees = models.IntegerField(default=0, help_text="Enter Registration Fees For The Event in Rupees")
+    details = models.TextField(null=True, blank=True)
+    created_at = models.DateTimeField(auto_now_add=True)
+    updated_at = models.DateTimeField(auto_now=True)
+
+    def __str__(self):
+        return self.event_name
+
+

view.py:

+
from django.shortcuts import render
+from .models import Event
+
+
+# Create your views here.
+def events(request):
+    context = {
+        'title': 'Events',
+        'events': Event.objects.all()
+    }
+    return render(request, 'main/Events.html', context)
+
+
+

What logic should be written in order to get both future and past events from my events table?

+

(If there's anything you don't understand or need something extra, feel free to ask for it).

","

The obvious way is to just do two queries, using the __gte (greater than or equal) and __lt (less than) operators.

+
from django.utils import timezone
+
+# ...
+
+now = timezone.now()
+
+context = {
+    'title': 'Events',
+    'future_events': Event.objects.filter(date_of_event__gte=now),
+    'past_events': Event.objects.filter(date_of_event__lt=now),
+}
+
+

You could also do a single query and do the filtering in Python:

+
now = timezone.now()
+all_events = Event.objects.all()
+future_events = [e for e in all_events if e.date_of_event >= now]
+past_events = [e for e in all_events if e.date_of_event < now]
+
+context = {
+    'title': 'Events',
+    'future_events': future_events,
+    'past_events': past_events,
+}
+
",python +"Python/OpenCV: Save pictures with defined path and name

would like to save an image in a defined path and with a defined name. +The path is fixed, but the name from a variable. +With the name alone is no problem as you see above but how can i input the fixed path?

+
import cv2
+
+img_name = "TEST"
+
+cam = cv2.VideoCapture(0)
+
+
+cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
+cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
+
+while(True):
+
+    ret, frame = cam.read()
+    cv2.imshow('preview',frame)
+
+    if cv2.waitKey(1) & 0xFF == ord('q'):
+        img_name = "{}.jpg".format(img_name)
+        cv2.imwrite(img_name, frame)
+        break
+
+cam.release()
+cv2.destroyAllWindows()
+
+

Thanks and best regards :)

","
import os
+import cv2
+
+img_name = "TEST"
+
+cam = cv2.VideoCapture(0)
+
+
+cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
+cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
+
+while(True):
+
+    ret, frame = cam.read()
+    cv2.imshow('preview',frame)
+
+    if cv2.waitKey(1) & 0xFF == ord('q'):
+        img_name = os.path.join("your_path_here", "{}.jpg".format(img_name))
+        cv2.imwrite(img_name, frame)
+        break
+
+cam.release()
+cv2.destroyAllWindows()
+
",python +"PyGithub - Can't set attribute error while trying to change default branch

I've written this code to change the default branch from "master" to "release".

+
from github import Github
+g = Github("github token", verify=False, base_url="url to repo")
+
+repo = g.get_repo("repo name")
+repo.default_branch = 'release'
+
+

I am getting the following error.

+
   repo.default_branch = 'release'
+AttributeError: can't set attribute
+
+

I am the admin of that repository and I created the branch. I don't think this is an access issue. What am I doing incorrectly?

","

The default_branch attribute is a read-only attribute; if you want to change the default branch you need to use the edit method:

+
repo.edit(default_branch='release')
+
",python +"Getting Value from div with class having another blank tag Python BeautifulSoup

I am trying to get the value '5' of from the following :

+
<div class="DrugPriceBox__price___dj2lv">₹<!-- -->5</div>
+
+

and the python-beautifulsoup code i used returns Nothing:

+
drugprice=soup.find('div', class_="DrugPriceBox__price___dj2lv")
+
+print(drugprice)
+
+

The webpage url is: https://www.1mg.com/drugs/acticort-5mg-tablet-321932

+

Thank you in advance!

+

Additional information:

+

The WORKING CODE after solving the problem:

+

+
+
if __name__ == '__main__':
+    #turl='https://www.1mg.com/drugs/acticort-5mg-tablet-321932'
+    turl='https://www.1mg.com/drugs/zerodol-sp-tablet-67307'
+    print (turl)
+    soup = BeautifulSoup(requests.get(turl,headers=headers).content, ""html.parser"")
+    #type 'div' pricing format
+    div = soup.find('div', class_='DrugPriceBox__price___dj2lv')
+    if div:
+        print(div.text)
+    else:
+        #type 'span' pricing format
+        #span =soup.find('span', class_=""PriceBoxPlanOption__offer-price___3v9x8 PriceBoxPlanOption__offer-price-cp___2QPU_"")
+        span =soup.find('span', class_=""PriceBoxPlanOption__margin-right-4___2aqFt PriceBoxPlanOption__stike___pDQVN"")      
+        if span:
+            print(span.text)
+        else:
+            print('Nada')
+
+
+

","

Not sure why you are getting an error. I cannot see the original site as it is blocked for some reason, but running an express server with exactly the div that you entered, and using the below worked fine for me with the below.

+
import string
+
+import bs4
+import requests
+
+if __name__ == '__main__':
+    r = requests.get('http://localhost:3000/')
+    soup = bs4.BeautifulSoup(r.text)
+    div = soup.find('div', class_='DrugPriceBox__price___dj2lv')
+    acceptable_chars = set(string.ascii_letters + string.digits + '.')
+    drugprice = ''.join(char for char in div.text if char in acceptable_chars)
+    print(drugprice)
+
",python +"Machine Learning Model Only Predicting Mode in Data Set

I am trying to do sentiment analysis for text. I have 909 phrases commonly used in emails, and I scored them out of ten for how angry they are, when isolated.

Now, I upload this .csv file to a Jupyter Notebook, where I import the following modules:

+
import numpy as np
+import pandas as pd
+from sklearn.model_selection import train_test_split
+from sklearn.naive_bayes import MultinomialNB
+from sklearn.feature_extraction.text import TfidfVectorizer
+
+

Now, I define both columns as 'phrases' and 'anger':

+
df=pd.read_csv('Book14.csv', names=['Phrase', 'Anger'])
+df_x = df['Phrase']
+df_y = df['Anger']
+
+

Subsequently, I split this data such that 20% is used for testing and 80% is used for training:

+
x_train, x_test, y_train, y_test = train_test_split(df_x, df_y, test_size=0.2, random_state=4)
+
+

Now, I convert the words in x_train to numerical data using TfidfVectorizer:

+
tfidfvectorizer = TfidfVectorizer(analyzer='word', stop_words='en')
+x_traincv = tfidfvectorizer.fit_transform(x_train.astype('U'))
+
+

Now, I convert x_traincv to an array:

+
a = x_traincv.toarray()
+
+

I also convert x_testcv to a numerical array:

+
x_testcv=tfidfvectorizer.fit_transform(x_test)
+x_testcv = x_testcv.toarray()
+
+

Now, I have

+
mnb = MultinomialNB()
+b=np.array(y_test)
+error_score = 0
+b=np.array(y_test)
+for i in range(len(x_test)):
+    mnb.fit(x_testcv,y_test)
+    testmessage=x_test.iloc[i]
+    predictions = mnb.predict(x_testcv[i].reshape(1,-1))
+    error_score = error_score + (predictions-int(b[i]))**2
+    print(testmessage)
+    print(predictions)
+print(error_score/len(x_test))
+
+

However, an example of the results I get are:

+
+

Bring it back +[0] +It is greatly appreciatd when +[0] +Apologies in advance +[0] +Can you please +[0] +See you then +[0] +I hope this email finds you well. +[0] +Thanks in advance +[0] +I am sorry to inform +[0] +You’re absolutely right +[0] +I am deeply regretful +[0] +Shoot me through +[0] +I’m looking forward to +[0] +As I already stated +[0] +Hello +[0] +We expect all students +[0] +If it’s not too late +[0]

+
+

and this repeats on a large scale, even for phrases that are obviously very angry. When I removed all data containing a '0' from the .csv file, the now modal value (a 10) is the only prediction for my sentences.

Why is this happening? Is it some weird way to minimise error? Are there any inherent flaws in my code? Should I take a different approach?

","

Two things, you are fitting The MultinomialNB with the test set. In your loop you have mnb.fit(x_testcv,y_test) but you should do mnb.fit(x_traincv,y_train)

+

Second, when performing pre-processing you should call the fit_transform only on the training data while on the test you should call only the transform method.

",python +"Translate array into x and y direction - Python

We have the following two-dimensional array with x and y coordinates:

+
x = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
+
+

We flatten it: x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) )

+

and our goal is to apply translations into x direction, y direction.

+

We are dealing with a 4x4 array (lattice), and the first transformation is 1 shift into x direction : +so from '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]' we get '[1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]'.

+

The next transformation is two shifts in x: +from '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]' we get '[2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]'.

+

We want to get this (flattened) array:

+
y = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+              [1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12],
+              [2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13],
+              [3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14],
+              [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3],
+              [5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12, 1, 2, 3, 0],
+              [6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13, 2, 3, 0, 1],
+              [7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14, 3, 0, 1, 2],
+              [8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7],
+              [9, 10, 11, 8, 13, 14, 15, 12, 1, 2, 3, 0, 5, 6, 7, 4],
+              [10, 11, 8, 9, 14, 15, 12, 13, 2, 3, 0, 1, 6, 7, 4, 5],
+              [11, 8, 9, 10, 15, 12, 13, 14, 3, 0, 1, 2, 7, 4, 5, 6],
+              [12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
+              [13, 14, 15, 12, 1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8],
+              [14, 15, 12, 13, 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9],
+              [15, 12, 13, 14, 3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10]])
+
+

I tried using:

+
y = np.roll(np.roll(x, -1), -1)  
+
","

Can concatenate two vstack operations. First, roll in axis=1 and then, roll in axis=0.

+
np.vstack([np.roll(np.roll(arr, -i, axis=0), -x, axis=1).flatten() \
+           for x in range(arr.shape[0])] \
+           for i in range(arr.shape[1]))
+
+
+
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15],
+       [ 1,  2,  3,  0,  5,  6,  7,  4,  9, 10, 11,  8, 13, 14, 15, 12],
+       [ 2,  3,  0,  1,  6,  7,  4,  5, 10, 11,  8,  9, 14, 15, 12, 13],
+       [ 3,  0,  1,  2,  7,  4,  5,  6, 11,  8,  9, 10, 15, 12, 13, 14],
+       [ 4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,  0,  1,  2,  3],
+       [ 5,  6,  7,  4,  9, 10, 11,  8, 13, 14, 15, 12,  1,  2,  3,  0],
+       [ 6,  7,  4,  5, 10, 11,  8,  9, 14, 15, 12, 13,  2,  3,  0,  1],
+       [ 7,  4,  5,  6, 11,  8,  9, 10, 15, 12, 13, 14,  3,  0,  1,  2],
+       [ 8,  9, 10, 11, 12, 13, 14, 15,  0,  1,  2,  3,  4,  5,  6,  7],
+       [ 9, 10, 11,  8, 13, 14, 15, 12,  1,  2,  3,  0,  5,  6,  7,  4],
+       [10, 11,  8,  9, 14, 15, 12, 13,  2,  3,  0,  1,  6,  7,  4,  5],
+       [11,  8,  9, 10, 15, 12, 13, 14,  3,  0,  1,  2,  7,  4,  5,  6],
+       [12, 13, 14, 15,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
+       [13, 14, 15, 12,  1,  2,  3,  0,  5,  6,  7,  4,  9, 10, 11,  8],
+       [14, 15, 12, 13,  2,  3,  0,  1,  6,  7,  4,  5, 10, 11,  8,  9],
+       [15, 12, 13, 14,  3,  0,  1,  2,  7,  4,  5,  6, 11,  8,  9, 10]])
+
",python +"How to mask only the most recent date?

Let's say I have 2 days worth of date times:

+
import pandas as pd
+import numpy as np
+
+index = pd.date_range("2020-01-01 00:00:00", "2020-01-03 00:00:00", freq="15T")
+
+print(index)
+DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 00:15:00',
+               '2020-01-01 00:30:00', '2020-01-01 00:45:00',
+               '2020-01-01 01:00:00', '2020-01-01 01:15:00',
+               '2020-01-01 01:30:00', '2020-01-01 01:45:00',
+               '2020-01-01 02:00:00', '2020-01-01 02:15:00',
+               ...
+               '2020-01-02 21:45:00', '2020-01-02 22:00:00',
+               '2020-01-02 22:15:00', '2020-01-02 22:30:00',
+               '2020-01-02 22:45:00', '2020-01-02 23:00:00',
+               '2020-01-02 23:15:00', '2020-01-02 23:30:00',
+               '2020-01-02 23:45:00', '2020-01-03 00:00:00'],
+              dtype='datetime64[ns]', length=193, freq='15T')
+
+

And then I declare a pandas array based on my index with each element set to False:

+
entries = pd.Series(False, index=index)
+
+

I then get the market times, and the open times:

+
market_hours_indices = entries.index.indexer_between_time('9:30', '16:00')
+market_hours_index = entries.index[market_hours_indices]
+open_hours_indices = entries.index.indexer_between_time('9:30', '10:30')
+open_hours_index = entries.index[open_hours_indices]
+
+

And then mask my initial pandas array with my indexs:

+
entries = entries[market_hours_index]
+entries[~entries.index.isin(open_hours_index)] = False
+entries
+
+

This gives me:

+
2020-01-01 09:30:00     True
+2020-01-01 09:45:00     True
+2020-01-01 10:00:00     True
+2020-01-01 10:15:00     True
+2020-01-01 10:30:00     True
+2020-01-01 10:45:00    False
+2020-01-01 11:00:00    False
+2020-01-01 11:15:00    False
+2020-01-01 11:30:00    False
+2020-01-01 11:45:00    False
+2020-01-01 12:00:00    False
+2020-01-01 12:15:00    False
+2020-01-01 12:30:00    False
+2020-01-01 12:45:00    False
+2020-01-01 13:00:00    False
+2020-01-01 13:15:00    False
+2020-01-01 13:30:00    False
+2020-01-01 13:45:00    False
+2020-01-01 14:00:00    False
+2020-01-01 14:15:00    False
+2020-01-01 14:30:00    False
+2020-01-01 14:45:00    False
+2020-01-01 15:00:00    False
+2020-01-01 15:15:00    False
+2020-01-01 15:30:00    False
+2020-01-01 15:45:00    False
+2020-01-01 16:00:00    False
+2020-01-02 09:30:00     True
+2020-01-02 09:45:00     True
+2020-01-02 10:00:00     True
+2020-01-02 10:15:00     True
+2020-01-02 10:30:00     True
+2020-01-02 10:45:00    False
+2020-01-02 11:00:00    False
+2020-01-02 11:15:00    False
+2020-01-02 11:30:00    False
+2020-01-02 11:45:00    False
+2020-01-02 12:00:00    False
+2020-01-02 12:15:00    False
+2020-01-02 12:30:00    False
+2020-01-02 12:45:00    False
+2020-01-02 13:00:00    False
+2020-01-02 13:15:00    False
+2020-01-02 13:30:00    False
+2020-01-02 13:45:00    False
+2020-01-02 14:00:00    False
+2020-01-02 14:15:00    False
+2020-01-02 14:30:00    False
+2020-01-02 14:45:00    False
+2020-01-02 15:00:00    False
+2020-01-02 15:15:00    False
+2020-01-02 15:30:00    False
+2020-01-02 15:45:00    False
+2020-01-02 16:00:00    False
+dtype: bool
+
+

Which is almost what I'm aiming to do, but how do I only target the second day? So that my array looks like:

+
2020-01-01 09:30:00    False
+2020-01-01 09:45:00    False
+2020-01-01 10:00:00    False
+2020-01-01 10:15:00    False
+2020-01-01 10:30:00    False
+2020-01-01 10:45:00    False
+2020-01-01 11:00:00    False
+2020-01-01 11:15:00    False
+2020-01-01 11:30:00    False
+2020-01-01 11:45:00    False
+2020-01-01 12:00:00    False
+2020-01-01 12:15:00    False
+2020-01-01 12:30:00    False
+2020-01-01 12:45:00    False
+2020-01-01 13:00:00    False
+2020-01-01 13:15:00    False
+2020-01-01 13:30:00    False
+2020-01-01 13:45:00    False
+2020-01-01 14:00:00    False
+2020-01-01 14:15:00    False
+2020-01-01 14:30:00    False
+2020-01-01 14:45:00    False
+2020-01-01 15:00:00    False
+2020-01-01 15:15:00    False
+2020-01-01 15:30:00    False
+2020-01-01 15:45:00    False
+2020-01-01 16:00:00    False
+2020-01-02 09:30:00     True
+2020-01-02 09:45:00     True
+2020-01-02 10:00:00     True
+2020-01-02 10:15:00     True
+2020-01-02 10:30:00     True
+2020-01-02 10:45:00    False
+2020-01-02 11:00:00    False
+2020-01-02 11:15:00    False
+2020-01-02 11:30:00    False
+2020-01-02 11:45:00    False
+2020-01-02 12:00:00    False
+2020-01-02 12:15:00    False
+2020-01-02 12:30:00    False
+2020-01-02 12:45:00    False
+2020-01-02 13:00:00    False
+2020-01-02 13:15:00    False
+2020-01-02 13:30:00    False
+2020-01-02 13:45:00    False
+2020-01-02 14:00:00    False
+2020-01-02 14:15:00    False
+2020-01-02 14:30:00    False
+2020-01-02 14:45:00    False
+2020-01-02 15:00:00    False
+2020-01-02 15:15:00    False
+2020-01-02 15:30:00    False
+2020-01-02 15:45:00    False
+2020-01-02 16:00:00    False
+dtype: bool
+
+

What I've tried:

+
# get the days I'm interested in
+df_all_days = df[(df['date'] >= previous_day) & (df['date'] <= date)]
+
+# get the day I want to trade
+df_current_day = df[df['date'] == date]
+current_day_index = df_current_day.index
+# create an empty numpy array 
+entries = pd.Series(True, index=current_day_index)
+
+# get the index of the current day between trading hours
+market_hours_indices = entries.index.indexer_between_time('9:30', '16:00')
+market_hours_index = entries.index[market_hours_indices]
+
+# return False any dates and times which fall outside of our date
+df_all_days['enter'] = df_all_days['enter'][~df_all_days['enter'].index.isin(market_hours_index)] = False
+
+

This returns (everything false):

+
2022-06-15 07:16:00    False
+2022-06-15 09:17:00    False
+2022-06-15 09:18:00    False
+2022-06-15 09:19:00    False
+...
+2022-06-16 19:59:00    False
+Name: enter, dtype: bool
+
","

I figured it out:

+
df = pd.read_csv(fname, index_col='datetime', usecols=["open", "high", "low", "close", "volume", "datetime", "date", "time"], parse_dates=True)
+
+# get the days I'm interested in
+df_all_days = df[(df['date'] >= previous_day) & (df['date'] <= date)]
+
+# get the day I want to trade
+df_current_day = df_all_days[df_all_days['date'] == date]
+# get the hours I want to trade
+df_current_day_indices = df_current_day.index.indexer_between_time('09:30', '16:00')
+current_day_index = df_current_day.index[df_current_day_indices]
+
+# create fake entry logic
+df_all_days['entries'] = np.where((0), True, False)
+# only enter during the days and hours we wanna trade        
+df_all_days['entries'] = df_all_days['entries'].index.isin(current_day_index)
+
+with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
+    # both arrays are the same size
+    print(df_all_days['entries'].size)
+    print(df_all_days['close'].size)
+    print(df_all_days['entries'])
+
",python +"Python, how to execute a line of code without it stopping the rest of the code from executing?

first of all, im a beginner. +Want i want to accomplish is that music plays while the script is executing. +What it does right now it plays the music, waits until the music is over and then executes the rest of the code. That is not what i want. Here my Code:

+
import os
+import subprocess
+import multiprocessing
+import threading
+from playsound import playsound
+CurrentPath = os.path.dirname(os.path.normpath(__file__))
+os.chdir(CurrentPath)
+
+def music():
+    Music = "Music.mp4"
+    #subprocess.run(["ffplay", "-nodisp", "-autoexit", "-hide_banner", Music])
+    playsound("Music.mp4")
+
+def other_things():
+    print("Hello World")
+
+#musicp = multiprocessing.Process(target=music())
+#restp = multiprocessing.Process(target=other_things())
+musicp = threading.Thread(target=music())
+restp = threading.Thread(target=other_things())
+
+restp.start()
+musicp.start()
+
+

LIke you can see i even tried multithreading but it still waits until the music is over before it goes to the rest of the code.

","

Don't call the functions in the target parameter of the Thread function - delete the brackets to reference the function, not its return value

+
musicp = threading.Thread(target=music) # instead of music()
+restp = threading.Thread(target=other_things) # instead of other_things()
+
",python +"Call compound.finance api with parameters

I'm trying to simply call the compound.finance api "https://api.compound.finance/api/v2/account" with the parameter max_health. the doc says

+
+

"If provided, should be given as { "value": "...string formatted +number..." }".

+
+

(https://compound.finance/docs/api#account-service)

+

So I tried 4 methods here below:

+
response = requests.get(
+    'https://api.compound.finance/api/v2/account',
+    params={
+        "max_health": "1.0" # method 1
+        "max_health": {"value":"1.0"} # method 2
+        "max_health": json.dumps({"value":"1.0"}) # method 3
+    }
+)
+
+

but it does not work, and I get

+
+

HTTPError: 500 Server Error: Internal Server Error for url:...

+
+

Any idea I should format it please?

","

They did not update the API docs. You should send a POST request and provide params as a request body.

+
import json
+import requests
+
+url = "https://api.compound.finance/api/v2/account"
+data = {
+    "max_health": {"value": "1.0"}
+}
+
+response = requests.post(url, data=json.dumps(data))  # <Response [200]>
+response = response.json()  # {'accounts': ...}
+
+

Edit notes

+

The problem was that the API expects raw JSON so I used json.dumps.

",python +"Format string to datetime in Pandas without zero padding, AM/PM and UTC

My csv file contains the date and time values like below. I want to convert this to a datetime format in pandas but I keep getting errors.
+I then want to convert it to a 24 hour format with zero padding and without the mention UTC.

+

I already tried : format="%m/%d/%Y %I:%M %p"

+
10/12/2021 10:25 AM UTC   
+9/28/2021 8:51 AM UTC   
+7/27/2021 9:45 AM UTC   
+2/2/2022 7:10 PM UTC 
+
+

Desired output:

+
10/12/2021 10:25   
+09/28/2021 08:51   
+07/27/2021 09:45   
+02/02/2022 19:10 
+
","

You can use %m/%d/%Y %H:%M:

+
pd.to_datetime(df['date'], dayfirst=False).dt.strftime('%m/%d/%Y %H:%M')
+
+

output:

+
0    10/12/2021 10:25
+1    09/28/2021 08:51
+2    07/27/2021 09:45
+3    02/02/2022 19:10
+Name: date, dtype: object
+
+

used input:

+
df = pd.DataFrame({'date': ['10/12/2021 10:25 AM UTC',
+                            '9/28/2021 8:51 AM UTC',
+                            '7/27/2021 9:45 AM UTC',
+                            '2/2/2022 7:10 PM UTC']})
+
",python +"Pivot values in specific order

I have a dataframe where I would like to pivot my data to fit a specific format, making sure the dates are consecutive.

+

Data

+
ID  Q122_c_en   Q122con_s   Q222_c_en   Q222con_s Q322_c_en Q322con_s Q422_c_en Q422con_s
+AA  900         89          1000        90        1200      92        1000      90
+BB  1000        10          1000        20        1100      25        1300      30
+                    
+
+

Desired

+
ID  Date    con_en  con_s   
+AA  Q122    900     89  
+AA  Q222    1000    90  
+AA  Q322    1200    92  
+AA  Q422    1000    90  
+BB  Q122    1000    10  
+BB  Q222    1000    20  
+BB  Q322    1100    25  
+BB  Q422    1300    30  
+
+

Doing

+
df.pivot(index="ID", columns="Date", values=["con_en", "con_s"])
+
+

I am using pivot, however, the format does not reflect the desired above format.

","

one option, where you can do the transform in one step, is with pivot_longer from pyjanitor:

+
# pip install pyjanitor
+import pandas as pd
+import janitor
+
+df.pivot_longer(
+    index = 'ID', 
+    names_to = ('Date', '.value'), 
+    names_pattern = r"(Q\d+)_?(.+)",
+    sort_by_appearance = True)
+
+   ID  Date  c_en  con_s
+0  AA  Q122   900     89
+1  AA  Q222  1000     90
+2  AA  Q322  1200     92
+3  AA  Q422  1000     90
+4  BB  Q122  1000     10
+5  BB  Q222  1000     20
+6  BB  Q322  1100     25
+7  BB  Q422  1300     30
+
+

Any label in the columns associated with .value stays as a header; this is determined by the groups in the regex in names_pattern.

",python +"Pass task results from preceding tasks celery

Here is my code. I want to pass the task myname result pass to be the task reverse in the signature as an argument.

+

Here is my code. I want to pass the task myname result pass to be the task reverse in the signature as an argument.

+
from app import app
+from app import app
+from time import sleep
+from celery.utils.log import get_task_logger
+import os
+from celery import signature, chain, group, chord
+from celery.result import allow_join_result
+
+
+MyQUEUE = os.getenv("SCANS_QUEUE")
+logger = get_task_logger(__name__)
+
+@app.task(queue=MyQUEUE, ignore_result=True)
+def reverse(text):
+    logger.info('reverse order '.format(text))
+    return {"reversename": str(text[::-1])}
+
+@app.task(queue=MyQUEUE, ignore_result=True)
+def add(a,b):
+    logger.info('Addition --> a : {0} & b : {1} '.format(a,b))
+    return {"addition": str(a+b)}
+
+@app.task(queue=MyQUEUE, ignore_result=True)
+def myname(a):
+    logger.info('Name --> a : {0}'.format(a))
+    return {"name": str(a)}
+
+
+@app.task(queue=MyQUEUE, ignore_result=True)
+def run_pipeline(a,b,n):
+    resultchain = chain([
+        group([
+            signature(
+                add,
+                args=(a,b),
+                queue=MyQUEUE
+            ),
+            signature(
+                myname,
+                args=(n),
+                queue=MyQUEUE
+            )
+        ]),
+        signature
+        (
+            reverse,
+            args=(-------),
+            queue=MyQUEUE
+        )
+    ]).apply_async()
+
+    with allow_join_result():
+        results = resultchain.join()
+    return results
+
","

First and most important, if you are gonna use chain, group, starmap or another kind of task workflow, tasks which results will be used on the future need to be set with ignore_result=False or omit the argument (default value is False). Needed to store the value, at least on myname and add

+
@app.task(queue=MyQUEUE)
+def add(a,b):
+    logger.info('Addition --> a : {0} & b : {1} '.format(a,b))
+    return {"addition": str(a+b)}
+
+@app.task(queue=MyQUEUE)
+def myname(a):
+    logger.info('Name --> a : {0}'.format(a))
+    return {"name": str(a)}
+
+
+

Now, for reverse to obtain the results in the group of add and myname, you need to adjust reverse to handle the group result (a list of the results).

+

For a chain the results of a task will be used as the first argument of the next task, in this case the group results will be injected in the first value of the reverse task as [{'addition': ...}, {'name': ...}], with that you can access the correct value.

+
@app.task(queue=MyQUEUE)
+def reverse(group_data):
+    # group_data value: [{'addition': '3'}, {'name': 'VALUE'}]
+    text = group_data[1]['name']
+    logger.info('reverse order '.format(text))
+    return {"reversename": str(text[::-1])}
+
+

Finally if you only want to reverse the result of myname, you have to chain only myname and reverse.

+
resultchain = chain([
+    signature(myname, args=(n,)),
+    signature(reverse)
+]).apply_async()
+
",python +"create volume in docker compose base on client directory path

I want to use a local folder for example dataset in my docker container. Also I have a python request module in which client send to API server a directory path. I want to use this path in docker compose as volume to use it in docker container.

+

How to send this path to docker compose. +API request is :

+
def train():
+    url = 'http://127.0.0.1:8000/train'  # server url
+    data = {'label': ['fire'],
+            'image_path': '/path/to/directory',
+            'label_path': '/path/to/directory',
+            'image_size': 640,
+            'validation_split': 0.2,
+            'save_dir': 'results/'}
+    r = requests.post(url, json=data)
+    print(r.text)
+
+

how to send local path 'image_path' and 'label_path'to docker compose and use it as volumes. +my docker compose :

+
version: "3.8"
+services:
+    inference:
+        container_name: "inference"
+        build: "./backbone"
+        ports:
+            - '5000:5000'
+        volumes:
+            - ./backbone:/code
+            # - ./volumes/weights:/weights
+        command: "python3 app.py"
+        environment:
+            - PORT=5000
+            - MODEL_PATH=/code/weights/best.pt
+        ipc: host
+        shm_size: 1024M
+
+    train:
+        container_name: "train"
+        build: "./train"
+        shm_size: '2gb'
+        command: "python3 main_train.py"
+        environment:
+            - RESPONSE_URL=http://127.0.0.1:8000/response
+            - LOGGER_URL=http://127.0.0.1:8000/logger
+            - PORT=8000
+            - IS_LOGGER_ON=False
+        ports:
+            - '8000:8000'
+        volumes:
+            - ./train:/code
+        ipc: host
+
","

You need a couple of changes to make this work successfully.

+

In the server code, you need to not accept a full path. There are a number of security concerns around doing this (can you retrieve the application code? the file of database credentials? system files like /etc/passwd?). Instead, set it to have a configurable data path, and only accept files within that path.

+
DATA_PATH = os.environ.get('DATA_PATH', 'data') # default relative to current directory
+
+def handle(data):
+  if '/' in data['image_file']:
+    raise InvalidInputError()
+  image_path = os.path.join(DATA_PATH, data['image_file'])
+  ...
+
+

When you set this up in a Docker image, you can specify a fixed path for that data path. Using a simple path in a subdirectory of the container filesystem root is fine.

+
# train/Dockerfile
+FROM python
+...
+ENV DATA_DIR=/data        # set this variable only because the application wants it
+RUN mkdir -p "$DATA_DIR"  # create an empty directory by default
+CMD ["./main_train.py"]
+
+

Now when you launch this in Compose, you know the (fixed) container-side path that will hold the data directory, so you can mount content there.

+
services:
+  train:
+    build: ./train
+    ports:
+      - '8000:8000'
+    volumes:
+      - ./dataset_3:/data
+
+

It's usually the case that details like the filesystem layout in an image, paths for injected data or configuration, and the port that the service inside the container uses are fixed properties of the image. So it's safe to specify "the data will always be in /data" and use that as a mount point; you do not need to specify it as a variable anywhere in the Docker setup. Similarly, you should not need to set a $PORT environment variable in your Compose setup since the container-side port number will generally be a fixed property of your image.

",python +"SMTP_HELO returns timeout when running email address validation

Using library py3-validate-email-1.0.5 (more here) to check if email address is valid, including SMTP check, I wasn't able to make it through check_smtp step, because I get following error:

+

Python script

+
from validate_email import validate_email
+from validate_email import validate_email_or_fail
+from csv import DictReader
+
+# iterate over each line by column name
+with open('email-list.csv', 'r') as read_obj:
+    csv_dict_reader = DictReader(read_obj, delimiter=';')
+    for row in csv_dict_reader:
+        i = 1
+        while i < 21:
+            header_name = 'Email'+str(i)
+            if validate_email_or_fail(
+                email_address=row[header_name],
+                check_format=True,
+                check_blacklist=True,
+                check_dns=True,
+                dns_timeout=10,
+                check_smtp=True,
+                smtp_timeout=5,
+                smtp_helo_host='emailsrv.domain.com',
+                smtp_from_address='email@domain.com',
+                smtp_skip_tls=False,
+                smtp_tls_context=None,
+                smtp_debug=False):
+                print('Email ' + row[header_name] + ' is valid.')
+            else:
+                print('Email ' + row[header_name] + ' is invalid.')
+            i += 1
+
+

Error:

+
Traceback (most recent call last):
+  File "//./main.py", line 13, in <module>
+    if validate_email_or_fail(
+  File "/usr/local/lib/python3.9/site-packages/validate_email/validate_email.py", line 59, in validate_email_or_fail
+    return smtp_check(
+  File "/usr/local/lib/python3.9/site-packages/validate_email/smtp_check.py", line 229, in smtp_check
+    return smtp_checker.check(hosts=mx_records)
+  File "/usr/local/lib/python3.9/site-packages/validate_email/smtp_check.py", line 197, in check
+    raise SMTPTemporaryError(error_messages=self.__temporary_errors)
+validate_email.exceptions.SMTPTemporaryError: Temporary error in email address verification:
+mx.server.com: 451 timed out (in reply to 'connect')
+
+

I figured there is problem with my DNS settings (probably), so I dockerized the script and run it on AWS EC2, where I have used elastic IP, attached it to the EC2 instance where docker container is running, I also setup reverse DNS for domain emailsrv.domain.com with this elastic IP. Tried to run the script, no change.

+

Then I added MX record pointing to the emailsrv.domain.com, but still no change. The DNS records are setup properly, because I have checked it with multiple DNS tools available.

+

Since the library doesn't require to actually use my email address login details, I wonder what can be the problem? Just to be sure, the email address used in the script doesn't exist, since I don't have smtp server setup on that instance, obviously.

+

Any ideas?

","

Reason behind this was closed port on AWS EC2 instance. Opening the port in security group is not enough, you must send a request to AWS so they remove the restriction on port 25.

+

When they did that, works flawlessly.

",python +"How to get Data from MySQL DB on Python Flask?

I´m learning Python Flask with MySQL Workbench, I have a database 'books' and a table 'books.books_tb' in my Workbench. I made a simple Flask app with the tutorial which looks like that:

+
from flask import Flask
+from flask_mysqldb import MySQL
+
+@app.route('/books')
+def home():
+    def GetBookLink():
+        mydb = mysql.connector.connect(
+                    host='localhost',
+                    user = 'root',
+                    database = 'books'
+                    )
+        mycursor = mydb.mycursor()
+
+        
+        
+        mycursor.execute("SELECT * FROM books.books_tb") 
+        DBData = mycursor.fetchall() 
+        mycursor.close()
+        return DBData
+         
+    DBData = GetBookLink()
+    return render_template("index.html", ScrapedBookData = DBData)
+
+
+

my index.html looks like that:

+
{% extends "base.html"%} {% block title %}Home{% endblock %}{% block content %}    
+<h1>{{ScrapedBookData}}</h1>
+{% endblock %}
+
+

But I get an error (link at bottom) and as a newbie I don´t understand how to solve it. How can I solve this problem and write some queries to display the rows in my database?

+

[enter image description here][1] +[1]: https://i.stack.imgur.com/lZTGQ.png

","

From the first page of the documentation, you're missing the instantiation of the MySQL class into a mysql variable.

+
from flask import Flask
+from flask_mysqldb import MySQL
+
+app = Flask(__name__)
+mysql = MySQL(app)  # this is the instantiation
+
+
+@app.route('/')
+def users():
+    cur = mysql.connection.cursor()
+    cur.execute('''SELECT user, host FROM mysql.user''')
+    rv = cur.fetchall()
+    return str(rv)
+
+if __name__ == '__main__':
+    app.run(debug=True)
+
",python +"Trying to open .bson file and read to pandas df but getting 'bson.errors.InvalidBSON: objsize too large' first time using .bson

#This is my code

+
import pandas as pd
+import bson
+
+FILE="users_(1).bson"
+
+with open(FILE,'rb') as f:
+    data = bson.decode_all(f.read())
+
+main_df=pd.DataFrame(data)
+main_df.describe()
+
+

#This is my .bson file

+
[{'_id': ObjectId('999f24f260f653401b'),
+    'isV2': False,
+    'isBeingMigratedToV2': False,
+    'firstName': 'Jezz',
+    'lastName': 'Bezos',
+    'subscription': {'_id': ObjectId('999f24f260f653401b'),
+     'chargebeeId': 'AzZdd6T847kHQ',
+     'currencyCode': 'EUR',
+     'customerId': 'AzZdd6T847kHQ',
+     'nextBillingAt': datetime.datetime(2022, 7, 7, 10, 14, 6),
+     'numberOfMonthsPaid': 1,
+     'planId': 'booster-v3-eur',
+     'startedAt': datetime.datetime(2022, 6, 7, 10, 14, 6),
+     'addons': [],
+     'campaign': None,
+     'maskedCardNumber': '************1234'},
+    'email': 'jeffbezos@gmail.com',
+    'groupName': None,
+    'username': 'jeffbezy',
+    'country': 'DE'},
+   {'_id': ObjectId('999f242660f653401b'),
+    'isV2': False,
+    'isBeingMigratedToV2': False,
+    'firstName': 'Caterina',
+    'lastName': 'Fake',
+    'subscription': {'_id': ObjectId('999f242660f653401b'),
+     'chargebeeId': '16CGLYT846t99',
+     'currencyCode': 'GBP',
+     'customerId': '16CGLYT846t99',
+     'nextBillingAt': datetime.datetime(2022, 7, 7, 10, 10, 41),
+     'numberOfMonthsPaid': 1,
+     'planId': 'personal-v3-gbp',
+     'startedAt': datetime.datetime(2022, 6, 7, 10, 10, 41),
+     'addons': [],
+     'campaign': None,
+     'maskedCardNumber': '************4311'},
+    'email': 'caty.fake@gmail.com',
+    'groupName': None,
+    'username': 'cfake',
+    'country': 'GB'}]
+
+

I get the error

+
'bson.errors.InvalidBSON: objsize too large'
+
+

Is it something to do with the datetime? Is it the structure of the .bson file, been at this for hours and can't seem to see the error. I know how to work with json and tried to convert it to json but no success. Any tips would be appreciated.

","

If the main goal here is to read the data into a pandas DataFrame you could indeed format the data to json and use bson.json_util.loads:

+
import pandas as pd
+from bson.json_util import loads
+
+with open(filepath,'r') as f:
+    data = f.read()
+
+mapper = {
+    '\'': '"',   # using double quotes
+    'False': 'false',
+    'None': '\"None\"',  # double quotes around None
+    # modifying the ObjectIds and timestamps
+    '("': '(', 
+    '")': ')', 
+    ')': ')"',
+    'ObjectId': '"ObjectId',
+    'datetime.datetime': '"datetime.datetime'
+}
+for k, v in mapper.items():
+    data = data.replace(k, v)
+
+data = loads(data)
+df = pd.DataFrame(data)
+
",python +"Flatten a nested xml with pandas

I have the follow xml in this format:

+
<?xml version='1.0' encoding='UTF-8'?>
+<ettevotjad>
+  <ettevotja>
+    <nimi>000 Holdings OÜ</nimi>
+    <ariregistri_kood>16372442</ariregistri_kood>
+    <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+    <ettevotja_oigusliku_vormi_alaliik/>
+    <kmkr_nr/>
+    <ettevotja_staatus>R</ettevotja_staatus>
+    <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+    <ettevotja_esmakande_kpv>23.11.2021</ettevotja_esmakande_kpv>
+    <ettevotja_aadress>
+      <asukoht_ettevotja_aadressis/>
+      <asukoha_ehak_kood/>
+      <asukoha_ehak_tekstina></asukoha_ehak_tekstina>
+      <indeks_ettevotja_aadressis/>
+      <ads_adr_id></ads_adr_id>
+      <ads_ads_oid></ads_ads_oid>
+      <ads_normaliseeritud_taisaadress/>
+    </ettevotja_aadress>
+    <teabesysteemi_link>https://ariregister.rik.ee/est/company/16372442</teabesysteemi_link>
+  </ettevotja>
+  <ettevotja>
+    <nimi>001 group OÜ</nimi>
+    <ariregistri_kood>12754230</ariregistri_kood>
+    <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+    <ettevotja_oigusliku_vormi_alaliik/>
+    <kmkr_nr/>
+    <ettevotja_staatus>R</ettevotja_staatus>
+    <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+    <ettevotja_esmakande_kpv>17.11.2014</ettevotja_esmakande_kpv>
+    <ettevotja_aadress>
+      <asukoht_ettevotja_aadressis>Õismäe tee 78-9</asukoht_ettevotja_aadressis>
+      <asukoha_ehak_kood>0176</asukoha_ehak_kood>
+      <asukoha_ehak_tekstina>Haabersti linnaosa, Tallinn, Harju maakond</asukoha_ehak_tekstina>
+      <indeks_ettevotja_aadressis>13513</indeks_ettevotja_aadressis>
+      <ads_adr_id>2182337</ads_adr_id>
+      <ads_ads_oid></ads_ads_oid>
+      <ads_normaliseeritud_taisaadress>Harju maakond, Tallinn, Haabersti linnaosa, Õismäe tee 78-9</ads_normaliseeritud_taisaadress>
+    </ettevotja_aadress>
+    <teabesysteemi_link>https://ariregister.rik.ee/est/company/12754230</teabesysteemi_link>
+  </ettevotja>
+</ettevotjad>
+
+

Using pandas' .read_xml() yields:

+
 import pandas as pd
+
+ data = pd.read_xml('test_file.xml')
+
+ print(data.head(2).to_string())
+              nimi  ariregistri_kood ettevotja_oiguslik_vorm  ettevotja_oigusliku_vormi_alaliik kmkr_nr ettevotja_staatus ettevotja_staatus_tekstina ettevotja_esmakande_kpv  ettevotja_aadress                               teabesysteemi_link
+0  000 Holdings OÜ          16372442                Osaühing                                NaN    None                 R         Registrisse kantud              23.11.2021                NaN  https://ariregister.rik.ee/est/company/16372442
+1     001 group OÜ          12754230                Osaühing                                NaN    None                 R         Registrisse kantud              17.11.2014                NaN  https://ariregister.rik.ee/est/company/12754230
+
+

Notice in the dataframe 'ettevotja_aadress' is NaN, but in fact if you look at the xml structure, it's nested with those sub columns/headers. How do I expand out those nested columns into the dataframe?

+

I thought one way to do it was to simply read in the file, remove the <ettevotja_aadress> and <ettevotja_aadress> tags, then read into pandas, but it seems like there should be direct way to do this, similar to pandas' .json_normalize().

","

This could be done by providing an XSL stylesheet to flatten the original XML. Code will look like following:

+
xml = '''<?xml version='1.0' encoding='UTF-8'?>
+<ettevotjad>
+  <ettevotja>
+    <nimi>000 Holdings OÜ</nimi>
+    <ariregistri_kood>16372442</ariregistri_kood>
+    <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+    <ettevotja_oigusliku_vormi_alaliik/>
+    <kmkr_nr/>
+    <ettevotja_staatus>R</ettevotja_staatus>
+    <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+    <ettevotja_esmakande_kpv>23.11.2021</ettevotja_esmakande_kpv>
+    <ettevotja_aadress>
+      <asukoht_ettevotja_aadressis/>
+      <asukoha_ehak_kood/>
+      <asukoha_ehak_tekstina></asukoha_ehak_tekstina>
+      <indeks_ettevotja_aadressis/>
+      <ads_adr_id></ads_adr_id>
+      <ads_ads_oid></ads_ads_oid>
+      <ads_normaliseeritud_taisaadress/>
+    </ettevotja_aadress>
+    <teabesysteemi_link>https://ariregister.rik.ee/est/company/16372442</teabesysteemi_link>
+  </ettevotja>
+  <ettevotja>
+    <nimi>001 group OÜ</nimi>
+    <ariregistri_kood>12754230</ariregistri_kood>
+    <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+    <ettevotja_oigusliku_vormi_alaliik/>
+    <kmkr_nr/>
+    <ettevotja_staatus>R</ettevotja_staatus>
+    <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+    <ettevotja_esmakande_kpv>17.11.2014</ettevotja_esmakande_kpv>
+    <ettevotja_aadress>
+      <asukoht_ettevotja_aadressis>Õismäe tee 78-9</asukoht_ettevotja_aadressis>
+      <asukoha_ehak_kood>0176</asukoha_ehak_kood>
+      <asukoha_ehak_tekstina>Haabersti linnaosa, Tallinn, Harju maakond</asukoha_ehak_tekstina>
+      <indeks_ettevotja_aadressis>13513</indeks_ettevotja_aadressis>
+      <ads_adr_id>2182337</ads_adr_id>
+      <ads_ads_oid></ads_ads_oid>
+      <ads_normaliseeritud_taisaadress>Harju maakond, Tallinn, Haabersti linnaosa, Õismäe tee 78-9</ads_normaliseeritud_taisaadress>
+    </ettevotja_aadress>
+    <teabesysteemi_link>https://ariregister.rik.ee/est/company/12754230</teabesysteemi_link>
+  </ettevotja>
+</ettevotjad>
+'''
+
+import pandas as pd
+
+stylesheet = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+<xsl:output indent="yes"/>
+<xsl:template match="/">
+    <ettevotjad>
+        <xsl:apply-templates select="//ettevotja"/>
+    </ettevotjad>
+</xsl:template>
+<xsl:template match="ettevotja">
+    <ettevotja>
+      <xsl:copy-of select="node()[not(self::ettevotja_aadress)]"/>
+      <xsl:apply-templates select="./ettevotja_aadress"/>
+    </ettevotja>
+ </xsl:template>
+ <xsl:template match="ettevotja_aadress">
+    <xsl:copy-of select="node()"/>
+  </xsl:template>
+ </xsl:stylesheet>
+'''
+
+df = pd.read_xml(xml, xpath="//ettevotja", stylesheet = stylesheet)
+
+df.head()
+
+

The idea behind the code is that XSL transformation is applied to the XML document, flattening its structure. The result of the transformation will be:

+
<?xml version="1.0" encoding="UTF-8"?>
+<ettevotjad>
+   <ettevotja>
+      <nimi>000 Holdings OÜ</nimi>
+      <ariregistri_kood>16372442</ariregistri_kood>
+      <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+      <ettevotja_oigusliku_vormi_alaliik/>
+      <kmkr_nr/>
+      <ettevotja_staatus>R</ettevotja_staatus>
+      <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+      <ettevotja_esmakande_kpv>23.11.2021</ettevotja_esmakande_kpv>
+      <teabesysteemi_link>https://ariregister.rik.ee/est/company/16372442</teabesysteemi_link>
+  
+      <asukoht_ettevotja_aadressis/>
+      <asukoha_ehak_kood/>
+      <asukoha_ehak_tekstina/>
+      <indeks_ettevotja_aadressis/>
+      <ads_adr_id/>
+      <ads_ads_oid/>
+      <ads_normaliseeritud_taisaadress/>
+    </ettevotja>
+   <ettevotja>
+      <nimi>001 group OÜ</nimi>
+      <ariregistri_kood>12754230</ariregistri_kood>
+      <ettevotja_oiguslik_vorm>Osaühing</ettevotja_oiguslik_vorm>
+      <ettevotja_oigusliku_vormi_alaliik/>
+      <kmkr_nr/>
+      <ettevotja_staatus>R</ettevotja_staatus>
+      <ettevotja_staatus_tekstina>Registrisse kantud</ettevotja_staatus_tekstina>
+      <ettevotja_esmakande_kpv>17.11.2014</ettevotja_esmakande_kpv>
+      <teabesysteemi_link>https://ariregister.rik.ee/est/company/12754230</teabesysteemi_link>
+  
+      <asukoht_ettevotja_aadressis>Õismäe tee 78-9</asukoht_ettevotja_aadressis>
+      <asukoha_ehak_kood>0176</asukoha_ehak_kood>
+      <asukoha_ehak_tekstina>Haabersti linnaosa, Tallinn, Harju maakond</asukoha_ehak_tekstina>
+      <indeks_ettevotja_aadressis>13513</indeks_ettevotja_aadressis>
+      <ads_adr_id>2182337</ads_adr_id>
+      <ads_ads_oid/>
+      <ads_normaliseeritud_taisaadress>Harju maakond, Tallinn, Haabersti linnaosa, Õismäe tee 78-9</ads_normaliseeritud_taisaadress>
+    </ettevotja>
+</ettevotjad>
+
+

After the transformation an XPath //ettevotja is applied to the transformation result, taking children of ettevotja elements as dataframe row fields.

",python +"FunctionTransformer & creating new columns in pipeline

I have a sample data:

+
df = pd.DataFrame(columns=['X1', 'X2', 'X3'], data=[
+                                               [1,16,9],
+                                               [4,36,16],
+                                               [1,16,9],
+                                               [2,9,8],
+                                               [3,36,15],
+                                               [2,49,16],
+                                               [4,25,14],
+                                               [5,36,17]])
+
+

I want to create two complementary columns in my df based on x2 ad X3 and include it in the pipeline.

+

I am trying to follow the code:

+
def feat_comp(x):
+ x1 = 100-x
+ return x1
+
+pipe_text = Pipeline([('col_test', FunctionTransformer(feat_comp, 'X2',validate=False))])
+X = pipe_text.fit_transform(df)
+
+

It gives me an error:

+
TypeError: 'str' object is not callable
+
+

How can I apply the function transformer on selected columns and how can I use them in the pipeline?

","

If I understand you correctly, you want to add a new column based on a given column, e.g. X2. You need to pass this column as an additional argument to the function using kw_args:

+
import pandas as pd
+from sklearn.preprocessing import FunctionTransformer
+from sklearn.pipeline import Pipeline
+
+df = pd.DataFrame(columns=['X1', 'X2', 'X3'], data=[
+                                               [1,16,9],
+                                               [4,36,16],
+                                               [1,16,9],
+                                               [2,9,8],
+                                               [3,36,15],
+                                               [2,49,16],
+                                               [4,25,14],
+                                               [5,36,17]])
+
+def feat_comp(x, column):
+   x[f'100-{column}'] = 100 - x[column]
+   return x
+
+pipe_text = Pipeline([('col_test', FunctionTransformer(feat_comp, validate=False, kw_args={'column': 'X2'}))])
+pipe_text.fit_transform(df)
+
+

Result:

+
   X1  X2  X3  100-X2
+0   1  16   9      84
+1   4  36  16      64
+2   1  16   9      84
+3   2   9   8      91
+4   3  36  15      64
+5   2  49  16      51
+6   4  25  14      75
+7   5  36  17      64
+
+

(in your example FunctionTransformer(feat_comp, 'X2',validate=False) X2 would be the inverse_func and the string X2 is not callalble, hence the error)

",python +"PyTorch CNN Different Input Size

Hello Guys I have a question about different Input Sizes.

+

My training set and validation dataset have an input Size of 256 and for my prediction (with an unseen Test Dataset) I have an input size of 496.

+
class Net(nn.Module):
+    def __init__(self, shape):
+        super(Net,self).__init__()
+        self.conv1 = nn.Conv1d(shape,1,1)
+        self.batch1 = nn.BatchNorm1d(1)
+        self.avgpl1 = nn.AvgPool1d(1, stride=1)
+        self.fc1 = nn.Linear(1,3)
+    
+    #forward method 
+    def forward(self,x):
+        x = self.conv1(x)
+        x = self.batch1(x)
+        x = F.relu(x)
+        x = self.avgpl1(x)
+        x = torch.flatten(x,1)
+        x = F.log_softmax(self.fc1(x))
+        return x
+
+

I saved the model and wanna use it also for my prediction.

+

Error Message is:

+
Input In [244], in predict_data(prediction_data, model_path, data_config, context)
+     25 new_model = Net(shape_preprocessed_data)
+     26 # load the previously saved state_dict
+---> 27 new_model.load_state_dict(torch.load("NetModel.pth"))
+     29 # check if predictions of models are equal
+     30 
+     31 # generate random input of size (N,C,H,W)
+     32 
+     33 # switch to eval mode for both models
+     34 model = model.eval()
+
+    RuntimeError: Error(s) in loading state_dict for Net:
+    size mismatch for conv1.weight: copying a param with shape 
+    torch.Size([1, 256, 1]) from checkpoint, the shape in current model is torch.Size([1, 494, 1]).
+
+How can I solve this?
+
","

You could reshape/downsample the input as the first step of the forward pass in your model. This can be done using the torch.nn.functional.interpolate function.

+

For example:

+
class Net(nn.Module):
+def __init__(self, shape):
+    super(Net,self).__init__()
+    self.input_shape = shape
+    self.conv1 = nn.Conv1d(shape,1,1)
+    self.batch1 = nn.BatchNorm1d(1)
+    self.avgpl1 = nn.AvgPool1d(1, stride=1)
+    self.fc1 = nn.Linear(1,3)
+
+#forward method 
+def forward(self,x):
+    x = torch.nn.functional.interpolate(x, size=self.input_shape)
+    x = self.conv1(x)
+    x = self.batch1(x)
+    x = F.relu(x)
+    x = self.avgpl1(x)
+    x = torch.flatten(x,1)
+    x = F.log_softmax(self.fc1(x))
+    return x
+
+

Your test images would then be downsampled to size 256 in order to be compatible with the model.

",python +"Multiple filter data dropdown table with plotly in python

I am currently trying to generate a table with multiple dropdown options (in a Jupiter Notebook). I have been able to create the scenario but the dropdown buttons work independently, meaning that if I select one dropdown from my 'Decision' dropdown with option 'A' and then select the other downtown 'Sex' with option 'Female' I either get option A or option 2 depending on the button last selected. However, what I really want is to have both filters applied at the same time. So I would get all Decisions 'A' that are 'Female' as filters for my table.

+

This is my code:

+
fig = go.Figure(go.Table(header={"values": df_dash.columns,'fill_color':'navy','align':'left',
+                                 'font':dict(color='white', size=12)}, 
+                         cells={"values": df_dash.T.values,'fill_color':'white','align':'left'}))
+fig.update_layout(
+    updatemenus=[
+        {
+            "y": 1 - (i / 5),
+            "buttons": [
+                {
+                    "label": c,
+                    "method": "restyle",
+                    "args": [
+                        {
+                            "cells": {
+                                "values": df_dash.T.values
+                                if c == "All"
+                                else df_dash.loc[df_dash[menu].eq(c)].T.values
+                            }
+                        }
+                    ],
+                }
+                for c in ["All"] + df_dash[menu].unique().tolist()
+                
+            ],
+            
+        }
+        for i, menu in enumerate(["Decision", "Sex",])
+    ]
+)
+
+

And this is how it looks:

+

+

Any ideas what am I doing wrong or what can I add to make both buttons actively filtering my df table at the same time?

","

Based on this answer in the plotly forums, you cannot create buttons that are dependent on each other.

+

The best you could probably do is create one dropdown with every possible combination in your current Decision and Sex dropdowns – which I understand probably isn't ideal.

+

If you are willing to use plotly-dash, then it is possible as you can create two dropdowns that are inputs to a basic callback that updates the fig, as shown in this example in the plotly-dash documentation

",python +"Not able to access child window using pywinauto

Control identifiers
+

+

I am trying to automate the process to decrypt the file using kleopatra application using pywinauto library. I'm able to connect and the access the element from the main window, but not able to get hold of the new window that pops up.

+

I want to access the new windows element and open a file from that window whose title is "Select One or More Files to Decrypt and/or Verify".

+

Here is what I'm doing in the code, but getting the error.

+
import pywinauto
+app = pywinauto.application.Application(backend='uia').start(r"C:\Program Files (x86)\Gpg4win\bin\kleopatra.exe").connect(title="kleopatra",timeout=100)
+
+fileMenu = app.kleopatra.child_window(title="File", auto_id="MainWindow#1.file.file", control_type="MenuItem").wrapper_object()
+
+fileMenu.click_input()
+
+# app.kleopatra.print_control_identifiers()
+
+decryptMenu = app.kleopatra.child_window(title="Decrypt/Verify...", auto_id="KXMLGUIClient-KActionCollection.file_decrypt_verify_files", control_type="MenuItem")
+
+decryptMenu.click_input()
+
+selectFileWindow = pywinauto.application.Application(backend='uia').connect(title = "Select One or More Files to Decrypt and/or Verify")
+
+
+
+

How can I connect to new window?

+

Error
+

","

Try this - +selectFileWindow = app.window(title = "Select One or More Files to Decrypt and/or Verify")

",python +"How to insert variable length list into string

I have what I think is a basic question in Python:

+

I have a list that can be variable in length and I need to insert it into a string for later use. +Formatting is simple, I just need a comma between each name up to nameN and parenthesis surrounding the names.

+
List = ['name1', 'name2' .... 'nameN']
+string = "Their Names are <(name1 ... nameN)> and they like candy.
+
+

Example:

+
List = ['tom', 'jerry', 'katie']
+print(string)
+Their Names are (tom, jerry, katie) and they like candy.
+
+

Any ideas on this? Thanks for the help!

","
# Create a comma-separated string with names
+the_names = ', '.join(List) # 'tom, jerry, katie'
+
+# Interpolate it into the "main" string
+string = f"Their Names are ({the_names}) and they like candy."
+
",python +"How to return a big number in a plain format?

I want to return a big number in a plain format but instead I'm getting this:

+
>>> x=1000000000000000000000000000000
+>>> int(1*x/100) # try to get 1% of x
+9999999999999999583119736832 # <------------ here
+
+

I was expecting 10000000000000000000000000000, how do I achieve this?

","

You can use decimal to handle the decimal point more precisely.

+

It provides fast correctly-rounded decimal floating point arithmetic. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. Decimal numbers can be represented exactly and in decimal floating point.

+
from decimal import Decimal
+x = Decimal(1000000000000000000000000000000)
+print(int(1*x/100))  # 10000000000000000000000000000
+
",python +"List Comprehension for List of Dictionary to get Values Separately for Each Key

I want to get the city names and their respective population in separate list from a given list of dictionary. I have achieved this using naive method and using map() function as well but I need it to be executed using List Comprehension technique. I have tried below code but it is not giving proper output. What modifications should I do, please comment. Thanks.

+
towns = [{'name': 'Manchester', 'population': 58241}, 
+         {'name': 'Coventry', 'population': 12435}, 
+         {'name': 'South Windsor', 'population': 25709}]
+
+print('Name of towns in the city are:', [item for item in towns[item]['name'].values()])
+print('Population of each town in the city are:', [item for item in towns[item]['population'].values()])
+
+

** Expected Output **

+

Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']

+

Population of each town in the city are: [58241, 12435, 25709]

","

try this :

+
towns = [{'name': 'Manchester', 'population': 58241}, 
+         {'name': 'Coventry', 'population': 12435}, 
+         {'name': 'South Windsor', 'population': 25709}]
+
+print('Name of towns in the city are:',
+      [town['name'] for town in towns])
+print('Population of each town in the city are:',
+      [town['population'] for town in towns])
+
+

output:

+
Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']
+Population of each town in the city are: [58241, 12435, 25709]
+
",python +"Find counts of duplicates in list of sets

Hi i have to check the overlapping and duplicate of string from the data , i could do it can anyone help me to find the duplicate of string .I have this data s = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")] and i done the overlap part but theduplicate check odf string i need help .

+
def overlap(a, b) -> bool:
+  a_start, a_end, _ = a
+  b_start, b_end, _ = b
+  return a_start < b_end and b_start < a_end
+ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")]
+overlaps = set()
+for idx_a in range(len(ls)):
+    for idx_b in range(len(ls)):
+        if idx_a != idx_b:  
+            if overlap(ls[idx_a], ls[idx_b]):
+                overlaps.add(ls[idx_a])
+                overlaps.add(ls[idx_b])
+
+print(f"Number of overlaps: {len(overlaps)}")
+
","

It seems like you don't need to use set in case you need only number of overlaps.

+

I would solve your problem like this:

+
def is_overlapped(a, b) -> bool:  # changed the name for readability
+    a_start, a_end, _ = a
+    b_start, b_end, _ = b
+    return a_start < b_end and b_start < a_end
+ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")]
+overlaps = 0 # int instead of set
+for idx_a, value_a in enumerate(ls):  # this is more pythonic way to access the index and item at the same time
+    for idx_b, value_b in enumerate(ls):
+        if idx_a != idx_b:
+            if is_overlapped(value_a, value_b):
+                overlaps += 1
+print(f"Number of overlaps: {overlaps}")
+
",python +"How to reshape a (x, y) numpy array into a (x, y, 1) array?

How do you reshape a (55, 11) numpy array to a (55, 11, 1) numpy array?

+

Attempts:

+
    +
  • Simply doing numpy_array.reshape(-1, 1) without any loop produces a flat array that is not 3D.
  • +
  • The following for loop produces a "cannot +broadcast error":
  • +
+
for i in range(len(numpy_array)):
+       numpy_array[i] = numpy_array[i].reshape(-1, 1)
+
","

Maybe you are looking for numpy.expand_dims(https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html)?

+
import numpy
+a = numpy.random.rand(55,11)
+print(a.shape) # 55,11
+print(numpy.expand_dims(a, 2).shape) # 55, 11, 1
+
",python +"How to get my messages to show on Django for a registration form?

I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can't seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the views.py page (from django.contrib import messages) and I think my setting.py is all configured correct: setting.py

+

Here is my views.py code:

+
def register(request):
+if request.method == "GET":
+    register_form = RegisterForm()
+    return render(request, "main/register.html", {
+        'form': register_form
+    })
+else:
+    register_form = RegisterForm(request.POST)
+    if register_form.is_valid():
+        first_name = request.POST['first_name']
+        last_name = request.POST['last_name']
+        username = request.POST['username']
+        email = request.POST['email']
+        password = request.POST['password']
+        confirm_password = request.POST['confirm_password']
+
+
+        if password == confirm_password:
+            if User.objects.filter(email=email).exists():
+                    messages.info(request, 'Email or user name Already taking')
+                    return redirect('register')
+            elif User.objects.filter(username=username).exists():
+                    messages.info(request, 'username is taken')
+                    return redirect('register')
+            else:
+                User.objects.get_or_create(username=username, 
+                first_name=first_name, last_name=last_name, email=email, 
+                password=password)
+                
+                return redirect('main/login.html')
+        else:
+            messages.error(request, 'Password Not Match')
+            return redirect('register')   
+        #return redirect ('/')     
+    else:
+        return render(request, 'main/login.html')
+
+

and this is my register.html form:

+
          <form action="{% url 'register' %}" method="POST">
+                {% csrf_token %}
+                <fieldset>
+                    <legend>Enter details</legend>
+                    <ul>
+                        {{ form.as_table }}
+                    
+                        <button type="submit" class="mybutton _f-purple" value="submit">Register</button>
+                    </ul>
+                </fieldset>
+            </form>
+
","

I think this is what you need.

+
          {% if messages %}
+            <div class="mgs-area">
+                <div class="mgs-item">
+                {% for message in messages %}
+                <span {% if message.tags %} class="nav_item message-{{ message.tags }} " {% endif %}> {{ message }} </span>
+                {% endfor %}
+                </div>
+            </div>
+            {% endif %}
+
+

You can style success or error messages differently.

+
+

class="nav_item message-{{ message.tags }}

+
",python +"How to find the most common name in 2 related lists

I would like to seek help from the community.. I have 2 related lists here:

+
names = ['alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady']
+votes = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True]
+
+

The votes list is a result of a facial recognition algorithm matching from the corresponding names list. Then I shall link each True vote to the corresponding name, and find the most frequently occurred name to be the final 'winner'.

+

I have tried 2 ways:

+
characters = {}
+for name, vote in list(zip(names, votes)):
+    if vote == True:
+        characters[name] = characters.get(name, 0) + 1
+#print(characters)
+print(max(characters, key=characters.get))
+
+

The output is 'owen_grady'

+
from collections import Counter
+
+characters = [name for name, vote in list(zip(names, votes)) if vote == True]
+#print(characters)
+print(Counter(characters).most_common()[0][0])
+
+

The output is also 'owen_grady'. Which way is more efficient: Dictionary? or List Comprehension with Counter?

+

My ultimate question: is there another way (the most efficient) to get the result? I would like the output to be just 'owen_grady'

","

You can use itertools.compress() to filter all false entries. Option with Counter should be most efficient, just use n argument in .most_common() to let it return a single pair.

+

Code:

+
from itertools import compress
+from collections import Counter
+
+names = ['alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady']
+votes = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True]
+
+most_common = Counter(compress(names, votes)).most_common(1)[0][0]
+# Or with some syntax sugar:
+# [(most_common, _)] = Counter(compress(names, votes)).most_common(1)
+
+
+

Upd. I've made some benchmarks and it seems like for this particular case slightly optimized first method demonstrates better performance:

+
from itertools import compress
+
+names = ['alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'alan_grant', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'claire_dearing', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ellie_sattler', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'ian_malcolm', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'john_hammond', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady', 'owen_grady']
+votes = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True]
+
+characters = list(compress(names, votes))
+most_common = max(set(characters), key=characters.count)
+
+
+

You can help my country, check my profile info.

",python +"Solidity ""require"" error message in Python

I am having trouble displaying the error message from the smart contract's require method in my Python console. I am using the web3.py module to interact with the contract.

+

Here is the smart contract code:

+
function burn(uint258 amount) public returns(bool){
+    require(balance[msg.sender]>=amount, "Not enough balance to burn");
+    ...
+}
+
+

Calling this method trying to trigger the require restriction does nothing in the console. Checking on etherscan the transaction is not completed (which is the desired behaviour). I found some solutions online about Remix, but I want the error message to be displayed in my python code.

+

Is the error message encrypted in some response like the hash of the transaction, or is there another way to get the message ?

","

To get the revert reason of a transaction, you can use fetch_transaction_revert_reason function from web3-ethereum-defi library.

",python +"Runtime variable for Oracle DATE type in Airflow

I'm trying to define task that requires a run-time parameter (let's call it 'batch_dt') in Apache Airflow.
+I'm using OracleStoredProcedureOperator and the parameter of the procedure is of database type date.

+
procedure use_dates (
+    i_date  in date,
+    i_date2 in date,
+    i_date3 in date
+  );
+
+

However I'm having hard time defining this parameter as runtime variable. I could use an exactly formatted string for particular database but don't want to depend on current NLS setting in the database.

+
    +
  1. Airflow macros don't work {{ dag_run.conf['batch_dt'] }} or even
    {{ macros.datetime.strptime(dag_run.conf['batch_dt'], '%Y-%m-%d') }} +returns always a string resulting in

    +

    ORA-01861: literal does not match format string

    +
  2. +
  3. Using to_date('{{ dag_run.conf['batch_dt'] }}', 'DD-MM-YYYY') results in

    +

    ORA-01858: a non-numeric character was found where a numeric was expected

    +
  4. +
  5. When I define date.today() right in the task, it works fine, however I need to use run-time variable.

    +
  6. +
+
res_task = OracleStoredProcedureOperator(
+    task_id = 'mytask',
+    procedure = 'use_dates',
+    parameters = 
+        {"i_date": date.today(), #works but is not runtime
+        "i_date2": "to_date('{{ dag_run.conf['batch_dt'] }}', 'DD-MM-YYYY')", 
+        #returns a string "to_date('13-06-2022', 'DD-MM-YYYY')" which results in ORA-01858: a non-numeric character was found where a numeric was expected
+        "i_date3": "{{ macros.datetime.strptime(dag_run.conf['batch_dt'], '%Y-%m-%d' ) }}"
+        #returns a string '2022-06-13 00:00:00' which results in ORA-01861: literal does not match format string
+        }
+    )
+
+

I was thinking about macro that returns a datetime object at runtime, however it seems macros can return only strings. Any idea how this can be achieved?

","

Jinja templating, used in Apache Airflow, renders template fields as strings by default. Therefore the result of your strptime method call is converted into string when rendered.

+

To override this behavior and be able to render native Python objects instead of plain strings, you have to set DAG's render_template_as_native_obj option to True (default option's value is False).

+
with DAG(
+        'USE_DATES',
+        description='TEST DATE INPUT RUNTIME DAG',
+        ...
+        render_template_as_native_obj=True
+) as dag:
+...
+
+

Your OracleStoredProcedureOperator call should now function as expected, passing Jinja rendered parameters as native Python objects (datetime in this case).

+

For more information please refer to official Airflow's documentation: +https://airflow.apache.org/docs/apache-airflow/stable/concepts/operators.html#rendering-fields-as-native-python-objects

",python +"Define and use class methods from variable

Let's say I have two classes with some methods.

+

First class:

+
@dataclass
+class MyFirstClass:
+    y1: List[float]
+    y2: List[float]
+    
+    @property
+    def my_func1(self) -> List[float]:
+        return self.y1-self.y2
+
+    @property
+    def my_func2(self) -> List[float]:
+        return self.y1+self.y2
+
+    @property
+    def my_func3(self) -> List[float]:
+        return self.y1*self.y2
+
+

Second class:

+
@dataclass
+class MySecondClass:
+    list_vals: List[float]
+    
+    @property
+    def norm1(self):
+        return self.list_vals
+ 
+    @property
+    def norm2(self):
+        return self.list_vals / numpy.mean(self.list_vals)
+
+

So my question is two fold. +Say in my main I have something like:

+
def main():
+    FUNCTION = <?>
+    NORM = <?>
+
+    y1 = [1, 2, 3, 4, 5]
+    y2 = [3, 4, 5, 6, 7]
+
+    test = MyFirstClass(y1, y2).my_func1
+
+

Then I just call MyFirstClass with the y1 and y2 lists and get an output.

+

But as can be seen in the beginning of main I have FUNCTION and NORM. Is there any way to call MyFirstClass from there, and then reuse it all through main, i.e. something like:

+
FUNCTION = MyFirstClass.my_func1
+
+test = FUNCTION(y1, y2)
+
+

This doesn't work obviously. So how can one do that ?

+

Also, and this is probably a build upon the above, how can I, once again, choose the norm function to be used in the other class ? For instance, if I update MyFirstClass a bit to:

+
@dataclass
+    class MyFirstClassUpdated:
+        y1: List[float]
+        y2: List[float]
+        norm: NORM
+        
+        @property
+        def my_func1(self) -> List[float]:
+            return norm(self.y1)-norm(self.y2)
+    
+        @property
+        def my_func2(self) -> List[float]:
+            return norm(self.y1)+norm(self.y2)
+    
+        @property
+        def my_func3(self) -> List[float]:
+            return norm(self.y1)*norm(self.y2) 
+
+

And then when the class is called it takes the NORM argument from the main function, i.e. something like:

+
FUNCTION = MyFirstClass.func1
+NORM = MySecondClass.norm1
+
+test = FUNCTION(y1, y2, NORM)
+
+

I have no idea if this is even possible without making the code "uglier".

","

You need to create an instance of MyFirstClass, and pass it as the self argument to the function.

+
FUNCTION = MyFirstClass.my_func1
+mfc = MyFirstClass(y1, y2)
+test = FUNCTION(mfc)
+
",python +"Python: removing objects from a list by attribute value
class MyClass():
+    def __init__(self, name, att1, att2):
+        ...
+
+myList = [MyClass("p1", 1, 1), MyClass("p2", 0, 0), MyClass("p3", 0, 1)]
+
+

Now I want to remove every object from myList if its att2 == 1.

","

Rather than removing the class instance from the list, construct a new list (list comprehension) that excludes unwanted classes. For example:

+
class MyClass():
+    def __init__(self, name, att1, att2):
+        self._name = name
+        self._att1 = att1
+        self._att2 = att2
+    def __repr__(self):
+        return f'{self._name=}, {self._att1=}, {self._att2=}'
+
+myList = [MyClass("p1", 1, 1), MyClass("p2", 0, 0), MyClass("p3", 0, 1)]
+
+myList = [c for c in myList if c._att2 != 1]
+
+print(myList)
+
+

Output:

+
[self._name='p2', self._att1=0, self._att2=0]
+
",python +"Use Conditional within Context Manger

I want to be able to do something like this:

+
file1 = 'data/f1.txt'
+file2 = None
+file3 = 'data/f3.txt'
+with open(file1) as f1, open(file2) as f2, open(file3) as f3:
+    for i in range(1000):
+        x,y,z = func(i)
+        if f1: f1.write(f"{x}\n")
+        if f2: f2.write(f"{y}\n")
+        if f3: f3.write(f"{z}\n")
+
+
+

So that output is only written to files if paths are provided.

+

I tried the following:

+
file1 = 'data/f1.txt'
+file2 = None
+file3 = 'data/f3.txt'
+with open(file1) if file1 else None as f1, open(file2) if file2 else None as f2, open(file3) if file3 else None as f3:
+    for i in range(1000):
+        x,y,z = func(i)
+        if f1: f1.write(f"{x}\n")
+        if f2: f2.write(f"{y}\n")
+        if f3: f3.write(f"{z}\n")
+
+

But I got TypeError: expected str, bytes or os.PathLike object, not NoneType.

+

Is there a simple, pythonic way to achieve this?

+

Thanks.

","

By the time you've invented identifiers file{1,2,3}, +that's starting to be a Code Smell that you +really want to fill a container with files.

+

Create a class FilesWriter that is a context manager. +Pass in a bunch of filespecs. +It will simply discard any empty ones:

+
    self.fspec_to_file = {}
+    for fspec in fspecs:
+        if fspec is not None:
+            self.fspec_to_file[fspec] = open(fspec, 'w')
+
+

Now your instance is responsible for closing those +when the with calls your __exit__ method.

+

In the body of the with, +caller will either invoke a write_to_all(s: str) method you provide, +or will use the elements of fspec_to_file as needed.

+

So calling sequence would look like:

+
    with FilesWriter([fspec1, fspec2, fspec3]) as fw:
+        for i in range(1000):
+            result = compute()
+            fw.write_to_all(result)
+
+

and upon leaving the block your __exit__ method does:

+
    for f in self.fspec_to_file.values():
+        f.close()
+
+

Strictly speaking .close() can fail, e.g. due to full disk. +Put it in a try block if needed.

+

If any open() fails, it might make sense to +close all previously opened files and die +with fatal error.

+

You seemed to need to know details about each open file. +But if not, feel free to convert that dict to +a simple set of open file handles.

",python +"Simple CNN Binary Classification Network with dataset consisting of more than 100000 image files

I am trying to build a simple CNN model for binary classification but the training dataset consists of over 100k of '.png' file. If I train the model by loading all the data at once, it will create a MemoryExhaustion Error. Can somebody help me to build the network to deal with such huge dataset?

","

You can stream with yield statement.

+
def load_at_once(image_names):
+    return [load(image_name) for image_name in image_names] # memory exhaust
+
+def load_stream(image_names):
+    for image_name in image_names:
+        yield load(image_name)
+
+

You can iterate images with for statement. load_stream function will load image one by one and prevent memory exhaust if you don't try saving all images in memory.

+

Of course streaming is slower than loading everything to memory when you use images more than one time, because it will read image every time you want to use.

",python +"converting 3 digit integers in a column to dates?

I have an a column with 3 digit integers as m/dd. e.g.

+
410
+417
+505
+522
+
+

I want to convert them to

+
2022-04-10
+2022-04-17
+2022-05-05
+2022-05-22
+
+

How can I accomplish this?

","

You can use .apply() to format the integers as strings, and then use pd.to_datetime() to turn those strings into dates. Notably, this approach works even if the month is represented by two digits (i.e. October, November, or December):

+
import pandas as pd
+
+df = pd.DataFrame([410, 417, 505, 522, 1222], columns=["dates"])
+df["dates"] = df["dates"].apply(lambda x: "{:02}/{:02}/2022".format(x // 100, x % 100))
+df["dates"] = pd.to_datetime(df["dates"], format="%m/%d/%Y")
+
+

This outputs:

+
       dates
+0 2022-04-10
+1 2022-04-17
+2 2022-05-05
+3 2022-05-22
+4 2022-12-22
+
",python +"Communicating Python Exception to a shell script

I have a test.py python script which contains following code.

+
def f(x):
+    if x < 0:
+        raise Exception("negative number")
+
+    else: 
+        return x
+
+

I have written another shell script test.sh that runs the python function inside it. The code is as follows

+
#!/bin/bash
+X=$1
+
+y=$(python3 -c "from test import f; print(f(`echo $X`))")
+echo this is y: $y
+
+

The shell script works fine when input is positive i.e bash test.sh 1. This gives this is y: 1.

+

However, when the input is negative i.e bash test.sh -1. It gives a python traceback.

+
Traceback (most recent call last):
+  File "<string>", line 1, in <module>
+  File "/home/user/test.py", line 4, in f
+    raise Exception("negative number")
+Exception: negative number
+this is y:
+
+

Question: what changes should be made to avoid the above output (avoid printing traceback).

+

Expected output:

+
this is y: exception
+
","

Use a try/except that prints exception.

+
y=$(python3 -c "from test import f
+try: print(f(`echo $X`))
+except: print('exception')")
+
",python +"Create Xpath using scrapy
import scrapy
+from scrapy.http import Request
+from scrapy.crawler import CrawlerProcess
+
+class TestSpider(scrapy.Spider):
+    name = 'test'
+    start_urls = ['https://rejestradwokatow.pl/adwokat/list/strona/1/sta/2,3,9']
+    custom_settings = {
+        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
+        'DOWNLOAD_DELAY': 1,
+        'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
+        }
+
+
+    def parse(self, response):
+        books = response.xpath("//td[@class='icon_link']//a//@href").extract()
+        for book in books:
+            url = response.urljoin(book)
+            yield Request(url, callback=self.parse_book)
+
+  
+
+    def parse_book(self, response):
+        wev={}
+        d1=response.xpath("//*[@class='line_list_K']//div//span")
+        for i in range(len(d1)):
+            if 'Status:' in d1[i].get():
+                d2=response.xpath("//div["+str(i+1)+"]//text()").get()
+                print(d2)
+
+

I will get the status value but they will give me empty output this is page link https://rejestradwokatow.pl/adwokat/abramska-danuta-51494

+

","

Why not selecting your element more specific by its text and getting the text from its next sibling:

+
//span[text()[contains(.,'Status')]]/following-sibling::div/text()
+
+

Example: http://xpather.com/ZUWI58a4

+

To get the email:

+
//span[text()[contains(.,'Email')]]/following-sibling::div/(concat(@data-ea,'@',@data-eb))
+
",python +"How can i print the specific line number of a json file

I am using python to load a json file and using jsonschema to print errors according to the schema i have prepared.

+

My question is how do i print a specific line of a json file from a loop:

+
errors = sorted(validator.iter_errors(jsonData[a]), key=lambda e: e.path)
+for error in errors:
+    print(error.message, sep=", ")
+
+

The output i get is 'lending_details' is a required property which is the error.message.

+

What i want is to print: On line number 4 ,'lending_details' is a required property

+

Is there a way to count and display the specific line number of a json file?

","

In general, no, because by the time the JSON Schema evaluator sees the data instance, the data has been parsed from JSON text into a data structure and the line number information has been lost.

+

To make this work, you will need to have a JSON decoder that can associate line numbers with each section of the data in a way that the JSON Schema evaluator can later make use of it when generating its errors. For example, I could see a decoder turning this JSON:

+
{
+  "foo": {
+    "hello": [
+      "a",
+      "b",
+      "c"
+    ]
+  "bar": true
+}
+
+

into this line number mapper:

+
{
+  "": 1,
+  "/foo": 2,
+  "/foo/hello": 3,
+  "/foo/hello/0": 4,
+  "/foo/hello/1": 5,
+  "/foo/hello/2": 6,
+  "/bar": 8
+}
+
+

..and then when the JSON Schema evaluator is generating an error at data instance "/bar", we can use this lookup table to insert "..at line 8" into the error.

",python +"I'm trying to make a secure password generating program. Well, I was debugging the Index Error that I get when I ran this incomplete program

I seem to have run into wall here. It keeps showing an Index Error at line "unordered_letter[letter] = random.choice(letters[nr_letters - 1])". My inexperienced eyes are unable to catch the issue so kindly help with the same. Thanks in advance!

+
import random
+
+letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
+           'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
+           'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
+numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
+symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
+
+print("Welcome to the PyPassword Generator!")
+nr_letters = int(input("How many letters would you like in your password?\n"))
+nr_symbols = int(input(f"How many symbols would you like?\n"))
+nr_numbers = int(input(f"How many numbers would you like?\n"))
+
+unordered_letter = []
+
+for letter in range(0, nr_letters):
+    unordered_letter[letter] = random.choice(letters[nr_letters - 1])
+print(unordered_letter)
+
","

Change:

+
for letter in range(0, nr_letters):
+    unordered_letter[letter] = random.choice(letters[nr_letters - 1])
+
+

To this:

+
for letter in range(0, nr_letters):
+    unordered_letter.append(random.choice(letters))
+
+

Change #1:

+

Use the .append() function. Your original code produces an error since you are trying to set a value to a nonexistent index since your array is empty.

+

Change #2:

+

Change random.choice(letters[nr_letters - 1]) to random.choice(letters) if you want to produce a variety of letters rather than one singular letter. Your original code will only append the nr_letters - 1th element of letters, while this new code will choose random elements from letters.

+

Use the same process for symbols and numbers.

",python +"Is there any method to transfer files between docker container using python scripts?

Project in container A and has a function to restore data,which may need to send files to container B +Or I should not do like this?

","

try using volume option when you run container A & B

+

docker run -t imagename:tag -v 'data path shared on local': path data on container A container A

+

docker run -t imagename:tag -v 'data path shared on local': path data on container B container B

+

when restore new file in container A in access in path local and container B could used it

",python +"How do you use patch() as a context manager?

I have a class that mocks database functionality which does not subclass Mock or MagicMock because it defines its own __init__ method:

+
class DatabaseMock():
+    def __init__(self, host=None):
+        self.host = host
+        self.x = {}
+   
+    # other methods that mutate x
+
+

There is a function I want to test that makes an API call to the real database, so I patched it out:

+
class TestFunctions():
+    def test_function(self):
+        with patch("path.to.database.call", DatabaseMock) as mock:
+            result = function_i_am_testing()
+            assert mock.x == result
+
+

There is a field of the DatabaseMock called x, but in the patch context, mock.x returns +an AttributeError. This leads to me believe mock is not really an instance of DatabaseMock. Also, I had tried making x a class level object which does make x visible, but its state would persist through separate test calls which I do not want. +What is mock and how can I reference the mocked object in the context?

","

I have figured out the issue. When patch is given a class, it will return a class, not an object of that class. So mock in my example is not a DataBaseMock object, but a reference to the class. This is why class level variables are visible, but not object fields. In order get my desired functionality, I did this:

+
class TestFunctions():
+    def test_function(self):
+        with patch("path.to.database.call") as mock:
+            mock.return_value = DataBaseMock()
+            result = function_i_am_testing()
+            assert mock.return_value.x == result    
+
+

Now, mock is a MagicMock object, whose return value is the object I need.

",python +"Remove series border lines from plotly express area chart

px.area shows a line atop each area series. How can I remove it?

+

The documentation only shows how to remove lines from go.Scatter calls (with mode='none').

+

Here's an example (notebook), where I'd like to remove the dark blue and red lines atop the light blue and red areas, respectively (to avoid the perception that the red series is nonzero where it stacks atop the blue series):

+
import plotly.express as px
+
+px.area(y=[[1, 2, 3], [0, 0, 1]])
+
+

","

IIUC this is what you're looking for:

+
import plotly.express as px
+
+fig = px.area(y=[[1, 2, 3], [0, 0, 1]])
+
+

Before:

+

+

If you want lines same color as traces:

+
for i in range(len(fig['data'])):
+  fig['data'][i]['line']['width']=0
+
+

+

If you want traces same color as lines:

+
fig.for_each_trace(lambda trace: trace.update(fillcolor = trace.line.color))
+
+

",python +"Create CSV output with an uneven dictionary of single values and lists

I am using python and running my example on google colab. I am new to csv writing. +I want to csv write out like the following. +desired output example +The issue I am having is with my lists in 'add' and 'reg'. When I run my example code I get the following. +my output +What should I do to get my desired output? Below is my attempt. If there is another post that has a similar situation as mine could you link it as I have already tried searching and could not find someone with the the issue as mine.

+
d = [{'local_date': '12/16/2022', 'local_time': '12:00', 'add':[2, 8, 22, 17], 'reg':[1001, 1002, 1003, 1004] }]
+fields = ['local_date', 'local_time', 'add', 'reg']
+
+with open("tester.csv", "w") as outfile:
+  writer = csv.DictWriter(outfile, fieldnames = fields)
+  writer.writeheader()
+  writer.writerows(d)
+
","

using csv

+
import csv
+
+d = [{'local_date': '12/16/2022', 'local_time': '12:00', 'add':[2, 8, 22, 17], 'reg':[1001, 1002, 1003, 1004]}]
+
+fields = ['local_date', 'local_time', 'add', 'reg']
+
+# we parse the d list to get the create new row with each add, reg value
+data = [{**dat, 'add':add, 'reg':reg} for dat in d for add, reg in zip(dat['add'], dat['reg'])]
+
+with open("tester.csv", "w") as outfile:
+  writer = csv.DictWriter(outfile, fieldnames = fields)
+  writer.writeheader()
+  writer.writerows(data)
+
+

using pandas

+
import pandas as pd
+
+d = [{'local_date': '12/16/2022', 'local_time': '12:00', 'add':[2, 8, 22, 17], 'reg':[1001, 1002, 1003, 1004]}]
+
+df = pd.DataFrame(d).explode(['add', 'reg'])
+
+df.to_csv('tester.csv', index=False)
+
",python +"Parse all valid datetime strings in json recursively

I have a json blob of the following format. Is there a way to identify all strings which match the format

+
%Y-%m-%dT%H:%M:%S
+
+

And convert them to datettime strings

+
{
+    "data":[
+        {
+            "name":"Testing",
+            "dob":"2001-01-01T01:00:30"
+        },
+        {
+            "name":"Testing2",
+            "dob":"2001-01-01T01:00:30",
+            "licence_info":{
+                "issue_date":"2020-01-01T01:00:30"
+            }
+        }
+    ]
+}
+
","

The easiest way to do this is to parse each value and attempt to convert it to a datetime. You could do something like this:

+
from datetime import datetime
+
+def convert_dates(value):
+    if isinstance(value, dict):
+        return { k : convert_dates(v) for k, v in value.items() }
+    elif isinstance(value, list):
+        return [ convert_dates(v) for v in value ]
+    else:
+        try:
+            dt = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
+            return dt
+        except ValueError:
+            return value
+
+jstr = '''
+{
+    "data":[
+        {
+            "name":"Testing",
+            "dob":"2001-01-01T01:00:30"
+        },
+        {
+            "name":"Testing2",
+            "dob":"2001-01-01T01:00:30",
+            "licence_info":{
+                "issue_date":"2020-01-01T01:00:30"
+            }
+        }
+    ]
+}
+'''
+d = json.loads(jstr)
+convert_dates(d)
+
+

Output:

+
{
+ 'data': [
+    {'name': 'Testing',
+     'dob': datetime.datetime(2001, 1, 1, 1, 0, 30)
+    },
+    {'name': 'Testing2',
+     'dob': datetime.datetime(2001, 1, 1, 1, 0, 30),
+     'licence_info': {'issue_date': datetime.datetime(2020, 1, 1, 1, 0, 30)}
+    }
+  ]
+}
+
",python +"i get an empty list when scraping a website
from bs4 import BeautifulSoup
+import requests
+
+link = requests.get("https://www.upwork.com/nx/jobs/search/?q=web%20scraping&sort=recency")
+source = link.content
+soup = BeautifulSoup(source, "lxml")
+
+title = soup.find_all("h4", {"class": "my-0 p-sm-right job-tile-title"})
+print(title)
+
+

i am trying to scrap the job titles but the problem is that i get an empty list +but in other websites it work just fine

+

help me please

","

You got an empty list because this data loads from a different request. You can see it if opens the console in your browser, network tab

+

Needed request

",python +"Easy Leetcode question, I don't understand what I'm doing wrong

I'm beginner in coding and I am working on some easy leetcode questions along the way. The question is converting roman numerals to integers and when I run this code, it says the "string index out of range". Rather than looking for other answers, I wanted to understand what I did wrong. I appreciate the help!

+
s = "CCXLVII"
+
+roman_dict = {
+    'C' : 100,
+    'L' : 50,
+    'X' : 10,
+    "V" : 5,
+    "I" : 1
+}
+
+temp = 0
+
+for i in range(len(s)):
+    if roman_dict[s[i]] > roman_dict[s[i+1]] and i + 1 < len(s): #string index out of range
+        temp = temp - roman_dict[s[i]]
+    else:
+        temp = temp + roman_dict[s[i]]
+
","

You just have to swap the order of the conditionals:

+

Change:

+
if roman_dict[s[i]] > roman_dict[s[i+1]] and i + 1 < len(s):
+
+

To:

+
if i + 1 < len(s) and roman_dict[s[i]] > roman_dict[s[i+1]]:
+
+

This makes it so that the boundary check is done before attempting to access the i+1 index. Python will short-circuit the condition as soon as i + 1 >= len(s) is true

",python +"How to persist an inmemory monetdbe db to local disk

I am using an embedded monetdb database in python using Monetdbe. +I can see how to create a new connection with the :memory: setting

+

But i cant see a way to persist the created database and tables for use later. +Once an in memory session ends, all data is lost.
+So i have two questions:

+
    +
  1. Is there a way to persist an in memory db to local disk +and
  2. +
  3. Once an in memory db has been saved to local disk, is it possible to load the db to memory at a later point to allow fast data analytics. At the moment it looks like if i create a connection from a file location, then my queries are reading from local disk rather memory.
  4. +
","

It is a little bit hidden away admittedly, but you can check out the following code snipet from the movies.py example in the monetdbe-examples repository:

+
import monetdbe
+
+database = '/tmp/movies.mdbe'    
+
+with monetdbe.connect(database) as conn:
+    conn.set_autocommit(True)
+    conn.execute(
+        """CREATE TABLE Movies
+        (id SERIAL, title TEXT NOT NULL, "year" INTEGER NOT NULL)""")
+
+

So in this example the single argument to connect is just the desired path to your database directory. This is how you can (re)start a database that stores its data in a persistent way on a file system.

+

Notice that I have intentionally removed the python lines from the example in the actual repo that start with the comment # Removes the database if it already exists. Just to make the example in the answer persistent.

+

I haven't run the code but I expect that if you run this code twice consecutively the second run wil return a database error on the execute statement as the movies table should already be there.

+

And just to be sure, don't use the /tmp directory if you want your data to persist between restarts of your computer.

",python +"How to parse JSONP response in python?

+

How can i parse JSONP response, i tried json.loads(), but it will never work for JSONP

","

By the reading following

+
+

JSONP is JSON with padding, that is, you put a string at the beginning +and a pair of parenthesis around it.

+
+

I tried to remove padding from the string and used json.loads()

+
from json import loads
+response = requests.get(link)
+startidx = response.text.find('(')
+endidx = response.text.rfind(')')
+data = loads(response.text[startidx + 1:endidx])
+
+

it's working

",python +"OpenCV Limit FPS While Running

I'm using opencv python to do image processing. When I measure the FPS it's not stable. Sometimes FPS is 10 sometimes 12. I want to make FPS stable at 9 frame per second. Is there anyway to do that?

+

EDIT: I'm using my laptop's webcam. But I also have an Hikvision IP Camera. I need to do that independent from camera. +Here is how I'm measuring FPS.

+
while True:
+
+      timer = cv2.getTickCount()
+      ret, img = cap.read()
+
+      fps = cv2.getTickFrequency()/(cv2.getTickCount()-timer)
+      cv2.putText(img, str(int(fps)), (75, 75),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
+      cv2.imshow("Tracking", img)
+
+      if cv2.waitKey(1) & 0xFF == ord('q'):
+         break
+
+cap.release()
+cv2.destroyAllWindows()
+
","

I don't know why you need that but here is your answer:

+

You can not expect a camera to give always exact/constant fps because of some low level device design configurations. If 30 fps written in a camera spec, its fps can vary 30~33.

+

What you can do is that you can pull 9 frames from the buffer in a sec and ignore the extra frames which camera feeds.

+

Here is a good discussion to check.

",python +"Get elements from list in python by ¿index?

I want to get the ids from this list to put them in an other to use

+
random.choice(list)
+
+
+

[<Member id=986970159736586261 name='Nasgar-Bot' discriminator='5799' +bot=True nick=None guild=>, <Member +id=568157479020527636 name='ElmerKao' discriminator='0058' bot=False +nick=None guild=>]

+
+

How can i get the id from here and put them into a list to use that command?

","

The way you worded you problem wasn't very clear but I think I understood, you want to add a user id in a list.Let's imagine the user sent a message. that you passed to your function with ctx.

+
ids = []
+discord_id = ctx.message.author.id
+ids.append(discord_id)
+
+

I am not sure if this answer is clear enough but try to give more context when asking a question.

+

PS: don't use list as a name for a list, it will break your code.

",python +"Merging pandas dataframes to fill in the gaps

Have been struggling with this for a bit today. I've got a master dataframe that is missing some values, and a secondary one that has these values which I would like to add in. The key to match on is column 1.

+
d1 = {1:['Test','Test1','Test2'], 2:['A','B','C']}
+d2 = {1:['Something','Test','Test1','Test2','Test3','Test4'], 2:['z',None,None,None,'x','y'],3:['Blah','Blah','Blah','Blah','Blah','Blah']}
+
+df1 = pd.DataFrame(data=d1)
+df2 = pd.DataFrame(data=d2)
+
+df1
+       1  2
+0   Test  A
+1  Test1  B
+2  Test2  C
+
+df2
+           1     2     3
+0  Something     z  Blah
+1       Test  None  Blah
+2      Test1  None  Blah
+3      Test2  None  Blah
+4      Test3     x  Blah
+5      Test4     y  Blah
+
+
+
+

The outcome I'm looking for is:

+
           1     2     3
+0  Something     z  Blah
+1       Test     A  Blah
+2      Test1     B  Blah
+3      Test2     C  Blah
+4      Test3     x  Blah
+5      Test4     y  Blah
+
+
+

Any ideas?

","

You can use a map and fillna:

+
df2[2] = df2[2].fillna(df2[1].map(df1.set_index(1)[2]))
+
+

Output:

+
          1  2     3
+0  Something  z  Blah
+1       Test  A  Blah
+2      Test1  B  Blah
+3      Test2  C  Blah
+4      Test3  x  Blah
+5      Test4  y  Blah
+
",python +"How to bypass Terms and Conditions agreement with Beautiful Soup

I want to scrape this website: https://cage.dla.mil/Home/UsageAgree using Beautiful Soup. +What I'm doing:

+
import requests
+url = "https://cage.dla.mil/Home/UsageAgree"
+r = requests.get(url)
+soup = BeautifulSoup(r.content, "html.parser")
+print(soup)
+
+

which returns HTML from a cookie agreement page. +What I am then looking for is to bypass this to scrape the content of the actual page once we accept the cookies.

+

I followed this post: Scraping a webpage using Python (beautiful soup) that requires "I agree to cookies" button being clicked?

+

and did:

+
import requests
+url = 'https://cage.dla.mil/'
+s = requests.Session()
+s.cookies.update({'agree': 'True'})
+s.get(url)
+soup = BeautifulSoup(r.content, "html.parser")
+print(soup)
+
+

but I'm still getting the agreement page.

+

It seems that one of the cookies always gives a unique value. I'm not sure how to deal with this.

","

Well, this should work.

+
import requests
+from bs4 import BeautifulSoup
+
+headers = {
+    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0"
+}
+
+with requests.Session() as s:
+    token = (
+        BeautifulSoup(
+            s.get(
+                "https://cage.dla.mil/Home/UsageAgree",
+                headers=headers,
+            ).text,
+            "lxml",
+        ).select_one("form input")["value"]
+    )
+    payload = {
+        "__RequestVerificationToken": token,
+        "returningURL": "",
+    }
+    _ = s.post(
+        "https://cage.dla.mil/Home/UsageAgree",
+        data=payload,
+        headers=headers
+    )
+    soup = (
+        BeautifulSoup(
+            s.get("https://cage.dla.mil/", headers=headers).text,
+            "lxml",
+        ).select("#briefnewslist > div > p > em")
+    )
+    print("\n".join(p.getText(strip=True) for p in soup))
+
+

Output:

+
Scheduled Maintenance
+SAM Validation: Unable To Find A Matching Entity When Asked To Enter Or Validate My Entity Information
+SAM Validation: Continue A Registration Update Or Renewal If Validation Fails
+SAM.gov Registration for Financial Assistance
+Financial Assistance Update
+CAGE Expiration Date
+
",python +"How to extract GPS location from HEIC files?

I use the following code to extract GPS location both from JPG and HEIC files:

+
#coding=utf-8
+from PIL import Image
+from urllib.request import urlopen
+from PIL.ExifTags import TAGS
+from PIL.ExifTags import GPSTAGS
+
+from pillow_heif import register_heif_opener
+
+def get_exif(filename):
+    image = Image.open(filename)
+    image.verify()
+    return image._getexif()
+
+def get_geotagging(exif):
+    if not exif:
+        raise ValueError("No EXIF metadata found")
+
+    geotagging = {}
+    for (idx, tag) in TAGS.items():
+        if tag == 'GPSInfo':
+            if idx not in exif:
+                raise ValueError("No EXIF geotagging found")
+
+            for (key, val) in GPSTAGS.items():
+                if key in exif[idx]:
+                    geotagging[val] = exif[idx][key]
+
+    return geotagging
+
+register_heif_opener()
+
+my_image='IMG_9610.HEIC'
+#my_image='IMG_20210116_215317.jpg'
+
+exif = get_exif(my_image)
+labeled = get_geotagging(exif)
+print(labeled)
+
+

This code works well with JPEG files, but returns the following error with HEIC:

+
AttributeError: _getexif
+
+

If I add the following function

+
def get_labeled_exif(exif):
+    labeled = {}
+    for (key, val) in exif.items():
+        labeled[TAGS.get(key)] = val
+
+    return labeled
+
+

and replace '_getexif()' with 'getexif()' then it works for both files, but the data is encrypted there - 'GPSInfo': 1234 and get_geotagging() doesn't work for such exif.

+

How could I fix it?

","

UPDATED POST 06-12-2022

+

The code below is able to extract the GEO tagging information from a HEIC image file on my system.

+
from PIL import Image
+from pillow_heif import register_heif_opener
+
+
+def get_exif(filename):
+    image = Image.open(filename)
+    image.verify()
+    return image.getexif().get_ifd(0x8825)
+
+
+def get_geotagging(exif):
+    geo_tagging_info = {}
+    if not exif:
+        raise ValueError("No EXIF metadata found")
+    else:
+        gps_keys = ['GPSVersionID', 'GPSLatitudeRef', 'GPSLatitude', 'GPSLongitudeRef', 'GPSLongitude',
+                    'GPSAltitudeRef', 'GPSAltitude', 'GPSTimeStamp', 'GPSSatellites', 'GPSStatus', 'GPSMeasureMode',
+                    'GPSDOP', 'GPSSpeedRef', 'GPSSpeed', 'GPSTrackRef', 'GPSTrack', 'GPSImgDirectionRef',
+                    'GPSImgDirection', 'GPSMapDatum', 'GPSDestLatitudeRef', 'GPSDestLatitude', 'GPSDestLongitudeRef',
+                    'GPSDestLongitude', 'GPSDestBearingRef', 'GPSDestBearing', 'GPSDestDistanceRef', 'GPSDestDistance',
+                    'GPSProcessingMethod', 'GPSAreaInformation', 'GPSDateStamp', 'GPSDifferential']
+
+        for k, v in exif.items():
+            try:
+                geo_tagging_info[gps_keys[k]] = str(v)
+            except IndexError:
+                pass
+        return geo_tagging_info
+
+
+register_heif_opener()
+
+my_image = 'IMG_8362.heic'
+image_info = get_exif(my_image)
+results = get_geotagging(image_info)
+print(results)
+# x used to mask data
+{'GPSLatitudeRef': 'N', 
+'GPSLatitude': '(3x.0, 5x.0, 1x.0x)', 
+'GPSLongitudeRef': 'W', 
+'GPSLongitude': '(8x.0, 2x.0, 5x.2x)', 
+'GPSAltitudeRef': "b'\\x00'", 
+'GPSAltitude': '279.63243243243244', 
+'GPSSpeedRef': 'K', 
+'GPSSpeed': '0.04649941997239198', 
+'GPSImgDirectionRef': 'T', 
+'GPSImgDirection': '274.37165833514456', 
+'GPSDestBearingRef': 'T', 
+'GPSDestBearing': '27x.37165833514456', 
+'GPSDateStamp': '2022:06:12'}
+
+
----------------------------------------
+My system information
+----------------------------------------
+Platform:     Apple
+OS Version:   macOS Catalina 10.15.7
+Python: 3.9
+Pillow: 9.1.1
+pillow_heif: 0.3.0
+----------------------------------------
+
+

ORIGINAL POST 06-11-2022

+

The short answer is that Pillow does not currently support the High Efficiency Image Format (HEIF) file format.

+

Reference:

+ +

One of the workarounds for this issue is pyheif. This Python package has the functionality to covert a HEIC image to a JPEG one. After this transformation Pillow will be able to read the data from the image.

+

Another workaround for this format reading problem is piexif. Here is an answer that I posted on converting a TIFF file to a JPEG one for reading with Pillow.

+

You could also use ExifTool, which reads HEIC files out of the box. Using it is slightly more complicated, because it requires using subprocess.

",python +"Python function overloading recommended approach

Assume a function that takes an object as parameter. There could be various ways to express the parameter object creation, some of which expressive, and likely easier to be used.

+

To give a simple example, we have a function which takes DateTime. We also want to accept string representations of DateTime, if possible (for example '20220606').

+
# version 1, strict. must send a DateTime  
+def UsefulFunc(startdate: DateTime) -> None:
+    pass
+
+# version 2, allow more types, but loose on type hints
+def UsefulFunc(startdate: (DateTime, str)) -> None:
+    # check if type is str, convert to DateTime if yes
+    pass
+
+# version 3, multiple signatures to accept and call the base function 
+def UsefulFuncString(startdatestr: str) -> None:
+    # convert startdatestr to DateTime
+    UsefulFunc(startdate)
+
+# … …
+
+

What approach is recommended in Python (I come from C# background)? If there's no clear indication/ or decision is based on situation, what are the considerations?

","

After some research, and taking inspirations from the @Copperfield answer, I found an elegant solution to the problem.

+

Let's first rephrase the problem - we have a function that takes an object. We want to provide some overloads, which will do the validations/ conversions etc. and call the base function which accepts object. We also need to reject any call not following any function signature which are not implemented.

+

The library that I found very useful was multipledispatch. An easy example:

+
from multipledispatch import dispatch
+
+@dispatch(int, int)
+def add_nums(num1: int, num2: int) -> int:
+  return num1 + num2
+
+@dispatch(str, str)
+def add_nums(num1: str, num2: str) -> int:
+  # do some useful validations/ object transformations
+  # implement any intermediate logic before calling the base func
+  # this enables base function do it's intended feature rather than    
+  # implementing overloads 
+  return add_nums(int(num1), int(num2))
+
+
+

if we call add_nums(40, 15), we get 55 as the (int, int) version get called. add_nums('10', '15') get us 25 as expected as (str, str) version get called.

+

It becomes very interesting when we call add_nuns(10, 10.0) as this will fail saying NotImplementedError: Could not find signature for add_nums: <int, float>. Essentially any call not in (int, int) or (str, str) format, fail with NotImplementedError exception.

+

This is by far the closest behaviour of function overloading, when comparing with typed languages.

+

The only concern I have - this library was last updated on Aug 9, 2018.

",python +"Pyspark dataframe is changed while the 'write' function usage

This is a real mystery for me: when I try to write a pyspark df into Azure dataframe using jdbc, I run into a strange situation. While running the 'write' function my table is changed somehow without any reason, and sends to Azure wrong data. Afterwards it saves my pyspark df with the same wrong data. Here is a part of code I have written:

+
print(sparkDF_cleaned.show())
+sparkDF_cleaned.write \
+            .format("jdbc") \
+            .mode("overwrite")
+            .option("url", jdbcUrl) \
+            .option("dbtable", "dbo.upsert_test") \
+            .option("user", jdbcUsername) \
+            .option("password", jdbcPassword) \
+            .save() 
+print(f"data loaded to table {db_table_name}")
+print(sparkDF_cleaned.show())
+
+

Output is next:

+
sparkDF_cleaned : 
++------------+---+-----+----------+----------------------+
+|     id_date| id|value|     _date|datetime_of_extraction|
++------------+---+-----+----------+----------------------+
+|1 2022-05-01|  1|   17|2022-05-01|            2022-06-01|
+|1 2022-05-06|  1|    6|2022-05-06|            2022-06-13|
+|2 2022-05-02|  2|   10|2022-05-02|            2022-06-01|
+|3 2022-05-03|  3|   15|2022-05-03|            2022-06-01|
++------------+---+-----+----------+----------------------+
+
+data loaded to table upsert_test
+
+sparkDF_cleaned : 
++------------+---+-----+----------+----------------------+
+|     id_date| id|value|     _date|datetime_of_extraction|
++------------+---+-----+----------+----------------------+
+|1 2022-05-06|  1|    6|2022-05-06|            2022-06-13|
+|2 2022-05-02|  2|    5|2022-05-02|            2022-06-13|
++------------+---+-----+----------+----------------------+
+
+

Azure table recieves the data as it is in the second table. Dear colleges, why does it happen? +Thanks for your time in advance.

","

I can't still avoid the problem when using pyspark jdbc overwrite with pyspark transformed table.

+

Hovewer, I have decided to write pyspark table to local file, read saved data from the file and than post the data using the pyspark jdbc overwrite function.

+

It does not seem to be the best solution, hovewer, it works. If there will be better solutions, will be happy to read.

+
path = "*DataBricksWorkspace*/temp_table.json"
+    dbutils.fs.rm(path, True)
+    sparkDF.write.json(path) 
+
+    sparkDF_copy = spark.read.json(file)
+
+    sparkDF_copy.write.jdbc(url=jdbcUrl,
+                           table=db_table_name,
+                           mode="overwrite",
+                           properties=connectionProperties)
+
",python +"Making an effiecient combining and fill-up algorithm

I have a list of suitcases, each suitcase has a name and a weight associated to it. I want to write a function that groups these suitcases in a way together that their weights always forms a multiple of 8 and returns a list of the formed tuples. If there is a suitcase that can not be formed to a multiple of 8ths then that suitcase gets "filled up" with 1s (this should only be the last resort). So for example:

+
sc1 = suitcase("sc1", 5)
+sc2 = suitcase("sc2", 1)
+sc3 = suitcase("sc3", 3)
+sc4 = suitcase("sc4", 14)
+sc5 = suitcase("sc5", 4)
+sc6 = suitcase("sc6", 1)
+sc7 = suitcase("sc7", 8)
+sclist = [sc1,sc2,sc3,sc4,sc5,sc6,sc7]
+
+sorted_tuple = sort_suitcases(sclist)
+
+sorted_tuple = [(sc7),(sc1,sc3),(sc4,sc2,sc6),(sc5,{1,1,1,1})] # this is obviously only one of many possible combinations.
+# having only one big tuple would obviously also be a solution
+
+

My approach would be looping over each value and loop over each other value left in the list and see if their weight combined is %8, but I feel like this approach would be not very efficient with big data sets. Am I missing something?

","
    +
  1. Partition the suitcases into 8 groups, based on their weight % 8.
  2. +
  3. Pair up members of the groups to make sums that are multiples of 8: 1 & 7, 2 & 6, 3 & 5, 4 & itself.
  4. +
  5. Deal with those that couldn't be paired off (larger groups & filling-up)
  6. +
",python +"Easiest way to parse command line string to subprocess list?

I'm trying to figure out how to run this command using subprocess.run():

+
cmd = 'find / \( -path /mnt -prune -o -path /dev -prune -o -path /proc -prune -o -path /sys -prune \) -o ! -type l -type f -or -type d -printf "depth="%d/"perm="%m/"size="%s/"atime="%A@/"mtime"=%T@/"ctime"=%C@/"hardlinks"=%n/"selinux_context"=%Z/"user="%u/"group="%g/"name="%p/"type="%Y\\n'
+
+

I've put the command into a list, even removing items, etc:

+
cmd = [
+    'find',
+    '/',
+    '\( -path /mnt -prune -o -path /dev -prune -o -path /proc -prune -o -path /sys -prune \)',
+    '-o',
+    '! -type l',
+    '-type f',
+    '-or',
+    '-type d'
+]
+
+
+

I've tried running the command using /bin/bash:

+
cmd = '/bin/bash -c find / \( -path /mnt -prune -o -path /dev -prune -o -path /proc -prune -o -path /sys -prune \) -o ! -type l -type f -or -type d -printf "depth="%d/"perm="%m/"size="%s/"atime="%A@/"mtime"=%T@/"ctime"=%C@/"hardlinks"=%n/"selinux_context"=%Z/"user="%u/"group="%g/"name="%p/"type="%Y\\n'
+
+

Doesn't matter. Everything I've tried does not work. Either I get no output at all, or it lists the files in my home directory, or I get an error, e.g.: b'find: paths must precede expression: ! -type l\nUsage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]\n'

+

Is there any easy way to take a command that works at the command line and just parse the string into whatever list elements subprocess.run() wants?

","

Parsing With shlex.split()

+

After fixing the incorrect quotes in your printf string, we get:

+
cmd = r'''
+find / \( -path /mnt -prune -o -path /dev -prune -o -path /proc -prune -o -path /sys -prune \) -o ! -type l -type f -or -type d -printf 'depth=%d/perm=%m/size=%s/atime=%A@/mtime=%T@/ctime=%C@/hardlinks=%n/selinux_context=%Z/user=%u/group=%g/name=%p/type=%Y\\n'
+'''
+print(shlex.split(cmd))
+
+

...which emits an entirely correct result, and subprocess.call() works with it properly.

+
+

Building A Correct Command Line By Hand

+

In terms of what it looks like to do this by hand:

+
cmd = [
+    'find', '/',
+    '(',
+             '-path', '/mnt',  '-prune',
+       '-o', '-path', '/dev',  '-prune',
+       '-o', '-path', '/proc', '-prune',
+       '-o', '-path', '/sys',  '-prune',
+    ')',
+    '-o', '!', '-type', 'l',
+    '-type', 'f',
+    '-or',
+    '-type', 'd',
+    '-printf', 'depth=%d/perm=%m/size=%s/atime=%A@/mtime=%T@/ctime=%C@/hardlinks=%n/selinux_context=%Z/user=%u/group=%g/name=%p/type=%Y\n'
+]
+
+

Note:

+
    +
  • Syntactic quotes change the shell's parsing mode, they don't become part of the data. "foo" just becomes foo; "foo"bar"baz" becomes foobarbaz. So you can't/shouldn't/don't try to put those quotes into the data that Python is passing in.
  • +
  • This is true also for \(: the backslash is shell syntax. It doesn't actually become one of find's arguments, so you leave it out.
  • +
  • Any space that isn't quoted or escaped separates words; so -type f in shell is '-type', 'f', two separate words.
  • +
",python +"How to keep committing the code to github even after pytest-check hook fails?

Below is my .pre-commit-config.yaml file for my project.

+
# See https://pre-commit.com/hooks.html for more hooks
+fail_fast: true
+repos:
+-   repo: https://github.com/pre-commit/pre-commit-hooks
+    rev: v4.2.0
+    hooks:
+    -   id: trailing-whitespace
+    -   id: end-of-file-fixer
+    -   id: check-yaml
+    -   id: check-added-large-files
+
+-   repo: local
+    hooks:
+      - id: isort
+        name: isort
+        entry: isort
+        language: python
+        types: [python]
+-   repo: local
+    hooks:
+    -   id: black
+        name: black
+        entry: black
+        language: python
+        types: [python]
+
+-   repo: local
+    hooks:
+      - id: pytest-check
+        name: pytest-check
+        #entry: pytest tests/test_file2.py
+        entry: pytest
+        language: python
+        #args: [--maxfail=1]
+          #stages: [post-commit]
+        pass_filenames: false
+        always_run: false
+
+

I would like to achieve two things as described below.

+
    +
  1. Sometimes, developer modify the business logic and test cases too and those gets fail due to some reason.And, if test cases keep on failing continuously then there is risk of loosing the code because pre-commit won't allow to commit the changes until all checks are passed. Hence, we should always want to be able to commit to feature branches even though test cases fail. +Note : Please keep in mind that, I would like to achieve above scenario for pytest-check hook and not for other hooks.
  2. +
  3. As per my current configuration of pre-commit-config.yaml file, it executes complete test suit. But i wants to execute it for specific test case file.
  4. +
+

FYI. - I have already explored one approach to bypass pre-commit but it's applicable to all hook mentioned in the .pre-commit-config.yaml file.

+

How can we achieve all two scenario? Please suggest your input on the same?

","

Make your test into a shell script that executes, in effect,

+
pytest tests/test_file2.py (or whatever you are doing now)
+true
+
+

The last command could also be exit 0, or anything else that exits successfully.) That way the tests will run, with the side effects and output that you have now, but git will always treat them as successful.

",python +"Seeking missing element in an array in Python

I have an array I with shape=(10,2). I want to probe this array for missing j=1. By missing, I mean there are no indices with j=1. As is evident from I, there are indices with j=2,3,4,5,6,7.

+

For the purpose of notation, in [0,3], i=0,j=3.

+
import numpy as np
+
+I=np.array([[0, 3],
+       [1, 2],
+       [1, 4],
+       [2, 5],
+       [3, 4],
+       [4, 5],
+       [4, 6],
+       [5, 7],
+       [6, 7]])
+
+

The expected output is

+
Missing_j=[1]
+
","

If you want to check single index then you can use code from @ArrowRise comment.

+
if 1 not in I[:,1]: return '1 is missing'
+
+
+

If you want to get all missing indexes then you can use set() for this.

+

You can convert second column to set

+
set1 = set(I[:,1])
+
+

and generate set with all expected indexes

+
max_j = max(I[:,1])
+
+set2 = set( range(1, max_j+1) )
+
+

And later you can do

+
missing_j = set2 - set1
+
+
+

Full working example - I added [6, 10] to have more missing indexes.

+
import numpy as np
+
+I = np.array([
+    [0, 3],
+    [1, 2],
+    [1, 4],
+    [2, 5],
+    [3, 4],
+    [4, 5],
+    [4, 6],
+    [5, 7],
+    [6, 7],
+    [6, 10],    
+])
+
+set1 = set( I[:,1] )
+
+max_j = max(I[:,1])
+set2 = set( range(1, max_j+1) )
+
+missing_j = sorted( set2 - set1 )
+
+print( missing_j )
+
+

Result:

+
[1, 8, 9]
+
",python +"only list-like objects are allowed to be passed to isin(), you passed a [str]

I am trying to create dashboard by using the plotly python. Require to create dropdown for date selection for the pie chart. All the data are come from a .csv file.

+

Expectation: The data displayed in the pie chart are based on the date selected.

+

Data:
+enter image description here

+

Code:

+
date_category = list(df['Date'].unique())
+
+app.layout = ...,
+
+        dcc.Dropdown(id='date_drdn', multi=False, value= ['02/01/2022'], 
+                      options = [{'label':x, 'value':x} 
+                                for x in date_category]
+                      ),
+                     
+        dcc.Graph(id='pie-fig', figure={})
+
+@app.callback(  
+      Output('pie-fig', 'figure'),
+      Input('date_drdn', 'value'))
+
+
+def update_graph(selection):
+ 
+      dff = df[df['Date'].isin(selection)]      
+      fig = px.pie(dff, values='Transactions', names='Product', color_discrete_sequence=px.colors.sequential.RdBu)
+      fig.update_traces(textinfo= "label+value+percent").update_layout(title_x=0.5)
+      return fig     
+
+

However, it keep on showing the error message when select the date. +
Error message:"only list-like objects are allowed to be passed to isin(), you passed a [str]"

+

And the data is not display based on the date selected.

+

Does anyone know why and how to solve it?

","

If the return value of the dropdown allows multiple selections, it will be in list format and isin effect. Since the expected pie chart is a single selection of date and time, the list format is not needed as an initial value. At the same time, the return value of the callback will be a single date and time data for conditional extraction.

+
date_category = list(df['Date'].unique())
+
+from dash import Dash, dcc, html, Input, Output
+import plotly.express as px
+#from jupyter_dash import JupyterDash
+
+app = Dash(__name__)
+#app = JupyterDash(__name__)
+
+app.layout = html.Div([
+    html.H3('Daily Graph'),
+    dcc.Dropdown(id='date_drdn',
+                 multi=False,
+                 value= '02/01/2022',
+                 options = [{'label':x, 'value':x} for x in date_category]
+                ),
+                     
+        dcc.Graph(id='pie-fig', figure={})
+])
+
+@app.callback(  
+     Output('pie-fig', 'figure'),
+     Input('date_drdn', 'value'))
+def update_graph(selection):
+    # if selection:
+    dff = df[df['Date'] == selection]
+    #print(dff)
+    fig = px.pie(dff, values='Transactions', names='Product', color_discrete_sequence=px.colors.sequential.RdBu)
+    fig.update_traces(textinfo="label+value+percent").update_layout(title_x=0.5)
+    return fig
+
+if __name__ == '__main__':
+    app.run_server(debug=True)#, mode='inline'
+
+

",python +"Search by value of dict in array

I have a large list of dicts, each dict has a token.

+
large_list = [{"token": "4kj13", "value1": 10, "value2": 20},
+              {"token": "hm9gm", "value1": 15, "value2": 30}]
+
+

I need to quickly find a dictionary by token, something like

+
print(large_list["4kj13"]["value1"])
+
+

Is there any elegant way to do it? I think I can create a dictionary token to index:

+
token2index = {"4kj13": 0, "hm9gm": 1}
+
+

But if there's a better solution, then I would be glad to know.
+I can't change the input format (json), though I can create some intermediate data.

+

UPD: also the content of the dict is not simple, so the list can't be easily transformed to a table
+UPD2: tokens are unique

","

Convert list of dict to dict

+
d = {x["token"]: x for x in large_list}
+d["4kj13"]["value1"]
+# 10
+
",python +"FastAPI response model list of json objects

I am using MongoDB and FastAPI but can't get my response for more than one document to render without an error, it's a lack of understanding on my part but no matter what I read, I can't seem to get to the bottom of it?

+

models.py

+
from pydantic import BaseModel, constr, Field
+
+    #Class for a user
+    class User(BaseModel):
+       username: constr(to_lower=True)
+       _id: str = Field(..., alias='id')
+       name: str
+       isActive : bool
+       weekPlan : str
+
+    #Example to provide on FastAPI Docs
+    class Config:
+
+        allow_population_by_field_name = True
+        orm_mode = True
+        schema_extra = {
+
+        "example": {
+            "name": "John Smith",
+            "username": "john@smith.com",
+            "isActive": "true",
+            "weekPlan": "1234567",
+        }
+    }
+
+

routes.py

+
from fastapi import APIRouter, HTTPException, status, Response
+
+from models.user import User
+from config.db import dbusers
+
+user = APIRouter()    
+
+@user.get('/users', tags=["users"], response_model=list[User])
+         async def find_all_users(response: Response):
+         # Content-Range needed for react-admin
+         response.headers['Content-Range'] = '4'
+         response.headers['Access-Control-Expose-Headers'] = 'content-range'
+         users = (dbusers.find())
+         return users
+
+

mongodb json data

+
{
+    "_id" : ObjectId("62b325f65402e5ceea8a4b6f")
+  },
+  "name": "John Smith",
+  "isActive": true,
+  "weekPlan": "1234567"
+   },
+   {
+    "_id" : ObjectId("62b325f65402e5ceea9a3d4c"),
+    "username" : "john@smith.com",
+    "name" : "John Smith",
+    "isActive" : true,
+    "weekPlan" : "1234567"
+    }
+
+

This is the error I get:

+
    await self.app(scope, receive, send)
+  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 670, in __call__
+    await route.handle(scope, receive, send)
+  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 266, in handle
+    await self.app(scope, receive, send)
+  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 65, in app
+    response = await func(request)
+  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 235, in app
+    response_data = await serialize_response(
+  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 138, in serialize_response
+    raise ValidationError(errors, field.type_)
+pydantic.error_wrappers.ValidationError: 1 validation error for User
+response
+  value is not a valid list (type=type_error.list)
+
+

Can anyone help?

","

pymongo's find method returns a Cursor - you have to exhaust this iterator first, since Pydantic doesn't have any idea what it should do with a Cursor object.

+

You can do this by giving it as an argument to list:

+
@user.get('/users', tags=["users"], response_model=List[User])
+async def find_all_users(response: Response):
+    ...
+    return list(dbusers.find())
+
",python +"Python: Behaviour of float memory addressing

All, +When I execute the following code from inside Spyder IDE, I get the same ID of a, b, and the number 1000., yet when I execute the code from the Spyder console, I get different IDs (the ID of a is different from b). Floats are known to be immutable, yet they behave like mutable when executed by the spyder editor. Any idea why this is the case.

+
a=1000.
+b=1000.
+print('id of a='+str(id(a)))
+print('id of b='+str(id(b)))
+print('id of 1.'+str(id(1000.)))
+
+

Thanks

","

This has nothing to do with Spyder, this is purely a Python optimisation, as kindly explained by @Barmar.

+

Example 1: Line-based execution

+

When the values are assigned for line-execute (even if the lines are grouped when executed), the following output is provided:

+
>>> a = 1000.
+>>> b = 1000.
+>>> print(f'{id(a)=}\n{id(b)=}')
+
+id(a)=140093502852336
+id(b)=140093502851184
+
+

Different IDs.

+

Example 2: Function-based execution

+

However, when the assignments are wrapped in a function (as shown below), Python performs optimisations which basically say: "Hey, I've got a variable for that value already, so I'll just use it again."

+
def test():
+    a = 1000.
+    b = 1000.
+    print(f'{id(a)=}\n{id(b)=}')
+
+>>> test()
+id(a)=140093502851472
+id(b)=140093502851472
+
+

Same IDs.

+
+

Bytecode: Function-based execution

+

As shown in the bytecode for the test() function, the same ID has been assigned to the variables, due to compiler optimisations.

+
  2           0 LOAD_CONST               1 (1000.0)  # <-- Here (1)
+              2 STORE_FAST               0 (a)
+
+  3           4 LOAD_CONST               1 (1000.0)  # <-- Here (1)
+              6 STORE_FAST               1 (b)
+
+  4           8 LOAD_GLOBAL              0 (print)
+             10 LOAD_CONST               2 ('id(a)=')
+             12 LOAD_GLOBAL              1 (id)
+             14 LOAD_FAST                0 (a)
+             16 CALL_FUNCTION            1
+             18 FORMAT_VALUE             2 (repr)
+             20 LOAD_CONST               3 ('\nid(b)=')
+             22 LOAD_GLOBAL              1 (id)
+             24 LOAD_FAST                1 (b)
+             26 CALL_FUNCTION            1
+             28 FORMAT_VALUE             2 (repr)
+             30 BUILD_STRING             4
+             32 CALL_FUNCTION            1
+             34 POP_TOP
+             36 LOAD_CONST               0 (None)
+             38 RETURN_VALUE
+
",python +"Should libraries be synchronized with a repository (eg GitHub)

PyCharm offers to synchronize imported packages (eg openpyxl) with repositories.

+

Is it good practice to synch these (even though they are imported standard packages)?

+

Thanks

","

The answer is no.

+

A virtual environment need not be replicated as the packages and their version can be listed with the pop freeze command into a text file called requirements.txt that should be shared.

+

Others can use this file to build up the libraries.

",python +"Pandas apply().to_excel() got DataFrame is not callable
    empty_stock_list = [
+    {
+      'row_index': <num>,
+      'column_index': <num>
+    },
+    ...
+    ]
+
+    with pd.ExcelWriter(OUTPUT_FILE, engine='xlsxwriter') as writer:
+        df = pd.concat([header_row, data_price], ignore_index=False, sort=False).reset_index(drop=True)
+        
+        df_color = df.copy()
+        df_color.iloc[:,:] = 'font-color: black'
+        for empty_stock in empty_stock_list:
+            df_color.iloc[empty_stock['row_index'], empty_stock['column_index']] = 'font-color: #FF0000'
+
+        df.style.apply(df_color, axis=None).\
+            to_excel(writer, sheet_name=sheet_name, index=False, header=None)
+
+

I have this code above, but always get this error: TypeError: 'DataFrame' object is not callable. Basically what I'm trying to do is to make the cell color into a red color if a stock is empty (Based on the data row_index and column_index).

+

Tried to follow the documentation, but I can't seem to make this right.

+

Below is the traceback error messages:

+
Traceback (most recent call last):
+  File "main.py", line 129, in <module>
+    df.style.apply(df_color, axis=None).\
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 229, in to_excel
+    formatter.write(
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 734, in write
+    writer.write_cells(
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/excel/_xlsxwriter.py", line 212, in write_cells
+    for cell in cells:
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 688, in get_formatted_cells
+    for cell in itertools.chain(self._format_header(), self._format_body()):
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 590, in _format_regular_rows
+    for cell in self._generate_body(coloffset):
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 674, in _generate_body
+    styles = self.styler._compute().ctx
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 625, in _compute
+    r = func(self)(*args, **kwargs)
+  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 642, in _apply
+    result = func(data, **kwargs)
+TypeError: 'DataFrame' object is not callable
+
+

I'm using these dependencies:

+
    +
  • python 3.8.0
  • +
  • pandas 1.1.3
  • +
  • xlrd 1.2.0
  • +
  • XlsxWriter 1.3.7
  • +
","

I think you need create function and pass to Styler.apply and change font-color to color:

+
def func(df):
+
+    df_color = pd.DataFrame('color: black', index=df.index, columns=df.columns)
+    
+    for empty_stock in empty_stock_list:
+        i = empty_stock['row_index']
+        j = empty_stock['column_index']
+        df_color.iloc[i,j] = 'color: #FF0000'
+    return df_color
+
+
+with pd.ExcelWriter(OUTPUT_FILE, engine='xlsxwriter') as writer:
+    df = pd.concat([header_row, data_price], 
+                    ignore_index=False, 
+                    sort=False).reset_index(drop=True)
+        
+    (df.style.apply(func, axis=None)
+       .to_excel(writer, sheet_name=sheet_name, index=False, header=None))
+
",python +"How to increase AWS Sagemaker invocation time out while waiting for a response

I deployed a large 3D model to aws sagemaker. Inference will take 2 minutes or more. I get the following error while calling the predictor from Python:

+
An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (0) from model with message "Your invocation timed out while waiting for a response from container model. Review the latency metrics for each container in Amazon CloudWatch, resolve the issue, and try again."'
+
+

In Cloud Watch I also see some PING time outs while the container is processing:

+
2020-10-07T16:02:39.718+02:00 2020/10/07 14:02:39 https://forums.aws.amazon.com/ 106#106: *251 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 10.32.0.2, server: , request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/gunicorn.sock/ping", host: "model.aws.local:8080"
+
+

How do I increase the invocation time out?

+

Or is there a way to make async invocations to an sagemaker endpoint?

","

It’s currently not possible to increase timeout—this is an open issue in GitHub. Looking through the issue and similar questions on SO, it seems like you may be able to use batch transforms in conjunction with inference.

+

References

+

https://stackoverflow.com/a/55642675/806876

+

Sagemaker Python SDK timeout issue: https://github.com/aws/sagemaker-python-sdk/issues/1119

",python +"For loop within a Pandas dataframe to add a new column after each iteration

I have a dataframe that has a variety of properties on a dataset of buildings. These buildings are all assigned to a dwelling group (Apartment/ Semi detached house/ Detached house/ Terraced house) and a small area code. These buildings also have a year of construction column, however no unique identifier apart from their small area (circa 80 buildings).

+

I want to write a for loop that groups these buildings into their dwelling group, and then break them down into their small area and assigns them individually the median year of construction for that dwelling group in that small area. For example, divide up all apartments in small area 12345, and assign them individually (in a new column) the median year of construction for apartments in that small area.

+

So far geo_dwelling is a GeoDataFrame with columns;

+
In [20]: geo_dwelling.head(5)
+
+

Out[20]: +cso_small_area Dublin Postcode Year of construction Year of construction range Dwelling type description Energy Rating ... height_ag height_bg floors_ag floors_bg category Dwelling Group +7101 268109005 DUBLIN 1 2009.0 2005 onwards Mid floor apt. B3 ... 10.02 0 3 0 R Apartment +7101 268109005 DUBLIN 1 2009.0 2005 onwards Mid floor apt. B3 ... 10.73 0 3 0 R Apartment +7101 268109005 DUBLIN 1 2009.0 2005 onwards Mid floor apt. B3 ... 10.56 0 3 0 R Apartment +7101 268109005 DUBLIN 1 2009.0 2005 onwards Mid floor apt. B3 ... 10.75 0 3 0 R Apartment +7101 268109005 DUBLIN 1 2009.0 2005 onwards Mid floor apt. B3 ... 10.85 0 3 0 R Apartment

+
geo_dwelling = geo_dropped[
+geo_dropped["Dwelling Group"].str.contains("Apartment", na=False)]
+
+geo_dwelling.groupby(["cso_small_area"])[["Year of construction"]].median()
+
+

Any help is much appreciated!

","

It's generally considered bad practise to create 'for' loops in a pandas dataframe (Takes a lot of time too!). I believe the answer to your question lies in this article:

+

How to iterate over rows in a DataFrame in Pandas

",python +"Getting the correct order of output with append in for loop

I have a df in which I want to place column 1 under colum 0 and column 2 under column 1 and so on for n number of columns so that I have one series.

+

Input:

+
df = pd.DataFrame([['Adf', 'Bdf', 'Cdf','Ddf','Edf','Fdf','Gdf'],[45.1, 34.3, 23.1,67.1,45.4,78.2,85.1]] ) 
+tmp = pd.Series([], dtype=object)
+for i in range(df.shape[1]-1):
+    tmp=tmp.append(df.iloc[:][i].append(df.iloc[:][i+1]))
+
+

Output:df

+
      0     1     2     3     4     5     6
+0   Adf   Bdf   Cdf   Ddf   Edf   Fdf   Gdf
+1  45.1  34.3  23.1  67.1  45.4  78.2  85.1
+
+

Output: tmp: Almost correct but there are double entries

+
0     Adf
+1    45.1
+0     Bdf
+1    34.3
+0     Bdf
+1    34.3
+0     Cdf
+1    23.1
+0     Cdf
+1    23.1
+0     Ddf
+1    67.1
+0     Ddf
+1    67.1
+0     Edf
+1    45.4
+0     Edf
+1    45.4
+0     Fdf
+1    78.2
+0     Fdf
+1    78.2
+0     Gdf
+1    85.1
+
+

Desired Output:Created manually

+
Adf
+45.1
+Bdf
+34.3
+Cdf
+23.1
+Ddf
+67.1
+Edf
+45.4
+Fdf
+78.2
+Gdf
+85.1
+
+

I welcome any better approaches. Thanks

","

Use DataFrame.unstack:

+
s = df.unstack().reset_index(drop=True)
+print (s)
+0      Adf
+1     45.1
+2      Bdf
+3     34.3
+4      Cdf
+5     23.1
+6      Ddf
+7     67.1
+8      Edf
+9     45.4
+10     Fdf
+11    78.2
+12     Gdf
+13    85.1
+dtype: object
+
+

Or convert all values to numpy array and then use np.ravel:

+
s = pd.Series(np.ravel(df.to_numpy().T))
+print (s)
+0      Adf
+1     45.1
+2      Bdf
+3     34.3
+4      Cdf
+5     23.1
+6      Ddf
+7     67.1
+8      Edf
+9     45.4
+10     Fdf
+11    78.2
+12     Gdf
+13    85.1
+dtype: object
+
",python +"Problem with counting the number of occurrences of an item of a list

For some reason, I'm not able to count the number of occurrences of an item in a list. The first three functions are needed to generate some data and I'm looking at the function distribution() where I have the problem. The list I'm looking at is finalstate i.e. I am not getting the right value for variable c. For example, as below, I'm counting number of occurrences of [0,0,0] in finalstate and it is supposed to be 1 and I'm getting 0. May I know where I went wrong?

+

Output:

+
    finalstate:  [[1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 1], [0, 1, 1], [1, 0, 0], [0, 0, 0], [1, 1, 0], [1, 0, 0]]
+    key:  [0, 0, 0]
+    c:  0
+   
+
+

Code:

+
    def generateAllBinaryStrings(n, arr, l, i):  
+
+        if i == n: 
+            l.append(arr[:]) 
+            return
+
+        arr[i] = 0
+        generateAllBinaryStrings(n, arr, l, i + 1)  
+
+        arr[i] = 1
+        generateAllBinaryStrings(n, arr, l, i + 1)  
+
+        return l
+
+    
+    def dictionary(v):
+        d={}
+        for i in range(len(v)):
+            d[str(v[i])]=[]
+            temp=[]
+            for j in range(n):
+                temp=v[i][:]
+                if v[i][j]==1:
+                    temp[j]=0
+                else:
+                    temp[j]=1
+                d[str(v[i])].append(temp)
+        return d
+
+    
+    def srw(d,n,t):
+        h=[[0 for i in range(n)]]
+        w=[1/(2*n) for i in range(n)]
+        w.append(0.5)
+        for i in range(t):
+            temp=d[str(h[-1])][:]
+            temp.append(h[-1])
+            h.append(random.choices(temp,weights=w)[-1])
+
+        return h
+
+    
+    def distribution(d,n,t,num):
+        finalstate=[]
+        for i in range(num):
+            temp=srw(d,n,t)
+            finalstate.append(temp[-1])
+        print(finalstate)
+        Xt={}
+        for key in d:
+            c=finalstate.count(list(key))
+            print(c)
+            Xt[str(key)]=c/num
+        for key in d:
+            if key not in Xt:
+                Xt[key]=0
+
+        return Xt
+
+    import numpy as np
+    import matplotlib.pyplot as plt
+    import random
+    import collections as cs
+
+    time=40
+    numsim=10
+
+    #for n in range(5,11,5):
+    n=3
+    l = []  
+    arr = [None] * n 
+    vertices=generateAllBinaryStrings(n, arr, l, 0)
+    d=dictionary(vertices)
+    dist=distribution(d,n,time,numsim)
+
","

The key is a string and you are searching for a list.

+

Try this code:

+
c=finalstate.count(eval(key))  # convert string to list
+
",python +"Count values in Pandas data Frame -Python

I have a data set as such +

+

For simplicity -Let's say I want to calculate the number of type of each manufacturer of the plane. +

+

I want the output as such-

+
BOEING-xxx
+EMBRAER-xxx
+MCDONNELL-XXX
+:
+:
+:
+so on 
+
+

How can I do this ? Please help me out with this.

","

You can use dataframe['manufacturer'].value_counts() to get the result that you want;

+

However, note that you have NaNs in your column; so prior to applying the function above, use:

+
dataframe.dropna(subset=['manufacturer'],inplace=True)
+
+

Summing it up:

+
    +
  1. dataframe.dropna(subset=['manufacturer'],inplace=True)
  2. +
  3. dataframe['manufacturer'].value_counts()
  4. +
",python +"Create columns in dataframe from list (Number of columns change)

I'm working with a pandas dataframe and I have a problem.

+

My input is a list and I don't know how many elements there are in the list, it could be anything from 1 to 5 or 6. I need to add new columns to the dataframe, one for each element in the list.

+

Currently, I add comments to lines, but it doesn't work automatically. My code:

+
list = ['banana', 'apple', 'kiwi'] (3 elements, so i comment 2 lines)
+
+df.loc[:, list[0]] = np.where(df['food'] == list[0], 1.0, 0.0)
+df.loc[:, list[1]] = np.where(df['food'] == list[1], 1.0, 0.0)
+df.loc[:, list[2]] = np.where(df['food'] == list[2], 1.0, 0.0)
+#df.loc[:, list[3]] = np.where(df['food'] == list[3], 1.0, 0.0)
+#df.loc[:, list[4]] = np.where(df['food'] == list[4], 1.0, 0.0)
+
+

I would loke to have something that reads the number of elements in the list, and then creates the correct number of columns automatically, without # adding comments.

","

I think in pandas is best avoid loops, so use get_dummies with filtered rows by Series.isin:

+
L = ['banana', 'apple', 'kiwi']
+df1 = pd.get_dummies(df.loc[df['food'].isin(L), 'food'])
+
+

Last add 0 rows and add to original use DataFrame.reindex with DataFrame.join:

+
df = df.join(df1.reindex(df1.index, fill_value=0.0))
+
",python +"Python: Capture the output of a REST API based DMS service post uploading document

I am trying to upload a file to a DMS via REST API. Each time I upload the file to DMS, an unique doc_id is generated which needs to be saved in DB.

+

I am trying out the following code for the first part i.e. upload.

+
def upload_sotr(filepath:str,file_name:str):
+    upload_url = 'dms_url_path'
+    f = open(os.path.join(filepath,file_name),'rb')
+    files = {"file":(os.path.join(filepath,file_name),f)}
+    resp = requests.post(url=url,files=files)
+    if resp.status_code==201:
+      print('Success!!')
+      ##Want to get the doc_id as shown below and return the same
+      return 'Success!!'
+else:
+    strg='Failure'
+    return strg
+
+

However, I am not able to capture the doc_id string from upload_url post uploading the doc. Typically, doc_id is returned as

+
{
+  doc_type: 'image',
+  doc_id: 'AAD3456Q77'
+}
+
+

As indicated in the code, what trick I should do post print('Success!!') so that I get the doc_id?

","

Ok, I found the trick!!

+

I should use

+
data = resp.json()
+doc_id = data['doc_id''
+return doc_id
+
+

So the complete code would be:

+
def upload_sotr(filepath:str,file_name:str):
+  upload_url = 'dms_url_path'
+  f = open(os.path.join(filepath,file_name),'rb')
+  files = {"file":(os.path.join(filepath,file_name),f)}
+  resp = requests.post(url=url,files=files)
+  if resp.status_code==201:
+    data = resp.json()
+    doc_id = data['doc_id']
+    return doc_id
+ else:
+    strg='Failure'
+    return strg
+
",python +"Pandas Python highest 2 rows of every 3 and tabling the results

Suppose I have the following dataframe:

+
    .    Column1      Column2
+    0       25           1
+    1       89           2
+    2       59           3
+
+    3       78          10
+    4       99          20
+    5       38          30
+
+    6       89         100
+    7       57         200
+    8       87         300
+
+
+

Im not sure if what I want to do is impossible or not. But I want to compare every three rows of column1 and then take the highest 2 out the three rows and assign the corresponding 2 Column2 values to a new column. The values in column 3 does not matter if they are joined or not. It does not matter if they are arranged or not for I know every 2 rows of column 3 belong to every 3 rows of column 1.

+
    .    Column1      Column2   Column3
+    0       25           1        2
+    1       89           2        3
+    2       59           3
+    3       78          10        20
+    4       99          20        10
+    5       38          30
+    6       89         100        100
+    7       57         200        300
+    8       87         300
+
+
","

You can use np.arange with np.repeat to create a grouping array which groups every 3 values.

+

Then use GroupBy.nlargest then extract indices of those values using pd.Index.get_level_values, then assign them to Column3 pandas handles index alignment.

+
n_grps = len(df)/3
+g = np.repeat(np.arange(n_grps), 3)
+
+idx = df.groupby(g)['Column1'].nlargest(2).index.get_level_values(1)
+vals = df.loc[idx, 'Column2']
+vals
+# 1      2
+# 2      3
+# 4     20
+# 3     10
+# 6    100
+# 8    300
+# Name: Column2, dtype: int64
+
+df['Column3'] = vals
+df
+   Column1  Column2  Column3
+0       25        1      NaN
+1       89        2      2.0
+2       59        3      3.0
+3       78       10     10.0
+4       99       20     20.0
+5       38       30      NaN
+6       89      100    100.0
+7       57      200      NaN
+8       87      300    300.0
+
+

To get output like you mentioned in the question you have to sort and push NaN to last then you have perform this additional step.

+
df['Column3'] = df.groupby(g)['Column3'].apply(lambda x:x.sort_values()).values
+
+   Column1  Column2  Column3
+0       25        1      2.0
+1       89        2      3.0
+2       59        3      NaN
+3       78       10     10.0
+4       99       20     20.0
+5       38       30      NaN
+6       89      100    100.0
+7       57      200    300.0
+8       87      300      NaN
+
",python +"How to store result calcluated inside two for loops in np array?

I want to iterate through an image and save the calculated distance beetween the restrictive (x,y) pixel and the point (300,600) in the numpy array np_dist. At the moment the result for all dist values is saved in one element of the array. How is it possible to fill the array storing one value per element?

+
dist_arr = np.empty((width, height))
+for x in range(0, width): 
+    for y in range(0, height): 
+        pixel = (x, y) 
+        dist = math.sqrt((300 - pixel[0])**2 + (600 - pixel[1])**2) 
+        dist_arr[pixel[0], pixel[1]] = dist
+
+
","

There's nothing with your loops:

+
In [26]: width, height = 4,4
+    ...: dist_arr = np.empty((width, height))
+    ...: for x in range(0, width):
+    ...:     for y in range(0, height):
+    ...:         dist = math.sqrt((300 - x)**2 + (600 - y)**2)
+    ...:         dist_arr[x, y] = dist
+    ...: 
+In [27]: dist_arr
+Out[27]: 
+array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],
+       [670.37377634, 669.47890183, 668.58432527, 667.69004785],
+       [669.92835438, 669.03288409, 668.13771036, 667.24283436],
+       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])
+
+

There are ways of doing this faster, but they work.

+

Same values with whole-array numpy calculation:

+
In [28]: np.sqrt((300-np.arange(4)[:,None])**2 + (600 - np.arange(4))**2)
+Out[28]: 
+array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],
+       [670.37377634, 669.47890183, 668.58432527, 667.69004785],
+       [669.92835438, 669.03288409, 668.13771036, 667.24283436],
+       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])
+
",python +"Parsing XML files using element tree

I Would like to parse an XML file in order to get the information as variables for further studies.

+

One part of the XML looks like this:

+
'''<SchedulingPeriod ID="sprint01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="competition.xsd">
+  <StartDate>2010-01-01</StartDate>
+  <EndDate>2010-01-28</EndDate>
+  <Skills>
+    <Skill>Nurse</Skill>
+  </Skills>
+  <ShiftTypes>
+    <Shift ID="E">
+      <StartTime>06:30:00</StartTime>
+      <EndTime>14:30:00</EndTime>
+      <Description>Early</Description>
+      <Skills>
+        <Skill>Nurse</Skill>
+      </Skills>
+    </Shift>
+'''
+
+

I cant extract all the informations from the root element 3 which is ShiftTypes. My code looks like this but unfortunately I cannot extract the information shift type ID and skills:

+
import xml.etree.ElementTree as ET
+
+xmlfile = 'sprint01.xml'
+
+tree = ET.parse(xmlfile)
+root = tree.getroot()
+
+for x in root[3]:
+    print('StartTime: ', x.find('StartTime').text)
+    print('EndTime: ', x.find('EndTime').text)
+    print('Description', x.find('Description').text)
+
+

Thank you and if you have suggestions on how to store these elements and would really appreciate it. +Arthur

","

Use the following code to extract ID attribute:

+
import xml.etree.ElementTree as ET
+tree = ET.parse('a.xml')
+root = tree.getroot()
+for child in root:
+    if child.tag == 'ShiftTypes':
+        for i in child:
+            print ('Here is the ID: ', i.attrib)
+            for j in i:
+                if j.tag == 'StartTime':
+                    print ('Here is StartTime:', j.text)
+                elif j.tag == 'EndTime':
+                    print ('Here is EndTime:', j.text)
+                elif j.tag == 'Description':
+                    print ('Here is Description:', j.text)
+
+
Here is the ID:  {'ID': 'E'}
+Here is StartTime: 06:30:00
+Here is EndTime: 14:30:00
+Here is Description: Early
+
+

Here is a useful tutorial about parsing XML data:

+

https://www.datacamp.com/community/tutorials/python-xml-elementtree

",python +"How to remove more than one symbol from csv

I'm trying to replace my old.csv data that looks like this: 6004387,6219127,'12524449',10340

+

Into new.csv that should look like this: 6004387|6219127|12524449|10340

+

What I get now is "['6004387'| '6219127'| ""'12524449'""| '10340']"

+

How can I remove more than one symbol?

+
import csv
+import string
+
+input_file = open('old.csv', 'r')
+output_file = open('new.csv', 'w')
+data = csv.reader(input_file)
+writer = csv.writer(output_file)
+specials = ','
+
+for row in data:
+    row = str(row)
+    new_row = str.replace(row,specials,'|')
+    writer.writerow(new_row.split(','))
+
+input_file.close()
+output_file.close()
+
","

If you want to remove quote characters from input file, specify quotechar="'" in csv.reader. Also, for | delimiter in output file, specify delimiter='|' in csv.writer:

+
import csv
+
+input_file = open('old.csv', 'r')
+output_file = open('new.csv', 'w')
+data = csv.reader(input_file, quotechar="'")
+writer = csv.writer(output_file, delimiter='|')
+
+for row in data:
+    writer.writerow(row)
+
+input_file.close()
+output_file.close()
+
+

Creates new.csv:

+
6004387|6219127|12524449|10340
+
",python +"Numpy matrix looking like an array of lists?

I'm trying to declare a 16x16 numpy matrix:

+
P = np.array([[0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0,1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
+
+

Outputs:

+
       list([0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.0, 0.8, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.4, 0.0, 0.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.1, 0.3, 0.3, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.0, 0.8, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.4, 0.0, 0.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.1, 0.3, 0.3, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.0, 0.8, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.4, 0.0, 0.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0, 1, 0.3, 0.3, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.0, 0.0, 0.8, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
+       list([0.4, 0.0, 0.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])],
+      dtype=object)
+
+

Why? I want a pure numpy matrix, not an array of lists...Sure it's something boneheaded I'm doing but for life of me can't figure it out...

","

Well, lets investigate

+
import numpy as np
+
+P = np.array([[0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0,1, 0.3, 0.3, 0.3, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.5, 0.5, 0.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.0, 0.0, 0.8, 0.2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+              [0.4, 0.0, 0.0, 0.6, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
+
+for i in P:
+    print(i.__len__())
+
+
...
+16
+17 #oh?
+16
+16
+16
+
+

also note that it gives us a warning:

+
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
+
+

so there's a length problem!

+

lets look closer

+
[0,1, 0.3, 0.3, ...]
+[0.0, 0.5, 0.5, ...]
+
+

the lengths are different, that's why you're getting the error

+

maybe fix with [0.1, 0.3, 0.3, ...] to make it 16 x 16

",python +"How to reassemble a pandas dataframe based on a non-ordered index

I have been working on an algorithm that separates rows in a dataframe based on one of the columns to treat them differently. The results should be reassembled afterwards. I need to make sure that the index is preserved and in the same order.

+

Initially I thought I could just concatenate the results and then put the index in the same order. However, I cannot find an efficient way to do this. The best I could come up with is this:

+
import pandas as pd
+
+# Input data with non-ordered index.
+input_data = pd.DataFrame({
+    'type': ['a', 'a', 'b', 'c', 'a'],
+    'value': [1, 2, 3, 4, 5],
+}, index=[0, 10, 40, 30, 20])
+# input_data:
+#    type  value
+# 0     a      1
+# 10    a      2
+# 40    b      3
+# 30    c      4
+# 20    a      5
+
+# Data separated into two and treated differently.
+data_a = input_data[input_data['type'] == 'a']
+data_a['result'] = data_a['value'].mean()
+data_b = input_data[input_data['type'] != 'a'] 
+data_b['result'] = data_b['value'].max()
+
+# Assemble output.
+output_data = (
+    pd.DataFrame(index=input_data.index) # correct index order
+    .merge(
+        pd.concat(
+            [data_a['result'], data_b['result']], axis=0
+        ), # wrong index order
+        how='left', left_index=True, right_index=True # 'left' preserves order
+    )
+)
+# output_data:
+#       result
+# 0   2.666667
+# 10  2.666667
+# 40  4.000000
+# 30  4.000000
+# 20  2.666667
+
+

Is there a more straight-forward way to do this? Or perhaps more efficient?

","

Use DataFrame.reindex if index values are unique:

+
output_data  = pd.concat([data_a['result'], data_b['result']]).reindex(input_data.index)
+
",python +"How to print a list comprehension with strings and integers and add a symbol only to the strings?

I have a mixed list of integers and strings and I need to print '**' after strings only.

+
data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']
+[print(data, end='**') for data in data if isinstance(data, str)]
+
+

This is the output:

+

Fred**London**@#=£**Ice cream**Hamilton**tingle**

+

Desired output:

+

4, Fred**, London**, 34, 78, @#=£**, 89, Ice Cream**, Hamilton**, 12, tingle**

","

Your if is now filtering the list data. Put it before the for. Also, use str.join to join the various strings with , :

+
data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']
+
+print( ', '.join('{}**'.format(item) if isinstance(item, str) else str(item) for item in data) )
+
+

Prints:

+
4, Fred**, London**, 34, 78, @#=£**, 89, Ice cream**, Hamilton**, 12, tingle**
+
",python +"Python Pivot Table multi Sub-totals in column

I would like to be able to show the sub-total column from a multi-index pivot table in different ways for example, I would like to show the sum for a selected row and the max for another, is this possible?

+

I managed to get half code correct but I am stuck in replicating the code without offsetting the previous one and I am not able to loop this code over.

+

In my example I want to get the max value from Toyota and the sum value from Honda shown in the newly created Total column.

+
cars = {'Brand': ['Honda','Toyota', 'Honda','Toyota'],
+        'Target': ['A','B', 'A','B'],
+        'Speed': [20, 80, 30 , 10],
+        'Date' : ['13/02/2019', '18/02/2019', '18/02/2019', '13/02/2019']
+       }
+
+df = pd.DataFrame(cars)
+
+
+table = pd.pivot_table(df, values=['Speed'],
+                       index=['Target', 'Brand'],
+                       columns=['Date'],
+                       fill_value=0, aggfunc=np.sum, dropna=True)
+table
+
+

+

the code craeted: (which works only for the last line as it overwrites the first one)

+
table['Total'] = table.loc(axis=0)[:, ['Toyota']].max(axis=1)
+table['Total'] = table.loc(axis=0)[:, ['Honda']].sum(axis=1)
+
+

Current output:

+

+

Disired Output:

+

I would like to be able to see also the max value for Toyota which would be 80.

","

Use slicers for set new values in both sides, here : means all values for levels:

+
idx = pd.IndexSlice
+table.loc[idx[:, 'Toyota'], 'Total'] = table.max(axis=1)
+table.loc[idx[:, 'Honda'], 'Total'] = table.sum(axis=1)
+print (table)
+                   Speed            Total
+Date          13/02/2019 18/02/2019      
+Target Brand                             
+A      Honda          20         30  50.0
+B      Toyota         10         80  80.0
+
+

You can set and select in both sides:

+
idx = pd.IndexSlice
+table.loc[idx[:, 'Toyota'], 'Total'] = table.loc[idx[:, 'Toyota'], :].max(axis=1)
+table.loc[idx[:, 'Honda'], 'Total'] = table.loc[idx[:, 'Honda'], :].sum(axis=1)
+
",python +"How do I break up a squared term in sympy

I am using python (3.7.3) with sympy (1.6.2) to store a function with squared terms and non-squared terms, with each term being the product of exactly two variables.

+

For example,

+
>> import sympy as sy
+>> x = sy.Symbol('x')
+>> y = sy.Symbol('y')
+>> F = x*x+x*y
+>> print(F)
+x**2+x*y
+
+

I want to be able to iterate through the terms and get each operand. +For example,

+
terms = F.expand(basic=True).args
+for term in terms
+    (t0,t1) = term.args
+    print('t0:{}, t1:{}'.format(t0,t1))
+    # do some stuff using t0, t1
+
+

This works for the x*y term, but not the x**2 term.

+
>> print((x*y).args)
+(x,y)
+>> print((x**2).args) # I want this to be (x,x)
+(x,2)
+
+

I tried running (x**2).expand(), but this appears to be the fully expanded version of the expression.

+

My question is twofold:

+
    +
  1. is there a way to expand x**2 so that it is stored as x*x?
  2. +
  3. is there a better way to go about getting each operand in each term than the for loop I show above?
  4. +
","

You could define a custom function that defactors in the way you want:

+
def get_factors(expr):
+    if expr.func == sy.Mul:
+        return expr.args
+    elif expr.func == sy.Pow:
+        return tuple(expr.args[0] for _ in range(expr.args[1]))
+    else:
+        raise NotImplementedError()
+
+

Usage:

+
>>> a, b = terms
+>>> get_factors(a)
+(x, x)
+>>> get_factors(b)
+(x, y)
+
",python +"Python print every possibility of setences

I wrote a simple sentence generator made out of lists.

+
a_a = ['Hey, ', 'Hello, ', 'Hi, ']
+a_b = 'this is a random sentence! '
+a_c = ['Bye! ', 'Bye, bye! ', 'Goodbye! ']
+
+sentence = a_a[secrets.randbelow(3)] + a_b + a_c[secrets.randbelow(3)]
+
+

The real code is much bigger. I need a way to print out every possible sentence or safe it to a text file. Can someone help me? I am lost.

","

Using just plain python:

+
a_a = ['Hey, ', 'Hello, ', 'Hi, ']
+a_b = 'this is a random sentence! '
+a_c = ['Bye! ', 'Bye, bye! ', 'Goodbye! ']
+
+for element_a in a_a:
+    for element_c in a_c:
+        print(element_a + a_b + element_c)
+
+

Using itertools to get to a single loop that iterates over all combinations:

+
import itertools
+
+a_a = ['Hey, ', 'Hello, ', 'Hi, ']
+a_b = 'this is a random sentence! '
+a_c = ['Bye! ', 'Bye, bye! ', 'Goodbye! ']
+
+for element_a, element_c in itertools.product(a_a, a_c):
+    print(element_a + a_b + element_c)
+
+

If you want to save it to a file, replace the print statement with something else, like the command to write the combination to a file.

",python +"RE: Transferring Python2 to Python3 on This Specific Line

I am attempting to change this line to become acceptable by python3 from a python2 set of source:

+
Here is the error:
+
+TypeError: unicode strings are not supported, please encode to bytes: 
+'$PMTK251,9600*17\r\n'
+
+

Can anyone tell my why this is this way or how I can change it to suit Python3 methods?

+

It is a GPS set of source in Python2 that still works but I see that all ideas relating to Python2 will be gone from availability and/or is already pretty much done and gone.

+

So, my ideas were to update that line and others.

+

In python3, I receive errors relating to bytes and I have currently read about the idea of (arg, newline='') in source when attempting to make .csv files in Python3.

+

I am still at a loss w/ how to incorporate Python3 in this specific line.

+

I can offer more about the line or the rest of the source if necessary. I received this source from toptechboy.com. I do not think that fellow ever updated the source to work w/ Python3.

+
class GPS:
+def __init__(self):
+    #This sets up variables for useful commands.
+    #This set is used to set the rate the GPS reports
+    UPDATE_10_sec = "$PMTK220,10000*2F\r\n" #Update Every 10 Seconds
+    UPDATE_5_sec = "$PMTK220,5000*1B\r\n"   #Update Every 5 Seconds  
+    UPDATE_1_sec = "$PMTK220,1000*1F\r\n"   #Update Every One Second
+    UPDATE_200_msec = "$PMTK220,200*2C\r\n" #Update Every 200 Milliseconds
+    #This set is used to set the rate the GPS takes measurements
+    MEAS_10_sec = "$PMTK300,10000,0,0,0,0*2C\r\n" #Measure every 10 seconds
+    MEAS_5_sec = "$PMTK300,5000,0,0,0,0*18\r\n"   #Measure every 5 seconds
+    MEAS_1_sec = "$PMTK300,1000,0,0,0,0*1C\r\n"   #Measure once a second
+    MEAS_200_msec= "$PMTK300,200,0,0,0,0*2F\r\n"  #Meaure 5 times a second
+    #Set the Baud Rate of GPS
+    BAUD_57600 = "$PMTK251,57600*2C\r\n"          #Set Baud Rate at 57600
+    BAUD_9600 ="$PMTK251,9600*17\r\n"             #Set 9600 Baud Rate
+    #Commands for which NMEA Sentences are sent
+    ser.write(BAUD_57600)
+    sleep(1)
+    ser.baudrate = 57600
+    GPRMC_ONLY = "$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n" #Send only the GPRMC Sentence
+    GPRMC_GPGGA = "$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"#Send GPRMC AND GPGGA Sentences
+    SEND_ALL = "$PMTK314,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n" #Send All Sentences
+    SEND_NOTHING = "$PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n" #Send Nothing
+
+

...

+

That is the GPS Class Mr. McWhorter wrote for a GPS Module in python2. I am trying to configure this python2 source into a workable python3 class.

+

I am receiving errors like "needs to be bytes" and/or "cannot use bytes here".

+

Anyway, if you are handy w/ Python3 and know where I am making mistakes on this source to transfer it over to Python3, please let me know. I have tried changing the source many times to accept bytes and to be read as a utf-string.

+

Here: Best way to convert string to bytes in Python 3? <<< This seems like the most popular topic on this subject but it does not answer my question so far (I think).

","

This line simply works when adding a b for bytes in front of the string...like so.

+
(b'$PMTK251,9600*17\r\n')
+
+

That should rid you of that error of TypeError: unicode strings are not supported, please encode to bytes:

",python +"Button callback only works one time due to threading

I'm only able to use this button's callback once due to how I set up the 'command=' argument. I would like to be able to run this callback function again once it is finished, but I'm at a loss for how I can give the 'command=' argument a new thread object. I press it once and go through the process of the function, but once I press the button again after it is finished, I get 'RuntimeError: threads can only be started once.' Here is the code for the button and the callback:

+
def ocr_callback():
+    no_file_to_save_to = False
+    try:
+        status_label.pack_forget()
+        for f in files:    # files comes from another callback and is globally defined
+            name, extension = os.path.splitext(f)
+            if extension != '.pdf':
+                raise
+        if len(files) == 1:
+            new_file = filedialog.asksaveasfilename(filetypes=[('PDF', '.pdf')], defaultextension='.pdf')
+            if not new_file:
+                no_file_to_save_to = True
+                raise
+            try:
+                ocrmypdf.ocr(files[0], new_file, use_threads=True)
+            except ocrmypdf.exceptions.PriorOcrFoundError:
+                ocrmypdf.ocr(files[0], new_file, redo_ocr=True, use_threads=True)
+        elif len(files) > 1:
+            directory = filedialog.askdirectory()
+            if not directory:
+                no_file_to_save_to = True
+                raise
+            for f in files:
+                file_name = f.split('/')[-1]
+                try:
+                    ocrmypdf.ocr(f, directory + '/' + file_name, use_threads=True)
+                except ocrmypdf.exceptions.PriorOcrFoundError:
+                    ocrmypdf.ocr(f, directory + '/' + file_name, redo_ocr=True, use_threads=True)
+        status_label.config(text='Process Complete!', fg='blue')
+        status_label.pack(expand='yes')
+    except:
+        if no_file_to_save_to:
+            status_label.config(text='No file to save to. Process Cancelled', fg='blue')
+        else:
+            status_label.config(text='Error: One or more of the files could be corrupt.', fg='red')
+        status_label.pack(expand='yes')
+
+
+ocr_button = Button(root, text='OCR Files', relief='groove', bg='#5D1725', bd=0, width=scaled(20), fg='white',
+                    command=threading.Thread(target=ocr_callback).start, state=DISABLED)
+ocr_button.pack()
+
+

Any thoughts for how I could change it to make it work? I know this function must be threaded else the window will stall and freeze itself until it is finished. The 'ocr' function is what causes the bogging and necessity for the threading.

","

You should probably start the thread from a launch function, instead of from inside the button command.

+

Maybe like this:

+
def launch_cmd(dummy=None):
+    threading.Thread(target=ocr_callback).start()
+
+...
+ocr_button = Button(root, text='OCR Files', relief='groove', bg='#5D1725',\
+                    bd=0, width=scaled(20), fg='white', command=launch_cmd, state=DISABLED)
+
",python +"Match text from beautifulsoup children in Python bs4

In the below code I have Beautiful soup data "table":

+

This is table.prettify

+
<bound method Tag.prettify of <table border="0" cellpadding="14" cellspacing="0"
+
+
+
rows = table.findChildren(['tr'])
+
+

These are elements of rows:

+
<tr><td style="width: 166.35pt; padding: 10.5pt;" width="222"><p class="MsoNormal" style="text-justify: inter-ideograph; text-align: justify;"
+
+
+

i want to get something like:

+
a1 = 'a1': l1'
+a2 = 'a2: r2'
+
+

Can someone help me in how to cleanly go from "table" to get "a1" and "a2"? Any suggestions are welcome I can probably remove findchildren also.

","
    +
  1. Search for a string using the text parameter.
  2. +
  3. Search for the next tag using find_next(), which returns the first match.
  4. +
+

+ +

from bs4 import BeautifulSoup
+
+soup = BeautifulSoup(your_html, 'html.parser')
+
+a1 = soup.find(text=lambda t: "3" in t)
+a2 = soup.find(text=lambda t: "4" in t)
+
+print(a1, a1.find_next(text=True))
+print(a2, a2.find_next(text=True))
+
+

Output:

+
3. Maturity Date: January 12, 2021
+4. Offering Amount: About 7,550 billion yen
+
",python +"Error while running CNN for 1 dimensional data in R

I am trying to run 1 dimensional CNN in R using keras package. I am trying to create one-dimensional Convolutional Neural Network (CNN) architecture with the following specification

+

+
library(keras)
+library(deepviz)
+
+#create a neural network with a convolutional layer and train the model
+model <- keras_model_sequential() %>%
+  layer_conv_1d(filters=32, kernel_size=4, activation="relu", input_shape=c(100, 10)) %>%
+  layer_max_pooling_1d(pool_size=2) %>%
+  layer_conv_1d(filters=64, kernel_size=4, activation="relu") %>%
+  layer_max_pooling_1d(pool_size=5) %>%
+  layer_conv_1d(filters=128, kernel_size=4, activation="relu") %>%
+  layer_max_pooling_1d(pool_size=5) %>%
+  layer_conv_1d(filters=256, kernel_size=4, activation="relu") %>%
+  layer_max_pooling_1d(pool_size=5) %>%
+  layer_dropout(rate=0.4) %>%
+  layer_flatten() %>%
+  layer_dense(units=100, activation="relu") %>%
+  layer_dropout(rate=0.2) %>%
+  layer_dense(units=1, activation="linear")
+
+

But it is giving me following error

+
+

Error in py_call_impl(callable, dots$args, dots$keywords) : +ValueError: Negative dimension size caused by subtracting 4 from 1 for 'conv1d_20/conv1d' (op: 'Conv2D') with input shapes: [?,1,1,128], [1,4,128,256].

+
+

How to solve the error?

+

Another question, how to optimise the filters, kernel_size, pool_size, rate, units? +In my question input_shape=c(100, 10) is an arbitrary value. How to decide about the input size?

","

You have too many Max-Pooling layers, the max pooling layer reduces the dimension of the inputted vector by factor of its parameter.

+

Try to reduce the pool_size parameters , or alternatively remove the last 2 max-pooling layers. A value you can try is pool_size=2 for all layers.

+

As for the parameters you should learn of the meaning of them: +Here you can find an explanation of the convolution layer and max pooling layer parameters like filters , kernel size and pool size: +Convolutional layer

+

The dropout layer is a regularization which maximize the effectiveness of the layer weights , every epoch it zeroes different percent (size of "rate" parameter) of the weights . the larger the rate - you have less overfitting but training time is longer. learn about it here: +Dropout layer

+

The units is the size of the Fully Connected layer. +Fully Connected layer

+

The input shape is a dimensions of your data, when the number of records does not count. In 1d vectors it is (N,C) when N is the vector length and C is number of channels you have, if you have 1 channel it is (N,1). +In 2d vectors it is (Height,Width,Channels).

",python +"How to limit lower error of bar plot to 0?

I calculated the rttMeans and rttStds arrays. However, the value of rttStds makes the lower error less than 0.

+
rttStds = [3.330311915835426, 3.3189677330174883, 3.3319538853150386, 3.325173772304221, 3.3374145232695813]
+
+

How to set lower error to 0 instead of -#?

+

The python bar plot code is bellow.

+

+
import numpy as np
+import matplotlib.pyplot as plt
+import seaborn as sns
+
+sns.set(rc={'figure.figsize':(18,16)},style='ticks',font_scale = 1.5,font='serif')
+
+N = 5
+ind = ['RSU1', 'RSU2', 'RSU3', 'RSU4', 'RSU5']   # the x locations for the groups
+width = 0.4       # the width of the bars: can also be len(x) sequence
+
+fig = plt.figure(figsize=(10,6))
+ax = fig.add_subplot(111)
+
+p1 = plt.bar(ind, rttMeans, width, yerr=rttStds, log=False, capsize = 16, color='green', hatch="/", error_kw=dict(elinewidth=3,ecolor='black'))
+plt.margins(0.01, 0)
+
+#Optional code - Make plot look nicer
+plt.xticks(rotation=0)
+i=0.18
+for row in rttMeans:
+    plt.text(i, row, "{0:.1f}".format(row), color='black', ha="center")
+    i = i + 1
+
+ax.spines['right'].set_visible(False)
+ax.spines['top'].set_visible(False)
+params = {'axes.titlesize':24,
+          'axes.labelsize':24,
+          'xtick.labelsize':28,
+          'ytick.labelsize':28,
+          'legend.fontsize': 24,
+          'axes.spines.right':False,
+          'axes.spines.top':False}
+plt.rcParams.update(params)
+
+plt.tick_params(axis="y", labelsize=28, labelrotation=20, labelcolor="black")
+plt.tick_params(axis="x", labelsize=28, labelrotation=20, labelcolor="black")
+
+plt.ylabel('RT Time (millisecond)', fontsize=24)
+plt.title('# Participating RSUs', fontsize=24)
+
+
+# plt.savefig('RSUs.pdf', bbox_inches='tight')
+plt.show()
+
","

You can pass yerr as a pair [lower_errors, upper_errors] where you can control lower_errors :

+
lowers = np.minimum(rttStds,rttMeans)
+p1 = plt.bar(ind, rttMeans, width, yerr=[lowers,rttStds], log=False, capsize = 16, color='green', hatch="/", error_kw=dict(elinewidth=3,ecolor='black'))
+
+

Output:

+

",python +"Any easy way to transform a missing number sequence to its range?

Suppose I have a list that goes like : +''' +[1,2,3,4,9,10,11,20] +''' +I need the result to be like : +''' +[[4,9],[11,20]] +''' +I have defined a function that goes like this :

+
def get_range(lst):
+i=0
+seqrange=[]
+for new in lst:
+    a=[]
+    start=new
+    end=new
+    if i==0:
+        i=1
+        old=new
+    else:
+        if new - old >1:
+            a.append(old)
+            a.append(new)
+    old=new
+    if len(a):
+        seqrange.append(a)
+return seqrange
+
+

Is there any other easier and efficient way to do it? I need to do this in the range of millions.

","

You can use numpy arrays and the diff function that comes along with them. Numpy is so much more efficient than looping when you have millions of rows.

+
+

Slight aside: +Why are numpy arrays so fast? Because they are arrays of data instead of arrays of pointers to data (which is what Python lists are), because they offload a whole bunch of computations to a backend written in C, and because they leverage the SIMD paradigm to run a Single Instruction on Multiple Data simultaneously.

+
+

Now back to the problem at hand:

+

The diff function gives us the difference between consecutive elements of the array. Pretty convenient, given that we need to find where this difference is greater than a known threshold!

+
import numpy as np
+
+threshold = 1
+arr = np.array([1,2,3,4,9,10,11,20])
+
+deltas = np.diff(arr)
+# There's a gap wherever the delta is greater than our threshold
+gaps = deltas > threshold 
+gap_indices = np.argwhere(gaps)
+
+gap_starts = arr[gap_indices]
+gap_ends = arr[gap_indices + 1] 
+
+# Finally, stack the two arrays horizontally
+all_gaps = np.hstack((gap_starts, gap_ends))
+print(all_gaps)
+# Output: 
+# [[ 4  9]
+#  [11 20]]
+
+

You can access all_gaps like a 2D matrix: all_gaps[0, 1] would give you 9, for example. If you really need the answer as a list-of-lists, simply convert it like so:

+
all_gaps_list = all_gaps.tolist()
+print(all_gaps_list)
+# Output: [[4, 9], [11, 20]]
+
+
+

Comparing the runtime of the iterative method from @happydave's answer with the numpy method:

+
import random
+import timeit
+
+import numpy
+
+def gaps1(arr, threshold):
+    deltas = np.diff(arr)
+    gaps = deltas > threshold 
+    gap_indices = np.argwhere(gaps)
+    gap_starts = arr[gap_indices]
+    gap_ends = arr[gap_indices + 1] 
+    all_gaps = np.hstack((gap_starts, gap_ends))
+    return all_gaps
+
+def gaps2(lst, thr):
+    seqrange = []
+    for i in range(len(lst)-1):
+      if lst[i+1] - lst[i] > thr:
+        seqrange.append([lst[i], lst[i+1]])
+    return seqrange
+
+test_list = [i for i in range(100000)]
+for i in range(100):
+    test_list.remove(random.randint(0, len(test_list) - 1))
+
+test_arr = np.array(test_list)
+
+# Make sure both give the same answer:
+assert np.all(gaps1(test_arr, 1) == gaps2(test_list, 1))
+
+t1 = timeit.timeit('gaps1(test_arr, 1)', setup='from __main__ import gaps1, test_arr', number=100)
+t2 = timeit.timeit('gaps2(test_list, 1)', setup='from __main__ import gaps2, test_list', number=100)
+
+print(f"t1 = {t1}s; t2 = {t2}s; Numpy gives ~{t2 // t1}x speedup")
+
+

On my laptop, this gives:

+
t1 = 0.020834800001466647s; t2 = 1.2446780000027502s; Numpy gives ~59.0x speedup
+
+

My word that's fast!

",python +"Adding legend information to matplotlib plot

I have created a confidence interval plot which is working exactly how I want:

+
month = ['Nov-20', 'Dec-20', 'Jan-21', 'Feb-21', 'Mar-21', 'Apr-21', 'May-21', 'Jun-21', 'Jul-21', 'Aug-21', 'Sep-21', 'Oct-21']
+x = [0.85704744, 0.74785299, 0.68103776, 0.69793547, 0.8396294 ,
+       0.25560889, 0.37400785, 0.00742866, 0.84700224, 0.95142221,
+       0.08544432, 0.09068883]
+y = [0.09448781, 0.69683102, 0.96261431, 0.93635227, 0.31503366,
+       0.38335671, 0.24244469, 0.36712811, 0.22270387, 0.01506295,
+       0.78433   , 0.38408096]
+z = [0.84585527, 0.59615266, 0.60263581, 0.26366399, 0.42948978,
+       0.18138516, 0.54841131, 0.65201558, 0.03089001, 0.20581638,
+       0.57586628, 0.33622286]
+
+fig, ax = plt.subplots(figsize=(17,8))
+ax.plot(month, z)
+ax.fill_between(month, x, y, color='b', alpha=.3)
+ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
+plt.xlabel('Month')
+plt.ylabel('Target %')
+plt.rcParams["font.size"] = "20"
+plt.ylim((0.1, 1.0))
+plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
+plt.title("Target Forecast Nov20 - Nov21")
+
+plt.show()
+plt.close()
+
+

+

However, I want to add the following to the legend:

+
    +
  • An indicator that the blue line is the "probable forecast"
  • +
  • An indicator that the blue fill_between is the confidence interval
  • +
+

I did read this matplotlib documentation, and so I tried:

+
fig, ax = plt.subplots(figsize=(17,8))
+prob, = ax.plot(month, z)
+btwn, = ax.fill_between(month, x, y, color='b', alpha=.3)
+tgt, = ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
+plt.xlabel('Month')
+plt.ylabel('Target %')
+plt.rcParams["font.size"] = "20"
+plt.ylim((0.1, 1.0))
+plt.legend([prob, btwn, tgt], ['Probable', 'Confidence Interval', 'Target'])
+plt.title("Target Forecast Nov20 - Nov21")
+
+plt.show()
+plt.close()
+
+

But it ends in a TypeError:

+
---------------------------------------------------------------------------
+TypeError                                 Traceback (most recent call last)
+<ipython-input-61-3ef952c0fc7f> in <module>
+      1 fig, ax = plt.subplots(figsize=(17,8))
+      2 prob, = ax.plot(month, z)
+----> 3 btwn, = ax.fill_between(month, x, y, color='b', alpha=.3)
+      4 tgt, = ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
+      5 plt.xlabel('Month')
+
+TypeError: 'PolyCollection' object is not iterable
+
+

How can I add these things to the legend?

","

The matplotlib documentation often suggests to use proxy artists.

+

Otherwise, in your case, you can just add the label argument and name it the way you want, and the legend should be updated automatically.

+

In your case:

+
ax.plot(month, z, label="Probable Forecast")
+ax.fill_between(month, x, y, color='b', alpha=.3, label="Confidence Interval")
+
+

should work.

",python +"Average value and sum of strings for each day

I have a dataframe with 3 columns. I am using python / pandas.

+
     date         id         my_value1      my_value2
+0    31.07.20     128909      0.098333      positive
+1    31.07.20     128914      0.136364      positive
+3    31.07.20     853124     -0.025000      negative
+4    30.07.20     123456     -1.000000      neutral
+...
+
+

The first column contains the date (can be parsed to any other form) with days from 06.02.20 to 31.07.20 with some days missing. As you can see each day appears several times.

+

The column my_value1 contains a float number between 1 and -1.

+

The column my_value2 contains either the string "postive", "negative" or "neutral".

+

What I want is a new dataframe containing the average value of "my_value1" for each day and the sum of each value of "my_value2" which could look like this:

+
     date         average_value1     sum_positive     sum_negative     sum_neutral
+0    31.07.20      0.1               1532             2153             5321
+1    30.07.20      0.2               2153             5321             1532
+3    29.07.20     -0.3               1234             1234             1234
+...
+
+

Appreciate any help!

","

If the original DataFrame's index is unimportant, you could do

+
encoded_df = pd.get_dummies(df, prefix="", prefix_sep="", columns=["my_value2"])
+output = encoded_df.groupby("date").agg(
+    average_value1 = pd.NamedAgg("my_value1", "mean"),
+    sum_positive = pd.NamedAgg("positive", "sum"),
+    sum_negative = pd.NamedAgg("negative", "sum"),
+    sum_neutral = pd.NamedAgg("neutral", "sum")
+).reset_index()
+
+

Output:

+
       date  average_value1  sum_positive  sum_negative  sum_neutral
+0  30.07.20       -1.000000             0             0            1
+1  31.07.20        0.069899             2             1            0 
+
",python +"DJANGO EMAIL CONFIRMATION: [WinError 10061] No connection could be made because the target machine actively refused it

I'm trying to send an email verification code for account confirmation.

+

Now, the thing is that I am trying to send an email to myself first, and my other email. I have turned off my antivirus, so that shouldn't be a problem. Other than this I can't figure our what I did wrong that it is not sending emails on the gmail account. Please point out what I'm doing wrong. I even applied all the fixes mentioned by this thread.

+

views.py

+
from django.core.mail import send_mail
+from django.shortcuts import render,redirect
+from django.contrib import messages,auth
+from django.contrib.auth.models import User # this table already exists in django we import it 
+from django.contrib.auth import authenticate, login
+from django.conf import settings
+from django.core.mail import EmailMessage
+
+def register(request):
+    if request.method=='POST':
+        fname = request.POST['fname']
+        lname=request.POST['lname'] #request.post[id of the input field]
+        email = request.POST['email']
+        password = request.POST['pass']
+        password2 = request.POST['confirmpass']
+        agree=request.POST.get('agree')
+        if fname == '':
+             messages.warning(request, 'Please enter First name!')
+             return redirect('register')
+
+        if lname == '':
+             messages.warning(request, 'Please enter Last name!')
+             return redirect('register')
+
+        if email == '':
+             messages.warning(request, 'Please enter Email!')
+             return redirect('register')
+
+        if password == '':
+             messages.warning(request, 'Please enter Password!')
+             return redirect('register')
+
+        if password2 == '':
+             messages.warning(request, 'Please enter Confirm Password!')
+             return redirect('register')
+        if ('agree' not in request.POST):
+             messages.warning(request, 'Please agree to our terms and conditions!')
+             return redirect('register')
+
+        if password==password2:
+
+            if User.objects.filter(username=email):
+                messages.error(request,"Email Already Exists")
+                return redirect('register')
+            else:
+                user=User.objects.create_user(username=email,first_name=fname,last_name=lname,password=password) #these are postgres first_name,last_name
+                user.save()
+                messages.success(request,"Successfully Registered")
+                subject = 'Site Contact Form'
+                contact_message = "%s : %s via %s "%(fname, lname, email)
+                from_email = settings.EMAIL_HOST_USER
+                to_email = [from_email, 'myotheremail@gmail.com']
+                send_mail(subject, contact_message, from_email, to_email, fail_silently=False)
+    
+                return redirect('login')
+        
+        
+
+        else:
+            messages.error(request,"Passwords don't match")
+            return redirect('register')
+    else:
+        return render(request, 'signupdiv.html')
+
+

settings.py

+
EMAIL_HOSTS = 'smtp.gmail.com'
+EMAIL_HOST_USER = 'myemail@gmail.com'
+EMAIL_HOST_PASSWORD = '*****'
+EMAIL_PORT = 587
+EMAIL_USE_TLS = True
+EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
+DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
+
+

urls.py

+
from django.urls import path
+from . import views
+
+urlpatterns = [
+    path('login', views.login, name='login'), 
+    path('register', views.register, name='register'), 
+    path('logout', views.logout, name='logout'),
+]
+
+

When I register, the data successfuly stores into the database (as expected). But it gives error on send_email(params) from view.py of the code. Following is the error:

+
ConnectionRefusedError at /account/register
+[WinError 10061] No connection could be made because the target machine actively refused it
+Request Method: POST
+Request URL:    http://127.0.0.1:8000/account/register
+Django Version: 3.1.2
+Exception Type: ConnectionRefusedError
+Exception Value:    
+[WinError 10061] No connection could be made because the target machine actively refused it
+Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python37\lib\socket.py, line 716, in create_connection
+Python Executable:  C:\Users\User\Desktop\pfa\venv\Scripts\python.exe
+Python Version: 3.7.5
+Python Path:    
+['C:\\Users\\User\\Desktop\\pfa',
+ 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
+ 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
+ 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37\\lib',
+ 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37',
+ 'C:\\Users\\User\\Desktop\\pfa\\venv',
+ 'C:\\Users\\User\\Desktop\\pfa\\venv\\lib\\site-packages']
+Server time:    Sun, 25 Oct 2020 23:17:08 +0000
+
","

You missed a little bit trivial thing. +in settings.py

+

It should be EMAIL_HOST = 'smtp.gmail.com'

+

Not EMAIL_HOSTS = 'smtp.gmail.com'

",python +"discord.py (rewrite) How do I make a command to a specific channel

I need to make a command that is narrowed to only a specific channel. It sends a random picture of a car, but I have a channel called 'Pics' that i specifically need to narrow the command to. Can you help me out?

+
@client.command()
+async def car(ctx):
+    pictures = [
+    'https://car-images.bauersecure.com/pagefiles/78294/la_auto_show_11.jpg',
+    'http://www.azstreetcustom.com/uploads/2/7/8/9/2789892/az-street-custom-gt40-2_orig.jpg',
+    'http://tenwheel.com/imgs/a/b/l/t/z/1967_firebird_1968_69_70_2000_camaro_blended_custom_supercharged_street_car_1_lgw.jpg',
+    'https://rthirtytwotaka.files.wordpress.com/2013/06/dsc_0019.jpg',
+    'http://speedhunters-wp-production.s3.amazonaws.com/wp-content/uploads/2008/06/fluke27.jpg',
+    'https://i.ytimg.com/vi/pCt0KXC1tng/maxresdefault.jpg',
+    'https://i2.wp.com/www.tunedinternational.com/featurecars/dorift/02.jpg'
+    ]
+    channel = discord.utils.get()
+    if channel == 705161333972140072:
+        await ctx.channel.purge(limit=1)
+        await ctx.send(f'{random.choice(pictures)}')
+
","

Replace with

+
channel = bot.get_channel(705161333972140072)
+if ctx.channel == channel:
+  await ctx.channel.purge(limit=1)
+  await ctx.send(f'{random.choice(pictures)}')
+
+

Remove from your code

+
channel = discord.utils.get()
+if channel == 705161333972140072:
+    await ctx.channel.purge(limit=1)
+    await ctx.send(f'{random.choice(pictures)}')
+
+

Actually you were making a basic syntax error !

",python +"How to convert positive numbers to negative in Python?

I know that abs() can be used to convert numbers to positive, but is there somthing that does the opposite?

+

I have an array full of numbers which I need to convert to negative:

+
array1 = []
+arrayLength = 25
+for i in arrayLength:
+   array1.append(random.randint(0, arrayLength)
+
+

I thought perhaps I could convert the numbers as they're being added, not after the array is finished. Anyone knows the code for that?

+

Many thanks in advance

","

If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use:

+
    -abs(n)
+
+

Note that integer 0 will remain 0.

",python +"Error while obtaining start requests with Scrapy

I am having some trouble trying to scrape through these 2 specific pages and don't really see where the problem is. If you have any ideas or advices I am all ears ! +Thanks in advance !

+
import scrapy
+
+
+class SneakersSpider(scrapy.Spider):
+    name = "sneakers"
+    
+    def start_requests(self):
+        headers = {'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
+        urls = [ 
+            #"https://stockx.com/fr-fr/retro-jordans",
+            "https://stockx.com/fr-fr/retro-jordans?page=2",
+            "https://stockx.com/fr-fr/retro-jordans?page=3",
+            ]
+        for url in urls:
+            yield scrapy.Request(url = url, callback =self.parse ,headers = headers)
+            
+    def parse(self,response):
+        page = response.url.split("=")[-1]
+        filename = f'sneakers-{page}.html'
+        with open(filename, 'wb') as f:
+            f.write(response.body)
+        self.log(f'Saved file {filename}')
+            
+            
+            
+
+
+
","

Looking at the traceback always helps. You should see something like this in your spider's output:

+
Traceback (most recent call last):
+  File "c:\program files\python37\lib\site-packages\scrapy\core\engine.py", line 127, in _next_request
+    request = next(slot.start_requests)
+  File "D:\Users\Ivan\Documents\Python\a.py", line 15, in start_requests
+    yield scrapy.Request(url = url, callback =self.parse ,headers = headers)
+  File "c:\program files\python37\lib\site-packages\scrapy\http\request\__init__.py", line 39, in __init__
+    self.headers = Headers(headers or {}, encoding=encoding)
+  File "c:\program files\python37\lib\site-packages\scrapy\http\headers.py", line 12, in __init__
+    super(Headers, self).__init__(seq)
+  File "c:\program files\python37\lib\site-packages\scrapy\utils\datatypes.py", line 193, in __init__
+    self.update(seq)
+  File "c:\program files\python37\lib\site-packages\scrapy\utils\datatypes.py", line 229, in update
+    super(CaselessDict, self).update(iseq)
+  File "c:\program files\python37\lib\site-packages\scrapy\utils\datatypes.py", line 228, in <genexpr>
+    iseq = ((self.normkey(k), self.normvalue(v)) for k, v in seq)
+ValueError: too many values to unpack (expected 2)
+
+

As you can see, there is a problem in the code that handles request headers.

+

headers is a set in your code; it should be a dict instead.
+This works without a problem:

+
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
+
+

Another way to set a default user agent for all requests is using the USER_AGENT setting.

",python +"Scrape highchart into python

Can anyone tell me how can I extract the highchart data from the following link into python?

+

https://www.ree.es/en/datos/generation/generation-structure

","

Try below approach using python - requests simple, straightforward, reliable, fast and less code is required when it comes to requests. I have fetched the API URL from website itself after inspecting the network section of google chrome browser.

+

What exactly below script is doing:

+
    +
  1. First it will take the API URL which is created using dynamic parameters(all in caps) and do GET request. URL is dynamic you can pass any valid value in the params and the URL is created for you every time you want to fetch something from the chart.

    +
  2. +
  3. After getting the data script will parse the JSON data using json.loads library.

    +
  4. +
  5. Finally it will iterate all over the list of attributes and different values of the chart for ex:- Title, Type, Color, Last updates, percentage etc. you can modify these attributes as per your need.

    +
    import json
    +import requests
    +from urllib3.exceptions import InsecureRequestWarning
    +requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    +
    +def scrape_chart_data():
    +#### Dynamic Paramters######
    +START_DATE = '2020-10-22T00:00'
    +END_DATE = '2020-10-29T23:59'
    +TIME_TRUNC = 'day'
    +CACHED = 'true'
    +SYSTEM_ELECTRIC = 'nacional'
    +
    +URL = 'https://apidatos.ree.es/en/datos/generacion/estructura-generacion?start_date=' + START_DATE + '&end_date=' + END_DATE + '&time_trunc=' + TIME_TRUNC + \
    +'&cached=' + CACHED + '&systemElectric=' + SYSTEM_ELECTRIC  # Dynamic URL created using params
    +
    +response = requests.get(URL,verify = False) # GET API request
    +result = json.loads(response.text) # Parse JSON data
    +extracted_chart_data = result['included'] # extracted data using GET API call
    +
    +for idx in range(len(extracted_chart_data)): # iterate over the data and print attributes and values
    +    print('-' * 100)
    +    attributes = extracted_chart_data[idx]['attributes'] #attributes
    +    values = extracted_chart_data[idx]['attributes']['values'] #values
    +    print('Type : ', attributes['type'])
    +    print('Title : ', attributes['title'])
    +    print('Color : ', attributes['color'])
    +    print('Last Update : ', attributes['last-update'])
    +    print('Magnitude : ', attributes['magnitude'])
    +    print('-' * 50 + ' Values of ' + attributes['title'] + ' ' + '-' * 50)        
    +    for val in range(len(values)):           
    +        print('Date and Time : ', values[val]['datetime'])
    +        print('Percentage : ', values[val]['percentage'])
    +        print('Value : ', values[val]['value'])
    +    print('-' * 100)
    +
    +scrape_chart_data()
    +
    +
  6. +
",python +"Execute python program with multiple files - Python - Bash

I have hundreds of XML files and I would like to parse it into CSV files. I already code this program. +To execute the python program I use this command (on VScode MS):

+
python ConvertXMLtoCSV.py -i Alarm120.xml -o Alarm120.csv
+
+

My question is, how change this script to integrate a sort of for loop to execute this program for each xml files ?

+
+

UPDATE

+

If my files and folders are organized like in the picture:

+

+

I tried this and execute the file .bat in windows10 but it does nothing:

+
#!/bin/bash
+for xml_file in XML_Files/*.xml
+do
+   csv_file=${xml_file/.xml/.csv}
+   python ConvertXMLtoCSV.py -i XML_Files/$xml_file -o CSV_Files/$csv_file
+done
+
","

After discussion, it appears that you wish to use an external script so as to leave the original ConvertXMLtoCSV.py script unmodified (as required by other projects), but that although you tagged bash in the question, it turned out that you were not in fact able to use bash to invoke python when you tried it in your setup.

+

This being the case, it is possible to adapt Rolv Apneseth's answer so that you do the looping in Python, but inside a separate script (let's suppose that this is called convert_all.py), which then runs the unmodified ConvertXMLtoCSV.py as an external process. This way, the ConvertXMLtoCSV.py will still be set up to process only one file each time it is run.

+

To call an external process, you could either use os.system or subprocess.Popen, so here are two options.

+

Using os.system:

+
import os
+import sys
+
+directory_path = sys.argv[1]
+
+for file in os.listdir(directory_path):
+    if file.endswith(".xml"):
+        csv_name = file.replace(".xml", ".csv")
+        os.system(f'python ConvertXMLtoCSV.py -i {file} -o {csv_name}')
+
+

note: for versions of python too old to support f-strings, that last line could be changed to

+
        os.system('python ConvertXMLtoCSV.py -i {} -o {}'.format(file,csv_name))
+
+

Using subprocess.Popen:

+
import subprocess
+import sys
+
+directory_path = sys.argv[1]
+
+for file in os.listdir(directory_path):
+    if file.endswith(".xml"):
+        csv_name = file.replace(".xml", ".csv")
+        p = subprocess.Popen(['python', 'ConvertXMLtoCSV.py',
+                              '-i', file,
+                              '-o', csv_name])
+        p.wait()
+
+

You could then run it using some command such as:

+
python convert_all.py C:/Users/myuser/Desktop/myfolder
+
+

or whatever the folder is where you have the XML files.

",python +"Is there *any* solution to packaging a python app that uses cppyy?

I'm no novice when creating cross-platform runtimes of my python desktop apps. I create various tools for my undergraduates using mostly pyinstaller, cxfreeze, sometimes fbs, and sometimes briefcase. Anyone who does this one a regular basis knows that there are lots of quirks and adjustments needed to target Linux, windows, and macos when using arbitrary collections of python modules, but I've managed to figure everything out until now.

+

I have a python GUI app that uses a c++ library that is huge and ever-changing, so I can't just re-write it in python. I've successfully written python code that uses the c++ library using the amazing (and possibly magical) library called cppyy that allows you to run c++ code from python without hardly any effort. Everything runs great on Linux, mac, and windows, but I cannot get it packaged into runtimes and I've tried all the systems above. All of them have no problem producing the runtimes (i.e., no errors), but they fail when you run them. Essentially they all give some sort of error about not being able to find cppyy-backend (e.g., pyinstaller and fbs which uses pyinstaller gives this message when you run the binary):

+
/home/nogard/Desktop/cppyytest/target/MyApp/cppyy_backend/loader.py:113: UserWarning: No precompiled header available ([Errno 2] No such file or directory: '/home/nogard/Desktop/cppyytest/target/MyApp/cppyy_backend'); this may impact performance.
+Traceback (most recent call last):
+  File "main.py", line 5, in <module>
+  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
+  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
+  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
+  File "/home/nogard/Desktop/cppyytest/venv/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 628, in exec_module
+    exec(bytecode, module.__dict__)
+  File "cppyy/__init__.py", line 74, in <module>
+  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
+  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
+  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
+  File "/home/nogard/Desktop/cppyytest/venv/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 628, in exec_module
+    exec(bytecode, module.__dict__)
+  File "cppyy/_cpython_cppyy.py", line 20, in <module>
+  File "cppyy_backend/loader.py", line 74, in load_cpp_backend
+RuntimeError: could not load cppyy_backend library
+[11195] Failed to execute script main
+
+

I'm really stumped. Usually, you install cppyy with pip, which installs cppyy-backend and other packages. I've even used the cppyy docs methods to compile each dependency as well as cppyy, but the result is the same.

+

I'll use any build system that works...has anyone had success? I know I could use docker, but I tried this before and many of my students freaked out at docker asking them to change their bios settings to support virtualization So I'd like to use a normal packaging system that produces some sort of runnable binary.

+

If you know how to get pyinstaller, cxfreeze, fbs, or briefcase to work with cppyy (e.g, if you know how to deal with the error above), please let me know. However, if you've gotten a cppyy app packaged with some other system, let me know and I'll use that one.

+

If you're looking for some code to run, I've been testing out packaging methods using this minimal code:

+
import cppyy
+
+print('hello world from python\n')
+
+cppyy.cppexec('''
+#include <string>
+using namespace std;
+string mystring("hello world from c++");
+std::cout << mystring << std::endl;
+''')
+
","

EDIT: figured out the pyinstaller hooks; this should all be fully automatic once released

+

With the caveat that I have no experience whatsoever with packaging run-times, so I may be missing something obvious, but I've just tried pyinstaller, and the following appears to work.

+

First, saving your script above as example.py, then create a spec file:

+
$ pyi-makespec example.py
+
+

Then, add the headers and libraries from cppyy_backend as datas (skipping the python files, which are added by default). The simplest seems to be to pick up all directories from the backend, so change the generated example.spec by adding at the top:

+
def backend_files():
+    import cppyy_backend, glob, os
+
+    all_files = glob.glob(os.path.join(
+        os.path.dirname(cppyy_backend.__file__), '*'))
+
+    def datafile(path):
+        return path, os.path.join('cppyy_backend', os.path.basename(path))
+
+    return [datafile(filename) for filename in all_files if os.path.isdir(filename)]
+
+

and replace the empty datas in the Analysis object with:

+
             datas=backend_files(),
+
+

If you also need the API headers from CPyCppyy, then these can be found e.g. like so:

+
def api_files():
+    import cppyy, os
+
+    paths = str(cppyy.gbl.gInterpreter.GetIncludePath()).split('-I')
+    for p in paths:
+        if not p: continue
+       
+        apipath = os.path.join(p.strip()[1:-1], 'CPyCppyy')
+        if os.path.exists(apipath):
+            return [(apipath, os.path.join('include', 'CPyCppyy'))]
+
+    return []
+
+

and added to the Analysis object:

+
             datas=backend_files()+api_files(),
+
+

Note however, that Python.h then also needs to exist on the system where the package will be deployed. If need be, Python.h can be found through module sysconfig and its path provided through cppyy.add_include_path in the bootstrap.py file discussed below.

+

Next, consider the precompiled header (file cppyy_backend/etc/allDict.cxx.pch): this contains the C++ standard headers in LLVM intermediate representation. If addded, it pre-empts the need for a system compiler where the package is deployed. However, if there is a system compiler, then ideally, the PCH should be recreated on first use after deployment.

+

As is, however, the loader.py script in cppyy_backend uses sys.executable which is broken by the freezing (meaning, it's the top-level script, not python, leading to an infinite recursion). And even when the PCH is available, its timestamp is compared to the timestamp of the include directory, and rebuild if older. Since both the PCH and the include directory get new timestamps based on copy order, not build order, this is unreliable and may lead to spurious rebuilding. Therefore, either disable the PCH, or disable the time stamp checking.

+

To do so, choose one of these two options and write it in a file called bootstrap.py, by uncommenting the desired behavior:

+
### option 1: disable the PCH altogether
+
+# import os
+# os.environ['CLING_STANDARD_PCH'] = 'none'
+
+### option 2: force the loader to declare the PCH up-to-date
+
+# import cppyy_backend.loader
+#
+# def _is_uptodate(*args):
+#    return True
+#
+# cppyy_backend.loader._is_uptodate = _is_uptodate
+
+

then add the bootstrap as a hook to the spec file in the Analysis object:

+
             runtime_hooks=['bootstrap.py'],
+
+

As discussed above, the bootstrap.py is also a good place to add more include paths as necessary, e.g. for Python.h.

+

Finally, run as usual:

+
$ pyinstaller example.spec
+
",python +"Why is Pipenv not picking up my Pyenv versions?

My system Python version is 3.8.5, however I use pyenv to manage an additional version, 3.6.0, to mirror the server version my project is deployed to. I previously used virtualenv + virtualenvwrapper to manage my virtual environments, but I've heard great things on pipenv and thought I would give it a go. It's all great until I try using Python 3.6.0. Flow goes something like this:

+
$ mkdir test_project && cd test_project
+$ pyenv shell 3.6.0
+$ pipenv install django
+Creating a virtualenv for this project…
+Pipfile: /home/user/projects/test_project/Pipfile
+Using /home/user/.pyenv/shims/python (3.6.0) to create virtualenv…
+⠸ Creating virtual environment...created virtual environment CPython3.8.5.final.0-64 in 130ms
+  creator CPython3Posix(dest=/home/user/.local/share/virtualenvs/test_project-eAvoynKo-/home/user, clear=False, global=False)
+  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/user/.local/share/virtualenv)
+    added seed packages: pip==20.2.3, setuptools==50.3.0, wheel==0.35.1
+  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
+
+✔ Successfully created virtual environment! 
+Traceback (most recent call last):
+  File "/home/user/.pyenv/versions/3.6.0/bin/pipenv", line 11, in <module>
+    sys.exit(cli())
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 829, in __call__
+    return self.main(*args, **kwargs)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 782, in main
+    rv = self.invoke(ctx)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 1259, in invoke
+    return _process_result(sub_ctx.command.invoke(sub_ctx))
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 1066, in invoke
+    return ctx.invoke(self.callback, **ctx.params)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 610, in invoke
+    return callback(*args, **kwargs)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/decorators.py", line 73, in new_func
+    return ctx.invoke(f, obj, *args, **kwargs)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 610, in invoke
+    return callback(*args, **kwargs)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/vendor/click/decorators.py", line 21, in new_func
+    return f(get_current_context(), *args, **kwargs)
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/cli/command.py", line 252, in install
+    site_packages=state.site_packages
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/core.py", line 1928, in do_install
+    site_packages=site_packages,
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/core.py", line 580, in ensure_project
+    pypi_mirror=pypi_mirror,
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/core.py", line 512, in ensure_virtualenv
+    python=python, site_packages=site_packages, pypi_mirror=pypi_mirror
+  File "/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pipenv/core.py", line 986, in do_create_virtualenv
+    with open(project_file_name, "w") as f:
+FileNotFoundError: [Errno 2] No such file or directory: '/home/user/.local/share/virtualenvs/test_project-eAvoynKo-/home/user/.pyenv/shims/python/.project'
+
+
+

I came across this previous question Pipenv not recognizing Pyenv version? and set the environment variable PIPENV_PYTHON="$PYENV_ROOT/shims/python in my .bashrc file. to no avail.

+

Using the system Python version 3.8.5 works flawlessly:

+
$ pyenv install django
+Creating a virtualenv for this project…
+Pipfile: /home/user/projects/test_project/Pipfile
+Using /home/user/.pyenv/shims/python (3.8.5) to create virtualenv…
+⠹ Creating virtual environment...created virtual environment CPython3.8.5.final.0-64 in 114ms
+  creator CPython3Posix(dest=/home/user/.local/share/virtualenvs/test_project-eAvoynKo-/home/user/.pyenv/shims/python, clear=False, global=False)
+  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/user/.local/share/virtualenv)
+    added seed packages: pip==20.2.2, setuptools==50.3.0, wheel==0.35.1
+  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
+
+✔ Successfully created virtual environment! 
+Virtualenv location: /home/user/.local/share/virtualenvs/test_project-eAvoynKo-/home/user/.pyenv/shims/python
+Creating a Pipfile for this project…
+Installing django…
+Adding django to Pipfile's [packages]…
+✔ Installation Succeeded 
+Pipfile.lock not found, creating…
+Locking [dev-packages] dependencies…
+Locking [packages] dependencies…
+Building requirements...
+Resolving dependencies...
+✔ Success! 
+Updated Pipfile.lock (a6086c)!
+Installing dependencies from Pipfile.lock (a6086c)…
+     ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00
+To activate this project's virtualenv, run pipenv shell.
+Alternatively, run a command inside the virtualenv with pipenv run.
+
+

Update

+

While I still can't get it to recognize the python version activated with pyenv shell x.x.x, by removing the PIPENV_PYTHON environment variable, and creating a new virtualenv with pipenv install --python 3.6 pipenv does recognize the pyenv version installed.

","

pipenv doesn't respect pyenv local and pyenv global (reference)

+

maybe it also doesn't respect pyenv shell

+

I usually do what you did, specify the python like pipenv install --python 3.7

",python +"while loop equivalent function/snippet in awkward array

I have a function which I would like to convert so that i can use with awkward array 1.

+

Function following which used to work for float but not for awkward arrays for the known reasons.

+
def Phi_mpi_pi(x):
+    kPI=(3.14159265)
+    kTWOPI = 2 * kPI
+
+    #while ((x.any() >= kPI).any()): x = x - kTWOPI;                                                                                                                                                        
+    #while ((x.any() < -kPI).any()): x = x + kTWOPI;                                                                                                                                                        
+    while ((x >= kPI)): x = x - kTWOPI;
+    while ((x < -kPI)): x = x + kTWOPI;
+    return x;
+
+

I tried to convert it into numpy/awkward compatible form and new function look like

+
def Phi_mpi_pi(x):
+    kPI=numpy.array(3.14159265)
+    kPI = kPI.repeat(len(x))
+    kTWOPI = 2 * kPI
+    while ((x >= kPI)): x = x - kTWOPI;
+    while ((x < -kPI)): x = x + kTWOPI;
+    return x;
+
+

This function remains stuck in the while loop forever, I couldn't find a way to debug it.

+

Task of the function is to keep the values in an awkward array between +- kPI but this logic does not give the desired results.

+

e.g.

+
x=ak.Array([[0.7999999999999998, 1.0, -1.3], [], [-1.4], [-1.8000000000000003, -6.1000000000000005, -1.6000000000000005], [-4.6]])
+
+

However ((x < -kPI)) this give desired output.

+
>>> ak.to_list(x <= -kPI)
+    [[False, False, False], [], [False], [False, True, False], [True]]
+
+

but not the function

+

the desired output should be b/w +- kPI based on the logic of while loop, is there something straightforward or suggestion which can be used?

","

Okay, got it. You want to adjust every single scalar value in x (which are all angles) to be between -π and π.

+

You can do it like this:

+
def Phi_mpi_pi(x):
+    y = numpy.add(x, numpy.pi)
+    y = numpy.mod(y, 2*numpy.pi)
+    y = numpy.subtract(y, numpy.pi)
+    return y
+
+

Or, more terse and much less readable:

+
def Phi_mpi_pi(x):
+    return numpy.subtract(numpy.mod(numpy.add(x, numpy.pi), 2*numpy.pi), numpy.pi)
+
+

What it does is this:

+
    +
  1. Add π to all angles (so they point in the opposite direction).
  2. +
  3. Take modulo 2π on all angles so they are all from 0 to 2π (2π not included).
  4. +
  5. Subtract π from all the angles again (so they point in the right direction again). Now they are all from -π to +π (+π not included).
  6. +
+

Test:

+
x = ak.Array([[0.3, 3.1, numpy.pi, -numpy.pi, -4 * numpy.pi,
+               200 * numpy.pi, 2 * numpy.pi, -400 * numpy.pi], 
+              [], [-1.4], [-1.8, -6, -1.6], [-4.6]])
+y = Phi_mpi_pi(x)
+print("Type of result:", type(y))
+print("Result =", y)
+
+# Check that the resulting range of each value is correct.
+range_is_correct = (ak.all(y >= -numpy.pi) and ak.all(y < numpy.pi))
+
+# Calculate the factors of the 2π adjustments.
+factors = (x - y) / (2 * numpy.pi)
+print("2π factors=", factors)
+
+# Test that all factors of the 2π adjustmenst are approximate integers.
+adjustments_are_correct = ak.all(numpy.abs(numpy.mod(factors, 1)) < 1e-15)
+
+# Test that all values are correct, given the test input.
+print("Result is correct:", range_is_correct and adjustments_are_correct)
+
+

gives this output:

+
Type of result: <class 'awkward1.highlevel.Array'>
+Result = [[0.3, 3.1, -3.14, -3.14, 0, 1.78e-14, 0, 4.62e-14, ... [-1.8, 0.283, -1.6], [1.68]]
+2π factors= [[2.65e-17, 7.07e-17, 1, 0, -2, 100, 1, -200], [], [0], [0, -1, 0], [-1]]
+Result is correct: True
+
+

which proves that the operation was correctly performed with the specifically used test data.

+

Was that what you wanted?

",python +"Gradient colour for scatter plot based on age similarity

I have people from different communities that I would like to plot visually using a scatter plot with different colours based on their distance: if they are close to other points than they should take a similar colour.

+

I know that for a scatter plot I should use the following

+
ax1 = df.plot.scatter(x='Year',
+                       y='Community')
+
+

but I do not know how to set a similar condition. +For example:

+
Community            Year
+com1                 2006
+com2                 2012
+com3                 2006
+com4                 2013
+com5                 1996
+com6                 2008
+...
+
+

I should have com1 and com3 with same colour and com6 a colour similar, while com2 and com4 should have similar colour to each other.

+

I think it is something about gradient. +Can you give me some information on how to do it in python?

","

Let's just pass Year as color:

+
ax1 = df.plot.scatter(x='Year',y='Community', c=df['Year'], cmap='hot')
+
+

Output:

+

",python +"PyInstaller won't import pywin32 / win32clipboard - ImportError upon running executable

I'm working in Windows 10 with Python 3.8.6 and using PyInstaller 4.0 to compile my script as an executable for distribution. I just added a feature today that required importing win32clipboard. PyInstaller finishes compiling without any errors, but the excecutable fails to load due to:

+
+

ImportError: DLL load failed while importing win32clipboard: The specified module could not be found.

+
+

I attempted to compile the program again using the hidden-import flag:

+

pyinstaller myscript.py --onefile --hidden-import win32clipboard

+

This produced the same result and an ImportError upon trying to load the program (no errors during compiling).

+

I know that win32clipboard is part of pywin32 and my program compiled and ran without any issues prior to the code changes that required importing it. It still runs fine out of IDLE and functions as intended when using the win32clipboard-enabled features.

+

Is there some way to manually direct PyInstaller to import this correctly, or some other way to fix this issue and get the executable working again?

","

I was able to work around this issue by importing pywintypes into my script before win32clipboard.

+
import pywintypes
+import win32clipboard
+
+

Found the suggestion in an old GitHub bug report for an issue people were having importing win32api with PyInstaller and decided to give it a try. I was able to compile and run my program without any issues after doing this.

",python +"Readlines causing error after many lines?

I'm working on a NRE task at the moment, with data from wnut17train.conll (https://github.com/leondz/emerging_entities_17). It's basically a collection of tweets where each line is a single word from the tweet with an IOB tag attached (separated by a \t). Different tweets are separated by a blank line (actually, and weirdly enough if you ask me, a '\t\n' line).

+

So, for reference, a single tweet would look like this:

+
@paulwalk    IOBtag
+...          ...
+foo          IOBtag
+[\t\n]
+@jerrybeam   IOBtag
+...          ...
+bar          IOBtag
+
+

The goal for this first step is to achieve a situation where I converted this data set into a training file looking like this:

+
train[0] = [(first_word_of_first_tweet, POStag, IOBtag),
+(second_word_of_first_tweet, POStag, IOBtag),
+...,
+last_word_of_first_tweet, POStag, IOBtag)]
+
+

This is what I came up so far:

+
tmp = []
+train = []
+nlp = spacy.load("en_core_web_sm")
+with open("wnut17train.conll") as f:
+    for l in f.readlines():
+        if l == '\t\n':
+            train.append(tmp)
+            tmp = []
+        else:
+            doc = nlp(l.split()[0])
+            for token in doc:
+                tmp.append((token.text, token.pos_, token.ent_iob_))
+
+

Everything works smoothly for a certain amount of tweets (or lines, not sure yet), but after that I get a

+
IndexError: list index out of range
+
+

raised by

+
doc = nlp(l.split()[0])
+
+

First time I got it around line 20'000 (20'533 to be precise), then after checking that this was not due to the file (maybe a different way of separating tweets, or something like this that might have tricked the parser) I removed the first 20'000 lines and tried again. Again, I got an error after around line 20'000 (20'260 - or 40'779 in the original file - to be precise).

+

I did some research on readlines() to see if this was a known problem but it looks like it's not. Am I missing something?

","

I used the wnut17train.conll file from https://github.com/leondz/emerging_entities_17 and I ran a similar code to generate your required output. I found that in some lines instead of "\t\n" as the blank Line we have only "\n".

+

Due to this l.split() will give an IndexError: list index out of range. To handle this we can check if length is 1 and in that case also we add our tmp to train.

+
import spacy
+nlp = spacy.load("en_core_web_sm")
+train = []
+tmp = []
+with open("wnut17train.conll") as fp:
+    for l in fp.readlines():
+        if l == "\t\n" or len(l) == 1:
+            train.append(tmp)
+            tmp = []
+        else:
+            doc = nlp(l.split("\t")[0])
+            for token in doc:
+                tmp.append((l.split("\t")[0], token.pos_, l.split("\t")[1]))
+
+

Hope your question is resolved.

",python +"Adding numbers in the same indices in list of lists

Say I have a list a=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]. I want to create a new list, b with each value in the new list being the sum of all values in that index location of each sub-list. +So in this case it would be [15,18,21,24] (1+5+9, 2+6+10, 3+7+11, 4+8+12) +. This is what my code looks like at the moment.

+
a=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
+for i in range(len(a)+1):
+    b.append(sum(b[i] for b in a))
+print(b)
+>>> [15, 18, 21, 24]
+
+

I tried to use list comprehension to simplify into:

+

b=[sum([c[i]] for c in a) for i in range(len(a)+1)]

+

however I get an error TypeError: unsupported operand type(s) for +: 'int' and 'list'

+

Ive tried googling the problem, but all I can find is people adding lists to integers. In this code it should only be adding integers (a[c[i]]). Whatve I done wrong?

+

EDIT: as Marc Ittel pointed out, there [c[i]] should just be c[i]. However as Yatu pointed out, using map and zip is much simpler. +Also as everyone has pointed out, it should not be len(a)+1 but rather len(a[0])

+

Thanks a lot everyone!

","

This can be done quite simply using python's built-ins:

+
list(map(sum,zip(*a)))
+#[15, 18, 21, 24]
+
+

Your approach produces the expected result, not sure how you defined b though? If it is an empty list b=[], this works fine. +Also, are you sure about this for - for i in range(len(a)+1)?. Shouldn't you be iterating over as many items as you have in the inner lists?

+

Your list comprehension should be:

+
[sum(b[i] for b in a) for i in range(4)]
+# [15, 18, 21, 24]
+
+

In your code, you have [c[i]] in the inner level. You're generating a list of lists which you don't need. Just index the list and keep the integer b[i].

",python +"adding rows to pandas dataframe within loop

There is a table that I have scraped from a site which I need to convert to a dataframe. Its html dom looks like this:

+
<tbody>
+    <tr>
+        <td>value1</td>
+        <td>value2</td>
+        <td>&nbsp;</td>
+        ...
+    <tr>
+        <td>value1</td>
+        <td>&nbsp</td>
+        <td>&nbsp;</td>
+        ...
+
+

I am using beautifulsoup to scrape the page:

+
table=soup.find('tbody')
+for row  in soup.find_all('tr'):
+    value=row.find('td')
+    print(value.text)
+
+

I want to append this value.text to rows to a data frame including the &nbsp; values (as NaN).

+

this is a sample output of print(value.text)(the blank spaces represent &nbsp; values):

+
20Q4 FDLR WW Event Webinar 13 FixIssues - Didn't Attend
+205
+204
+0
+0.00%
+1
+0.49%
+1
+0.49%
+179
+87.75%
+65
+31.86%
+3
+1.47%
+3
+1.47%
+3
+ 
+4.62%
+1
+0.49%
+1
+0
+0.00%
+0
+0.00%
+0 
+
+

The first contains the headers of the table. +How do I go about doing so? Thanks a bunch! :)

","

You can simply use the pd.read_html function to convert the html into a dataframe. Here is how you do it:

+
import pandas as pd
+
+table=soup.find('table') #Important thing to note: You have to provide the entire table to pd.read_html, not just the body of the table. Only then it would work.
+
+dfs = pd.read_html(str(table))
+
+df = dfs[0] #The output of pd.read_html is a list. In order to access your table (i.e the first and last element of the list), you can use dfs[0] 
+
",python +"Django - ListView url not connecting to desired view

I am new to Django and have hit a wall with a certain part of my project and I hope someone can help.

+

I have two ListViews in my views.py file which I would like to work similar to published/draft posts (I'm actually using sanitised and unsanitised reports). Currently, every time I try to access the "Unsanitised" list view (unsanitised_list.html), it just directs me to the the sanitised list view (intelreport_list.html)

+

views.py:

+
class IntelReportListView(ListView):
+  model = IntelReport
+  context_object_name = 'all_logs'
+
+  def get_queryset(self):
+    return IntelReport.objects.filter(create_date__lte=timezone.now()).order_by('-create_date')
+
+
+
+class UnsanitisedListView(LoginRequiredMixin, ListView):
+    login_url = '/login/'
+    redirect_field_name = 'intel_db/unsanitised_list.html'
+    
+    model = IntelReport
+
+    def get_queryset(self):
+      return IntelReport.objects.filter(sanitised__isnull=True).order_by('-create_date')
+
+

models.py

+
class IntelReport(models.Model):
+    gpms_choices = (
+      ***REDACTED***
+    )
+    gpms = models.CharField(max_length=20, blank=True, null=True, choices=gpms_choices)
+    
+    officer = models.CharField(max_length=50)
+    create_date = models.DateTimeField(auto_now_add=True)
+    sanitised = models.BooleanField(default=False)
+
+    source_eval_choices = (
+      ***REDACTED****
+    )
+    source_eval = models.CharField(max_length=50, blank=True, null=True, choices=source_eval_choices)
+    
+    intel_eval_choices = (
+      ***REDACTED***
+    )
+    intel_eval = models.CharField(max_length=100, blank=True, null=True, choices=intel_eval_choices)
+
+    report = models.TextField(max_length=5000, blank=True, null=True)
+
+    def sanitised_log(self):
+      self.sanitised = True
+      self.save()
+
+    def get_absolute_url(self):
+      return reverse('log_details', kwargs={'pk':self.pk})
+
+    def __str__(self):
+      return str(self.pk)
+
+

urls.py

+

from django.urls import path +from intel_db import views

+
urlpatterns = [
+    path('welcome/', views.AboutView.as_view(), name='about'),
+    path('logs/', views.IntelReportListView.as_view(), name='log_list'),
+    path('logs/<int:pk>/', views.IntelReportDetailView.as_view(), name='log_detail'),
+    path('logs/new_log/', views.IntelReportCreateView.as_view(), name='new_log'),
+    path('unsanitised/', views.UnsanitisedListView.as_view(), name='unsanitised'),
+    path('logs/<int:pk>/sanitise_log/', views.sanitsed_report, name='sanitised_report'),
+]
+
+

and on my landing page (landing.html), this is the link I'm using to try and reach the unsanitised_list.html:

+
      **<a href="{% url 'unsanitised' %}">**
+        
+
+

I cannot figure out why it keeps redirecting me to intelreport_lists.html (the sanitised logs) rather than unsanitised_list.html (the unsanitised logs).

+

I hope I'm not just missing something really simple but I've been over it and tried to re-write it innumerable times and can't get it right.

+

I hope this is enough information and any help would be greatly appreciated.

+

Cheers

","

You just have to override template_name when you extend ListView. I mean update your IntelReportListView and UnsanitisedListViewlike this,

+
class IntelReportListView(ListView):
+  model = IntelReport
+  context_object_name = 'all_logs'
+  template_name = 'YOUR_APP_NAME/intelreport_list.html'
+
+  def get_queryset(self):
+    return IntelReport.objects.filter(create_date__lte=timezone.now()).order_by('-create_date')
+
+
+
+class UnsanitisedListView(LoginRequiredMixin, ListView):
+    login_url = '/login/'
+    redirect_field_name = 'intel_db/unsanitised_list.html'
+    template_name = 'YOUR_APP_NAME/unsanitised_list.html'
+    model = IntelReport
+
+    def get_queryset(self):
+      return IntelReport.objects.filter(sanitised__isnull=True).order_by('-create_date')
+
+

If you are interested to find out why it was redirecting to intelreport_list.html rather than unsanitised_list.html, whenever you extend ListView it will look for MODEL_NAME_list.html by default, where MODEL_NAME is name of the model that you have used inside your list views (in lower case). Since you have used model = IntelReport inside UnsanitisedListView, it's redirecting to intelreport_lists.html

",python +"How to find and print a dictionary key/value that matches user input?

I need to print a dictionary value that matches the input of the user. For example, if the user enters the course number CS101 the output will look like:

+
The details for CS101 are:
+Room: 3004
+Instructor: Haynes
+Time: 8:00 a.m.
+
+

However, if the user enters an incorrect/invalid course number, I need to print out a message letting them know:

+
CS101 is an invalid course number.
+
+

I have tried if, for loops, and while loops. The problem is, every time I get the course info printed, the invalid course number message won't display because of KeyError. On the other hand, if I happen to "fix" the error message, then the course number info won't print out and instead will return a NameError / TypeError. +I will be honest, I have struggled for some time now with this, and I feel as though I am either assigning something incorrectly or printing incorrectly. But I am a beginner and I don't have a great grasp on Python yet, which is why I am asking for help. +Unfortunately, I am not allowed to create one entire dictionary to group everything in (which would have been easier for me), but instead, I have to create 3 dictionaries. +This is the code:

+
room = {}
+
+room["CS101"] = "3004"
+room["CS102"] = "4501"
+room["CS103"] = "6755"
+room["NT110"] = "1244"
+room["CM241"] = "1411"
+
+instructor = {}
+
+instructor["CS101"] = "Haynes"
+instructor["CS102"] = "Alvarado"
+instructor["CS103"] = "Rich"
+instructor["NT110"] = "Burkes"
+instructor["CM241"] = "Lee"
+
+time = {}
+
+time["CS101"] = "8:00 a.m."
+time["CS102"] = "9:00 a.m."
+time["CS103"] = "10:00 a.m."
+time["NT110"] = "11:00 a.m."
+time["CM241"] = "1:00 p.m."
+
+def info():
+    print(f'College Course Locater Program')
+    print(f'Enter a course number below to get information')
+
+info()
+get_course = input(f'Enter course number here: ')
+print(f'----------------------------------------------')
+
+course_num = get_course
+number = course_num
+name = course_num
+meeting = course_num
+
+if number in room:
+    if name in instructor:
+        if meeting in time:
+            print(f'The details for course {get_course} are: ')
+            print(f'Room: {number["room"]}')
+            print(f'Instructor: {name["instructor"]}')
+            print(f'Time: {meeting["time"]}')
+else:
+    print(f'{course_num} is an invalid course number.')
+
+

I have also tried formatting dictionaries in this style:

+
time_dict = {
+    "CS101": {
+        "Time": "8:00 a.m."
+    },
+    "CS102": {
+        "Time": "9:00 a.m."
+    },
+    "CS103": {
+        "Time": "10:00 a.m."
+    },
+    "NT110": {
+        "Time": "11:00 a.m."
+    },
+    "CM241": {
+        "Time": "1:00 p.m."
+    },
+}
+
+

I thank everyone in advance who has an advice, answer, or suggestions to a solution.

","

This code here is unnecessary, because you are essentially setting 4 variables all to the same value get_course:

+
course_num = get_course
+number = course_num
+name = course_num
+meeting = course_num 
+
+

This code here doesn't work because you are trying to find a key with string "room" in a dictionary that doesn't exist, and same with the other lines afterwards

+
print(f'Room: {number["room"]}')
+print(f'Instructor: {name["instructor"]}')
+print(f'Time: {meeting["time"]}')
+
+

I replaced the code above with this:

+
print(f'Room: {room[get_course]}')
+print(f'Instructor: {instructor[get_course]}')
+print(f'Time: {time[get_course]}')
+
+

This searches the dictionary variable room for the key get_course (ex. "CS101") and returns the value corresponding to that key. The same thing happens for the other lines, except with the dictionary instructor and the dictionary time.

+

Here is the final code:

+
room = {}
+
+room["CS101"] = "3004"
+room["CS102"] = "4501"
+room["CS103"] = "6755"
+room["NT110"] = "1244"
+room["CM241"] = "1411"
+
+instructor = {}
+
+instructor["CS101"] = "Haynes"
+instructor["CS102"] = "Alvarado"
+instructor["CS103"] = "Rich"
+instructor["NT110"] = "Burkes"
+instructor["CM241"] = "Lee"
+
+time = {}
+
+time["CS101"] = "8:00 a.m."
+time["CS102"] = "9:00 a.m."
+time["CS103"] = "10:00 a.m."
+time["NT110"] = "11:00 a.m."
+time["CM241"] = "1:00 p.m."
+
+def info():
+    print(f'College Course Locater Program')
+    print(f'Enter a course number below to get information')
+
+info()
+get_course = input(f'Enter course number here: ')
+print(f'----------------------------------------------')
+
+
+if get_course in room and get_course in instructor and get_course in time:
+    print(f'The details for course {get_course} are: ')
+    print(f'Room: {room[get_course]}')
+    print(f'Instructor: {instructor[get_course]}')
+    print(f'Time: {time[get_course]}')
+else:
+    print(f'{get_course} is an invalid course number.')
+
+

Here is a test with the input "CS101":

+
College Course Locater Program
+Enter a course number below to get information
+Enter course number here: CS101
+----------------------------------------------
+The details for course CS101 are:
+Room: 3004
+Instructor: Haynes
+Time: 8:00 a.m.
+
",python +"How to calculate NDCG with binary relevances using sklearn?

I'm trying to calculate the NDCG score for binary relevances:

+
from sklearn.metrics import ndcg_score
+y_true = [0, 1, 0]
+y_pred = [0, 1, 0]
+ndcg_score(y_true, y_pred)
+
+

And getting:

+
ValueError: Only ('multilabel-indicator', 'continuous-multioutput',  
+'multiclass-multioutput') formats are supported. Got binary instead
+
+

Is there a way to make this work?

","

Please try:

+
from sklearn.metrics import ndcg_score
+y_true = [[0, 1, 0]]
+y_pred = [[0, 1, 0]]
+ndcg_score(y_true, y_pred)
+1.0
+
+

Note the expected shapes in the docs:

+
+

y_true: ndarray, shape (n_samples, n_labels)
+y_score: ndarray, shape (n_samples, n_labels)

+
",python +"""init_dgelsd failed init"" When using import numpy as np

I am trying to run this simple code

+
import numpy as np
+
+my_first_array = np.array([1, 2, 3,4,5])
+
+my_first_array([1, 2, 3, 4, 5])
+
+

I believe I am using python 3.9 as i just bought this computer and downloaded the newest version. +But keep getting the error code:

+
Traceback (most recent call last):
+  File "/Users/oledy/Documents/Skole/Dat200/test.py", line 1, in <module>
+    import numpy as np
+  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/__init__.py", line 286, in <module>
+    raise RuntimeError(msg)
+RuntimeError: Polyfit sanity test emitted a warning, most likely due to using a buggy Accelerate backend. If you compiled yourself, see site.cfg.example for information. Otherwise report this to the vendor that provided NumPy.
+RankWarning: Polyfit may be poorly conditioned
+
","

If you care to read up on the issue here is where I found the solution below.

+
rm -v ~/Library/Caches/pip/wheels/*/*/*/*/*numpy* # clear the pip wheel cache of any built numpy wheels
+brew install openblas # make sure OpenBLAS is installed
+# activate your virtualenv
+OPENBLAS="$(brew --prefix openblas)" pip install numpy # let numpy's setup.py know where OpenBLAS is installed
+
",python +"Transform a Pandas Series into a Dataframe with a for loop

Thank in advance for anyone's help.

+

I'm trying to transform this Pandas series into a Dataframe with the following logic.

+

Any time a row from the series starts with "MB" it should create another column in the dataframe, and all the rows below it until the next "MB" should go under that column.

+
MB104
+TR15
+TR16
+SP16
+MB301
+TR16
+SP11
+SP16
+SP26
+SP67
+MB302
+TR15
+MB504
+TR15
+SP16
+SP67
+SP109
+MB652
+SP109
+SP110
+
+

Into this:

+
MB104    MB031    MB302    MB504    MB652
+TR15     TR16     TR15     TR15     SP109
+TR16     SP11              SP16     SP110
+SP16     SP16              SP67
+         SP26              SP109
+         SP67
+
+

And this is what I've tried so far

+
mbdf = pd.DataFrame()
+assetlist = []
+for row in mbs.itertuples():
+    left2 = row.data[:2]
+    if left2 == 'MB':
+        if headername:
+            mbdf[headername] = pd.Series(assetlist)
+    
+    headername = row.data
+    assetlist = []
+else:
+    assetname = row.data
+    assetlist.append(assetname)
+
","

It's unclear from your question whether you want them as separate Series or together in the same DataFrame. I assume you want a DataFrame:

+
# Read the data
+from collections import defaultdict
+data = defaultdict(list)
+col = None
+
+with open('data.txt') as fp:
+    for line in fp:
+        line = line.strip('\n')
+        if line.startswith('MB'):
+            col = line
+        else:
+            data[col].append(line)
+
+

If you want a collection of series:

+
series = [pd.Series(value, name=key) for key, value in data.items()]
+
+

If you want a DataFrame:

+
# Pad every column to the same length
+max_len = max(len(v) for v in data.values())
+
+for key, value in data.items():
+    value += [None for _ in range(max_len - len(value))]
+
+df = pd.DataFrame(data)
+
",python +"Find repeated sentences within text

I would like to know how I could find similarity within the same sentence. +I have a list of sentences like these:

+
my_list=["do you want pizza for dinner? Do you want pizza for dinner?", "I like pizza", "I have no money I have no money"]
+
+

I would like to create a pandas dataframe where, if a sentence is repeated within the same, I assign 1, otherwise 0.

+

Something like this:

+
Text                                                              Repeated?
+do you want pizza for dinner? Do you want pizza for dinner?            1
+I like pizza                                                           0
+I have no money I have no money                                        1
+
+

I was thinking of something like this:

+
from collections import Counter
+
+
+my_list = dict(Counter(my_list.split()))
+for i in sorted(my_list.keys()):
+    print ('"'+i+'" is repeated '+str(my_list[i])+' time.')
+
+

Then counting how many words there are in total and how many unique words there are in total in that sentence. But I think it would be not good as coding. +Do you know if there is another way to get the expected result?

","

You can use regular expression for the task (regex101):

+
import re
+import pandas as pd
+
+my_list=["do you want pizza for dinner? Do you want pizza for dinner?", "I like pizza", "I have no money I have no money"]
+df = pd.DataFrame({'Text': my_list})
+
+r = re.compile(r'(.+)\s*\1$', flags=re.I)
+df['Repeated'] = df['Text'].apply(lambda x: bool(r.match(x))).astype(int) 
+print(df)
+
+

Prints:

+
                                                Text  Repeated
+0  do you want pizza for dinner? Do you want pizz...         1
+1                                       I like pizza         0
+2                    I have no money I have no money         1
+
",python +"Getting import error when importing db from app.py

app.py file

+
from flask import Flask
+from flask_sqlalchemy import SQLAlchemy
+from database import CreateQuestions
+
+app = Flask(__name__)
+app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://jim:password@localhost:5433/exquizdb"
+db = SQLAlchemy(app)
+
+
+@app.route('/questions')
+def post_question():
+    q = 'hey'
+    a = 'hi'
+    CreateQuestions.Create_questions(q, a)
+
+
+@app.route('/')
+def hello_world():
+    return 'Hello World!'
+
+
+if __name__ == '__main__':
+    app.run()
+
+

database.py

+
# database.py
+from app import db
+
+
+class Questions(db.Model):
+    question_id = db.Column(db.Integer, primary_key=True)
+    question = db.Column(db.Text)
+
+
+class Answers(db.Model):
+    answer_id = db.Column(db.Integer, primary_key=True)
+    answer = db.Column(db.Text)
+    question_id = db.Column(db.Integer, db.ForeignKey('questions.question_id'))
+
+
+class CreateQuestions:
+    def create_questions(self, q, a):
+        ques = Questions(question=q)
+        ans = Answers(answer=a)
+        db.create_all()
+        db.session.add(ques)
+        db.session.add(ans)
+        db.session.commit()
+
+

when I run the app, the crashes with 'ImportError: cannot import name 'db' from 'app''. I don't know what I am doing wrong. When I do them on the same file it works. when I takeout the database Model from the app.py file it doesnt work anymore. Thank you for your help

","

import database after you instantiate your db.

+
from flask import Flask
+from flask_sqlalchemy import SQLAlchemy
+
+app = Flask(__name__)
+app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://jim:password@localhost:5433/exquizdb"
+db = SQLAlchemy(app)
+from database import CreateQuestions
+
",python +"How to retrieve attributes from selected datum in Altair?

I have a Streamlit dashboard which lets me interactively explore a t-SNE embedding using an Altair plot. I am trying to figure out how to access the metadata of the selected datum so that I can visualize the corresponding image. In other words, given:

+
selector = alt.selection_single()
+chart = (
+    alt.Chart(df)
+    .mark_circle()
+    .encode(x="tSNE_dim1", y="tSNE_dim2", color="predicted class", tooltip=["image url", "predicted class"])
+    .add_selection(selector)
+)
+
+

...is there something akin to

+
selected_metadata = selector.tooltip
+update_dashboard_img(img=selected_metadata["image url"], caption=selected_metadata["predicted class"])
+
+

I am aware about image marks but the images are on S3 and there are too many of them to fit in the plot.

","

I hate to disagree with the creator of Altair, but I was able to achieve this using streamlit-vega-lite package. This works by wrapping the call to the chart creation function with altair_component():

+
    from streamlit_vega_lite import altair_component
+    ...
+
+    event_dict = altair_component(altair_chart=create_tsne_chart(tsne_df))
+    # note: works with selector = alt.selection_interval(), not selection_single()
+    dim1_bounds, dim2_bounds = event_dict.get("dim1"), event_dict.get("dim2")
+    if dim1_bounds:
+        (dim1_min, dim1_max), (dim2_min, dim2_max) = dim1_bounds, dim2_bounds
+        selected_images = tsne_df[
+            (tsne_df.dim1 >= dim1_min)
+            & (tsne_df.dim1 <= dim1_max)
+            & (tsne_df.dim2 >= dim2_min)
+            & (tsne_df.dim2 <= dim2_max)
+        ]
+        st.write("Selected Images")
+        st.write(selected_images)
+
+        if len(selected_images) > 0:
+            for _index, row in selected_images.iterrows():
+                img = get_img(row["image url"])
+                st.image(img, caption=f"{row['image url']} {row['predicted class']}", use_column_width=True)
+
+

The event_dict only contains information about the selector bounds. So, you have to use those values to reselect the data that was selected in the interactive chart.

+

Note that this package is a POC and has various limitations. Please upvote the Streamlit feature request created by the author of streamlit_vega_lite.

",python +"Sublime Text 3: How do I make a keybind to enable and disable Anaconda linting?

I want to be able to use a hotkey to enable/disable anaconda linting. Its really inconvenient to have to open the settings whenever I had to use it. I'm new to Sublime Text but from what I see at the Keybindings, you can pass a variable with the args. For example:

+
[{"keys": ["ctrl+q"], "command": "toggle_comment", "args": {"block": false}}]
+
+

So, I was thinking, maybe there's a command to change package "settings - user" and pass a var to set ["anaconda_linting": false,] into true or false?

","

You can do this with a custom plugin and keybinding. Select Tools → Developer → New Plugin… and set the contents of the file that opens to this:

+
import sublime
+import sublime_plugin
+
+
+class ToggleAnacondaLintingCommand(sublime_plugin.ApplicationCommand):
+    def run(self):
+        s = sublime.load_settings("Anaconda.sublime-settings")
+        current = s.get("anaconda_linting")
+        new = not current
+        s.set("anaconda_linting", new)
+        sublime.save_settings("Anaconda.sublime-settings")
+        sublime.active_window().run_command('save')
+
+

Hit CtrlS to save, and your Packages/User folder should open up. Save the file as toggle_anaconda_linting.py.

+

Now, open up your keybindings and add the following between the [ ] characters (choosing whatever shortcut you want):

+
{"keys": ["ctrl+alt+shift+l"], "command": "toggle_anaconda_linting"},
+
+

Now, whenever you hit the shortcut, "anaconda_linting" will be toggled for all files.

",python +"Getting first (or a specific) td in BeautifulSoup with no class

I have one of those nightmare tables with no class given for the tr and td tags.

+

A sample page is here: https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m

+

(You'll see in the code below that I'm getting multiple pages, but that's not the problem.)

+

I want the team name (nothing else) from each bracket. The output should be:

+
+

OCYS
+FL Rush
+Jacksonville FC
+Atlanta United
+SSA
+Miami Rush Kendall SC
+IMG
+Tampa Bay United
+etc.

+
+

I've been able to get every td in the specified tables. But every attempt to use [0] to get the first td of every row gives me an "index out of range" error.

+

The code is:

+
import requests
+import csv 
+from bs4 import BeautifulSoup
+
+batch_size = 2
+urls = ['https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m', 'https://system.gotsport.com/org_event/events/1271/schedules?age=17&gender=m']
+
+# iterate through urls
+for url in urls:
+    response = requests.get(url)
+    soup = BeautifulSoup(response.content, "html.parser")
+
+
+
+# iterate through leagues and teams
+    leagues = soup.find_all('table', class_='table table-bordered table-hover table-condensed')
+    for league in leagues:
+        row = ''
+        rows = league.find_all('tr')
+        for row in rows:
+            team = row.find_all('td')
+            teamName = team[0].text.strip()    
+            print(teamName)
+
+

After a couple of hours of work, I feel like I'm just one syntax change away from getting this right. Yes?

","

You can use a CSS Selector nth-of-type(n). It works for both links:

+
import requests
+from bs4 import BeautifulSoup
+
+url = "https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m"
+soup = BeautifulSoup(requests.get(url).content, "html.parser")
+
+for tag in soup.select(".small-margin-bottom td:nth-of-type(1)"):
+    print(tag.text.strip())
+
+

Output:

+
OCYS
+FL Rush
+Jacksonville FC
+Atlanta United
+SSA
+...
+...
+Real Salt Lake U19
+Real Colorado
+Empire United Soccer Academy
+
",python +"Performance difference between multithread using queue and futures.ThreadPoolExecutor using list in python3?

I was trying various approaches with python multi-threading to see which one fits my requirements. To give an overview, I have a bunch of items that I need to send to an API. Then based on the response, some of the items will go to a database and all the items will be logged; e.g., for an item if the API returns success, that item will only be logged but when it returns failure, that item will be sent to database for future retry along with logging.

+

Now based on the API response I can separate out success items from failure and make a batch query with all failure items, which will improve my database performance. To do that, I am accumulating all requests at one place and trying to perform multithreaded API calls(since this is an IO bound task, I'm not even thinking about multiprocessing) but at the same time I need to keep track of which response belongs to which request.

+

Coming to the actual question, I tried two different approaches which I thought would give nearly identical performance, but there turned out to be a huge difference.

+

To simulate the API call, I created an API in my localhost with a 500ms sleep(for avg processing time). Please note that I want to start logging and inserting to database after all API calls are complete.

+

Approach - 1(With threading.Thread and queue.Queue())

+
import requests
+import datetime
+import threading
+import queue
+
+def target(data_q):
+    while not data_q.empty():
+        data_q.get()
+        response = requests.get("https://postman-echo.com/get?foo1=bar1&foo2=bar2")
+        print(response.status_code)
+        data_q.task_done()
+
+if __name__ == "__main__":
+    data_q = queue.Queue()
+    for i in range(0, 20):
+        data_q.put(i)
+
+    start = datetime.datetime.now()
+    num_thread = 5
+    for _ in range(num_thread):
+        worker = threading.Thread(target=target(data_q))
+        worker.start()
+
+    data_q.join()
+
+    print('Time taken multi-threading: '+str(datetime.datetime.now() - start))
+
+

I tried with 5, 10, 20 and 30 times and the results are below correspondingly,
+Time taken multi-threading: 0:00:06.625710
+Time taken multi-threading: 0:00:13.326969
+Time taken multi-threading: 0:00:26.435534
+Time taken multi-threading: 0:00:40.737406

+

What shocked me here is, I tried the same without multi-threading and got almost same performance.

+

Then after some googling around, I was introduced to futures module.

+

Approach - 2(Using concurrent.futures)

+
def fetch_url(im_url):
+    try:
+        response = requests.get(im_url)
+        return response.status_code
+    except Exception as e:
+        traceback.print_exc()
+
+if __name__ == "__main__":
+    data = []
+    for i in range(0, 20):
+        data.append(i)
+
+    start = datetime.datetime.now()
+    urls = ["https://postman-echo.com/get?foo1=bar1&foo2=bar2" + str(item) for item in data]
+    with futures.ThreadPoolExecutor(max_workers=5) as executor:
+        responses = executor.map(fetch_url, urls)
+        for ret in responses:
+            print(ret)
+    print('Time taken future concurrent: ' + str(datetime.datetime.now() - start))
+
+

Again with 5, 10, 20 and 30 times and the results are below correspondingly,
+Time taken future concurrent: 0:00:01.276891
+Time taken future concurrent: 0:00:02.635949
+Time taken future concurrent: 0:00:05.073299
+Time taken future concurrent: 0:00:07.296873

+

Now I've heard about asyncio, but I've not used it yet. I've also read that it gives even better performance than futures.ThreadPoolExecutor().

+

Final question, If both approaches are using threads(or so I think) then why there is a huge performance gap? Am I doing something terribly wrong? I looked around. Was not able to find a satisfying answer. Any thoughts on this would be highly appreciated. Thanks for going through the question.

+

[Edit 1]The whole thing is running on python 3.8. +[Edit 2] Updated code examples and execution times. Now they should run on anyone's system.

","

The documentation of ThreadPoolExecutor explains in detail how many threads are started when the max_workers parameter is not given, as in your example. The behaviour is different depending on the exact Python version, but the number of tasks started is most probably more than 3, the number of threads in the first version using a queue. You should use futures.ThreadPoolExecutor(max_workers= 3) to compare the two approaches.

+

To the updated Approach - 1 I suggest to modify the for loop a bit:

+
for _ in range(num_thread):
+    target_to_run= target(data_q)
+    print('target to run: {}'.format(target_to_run))
+    worker = threading.Thread(target= target_to_run)
+    worker.start()
+
+

The output will be like this:

+
200
+...
+200
+200
+target to run: None
+target to run: None
+target to run: None
+target to run: None
+target to run: None
+Time taken multi-threading: 0:00:10.846368
+
+

The problem is that the Thread constructor expects a callable object or None as its target. You do not give it a callable, rather queue processing happens on the first invocation of target(data_q) by the main thread, and 5 threads are started that do nothing because their target is None.

",python +"Better way to write nested try except python

Is there a better way for me to write this without nesting it like this?

+
try:
+    if find_path(graph, startPos, (targetX+1,targetY,targetX,targetY)):
+        print('YES')
+except:
+    try:
+        if find_path(graph, startPos, (targetX,targetY+1,targetX,targetY)):
+            print('YES')
+    except:
+        try:
+            if find_path(graph, startPos, (targetX-1,targetY,targetX,targetY)):
+                print('YES')
+        except:
+            try:
+                if find_path(graph, startPos, (targetX,targetY-1,targetX,targetY)):
+                    print('YES')
+            except:
+                print('NO')
+
","

You could make a list of potential coordinates, and then try them each in turn, in a for loop, breaking the loop on success:

+
success = "NO"
+coords = ((targetX+1,targetY), (targetX,targetY+1), (targetX-1,targetY), (targetX,targetY-1))
+
+for coord in coords:
+    try:
+        x, y = coord
+        find_path(graph, startPos, (x, y, targetX,targetY))
+    except:
+        pass
+    else:
+        # Set success state and break out of the for loop
+        success = "YES"
+        break
+print(success)
+
",python +"Join DataFrame by Comparing columns

I have two dataframe:

+

df1:

+

+

df2:

+

+

I want update column 'D' of df1 such that if df2 have a lesser value for column d for same value of 'A' and 'B' column df.d will replace df1.d for that row.

+

expected output is:

+

+

Could someone help me with the python code for this?

+

Thanks.

","
df_new=pd.merge(df1,df2, how='left', on=['A','B'],suffixes=('', '_r'))#merge the two frames on A and B and suffix df2['D'] WITH R
+df_new['D']=np.where(df_new['D']>df_new['D_r'],df_new['D_r'],df_new['D'])#Use np.where to replace column D with the right value as per condition
+df_new.drop('D_r',1, inplace=True)#Drop the D_r column
+
+
+
+   A  B    C    D
+0  x  2    f  1.0
+1  x  3    2  1.0
+2  y  2    4  3.0
+3  y  5  dfs  2.0
+4  z  1  sds  5.0
+
",python +"Convert column to datetime format, in a leap year

I'm new to Python and programming in general, so I wasn't able to figure out the following: I have a dataframe named ozon, for which column 1 is the time stamp in mm-dd format. Now I want to change that column to a datetime format using the following code:

+
ozon[1] = pd.to_datetime(ozon[1], format='%m-%d')
+
+

Now this is giving me the following error: ValueError: day is out of range for month. +I think it has to do with the fact that it's a leap year, so it doesn't recognize February 29 as a valid date. How can I overcome this error? And could I also add a year to the timestamp (2020)? +Thanks so much in advance!

","

Add year to column and also to format:

+
ozon[1] = pd.to_datetime(ozon[1] + '-2000', format='%m-%d-%Y')
+
+

If still not working because some values are not valid add errors='coerce' parameter:

+
ozon[1] = pd.to_datetime(ozon[1] + '-2000', format='%m-%d-%Y', errors='coerce')
+
",python +"Update dictionary key(s) by drop starts with value from key in Python

I have a dictionary dict:

+
dict = {'drop_key1': '10001', 'drop_key2':'10002'}
+
+

The key(s) in dict startswith drop_, i would like to update dict by dropping drop_ value from key(s):

+
dict = {'key1': '10001', 'key2':'10002'}
+
+

What is the best approach to do it?

","

something like

+
d1 = {'drop_key1': '10001', 'drop_key2':'10002'}
+d2 = {k[5:]:v for k,v in d1.items()}
+print(d2)
+
+

output

+
{'key1': '10001', 'key2': '10002'}
+
",python +"Summing up the output of multiple functions in python

I currently have three sine functions (y1, y2, y3) and would like to sum the output of the functions in a new function (ytotal) but only where the output of the sine functions are greater than 0.

+
import numpy as np
+import matplotlib.pyplot as plt
+#%%
+
+phi = np.linspace(-2*np.pi, 2*np.pi, 100)
+
+y1 = 0.2*np.sin(phi)
+y2 = 0.2*np.sin(phi-(120*(np.pi/180)))
+y3 = 0.2*np.sin(phi-(240*(np.pi/180)))
+
+#if y1 or y2 or y3 > 0:
+#    ytotal = y1+y2+y3
+
+
+    
+
+
+plt.plot(phi,y1, label = "Piston 1")
+plt.plot(phi,y2, label = "Piston 2")
+plt.plot(phi,y3, label = "Piston 3")
+#plt.plot(phi,ytotal, label = "Total output")
+positions = (0,np.pi/3,2*np.pi/3,np.pi,4*np.pi/3,5*np.pi/3,2*np.pi)
+labels = ("0","60","120","180","240","300","360")
+plt.xticks(positions, labels)
+plt.xlabel('Angular displacement')
+plt.ylabel('Stroke')
+plt.legend()
+plt.show()
+
+

+

The output should be something like the following:

+

","

Do you mean:

+
plt.plot(phi, y1.clip(0)+y2.clip(0)+y3.clip(0), label='Total')
+
+

Output:

+

",python +"Not getting data from database in python

I have tried getting the registered data from a database the program has created when first run.

+

database.py

+
import sqlite3
+
+CREATE_TABLE = """CREATE TABLE IF NOT EXISTS college (
+                                    id INTEGER PRIMARY KEY,
+                                    FirstName TEXT,
+                                    SecondName TEXT,
+                                    Position TEXT);"""
+
+INSERT_DATA = "INSERT INTO college (FirstName, SecondName, Position) VALUES (?, ?, ?);"
+DISPLAY_DATA = "SELECT * FROM college WHERE Position = ?;"
+def connect():
+    return sqlite3.connect('databas.db')
+
+def create_table(connection):
+    with connection:
+        connection.execute(CREATE_TABLE)
+
+def insert_data(connection, FirstName, SecondName, Position):
+    with connection:
+        connection.execute(INSERT_DATA, (FirstName, SecondName, Position))
+
+def request_data(connection, position):
+    with connection:
+        return connection.execute(DISPLAY_DATA, (position,)).fetchall()
+
+

api.py

+
import database
+
+API_MENU = """
+--- Student Database ---
+
+1) Register new student
+2) Delete
+3) Show students
+
+4) Register new staff
+5) Delete
+6) Show staff
+
+7) >> Quit the program
+
+Your choice: """
+def main():
+    connection = database.connect()
+    database.create_table(connection)
+
+    
+    while (choice := input(API_MENU)) != "7":
+        if choice == "1":
+            FirstName = "Julius"
+            SecondName = "Jessie"
+            Position = "Student"
+
+            database.insert_data(connection, FirstName, SecondName, Position)
+        elif choice == "2":
+            database.request_data(connection, "Student")
+        elif choice == "3":
+            pass
+        elif choice == "4":
+            pass
+        elif choice == "5":
+            pass
+        elif choice == "6":
+            pass
+        else:
+            print("Invalid input, please try again!")
+
+main()
+
+

I am simply not being returned any data after I have registered the data using option 1. When running the code and choosing option 1, you should input a name, surname and position (Student / Staff) and then write that to the database (i have just defined strings for the purpose of putting the code here) and then choosing the option 2 should return the data that has "Student" as a position however it does not return any data.

","

The problem was that I was simply negligent with actually using the function print() to show the data.

+
database.request_data(connection, "Student")
+
+

The line above should be:

+
print(database.request_data(connection, "Student"))
+
",python +"Count rows with multiple criteria in pandas

I have a pandas dataframe with "user_ID", "datetime" and "action_type" columns like it is shown below and I want to get the last column (the last column = desired output) by performing some calculations:

+
data = {'user_id': list('ddabdacddaaa'), 
+            'datetime':pd.date_range("20201001", periods=12, freq='H'), 
+            'action_type':list('XXXWZWKOOXWX'), 
+            'as_if_X_calculated':list('121021022223')
+           }
+df = pd.DataFrame(data)
+df
+
+
    user_id datetime    action_type as_if_X_calculated
+0   d   2020-10-01 00:00:00 X   1
+1   d   2020-10-01 01:00:00 X   2
+2   a   2020-10-01 02:00:00 X   1
+3   b   2020-10-01 03:00:00 W   0
+4   d   2020-10-01 04:00:00 Z   2
+5   a   2020-10-01 05:00:00 W   1
+6   c   2020-10-01 06:00:00 K   0
+7   d   2020-10-01 07:00:00 O   2
+8   d   2020-10-01 08:00:00 O   2
+9   a   2020-10-01 09:00:00 X   2
+10  a   2020-10-01 10:00:00 W   2
+11  a   2020-10-01 11:00:00 X   3
+
+

So the last column shows how many times the user has performed an action X at the time of the current record. If we see a user "a", his results will be like 1-1-2-2-3 in chronological order. So how can I calculate the number of action X for the given user that happened at the time of the record or earlier?

+

P.S. In Excel it would look like =countifs(A:A; A2; B:B; "<="&B2; C:C; "X") (Column A = "user_id")

","

If your dataframe is sorted by datetime you can create a temporary column for the condition on action_type and use pd.expanding

+
df.sort_values('datetime', inplace=True)
+df['dummy'] = df.action_type == 'X'
+df['X_calculated'] = (df.groupby('user_id')['dummy']
+                      .expanding().sum()
+                      .reset_index(level=0, drop=True)
+                      .astype('int'))
+df.sort_index(inplace=True)
+print(df.drop('dummy', 1))
+assert df.as_if_X_calculated.astype('int').equals(df.X_calculated), 'X_calculated is not equal'
+
+

Out:

+
   user_id            datetime action_type as_if_X_calculated  X_calculated
+0        d 2020-10-01 00:00:00           X                  1             1
+1        d 2020-10-01 01:00:00           X                  2             2
+2        a 2020-10-01 02:00:00           X                  1             1
+3        b 2020-10-01 03:00:00           W                  0             0
+4        d 2020-10-01 04:00:00           Z                  2             2
+5        a 2020-10-01 05:00:00           W                  1             1
+6        c 2020-10-01 06:00:00           K                  0             0
+7        d 2020-10-01 07:00:00           O                  2             2
+8        d 2020-10-01 08:00:00           O                  2             2
+9        a 2020-10-01 09:00:00           X                  2             2
+10       a 2020-10-01 10:00:00           W                  2             2
+11       a 2020-10-01 11:00:00           X                  3             3
+
",python +"How to compare date in python?

How to check datetime in python3?

+

Both date and time are same but in 'b' there is no zero.

+
  a = '2020-09-08 05:09:02'
+  b = '2020-9-8 5:9:2'
+  if a == b:
+     print("yes")
+  else:
+     print("no")
+
+ Expected Output:
+   yes
+
","

you can turn them into datetime objects and compare them

+
import datetime as dt
+a = '2020-09-08 05:09:02'
+b = '2020-9-8 5:9:2'
+a_dt = dt.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
+b_dt = dt.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')
+if a_dt == b_dt:
+    print("yes")
+else:
+    print("no")
+
",python +"Python Pandas Dataframe Groupby Sum question

I'm new in Python and I need to combine 2 dataframe with 'id' as the primary key. I need to sum up all the Charges from df1 and df2.

+
df1:
+[df1][1]
+
+id     Name     Charge
+1       A         100
+1       A         100
+2       B         200
+2       B         200
+5       C         300
+6       D         400
+
+df2:
+[df2][2]
+
+id     Name      Charge
+1       A          100
+1       A          100
+2       B          200
+8       X          200
+
+output:
+[output][3]
+
+id       Name      Charge(TOTAL from df1 & df2)
+1         A           400
+2         B           600
+5         C           300
+6         D           400
+8         X           200
+
","

Try:

+
pd.concat([df1, df2]).groupby(['id', 'Name'], as_index=False)['Charge'].sum()
+
+

Output:

+
   id Name  Charge
+0   1    A     400
+1   2    B     600
+2   5    C     300
+3   6    D     400
+4   8    X     200
+
",python +"Python Split first ""middle"" and last word

I would like to split a list in 3 parts. It works except when the middle part is in "two parts".

+
file = open("/topladder/pr_top_fr","r")
+for line in file:
+    fields = line.split( )
+    
+    pos1 = fields[0]
+    pos2 = fields[1]
+    pos3 = fields[2]
+
+    print("Position: " + pos1 + " - " + pos2 + " - Tr:" + pos3)
+
+

the file look like:

+
308 Mars 6249
+948 Ben Stark 6063
+955 Toto 6061
+
+

And here is the result:

+
Position: 308 - Mars - Tr:6249
+Position: 948 - Ben - Tr:Stark
+Position: 955 - Toto - Tr:6061
+
+

Is it possible to "combine" everything that is in the middle in "pos2"? +Thanks !!

","
file = open("/topladder/pr_top_fr","r")
+for line in file:
+    fields = line.split( )
+    
+    pos1 = fields[0]
+    pos2 = fields[1:-1]
+    pos3 = fields[-1]
+
+    print("Position: " + pos1 + " - " + ' '.join(pos2) + " - Tr:" + pos3)
+
",python +"Django can't search ""method not allowed""

im new to django and im currently doing a website for my friend. he wants me to make a system where the users can search the database and the website gives the relevent items according to their serial number. +i followed a tutorial from the following site: https://learndjango.com/tutorials/django-search-tutorial to figure out how to do db searchs which helped a lot, but im still having a problem: my search bar works, and the result page also works but it only works when i manually type the query on the searchbar myself (e.x. results/?q=number1). However when i search using the input bar and the submit button it sends me to /results/ page and the page gives this:

+

This page isn’t working

+

If the problem continues, contact the site owner.

+

HTTP ERROR 405

+

-when i open up pycharm to see the error in terminal it says:

+
Method Not Allowed (POST): /result/
+
+Method Not Allowed: /result/
+
+[27/Oct/2020 20:06:02] "POST /result/ HTTP/1.1" 405 0
+
+

here are my codes(python3.7,pycharm) websites/urls:

+
from . import views
+from django.urls import path
+from django.contrib.auth import views as auth_views
+
+urlpatterns = [
+    path('register/',views.UserFormView.as_view(), name='register'),
+    path('login/', auth_views.LoginView.as_view(), name='login'),
+    path('', views.IndexViews.as_view(), name='index'),
+    path('scan/', views.ScanView.as_view(), name='scan'),
+    path('result/', views.SearchResultsView.as_view(), name='result'),
+]
+
+

websites/views:

+
class IndexViews(generic.ListView):
+    template_name = "websites/index.html"
+    context_object_name = "object_list"
+
+    def get_queryset(self):
+        return Website.objects.all()
+
+
+class ScanView(TemplateView):
+    form_class = SerialFrom
+    template_name = 'websites/scan.html'
+
+
+class SearchResultsView(ListView):
+    model = SerialNumber
+    template_name = 'websites/result.html'
+
+    def get_queryset(self):  # new
+        query = self.request.GET.get('q')
+        context = self.get_context_data(object=self.object)
+        object_list = SerialNumber.objects.filter(
+            Q(number__iexact=query)
+        )
+        return object_list
+
+

scan.html:

+
 {% extends 'websites/base.html' %}
+{% block albums_active %}active{% endblock %}
+
+{% block body %}
+<head>
+    <meta charset="UTF-8">
+    <title>Scan</title>
+    <link rel="stylesheet" href="style.css">
+</head>
+<body>
+    <form class="box" action="{% url 'result' %}" method="POST">
+      <h1>Product Check</h1>
+        <p> Please enter the serial id of your product to check it.</p>
+      {% csrf_token %}
+      <input type="text" name="q" placeholder="Serial Number">
+      <input type="submit" name="q" placeholder="Check">
+  </form>
+</body>
+{% endblock %}
+
+

thank you for taking your time and reading, please help me i really need to do this.

","

A ListView [Django-doc] by default does not implement a handler for a POST request. Searching is normally done through a GET request, so you should use:

+
<form class="box" action="{% url 'result' %}" method="GET">
+    <h1>Product Check</h1>
+    <p> Please enter the serial id of your product to check it.</p>
+    <input type="text" name="q" placeholder="Serial Number">
+    <input type="submit" placeholder="Check">
+</form>
+

Furthermore the <input type="submit"> should not have a name="q" attribute.

+

As @Melvyn says, you can also alter the type to type="search" [mozilla] for the text box:

+
<form class="box" action="{% url 'result' %}" method="GET">
+    <h1>Product Check</h1>
+    <p> Please enter the serial id of your product to check it.</p>
+    <input type="search" name="q" placeholder="Serial Number">
+    <input type="submit" placeholder="Check">
+</form>
",python +"Creating a sphere at center of array without a for loop with meshgrid creates shell artifact

I would like to implement the code below avoiding for loops to increase speed. Is there any way to do this so that I can create a sphere centered in the numpy array?

+
def Create_Sphere(square_numpy_array, pixel_min, pixel_max, HU, Radius_sq ):
+
+
+new_array = np.empty_like(square_numpy_array)
+
+for k in range(pixel_min, pixel_max, 1):
+    for i in range(pixel_min, pixel_max, 1):
+        for j in range(pixel_min, pixel_max, 1):
+            r_sq = (i - 255)**2 + (j - 255)**2 + (k - 255)**2
+            if r_sq <= Radius_sq:
+                new_array[k, i, j] = HU + 1000
+return new_array
+
+

Adopting the solution from the recommended link Python vectorizing nested for loops I was able to replace the code. I am getting unexplained artifacts in the final plot however. There are rings appearing around the central sphere. What could be causing these?

+
def Create_Sphere_CT(HU=12):
+
+     radius = np.uint16(100) #mm
+     Radius_sq_pixels = np.uint16((radius *2)**2 )
+     sphere_pixel_HU = np.uint16(HU + 1000) #dtype controlled for memory
+     center_pixel = np.uint16(400/2-1)  
+     new_array = np.zeros((400,400,400), dtype = np.uint16)
+
+     m,n,r = new_array.shape
+     x = np.arange(0, m, 1, dtype = np.uint16)
+     y = np.arange(0, n, 1, dtype = np.uint16)
+     z = np.arange(0, r, 1, dtype = np.uint16)
+
+     xx,yy,zz = np.meshgrid(x,y,z, indexing = 'ij')
+
+     X = (xx - center_pixel)
+     xx = None #free memory once variable is used
+     Y = (yy - center_pixel)
+     yy= None #free memory once variable is used
+     Z = (zz - center_pixel)
+     zz = None#free memory once variable is used
+
+     mask = (X**2 + Y**2 + Z**2) < Radius_sq_pixels  #create sphere mask
+     new_array = sphere_pixel_HU * mask  #assign values 
+
+     return new_array
+
+

This code give a sphere centered with some ring artifacts around +

","

I realized that using unsigned int was causing errors in subtraction. The final working solution is below

+
def Sphere(HU):
+num_pix = int(400)
+radius =100 
+Radius_sq_pixels = (radius)**2
+sphere_pixel_HU = HU 
+center_pixel = int(num_pix/2-1) 
+new_array = np.zeros((num_pix, num_pix, num_pix))
+
+m,n,r = new_array.shape
+x = np.arange(0, m, 1)
+y = np.arange(0, n, 1)
+z = np.arange(0, r, 1)
+
+xx,yy,zz = np.meshgrid(x,y,z,indexing = 'ij',sparse = True)
+X = (xx - center_pixel)
+Y = (yy - center_pixel)
+Z = (zz - center_pixel)
+
+mask = ((X**2) + (Y**2) + (Z**2)) < Radius_sq_pixels  #create sphere mask
+
+new_array = sphere_pixel_HU * mask  #assign values 
+new_array = new_array.astype(np.uint16) #change datatype
+
+plt.imshow(new_array[int(num_pix/2)])
+plt.show()
+
+return new_array
+
",python +"Fill DataFrame NaN with another DataFrame with groupby

I am sure this has been answered before but I cannot seem to find the right solution. I have tried pd.merge, merge, combine_first and update and they all don't seem to get the right job. They either create a new variable with an _x or they imply stack in below. I am wishing to merge df1 into df where column c is missing values. I wish to do this for each id on each date

+

Example df for task

+

df

+
  date     id    a    b   c     d
+1/1/2000    1   10   20   10   11
+1/1/2000    2   11   21   NaN  11
+1/1/2000    3   15   20   NaN  11
+1/1/2000    4   12   24   13   11
+1/2/2000    1   10   25   10   11
+1/2/2000    2   10   20   NaN  15
+1/2/2000    3   10   26   NaN  11
+1/2/2000    4   10   20   16   13
+1/3/2000    1   10   20   10   11
+1/3/2000    2   10   20   NaN  11
+1/3/2000    3   10   20   NaN  11
+1/3/2000    4   10   20   10   11
+
+

df1

+
 date         id   c    
+12/29/1999    2   1  
+12/30/1999    3   1  
+12/30/1999    2   1  
+12/31/1999    3   1  
+12/31/1999    2   1  
+12/31/1999    4   1  
+1/1/2000      2   1  
+1/1/2000      3   14  
+1/2/2000      2   13  
+1/2/2000      3   22  
+1/3/2000      2   13  
+1/3/2000      3   18  
+
+

desired df after combining df and d1

+

df

+
  date     id    a    b   c     d
+1/1/2000    1   10   20   10   11
+1/1/2000    2   11   21   1    11
+1/1/2000    3   15   20   14   11
+1/1/2000    4   12   24   13   11
+1/2/2000    1   10   25   10   11
+1/2/2000    2   10   20   13   15
+1/2/2000    3   10   26   22   11
+1/2/2000    4   10   20   16   13
+1/3/2000    1   10   20   10   11
+1/3/2000    2   10   20   13   11
+1/3/2000    3   10   20   18   11
+1/3/2000    4   10   20   10   11
+
","

Lets create a MultiIndex in both the dataframe with id and date columns then use Series.fillna to fill the NaN values in column c of df1 from corresponding values in df2:

+
df1['c'] = df1.set_index(['date', 'id'])['c']\
+              .fillna(df2.set_index(['id', 'date'])['c']).tolist()
+
+
+
        date  id   a   b     c   d
+0   1/1/2000   1  10  20  10.0  11
+1   1/1/2000   2  11  21   1.0  11
+2   1/1/2000   3  15  20  14.0  11
+3   1/1/2000   4  12  24  13.0  11
+4   1/2/2000   1  10  25  10.0  11
+5   1/2/2000   2  10  20  13.0  15
+6   1/2/2000   3  10  26  22.0  11
+7   1/2/2000   4  10  20  16.0  13
+8   1/3/2000   1  10  20  10.0  11
+9   1/3/2000   2  10  20  13.0  11
+10  1/3/2000   3  10  20  18.0  11
+11  1/3/2000   4  10  20  10.0  11
+
",python +"How Do I Download the Latest Version of PyQt5 Tools?

I want to download PyQt5 tools. I wrote the code from the pypi site, but it requests a version from me. He didn't accept what I wrote. I want to download the latest version, how can I do?

+
pip install pyqt5-tools
+
+
ERROR: Could not find a version that satisfies the requirement pyqt5-tools (from versions: none)
+
","

Specify the version, for example for version 5.11 write the following command +pip install pyqt5-tools~=5.11

",python +"How to get host name from website using python

I would like to look get the host name using requests repository in python. I tried to do this like that:

+
pprint(requests.get("https://www.facebook.com/").headers['domain'])
+
+

but it doesn't work. If it is possible in other repository I would be grateful for any answer.

","

Based on Regular Expression - Extract subdomain & domain

+
import requests
+import re
+
+p = re.compile("^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)")
+
+r = requests.get("https://www.google.com/")
+domain = p.match(r.url).group(1)
+print(domain)
+
",python +"Desktop Goose like program

i have been trying to create a python program similar to desktop goose in the aspect of a widget moving freely around the screen.

+

First i tried to create a window with tkinter and make a transparent window +with a PNG picture of a character and then moving the window with win32gui or any other library that would allow me to do this. +But first, the tkinter transparent window thing doesn't work because the widgets inherit the transparency, so there is no way i can display the PNG. +Then i had trouble finding any win32gui function that would allow me to move the windows, i just found stuff that would let me resize them.

+

Is there any way i can do any of these two tasks?

","

You can create a transparent window using a transparent PNG image as below:

+
import tkinter as tk
+
+# select a color as the transparent color
+TRNAS_COLOR = '#abcdef'
+
+root = tk.Tk()
+root.overrideredirect(1)
+root.attributes('-transparentcolor', TRNAS_COLOR)
+
+image = tk.PhotoImage(file='/path/to/image.png')
+tk.Label(root, image=image, bg=TRNAS_COLOR).pack()
+
+# support dragging window
+
+def start_drag(event):
+    global dx, dy
+    dx, dy = event.x, event.y
+
+def drag_window(event):
+    root.geometry(f'+{event.x_root-dx}+{event.y_root-dy}')
+
+root.bind('<Button-1>', start_drag)
+root.bind('<B1-Motion>', drag_window)
+
+root.mainloop()
+
+

Then you can use root.geometry(...) to move the root window.

",python +"Matplotlib.pylot says 'requirement already satisfied' but also 'Module not found'

This is a similar question to what I've asked before, but I don't understand what is happening. I am using pip 20.2.3 and python 3.8.2 on Windows.

+

Before, when I typed pip install matplotlib or pip3 install matplotlib into cmd, I would get a message saying that all the "requirements are satisfied". But when I run import matplotlib.pylot as plt on VSCode, it tells me

+
Traceback (most recent call last):
+  File "c:/Users/sound/Desktop/now/Trade Simulation/#2/Trade Simulation.py", line 6, in <module>
+    import matplotlib.pylot as plt
+ModuleNotFoundError: No module named 'matplotlib.pylot'
+
+

Not only that, I recently just updated pip from 20.2.3 to 20.2.4. When I run the same command pip install matplotlib, instead of saying "requirements are satisfied" like before, I get a massive error message in red that looks like:

+
    ERROR: Command errored out with exit status 1:
+     command: 'c:\users\sound\appdata\local\programs\python\python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sound\\AppData\\Local\\Temp\\pip-install-9w_lvhnf\\matplotlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\sound\\AppData\\Local\\Temp\\pip-install-9w_lvhnf\\matplotlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\sound\AppData\Local\Temp\pip-pip-egg-info-ihoi_gsj'
+         cwd: C:\Users\sound\AppData\Local\Temp\pip-install-9w_lvhnf\matplotlib\
+    Complete output (249 lines):
+    WARNING: The wheel package is not available.
+        ERROR: Command errored out with exit status 1:
+         command: 'c:\users\sound\appdata\local\programs\python\python39\python.exe' 'c:\users\sound\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\sound\AppData\Local\Temp\tmpsqdka5ne'
+
+

The change in output when I updated pip kind of threw me off. I'm not sure what to do or how to fix this installation error. Any insight would be appreciated.

+

Using pip3.8 install -U matplotlib gives me back

+
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\12132\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\~atplotlib\\ft2font.cp38-win32.pyd'
+Consider using the `--user` option or check the permissions.
+
","

Your error indicates a typo, there is no module pylot in matplotlib.

+

The import you have:

+

import matplotlib.pylot as plt

+

should be:

+

import matplotlib.pyplot as plt

",python +"TypeError: a bytes-like object is required, not 'str' when reading and iterating over a file in Python3.x

I'm trying to read and iterate over a text file in Python but I keep running into this error. I'm pretty new to Python and I'm not sure where the error in my code is:

+
import socket
+
+def getBanner(ip, port):
+    try:
+        socket.setdefaulttimeout(2)
+        s = socket.socket()
+        s.connect((ip, port))
+        banner = s.recv(1024)
+        return banner
+    except:
+        return
+
+def vulnCheck(banner):
+    f = open("vuln_banners.txt", 'r')
+    for line in f.readlines():
+        if line.strip('\n') in banner:
+            print("[+] Server is vulnerable: "+banner.strip('\n'))
+        else:
+            print("[-] FTP Server is not vulnerable.")
+            return
+
+
+def main():
+    portList = [21, 22, 25, 80, 110, 443]
+    for x in range(1, 255):
+        ip = '192.168.1.' + str(x)
+        for port in portList:
+            banner = getBanner(ip, port)
+            if banner:
+                print("[+] " + str(ip) + ": " + str(banner))
+                vulnCheck(banner)
+
+if __name__ == '__main__':
+    main()
+
+

I would like my program to iterate over a list of strings in a text file to compare against a banner, however, every time I run the code I get this error:

+
  File "/home/testing/Documents/HelloWorld.py", line 17, in vulnCheck
+    if line.strip('\n') in banner:
+TypeError: a bytes-like object is required, not 'str'
+
+

I've read few of the answers about this error and they talk about NOT opening the file as binary, but I don't think I'm doing that in my code. I'm simply trying to read each line in a text file and iterate over it. Can anyone point out the error in my code? Any help would be appreciated.

","

Your socket returns bytes while the file contains strings. You need to map one to the other - probably decode bytes banners to strings.

+

As an aside, repeatedly reading the same static text file is a significant bottleneck here. Unless the file is so huge that you should be using a database instead anyway, read it once, at the start.

+

The following also has assorted bug fixes and stylistic updates; most importantly, don't return in the middle of the vulnerability check if the first vulerability wasn't matched. Notice also how functions generally just return a result, and leave it to the caller to decide e.g. whether to print something based on that.

+
import socket
+
+def get_banner(ip, port):
+    try:
+        socket.setdefaulttimeout(2)
+        s = socket.socket()
+        s.connect((ip, port))
+        banner = s.recv(1024)
+        return banner.decode('utf-8')
+    except:
+        return
+
+def vuln_check(banner, vulnlist):
+    for line in vulnlist:
+        if line in banner:
+            return True
+    return False
+
+def read_vulns(filename):
+    with open(filename, 'r') as f:
+        return f.read().splitlines()
+
+def main():
+    vulns = read_vulns("vuln_banners.txt")
+
+    port_list = [21, 22, 25, 80, 110, 443]
+    for x in range(1, 255):
+        ip = '192.168.1.' + str(x)
+        for port in port_list:
+            banner = get_banner(ip, port)
+            if banner:
+                print("[+]", ip + ":", banner)
+                if vuln_check(banner, vulns):
+                    print("[+] Server is vulnerable:", banner.strip('\n'))
+                else:
+                    print("[-] FTP Server is not vulnerable.")
+
+if __name__ == '__main__':
+    main()
+
",python +How to find total hits on DynamoDB table

I have a Lambda function that is hitting DynamoDB and getting values from there. I wanted to check if there is any way where I can see how many times lambda hits the DynamoDB table. I tried to see in CloudWatch but unable to find it.

,"

There is no simple way to do it. +You can use read/write capacity metrics for the table if the lambda is the only consumer of this table

+

Under Dynamodb -> you table -> Metrics, or from CW Metrics

+

+

And calculate a measurement of the actions according to this topic: +How are consumed read capacity units calculated in DynamoDB query

+

Currently, AWS doesn't show these metrics that you asked for

",python +"Output of a Nested for Loop - Python

I am trying to get the output of a nested for loop into an array or matrix. For instance, in the code example below, I want to have a (3 by 2)-matrix of the form:

+
[[5 6],
+ [6 7],
+ [7 8]]
+
+

But my code is giving out of bound error.

+
import numpy as np
+
+num = [1,2,3]
+sep = [4, 5]
+M = np.zeros((3,2))
+for i in num:
+    for j in sep:
+        M[i, j] = i + j
+M
+
+

However, I realized that changing the initialization to np.zeros((4,6)) seems to work but with some irrelevant cells. Can someone explain how this works or possibly how I can achieve this (3 by 2)-matrix.

","

You are using the values in your num and sep lists as indexes. You need to use indexes instead:

+
import numpy as np
+
+num = [1,2,3]
+sep = [4, 5]
+M = np.zeros((3,2))
+for i_i,i in enumerate(num):
+    for i_j,j in enumerate(sep):
+        M[i_i, i_j] = i + j
+
+print(M)
+
+

Output as required.

",python +"Alpine.js +flatpickr Datetimepicker is not working

i really stucked in my project. I have a site with alpine.js where i want to render data to an element

+

Everything is working perfect until the fact that my flatpickr is not shown up. +The datepicker is working perfect. It seams, that x-html, x-text nor document.getElementById().innerHTML used in alpine.js is working ....

+
<div x-data="app()" x-html="modalData" x-show="isOpenModal" id="test">
+ only a test
+  <input class="picker" />
+</div>
+
+

......

+
    <script>
+      const fp = flatpickr(".picker", {
+        locale: "at", 
+        minDate: "1930-01",
+        maxDate: 'today',
+        enableTime: true,
+        time_24hr: true,
+        minTime: "07:00",
+        maxTime: "20:00",
+        dateFormat: "d.m.Y H:i",
+        disableMobile: "true",
+        static:false,
+              });
+
+     function app(){  
+        return {
+            isOpenModal: true,
+            modalData: '<input class=" form-control placeholder-primary-500 picker">',
+            }
+        }
+
+ +

in this very simple example 2 input field are shown up, but only the second shows the flatpickr.

+

Try:

+
    +
  • If i delete the second the first will be not working.
  • +
  • x-text instead of x-html brings only the text <input ..... >
  • +
  • on the other hand without alpine.js it is working
  • +
+
<script>
+ const test = document.getElementById('test').innerHTML = '<input class="picker" />';
+ const fp = flatpickr(".picker", {
+            locale: "at",
+            minDate: "1930-01",
+            maxDate: 'today',
+            enableTime: true,
+            time_24hr: true,
+            minTime: "07:00",
+            maxTime: "20:00",
+            dateFormat: "d.m.Y H:i",
+            disableMobile: "true",
+            static:false,
+      });
+ </script>
+
+

UPDATE 30.10.20: +I simplified the code, is still not working but why ?

+
<div x-data="test()">
+ <button  @click="show = true"> Klick </button>
+    <div  x-show="show" x-model="daten" x-html="daten"> 
+ <input class="bg-green-500 picker" />
+</div>
+
+

it is shown up correctly, flatpickr is initialized but the picker is not shown up.

+
    function test() {
+    return {
+        daten:'<input class="bg-red-500 picker" />',
+        show: false,
+    }
+}
+
+

such a simple code and not working :( +I hope you understand my confusing special problem.

+

Thanks for helping,

+

Greets Martin

","

The issue here is initializing the flatpickr. if you add it on the init hook of the alphine component it works perfectly. so when alphine component initializes the code segment in init hook will be executed. +So to solve your issue,

+
 <div x-data="app()" x-init="initFlatpickr">
+       <input x-ref="picker" />
+ </div>
+
+
+

and in the script tag,

+
<script> 
+     function app() {
+            return {
+                initFlatpickr() {
+                    const fp = flatpickr(this.$refs.picker, {
+                        locale: "at",
+                        minDate: "1930-01",
+                        maxDate: "today",
+                        enableTime: true,
+                        time_24hr: true,
+                        minTime: "07:00",
+                        maxTime: "20:00",
+                        dateFormat: "d.m.Y H:i",
+                        disableMobile: "true",
+                        static: false,
+                    });
+                }
+            }
+        }
+</script>
+
+
+

Now the initFlatpickr function will execute when the alphine js component is initialized. +I have made use of refs which is a helpful alternative to setting ids and using document.querySelector all over the place. +check out the docs for more detail.

",python +"psycopg2.ProgrammingError: can't adapt type 'set'

There is this discord bot. I wan't to create for my server. But i used psycopg2 because i wan't it to create a list of projects ideas. And i got this error psycopg2.ProgrammingError: can't adapt type 'set' there is my code:

+
import psycopg2
+import os
+from discord.ext import commands
+import discord
+
+conn = psycopg2.connect(
+        host="ec2-3-216-92-193.compute-1.amazonaws.com",
+        database="d1vpende403347",
+        user="hnzgmwsoiogmmt",
+        password="86bfca0c982e04ae0ca6e6f4d1f4fb03ca5f4f4cb9a911672fa993a300e7ea0e",
+        port=5432)
+bot=discord.Client()
+bot=commands.Bot(command_prefix="!")
+cursor=conn.cursor()
+
+@bot.command()
+async def rules(ctx):
+    await ctx.send("1. To enter our server, you have of course to learn python and some libraries, for example: 'discord.py', 'django'.\n2. No insults or bad words.\n3.Enjoy it.")
+@bot.command()
+async def new(ctx, author:discord.Member, project):
+    name=author.display_name
+    await ctx.send(f"There is your entry: The author: {name} , project: {project}")
+    cursor.execute(f"INSERT INTO ideas(author,project) VALUES(%s,%s)",({name},{project}))
+    await ctx.send("The entry was succesfully added""")
+
+print("And There it is, you're connected")
+
+TOKEN=os.environ.get("DISCORD_BOT_SECRET")
+bot.run(TOKEN)
+
+cursor.close()
+conn.close()
+
+

thx for the response

","
import psycopg2
+import os
+from discord.ext import commands
+import discord
+
+conn = psycopg2.connect(
+        host="ec2-3-216-92-193.compute-1.amazonaws.com",
+        database="d1vpende403347",
+        user="hnzgmwsoiogmmt",
+        password="86bfca0c982e04ae0ca6e6f4d1f4fb03ca5f4f4cb9a911672fa993a300e7ea0e",
+        port=5432)
+bot=discord.Client()
+bot=commands.Bot(command_prefix="!")
+cursor=conn.cursor()
+
+@bot.command()
+async def rules(ctx):
+    await ctx.send("1. To enter our server, you have of course to learn python and some libraries, for example: 'discord.py', 'django'.\n2. No insults or bad words.\n3.Enjoy it.")
+@bot.command()
+async def new(ctx, author:discord.Member, project):
+    name=author.display_name
+    await ctx.send(f"There is your entry: The author: {name} , project: {project}")
+    cursor.execute(f"INSERT INTO ideas(author,project) VALUES(%s,%s)",(name,project))
+    await ctx.send("The entry was succesfully added""")
+
+print("And There it is, you're connected")
+
+TOKEN=os.environ.get("DISCORD_BOT_SECRET")
+bot.run(TOKEN)
+
+cursor.close()
+conn.close()
+
",python +"Disable unique constraint on Django's ManyToManyField

From the Django documentation for ManyToManyField:

+
+

If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint.

+
+

How do I disable this constraint? Is the only way to provide an explicit through table? Or is there a way to tell Django to not add the UniqueConstraint to the generated many-to-many-table?

","

m2m tables are linked by an intermediary table which manages the relationships and has a unique_together constraint. This table is automatically created but you can use your own table as the doc says with the through argument. You can read about it in the docs. In your case you need disable the unique_together constraint by defining your own intermediary table.

+

Other options are:

+
    +
  1. Extend the default ManyToManyField and override the contribute_to_class method.
  2. +
  3. Edit the default ManyToManyField directly as @Melvyn mentioned.
  4. +
",python +"Python 3 - reading utf-8 encoded csv into pandas

I am trying to load my utf-8 encoded csv file with data from Twitter (in polish language) into pandas dataframe in Python 3.

+

This is a piece of my csv:

+
2020-03-28 20:26:57,"b'Oj b\xc4\x99dzie impreza, oj b\xc4\x99dzie. #WyboryPrezydenckie2020 #Wybory2020 #Wybory\xc5\x9amierci'"
+2020-03-28 20:26:41,"b'Skoro Prezydent ju\xc5\xbc mi\xc4\x99dzy wierszami przemyca, \xc5\xbce wybory mog\xc4\x85 by\xc4\x87 prze\xc5\x82o\xc5\xbcone, to nale\xc5\xbcy czyta\xc4\x87, \xc5\xbce wybory b\xc4\x99d\xc4\x85 prze\xc5\x82o\xc5\xbcone, a i pewnie zostanie to poprzedzone kwiecistym or\xc4\x99dziem Prezydenta w pelerynie zbawcy narodu. #koronowiruswpolsce #WyboryPrezydenckie2020'"
+2020-03-28 20:24:50,"b'Idea i miara. Pomoc wyborc\xc3\xb3w i narodu g\xc5\x82osuj\xc4\x85cego dla medycyny przez #podatek_dla_demokracji, 360 mln z\xc5\x82 na subwencje dla partii i na #WyboryPrezydenckie2020 #Wybory2020 #wybory. STOP-dla-Subwencji dla partii i na wybory z mixu podatkowego.\n@tvp_info\n@Cyfrowy_Polsat\n@tvn24\n#POPiS'"
+
+

I was trying to load it this way:

+
df = pd.read_csv('WyboryPrezydenckie2020.csv', names=["date", "tweet"], encoding='utf-8')
+
+

but result looked like that:

+

+    date                    tweet
+0   2020-03-28 20:26:57     b'Oj b\xc4\x99dzie impreza, oj b\xc4\x99dzie. ...
+1   2020-03-28 20:26:41     b'Skoro Prezydent ju\xc5\xbc mi\xc4\x99dzy wie...
+2   2020-03-28 20:24:50     b'Idea i miara. Pomoc wyborc\xc3\xb3w i narodu...
+3   2020-03-28 20:22:34     b'RT @wkrawcz1: Kandydat @szymon_holownia m\x...
+4   2020-03-28 20:22:03     b'RT @wkrawcz1: Kandydat @szymon_holownia m\x...
+
+

and it seems that my tweets weren't decoded at all. For example the first tweet should look like that:

+
Oj będzie impreza, oj będzie. #WyboryPrezydenckie2020 #Wybory2020 #WyboryŚmierci
+
+

How can I solve this issue?

","

You've got strings for bytes (for some reason). To read it properly you need:

+
    +
  1. evaluate strings to bytes
  2. +
  3. decode unicode bytes to strings:
  4. +
+

+from ast import literal_eval
+df = pd.read_csv('WyboryPrezydenckie2020.csv', names=["date", "tweet"], converters={"tweet":lambda x:literal_eval(x).decode("utf8")})
+print(df)
+                  date                                              tweet
+0  2020-03-28 20:26:57  Oj będzie impreza, oj będzie. #WyboryPrezydenc...
+1  2020-03-28 20:26:41  Skoro Prezydent już między wierszami przemyca,...
+2  2020-03-28 20:24:50  Idea i miara. Pomoc wyborców i narodu głosując...
+
",python +"SyntaxError File ""import.py"", line 14
def division_title(initial):
+    n = initial.split()
+    if len(n) == 3 :
+    return n
+    else return [n[0],None,n[1]]
+
+

SyntaxError: invalid syntax +error message

","

You need to write it as follows.

+
def division_title(initial):
+    n = initial.split()
+    if len(n) == 3:
+     return n
+    
+
",python +"Format string with special chars

Below code throws KeyError. Any ideas please? I tried doubling the braces but still no luck.

+
v = "My Name='{x[1].name}'"
+p = "x[1].name"
+pv = 'test'
+v = v.format(p=pv)
+print(v)
+
+

I also do not want to create another variable and wanted to work formatting on v variable.

+

expected output

+
My Name='test'
+
","

If you really must use {x[1].name} as a format marker, you can create a suitable object to go in the place of x.

+
v = "My Name='{x[1].name}'"
+
+class Foo:
+    name = 'test'
+
+print(v.format(x=[Foo,Foo]))
+
+

Output:

+
My Name='test'
+
+

Here x is a list, x[1] is the class Foo, and x[1].name is the string 'test', as required.

",python +"Change date in Dataframe when midnight reached

I've got a Dataframe with a column 'Date_and_time' which is in datetime format. Unfortunately, when midnight is reached (line 15235: 2020-08-02 00:00:00.000000), the date doesn't change accordingly. So, 2020-08-02 00:00:00.000000 should go to 2020-08-03 00:00:00.00000 when midnight (00:00:00.000000) is reached. On line 15235 midnight is reached, but the date doesn't change until line 16000. How can I change this so the date is correct when midnight is reached? Thank you.

+
#Load file
+df = pd.read_csv(file, sep=";", names=["Date", "Time", "ID1","ID2","ID3","MP","ET"], skiprows = 1 ,float_precision='round_trip')
+df1 = df['Time'].str.split(expand=True)
+
+#Use columns 'Date' and 'Time' to create column 'Date_and_time' in datetime format
+df['Date_and_time'] =  (pd.to_datetime(df['Date']) +
+               pd.to_timedelta(df1[0]) + 
+               pd.to_timedelta(df1[1].str.replace('ms','').astype(int), unit='us'))
+
+Out[45]: 
+              Date  ...              Date_and_time
+0       2020/08/02  ... 2020-08-02 21:21:46.000000
+1       2020/08/02  ... 2020-08-02 21:21:46.082191
+2       2020/08/02  ... 2020-08-02 21:21:46.164383
+3       2020/08/02  ... 2020-08-02 21:21:46.246575
+4       2020/08/02  ... 2020-08-02 21:21:46.328767
+           ...  ...                        ...
+15235   2020/08/02  ... 2020-08-02 00:00:00.000000
+15236   2020/08/02  ... 2020-08-02 00:00:00.082191
+15237   2020/08/02  ... 2020-08-02 00:00:00.164383
+15238   2020/08/02  ... 2020-08-02 00:00:00.246575
+           ...  ...                        ...
+16000   2020/08/03  ... 2020-08-03 00:00:16.082191
+           ...  ...                        ...
+330404  2020/08/03  ... 2020-08-03 03:00:33.000000
+330405  2020/08/03  ... 2020-08-03 03:00:33.040513
+330406  2020/08/03  ... 2020-08-03 03:00:33.081026
+330407  2020/08/03  ... 2020-08-03 03:00:33.121539
+330408  2020/08/03  ... 2020-08-03 03:00:33.162052
+
+[330409 rows x 8 columns]
+
","

This is essentially another question requiring the "diff-cumsum" trick to accumulate the number of negative changes. In this case, however, .diff() does not support datetime difference so it would be more tricky to do.

+

Here is a quick and dirty showcase on df["Date_and_time"]. You should do the similar on the other columns involved by yourself.

+
from datetime import timedelta
+
+#df = pd.read_clipboard(sep=r"\s{2,}")
+df["Date_and_time"] = pd.to_datetime(df["Date_and_time"])
+# get timestamp in nanoseconds
+df["ns"] = df["Date_and_time"].values.astype(np.int64)
+# detect reversed time change and accumulate days
+df["days"] = (df["ns"].diff() < 0).cumsum()
+# add the days found 
+df["Date_and_time_new"] = df.apply(lambda row: row["Date_and_time"] + timedelta(days=row["days"]), axis=1)
+
+df
+Out[76]: 
+          Date              Date_and_time  ...  days          Date_and_time_new
+0   2020/08/02 2020-08-02 21:21:46.000000  ...     0 2020-08-02 21:21:46.000000
+1   2020/08/02 2020-08-02 21:21:46.082191  ...     0 2020-08-02 21:21:46.082191
+2   2020/08/02 2020-08-02 21:21:46.164383  ...     0 2020-08-02 21:21:46.164383
+3   2020/08/02 2020-08-02 21:21:46.246575  ...     0 2020-08-02 21:21:46.246575
+4   2020/08/02 2020-08-02 21:21:46.328767  ...     0 2020-08-02 21:21:46.328767
+5   2020/08/02 2020-08-02 00:00:00.000000  ...     1 2020-08-03 00:00:00.000000
+6   2020/08/02 2020-08-02 00:00:00.082191  ...     1 2020-08-03 00:00:00.082191
+7   2020/08/02 2020-08-02 00:00:00.164383  ...     1 2020-08-03 00:00:00.164383
+8   2020/08/02 2020-08-02 00:00:00.246575  ...     1 2020-08-03 00:00:00.246575
+9   2020/08/03 2020-08-03 00:00:16.082191  ...     1 2020-08-04 00:00:16.082191
+10  2020/08/03 2020-08-03 03:00:33.000000  ...     1 2020-08-04 03:00:33.000000
+11  2020/08/03 2020-08-03 03:00:33.040513  ...     1 2020-08-04 03:00:33.040513
+12  2020/08/03 2020-08-03 03:00:33.081026  ...     1 2020-08-04 03:00:33.081026
+13  2020/08/03 2020-08-03 03:00:33.121539  ...     1 2020-08-04 03:00:33.121539
+14  2020/08/03 2020-08-03 03:00:33.162052  ...     1 2020-08-04 03:00:33.162052
+[15 rows x 5 columns]
+
",python +"Given list of strings return just strings not contained in any other

I'm trying to find a computationally friendly way for doing the following:

+

given list_of_strings = ['many', 'man', 'cat', 'caterpillar', 'pillow', 'pi', 'pill']

+

return sublist = ['many', 'caterpillar', 'pillow'], i.e. the list of strings not contained in any other string.

+

The simplest solution would be to iterate over the elements and check whether each element is contained in the other, with O(n^2) complexity (even if there are some little optimizations I thought about, like sorting the strings by length, but this adds the sorting complexity), but I think it's too expensive.

+

I thought also about implementing a trie and then use each element of the list as an haystack, then keeping just the strings contained in one haystack (that of the string itself).

+

I think I'm missing more than I know, so I'm looking for suggestions

","

I've implemented the following (but I'm eager to see other approaches before accepting any answer):

+
import ahocorasick
+
+def make_automation(list_of_tokens):
+    A = ahocorasick.Automaton()
+    for idx, key in enumerate(list_of_tokens):
+        A.add_word(key, (idx, key))
+    A.make_automaton()
+    return A
+
+def search_list_aho_corasick(txt_to_search, ahocorasick_automaton):
+    match = []
+    for end_index, (insert_order, original_value) in ahocorasick_automaton.iter(txt_to_search):
+        start_index = end_index - len(original_value) + 1
+        if original_value == txt_to_search:
+            continue
+        else:
+            match.append(original_value) 
+        assert txt_to_search[start_index:start_index + len(original_value)] == original_value
+    return match
+
+def filter_matches(list_of_matches):
+    if len(list_of_matches) == 0:
+        return list_of_matches
+    else:
+        aut = make_automation(list_of_matches)
+        contained = []
+        contained_result = list(map(lambda x: search_list_aho_corasick(x, aut), list_of_matches))
+        return list(set(list_of_matches) - set(flatten_list(contained_result)))
+
+

So in our case:

+
result = filter_matches(list_of_strings)
+
+

It uses ahocorasick package, which implements Aho-Corasick algorithm for string search.

+

Compared to @IoaTzimas answers it drastically reduces computation time: I've backtested both on a 40k list and it went from roughly 330seconds to less than a second

",python +"Numpy doesn't throw FloatingPointError for dot product

I am taking the dot-product of two numpy arrays (both float32). I am deliberately setting numpy to raise a FloatingPointError in case of overflow. However, dot does not behave as expected: instead of raising a FloatingPointError as it does when using ordinary multiplication, dot returns inf.

+

Is this the intended behavior? Is there a way to force dot to raise an exception as well?

+

Minimal working example:

+
import numpy as np
+
+np.seterr(over="raise")
+
+x = np.array([2e+38], dtype=np.float32)
+y = np.array([10], dtype=np.float32)
+
+x * y
+>>> FloatingPointError: overflow encountered in multiply
+
+np.dot(x,y)
+>>> inf
+
","

Accepting @hpaulj's comment as the answer – matmul does throw a FloatingPointError as required, while dot doesn't (no idea why). For my purpose matmul gives the same result as dot.

",python +"Creating masks for duplicate elements in Tensorflow/Keras

I am trying to write a custom loss function for a person-reidentification task which is trained in a multi-task learning setting along with object detection. The filtered label values are of the shape (batch_size, num_boxes). I would like to create a mask such that only the values which repeat in dim 1 are considered for further calculations. How do I do this in TF/Keras-backend?

+

Short Example:

+
Input labels = [[0,0,0,0,12,12,3,3,4], [0,0,10,10,10,12,3,3,4]]
+Required output: [[0,0,0,0,1,1,1,1,0],[0,0,1,1,1,0,1,1,0]] 
+
+

(Basically I want to filter out only duplicates and discard unique identities for the loss function).

+

I guess a combination of tf.unique and tf.scatter could be used but I do not know how.

","

This code works:

+
x = tf.constant([[0,0,0,0,12,12,3,3,4], [0,0,10,10,10,12,3,3,4]])
+def mark_duplicates_1D(x):
+  y, idx, count = tf.unique_with_counts(x)
+  comp = tf.math.greater(count, 1)
+  comp = tf.cast(comp, tf.int32)
+  res = tf.gather(comp, idx)
+  mult = tf.math.not_equal(x, 0)
+  mult = tf.cast(mult, tf.int32)
+  res *= mult
+  return res
+res = tf.map_fn(fn=mark_duplicates_1D, elems=x)
+
",python +"How do I split up thresholds into squares in OpenCV2?

I have a picture of a lovely Rubiks cube:

+

+

I want to split it into squares and identify the colour of each square. I can run a Guassian Blur on it, followed by 'Canny' before ending on 'Dilate' in order to get the following:

+

+

This visibly looks good, but I'm unable to turn it into squares. Any sort of 'findContours' I try brings up only one or two squares. Nowhere near the nine I'm aiming for. Do people have any ideas on what I can do beyond this?

+

Current best solution:

+

+

The code is below and requires numpy + opencv2. It expects a file called './sides/rubiks-side-F.png' and outputs several files to a 'steps' folder.

+
import numpy as np
+import cv2 as cv
+
+def save_image(name, file):
+    return cv.imwrite('./steps/' + name + '.png', file)
+
+
+def angle_cos(p0, p1, p2):
+    d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
+    return abs(np.dot(d1, d2) / np.sqrt(np.dot(d1, d1)*np.dot(d2, d2)))
+
+def find_squares(img):
+    img = cv.GaussianBlur(img, (5, 5), 0)
+    squares = []
+    for gray in cv.split(img):
+        bin = cv.Canny(gray, 500, 700, apertureSize=5)
+        save_image('post_canny', bin)
+        bin = cv.dilate(bin, None)
+        save_image('post_dilation', bin)
+        for thrs in range(0, 255, 26):
+            if thrs != 0:
+                _retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)
+                save_image('threshold', bin)
+            contours, _hierarchy = cv.findContours(
+                bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
+            for cnt in contours:
+                cnt_len = cv.arcLength(cnt, True)
+                cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
+                if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
+                    cnt = cnt.reshape(-1, 2)
+                    max_cos = np.max(
+                        [angle_cos(cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4]) for i in range(4)])
+                    if max_cos < 0.2:
+                        squares.append(cnt)
+    return squares
+
+img = cv.imread("./sides/rubiks-side-F.png")
+squares = find_squares(img)
+cv.drawContours(img, squares, -1, (0, 255, 0), 3)
+save_image('squares', img)
+
+

You can find other sides here

","

I know that you might not accept this answer because it is written in C++. That's ok; I just want to show you a possible approach for detecting the squares. I'll try to include as much detail as possible if you wish to port this code to Python.

+

The goal is to detect all 9 squares, as accurately as possible. These are the steps:

+
    +
  1. Get an edge mask where the outline of the complete cube is +clear and visible.
  2. +
  3. Filter these edges to get a binary cube (segmentation) mask.
  4. +
  5. Use the cube mask to get the cube’s bounding box/rectangle.
  6. +
  7. Use the bounding rectangle to get the dimensions and location of +each square (all the squares have constant dimensions).
  8. +
+

First, I'll try to get an edges mask applying the steps you described. I just want to make sure I get to a similar starting point like where you currently are.

+

The pipeline is this: read the image > grayscale conversion > Gaussian Blur > Canny Edge detector:

+
    //read the input image:
+    std::string imageName = "C://opencvImages//cube.png";
+    cv::Mat testImage =  cv::imread( imageName );
+
+    //Convert BGR to Gray:
+    cv::Mat grayImage;
+    cv::cvtColor( testImage, grayImage, cv::COLOR_RGB2GRAY );
+
+   //Apply Gaussian blur with a X-Y Sigma of 50:
+    cv::GaussianBlur( grayImage, grayImage, cv::Size(3,3), 50, 50 );
+
+    //Prepare edges matrix:
+    cv::Mat testEdges;
+
+    //Setup lower and upper thresholds for edge detection:
+    float lowerThreshold = 20;
+    float upperThreshold = 3 * lowerThreshold;
+
+    //Get Edges via Canny:
+    cv::Canny( grayImage, testEdges, lowerThreshold, upperThreshold );
+
+

Alright, this is the starting point. This is the edges mask I get:

+ +

Close to your results. Now, I'll apply a dilation. Here, the number of iterations of the operation is important, because I want nice, thick edges. Closing opened contours is also desired, so, I want an mild-aggressive dilation. I set the number of iterations = 5 using a rectangular structuring element.

+
    //Prepare a rectangular, 3x3 structuring element:
+    cv::Mat SE = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(3, 3) );
+
+    //OP iterations:
+    int dilateIterations = 5;
+
+   //Prepare the dilation matrix:
+    cv::Mat binDilation;
+
+   //Perform the morph operation:
+    cv::morphologyEx( testEdges, binDilation, cv::MORPH_DILATE, SE, cv::Point(-1,-1), dilateIterations );
+
+

I get this:

+ +

This is the output so far with nice and very defined edges. The most important thing is to clearly define the cube, because I'll rely on its outline to compute the bounding rectangle later.

+

What follows is my attempt to clean the cube's edges from everything else as accurately as possible. There's a lot of garbage and pixels that do not belong to the cube, as you can see. I'm especially interested on flood-filling the background with a color (white) different from the cube (black) in order to get a nice segmentation.

+

Flood-filling has a disadvantage, though. It can also fill the interior of a contour if it is not closed. I try to clean garbage and close contours in one go with a "border mask", which are just white lines at the side of the dilation mask.

+

I implement this mask as four SUPER THICK lines that border the dilation mask. To apply the lines I need starting and ending points, which correspond to the image corners. These are defined in a vector:

+
    std::vector< std::vector<cv::Point> > imageCorners;
+    imageCorners.push_back( { cv::Point(0,0), cv::Point(binDilation.cols,0) } );
+    imageCorners.push_back( { cv::Point(binDilation.cols,0), cv::Point(binDilation.cols, binDilation.rows) } );
+    imageCorners.push_back( { cv::Point(binDilation.cols, binDilation.rows), cv::Point(0,binDilation.rows) } );
+    imageCorners.push_back( { cv::Point(0,binDilation.rows), cv::Point(0, 0) } );
+
+

Four starting/ending coordinates in a vector of four entries. I apply the "border mask" looping through these coordinates and drawing the thick lines:

+
    //Define the SUPER THICKNESS:
+    int lineThicness  = 200;
+
+    //Loop through my line coordinates and draw four lines at the borders:
+    for ( int c = 0 ; c < 4 ; c++ ){
+        //Get current vector of points:
+        std::vector<cv::Point> currentVect = imageCorners[c];
+       //Get the starting/ending points:
+        cv::Point startPoint = currentVect[0];
+        cv::Point endPoint = currentVect[1];
+        //Draw the line:
+        cv::line( binDilation, startPoint, endPoint, cv::Scalar(255,255,255), lineThicness );
+    }
+
+

Cool. This gets me this output:

+ +

Now, let's apply the floodFill algorithm. This operation will fill a closed area of same colored pixels with a "substitute" color. It needs a seed point and the substitute color (white in this case). Let's Flood-fill at the four corners inside of the white mask we just created.

+
    //Set the offset of the image corners. Ensure the area to be filled is black:
+    int fillOffsetX = 200;
+    int fillOffsetY = 200;
+    cv::Scalar fillTolerance = 0; //No tolerance
+    int fillColor = 255; //Fill color is white
+   
+    //Get the dimensions of the image:
+    int targetCols = binDilation.cols;
+    int targetRows = binDilation.rows;
+
+    //Flood-fill at the four corners of the image:
+    cv::floodFill( binDilation, cv::Point( fillOffsetX, fillOffsetY ), fillColor, (cv::Rect*)0, fillTolerance, fillTolerance);
+    cv::floodFill( binDilation, cv::Point( fillOffsetX, targetRows - fillOffsetY ), fillColor, (cv::Rect*)0, fillTolerance, fillTolerance);
+    cv::floodFill( binDilation, cv::Point( targetCols - fillOffsetX, fillOffsetY ), fillColor, (cv::Rect*)0, fillTolerance, fillTolerance);
+    cv::floodFill( binDilation, cv::Point( targetCols - fillOffsetX, targetRows - fillOffsetY ), fillColor, (cv::Rect*)0, fillTolerance, fillTolerance);
+
+

This can also be implemented as a loop, just like the "border mask". After this operation I get this mask:

+ +

Getting close, right? Now, depending on your image, some garbage could survive all these "cleaning" operations. I'd suggest applying an area filter. The area filter will remove every blob of pixels that is under a threshold area. This is useful, because the cube's blobs are the biggest blobs on the mask and those surely will survive the area filter.

+

Anyway, I'm just interested on the cube's outline; I don't need those lines inside the cube. I'm going to dilate the hell out of the (inverted) blob and then erode back to original dimensions to get rid of the lines inside the cube:

+
    //Get the inverted image:
+    cv::Mat cubeMask = 255 - binDilation;
+
+    //Set some really high iterations here:
+    int closeIterations = 50;
+
+    //Dilate
+    cv::morphologyEx( cubeMask, cubeMask, cv::MORPH_DILATE, SE, cv::Point(-1,-1), closeIterations );
+    //Erode:
+    cv::morphologyEx( cubeMask, cubeMask, cv::MORPH_ERODE, SE, cv::Point(-1,-1), closeIterations );
+
+

This is a closing operation. And a pretty brutal one, this is the result of applying it. Remember I previously inverted the image:

+ +

Isn't that nice or what? Check out the cube mask, here overlaid into the original RBG image:

+ +

Excellent, now let's get the bounding box of this blob. The approach is as follows:

+
Get blob contour > Convert contour to bounding box
+
+

This is fairly straightforward to implement, and the Python equivalent should be very similar to this. First, get the contours via findContours. As you see, there should be only one contour: the cube outline. Next, convert the contour to a bounding rectangle using boundingRect. In C++ this is the code:

+
    //Lets get the blob contour:
+    std::vector< std::vector<cv::Point> > contours;
+    std::vector<cv::Vec4i> hierarchy;
+
+    cv::findContours( cubeMask, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
+
+    //There should be only one contour, the item number 0:
+    cv::Rect boundigRect = cv::boundingRect( contours[0] );
+
+

These are the contours found (just one):

+ +

Once you convert this contour to a bounding rectangle, you can get this nice image:

+ +

Ah, we are very close to the end here. As all the squares have the same dimensions and your image doesn’t seem to be very perspective-distorted, we can use the bounding rectangle to estimate the square dimensions. All the squares have the same width and height, there are 3 squares per cube width and 3 squares per cube height.

+

Divide the bounding rectangle in 9 equal sub-squares (or, as I call them, "grids") and get their dimensions and location starting from the coordinates of the bounding box, like this:

+
    //Number of squares or "grids"
+    int verticalGrids = 3;
+    int horizontalGrids = 3;
+
+    //Grid dimensions:
+    float gridWidth = (float)boundigRect.width / 3.0;
+    float gridHeight = (float)boundigRect.height / 3.0;
+
+    //Grid counter:
+    int gridCounter = 1;
+    
+    //Loop thru vertical dimension:
+    for ( int j = 0; j < verticalGrids; ++j ) {
+
+        //Grid starting Y:
+        int yo = j * gridHeight;
+
+        //Loop thru horizontal dimension:
+        for ( int i = 0; i < horizontalGrids; ++i ) {
+
+            //Grid starting X:
+            int xo = i * gridWidth;
+            
+            //Grid dimensions:
+            cv::Rect gridBox;
+            gridBox.x = boundigRect.x + xo;
+            gridBox.y = boundigRect.y + yo;
+            gridBox.width = gridWidth;
+            gridBox.height = gridHeight;
+
+            //Draw a rectangle using the grid dimensions:
+            cv::rectangle( testImage, gridBox, cv::Scalar(0,0,255), 5 );
+
+            //Int to string:
+            std::string gridCounterString = std::to_string( gridCounter );
+
+            //String position:
+            cv::Point textPosition;
+            textPosition.x = gridBox.x + 0.5 * gridBox.width;
+            textPosition.y = gridBox.y + 0.5 * gridBox.height;
+
+            //Draw string:
+            cv::putText( testImage, gridCounterString, textPosition, cv::FONT_HERSHEY_SIMPLEX,
+                         1, cv::Scalar(255,0,0), 3, cv::LINE_8, false );
+
+            gridCounter++;
+
+        }
+
+    }
+
+

Here, for each grid, I'm drawing its rectangle and a nice number at the center of it. The draw rectangle function requires a defined rectangle: Upper left starting coordinates and rectangle width and height, which are defined using the gridBox variable of cv::Rect type.

+

Here's a cool animation of how the cube gets divided into 9 grids:

+ +

Here’s the final image!

+ +

Some suggestions:

+
    +
  1. Your source image is way too big, try resizing it to a smaller size, operate
    +on it and scale back the results.
  2. +
  3. Implement the area filter. It is very handy in getting rid of small +blobs of pixels.
  4. +
  5. Depending on your images (I just tested the once you posted in your +question) and the perspective distortion introduced by the camera, a +simple contour to boundingRect might not be enough. In that case, +another approach would be to get the four points of the cube outline +via Hough line detection.
  6. +
",python +"Ansible Runner can't execute playbook

I am trying execute an ansible playbook inside a Flask Python project using ansible runner but upon execution, I get the following error: The command was not found or was not executable: ansible-playbook.

+

The app runs in a docker container inside directory /app.

+

Code:

+
        r = ansible_runner.run(private_data_dir='/app/flask/ansible', playbook='project/playbook.yml')
+        app.logger.info("{}: {}".format(r.status, r.rc))
+        # successful: 0
+        for each_host_event in r.events:
+            app.logger.info(each_host_event['event'])
+        app.logger.info("Final status:")
+        app.logger.info(r.stats)
+
+

This is the project tree:

+
.
+├── README.md
+├── ansible.cfg
+├── docker-compose.yml
+├── flask
+│   ├── Dockerfile
+│   ├── ansible
+│   │   ├── env
+│   │   │   ├── cmdline
+│   │   │   ├── envvars
+│   │   │   ├── extravars
+│   │   │   ├── passwords
+│   │   │   ├── settings
+│   │   │   └── ssh-key
+│   │   ├── inventory
+│   │   │   └── hosts
+│   │   └── project
+│   │       └── playbook.yml
+│   ├── app.ini
+│   ├── main.py
+│   ├── run.py
+│   ├── static
+│   │   ├── app.js
+│   │   ├── bulma.min.css
+│   │   ├── highlight.min.css
+│   │   ├── highlight.min.js
+│   │   └── styles.css
+│   └── templates
+│       ├── 404.html
+│       ├── base.html
+│       ├── create_user.html
+│       └── login.html
+├── nginx
+│   ├── Dockerfile
+│   └── nginx.conf
+
+

Flask DockerFile:

+
FROM python:3.7.2-stretch
+WORKDIR /app
+ADD . /app
+RUN pip install --upgrade pip && pip install flask uwsgi requests ansible_runner
+CMD ["uwsgi","app.ini"]
+
","

The ansible_runner Python package is just an interface to the ansible executable. You need to install Ansible itself within your Docker container. Add RUN apt-get update && apt-get install -y ansible to your Dockerfile

+
FROM python:3.7.2-stretch
+
+RUN apt-get update && \
+    apt-get install -y ansible && \
+    rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+ADD . /app
+RUN pip install --upgrade pip && pip install flask uwsgi requests ansible_runner
+CMD ["uwsgi","app.ini"]
+
",python +"How to find the row number from a character index in python?

I have a genetic dataset where the index of a row is the name of the gene. I am looking to also find the row number of any given gene so I can look at genes individually after they've gone through a machine learning model prediction - to interpret the gene's prediction in shap. How I code for the shap plot currently needs a row number to pull out the specific gene.

+

My data looks like this:

+
Index   Feature1  Feature2   ... FeatureN
+Gene1     1           0.2          10
+Gene2     1           0.1          7
+Gene3     0           0.3          10
+
+

For example if I want to pull out and view model prediction of Gene3 I do this:

+
import shap
+shap.initjs()
+
+xgbr = xgboost.XGBRegressor()
+
+def shap_plot(j):
+    explainerModel = shap.TreeExplainer(xgbr)
+    shap_values_Model = explainerModel.shap_values(X_train)
+    p = shap.force_plot(explainerModel.expected_value, shap_values_Model[j], X_train.iloc[[j]],feature_names=df.columns)
+    return(p)
+
+shap_plot(3)
+
+

Doing shap_plot(3) is a problem for me as I do not actually know if the gene I want is in row 3 in the shuffled training or testing data.

+

Is there a way to pull out the row number from a known Gene index? Or potentially re-code my shap plot so it does accept my string indices? I have a biology background so any guidance would be appreciated.

","

Try the following. df is your dataframe and result will give you the row number (first row will result 1, etc) for a given gene

+
list(df.index).index('Gene3')+1
+
+#result
+
+3
+
",python +"How do I create a ""rpg door"" effect in pygame, and what's wrong with my method?

I'm creating a game where going near a door(defined using Rect function) calls a function which loads a new game screen which gives the effect of going through to that door inside the house. I tried to do the same thing with the coming out mechanism where I tried to define an area with a Rect object and made it so that when the player comes near it the main game loop is called and it would give the effect of coming out the door but doing so makes it so that the player is stuck in an infinite loop of the screen fading away. the part of the code is attached below and the full code is here

+

this is the door collision detection

+
    out = pygame.Rect(360, 580, 80, 10)
+    player_rect = playerImgXL.get_rect(topleft=(playerXxl, playerYxl))
+
+    if player_rect.colliderect(out):
+        game()  # coming out of the house
+
+

this is the game loop function

+
def game():
+  global present_dialogue
+  global current_dialogue
+  global playerX
+  global playerY
+  clock.tick(12)
+  mixer.music.pause()
+  mixer.music.load('pallet_music.mp3')
+  # mixer.music.play(100)
+  playerX_change = 0
+  playerY_change = 0
+  running = True
+  while running:
+      present_dialogue = None
+      current_dialogue = None
+      for event in pygame.event.get():
+          if event.type == pygame.QUIT:
+              pygame.quit()
+              sys.exit()
+      redrawgamewindow()
+      pygame.display.update()
+
+

this isn't the entire game loop there's just the event detection and collision detection between the sys.exit statement and the display update statement

+

this is the redrawgamewindow function that I call at the end of the game loop

+
def redrawgamewindow():
+  global walkcount
+  scr.fill((0, 0, 0))
+  scr.blit(pallet, (60, 0))
+  if current_dialogue:
+      scr.blit(*current_dialogue)
+      npc_one_dialogue()
+  if walkcount + 1 >= 29:
+      walkcount = 0
+  if up:
+      scr.blit(WalkFront[walkcount // 7], (playerX, playerY))
+      walkcount += 1
+  elif down:
+      scr.blit(WalkBack[walkcount // 7], (playerX, playerY))
+      walkcount += 1
+  elif left:
+      scr.blit(WalkLeft[walkcount // 7], (playerX, playerY))
+      walkcount += 1
+  elif right:
+      scr.blit(WalkRight[walkcount // 7], (playerX, playerY))
+      walkcount += 1
+  else:
+      player(playerX, playerY)
+  if present_dialogue:
+      scr.blit(*present_dialogue)
+      npc_two_dialogue()
+
","

A few changes are needed to prevent the fade loop:

+
    +
  • In the inhouse_oak function, reset the starting position when the player enters the room

    +
  • +
  • When the player exits the room, just return to the main game loop

    +
    def inhouse_oak():
    +    global playerXxl
    +    global playerYxl
    +    playerXxl = 365  # reset starting position
    +    playerYxl = 480
    +    ...........
    +    while running:
    +        .................
    +        if player_rect.colliderect(out):
    +            return  # return to main loop
    +            # game()  # coming out of the house
    +
    +
  • +
  • In the main loop, when the player exits the room, move the player away from the door

    +
      door3 = pygame.Rect(462, 348, 25, 5)
    +  if player_rect.colliderect(door3):
    +      fade(800, 600)
    +      inhouse_oak()  # Oak's Lab door
    +      playerY_change = playerX_change = 0  # stop player movement
    +      playerY += 10  # move away from door
    +
    +
  • +
+

To add a fade when exiting the room, make these changes:

+
    +
  • Generalize the fade function.

    +
    def fade(x, y, rgw):  # last parameter is screen function to call
    +    fade = pygame.Surface((x, y))
    +    fade.fill((0, 0, 0))
    +    for alpha in range(0, 300):
    +        fade.set_alpha(alpha)
    +        rgw(True)  # fading = True
    +        scr.blit(fade, (0, 0))
    +        pygame.display.update()
    +
    +
  • +
  • Add the fading parameter to the main game function.

    +
    def redrawgamewindow(fading=False):
    +
    +
  • +
  • Add the fading parameter to the room function and check the parameter before updating the screen to prevent screen flash.

    +
    def redrawgamewindow_oak(fading=False):
    +    .........
    +    if not fading: pygame.display.update()  # prevent flash if fading
    +
    +
  • +
  • Update the fade call in the redrawgamewindow function.

    +
      door3 = pygame.Rect(462, 348, 25, 5)
    +  if player_rect.colliderect(door3):
    +      fade(800, 600, redrawgamewindow)  # fade main game
    +      inhouse_oak()  # Oak's Lab door
    +      playerY_change = playerX_change = 0
    +      playerY += 10  #playerX_change
    +
    +
  • +
  • In redrawgamewindow_oak, when leaving the room, call the fade function.

    +
      if player_rect.colliderect(out):
    +      fade(800, 600, redrawgamewindow_oak)  # fade room
    +      return  # return to main loop
    +      #game()  # coming out of the house
    +
    +
  • +
",python +"how do I process an excel file with hyperlink/url in pandas?

I have an excel file that has one column filled with Hyperlinks, I read it using df = pd.read_excel() then filtered it and saved it to a new excel file with df.to_excel().

+

The problem is that I have now lost the clickable hyperlinks, instead, there's just the text(not a hyperlink)

+

Can I use pandas for this? or should I be using some other library?

","

You can use the import xlsxwriter library to add hyperlinks. Speaking of hyperlinks, the example here shows some examples such as:

+
worksheet.write_url('A5', 'http://www.python.org/', tip='Click here')
+
+

But, if you don't want to manually write a line of code for each cell, then you can loop through and add the hyperlinks dynamically if you have a list of all the hyperlinks.

+
hyperlinks = ['a.com', 'b.com', 'c.com' ... etc.]
+
+for i in range(1, len(hyperlinks)):
+    worksheet.write_url(f'A{i}', hyperlinks[i-1], tip=df['column string'][i-1])
+
+

Your hyperlinks would obviously have to be in the correct order in the list, or you could create a dictionary that makes the text and hyperlink a key-value pair and use .map to bring the hyperlink into your dataframe as a column. Then you could sort the values and send the hyperlink to a list with hyperlinks = df['hyperlink'].to_list(). Then you could run the for-loop.

+

But, I think you will have to create a list or dictionary first.

+
+

Also, check out this answer for reading in date with hyperlinks using openpyxl:

+

Pandas read_excel with Hyperlink

+

And, this one for writing data with hyperlinks using pandas:

+

add hyperlink to excel sheet created by pandas dataframe to_excel method

",python +"Close PyQt Dialog without closing main programme

I am trying to use a PyQt dialog created in Qt Designer to take some user inputs (complexity rating, material type and machine type) before using these input for the reminder of my python programme. The options displayed in the dialog box are read out from a dictionary. My problem is that no matter what I have tried, closing the dialog box, through pressing the submit button, stops the remainder of my programme running, whether I keep the dialog box in the main py programme or run it as a function in a separate file. I am quite sure it is related to the sys.exit(app.exec_()) line, I have also tried using .close and .reject for closing the dialog with the same result. Also I'm aware that the programme is not great and I'm butchering the variable passing out of the function, but if you have any advice for how to get the rest of my programme talking with the dialog box I would be super grateful, I have exhausted the rest of Google on this problem, thanks so much!

+
import os
+import numpy as np
+
+def get_part_info():
+    material_ops =[]
+    complex_ops = [1,2,3]
+    machine_ops = []
+    
+#---Dictionary containing material options and machine options is read out here, this part works fine ----
+    
+    mat_choice = 'empty'
+    comp_choice = 'empty'
+    mach_choice = 'empty'
+    
+    from PyQt5 import QtCore, QtGui, QtWidgets
+    class Ui_Dialog(object):
+        def setupUi(self, Dialog):
+            Dialog.setObjectName("Dialog")
+            Dialog.resize(227, 217)
+            self.verticalLayout_3 = QtWidgets.QVBoxLayout(Dialog)
+            self.verticalLayout_3.setObjectName("verticalLayout_3")
+            self.verticalLayout = QtWidgets.QVBoxLayout()
+            self.verticalLayout.setObjectName("verticalLayout")
+            self.Material = QtWidgets.QComboBox(Dialog)
+            self.Material.setObjectName("Material")
+            self.verticalLayout.addWidget(self.Material)
+            self.Complexity = QtWidgets.QComboBox(Dialog)
+            self.Complexity.setObjectName("Complexity")
+            self.verticalLayout.addWidget(self.Complexity)
+            self.Machine = QtWidgets.QComboBox(Dialog)
+            self.Machine.setObjectName("Machine")
+            self.verticalLayout.addWidget(self.Machine)
+            self.textEdit = QtWidgets.QTextEdit(Dialog)
+            self.textEdit.setObjectName("textEdit")
+            self.verticalLayout.addWidget(self.textEdit)
+            self.verticalLayout_3.addLayout(self.verticalLayout)
+            self.Submit = QtWidgets.QPushButton(Dialog)
+            self.Submit.setMaximumSize(QtCore.QSize(100, 16777215))
+            self.Submit.setObjectName("Submit")
+            self.verticalLayout_3.addWidget(self.Submit, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
+
+#------Read out from the dictionary is added to the drop down menus here-----
+
+            for i in list(material_ops):
+                self.Material.addItem(i)
+            for i in list(complex_ops):
+                self.Complexity.addItem(str(i))
+            for i in list(machine_ops):
+                self.Machine.addItem(i)
+    
+            self.Submit.pressed.connect(self.save)
+            self.retranslateUi(Dialog)
+            self.Submit.pressed.connect(Dialog.reject)
+            QtCore.QMetaObject.connectSlotsByName(Dialog)
+    
+        def retranslateUi(self, Dialog):
+            _translate = QtCore.QCoreApplication.translate
+            Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
+            self.Submit.setText(_translate("Dialog", "Submit"))
+    
+        def save(self):
+            global mat_choice, comp_choice, mach_choice
+            mat_choice = (self.Material.currentText())
+            comp_choice = (self.Complexity.currentText())
+            mach_choice = (self.Machine.currentText())
+    
+    if __name__ == "__main__":
+        import sys
+        app = QtWidgets.QApplication(sys.argv)
+        Dialog = QtWidgets.QDialog()
+        ui = Ui_Dialog()
+        ui.setupUi(Dialog)
+        Dialog.show() 
+        sys.exit(app.exec_())
+        return mat_choice, comp_choice, mach_choice, matdict
+        
+get_part_info()
+
+print('Rest of programme is working') # programme never gets this far
+
+#---The rest of the programme that uses these user chosen options is here and never runs due to the dialog closing stopping the whole programme ------
+
",

I solved this by removing the sys.exit(app.exec_()) line and used just app.exec_() instead which successfully runs the input dialog and then the remainder of the programme using the chosen values. I can't pretend to know why it works now but it does in case anyone encounters a similar issue.

,python +"Problems converting a python pygame into exe

okay so I'm trying to convert my python pygame game into a .exe file so I can send it to friends but every time I try to convert it creates the .exe file but I can't open it doesn't mark any error and it doesn't have any extra files

+

I have tried auto-py-to-exe and pyinstaller almost every possible combination

+

it only uses pygame, Sys and random modules and python of curse +here is a GitHub with the file

+

I don't know if you can tell me how to convert it or just straight upconvert it for me

","

Get py2exe. It is easy to use. Assuming your main script is game.py and that script includes all the other stuff, all you need to do is prepare yet another script, let us call it setup.py and type in:

+
+

from distutils.core import setup import py2exe
+setup(console=['game.py'])

+
+

Now execute that file and it compiles everything into an executable:

+
+

python setup.py py2exe

+
",python +"Creating new column from filtering others

I need to assign to a new column the value 1 or 0 depending on what other columns have. +I have around 30 columns with binary values (1 or 0), but also other variables with numeric, continuous, values (e.g. 200). I would like to avoid the write a logical condition with many OR, so I was wondering if there is an easy and fast way to do it. +For example, creating a list with name of columns and assign 1 to the new column if there is at least a value 1 across all the columns for that corresponding row.

+

Example:

+
a1 b1 d4    ....
+1   0  1
+0   0  1
+0   0  0
+...
+
+

Expected:

+
a1 b1 d4    .... New  
+1   0  1          1
+0   0  1          1
+0   0  0          0
+...
+
+

Many thanks for your help

","

Here is a simple solution:

+
df = pd.DataFrame({'a1':[1,0,0,1], 'b1':[0,0,0,1], 'd4':[1,1,0,0], 'num':[12,-2,0,3]})
+df['New'] = df[['a1','b1','d4']].any(1).astype('int')
+df
+
+    a1  b1  d4  num New
+0   1   0   1   12  1
+1   0   0   1   -2  1
+2   0   0   0   0   0
+3   1   1   0   3   1
+
",python +"I want to display all the data entered by user in view_project.html page in django

views.py

+
@login_required(login_url="/accounts/login/")
+def add_project(request):
+    if request.method == 'POST':
+        form = forms.CreateProject(request.POST, request.FILES)
+        if form.is_valid():
+            # save in db 
+            instance = form.save(commit=False)
+            instance.candidate = request.user 
+            instance.save()
+            return redirect ('view_project')
+    else :
+        form = forms.CreateProject()
+    return render(request, 'home/add_project.html', {'form': form})
+
+@login_required(login_url="/accounts/login/")
+def view_project(request):
+    return render(request, 'home/view_project.html')
+
+

models.py

+
from django.db import models
+from django.contrib.auth.models import User
+
+# Create your models here.
+class project(models.Model):
+    Name_of_the_organisation_or_Individual_applying = models.CharField(max_length=200)
+    Name_of_the_Project = models.CharField(max_length=200)
+    Name_of_the_Principal_Investigator = models.CharField(max_length=200)
+    date = models.DateTimeField(auto_now_add = True)
+    Cover_Letter = models.FileField(upload_to=None, max_length=254)
+    Summary_of_Project = models.CharField(max_length=500)
+    Study_Proposal = models.CharField(max_length=1000)
+    Any_other_documents_required = models.FileField(upload_to=None, max_length=254)
+    candidate = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
+
+

This is the views.py file where the project is added into the database for a particular user and the HTML file used for this is add_project.html

","

To display all the project, you have to pass them in your view using Django's context. Also, you need to use the query method on the models which you want to retrieve all of it's data. look into the code below to get a better idea.

+
@login_required(login_url="/accounts/login/")
+def view_project(request):
+    projects = project.objects.all()
+    context = {"projects":projects}
+    return render(request, 'home/view_project.html', context)
+
+

Then in your html file, you can then loop through all the "projects" context like this:

+
{% for project in projects %}
+<h1>{{project.Name_of_the_organisation_or_Individual_applying}} </h1>
+<h1>{{project.Name_of_the_Project}} </h1>
+# and so on for all other fields
+{% endfor %}
+
",python +"Python Dataframe get previous row
              Open    High     Low   Close     Volume  Dividends  Stock Splits
+Date                                                                                      
+2020-07-31  324.60  325.33  320.05  325.22   85210800        0.0             0 
+2020-08-03  327.01  328.31  326.42  327.48   53077900        0.0             0 
+2020-08-04  326.55  328.74  326.55  328.74   41917900        0.0             0 
+
+

How do I write the following in code:

+
+

If current row volume is more than previous row volume then add new +column titled position and subtract close - open of the current row ?

+
","

Not the most elegant but should work:

+
df['Position'] = np.nan
+df.loc[df['Volume']>df.shift(periods=1)['Volume'],'Position'] = df.loc[df['Volume']>df.shift(periods=1)['Volume'],'Close']-df.loc[df['Volume']>df.shift(periods=1)['Volume'],'Open']
+
+

If you are ok with 0.00 for positions where the volume condition is not satisfied (rather than NaN), a simpler version will work:

+
df['Position'] = (df.shift(periods=1)['Volume'] <df['Volume']) *(df['Close']-df['Open'])
+
",python +"Relative import between modules

I've written a group of functions that I wanted to use for my computation and I've organize them in some .py file, say functions1.py and functions2.py. Within the same folder I have also another file main.py, then:

+
root\ 
+- functions1.py
+- functions2.py 
+- main.py
+
+
+

Inside functions1.py suppose I have the following code:

+
import numpy as np
+
+def mycos(x): 
+    return np.cos(x)
+
+def mysin(x):
+    return np.sin(x)
+
+

While inside functions2.py:

+
from .functions1 import mysin, mycos
+
+def mytan(x):
+    return mysin(x)/mycos(x)
+
+
+

Now suppose that main.py contain:

+
import numpy as np
+from .functions2 import mytan
+
+angle = np.pi/3
+if mytan(angle) == np.tan(angle):
+    print('OK')
+
+

Then, If I execute main.py I got the following error:

+
Traceback (most recent call last):
+  File "functions2.py", line 6, in <module>
+    from .functions1 import mysin, mycos
+ImportError: attempted relative import with no known parent package
+
+

Did I miss something in the use of relative import?

","

i think this is because when you run the code you are not executing in the project directory, try adding these few lines at the beginning of the code of main.py

+
import os # don't add this line if you have already imported os
+os.chdir(os.path.dirname(os.path.abspath(__file__)))
+
+

let me know if this works, if it doesn't... can you share the full code to understand better your problem?

+
+EDIT
+the problem should be that the file functions1.py and functions2.py are not actually modules, to fix this i am gonna suggest you two solutions:

+

Create a folder

+as the two function file are not taken as a module, create a folder and put them inside it like so

+
MAINDIR
+– main.py
+– functions
+–– functions1.py
+–– functions2.py
+
+

the code is this

+

main.py

+
import numpy as np
+from functions.functions2 import mytan
+
+angle = np.pi/3
+if mytan(angle) == np.tan(angle):
+    print('OK')
+
+

functions1.py

+
import numpy as np
+
+def mycos(x):
+    return np.cos(x)
+
+def mysin(x):
+    return np.sin(x)
+
+

functions2.py

+
from .functions1 import mysin, mycos
+
+def mytan(x):
+    return mysin(x)/mycos(x)
+
+
+

Use __init__.py


+
MAINDIR
+– main.py
+– functions
+–– __init__.py
+–– functions1.py
+–– functions2.py
+
+

and this is the code

+init.py

+
import functions1, functions2
+
+

(and all other files just like the first solution)
+note that this solution is a bit longer, but this should be the most "correct" way to do this

+

And then?

+if you wanna understand better why it wasn't working i would like to suggest you to read this well done articles:
+real python
+geeks for geeks
+
+Cheers J.Bloom",python +"Best way to enhance a widget in another package?

The rgl package exports a couple of htmlwidgets: the one produced by rgl::rglwidget() and the one produced by rgl::playwidget(). In a separate package, I'd like to export some Javascript code that will work with these. (It will be a new control that can be handled by rgl::playwidget() and will modify an rgl widget.)

+

So this code is much less than a widget; it won't ever be displayed on its own. It needs to have the rgl code loaded first, and then it will add some rglwidgetClass methods.

+

How should this be done? Is there a way to make an invisible widget, that just exists so that dependencies can be declared?

","

I don't know if this is the best way, but here is one way to do what I want.

+

The idea is that the htmltools package allows you to attach dependencies to just about any HTML object that you're outputing. For example,

+
library(htmltools)
+p("This is some text", htmlDependency( .... ))
+
+

will automatically cause the htmlDependency to be loaded into the header of the created web page.

",html +"display list that in each row 1 li

How can I display the list that in each line I will have one li and not 2 li in one row?

+

+
+
<div class=""recent_questions promoted_questions pblock"">
+  <ul class=""vertical_menu main_questions"">
+    <li>
+      <span class=""header"">
+                    <a href=""covid.php"">corona<img src=""photos/Covid.gif""></a></span>
+      <span class=""questions""><span class=""big_image"">
+                  <img class=""photo_sub"" src=""photos/covid.jpg""/></span></span>
+    </li>
+    <li></li>
+    <li></li>
+  </ul>
+</div>
+
+
+

","

You can simply wrap your images into individual <li> elements, and they will appear below each other:

+

+
+
<div class=""recent_questions promoted_questions pblock"">
+    <ul class=""vertical_menu main_questions"">
+        <li>
+            <span class=""header"">
+                <a href=""covid.php"">
+                    corona
+                    <img src=""photos/Covid.gif"">
+                </a>
+            </span>
+        </li>
+        <li>
+            <span class=""questions"">
+                <span class=""big_image"">
+                    <img class=""photo_sub"" src=""photos/covid.jpg"" />
+                </span>
+            </span>
+        </li>
+    </ul>
+</div>
+
+
+

",html +"Why do these divs keep displaying on top of each other?

I am trying to make a navigation bar with dropdowns when you hover. I got this from w3schools.com, but I wanted to have multiple drop downs next to each other. I have 2 of them next to each other, but when I hover over either of them, it shows the same dropdown menu. How do I fix this? Sorry if this seems obvious, I'm a beginner.

+

+
+
.navbar {
+  overflow: hidden;
+  background-color: red;
+  width: 620px;
+  box-shadow: 0 2px 2px #FF0000, -2px 1px 0 #D30000, -4px 2px 0 #FE471E, -8px 3px 0 #FEF100, -12px 4px 0 #00A500, -16px 5px 0 #0080F6, -20px 6px 0 #20007D;
+}
+
+.navbar a {
+  float: left;
+  font-size: 16px;
+  color: white;
+  text-align: center;
+  padding: 14px 16px;
+  text-decoration: none;
+}
+
+.dropdown {
+  float: left;
+  text-align: center;
+  overflow: hidden;
+}
+
+.dropdown .dropbtn {
+  font-size: 16px;
+  border: none;
+  color: white;
+  padding: 14px 16px;
+  background-color: inherit;
+  font-family: inherit;
+  margin: 0;
+}
+
+.navbar a:hover,
+.dropdown:hover .dropbtn {
+  background-color: red;
+}
+
+.dropdown-content {
+  display: none;
+  position: absolute;
+  background-color: #f9f9f9;
+  min-width: 80px;
+  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
+  z-index: 10;
+}
+
+.dropdown-content a {
+  float: none;
+  color: black;
+  padding: 12px 16px;
+  text-decoration: none;
+  display: block;
+  text-align: center;
+}
+
+.dropdown-content a:hover {
+  background-color: #ddd;
+}
+
+.dropdown:hover .dropdown-content {
+  display: block;
+}
+
<div class=""navbar"">
+  <a href=""#home"">Home</a>
+  <a href=""#news"">Blog</a>
+  <div class=""dropdown"">
+    <button class=""dropbtn"">Projects ▼
+    </button>
+    <div class=""dropdown-content"">
+      <a href=""#"">Link 1</a>
+      <a href=""#"">Link 2</a>
+      <a href=""#"">Link 3</a>
+    </div>
+    <div class=""dropdown"">
+      <button class=""dropbtn"">Archives ▼
+    </button>
+      <div class=""dropdown-content"">
+        <a href=""#"">Hello</a>
+        <a href=""#"">hi</a>
+        <a href=""#"">how are you</a>
+      </div>
+    </div>
+  </div>
+  <a href=""#guestbook"">Guestbook</a>
+  <a href=""#about"">About Me</a>
+
+</div>
+
+
+

","

You had a simple error with your pairing your div tags.

+

Fix your code like so and it should work:

+

+
+
 overflow: hidden;
+  background-color: red;
+  width: 620px;
+    box-shadow: 0 2px 2px #FF0000, 
+      -2px 1px 0 #D30000, 
+      -4px 2px 0 #FE471E,
+      -8px 3px 0 #FEF100,
+      -12px 4px 0 #00A500,
+      -16px 5px 0 #0080F6,
+      -20px 6px 0 #20007D;
+}
+
+.navbar a {
+  float: left;
+  font-size: 16px;
+  color: white;
+  text-align: center;
+  padding: 14px 16px;
+  text-decoration: none;
+}
+
+.dropdown {
+  float: left;
+  text-align: center;
+  overflow: hidden;
+}
+
+.dropdown .dropbtn {
+  font-size: 16px;  
+  border: none;
+  color: white;
+  padding: 14px 16px;
+  background-color: inherit;
+  font-family: inherit;
+  margin: 0;
+}
+
+.navbar a:hover, .dropdown:hover .dropbtn {
+  background-color: red;
+}
+
+.dropdown-content {
+  display: none;
+  position: absolute;
+  background-color: #f9f9f9;
+  min-width: 80px;
+  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
+  z-index: 10;
+}
+
+.dropdown-content a {
+  float: none;
+  color: black;
+  padding: 12px 16px;
+  text-decoration: none;
+  display: block;
+  text-align: center;
+}
+
+.dropdown-content a:hover {
+  background-color: #ddd;
+}
+
+.dropdown:hover .dropdown-content {
+  display: block;
+}
+
<a href=""#home"">Home</a>
+<a href=""#news"">Blog</a>
+
+<div class=""dropdown"">
+  <button class=""dropbtn"">Projects ▼</button>
+  <div class=""dropdown-content"">
+    <a href=""#"">Link 1</a>
+    <a href=""#"">Link 2</a>
+    <a href=""#"">Link 3</a>
+  </div>
+</div>
+
+<div class=""dropdown"">
+    <button class=""dropbtn"">Archives ▼</button>
+    <div class=""dropdown-content"">
+      <a href=""#"">Hello</a>
+      <a href=""#"">hi</a>
+      <a href=""#"">how are you</a>
+    </div>
+</div> 
+
+
+<a href=""#guestbook"">Guestbook</a>
+<a href=""#about"">About Me</a>
+
+
+

",html +"How do I fix the container div that ruined the layout?

After I was done working on side bar I wanted to head to the content page to the right so I added a container div that I wanted to set to flex So that I make the two boxes to start styling, but right after adding it, the footer's position is ruined and the side bar isn't taking as much space as it should.

+

Here's a picture:

+

+

+
+
.side-bar {
+  font-family: 'Montserrat', sans-serif;
+  font-size: large;
+  font-weight: bold;
+  display: flex;
+  justify-content: left;
+  background-color: rgb(235, 235, 235);
+  width: 20%;
+  height: 80%;
+  flex-direction: column;
+}
+
+.side-bar ul {
+  display: flex;
+  flex-direction: column;
+  margin-left: 0%;
+  list-style: none;
+  margin-top: 5%;
+}
+
+.side-bar ul li {
+  margin-bottom: 10px;
+  display: inline;
+  cursor: pointer;
+}
+
+.togglable:hover {
+  border-radius: 7px;
+  background-color: rgb(216, 216, 216);
+}
+
+.togglable:active {
+  background-color: rgb(221, 221, 221);
+}
+
+.side-bar ul a {
+  color: black;
+  text-decoration: none;
+}
+
+.side-bar h2 {
+  font-family: 'Josefin Sans', sans-serif;
+  margin-bottom: 20px;
+}
+
+.container {
+  display: flex;
+}
+
+.task-container {
+  background-color: red;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>ToDoList</title>
+  <link rel=""stylesheet"" href=""style.css"">
+</head>
+
+<body>
+  <div class=""nav-bar"">
+    <img src=""logo.png"" alt=""logo"">
+    <nav>
+      <ul>
+        <li><a href=""#"">Services</a></li>
+        <li><a href=""#"">Projects</a></li>
+        <li><a href=""#"">About</a></li>
+      </ul>
+    </nav>
+    <a class=""cta"" href=""#""><button>Contact</button></a>
+  </div>
+  <div class=""container"">
+    <div class=""side-bar"">
+      <ul>
+        <li class=""togglable""><img src=""gym.png"" alt=""gym"" id=""gym""><a href=""#"">Gym</a></li>
+        <li class=""togglable""><img src=""today.png"" alt=""calendar"" id=""today""> <a href=""#"">Today</a></li>
+        <li class=""togglable""><img src=""week.png"" alt=""calendar"" id=""week""><a href=""#"">This Week</a></li>
+        <li class=""togglable""><img src=""month.png"" alt=""calendar"" id=""month""> <a href=""#"">This Month</a></li>
+        <h2>Projects : </h2>
+        <li id=""addPr"" class=""togglable""><a href=""#""><span id=""plus-sgn"">+</span> Add Project</a></li>
+        <!-- <li class=""togglable""><img src=""checklist.png"" alt=""checlist"" id=""list""> <a href=""#"">Testing</a></li> -->
+      </ul>
+    </div>
+    <div class=""task-container"">
+      <p>Some Text To test the box</p>
+    </div>
+  </div>
+  <div class=""footer"">
+    <p id=""copyright"">Copyright © 2021 FaroukHamadi</p>
+  </div>
+  <script src=""main.js""></script>
+</body>
+
+</html>
+
+
+

","

Add width attribute to task-contianer and add your fotter class attribute on your CSS file.

+
.task-container {
+    background-color: red;
+    width: 100%;
+    
+}
+
+.footer{
+    position: absolute;
+    bottom: 0px;
+    width: auto;
+}
+
",html +"Hover is still active after action on the phone

EDIT: Anyone please?

+

I got this from somewhere but when I tap on it on the phone (on PC it's ok) it stays with hover attributes = no BG and black colour to the next website refresh:

+

HTML

+
<a id="back2Top" title="Top" href="#">&#10148;</a>
+
+

CSS

+
#back2Top {
+    width: 40px;
+    line-height: 40px;
+    overflow: hidden;
+    z-index: 999;
+    display: none;
+    cursor: pointer;
+    transition: background-color 0.2s linear;
+    -moz-transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    -o-transform: rotate(270deg);
+    -ms-transform: rotate(270deg);
+    transform: rotate(270deg);
+    position: fixed;
+    bottom: 39px;
+    right: 0;
+    background-color: #8db500;
+    color: #fff;
+    text-align: center;
+    font-size: 30px;
+    text-decoration: none;
+}
+#back2Top:hover {
+    background-color: transparent;
+    color: #000;
+}
+@media only screen and (max-width: 767px) {
+#back2Top {
+    bottom: 0px;
+}}
+
+

And JS

+
$(window).scroll(function() {
+    var height = $(window).scrollTop();
+    if (height > 100) {
+        $('#back2Top').fadeIn();
+        $('.open').css('background', 'rgba(141, 181, 0, 0.5)'); //these 3 are for something different
+        $('.closed').css('background', 'rgba(201, 0, 10, 0.5)');
+        $('.warn').css('background', 'rgba(255, 113, 0, 0.5)');
+
+    } else {
+        $('#back2Top').fadeOut();
+        $('.open').css('background', 'rgba(141, 181, 0, 1)'); //these 3 are for something different
+        $('.closed').css('background', 'rgba(201, 0, 10, 1)');
+        $('.warn').css('background', 'rgba(255, 113, 0, 1)');
+    }
+});
+$(document).ready(function() {
+
+    $("#back2Top").click(function(event) {
+        event.preventDefault();
+        $("html, body").animate({ scrollTop: 0 }, "slow");
+        return false;
+    });
+
+});
+
+

What is wrong there? Or what I did wrong? +×I don't know what to add more here, it won't let me post it because of mostly code.× +Thank you.

","

If I'm right then you're trying to make an icon to go to the Top. +Here, I'm sharing a simple code for that, you'll understand easily.

+

+
+
window.onscroll = function () { myFunction() };
+
+var goToTop = document.getElementById(""goToTop"");
+
+function myFunction() {
+  if (window.pageYOffset >= 30) {
+    goToTop.classList.add(""sticky"")
+  } else {
+    goToTop.classList.remove(""sticky"");
+  }
+}
+
body{
+height:1500px;
+width:100vw;
+}
+.goToTop{
+    height:69px;
+    width:69px;
+    border-radius: 50%;
+    background:white;
+    position:fixed;
+    right:30px;
+    bottom:20px;
+    z-index:1000;
+    display:none;
+}
+.goToTop img{
+    width:70px;
+}
+.goToTop.sticky{
+    display: inline-block;
+}
+
<body id=""body"">
+  <div class=""goToTop"" id=""goToTop"">
+      <a href=""#body"">
+        <img src=""https://img.icons8.com/ios/50/000000/collapse-arrow--v1.png""/>
+      </a>
+  </div>
+</body>
+
+
+

+

OR
+If I'm wrong +Or +You want me to fix your code only, then let me know in the comments.

",html +"Plotly Dash in Kubernetes pod cannot get assets for IFrame

The idea is to display .html file in html.iFrame in Plotly Dash hosted in Kubernetes.

+

The code works as intended in local however it's met with 404 ( in K8s log ) when trying to fetch the file in the pod (/project/assets/). I have went into the pod to check and the files are there. I have checked for file permissions and they are the same as local (-rw-r--r--), parents folders have the same permissions too. I have some other files in /project/cache folders that can be successfully displayed through dcc.Graph indicating that io is fine.

+
100.64.109.71 - - [04/Feb/2022 02:41:58] "POST /_dash-update-component HTTP/1.1" 200 -
+100.64.109.71 - - [04/Feb/2022 02:41:58] "GET /assets/country/datetime/filename.html HTTP/1.1" 404 -
+
+

Is there something unique about html.iFrame in Kubernetes that I have missed out? My apologies if the question is too terse but I am not even sure where or how to start debugging.

+

Update 1: Found useful reference ( https://github.com/plotly/dash/issues/489 )

","

Solved using srcDoc instead of src.

+
with open(f"assets/{filename}", "r") as f:
+    html_content =  f.read()
+
+content = html.Iframe(srcDoc=f"{html_content}", style={"height": "1067px", "width": "98%"})
+
",html +"CSS pseudo element positioning - partial border above header

I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element. It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

+

I have tried absolute positioning, different displays but nothing works.

+

https://codepen.io/lol4000/pen/dyZvmGK

+
 <img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">            <h2 class="sub-title">Test English subtitle</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p> <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis. <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
+
+h2.sub-title {font-size:28px;display: block;}
+h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}
+
+
+.wp-post-image {
+    float: left;
+    margin: 0 15px 10px 0;}
+
","

Update: Ok, so we use display: inline-block; in heading to properly define the role of the box in the page, which is inline. Since there is no wrapper element in our content, we do not need to do anything else (except the relative and absolute positioning). Also, I used the float: left; on the img since we want img to be on the far left and the rest of the content overflow in its right.

+

+
+
h2.sub-title {
+  font-size: 28px;
+  position: relative;
+  display: inline-block;
+}
+
+h2.sub-title::before {
+  position: absolute;
+  height: 8px;
+  width: 130px;
+  left: 0;
+  top: -10px;
+  background: #441A6D;
+  display: block;
+  content: """";
+}
+
+img {
+  margin: 0 15px 10px 0;
+  max-width: 100%;
+  height: auto;
+  float: left;
+}
+
<div>
+  <img src=""https://via.placeholder.com/200x200"">
+  <h2 class=""sub-title"">Test English subtitle</h2>
+  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p>
+  <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
+  <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p>
+  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
+    enim.
+  </p>
+  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
+  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
+    enim.
+  </p>
+  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
+</div>
+
+
+

",html +"How can I detect the scroll width and differentiate between the mobile and the desktop versions?

Because of diferent sizes of scrollbar I'm getting a problem while using a fixed component in both mobile and desktop:

+

+

+

While the desktop version get correctly aligned with the components below, the mobile version doesn't. +If I fix the width for the mobile the desktop will go over the component limit and it just doesn't work.

+

My css for it is as follow, the commented width is the one that works for the mobile. +Anyone have any ideas?

+
.fixed-header {
+  position: fixed;
+  top: 56px;
+  left: 14px;
+  width: calc(100vw - 45px); //calc(100vw - 30px);
+  z-index: 2;
+
+  @include md {
+    position: relative;
+  }
+}
+
","

I managed to do it by testing the scroll width in the ngOnInit as suggested in this answer (I edited a little for convenience), to test if it was mobile or not:

+
testIsMobile() {
+    var scrollbox = document.createElement('div');
+    scrollbox.style.overflow = 'scroll';
+    document.body.appendChild(scrollbox);
+
+    var scrollWidth = scrollbox.offsetWidth - scrollbox.clientWidth;
+
+    document.body.removeChild(scrollbox);
+
+    this.isMobile = scrollWidth == 0
+}
+
+

Then I added the correct class through [ngClass]="fixedHeaderClass"

+
if (this.isMobile)
+  this.fixedHeaderClass = "fixed-header-mobile";
+else
+  this.fixedHeaderClass = "fixed-header";
+
",html +"How can i do onclick event with html,css,js

I want the css codes of the blog1popup class to change when the image is clicked. +I know how to do this with hover, but i don't know how to make this action happen by clicking.
+
+The element I want to use as this button;

+
<div class="row">
+<div class="col-lg-4 col-md-6 sm-mb-35px">
+   <div class="blog-item">
+      <div class="img">
+         <img src="assets/img/blog-grid-1.jpg" alt=""></a>
+         <a href="" class="date"> <span class="day">14</span> <span class="month">April</span></a>
+      </div>
+      <a href="" class="title padding-30px"  style="margin-top: -1rem;">Fransa Geneline Islak Mendil İhracı</a> 
+      <p style="padding-left: 30px; padding-bottom: 20px; margin-top: -25px; line-height: 20px;">Tüm dünya ülkelerine yardımseverliği gösteren ülkemize..</p>
+   </div>
+</div>
+
+
+This is the element I want to have changes in the css codes. +
+

<div class="blog1popup"></div>

+

Example on hover technique; +

+
.blog-item:hover > .blog1popup{
+opacity: 100%;
+}
+
","

You can add click event on blog-item class, then you can add classes to any element or change any css property using jquery methods.

+

Eg.

+
$(".blog-item").on("click", function (e) {
+  $(".blog1popup").css("opacity", "100%");
+  $(".blog1popup").addClass("any-class");
+});
+
",html +"Parsing an updating html using jsoup

we have a problem (we are a group).

+

We have to use jsoup in java for an university project. We can parse Htmls with it. But the problem is that we have to parse an html which updates when you click on a button (https://www.bundestag.de/services/opendata).

+

First Slide

+

Second Slide

+

We want to access all xmls from "Wahlperiode 20". But when you click on the slide buttons the html code updates but the html url stays the same. But you have never access to all xmls in the html because the html is updating over the slide button.

+

Another idea was to find out how the urls of the xmls we want to access are built so that we dont have to deal with the slide buttons and only access the xml urls. But they are all built different.

+

So we are all desperate how to go on. I hope y'all can help us :)

","

It's rather ironic that you are attempting to hack1 out some data from an opendata website. There is surely an API!!

+

The problem is that websites aren't static resources; they have javascript, and that javascript can fetch more data in response to e.g. the user clicking a 'next page' button.

+

What you're doing is called 'scraping': Using automated tools to attempt to query for data via a communication channel (namely: This website) which is definitely not meant for that. This website is not meant to be read with software. It's meant to be read with eyeballs. If someone decides to change the design of this page and you did have a working scraper, it would then fail after the design update, for example.

+

You have, in broad strokes, 3 options:

+

Abort this plan, this is crazy

+

This data is surely open, and open data tends to come with APIs; things meant to be queried by software and not by eyeballs. Go look for it, and call the german government, I'm sure they'll help you out! If they've really embraced the REST principles of design, then send an accept header that including e.g. application/json and application/xml and does not include text/html and see if the site just responds with the data in JSON or XML format.

+

I strongly advise you fully exhaust these options before moving on to your next options, as the next options are really bad: Lots of work and the code will be extremely fragile (any updates on the site by the bundestag website folks will break it).

+

Use your browser's network inspection tools

+

In just about every browser there's 'dev tools'. For example, in Vivaldi, it's under the "Tools" menu and is called "Developer tools". You can also usually right click anywhere on a web page and there will be an option for 'Inspect', 'Inspector', or 'Development Tools'. Open that now, and find the 'network' tab. When you (re)load this page, you'll see all the resources its loading in (so, images, the HTML itself, CSS, the works). Look through it, find the interesting stuff. In this specific case, the loading of wahlperioden.json is of particular interest.

+

Let's try this out:

+
curl 'https://www.bundestag.de/static/appdata/filter/wahlperioden.json'
+
+[{"value":"20","label":"WP 20: seit 2021"},{"value":"19","label":"WP 19: 2017 - 2021"},(rest omitted - there are a lot of these)]
+
+

That sounds useful, and as its JSON you can just read this stuff with a json parser. No need to use JSoup (JSoup is great as a library, but it's a library that you can use when all other options have failed, and any code written with JSoup is fragile and complicated simply because scraping sites is fragile and complicated).

+

Then, click on the buttons that 'load new data' and check if network traffic ensues. And so it does, when you do so, you notice a call going out. And so it is! I'm seeing this URL being loaded:

+
https://www.bundestag.de/ajax/filterlist/de/services/opendata/866354-866354?limit=10&noFilterSet=true&offset=10
+
+

The format is rather obvious. offset=10 means: Start from the 10th element (as I just clicked 'next page') and limit=10 means: NO more than 10 pages.

+

This html is also incredibly basic which is great news, as that makes it easy to scrape. Just write a for loop that keeps calling this URL, modifying the offset=10 part (first loop: no offset. Second, offset=10, third: offset=20. Keep going until the HTML you get back is blank, then you got it all).

+

For future reference: Browser emulation

+

Javascript can also generate entire HTML on its own; not something jsoup can ever do for you: The only way to obtain such HTML is to actually let the javascript do its work, which means you need an entire browser. Tools like selenium will start a real browser but let you use JSoup-like constructs to retrieve information from the page (instead of what browsers usually do, which is to transmit the rendered data to your eyeballs). This tends to always work, but is incredibly complicated and quite slow (you're running an entire browser and really rendering the site, even if you can't see it - that's happening under the hood!).

+

Selenium isn't meant as a scraping tool; it's meant as a front-end testing tool. But you can use it to scrape stuff, and will have to if its generated HTML. Fortunately, you're lucky here.

+

Option 1 is vastly superior to option 2, and option 2 is vastly superior to option 3, at least for this case. Good luck!

+

[1] I'm using the definition of: Using a tool or site to accomplish something it was obviously not designed for. The sense of 'I bought half an ikea cupboard and half of an ikea bookshelf that are completely unrelated, and put them together anyway, look at how awesome this thingie is' - that sense of 'hack'. Not the sense of 'illegal'.

",html +"How to center the content of (centered) pure css columns

The snippet presents a series of columns containing a single letter. I'd like to have the center of the glyph in the center of each, but as you can see, they not quite centered -- appearing just off to the right. (I suspect by half the glyph width, but I'm not sure).

+

I've tried justify-content: center, margin: auto to no avail. Inspecting the pure, I don't see anything that should prevent what I'm aiming for. Can you help me fix it?

+

+
+
.centered-cols {
+  justify-content: center;
+}
+
+.key {
+  text-align: center;
+  min-width: 1.9em;
+  margin: 0.2em;
+  border-radius: 0.4em;
+  background-color: lightgrey;
+}
+
<link href=""https://unpkg.com/purecss@2.0.6/build/pure-min.css"" rel=""stylesheet"" />
+
+<div class=""pure-g centered-cols"">
+  <div id=""q"" class=""pure-u-1-10 key""><p>A</p></div>
+  <div id=""w"" class=""pure-u-1-10 key""><p>B</p></div>
+  <div id=""e"" class=""pure-u-1-10 key""><p>C</p></div>
+  <div id=""r"" class=""pure-u-1-10 key""><p>D</p></div>
+  <div id=""t"" class=""pure-u-1-10 key""><p>E</p></div>
+  <div id=""y"" class=""pure-u-1-10 key""><p>F</p></div>
+  <div id=""u"" class=""pure-u-1-10 key""><p>G</p></div>
+  <div id=""i"" class=""pure-u-1-10 key""><p>H</p></div>
+  <div id=""o"" class=""pure-u-1-10 key""><p>I</p></div>
+  <div id=""p"" class=""pure-u-1-10 key""><p>J</p></div>
+</div>
+
+
+

","

Add letter-spacing: 0 in your .key css class:

+

+
+
.key {
+  letter-spacing: 0;
+  text-align: center;
+  min-width: 1.9em;
+  margin: 0.2em;
+  border-radius: 0.4em;
+  background-color: lightgrey;
+}
+
<link href=""https://unpkg.com/purecss@2.0.6/build/pure-min.css"" rel=""stylesheet"" />
+
+<div class=""pure-g centered-cols"">
+  <div id=""q"" class=""pure-u-1-10 key"">
+    <p>A</p>
+  </div>
+  <div id=""w"" class=""pure-u-1-10 key"">
+    <p>B</p>
+  </div>
+  <div id=""e"" class=""pure-u-1-10 key"">
+    <p>C</p>
+  </div>
+  <div id=""r"" class=""pure-u-1-10 key"">
+    <p>D</p>
+  </div>
+  <div id=""t"" class=""pure-u-1-10 key"">
+    <p>E</p>
+  </div>
+  <div id=""y"" class=""pure-u-1-10 key"">
+    <p>F</p>
+  </div>
+  <div id=""u"" class=""pure-u-1-10 key"">
+    <p>G</p>
+  </div>
+  <div id=""i"" class=""pure-u-1-10 key"">
+    <p>H</p>
+  </div>
+  <div id=""o"" class=""pure-u-1-10 key"">
+    <p>I</p>
+  </div>
+  <div id=""p"" class=""pure-u-1-10 key"">
+    <p>J</p>
+  </div>
+</div>
+
+
+

",html +"Is there any benefit to writing aria-required=""false""?

Is there any benefit to writing aria-required="false" or is it best only to add aria-required="true" as needed and otherwise leave it off?

+

I have struggled to find any clarification on this in the WCAG docs I have read.

","

For simplicity, I always leave off the attribute rather than setting it to false even if false is the default value. Most(*) of the time you're ok either way. From a javascript perspective, sometimes it's easier to use a conditional (ternary) operator rather than remove the attribute.

+
disabled = obj.getAttribute('aria-disabled');
+obj.setAttribute('aria-disabled', disabled ? "false" : "true");
+
+/* versus */
+
+disabled = obj.getAttribute('aria-disabled');
+if (disabled) 
+  obj.removeAttribute('aria-disabled')
+else 
+  obj.setAttribute('aria-disabled', "true");
+
+

Sometimes there's a note in the doc to not do this, as with aria-hidden

+
+

Note
+At the time of this writing, aria-hidden="false" is known to work inconsistently in browsers. As future implementations improve, use caution and test thoroughly before relying on this approach.

+
+

(*) There are a few aria- attributes where you do have to set the value specifically to true or false because setting it to false is not the same as not having the attribute, such as aria-expanded, aria-pressed, aria-checked, aria-selected. For example, not having aria-expanded doesn't have any meaning but having aria-expanded="false" means you have an expandable/collapsable section that is currently collapsed. Not having aria-checked doesn't have any meaning but having aria-checked="false" means you have a checkbox that is unchecked.

+

With aria-required, since it's value will typically not change once it's set (unlike the four attributes just mentioned which do typically change based on user interaction), I keep the code simple and just don't have the attribute.

",html +"How to attach a link in the setBody of gomail?

In this code, I am trying to make the value[2] as an href link so that if somebody clicks on the token, it will be redirected to some page but I am not sure how to do it. I searched for the solution but didn't find it.

+
func SendEmail(value [3]string) {
+    mail := gomail.NewMessage()
+    myEmail := middleware.LoadEnvVariable("EMAIL")
+    myPassword := middleware.LoadEnvVariable("APP_PASSWORD")
+    mail.SetHeader("From", myEmail)
+    mail.SetHeader("To", value[0])
+    mail.SetHeader("Reply-To", myEmail)
+    mail.SetHeader("Subject", value[1])
+    mail.SetBody("text/html", "<href='localhost:4000'>"+value[2]+"</href>")
+
+    a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, myPassword)
+    if err := a.DialAndSend(mail); err != nil {
+        log.Fatal(err)
+    }
+}
+
","

Following on the gomail docs, try to use the <a> tag:

+
mail.SetBody("text/html", "<a href=\"" + value[2] + "\">some text</a>")
+
",html +"ctx.fillText isn't doing anything

I'm making a website where I want to have text written in the middle of a rectangle. The text will be a number from 1 to 100. For some reason ctx.fillText() isn't doing anything. My canvas isn't small. It's as big as the image that's being drawn on it.

+

Code:

+
const ctx = editCanvas.getContext("2d");
+
+const backgroundImage = new Image();
+
+backgroundImage.src = "some random path";
+
+backgroundImage.onload = () => {
+    editCanvas.width = backgroundImage.width;
+    editCanvas.height = backgroundImage.height;
+
+    ctx.drawImage(backgroundImage, 0, 0);
+};
+
+function drawSelectionRect(
+    text,
+    { x, y, width, height },
+    { strokeWidth, lineDash, strokeColor },
+    fillColor
+) {
+    ctx.lineWidth = strokeWidth;
+    ctx.setLineDash(lineDash);
+    ctx.strokeStyle = strokeColor;
+
+    ctx.strokeRect(x, y, width, height);
+
+    ctx.fillStyle = fillColor;
+
+    ctx.fillRect(x, y, width, height);
+
+    const { width: textWidth, height: textHeight } = ctx.measureText(text);
+
+    ctx.fillStyle = "#000";
+    ctx.font = "16px sans-serif";
+
+    ctx.fillText(
+        text,
+        x + width / 2 - textWidth / 2,
+        y + height / 2 - textHeight / 2,
+        width
+    );
+}
+
","

You might want to double check the return of measureText:
+https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText#return_value
+there is nothing height related there...

+

If we remove those textWidth & textHeight your drawSelectionRect function works.

+

I believe what you are trying to accomplish is to align the text, perhaps with these, you can do it:

+ +

Here is your code with those +

+
+
const editCanvas = document.getElementById('c');
+const ctx = editCanvas.getContext(""2d"");
+
+function drawSelectionRect(
+    text,
+    { x, y, width, height },
+    { strokeWidth, lineDash, strokeColor },
+    fillColor
+) {
+    ctx.lineWidth = strokeWidth;
+    ctx.setLineDash(lineDash);
+    ctx.strokeStyle = strokeColor;
+
+    ctx.strokeRect(x, y, width, height);
+    ctx.fillStyle = fillColor;
+    ctx.fillRect(x, y, width, height);
+
+    console.log(ctx.measureText(text))
+    
+    ctx.fillStyle = ""#000"";
+    ctx.font = ""16px sans-serif"";
+    ctx.textBaseline = ""middle"";
+    ctx.textAlign = ""center"";
+    ctx.fillText(
+        text,
+        x + width / 2,
+        y + height / 2,
+        width
+    );
+}
+
+drawSelectionRect(
+  ""ooo"", 
+  {x:2, y:2, width:40, height:40}, 
+  {strokeWidth:3, lineDash:[0], strokeColor: ""black""}, 
+  ""red""
+)
+
<canvas id=""c""></canvas>
+
+
+

+

Remember console.log( is your friend, when you are not sure what is going on, output the variables you are using and see what is not the way you plan it

",html +"text box that goes to website when answer is correct

I need the user to type a word and if its the right keyword, I need it to change pages.

+

my code

+
<form action="/yay.html">
+    <label>what's 1+1</label><br>
+    <input type="text"><br>
+    <input type="submit" value="Submit">
+</form>
+
+

for example I want something a bit like this.

+
<script>
+function checkstuff() {
+if text = "hello world" 
+}
+</script>
+//so a function checks if the text is equal to "hello world"
+
+<form action="/yay.html">
+    <input type="text">
+    <input type="submit" value="Submit" onclick="checkstuff()">
+    //submit input runs function
+</form>
+
","

In the solution below, the user input is evaluated to enable/disable the disabled attribute of the submit button.

+

+
+
const submit = document.getElementById('submit');
+let answer = document.getElementById('answer');
+const target = 2;
+
+function log(value, mode) {
+  console.clear();
+  
+  if(mode)
+    console.log(`Information: ${value}`);
+  else
+    console.log(`Input: ${value}`);
+}
+
+answer.addEventListener('input', function(event) {
+  log(this.value, true);
+  
+  if(parseInt(this.value) == target) {
+    submit.disabled = false;
+  }
+  else {
+    submit.disabled = true; 
+  }
+});
+
+submit.addEventListener('click', function(event) {
+  log(""Button fired."", false);
+});
+
<form action=""/yay.html"">
+    <label>what's 1+1</label><br>
+    <input id=""answer"" type=""text""><br>
+    <input id=""submit"" type=""submit"" value=""Submit"" disabled>
+</form>
+
+
+

",html +"How can I get text from only

and

tags when finding element by class with selenium and python?

I am trying to get the text only from the h2 and the first p tag. I've been using class name to find the div and the output gives me all of the text in the div (obviously).

+

Here is the HTML:

+
<div class="horoscope-content">
+<h2> Today's Libra Horoscope for January 27, 2022 <span class="today-badge">TODAY</span></h2>
+<p>Go with the flow, Libra. If you find that a situation isn't unfolding the way you'd like it to, take it as a sign to back off. Swimming upstream is hard work, so use your energy more efficiently by exploring different options. When you step back from a stressful situation, circumstances could turn around. Lighten up by considering other possibilities or talking it through with a helpful friend.</p>            
+<p>What's in the stars for you tomorrow? <a href="/horoscopes/daily/libra/friday">Read it now</a>.</p>
+<div class="dropdown-inline">Read the <b>daily horoscope</b> for another zodiac sign:<div id="dropdown_below_horoscope_dropdown" class="dropdown">
+
+

Here is the code I'm using:

+
libra_content = driver.find_elements(By.CLASS_NAME, 'horoscope-content')
+
+

I assume the answer is to use xpath but I can't figure out how to include both tags. Do I need to use two separate lines of code to do it or can I combine both into one?

","

I solved it using css selectors, but didn't combine them into one. Another commenter's answer using xpath and class name combining the two is a possible solution.

+
libra_h2 = driver.find_element(By.CSS_SELECTOR, 'div.horoscope-content > h2')
+libra_p = driver.find_element(By.CSS_SELECTOR, 'div.horoscope-content > p')
+
",html +"Most proper HTML structure to use for parenthetical asides inside a quotation

Suppose I have to translate the following blockquote to an HTML markup:

+
+

The quick brown fox jumped (some kind of parenthetical aside) over the head of the lazy dog.

+
+

What is the best way to approach structuring the content? Do I just simply wrap the parenthetical aside above in a <span> tag and style it differently like this?

+
<blockquote>
+  <p>The quick brown fox jumped <span class="p-aside">(some kind of parenthetical aside)</span> over the head of the lazy dog.</p>
+</blockquote>
+
+

Or maybe there's something else I can use for this specific case? Thanks!

","

It depends on how you're using the parentheses, but I don't think any special semantic markup is needed here. The parentheses themselves serve to communicate the separateness and change in voice of the aside. If you need to style it differently, a non-semantic <span> would be the way to go.

+

+
+
blockquote {
+  font-style: italic;
+}
+.parenthetical-aside {
+  font-style: normal;
+  font-weight: bolder;
+}
+
<blockquote>
+  <p>She’s been dating Nathan <span class=""parenthetical-aside"">(the shy twin)</span> for about six months now.</p>
+</blockquote>
+
+
+

+

However, an argument could be made that an <i> (idiomatic text element) could also be appropriate. These elements are used to communicate "spans of text representing a different quality or mode of text, such as an alternative voice or mood" (among other uses). Just remember than many browsers will style this element in italics by default, so you may need to override that.

+

+
+
blockquote {
+  font-style: italic;
+}
+.parenthetical-aside {
+  font-style: normal;
+  font-weight: bolder;
+}
+
<blockquote>
+  <p>She’s been dating Nathan <i class=""parenthetical-aside"">(the shy twin)</i> for about six months now.</p>
+</blockquote>
+
+
+

",html +"How to make the article above cover the article below when it gets mor height?

I need some help when hovering over article , i want to cover the article below it instead of pushing the whole next row, i tried to give it some padding and then heigh but i'm getting the same result. I tried also with Jquery to use .hover() function and it gave the same result.

+

The whole container has a display flex , and every article has a width and height , and when hovering over the article it gets more height. The article without hovering has a 480px and then when hovering 500px

+

+
+
.container {
+  width: 1400px;
+  margin: 0 auto;
+  padding: 20px;
+}
+.articles_container {
+  border-radius: 4px;
+  max-width: calc(100vw - 10px);
+  margin-bottom: 1px;
+  display: flex;
+  flex-wrap: wrap;
+}
+article {
+  width: 24%;
+  border: 1px solid red;
+  margin-left: -1px;
+  margin-top: -1px;
+  
+  height: 480px;
+}
+img {
+  width: auto;
+  max-width: 100%;
+  display: block;
+  margin: 0 auto;
+  height: auto;
+}
+.bottom {
+  display: none;
+}
+
+article:hover {
+  height: 500px;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+  <head>
+    <meta charset=""UTF-8"" />
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
+    <meta http-equiv=""X-UA-Compatible"" content=""ie=edge"" />
+    <link rel=""stylesheet"" href=""style.css"" />
+    <title>Static Template</title>
+  </head>
+  <body>
+    <div class=""container"">
+      <div class=""articles_container"">
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+          <div class=""bottom"">
+            <p>25</p>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+          <div class=""bottom"">
+            <p>25</p>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+
+          <div class=""bottom"">
+            <p>25</p>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+          <div class=""bottom"">
+            <p>25</p>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+        </article>
+        <!--        -->
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+        </article>
+        <!--        -->
+      </div>
+    </div>
+   
+  </body>
+</html>
+
+
+

+

","

Edit here is an example using javascript

+

+
+
const articleItem = document.querySelector('.article_item')
+for(let i = 0; i<10;i++){
+  articleItem.insertAdjacentHTML(""afterend"", articleItem.outerHTML);
+}
+const articles = document.querySelectorAll('article')
+
+articles.forEach(a=>{
+  a.addEventListener('mouseover',handleHover)
+  a.addEventListener('mouseout',handleHoverEnd)
+})
+
+function handleHover(e){
+  const width = e.currentTarget.clientWidth 
+  const top = e.currentTarget.offsetTop + 1 //>>adjust for margins set in css
+  const left = e.currentTarget.offsetLeft + 1 //>>adjust for margins set in css
+  e.currentTarget.classList.add('active')
+  e.currentTarget.style.cssText = `top: ${top}px; left: ${left}px; width: ${width}px`
+}
+function handleHoverEnd(e){
+  e.currentTarget.classList.remove('active')
+}
+
.container {
+  width: 1400px;
+  margin: 0 auto;
+  padding: 20px;
+}
+.articles_container {
+  border-radius: 4px;
+  max-width: calc(100vw - 10px);
+  margin-bottom: 1px;
+  position: relative;
+  display: flex;
+  flex-wrap: wrap;
+  align-items: flex-start;
+}
+.article_item{
+width: 24%;
+}
+article {
+  display: flex;
+  flex-direction: column;
+  border: 1px solid red;
+  margin-left: -1px;
+  margin-top: -1px;
+  height: 180px;
+  background-color: white;
+  overflow: hidden;
+}
+img {
+  max-width: 100%;
+}
+.bottom {
+  display: none;
+  
+}
+
+.active {
+  position: absolute;
+  height: 300px;
+  z-index: 3;
+}
+
<body>
+    <div class=""container"">
+      <div class=""articles_container"">
+        <div class=""article_item"">
+        <article>
+          <img src=""https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg"" alt=""bycekel"" />
+          <div class=""info"">
+            <h4>Titel</h4>
+            <p>
+              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
+              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
+              libero aperiam fugit ex temporibus reprehenderit, recusandae
+              necessitatibus quia, dignissimos accusamus asperiores!
+            </p>
+            <button>Click Me</button>
+          </div>
+          <div class=""bottom"">
+            <p>25</p>
+          </div>
+        </article>
+        </div>
+      </div>
+    </div>
+   
+  </body>
+
+
+

",html +"How can I integrate in html pages 2 different CSS styles for 2 diferent images?

Can anyone help me?

+

How can I integrate in html pages 2 different CSS styles for 2 diferent images, both being separated vertically by a space?

+

See the paintings below. They have different sizes, different styles.

+

","

Something like this. You may change the dimensions anytime

+
.img, .firstImage, .secondImage {
+    border: 1px dotted blue;
+    width: 200px;
+}
+
+.firstImage {
+    float:left;
+    border: 1px solid #ddd;
+    border-radius: 4px;
+    padding: 5px;
+    width: 150px;
+}
+
+.secondImage {
+    float:right;
+    border: 2px solid #fff;
+    border-radius: 2px;
+    padding: 3px;
+    width: 120px;
+}
+
",html +"How can I change the margin of the element with a variable in JavaScript?

I am quite a beginner and trying to learn JavaScript. I am trying to improve an example for Popup.

+

I want to adjust the left margin of the popup so I can center the element to the text. +I added the CSS for reference but I am trying to do it in JS.

+

Basically the problem is if I put the code as below it works.

+
popup.style.marginLeft = "165px";
+
+

But if I define it with variable and put it like below, it won't work.

+
popup.style.marginLeft = widthPopup;
+
+

I don't know if I am missing anything. I added the all code below for reference.

+

+
+
    function myFunction() {
+      var popup = document.getElementById(""myPopup"");
+      popup.classList.toggle(""show"");
+
+// what I tried to do for the solution
+//      let widthPopup = document.createTextNode(popup.clientWidth / -2+""px"");
+//      console.log(widthPopup);
+//      popup.style.marginLeft = widthPopup;
+    }
+
* {
+  font-family: ""lato"";
+  font-weight: 300;
+  font-size: 17px;
+}
+
+/* Popup container */
+.popup {
+  position: relative;
+  display: inline-block;
+  cursor: pointer;
+  margin: 15em;
+}
+
+/* The actual popup (appears on top) */
+.popup .popuptext {
+  visibility: hidden;
+  width: 30ch;
+  background-color: #555;
+  color: #fff;
+  text-align: center;
+  border-radius: 6px;
+  padding: 8px 0;
+  position: absolute;
+  z-index: 1;
+  bottom: 125%;
+  left: 50%;
+  padding: 20px;
+}
+
+/* Popup arrow */
+.popup .popuptext::after {
+  content: """";
+  position: absolute;
+  top: 100%;
+  left: 50%;
+  margin-left: -5px;
+  border-width: 5px;
+  border-style: solid;
+  border-color: #555 transparent transparent transparent;
+}
+
+/* Toggle this class when clicking on the popup container (hide and show the popup) */
+.popup .show {
+  visibility: visible;
+  -webkit-animation: fadeIn 1s;
+  animation: fadeIn 1s;
+}
+
+/* Add animation (fade in the popup) */
+@-webkit-keyframes fadeIn {
+  from {
+    opacity: 0;
+  }
+  to {
+    opacity: 1;
+  }
+}
+
+@keyframes fadeIn {
+  from {
+    opacity: 0;
+  }
+  to {
+    opacity: 1;
+  }
+}
+/*# sourceMappingURL=main.css.map */
+
<div class=""popup"" onclick=""myFunction()"">Click me!
+    <span class=""popuptext"" id=""myPopup"">Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, modi magnam tenetur quo labore, nostrum debitis, facere velit nam suscipit error hic? Suscipit ab aspernatur eos rerum, odit quas, voluptatem velit amet quia, nesciunt possimus. Placeat ad suscipit quae ipsum vero voluptatem laboriosam! Labore perspiciatis accusantium reiciendis ex inventore temporibus! Est itaque a adipisci neque mollitia voluptas, tempora praesentium qui? Fuga facilis, ea, aliquam esse nostrum id architecto sit ipsum voluptates vel aspernatur voluptatibus. Molestiae adipisci libero eligendi expedita totam facilis obcaecati officiis voluptatibus magnam quia praesentium exercitationem perspiciatis ipsam impedit suscipit in, corrupti minima enim dolorum vel! Debitis, quaerat.</span>
+</div>
+
+
+

+

Thank you for any help!

","

In your example (see below) you tried to set the margin to be equal to a TextNode, which is not a valid value.

+
// what I tried to do for the solution
+//      let widthPopup = document.createTextNode(popup.clientWidth / -2+"px");
+//      console.log(widthPopup);
+//      popup.style.marginLeft = widthPopup;
+
+

You are looking for something like this.

+
function myFunction() {
+      var popup = document.getElementById("myPopup");
+      popup.classList.toggle("show");
+
+      // let widthPopup = document.createTextNode(popup.clientWidth / -2+"px");
+      let newMargin = popup.clientWidth / -2+"px";
+      console.log(widthPopup);
+      popup.style.marginLeft = newMargin;
+    }
+
",html +"How to prevent overflowing of an element in css?

So I am trying to create a logo and a menu icon in the header but for some reason, they are always overflowing the height of the header which I have strictly specified! Why is that ?

+

And I know I can hide out the overflowing items by using overflow:hidden; property but it is not always a good case.

+

For example, I tried to create a hamburger icon but I could not because of this overflow issue. The menu lines were working as if the entire element is shown but I had to hide it out so that it could fit into the header.

+

Here is the code -

+
    <header>
+  <div class="logo">
+Elvis
+  </div>
+  
+   <div class="menu">
+Hamburger Menu
+  </div>
+  
+</header>
+
+

In CSS -

+
    *{
+  padding:0px;
+  margin:0px;
+}
+
+header{
+  height: 60px;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  border: 2px solid red;
+}
+
+.logo {
+  font-size: 33px;
+  text-decoration: none;
+  padding: 20px 30px;
+  background-color: green;
+  color: white;
+}
+
+.menu {
+  height: 100px;
+  width: 100px;
+  background-color: #bd4439;
+}
+
+

Here is the codepen link - +https://codepen.io/raghav-sharma333/pen/eYeZYGO

+

Here is the image of the issue - +Overflowing content

+

So I just want to know :

+
    +
  1. Why is it happening?
  2. +
+

&

+
    +
  1. How can it be prevented?
  2. +
","

Basically you are forcing your elements to be higher than the header itself by giving them static heights (height 100px on the menu and padding-top/bottom 30px on the logo)

+

I updated your pen: https://codepen.io/penmasterx/pen/wvPGaGz

+

Using height 100%, so the elements adapt to the header.

+

Let me know if this solves your problem. If not, let me know in more detail what you're trying to accomplish.

+

What I added to the pen:

+
.logo {
+  height: 100%;
+  display: flex;
+  align-items: center;
+  /* removed padding top/bottom */
+}
+
+.menu {
+  height: 100%;
+}
+
",html +"Javascript to Modify a function in HTML and reload the page

I have one page HTML which part of it is:

+
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
+<script type="text/javascript">
+google.charts.load('current', {'packages':['corechart']});
+google.charts.setOnLoadCallback(Social);
+
+
+function Social() {
+        var data = new google.visualization.DataTable();
+        data.addColumn('string', 'Name');
+        data.addColumn('number', 'Errors');
+        data.addRows([
+        ['bla', 53],
+        ['bla', 5]
+
+         ]);
+        var options = {title:'Social',
+                       width:600,
+                       height:200,
+                       animation:{
+                         "startup": true,
+                          duration: 1500,
+                          easing: 'out'}
+                        };
+        var chart = new google.visualization.ColumnChart(document.getElementById('Social'));
+        chart.draw(data, options);}
+</script>
+
+
+

Upon loading this page it uses google to nicely show the rows in ColumnChart.

+

If I would change the line starting with "var chart" to this:

+
var chart = new google.visualization.BarChart(document.getElementById('Social'));
+
+

The html would show barchart.

+

I want to create a javascript button that will replace text in the html from ColumnChart to BarChart and reload the page, something like:

+
function myFunction() {
+ document.body.innerHTML = document.body.innerHTML.replace("ColumnChart", "BarChart");
+ location.reload();
+}
+
+

But this reload the page with the initial values. If I don't add reload I don't see any difference of course.

+

How can I achieve this?

","

It is not possible to make change and reload the page and keep the change as GET request will reload the page from the server. Instead, you want to inject a script and run it so you update the existing page, you can try to run this after the page as loaded to overwrite the ColumnChart :

+

+function socialBarChart() {
+  var data = new google.visualization.DataTable();
+  data.addColumn('string', 'Name');
+  data.addColumn('number', 'Errors');
+  data.addRows([
+    ['bla', 53],
+    ['bla', 5]
+  ]);
+  var options = {
+    title:'Social',
+    width: 600,
+    height: 200,
+    animation: {
+      "startup": true,
+      duration: 1500,
+      easing: 'out'
+    }
+  };
+  var chart = new google.visualization.BarChart(document.getElementById('Social'));
+  chart.draw(data, options);
+}
+
+// Then call this :
+socialBarChart()
+
+
+
+

It is best practice to use camelCase with a lowercase first char for naming your function, otherwise, it look like a class constructor.

+
",html +"Input border cutout for label cross section

I would like to put inputs label on border cross section and would like to hide borders under label like this + +I did this by simply making label background white but it obviously doesn't work if I place it inside grey div any other solution for this?

+

Also I'm using quasar inputs so I'm limited to css only solutions

","

Use fieldset

+

+
+
textarea {
+  width: 100%;
+  border: none;
+}
+
<form>
+  <fieldset>
+    <legend>Your heading</legend>
+    <textarea></textarea>
+  </fieldset>
+</form>
+
+
+

",html +"injecting value into html using innerHTML returns undefined

So basically im trying to inject information that comes from my database (im using postgresSQL and node.js) into the webpage and i have confirmed that im getting the information i want right before trying to innerHTML however as soon as it goes to that codeline somehow it can't detect the value and inject undefined (i think) and im not sure why it's doing that.

+

here is the javascript for the html page im having problems :

+
window.onload = async function() {
+
+    try {
+        let courseId = sessionStorage.getItem("courseId");
+        let course = await $.ajax({
+            url: `/api/courses/${courseId}/classes`,
+            method: "get",
+            dataType: "json"
+        });
+
+        document.getElementById("course").innerHTML = course.cour_name;
+    } catch (err) {
+        console.log(err);
+    }
+}
+
+

I find it really weird since i have done it similarly with another page and it works fine.

+

here is the html for the page:

+
<html>
+
+<head>
+  <title>Express</title>
+  <link rel="stylesheet" href="/stylesheets/style.css">
+  <link rel="stylesheet" href="/stylesheets/courses.css">
+  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js%22%3E</script>
+  <script src = "./javascript/courseInfo.js"></script>
+</head>
+
+<body>
+    <header id = "header">
+    </header>
+    <nav>
+      <a href= "courses.html"><p>Back</p></a>
+    </nav>
+   <section>
+     <main id="course">
+
+     </main>
+   </section>
+</body>
+
+</html>
+
+

I don't know why fills that field with undefined since when i stringify what the ajax return it shows that it has exactly what i need, one of those fields being the cour_name row.

+

I'd really appreciate if someone could help me with this problem and thank you for your time.

","

if using chrome browser , try devtool debugger.

+

open the DevTool (e.g. press F12) then click on sources tab and locate your javascript file and put a breakpoint on the line this not working as expected. then reload the page and check the value of variables and executes the rest of the code line by line.

+

see this tutorial on how to use debugger https://developer.chrome.com/docs/devtools/javascript/

",html +"My div won't become scrollable after opening child details elements

While on a Desktop, opening the details elements does not cause the #list-wrapper element to become scrollable. I can't remember all of the things I have tried. The whole idea is that the header and form stay in place while the #list-wrapper element can scroll. I have made a simpler version of this work and I can't seem to spot where I'm going wrong.

+
<html lang="en">
+    <title>Length Of Stay</title>
+  </head>
+  <body id="body">
+    <div id="page">
+      <header id="head"><h1>LENGTH OF STAY</h1></header>
+      <main>
+        <form
+          class="form"
+          id="input-form"
+          action="los/create"
+          method="post"
+          autocomplete="off"
+        >
+          <label
+            >NAME<input
+              type="text"
+              name="name"
+              maxlength="12"
+              placeholder="Animal's name"
+              required="required" /></label
+          ><label
+            >ID #
+            <input
+              type="text"
+              name="id"
+              maxlength="8"
+              placeholder="Animal's ID number"
+              required="required" /></label
+          ><label
+            >SPECIES<select name="species" required="required">
+              <option
+                value=""
+                disabled="disabled"
+                hidden="hidden"
+                selected="selected"
+              >
+                Select one...
+              </option>
+              <option value="Cat">Cat</option>
+              <option value="Dog">Dog</option>
+              <option value="Other">Other</option>
+            </select></label
+          ><label
+            >DATE<input
+              type="date"
+              name="date-of-entry"
+              value="2020-10-19"
+              required="required" /></label
+          ><label
+            >SHELTER<select name="shelter" required="required">
+              <option
+                value=""
+                disabled="disabled"
+                hidden="hidden"
+                selected="selected"
+              >
+                Select one...
+              </option>
+              <option value="1">Shelter 1</option>
+              <option value="2">Shelter 2</option>
+            </select></label
+          ><label
+            >AREA<select name="area" required="required">
+              <option
+                value=""
+                disabled="disabled"
+                hidden="hidden"
+                selected="selected"
+              >
+                Select one...
+              </option>
+              <option value="F">Shelter Floor (F)</option>
+              <option value="Q">Quarantine (Q)</option>
+            </select></label
+          ><label
+            >NOTE<textarea name="notes" cols="30" rows="10"></textarea></label
+          ><input class="button" type="submit" />
+          <hr id="hr" />
+        </form>
+        <div id="toggle-wrapper">
+          <input
+            class="toggle"
+            id="first-shelter"
+            type="button"
+            value="Show sh2 First"
+          /><input
+            class="toggle"
+            id="form-visibility"
+            type="button"
+            value="Show Input Form"
+          />
+        </div>
+        <div id="list-wrapper">
+          <div id="list-header">
+            <div id="header-name">NAME</div>
+            <div id="header-los">LOS</div>
+            <div id="header-date">SPECIES</div>
+            <div id="headter-shelter">SHELTER</div>
+          </div>
+          <div class="list" id="sh1-list"></div>
+          <hr id="divider" />
+          <div class="list" id="sh2-list">
+            <details>
+              <summary class="sh2 F">
+                <div class="status-bar">
+                  <div class="status name">Emma</div>
+                  <div class="status red">42</div>
+                  <div class="status">Cat</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-09-08</div>
+                    <div class="id info">ID: A45461728</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: F</div>
+                  </div>
+                  <p>NOTES: Bonded with Kaitlynn.</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521a66480ea700973abcd"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521a66480ea700973abcd"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521a66480ea700973abcd"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 F">
+                <div class="status-bar">
+                  <div class="status name">Kaitlynn</div>
+                  <div class="status red">42</div>
+                  <div class="status">Cat</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-09-08</div>
+                    <div class="id info">ID: A45461764</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: F</div>
+                  </div>
+                  <p>NOTES: Bonded with Emma.</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521f96480ea700973abce"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521f96480ea700973abce"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8521f96480ea700973abce"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 Q">
+                <div class="status-bar">
+                  <div class="status name">Lily</div>
+                  <div class="status orange">8</div>
+                  <div class="status">Cat</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-10-12</div>
+                    <div class="id info">ID: A147765</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: Q</div>
+                  </div>
+                  <p>
+                    NOTES: No resident pets. Must go to experienced fosters
+                    only.
+                  </p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8522f36480ea700973abcf"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8522f36480ea700973abcf"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8522f36480ea700973abcf"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 Q">
+                <div class="status-bar">
+                  <div class="status name">GRENDEL</div>
+                  <div class="status red">29</div>
+                  <div class="status">Dog</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-09-21</div>
+                    <div class="id info">ID: A45561172</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: Q</div>
+                  </div>
+                  <p>NOTES: Medical foster</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8523a06480ea700973abd0"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8523a06480ea700973abd0"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8523a06480ea700973abd0"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 Q">
+                <div class="status-bar">
+                  <div class="status name">Beowolf</div>
+                  <div class="status red">29</div>
+                  <div class="status">Dog</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-09-21</div>
+                    <div class="id info">ID: A4550752</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: Q</div>
+                  </div>
+                  <p>NOTES: Medical Foster</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8524046480ea700973abd1"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8524046480ea700973abd1"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8524046480ea700973abd1"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 F">
+                <div class="status-bar">
+                  <div class="status name">Sweet Pea</div>
+                  <div class="status red">28</div>
+                  <div class="status">Dog</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-09-22</div>
+                    <div class="id info">ID: A44416615</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: F</div>
+                  </div>
+                  <p>NOTES: Behavior. Bite Waiver.</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525086480ea700973abd2"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525086480ea700973abd2"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525086480ea700973abd2"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 F">
+                <div class="status-bar">
+                  <div class="status name">Serenity</div>
+                  <div class="status orange">12</div>
+                  <div class="status">Dog</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-10-08</div>
+                    <div class="id info">ID: A45143898</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: F</div>
+                  </div>
+                  <p>NOTES: No resident pets.</p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525986480ea700973abd3"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525986480ea700973abd3"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8525986480ea700973abd3"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+            <details>
+              <summary class="sh2 F">
+                <div class="status-bar">
+                  <div class="status name">Baylee</div>
+                  <div class="status orange">8</div>
+                  <div class="status">Dog</div>
+                  <div class="status">sh2</div>
+                </div>
+              </summary>
+              <div class="detail">
+                <div class="left-panel">
+                  <div class="info-display">
+                    <div class="inDate info">IN DATE: 2020-10-12</div>
+                    <div class="id info">ID: A45126803</div>
+                    <div class="shelter info">SHELTER: sh2</div>
+                    <div class="area info">AREA: F</div>
+                  </div>
+                  <p>
+                    NOTES: Came into shelter 7/27. Let's find this girl a great
+                    home!
+                  </p>
+                </div>
+                <div class="icons">
+                  <form action="los/delete" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8526146480ea700973abd4"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/delete.svg"
+                      alt="delete this record"
+                    />
+                  </form>
+                  <form action="los/edit" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8526146480ea700973abd4"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/edit.svg"
+                      alt="edit this record"
+                    />
+                  </form>
+                  <form action="los/foster" method="post">
+                    <input
+                      type="hidden"
+                      name="id"
+                      value="5f8526146480ea700973abd4"
+                    /><input
+                      class="icon"
+                      type="image"
+                      src="los/home.svg"
+                      alt="change this record to in-foster"
+                    />
+                  </form>
+                </div>
+              </div>
+            </details>
+          </div>
+        </div>
+      </main>
+    </div>
+    <script src="los/index.js"></script>
+  </body>
+</html>
+
+
* {
+  margin: 0;
+  padding: 0;
+  box-sizing: border-box;
+}
+
+html {
+  font-family: acumin-pro, Arial, Helvetica, sans-serif;
+}
+
+p {
+  white-space: pre-wrap;
+  word-wrap: break-word;
+}
+
+#page {
+  background-color: #47484d;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  color: white;
+  min-height: 100vh;
+}
+
+header {
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  font-size: 150%;
+  font-family: acumin-pro-extra-condensed, Arial, Helvetica, sans-serif;
+}
+
+main {
+  display: flex;
+  width: 100%;
+  flex-direction: column;
+  align-items: center;
+}
+
+#list-wrapper {
+  width: 100%;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+}
+
+#input-form {
+  display: none;
+}
+
+.form {
+  grid-area: "form";
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+  width: 90%;
+  margin-top: 13px;
+}
+
+label {
+  width: 100%;
+  margin-bottom: 5px;
+  font-weight: bold;
+  color: azure;
+}
+
+label input,
+select {
+  width: 100%;
+  height: 34px;
+  padding: 3px;
+}
+
+textarea {
+  width: 100%;
+  padding: 3px;
+}
+
+.button-wrapper {
+  display: flex;
+  justify-content: space-evenly;
+  width: 100%;
+}
+
+.button {
+  height: 34px;
+  width: 34%;
+  padding: 5px;
+  margin: 3px;
+}
+
+hr {
+  margin: 13px 0;
+  width: 90%;
+  color: white;
+}
+
+#toggle-wrapper {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  width: 100%;
+}
+
+.toggle {
+  flex: 1 1 50%;
+  padding: 5px;
+  color: white;
+  border: none;
+  background-color: transparent;
+}
+
+#list-header {
+  width: 90%;
+  font-weight: bold;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 8px 5px 3px 21px;
+}
+
+.list {
+  width: 100%;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+}
+
+details {
+  width: 90%;
+  background-color: white;
+  margin: 5px 0;
+  color: black;
+}
+
+summary {
+  display: flex;
+  align-items: center;
+}
+
+.status-bar {
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 5px;
+  width: 80%;
+}
+
+.status {
+  width: 13px;
+}
+
+.name {
+  width: 55px;
+  white-space: nowrap;
+}
+
+.detail {
+  display: flex;
+  padding: 5px 0 8px 13px;
+}
+
+.left-panel {
+  display: flex;
+  flex-direction: column;
+  justify-content: space-between;
+  width: 90%;
+}
+
+.info-display {
+  display: flex;
+  flex-direction: column;
+}
+
+.info {
+  margin-right: 8px;
+}
+
+.icons {
+  display: flex;
+  flex-direction: column;
+  justify-content: flex-start;
+  align-items: center;
+}
+
+.icons form {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.icon {
+  padding: 3px;
+  width: 75%;
+}
+
+.card {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  width: 89%;
+  padding: 8px;
+  margin-top: 34px;
+}
+
+.PA {
+  border-bottom: 5px solid #003057;
+}
+
+.RWC {
+  border-bottom: 5px solid #4e7e96;
+}
+
+.Q {
+  border-bottom: 5px solid #ff5555;
+}
+
+.true {
+  background-color: #c4c4c4;
+}
+
+.green {
+  color: green;
+  font-weight: bold;
+}
+
+.orange {
+  color: darkorange;
+  font-weight: bold;
+}
+
+.red {
+  color: firebrick;
+  font-weight: bold;
+}
+
+@media only screen and (min-width: 980px) {
+  body {
+    overflow: hidden;
+  }
+
+  #page {
+    display: grid;
+    grid-template-rows: 1fr 6fr;
+    width: 100vw;
+    height: 100vh;
+    flex-direction: unset;
+    align-items: unset;
+  }
+
+  #head {
+    background-color: #47484d;
+    height: 100%;
+    width: 100%;
+    z-index: 1;
+  }
+
+  main {
+    display: grid;
+    grid-template-columns: 2fr 3fr;
+    overflow: hidden;
+    justify-items: center;
+    align-items: start;
+  }
+
+  #input-form {
+    display: flex;
+  }
+
+  #list-wrapper {
+    overflow-y: auto;
+  }
+
+  #toggle-wrapper,
+  #hr {
+    display: none;
+  }
+}
+
+
","

You need to change : +OverFlow:hidden; +to: +Overflow:auto;

",html +"alternative elementtype to match styles of an anchor-element

I am currently adjusting my navbar and I want to remove the functionality of one anchor in my ul while still matching the style of the other anchors.

+

I already tried to use an id on the specific li-element and replacing it with a button (just copy-pasting the css), but nothing works so far.

+

Here is my code pen: +https://codepen.io/gisbert12843/pen/XWKdZXj

+

The CodePen contains the full CSS ^^

+

And this is the HTML (highlighted the element by space):

+
<body>
+<div class="snap-wrapper">
+    <div id="main1" class="snap-box box_1">
+        <nav class="navbar">
+            <ul>
+                <li class="active"><a href="/index.html"><i class="fas fa-home"></i> Home</a></li>
+                <li class="dropdown"><a href="/dist/htmls/leistungen.html"><i class="fas fa-cut"></i>
+                        Leistungen</a>
+                    <div class="dropdown-class">
+                        <ul class="dropdown-content">
+                            <li><a href="/dist/htmls/leistungen.html#Herren">Herren</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#Damen">Damen</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#FarbenUndSträhnen">Farben und Strähnen</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#WellenUndGlätten">Wellen und Glätten</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#EPT">Extension | Perücken | Toupets</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#Kuren">Kuren</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#Brautservice">Brautservice</a></li>
+                            <li><a href="/dist/htmls/leistungen.html#Kosmetik">Kosmetik</a></li>
+                        </ul>
+                    </div>
+                </li>
+                <li><a href="/dist/htmls/covid.html"><i class="fas fa-hands-wash"></i> Covid-19</a></li>
+                <li><a href="/dist/htmls/inspiration.html"><i class="fas fa-images"></i> Inspiration</a></li>
+                <li><a href="/dist/htmls/jobs.html"><i class="fas fa-user-graduate"></i> Jobs</a></li>
+
+
+
+
+
+
+                      <!-- trying to remove the a-tag below, while keeping the style -->
+
+
+
+                <li class="dropdown"><a href="/dist/htmls/mehr.html"><i class="fas fa-chevron-right"></i>Mehr</a>
+                    <div class="dropdown-class">
+                        <ul class="dropdown-content">
+                            <li><a href="/dist/htmls/mehr htmls/impressum.html"> Impressum</a></li>
+                            <li><a href="/dist/htmls/mehr htmls/datenschutz.html"> Datenschutz</a></li>
+                        </ul>
+                    </div>
+                </li>
+
+
+
+
+
+
+            </ul>
+        </nav>
+    </div>
+</div>
+<div id="main2" class="snap-box box_2">
+</div>
+</div>
+</body>
+            
+
+

And this is the CSS of the specific element:

+
.snap-wrapper .snap-box.box_1 .navbar ul {
+  list-style: none;
+  display: flex;
+  color: transparent;
+  position: relative;
+}
+
+.snap-wrapper .snap-box.box_1 .navbar ul li {
+  position: relative;
+}
+
+.snap-wrapper .snap-box.box_1 .navbar ul li a {
+  font-size: 1.5rem;
+  padding: 23px;
+  display: block;
+  position: relative;
+  z-index: 1;
+  color: #e4e4e4;
+  text-decoration: none;
+}  
+
+

I am grateful for any kind of suggestions and help! <3

","

Replace the <a> tag you want to "remove" by a <span> (obvioously remove the href attribute) and in your CSS add this selector .snap-wrapper .snap-box.box_1 .navbar ul li span before .snap-wrapper .snap-box.box_1 .navbar ul li a like so

+
.snap-wrapper .snap-box.box_1 .navbar ul li span,
+.snap-wrapper .snap-box.box_1 .navbar ul li a {
+  font-size: 1.5rem;
+  padding: 23px;
+  display: block;
+  position: relative;
+  z-index: 1;
+  color: #e4e4e4;
+  text-decoration: none;
+} 
+
",html +"Variable link that modifies the index of my website

I am looking for the method that allows to modify a value/text on my home page with the used link.

+

For example, if the URL is mywebsite.com/index.php?name=Mike

+

somewhere on my website, it will say

+
+

"Welcome Mike"

+
+

If the URL is mywebsite.com/index.php?name=Mark, it will automatically change to

+
+

"Welcome Mark"

+
+

without changing anything in my code.

+

Is it possible with HTML only or do I need PHP?

","

This is possible with HTML, but you need JavaScript. Here's an example:

+

+
+
// Find the query
+let query = window.location.search;
+// Extract the name
+let match = query.match(/name=([^&]+)/);
+// If the name exist, put it in the body
+if (match) document.body.innerHTML = match[1];
+
+
+

+

Note that this won't work here, but it will work in the website.

+

As @JNa0 said, PHP is better suited to this task. The PHP would look like echo $_GET["name"];

",html +"how can i remove underline in link

i am working on a project in which i have to make a webpage .i have some links for going web sites and i want to remove underline in link ( a ). +please help me.

+

+
+
      <a href=""google.com"" >google</a><br>
+      <a href=""youtup.com"" >youtup</a><br>
+      <a href=""owerstackflow.com"" >stackoverflow</a>
+
+
+

","

Use this:

+
<a style="text-decoration:none" href="http://Example.Microsoft.Com">nonunderlinedhyperlink</a>
+
",html +"I am having sketch.js with particles but the particles are over my navbar so the links are not clickable

I am using particles.js by sketch.js

+

It is a nice effect and I want to use it but when I am doing so it is placed over my website's navbar and thus the links are not clickable

+

I tried Z-INDEX : 99999;, but it still "overlaps my nabvar"

","

As I understand you have placed your sketch.js canvas on top of your navbar, thus the nav is not clickable?

+

Try putting pointer-events: none; on the sketch.js canvas or its immediate container. Setting this property to none means that the element will "pass through" all of the mouse events.

",html +"HTML: How do I simply indent a form?

I've searched and searched for what I thought would be a simple find but haven't found anything. I have this form:

+
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES) ?>" method="post" enctype="multipart/form-data"> 
+    <input type="file" name="thefile"> 
+    <input type="submit" value="Upload File"> 
+    <br />
+    <!-- test key -->
+    <div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
+</form> 
+
+

I want it indented so it doesn't touch the side of the area it's in, I've tried something like <div style="text-indent-left:20px"> wrapped around it but didn't phase it.

+

How do I do I indent the form?

+

Thanks.

","

Please try the following (indented 60 pixels from the left margin)

+

+
+
#form1
+{
+padding-left:60px;
+}
+
<form action=""self.php"" method=""post"" enctype=""multipart/form-data"" id=form1> 
+    <input type=""file"" name=""thefile""> 
+    <input type=""submit"" value=""Upload File""> 
+    <br />
+    <!-- test key -->
+    <div class=""g-recaptcha"" data-sitekey=""6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI""></div>
+</form> 
+
+
+

",html +"ThreeJS : fit camera zoom according to a DOM element

I just begin to learn Three js and I face to a problem when tryng to add a plane geometry based on a img tag on the dom.

+

Context

+

Here is my actuel html template :

+
<figure>
+  <div class="aspect" />
+  <img class="img" src="@/assets/images/project1.jpg" />
+</figure>
+
+

The img tag is hidden by css property display: none and the .aspect div give the size of the element by receiving width: 50vw and padding-top: 60%

+

I calculate the width - height of the element by using getBoundingClientRect func and applying it to the plane geometry like that :

+
const geometry = new THREE.PlaneBufferGeometry(el.width, el.height, 5)
+
+

Then I simply apply the texture of my image to it

+

My problem

+

As you can see on the screenshots, the plane geometry has not the exact size of my aspect div (in red) :

+

+

+

For the moment I manually set the z axis of my camera, but I know it's not the good solution and just wanted to know if there was an existing solution to acheive this ?

+

Thank you in advance !

","

Solved by using an OrthographicCamera

+

Doc here : +https://threejs.org/docs/#api/en/cameras/OrthographicCamera

",html +"How to apply css on a div that has no class or id?

I have two div and I want to apply some css on the first div that has no class or id .How can I do it ??

+

Html:

+
<div>some content</div>
+
+<div class="text-1">
+
","

You can use the :not() selector:

+

+
+
div:not([class]) {
+  color: red;
+}
+
<div>some content</div>
+
+<div class=""text-1"">some more</div>
+
+
+

+

Basically this says select any div that doesn't have the class attribute.

",html +"Form is submitted even if minlength is unmet

I noticed, that a form containing an <input> element is submitted, even if the <input> has a minlength attribute.

+

F.e. in my attached code, submitting works when no value is entered, but it fails if the length of the entered value is less than fife.

+

Why does it behave like this? +In my opinion the browser should prevent a submit when the minlength requirement is not met.

+

+
+
<form>
+  <label>Name:</label>
+  <input type=""text"" minlength=""5"">
+  <button type=""submit"">Submit</button>
+</form>
+
+
+

","

It is nature of minlength.

+

By adding minlength="5", the value must either be empty or five characters or longer to be valid.

+

If you want to avoid empty case you need to use required.

+

More details here: +https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/minlength

",html +"CSS show scrollbar only when max-width reached

I have two child divs in a parent div with display: flex.

+

Here's a dummy snippet to represent my situation:

+
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+</head>
+
+<body>
+    <div style="display: flex;">
+        <div style="width: 100%;">
+            long text long text long text long text long text long text long text long text long text long text long
+            text long text long text long text long text long text long text long text long text long text long text
+            long text long text long text long text long text long text long text long text long text long text long
+            text long text long text long text long text long text long text long text long text long text long text
+            long text long text long text long text long text long text long text long text long text long text long
+            text long text long text long text long text long text long text long text long text long text long text
+            long text long text long text long text long text long text long text long text long text long text long
+            text long text long text long text long text long text long text long text long text long text long text
+            long text long text long text
+        </div>
+        <div style="width: fit-content; max-width: 60%; display: flex; overflow: auto;">
+            <div style="height: 100px; width: 100px; min-width: 100px; background-color: red; margin-right: 15px;"></div>
+            <div style="height: 100px; width: 100px; min-width: 100px; background-color: red; margin-right: 15px;"></div>
+            <div style="height: 100px; width: 100px; min-width: 100px; background-color: red; margin-right: 15px;"></div>
+            <div style="height: 100px; width: 100px; min-width: 100px; background-color: red; margin-right: 15px;"></div>
+        </div>
+    </div>
+</body>
+
+</html>
+
+

Output looks like this:

+

+

The content in the right div will be added dynamically, in this case we have red boxes. So it may contain 0 or more of those red boxes.

+

What I want is:

+
    +
  • I want for the right div to expand as long as it doesn't reach it's max set width of 60% and after it does I want for a horizontal scrollbar to appear for that div.

    +
  • +
  • As the right div expands (until it reaches 60% of the max width) the left div will decrease in size.

    +
  • +
+

The snippet above will do this if I remove overflow: auto from the right div, but when it reaches it's maximum of 60% the horizontal scrollbar will appear for the whole page instead of only appearing for the right div area.

+

And if I leave overflow: auto then the scrollbar will be there from the beginning (like you can see in the image, and I only want it to appear after max-width of 60% has been exceeded).

+

How would I handle this?

+

EDIT:

+

Here is codepen link: https://codepen.io/transcend/pen/wvWyZvK

","

Update your CSS as below:

+
.container {
+  display: flex;
+}
+.full-width {
+  width: 100%;
+  flex: 40%;
+}
+.box-container {
+  width: fit-content;
+  max-width: 60%;
+  display: flex;
+  overflow-x: auto;
+}
+.box {
+  height: 100px;
+  width: 100px;
+  min-width: 100px;
+  background-color: red;
+  margin-right: 15px;
+}
+
+

I have used overflow-x: auto; which helps to generate a horizontal scroll bar. Hope this works fine.

",html +"Cannot use addEventListener() on a createElement() (a button) after displaying it in the DOM (in javascript)

I am creating a Javascript framework recently and I am facing two problems that I don't understand at all. When I create a new button with createElement() in Javascript, I can't place it inside several elements at the same time without killing the "click" event (if this is an id, it works).

+

(Note : "button.onclick = function()" doesn't work either)

+

Here is the code : (I don't want to use any libraries)

+

+
+
function createButton() {
+    var button = document.createElement(""button"");
+    button.innerHTML = ""YOOOO"";
+    button.style.backgroundColor = ""red"";
+    button.style.color = ""white"";
+
+    // Problem Two : If I click on the button, nothing happends
+    button.addEventListener(""click"", function(e) {
+        alert(e.target);
+    }, false);
+
+    var clas = document.getElementsByClassName(""test"");
+    Array.from(clas).forEach(element => {
+        element.appendChild(button);
+        element.innerHTML += """"; // First problem : If I don't do this, the button does not appear in the first div. I have no idea why !
+    });
+}
+createButton();
+
 body {
+    margin: 0;
+    padding: 0;
+    display:flex;
+    justify-content: center;
+    align-items: center;
+    height: 100vh;
+    background-color: rgba(30, 30, 30, 0.2);
+}
+
+button {
+    cursor: pointer;
+    width: 80px;
+    height: 50px;
+    padding: 10px;
+}
+
<!DOCTYPE html>
+<html>
+<head>
+    <meta charset=""UTF-8"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>bug</title>
+</head>
+
+<body>
+
+<div class=""test"" id=""1"" style=""padding: 50px;"">
+    <span>1</span>
+</div>
+<div class=""test"" id=""2"" style=""padding: 50px;"">
+    <span>2</span>
+</div>
+
+</body>
+</html>
+
+
+

","

There are 2 problems:

+
    +
  • element.innerHTML += "";, where element refers to the button's parent, will force the parent to re-parse its contents from their HTML string, thus corrupting any existing handlers on child elements. The element the listener is attached to will be removed from the DOM and replaced with a different one; the new one does not have the listener.

    +
  • +
  • When you do appendChild, if the element being appended already exists in the DOM, it'll be removed from where it existed previously before being appended to its new location. Since you only do document.createElement('button') once, without the innerHTML += '', the button gets removed from its first position when appended to the second.

    +
  • +
+

Create the button inside the loop instead, and both problems are solved.

+

+
+
function createButton() {
+  var clas = document.getElementsByClassName(""test"");
+  Array.from(clas).forEach(element => {
+
+    var button = document.createElement(""button"");
+    button.innerHTML = ""YOOOO"";
+    button.style.backgroundColor = ""red"";
+    button.style.color = ""white"";
+
+    // Problem Two : If I click on the button, nothing happends
+    button.addEventListener(""click"", function(e) {
+      alert(e.target);
+    }, false);
+    element.appendChild(button);
+
+  });
+}
+createButton();
+
body {
+  margin: 0;
+  padding: 0;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  height: 100vh;
+  background-color: rgba(30, 30, 30, 0.2);
+}
+
+button {
+  cursor: pointer;
+  width: 80px;
+  height: 50px;
+  padding: 10px;
+}
+
<div class=""test"" id=""1"" style=""padding: 50px;"">
+  <span>1</span>
+</div>
+<div class=""test"" id=""2"" style=""padding: 50px;"">
+  <span>2</span>
+</div>
+
+
+

+

Or, making the code a bit prettier:

+

+
+
function createButton() {
+  for (const parent of document.querySelectorAll('.test')) {
+    const button = parent.appendChild(document.createElement(""button""));
+    button.textContent = ""YOOOO"";
+    button.style.backgroundColor = ""red"";
+    button.style.color = ""white"";
+    button.addEventListener(""click"", function(e) {
+      console.log(e.target);
+    });
+  }
+}
+createButton();
+
body {
+  margin: 0;
+  padding: 0;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  height: 100vh;
+  background-color: rgba(30, 30, 30, 0.2);
+}
+
+button {
+  cursor: pointer;
+  width: 80px;
+  height: 50px;
+  padding: 10px;
+}
+
<div class=""test"" id=""1"" style=""padding: 50px;"">
+  <span>1</span>
+</div>
+<div class=""test"" id=""2"" style=""padding: 50px;"">
+  <span>2</span>
+</div>
+
+
+

",html +"Trying to change the delimiter from webpack HtmlWebpackPlugin or using a custom loader with no success

I have been trying to change the delimiter of HtmlWebpackPlugin ejs since I need to be able to output <%.

+

So things I have tried:

+
    +
  1. Using <%% gives an error of unexpected identifier.
  2. +
  3. It seems that I can't pass the delimiter as options to the default loader so using a custom loader gives the following: "To support the 'esModule' option, the 'variable' option must be passed to avoid 'with' statements"
  4. +
+

here is my config

+
    const path = require("path");
+const common = require("./webpack.common");
+const merge = require("webpack-merge");
+const CleanWebpackPlugin = require("clean-webpack-plugin");
+const MiniCssExtractPlugin = require("mini-css-extract-plugin");
+const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
+const TerserPlugin = require("terser-webpack-plugin");
+var HtmlWebpackPlugin = require("html-webpack-plugin");
+const WebpackShellPlugin = require('webpack-shell-plugin');
+const { data } = require("jquery");
+
+module.exports = merge(common, {
+  mode: "production",
+  output: {
+    filename: "[name].[contentHash].bundle.js",
+    path: path.resolve(__dirname, "dist")
+  },
+  optimization: {
+    minimizer: [
+      new OptimizeCssAssetsPlugin(),
+      new TerserPlugin(),
+      new HtmlWebpackPlugin({
+        template: "./src/template.html",
+        minify: {
+          removeAttributeQuotes: true,
+          collapseWhitespace: true,
+          removeComments: true
+        }
+      }),
+      new HtmlWebpackPlugin({
+        title: 'Custom template',
+        inject: false,
+        filename: 'test.aspx',
+              //     interpolate : '\\{\\{(.+?)\\}\\}',
+      //     evaluate : '\\[\\[(.+?)\\]\\]'
+        template: './src/templateasp.ejs',
+        // template: '!!ejs-loader!./src/templateasp.ejs'
+      }),
+    ]
+  },
+  plugins: [
+    new MiniCssExtractPlugin({ filename: "[name].[contentHash].css" }),
+    new CleanWebpackPlugin(),
+    new WebpackShellPlugin({onBuildStart:['node "./prov/lists.build.node.mjs"'], onBuildEnd:['echo "Webpack End"']}),
+  ],
+  module: {
+    rules: [
+      {
+        test: /\.scss$/,
+        use: [
+          MiniCssExtractPlugin.loader, //3. Extract css into files
+          "css-loader", //2. Turns css into commonjs
+          "sass-loader" //1. Turns sass into css
+        ]
+      },
+      // {
+      //   test: /\.ejs$/,
+      //   loader: 'ejs-loader',
+      //   options: {
+      //     variable: 'data',
+      //     interpolate : '\\{\\{(.+?)\\}\\}',
+      //     evaluate : '\\[\\[(.+?)\\]\\]'
+      //   }
+      // }
+    ]
+  }
+});
+
+

most of it copied from freecodecamp wp course

+

Any ideas what I can do to deal with this issue? I just need to be able to output a aspx file which has "<%-- " and "<%@" on it. the rest I can handle with the sample file they have to put the assets in the right place.

","

I figured it out. You need to do the following:

+

ex1:

+
<%= '\<%-- _lcid="1033" _version="16.0.20113" _dal="1" --%\>' %>
+
+

ex2

+
<%= '\<%-- _LocalBinding --%\>' %>
+
+

ex3

+
<%= 'string text, use backslash to escape the delimiter as in \<% or %\>' %>
+
",html +"How can I use localStorage to store the value/data IN a form in javascript and html

How can I use localStorage to store the data of a form. Here is the code:

+

+<form>
+
+<textarea id="txt" placeholder="Type in some text!"></textarea>
+
+</form>
+
","

You can store data like this

+
localStorage.setItem("key", "value");
+//for your example
+var txtValue = document.getElementById("txt").value;
+
+localStorage.setItem("txt", txtValue);
+
+

To get the value you can do like:

+
localStorage.getItem("txt");
+
",html +"Grabbing the CSS of an HTML text selection using JS

I am creating a text editor using HTML, CSS, and JS. I've got most of the functions worked out, and even though it is deprecated, I've been using document.execCommand() to stylize text content in a contenteditable div. I have a hotbar at the top of the screen that has all the buttons to change the font, change the size, bold, italic, underline etc. Similarly to google docs, I would like the top bar to update its values to match those of whatever text is selected. I've got a function that grabs the HTML of a text selection thanks to another post on this site:

+
function getHTMLOfSelection () {
+    var range;
+    if (document.selection && document.selection.createRange) {
+        range = document.selection.createRange();
+        return range.htmlText;
+    }
+    else if (window.getSelection) {
+        var selection = window.getSelection();
+        if (selection.rangeCount > 0) {
+            range = selection.getRangeAt(0);
+            var clonedSelection = range.cloneContents();
+            var div = document.createElement('div');
+            div.appendChild(clonedSelection);
+            return div.innerHTML;
+        }
+        else {
+            return '';
+        }
+    }
+    else {
+        return '';
+    }
+}
+
+

But I don't know how to grab the css of the whole thing. For instance, if half the selection is Arial font, and the other is Serif. I want it to pick the first. But I don't even know how to start with getting the CSS. Here is what I have so far:

+
function updateControlBar() {
+    selection = getHTMLOfSelection();
+    if (typeof selection != "undefined") {
+        // Get the selection's font and update the font menu to show it.
+        document.getElementById('font-button').value = selection.fontFamily;
+        document.getElementById('font-button').style.fontFamily = selection.fontFamily;
+        console.log(selection.fontFamily);
+    } else {
+        console.log("No selection, cannot update control bar values.");
+    }
+}
+
+

Thanks for the help!

","

Looks like you can now use getComputedStyle().

+

Try the following:

+
var bEl =  document.querySelector("body"); 
+getComputedStyle(bEl);
+
+

You'll see :

+

I ran it on this page (via console) and I saw over 400 css properties listed.

+
+

CSS2Properties(486)

+
",html +"Content of database not showing up in Django

I have some problems to get the content out of the django database. +I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff.

+

So to come to my problem I initalized my modules in models.py

+
from django.db import models
+
+class Aboutme(models.Model):
+    author = models.CharField(max_length=30)
+    ...
+
+

This works because I could add content to the database. +So there is no mistake.

+

Now in the views.py

+
from django.shortcuts import render
+from portfolio.models import Aboutme
+
+def portfolio_index(request):
+    
+    aboutme = Aboutme.objects.all()
+    context = {'aboutme': aboutme}
+
+    return render(request, 'portfolio_index.html', context)
+
+

So finally in my HTML file, called portfolio_index.html, I call the content via

+
 <h1>{{ aboutme.author }}</h1>
+
+

I guess it's right. But the content of author doesn't showup, so what did I miss? +I can call static files via django, so couldn't be something wrong with django...

+

Can anyone help.

+

Thanks in advance.

","

I think that you need to use a for loop to show "aboutme" because with "aboutme = Aboutme.objects.all()" you query a list of elements.

+
{% for aboutme_item in aboutme %}
+    <h1>{{ aboutme_item.author }}</h1>
+{% endfor %}
+
",html +"vb.net - grabbing the value ot a text input box displayed in a webview and bringing it back into winforms

I've got a winform that contains a webview. +At some points the webview will display html content including input boxes for the end user to throw some responses into.

+

Is it possible for me to interact with the input box in the webview to grab its contents programatically? +Even if its just to display that text in a messagebox as an example, that will get me well on my way!

+

so in the example form below, I'd be looking to grab whatever the end user entered into 'userresponse' and throw it into a variable. like...

+
 dim response as string = 'the contents of the input box in the webview
+ messagebox.show(response)
+
+

any help appreciated and thanks in advance! :)

+
 <HTML>
+     <Body>
+      <form>
+        <input type="text" id="userresponse" name="userresponse"><br>
+      </form>
+     </Body>
+ </HTML>
+
","

You can use InvokeScriptAsync() to to achieve it.

+

Sample code:

+
Imports System.IO
+Public Class Form1
+Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
+    Dim html As String = File.ReadAllText("test1.html")
+    WebView1.NavigateToString(html)
+End Sub
+
+Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
+    Dim ss As String = Await WebView1.InvokeScriptAsync("eval", New String() {"document.getElementById('userresponse').value;"})
+    MsgBox(ss)
+End Sub
+
+End Class
+
+

Result:

+

",html +"i get white space when i use marging in a section

what am trying to do is place a div in center of my section i tried margin: 2% auto; but it looked like this (the background isn't filled)

+

+this is the link to the code +https://jsfiddle.net/medbenzekri/7gc2j9bk/1/

+

this is my html

+
{%load static%}
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+   <!-- Required meta tags -->
+   <meta charset="utf-8">
+   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+
+   <!--  CSS -->
+   <link rel="stylesheet"  href={%static 'css/translate_page.CSS' %}>
+   <link href='https://fonts.googleapis.com/css?family=Bangers' rel='stylesheet'>
+
+ <title>translate</title>
+ <script src="https://kit.fontawesome.com/a076d05399.js"></script>
+ </head>
+ <body>
+ {% include "nav.html" %}
+ <style>
+  a.active-translate-page{
+  background:  #33ccff ;
+ </style>
+ </body>
+ <section class="container">
+ <div class="the-form">
+ 
+ </div>
+ </section>
+ 
+</html> 
+
+

and this is my css

+
*{
+   padding: 0;
+   margin: 0;
+   text-decoration: blink;
+   list-style: none;
+   box-sizing: border-box;
+}
+body {
+ font-family: montserrat;
+}
+.container{
+display: block;
+background: linear-gradient(to bottom, #33ccff 5%, #7882F3 50%);
+background-size : cover;
+height: calc(100vh - 80px);
+}
+
+.the-form{
+width: 600px;
+height: 500px;
+background: #fff;
+margin: 2%   auto ;
+border-radius: 2%;
+
+}
+
+

and btw am using django

","

You may try the flex layout in this case:

+
.container {
+    display: flex;
+    background: linear-gradient(to bottom, #33ccff 5%, #7882f3 50%);
+    background-size: cover;
+    width: 100%;
+    height: calc(100vh - 80px);
+    align-items: center;
+    justify-content: center;
+}
+
+.the-form {
+    width: 600px;
+    height: 500px;
+    background: #fff;
+    border-radius: 2%;
+}
+
",html +"keep text from moving

I have a span tag inside of a paragraph that updates every second, and whenever it does, it keeps on shifting the text either to the right or left:

+

+
+
setInterval(() => {document.querySelector(""#fruits"").innerHTML = Date.now() % 20}, 1)
+
<p>Here is some text ""<span id=""fruits""></span>"" Here is some more text</p>
+
+
+

+

How can I prevent the words from moving?

","

Add this style style="display: inline-block;width: 15px;" on span #fruits

+

+
+
setInterval(() => {document.querySelector(""#fruits"").innerHTML = Date.now() % 20}, 1);
+
<p>Here is some text ""<span id=""fruits"" style=""display: inline-block;width: 15px;""></span>"" Here is some more text</p>
+
+
+

",html +"How to avoid negative values from css calc function?

I am using css calc function from css-tricks

+
calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum viewport width]) / ([maximum viewport width] - [minimum viewport width])));
+
+

I use the calc function like this

+
margin-top: calc(270px + (0 - 270) * (100vw - 320px) / (900 - 320));
+
+

This works and my margin-right is 270px at 320px viewport width and 0px at 900px viewport width. +But when I resize my window bigger than 900px, the margin-right is negative.

+

I can use media queries, but is there another CSS solution? Can I combine these calc function with min() max() or clamp() to avoid negative values?

+

Edit

+

i found a possible solution. It works with max() in this way

+
margin-right: max(0vw, calc(270px + (0 - 270) * ((100vw - 320px) / (900 - 320))))
+
","

for all who are interested. I ended up with this css rules.

+

if your minimum value is negative you need the css min() function like this

+
margin-right: min(0vw, calc(-270px + (0 - -270) * ((100vw - 320px) / (900 - 320))))
+
+

if your minimum value is positive you need the css max() function like this

+
margin-right: max(0vw, calc(270px + (0 - 270) * ((100vw - 320px) / (900 - 320))))
+
",html +"how do i go about aligning two images with two paragraphs?

How can I make it so I have one image on the left, with a paragraph on the right. Then another image on the right, with a paragraph on the left.

+

Like this

+

I think it's simple but i can't get my head around how to do it

","

Most people use flex or grid to do this, some people use float too. +This is your answer via flex

+

+
+
img {max-width: 100%}
+
+.blog-card {
+    width: 700px;
+    margin: 30px auto 0;
+    padding: 15px;
+    border-radius: 5px;
+    background: #f0f0f0;
+    
+    display: flex;
+}
+
+.thumbnail {
+    -ms-flex: 0 0 300px;
+    flex: 0 0 300px;
+    max-width: 300px;
+    margin-right: 15px;
+}
+
+.blog-card:nth-child(even) .thumbnail {
+    order: 2;
+    margin: 0;
+}
+
<div class=""blog-card"">
+    <div class=""thumbnail"">
+        <a href=""#"">
+            <img src=""https://images.pexels.com/photos/2693529/pexels-photo-2693529.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"" alt=""Thumbnail"">
+        </a>
+    </div>
+    <div class=""blog-card-blody"">
+        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum necessitatibus dolore doloremque laborum iste ad aspernatur praesentium quas magnam deserunt!</p>
+    </div>
+</div>
+
+<div class=""blog-card"">
+    <div class=""thumbnail"">
+        <a href=""#"">
+            <img src=""https://images.pexels.com/photos/2693529/pexels-photo-2693529.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"" alt=""Thumbnail"">
+        </a>
+    </div>
+    <div class=""blog-card-blody"">
+        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum necessitatibus dolore doloremque laborum iste ad aspernatur praesentium quas magnam deserunt!</p>
+    </div>
+</div>
+
+<div class=""blog-card"">
+    <div class=""thumbnail"">
+        <a href=""#"">
+            <img src=""https://images.pexels.com/photos/2693529/pexels-photo-2693529.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"" alt=""Thumbnail"">
+        </a>
+    </div>
+    <div class=""blog-card-blody"">
+        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum necessitatibus dolore doloremque laborum iste ad aspernatur praesentium quas magnam deserunt!</p>
+    </div>
+</div>
+
+<div class=""blog-card"">
+    <div class=""thumbnail"">
+        <a href=""#"">
+            <img src=""https://images.pexels.com/photos/2693529/pexels-photo-2693529.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"" alt=""Thumbnail"">
+        </a>
+    </div>
+    <div class=""blog-card-blody"">
+        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum necessitatibus dolore doloremque laborum iste ad aspernatur praesentium quas magnam deserunt!</p>
+    </div>
+</div>
+
+
+

",html +"How to get the first instance of specific value found in data-* using jQuery

As the title states I want to get the first instance of a value that is given to the attribute in a data-*

+

Ex:

+
<div class="row mt-2" data-group="1">
+<div class="row mt-2" data-group="1">
+<div class="row mt-2" data-group="2">
+<div class="row mt-2" data-group="2">
+<div class="row mt-2" data-group="3">
+<div class="row mt-2" data-group="3">
+
+

Let's say I already have a list of all the unique values found in data-group. How would I be able to specify the divs that have the first instance of "1", "2", and "3". +The goal of this is to be able to prepend something before the first instance of each of the unique data-group using jQuery

","

You can loop over each data-group number, and select only the first one in the group :

+

+
+
for (let i = 1; i < 4; i++) {
+  $(`[data-group=${i}]`).first().css(""border"", ""blue solid 2px"")
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div id=""groups""> <!-- or something -->
+  <div class=""row mt-2"" data-group=""1"">Group 1</div>
+  <div class=""row mt-2"" data-group=""1"">Group 1</div>
+  <div class=""row mt-2"" data-group=""1"">Group 1</div>
+  <div class=""row mt-2"" data-group=""2"">Group 2</div>
+  <div class=""row mt-2"" data-group=""2"">Group 2</div>
+  <div class=""row mt-2"" data-group=""3"">Group 3</div>
+  <div class=""row mt-2"" data-group=""3"">Group 3</div>
+  <div class=""row mt-2"" data-group=""3"">Group 3</div>
+  <div class=""row mt-2"" data-group=""3"">Group 3</div>
+</div>
+
+
+

",html +"How to display different HTML sections as different pages of a website
<!DOCTYPE html>
+<html>
+<head>
+<title></title>
+</head>
+<body>
+
+<div class="main-container">
+    <!--NAVAGATION-->
+    <ul class="nav">
+    <li><a href="#home"></a>Home</li>
+    <li><a href="#about"></a>About</li>
+    <li><a href="#robotics">Robotics</a></li>
+    <li><a href="#books">Books</a></li>
+    </ul>
+</div>
+
+<div class="main-content">
+    <section class="home section" id="home">
+        <!--home page content-->
+    </section>
+    <section class="about section" id="about">
+        <!--about page content-->
+    </section>          
+    <section class="robotics section" id="robotics">
+         <!--robotics page content-->
+    </section>
+    <section class="books section" id="books">
+         <!--books page content-->
+    </section>
+</div>
+    
+</div>
+
+</body>
+</html>
+
+

Hello, guys! I am playing with this structure and trying to link each sections to its corresponding NAV option so I can display only the content selected (as a different page). However with the structure of an "id" attribute in the section and "href" attribute to the NAV option doesn't help too much, because only switches the content on the page, not the page itself. I've tried my best to do this, but this is the best I could do.

","

You could use the CSS pseudo class :target to do this. Hide your sections by default and when one is clicked on, change that section's display to block:

+

+
+
section {
+  display: none;
+}
+
+section:target {
+  display: block;
+}
+
<div class=""main-container"">
+  <!--NAVAGATION-->
+  <ul class=""nav"">
+    <li><a href=""#home"">Home</a></li>
+    <li><a href=""#about"">About</a></li>
+    <li><a href=""#robotics"">Robotics</a></li>
+    <li><a href=""#books"">Books</a></li>
+  </ul>
+</div>
+
+<div class=""main-content"">
+  <section class=""home section"" id=""home"">
+    home page content
+  </section>
+  <section class=""about section"" id=""about"">
+    about page content
+  </section>
+  <section class=""robotics section"" id=""robotics"">
+    robotics page content
+  </section>
+  <section class=""books section"" id=""books"">
+    books page content
+  </section>
+</div>
+
+</div>
+
+
+

",html +"Video does not load - chrome: Not allowed to load local resource

I'm using the plyr library to upload a video. The video URL comes from a server, however the video is not loaded and I get the following error in chrome: Not allowed to load local resource.

+

Does anyone know why this error appears?

+

HTML

+
 <video id="plyrID" controls playsinline [poster]="poster" (plyrPlay)="played($event)"
+                (plyrInit)="player = $event">
+                <source src="//MyServer/videos/video.mp4" type="video/mp4">
+ </video>
+
+

Error

+

","

If you look at the error message you are getting above you will see that it is trying to open the video from a URL starting with:

+
+

file://

+
+

The browser is interpreting that this file is a local file and not on a server - i.e. even though the 'video URL comes from a server' as you say the URL which the browser is seeing is a local URL.

+

If you want the source to be a video on a server your HTML code you should either see an absolute server source URL like this example:

+
<video id="testVid" controls preload="auto">
+    <source src="https://ftp.nluug.nl/pub/graphics/blender/demo/movies/ToS/tears_of_steel_720p.mov" type='video/mp4'>
+</video>
+
+

Or a URL which is relative to your own web server serving the current page like this:

+
<video id="testVid" controls preload="auto">
+    <source src="/MyServerMoviesFolder/ToS/tears_of_steel_720p.mov" type='video/mp4'>
+</video>
+
+

You can see some more examples here: https://www.w3schools.com/html/html_filepaths.asp

+

If, in your example, 'MyServer' is a valid 'authority name, e.g. 'MyServerDomainName.com:8080', then you URL is indeed a valid URL according to the RFC. It is referred to as a network-path reference URI and described in section 4.2 of the RFC linked below.

+

Different browsers may treat this differently, and Chrome does seem to default to a local file when it sees a URI starting with a double forward slash if you enter it directly in the URL tab of the browser.

+

However, with a valid 'authority' in the URL it should resolve to a video - see the example snippet below which is tested on Chrome and Safari and plays the video:

+

+
+
<video id=""testVid2"" controls preload=""auto"">
+    <source src=""//commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"" type='video/mp4'>
+</video>
+
+
+

+

If this is not working in your case and defaulting to a local file, it seems most likely that URL does not contain a valid 'authority' part. However, in this case it should give a name not resolved case on Chrome, as in the snippet below:

+

+
+
const player = new Plyr('#plyrID');
+
<video id=""plyrID"" controls playsinline [poster]=""poster"" (plyrPlay)=""played($event)""
+                (plyrInit)=""player = $event"">
+                <source src=""//MyServer/videos/video.mp4"" type=""video/mp4"">
+ </video>
+
+<script src=""https://cdn.plyr.io/3.6.2/plyr.js""></script>
+
+
+

+

It is worth noting that this is a very specific URL format and it may be that you don't actually need to use this format. It is usually used so that the request uses either HTTP or HTTPS in line with the current page. See discussion here and the definition in the RFC also:

+",html +"How can I write a multiple condition in Javascript in order to change a
class?

I have a <div> that takes a class depending on an if statement(message.isSent() returning true) like this:

+
 <div [class] = "message.isSent() ? 'my-message' : 'other-message'" class = "messageContainer" >   
+
+

How can I give this <div> another class (let's say 'info-message') in case of another method returning true?(message.isInfoMessage())

+

Thanks a lot

","

See if this solves the issue:

+
  <div [class] = "message.isSent() ? 'my-message' : message.isInfoMessage() ? 'info-message' : 'other-message'" class = "messageContainer" > 
+
+

Another approach is to add a helper method to the Message:

+

Define a messageType() method:

+
type() {
+   if (this.isSent()) return "my-message";
+   if (this.isInfoMessage()) return "info-message";
+   return "other-message";
+}
+
+

html:

+
  <div [class] = "message.type()" class = "messageContainer" >
+
",html +"HTML Bullets Not Showing

I am using the TinyMCE gem with Rails (if that even matters) to generate text on my site. All the sudden bullet points are not appearing. (They used to display just fine.)

+

After all the ERB is rendered, the final HTML is pretty unstyled and boring (it looks like this...)

+
<ul>
+   <li>Text here</li>
+   <li>More text here</li>
+</ul>
+
+

There is no CSS that speaks directly to bullets (ul, li, or ol).

+

Looking at other StackOverflow posts (like this) you're supposed to ensure that <li> tags have the css property display: list-item, but when I look at them in the Chrome inspector, they do have this display property.

+

You can see the issue live here if you want to verify that this property is correct.

+

Other than this, I'm not sure what could be causing the issue. What else can I check for? I've never had bullets just disappear before!

","

As per your live issue here

+

overflow-x: hidden; on <li>

+

is hiding the bullets.

+

Removing it or adding +overflow-x : unset; may help

",html +"php login with $_SESSION

i am making a login form with sessions this is my index.php page code:

+
<?php
+    include "../config/MainClass.php";
+    include "../connection.php";
+    session_start();
+    if (empty($_SESSION['admin'])){
+        echo "<script>location='../login.php'</script>";
+    }
+    if (isset($_GET['logout'])){
+        unset($_SESSION['admin']);
+        echo "<script>location='../login.php'</script>";
+    }
+    if (isset($_GET['success'])) {
+        if ($_GET['success']==1) {
+            echo "<script>alert('Record Deleted Successfully');</script>";
+        }
+        
+    }
+    if (isset($_GET['success1'])) {
+        if ($_GET['success1']==1) {
+            echo "<script>alert('Record Updated Successfully');</script>";
+        }
+        
+    }
+?>
+
+

(thats the bit with the error) +and this is my login page code:

+
<!DOCTYPE html>
+<html>
+
+<?php
+    include "config/MainClass.php";
+?>
+
+<?php if (isset($_POST['SubBtn'])) {
+    $to = $use->login($_POST['u'], $_POST['pw'], $_POST['em']);
+    if ($to == 0) {
+        ?>
+        <script type="text/javascript">alert('Undefined user')</script>
+        <meta http-equiv="refresh" content="0; ./login.php">
+    <?php } else {
+        echo "<script>location='./dashboard/';</script>";
+    }
+} ?>
+
+
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
+    <title>Login Form</title>
+    <link rel="stylesheet" href="asset/bootstrap/css/bootstrap.min.css">
+    <link rel="stylesheet" href="asset/fonts/ionicons.min.css">
+    <link rel="stylesheet" href="asset/css/Login-Form-Dark.css">
+    <link rel="stylesheet" href="asset/css/styles.css">
+</head>
+
+<body>
+    <div class="login-dark">
+        <form method="POST">
+            <h2 class="sr-only">Login Form</h2>
+            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
+            <div class="form-group"><input class="form-control" type="name" name="u" autocomplete="off" placeholder="Username"></div>
+            <div class="form-group"><input class="form-control" type="k" name="em" autocomplete="off" placeholder="Email"></div>
+            <div class="form-group"><input class="form-control" type="password" name="pw" autocomplete="off" placeholder="Password"></div>
+            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" name="SubBtn">Login</button></div><a class="forgot" href="signup.php">Dont have an account? Sign Up!</a></form>
+    </div>
+    <script src="asset/js/jquery.min.js"></script>
+    <script src="asset/bootstrap/js/bootstrap.min.js"></script>
+</body>
+
+</html>
+
+

and the main class one is:

+
<?php
+session_start([1]);
+
+class MainClass
+{
+    function __construct()
+    {
+
+        
+        $host_name = 'aaaaaaaaaaaa';
+           $database = 'aaaaaaaaaaaaaa';
+           $user_name = 'aaaaaaaaaaaaa';
+           $password = 'aaaaaaaaaa';
+
+
+        
+        try {
+            $this->db = new PDO('mysql:host=aaaaaaaaaaaaaaa;dbname=aaaaaaaaaaaa', $user_name, $password);
+        } catch (PDOException $e) {
+            print "Error!: " . $e->getMessage() . "<br/>";
+            die();
+        }
+        
+    
+    }
+
+    function login($user, $pw, $em)
+    {
+
+        $to = $this->db->query("SELECT * FROM users where username='$user' AND password='$pw' AND email='$em' ");
+        if ($to->rowCount() > 0) {
+            $_SESSION['admin'] = $to->fetch(PDO::FETCH_ASSOC);
+            return 1;
+        } else {
+            return 0;
+        }
+
+    }
+
+}
+
+
+
+$use = new MainClass();
+
+
+

and it all works but when you login it redirects you to the index.php page but instantly redirects you back? it meant to only redirect you if your not logged in.

+

Anyone know how to fix this??

","

First remove session_start(); from index.php and in MainClass.php change it from session_start([1]); to simply session_start();

+

and also change empty($_SESSION['admin']) to !isset($_SESSION['admin']) in index.php

+

This way it worked for me (assuming the login() function was working correctly) and asigned a value to admin session

+

I also didn't check it with a database only with raw data but it shouldn't work much differently.

+

One last advice change query() to prepare() (prepared statements) in MainClass login() function. Passing data directly to the database without properly sanitazing it is extremly dangerous and will lead to SQL Injections.

+

Edit:

+

Do you mind copying and pasting once the edited code below ? +I've commented the changes I made. +Also make sure you are typing in correct login information

+

index.php

+
<?php
+
+include "../config/MainClass.php";
+include "../connection.php";
+
+if (!$_SESSION['logged_in']) {  // changed session name "admin" to "logged_in" as it makes more sense. 
+    // And also now the session will hold only boolean (true/false) values, so it's easier to check
+
+    echo "<script>location='./login.php'</script>"; // header("Location: login.php"); would also be an option 
+    // die("reached here");  // For debugging
+}
+if (isset($_GET['logout'])) {
+    unset($_SESSION['logged_in']);
+    echo "<script>location='./login.php'</script>";
+    // die("reached here below"); // For debugging
+}
+if (isset($_GET['success'])) {
+    if ($_GET['success'] == 1) {
+        echo "<script>alert('Record Deleted Successfully');</script>";
+    }
+}
+if (isset($_GET['success1'])) {
+    if ($_GET['success1'] == 1) {
+        echo "<script>alert('Record Updated Successfully');</script>";
+    }
+}
+
+

MainClass.php

+
<?php
+session_start();
+
+class MainClass
+{
+    protected $db; // This was missing here since you used it below but it didn't exist in the class
+
+    
+    function __construct()
+    {
+        // Make sure to put your db connection details here 
+        $hostName = 'localhost';
+        $database = 'testDB';
+        $userName = 'root';
+        $password = '';
+
+
+
+        try {
+            // Don't hardcode your db connection details here like before. Instead type them in the variable above or you can even put them in a config file 
+            $this->db = new PDO('mysql:host=' . $hostName . ';dbname=' . $database . '', $userName, $password);
+        } catch (PDOException $e) {
+            print "Error!: " . $e->getMessage() . "<br/>";
+            die();
+        }
+    }
+
+    function login($user, $pw, $em)
+    {
+
+        // Used prepared statements instead of query() because it's more secure
+        $to = $this->db->prepare("Select * from users where username=:user and password=:pw and email=:em");
+        $to->bindParam(":user", $user);
+        $to->bindParam(":pw", $pw);
+        $to->bindParam(":em", $em);
+        $to->execute(); // Execute the query above
+
+        $rowNum = $to->rowCount();
+
+        if ($rowNum) { // check if there are any results for your query
+            $_SESSION["logged_in"] = true; // assign a true value inside the "Logged_in" session
+            return true;
+        }
+
+        return false; // Return false if something went wrong
+    }
+}
+
+
+
+$use = new MainClass();
+
+
+

login.php

+
<!DOCTYPE html>
+<html>
+
+<?php
+include "config/MainClass.php";
+
+if (isset($_POST['SubBtn'])) {
+    $to = $use->login($_POST['u'], $_POST['pw'], $_POST['em']);
+    if ($to == 0) {
+?>
+        <script type="text/javascript">
+            alert('Undefined user')
+        </script>
+        <meta http-equiv="refresh" content="0; ./login.php">
+<?php } else {
+        echo "<script>location='./index.php';</script>";
+    }
+} ?>
+
+
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
+    <title>Login Form</title>
+    <link rel="stylesheet" href="asset/bootstrap/css/bootstrap.min.css">
+    <link rel="stylesheet" href="asset/fonts/ionicons.min.css">
+    <link rel="stylesheet" href="asset/css/Login-Form-Dark.css">
+    <link rel="stylesheet" href="asset/css/styles.css">
+</head>
+
+<body>
+    <div class="login-dark">
+        <form method="POST">
+            <h2 class="sr-only">Login Form</h2>
+            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
+            <div class="form-group"><input class="form-control" type="name" name="u" autocomplete="off" placeholder="Username"></div>
+            <div class="form-group"><input class="form-control" type="k" name="em" autocomplete="off" placeholder="Email"></div>
+            <div class="form-group"><input class="form-control" type="password" name="pw" autocomplete="off" placeholder="Password"></div>
+            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" name="SubBtn">Login</button></div><a class="forgot" href="signup.php">Dont have an account? Sign Up!</a>
+        </form>
+    </div>
+    <script src="asset/js/jquery.min.js"></script>
+    <script src="asset/bootstrap/js/bootstrap.min.js"></script>
+</body>
+
+</html>
+
",html +"Can anyone help me with this issue - Django View (Passing of keys)

I have the following views:

+
def device_port(request):
+    devices = Device.objects.all()
+    if request.method == "POST":
+        selected=request.POST.get('device')
+        devices = Device.objects.get(pk=selected)        
+        tablename = 'dev_interface_'+selected
+        print("tablename: " +tablename)
+        cursor=connection.cursor()
+        cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2")
+        righttable = cursor.fetchall()         
+        return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} )        
+    return render(request, 'interface/device_port.html',{'devices':devices})
+
+def device_port_selected(request, pk):    
+    if request.method == "POST":
+        job = JobForm(request.POST)
+        device = devices.hostname
+        print(devices)
+        #job.associateddevice = devices.hostname
+        try:
+            selection=request.POST.get('portrange')
+        except:
+            selection = ""
+            messages.warning(request, "Please select the ports")
+        print(selection)
+        #job.associatedinterface = selection
+        return render(request, 'interface/device/port/selected/'+device+'.html',{'devices':devices, 'righttable':righttable} )        
+    return render(request, 'interface/device_port_selected.html',{'devices':devices, 'selected': selected, 'righttable':righttable} )
+
+

urls.py

+
urlpatterns = [
+    path('', views.home, name='interface-home'),
+    path('device/', DeviceListView.as_view(), name='interface-device'),
+    path('device_edit/<int:pk>/', views.device_edit, name='device-edit'),
+    path('device_delete/<int:pk>/', views.device_delete, name = 'device-delete'),
+    path('device_add/', views.device_add, name='device-add'),
+    path('device/port/', views.device_port, name='device-port'),
+    path('device/port/selected/', views.device_port_selected, name='device-port-selected'),
+    path('device/routeport/', views.device_routeport, name='device-routeport'),
+    path('interface/', views.interface_list, name='interface-list')
+]
+
+

device_port.html

+
<form method="POST">
+ <div class="form-row align-items-center">
+  <div class="col-md-5 my-1">                                                 
+   {% csrf_token %}
+   <label for="Hostname">Hostname</label>
+    <div class="input-group">
+     <select id = "list" class="custom-select mr-sm-2"  onchange="getSelectValue();">
+      <option selected>Select</option>
+      {% for device in devices %}
+       <option value={{device.id}}>{{device.hostname}}</option>
+      {%endfor%}
+      </select>
+      <div class="input-group-append">                                                                            
+       <button class="btn btn-outline-secondary" type="submit">Go</button>
+      </div>
+     </div>
+    </div>                                                              
+   </div>                                                                                                                  
+  <input type ="text" name="device" id= "txtvalues" style="display:none">
+</form>
+
+

So there are 2 page I am dealing with over here (/device/port and /device/port/selected). In this first page /device/port, user is required to pick a value from the drop down box and press the button Go. From here, it is intended to go to the next page which is /device/port/selected with the selected value in the first page pass to the next page.

+

But with the following code, I receive the error of

+
device_port_selected() missing 1 required positional argument: 'pk'
+
+

when moving from the first page to the next page.

","

You can't pass a context dictionary to a redirect. The second argument should be the URL arguments, not a context. So change the following line:

+
return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} )
+
+

to

+
return redirect('device-port-selected', pk=selected)
+
+

Note that it is better to use the name of the URL (i.e. device-port-selected) instead of the whole path as you can change paths in the future without affecting the rest of your code.

",html +"Border Bottom makes Material UI icons smaller when hovered

I'm working on this React app where the header have some Material UI icons. I have been trying to apply a border which would show at the bottom of the headen when hovered on each icon. But right now the borders are really close to each of their respective icons.

+

Another issue is the icons get smaller when hovered. I have been trying for hours now to fix it but nothing seems to work.

+

The icons should have 1.6rem of font size and the border must be 4px. How can I fix it?

+

Here's the CodeSandbox.

+

Here's the code for the Header Component:

+
import React from "react";
+import "./Header.css";
+import PowerSettingsNewIcon from "@mui/icons-material/PowerSettingsNew";
+import SettingsIcon from "@mui/icons-material/Settings";
+
+const Header = () => {
+  return (
+    <header className="header">
+      <div className="header__leftContainer">
+        <h1>Logo</h1>
+      </div>
+
+      <div className="header__rightContainer">
+        <SettingsIcon className="header__rightContainer__icons" />
+        <PowerSettingsNewIcon className="header__rightContainer__icons" />
+      </div>
+    </header>
+  );
+};
+
+export default Header;
+
+

Here's the css:

+
.header {
+  width: 100%;
+  background: yellow;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+}
+
+.header__leftContainer,
+.header__rightContainer {
+  padding: 15px 40px;
+}
+
+.header__leftContainer h1 {
+  color: red;
+}
+
+.header__rightContainer svg {
+  font-size: 1.6rem;
+  margin: 0 15px;
+  cursor: pointer;
+}
+
+.header__rightContainer svg:last-child {
+  margin: 0 !important;
+}
+
+.header__rightContainer svg:hover {
+  border-bottom: 4px solid blue;
+}
+
+
","

Instead of applying padding to your left and right container, set a fix height of your header. Try this:

+
.header {
+  width: 100%;
+  background: yellow;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  height: 4rem;
+}
+
+.header__leftContainer,
+.header__rightContainer {
+  height: 100%;
+  display: flex;
+}
+
+.header__leftContainer h1 {
+  color: red;
+}
+
+.header__rightContainer svg {
+  font-size: 1.6rem;
+  margin: 0 15px;
+  cursor: pointer;
+  height: 100%;
+  border-bottom: 4px solid transparent;
+}
+
+.header__rightContainer svg:last-child {
+  
+}
+
+.header__rightContainer svg:hover {
+  border-bottom: 4px solid blue;
+}
+
",html +"css - unexpected position of span in side a content area

I am using react-pro-sidebar as the side bar.

+
export default function App() {
+  return (
+    <div className="App">
+      <NavBar />
+      <span>Why is this span here?</span>
+    </div>
+  );
+}
+
+

What I am expecting: +

+

But actually: +

+

CodeSandbox:
+https://codesandbox.io/s/ecstatic-mayer-dhem4?file=/src/Navbar/index.js

+

Update 1
+Why wouldn't it happen in the demo?
+https://azouaoui-med.github.io/react-pro-sidebar/

","

Nikola is correct but its important to understand why this is happening. I assume NavBar is a display block element, and in that case it will take up the full available width. Therefor the span element will end up being rendered under it.

+

One of the possible solutions is to make their container's display property be flex

",html +"Insert link and meta tags in HTML head using .htaccess

I have several HTML pages that use the following tags in the <head>. To reduce file size, I instead want to add the tags using .htaccess:

+
<link type='image/x-icon' rel='shortcut icon' href='images/favicon.ico' />
+<link rel='apple-touch-icon' sizes='180x180' href='apple-touch-icon.png'>
+<link rel='icon' type='image/png' sizes='32x32' href='favicon-32x32.png'>
+<link rel='icon' type='image/png' sizes='16x16' href='favicon-16x16.png'>
+<link rel='manifest' href='site.webmanifest'>
+<link rel='mask-icon' href='safari-pinned-tab.svg' color='#000'>
+<meta name='msapplication-tilecolor' content='#000' />
+<meta name='theme-color' content='#ffffff' />
+<link rel='stylesheet' href='css/styles.css' />
+
+

I tried searching online but haven't found any information if this is possible. How can I insert the tags above in the <head> of each page using .htaccess?

","

.htaccess filters and modifies http requests, not handle them. To handle a request server side, you should use a server-side language such as php to make changes to html files.

+

To reduce file size, you should use built-in compression tools (in .htaccess). This consistently reduce html sizes by over 60% from minified html.

+
<IfModule mod_deflate.c>
+AddOutputFilterByType DEFLATE [ ]
+</IfModule>
+
+

and replace [ ] with the desired content-type

+

To add the same <head> tags client-side, you can write a writeHead.js file to write html elements: How to add DOM element script to head section?. Then in your <head> manually add

+
<script type="text/javascript" src="writeHead.js">
+
+

Final note, this js "blocks" DOM loading as the browser must load the file completely before loading additional elements. Performance-wise, it's better to keep the html as is instead of using browser resources to generate elements you know will be there 100%. This would lead to non-tangible file size savings in exchange for perhaps a tangibly longer loading time.

",html +"HTML table cell column mixing fixed widths + percentages

I want to do something very basic, a table with 4 columns: 2 columns should be 50px each, the other 2 columns should take 50% of the remaining space each.

+

I'm surprised to find out that calc() does not work for setting width on table cells. So doing something like td { width: calc(50% - 100px); } is not a possibility.

+

Is there a way to achieve this with the table element or is using another layout method like flexbox the only choice?

","

Width calculation for tables is a bit clunky, but can be improved by using table-layout: fixed because then cell widths will no longer be calculated based on what's inside the cells. And then you may not even need calc() anymore, although you definitely can.

+

It should also be noted that a table by default takes up the least width possible, it usually gets better if we tell the table to use 100% width (or whatever is needed in your case).

+

width: 100% combined with table-layout: fixed and no calc() gives the following results:

+

+
+
table {
+  width: 100%;
+  table-layout: fixed;
+}
+
+td {
+  background: #eee;
+  height: 70px;
+}
+
+td.fixed {
+  width: 50px;
+}
+
+td.rest {
+  width: 50%;
+  background: #fca;
+}
+
<table>
+  <tbody>
+    <tr>
+      <td class=""fixed"">1</td>
+      <td class=""fixed"">234</td>
+      <td class=""rest"">a</td>
+      <td class=""rest"">bcd efg</td>
+    </tr>
+  </tbody>
+</table>
+
+
+

",html +"bootstrap modal wont open on page load

My bootstrap modal wont open on page load I do not know why. +The button to open the modal works tho.

+

My code:

+
<div id="myModal" class="modal fade" role="dialog">
+            <div class="modal-dialog">
+                <div class="modal-content">
+                <div class="modal-header">
+                    <button type="button" class="close" data-dismiss="modal">&times;</button>
+                    <h4 class="modal-title">Modal Header</h4>
+                  </div>
+                  <div class="modal-body">
+                    <p>Some text in the modal.</p>
+                  </div>
+                  <div class="modal-footer">
+                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
+                  </div>
+            </div>
+            </div>
+        </div>
+
+    window.onload = function() {
+                $('#myModal').modal('show');
+    }
+
","

Your case may be already answered thousand times, but consider few these causes:

+
    +
  1. Order of your libraries, are they in correct position?
  2. +
  3. Perhaps you forget to include bootstrap.js
  4. +
  5. Consider to include popper.js +Please let me know, if it helps
  6. +
",html +"How to get value of nested img src with Html Agility Pack?

I'm trying to get a nested img srcs with Html Agility pack and I've tried multiple things with no success. Basically there are multiple img srcs I need to grab, all are nested. There are 17 of these I need to grab but can't figure it out for the life of me. Here is the barebones html, I need the value of src in the last line:

+
<div class="largeTitle">
+    <article class="articleItem" data-id="0000">
+       <a href="#blank_link"> class="img">
+         <img class=" lazyloaded" data-src="#blank_link" alt="test" onerror="script" 
+          src="image_link.jpg">
+</a>
+</article>
+
+<article class="articleItem" data-id="0001">
+       <a href="#blank_link"> class="img">
+         <img class=" lazyloaded" data-src="#blank_link" alt="test" onerror="script" 
+          src="image_link.jpg">
+</a>
+</article>
+</div>
+
","

With the url you mentioned in comments, you can do:

+
var web = new HtmlWeb();
+var doc = web.Load("https://www.investing.com/");
+var images = doc.DocumentNode.SelectNodes("//*[contains(@class,'js-articles')]//a[@class='img']//img");
+        
+foreach(var image in images)
+{
+    string source = image.Attributes["data-src"].Value;
+    string label = image.Attributes["alt"].Value;
+    Console.WriteLine($"\"{label}\" {source}");
+}
+
",html +"How to make scroll for inner block?

I have a children block .body I need to make vertiacal scroll if contant is not fit to the parent #container. Just scroll content inside .body and dont scroll .header.

+

+
+
#container {
+  min-height: fit-content;
+  max-height: 50%;
+  overflow-y: auto;
+  border: 1px solid red;
+  overflow: hidden;
+}
+
+.body {
+  overflow-y: scroll;
+  height: inherit;
+}
+
+.item {
+  padding: 20px;
+  height: 70px;
+  border-bottom: 1px solid #ccc
+}
+
<div id=""container"">
+  <div>
+    Header
+  </div>
+  <div class=""body"">
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+  </div>
+</div>
+
+
+

+

My full code is:

","

In order to make .body scrollable, you have to assign it a definite height.

+

That, in turn, means that you have to assign #container with a definite height:

+

+
+
#container {
+  height: 50vh;
+  border: 1px solid red;
+  overflow: hidden;
+}
+
+.body {
+  overflow-y: scroll;
+  height: inherit;
+}
+
+.item {
+  padding: 20px;
+  height: 70px;
+  border-bottom: 1px solid #ccc
+}
+
<div id=""container"">
+  <div>
+    Header
+  </div>
+  <div class=""body"">
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+    <div class=""item"">
+      Item
+    </div>
+  </div>
+</div>
+
+
+

",html +"Uncaught ReferenceError: $ is not defined problem

I've tried pasting the code copied from the code pen site below in the vault, but it doesn't work. I wonder why it's not working. What do I have to do to make it work? The CSS source code was imported using Viw compiled. Does this matter?

+

Code Pen Address +https://codepen.io/dodozhang21/pen/vNOmrv

+

Error :

+
249 Uncaught ReferenceError: $ is not defined
+
+

It says this is the problem.

+
var $form = $("#imageUploadForm"),
+
+

Paste Source Code

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Title</title>
+</head>
+<style>
+    @import url(https://fonts.googleapis.com/css?family=Nunito);
+@import url(//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css);
+*,
+*:before,
+*:after {
+  -moz-box-sizing: border-box;
+  -webkit-box-sizing: border-box;
+  box-sizing: border-box;
+}
+
+html {
+  height: 100%;
+}
+
+body {
+  background: #ffd16e;
+  height: 100%;
+  padding: 0;
+  margin: 0;
+  font-size: 16px;
+  display: -webkit-flex;
+  display: flex;
+  -webkit-align-items: center;
+  align-items: center;
+  -webkit-justify-content: center;
+  justify-content: center;
+}
+
+.uploadWrapper {
+  font-family: "Nunito", sans-serif;
+}
+
+.imageUploadForm {
+  background: #6e95f7;
+  height: 400px;
+  width: 500px;
+  position: relative;
+  display: -webkit-flex;
+  display: flex;
+  -webkit-align-items: flex-end;
+  align-items: flex-end;
+  -webkit-justify-content: center;
+  justify-content: center;
+  -webkit-flex-wrap: wrap;
+  flex-wrap: wrap;
+}
+.imageUploadForm .helpText {
+  color: white;
+  display: block;
+  position: absolute;
+  top: 2%;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  text-align: center;
+  font-size: 30px;
+}
+.imageUploadForm .helpText:after {
+  content: "\f067";
+  font-family: "FontAwesome";
+  font-size: 150%;
+  color: rgba(255, 255, 255, 0.5);
+  display: -webkit-flex;
+  display: flex;
+  -webkit-align-items: center;
+  align-items: center;
+  -webkit-justify-content: center;
+  justify-content: center;
+  margin: 4% auto auto auto;
+  width: 50%;
+  height: 50%;
+  border: 6px dashed rgba(255, 255, 255, 0.5);
+}
+.imageUploadForm .pickFile {
+  position: absolute;
+  bottom: 0;
+  left: 0;
+  display: block;
+  background: white;
+  height: 25%;
+  width: 100%;
+  display: -webkit-flex;
+  display: flex;
+  -webkit-align-items: center;
+  align-items: center;
+  -webkit-justify-content: center;
+  justify-content: center;
+}
+.imageUploadForm .pickFileButton {
+  display: inline-block;
+  padding: 0.7em 2em;
+  color: white;
+  background: #fb92ae;
+  text-decoration: none;
+}
+.imageUploadForm .pickFileButton:hover {
+  text-decoration: none;
+}
+.imageUploadForm .uploadButton {
+  position: absolute;
+  top: 0;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  opacity: 0;
+  cursor: pointer;
+  z-index: 10;
+}
+
+.imageUploadForm.loading .helpText {
+  font-size: 0;
+  top: 7%;
+}
+.imageUploadForm.loading .helpText:before {
+  font-size: 30px;
+  content: "Uploading...";
+}
+.imageUploadForm.loading .helpText:after {
+  display: none;
+}
+.imageUploadForm.loading .uploadedImg {
+  position: absolute;
+  bottom: 12.5%;
+  left: 12.5%;
+  width: 75%;
+  height: 65%;
+  background-repeat: no-repeat;
+  background-position: center center;
+  background-size: cover;
+  border: 4px solid white;
+  -moz-transition: opacity ease-out;
+  -o-transition: opacity ease-out;
+  -webkit-transition: opacity ease-out;
+  transition: opacity ease-out;
+}
+.imageUploadForm.loading .unveil {
+  position: absolute;
+  background: #6e95f7;
+  display: block;
+  width: 100%;
+  height: 100%;
+  top: 0;
+  left: 0;
+  -moz-animation: toTop 4s forwards;
+  -webkit-animation: toTop 4s forwards;
+  animation: toTop 4s forwards;
+}
+.imageUploadForm.loading .unveil:after {
+  content: "";
+  position: absolute;
+  left: -3%;
+  bottom: 0;
+  height: 10px;
+  width: 106%;
+  background: #ffd16e;
+  border-radius: 5px;
+}
+.imageUploadForm.loading .pickFile,
+.imageUploadForm.loading .uploadButton {
+  display: none;
+}
+
+.imageUploadForm.loading.loaded {
+  height: 200px;
+}
+.imageUploadForm.loading.loaded .uploadedImg {
+  opacity: 0;
+}
+.imageUploadForm.loading.loaded .helpText:before {
+  content: "Upload Complete!";
+}
+.imageUploadForm.loading.loaded .helpText:after {
+  display: block;
+  opacity: 0;
+  font-size: 0;
+  line-height: 100px;
+  -moz-animation: fadeIn 0.4s forwards;
+  -webkit-animation: fadeIn 0.4s forwards;
+  animation: fadeIn 0.4s forwards;
+  content: "\f058";
+  color: white;
+  margin-top: 2%;
+  border-width: 0;
+}
+
+@-moz-keyframes toTop {
+  to {
+    height: 0;
+  }
+}
+@-webkit-keyframes toTop {
+  to {
+    height: 0;
+  }
+}
+@keyframes toTop {
+  to {
+    height: 0;
+  }
+}
+@-moz-keyframes fadeIn {
+  to {
+    opacity: 1;
+    font-size: 90px;
+  }
+}
+@-webkit-keyframes fadeIn {
+  to {
+    opacity: 1;
+    font-size: 90px;
+  }
+}
+@keyframes fadeIn {
+  to {
+    opacity: 1;
+    font-size: 90px;
+  }
+}
+
+</style>
+
+<body>
+<div class="uploadWrapper">
+  <form id="imageUploadForm" class="imageUploadForm">
+    <span class="helpText" id="helpText">Upload an image</span>
+    <input type='file' id="file" class="uploadButton" accept="image/*" />
+    <div id="uploadedImg" class="uploadedImg">
+      <span class="unveil"></span>
+    </div>
+    <span class="pickFile">
+      <a href="#" class="pickFileButton">Pick file</a>
+    </span>
+      <script>
+          function readURL(input) {
+  if (input.files && input.files[0]) {
+    var reader = new FileReader();
+
+    reader.onload = function (e) {
+      $uploadedImg[0].style.backgroundImage = "url(" + e.target.result + ")";
+    };
+
+    reader.readAsDataURL(input.files[0]);
+  }
+}
+
+var $form = $("#imageUploadForm"),
+  $file = $("#file"),
+  $uploadedImg = $("#uploadedImg"),
+  $helpText = $("#helpText");
+$file.on("change", function () {
+  readURL(this);
+  $form.addClass("loading");
+});
+$uploadedImg.on(
+  "webkitAnimationEnd MSAnimationEnd oAnimationEnd animationend",
+  function () {
+    $form.addClass("loaded");
+  }
+);
+$helpText.on(
+  "webkitAnimationEnd MSAnimationEnd oAnimationEnd animationend",
+  function () {
+    setTimeout(function () {
+      $file.val("");
+      $form.removeClass("loading").removeClass("loaded");
+    }, 5000);
+  }
+);
+
+      </script>
+  </form>
+</div>
+</body>
+</html>
+
","

I think is becaus you have to import Jquery. +Place this in your HTML +<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

",html +"How to create linear gradient using SCSS variables?

I am trying to create a linear gradient using scss variables. Here is what I have tried.

+
$colour__social--ig:  linear-gradient(#fdc468 to #ee867c to #df4996);
+
+

and then I am assigning the colour to .wrapper class.

+
background-color: $colour__social--ig;
+
+

BUT I have no idea why this is not working.

",

A gradient doesn't work as a background-color. Use the background property instead.

,html +"How do you get the selected directory path from file system access api window.showDirectoryPicker()

When I choose a folder I do get a dirHandle but cannot figure out what property or method will give me the full path

+
const dirHandle = await window.showDirectoryPicker()
+
+

So something like let path = dirHandle.fullpath

+

Any ideas?

","

For security reasons the full path will not be revealed to web applications. You can only learn the relative paths by walking through a directory. In the example below, if the user opens shared/, you can learn about the existence of ./public and ./public/file.txt inside of it, but not that shared/ lies in secret/ and further up.

+
/root/secret/shared/public/file.txt
+
",html +"Scraping data from Zillow.com using BeautifulSoup

Following this tutorial, I am trying to extract basic property information from zillow.com. More specifically, I want to extract the information pertinent to property cards displayed on the website.

+

+

The following code is able to extract information of only 3 properties, even though several property cards exist on the first page. Can someone please explain why is the code skipping the remaining properties?

+
import requests
+import ast
+from bs4 import BeautifulSoup
+
+url = 'https://www.zillow.com/homes/for_sale/house,multifamily,townhouse_type/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-106.43826441618356%2C%22east%22%3A-103.36483912321481%2C%22south%22%3A38.903882034738686%2C%22north%22%3A40.52008627183672%7D%2C%22mapZoom%22%3A9%2C%22customRegionId%22%3A%22fcac4612c1X1-CR9xde3hldsvpa_v24ah%22%2C%22isMapVisible%22%3Afalse%2C%22filterState%22%3A%7B%22hoa%22%3A%7B%22max%22%3A200%7D%2C%22con%22%3A%7B%22value%22%3Afalse%7D%2C%22apa%22%3A%7B%22value%22%3Afalse%7D%2C%22sch%22%3A%7B%22value%22%3Atrue%7D%2C%22ah%22%3A%7B%22value%22%3Atrue%7D%2C%22sort%22%3A%7B%22value%22%3A%22globalrelevanceex%22%7D%2C%22land%22%3A%7B%22value%22%3Afalse%7D%2C%22schu%22%3A%7B%22value%22%3Afalse%7D%2C%22manu%22%3A%7B%22value%22%3Afalse%7D%2C%22schr%22%3A%7B%22value%22%3Afalse%7D%2C%22apco%22%3A%7B%22value%22%3Afalse%7D%2C%22basf%22%3A%7B%22value%22%3Atrue%7D%2C%22schc%22%3A%7B%22value%22%3Afalse%7D%2C%22schb%22%3A%7B%22min%22%3A%227%22%7D%7D%2C%22isListVisible%22%3Atrue%7D'
+
+headers = {
+            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
+            'accept-encoding': 'gzip, deflate, br',
+            'accept-language': 'en-US,en;q=0.9',
+            'cookie': 'zguid=23|%24ca6368b9-7b92-4d51-ab67-c2be89065efd; _ga=GA1.2.1460486079.1621047110; _pxvid=7fa13d96-b528-11eb-9860-0242ac120012; _gcl_au=1.1.2025797213.1621047113; __gads=ID=66253ab863481044:T=1621047113:S=ALNI_MZr3mehwm2Wjo7NOrmalVtEcJSXag; __pdst=50987f626deb4767a53b5d8ca2ea406a; _fbp=fb.1.1621047115574.1019382068; _pin_unauth=dWlkPU5EVm1PRGRpTVRBdE5UTTFaUzAwWlRBNExUZzJZall0TWpZMU1HWTBNV0ppWlRkbA; G_ENABLED_IDPS=google; userid=X|3|231a9d744e104379%7C3%7CiEt8bkUx9hWaFeyCeAwN9tHl_T0d0Cq-kynGuEvNYr4%3D; loginmemento=1|c2274ba4a4ad76bbe89263d30695c182e9177b9c40a2691f3054987d66a944be; zjs_user_id=%22X1-ZU158jhpb2klds9_4wzn7%22; zgcus_lbut=; zgcus_aeut=189997416; zgcus_ludi=b44a961b-c7ef-11eb-a48f-96824e7eff50-18999; optimizelyEndUserId=oeu1623111792776r0.8778663892923859; _cs_c=1; WRUIDAWS=3326630244368428; visitor_id701843=248614376; visitor_id701843-hash=4be116fbd77089f953bfb6eaf5996ef92662a6ef7d237d3c49f154ffaf4eaa9295c64fb254b106bdff234e183c94498c01af2aab; __stripe_mid=80125db1-17d1-4fc5-ae37-86b12a68709cf3da6d; g_state={"i_p":1627697570928,"i_l":4}; zjs_anonymous_id=%22ca6368b9-7b92-4d51-ab67-c2be89065efd%22; _gac_UA-21174015-56=1.1626042638.Cj0KCQjwraqHBhDsARIsAKuGZeH8gi095UkXfohW-WWvyLosdmTdL8cfJwgAabYF9hS2XU6JlXqpWLcaAq5SEALw_wcB; _gcl_aw=GCL.1626042640.Cj0KCQjwraqHBhDsARIsAKuGZeH8gi095UkXfohW-WWvyLosdmTdL8cfJwgAabYF9hS2XU6JlXqpWLcaAq5SEALw_wcB; zgsession=1|1edd82e6-372a-4546-bc8b-c2bbadfd29b4; DoubleClickSession=true; fbc=fb.1.1626412984774.IwAR2QM6bzrTskAWN5Sk8UnmPlAxb1HRy1h1GRch888QqXfczHZZWb2vDZfIw; _fbc=fb.1.1626413249162.IwAR2QM6bzrTskAWN5Sk8UnmPlAxb1HRy1h1GRch888QqXfczHZZWb2vDZfIw; _csrf=lV2BBFim7Vy2gFTn--PUt0VA; _gaexp=GAX1.2.w27igyYtRQaAa8XQM3MjDw.18837.2!VDVoDKTnRcyv8f4FAcJ8PA.18915.2!Khnq27RoQmSe5DEusmh5xA.18913.3; _gid=GA1.2.705011419.1630004829; FSsampler=707279376; __CT_Data=gpv=26&ckp=tld&dm=zillow.com&apv_82_www33=26&cpv_82_www33=26&rpv_82_www33=13; OptanonConsent=isIABGlobal=false&datestamp=Fri+Aug+27+2021+12%3A39%3A52+GMT-0600+(Mountain+Daylight+Time)&version=5.11.0&landingPath=NotLandingPage&groups=1%3A1%2C3%3A1%2C4%3A1&AwaitingReconsent=false; _cs_id=41cbdc9c-bb0b-aad9-9521-b1328a65ff77.1623111795.22.1630089665.1630089591.1.1657275795752; utag_main=v_id:01796deff9e3001a59964343177e03079002907100838$_sn:41$_se:2$_ss:0$_st:1630255637884$dc_visit:38$ses_id:1630253822479%3Bexp-session$_pn:1%3Bexp-session$dcsyncran:1%3Bexp-session$tdsyncran:1%3Bexp-session$dc_event:2%3Bexp-session$dc_region:us-east-1%3Bexp-session$ttd_uuid:7b8796ca-44dd-45c9-97d9-bcb642d04cd1%3Bexp-session; JSESSIONID=6CB8C410E0FE216644E8C3A0D0851618; ZILLOW_SID=1|AAAAAVVbFRIBVVsVEklf443J474nftKzJe5PKLD80sujgHvySB7tGcqZunX3BDDH9VwceMqGMTPC54%2F0q4CH%2BfmwsC6P; KruxPixel=true; _derived_epik=dj0yJnU9ai1PSUp1eHZ2Y3J3d0c2NVU1N3BBOFlHbnRBOGFzT0smbj1vLWRISDFwdUNoblN5MjQ4cTVyN213Jm09MSZ0PUFBQUFBR0VzRjRVJnJtPTEmcnQ9QUFBQUFHRXNGNFU; KruxAddition=true; search=6|1632872450375%7Crect%3D40.241821806991595%252C-103.77545313688668%252C39.18758562803622%252C-106.02765040251168%26disp%3Dmap%26mdm%3Dauto%26type%3Dhouse%252Cmultifamily%252Ctownhouse%26fs%3D1%26fr%3D0%26mmm%3D1%26rs%3D0%26ah%3D0%09%0911093%09%09%09%09%09%09; _uetsid=d5e0465006a011ecbe3bd1a0f1c47d01; _uetvid=987e1c70c40a11ebaed8859af36f82fb; _px3=ba45c3df5d5d63d4d9780a102253cd60b21ab52b04778344e332e05474011c21:oCvapPXE6jD0rCXhSf4UjtEC2U956148EDyiWwRFOF8z5vwK63/hC8OWsk09O61g1spnZw64iXApZu1wOmKpyA==:1000:68UzJ5+ar5XwNm61bm41bhSHp8Zp1PfQQlL/5tcqdUIJ3RmA106//vvYGewCCwmln6acqbDAVKgqfB8Th05yX0Cw0TBW7dhfNdeNRjp9bxeLvKqZ56yuW+aVoYYp/zj6MNKv9c16vKlP771xSdCgUTvZ0CDmh7Ng55sHugOHt/jj+2Zmp2WLnuYR4rf7SEndqWBbAyQhhG4BKeyrZyEMpA==; AWSALB=3BIj2fUDeYgoAcLKaZdMkcyTzWSof62v91DQuCssJMyknlpZWcRcVnUU5Me29AcnFcjg1k9H2ehS6N0rSwxo4w8lmEvFCy6hgQfKm1HH8oVoWtpICS36NoLMMxmZ; AWSALBCORS=3BIj2fUDeYgoAcLKaZdMkcyTzWSof62v91DQuCssJMyknlpZWcRcVnUU5Me29AcnFcjg1k9H2ehS6N0rSwxo4w8lmEvFCy6hgQfKm1HH8oVoWtpICS36NoLMMxmZ',
+            'referer': 'https://www.google.com/',
+            'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
+            'sec-ch-ua-mobile': '?1',
+            'sec-fetch-dest': 'document',
+            'sec-fetch-mode': 'navigate',
+            'sec-fetch-site': 'same-origin',
+            'upgrade-insecure-requests': '1',
+            'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36'
+          }
+
+params = {
+          'searchQueryState': '{"mapBounds":{"west":-106.02765040251168,"east":-103.77545313688668,"south":39.18758562803622,"north":40.241821806991595},"isMapVisible":true,"filterState":{"sort":{"value":"globalrelevanceex"},"ah":{"value":true},"con":{"value":false},"apco":{"value":false},"land":{"value":false},"apa":{"value":false},"manu":{"value":false},"basf":{"value":true},"hoa":{"max":200},"sch":{"value":true},"schb":{"min":"7"},"schc":{"value":false},"schr":{"value":false},"schu":{"value":false}},"isListVisible":true,"mapZoom":9,"customRegionId":"fcac4612c1X1-CR9xde3hldsvpa_v24ah","pagination":{}}'
+          }
+
+
+
+class ZillowScraper:
+
+    def __init__(self, url, headers, params):
+
+        self.headers = headers
+        self.url = url
+        self.params = params
+
+
+    def fetch(self):
+
+        response = requests.get(url=self.url, headers=self.headers, params=self.params)
+        return response
+
+
+    def get_cards_info(self, deck_text):
+
+        urls = []
+
+        for card in deck_text.contents:
+
+            script = card.find('script', {'type': 'application/ld+json'})
+
+            if script:
+                script_json = ast.literal_eval(str(script.contents[0]))
+                print(script_json)
+
+
+
+    def parse(self, response_text):
+
+        content = BeautifulSoup(response_text, features="html.parser")
+
+        deck_text = content.find('ul', {'class': 'photo-cards photo-cards_wow photo-cards_short photo-cards_extra-attribution'})
+
+        cards_info = self.get_cards_info(deck_text)
+
+
+
+    def run(self):
+
+        response = self.fetch()
+        self.parse(response.text)
+
+
+
+if __name__ == "__main__":
+
+    scraper = ZillowScraper(url, headers, params)
+    scraper.run()
+
+
+

OUTPUT

+
{'@type': 'SingleFamilyResidence', '@context': 'http://schema.org', 'name': '11615 River Run Cir, Henderson, CO 80640', 'floorSize': {'@type': 'QuantitativeValue', '@context': 'http://schema.org', 'value': '2,001'}, 'address': {'@type': 'PostalAddress', '@context': 'http://schema.org', 'streetAddress': '11615 River Run Cir', 'addressLocality': 'Henderson', 'addressRegion': 'CO', 'postalCode': '80640'}, 'geo': {'@type': 'GeoCoordinates', '@context': 'http://schema.org', 'latitude': 39.908753, 'longitude': -104.851576}, 'url': 'https://www.zillow.com/homedetails/11615-River-Run-Cir-Henderson-CO-80640/49457209_zpid/'}
+{'@type': 'SingleFamilyResidence', '@context': 'http://schema.org', 'name': '5089 Enid Way, Denver, CO 80239', 'floorSize': {'@type': 'QuantitativeValue', '@context': 'http://schema.org', 'value': '1,852'}, 'address': {'@type': 'PostalAddress', '@context': 'http://schema.org', 'streetAddress': '5089 Enid Way', 'addressLocality': 'Denver', 'addressRegion': 'CO', 'postalCode': '80239'}, 'geo': {'@type': 'GeoCoordinates', '@context': 'http://schema.org', 'latitude': 39.784449, 'longitude': -104.815903}, 'url': 'https://www.zillow.com/homedetails/5089-Enid-Way-Denver-CO-80239/13271929_zpid/'}
+{'@type': 'SingleFamilyResidence', '@context': 'http://schema.org', 'name': '6088 S Pierson Ct, Littleton, CO 80127', 'floorSize': {'@type': 'QuantitativeValue', '@context': 'http://schema.org', 'value': '1,810'}, 'address': {'@type': 'PostalAddress', '@context': 'http://schema.org', 'streetAddress': '6088 S Pierson Ct', 'addressLocality': 'Littleton', 'addressRegion': 'CO', 'postalCode': '80127'}, 'geo': {'@type': 'GeoCoordinates', '@context': 'http://schema.org', 'latitude': 39.605764, 'longitude': -105.123466}, 'url': 'https://www.zillow.com/homedetails/6088-S-Pierson-Ct-Littleton-CO-80127/13818492_zpid/'}
+
+
","

The results are stored in <script> variable inside the page. To parse them, you can use next example:

+
import json
+import requests
+from bs4 import BeautifulSoup
+
+
+url = "https://www.zillow.com/homes/for_sale/house,multifamily,townhouse_type/?searchQueryState={%22pagination%22%3A{}%2C%22mapBounds%22%3A{%22west%22%3A-106.97384791227731%2C%22east%22%3A-102.82925562712106%2C%22south%22%3A39.18758562803622%2C%22north%22%3A40.241821806991595}%2C%22customRegionId%22%3A%22fcac4612c1X1-CR9xde3hldsvpa_v24ah%22%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A{%22hoa%22%3A{%22max%22%3A200}%2C%22con%22%3A{%22value%22%3Afalse}%2C%22apa%22%3A{%22value%22%3Afalse}%2C%22sch%22%3A{%22value%22%3Atrue}%2C%22ah%22%3A{%22value%22%3Atrue}%2C%22sort%22%3A{%22value%22%3A%22globalrelevanceex%22}%2C%22land%22%3A{%22value%22%3Afalse}%2C%22schu%22%3A{%22value%22%3Afalse}%2C%22manu%22%3A{%22value%22%3Afalse}%2C%22schr%22%3A{%22value%22%3Afalse}%2C%22apco%22%3A{%22value%22%3Afalse}%2C%22basf%22%3A{%22value%22%3Atrue}%2C%22schc%22%3A{%22value%22%3Afalse}%2C%22schb%22%3A{%22min%22%3A%227%22}}%2C%22isListVisible%22%3Atrue}"
+headers = {
+    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
+}
+
+soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")
+
+data = json.loads(
+    soup.select_one("script[data-zrr-shared-data-key]")
+    .contents[0]
+    .strip("!<>-")
+)
+
+# uncomment this to print all data:
+# print(json.dumps(data, indent=4))
+
+for result in data["cat1"]["searchResults"]["listResults"]:
+    print(
+        "{:<15} {:<50} {:<15}".format(
+            result["statusText"], result["address"], result["price"]
+        )
+    )
+
+

Prints:

+
House for sale  6092 S Marshall Dr, Littleton, CO 80123            $680,000       
+House for sale  3050 S Roslyn St, Denver, CO 80231                 $774,900       
+House for sale  15538 Greenstone Cir, Parker, CO 80134             $590,000       
+House for sale  7141 Fenton Cir, Arvada, CO 80003                  $549,500       
+House for sale  7823 S Logan Dr, Littleton, CO 80122               $665,000       
+House for sale  1825 Clermont St, Denver, CO 80220                 $599,900       
+House for sale  408 S Locust St, Denver, CO 80224                  $550,000       
+House for sale  8660 De Soto St, Denver, CO 80229                  $450,000       
+House for sale  1811 S Humboldt St, Denver, CO 80210               $675,000       
+House for sale  7329 E Easter Ave, Centennial, CO 80112            $699,900       
+House for sale  13638 W Montana Pl, Lakewood, CO 80228             $600,000       
+House for sale  8296 E Hinsdale Dr, Centennial, CO 80112           $699,900       
+House for sale  10325 Ravenswood Ln, Highlands Ranch, CO 80130     $660,000       
+House for sale  2833 E 90th Pl, Denver, CO 80229                   $445,000       
+House for sale  5756 W 8th Ave, Lakewood, CO 80214                 $600,000       
+House for sale  6088 S Pierson Ct, Littleton, CO 80127             $509,000       
+House for sale  2829 S Lowell Blvd, Denver, CO 80236               $475,000       
+House for sale  604 Eldridge St, Golden, CO 80401                  $650,000       
+House for sale  7171 McIntyre Ct, Arvada, CO 80007                 $850,000       
+House for sale  1301 S Blackhawk Way, Aurora, CO 80012             $500,000       
+House for sale  215 S Julian St, Denver, CO 80219                  $350,000       
+House for sale  7095 E 67th Ave, Commerce City, CO 80022           $440,000       
+House for sale  8248 S Yukon St, Littleton, CO 80128               $695,000       
+House for sale  2846 S Macon Ct, Aurora, CO 80014                  $520,000       
+House for sale  9340 Burgundy Cir, Littleton, CO 80126             $799,000       
+House for sale  2072 S Cathay Way, Aurora, CO 80013                $560,000       
+House for sale  1317 W 85th Ave, Federal Heights, CO 80260         $405,000       
+House for sale  6701 Eagle Shadow Ave, Brighton, CO 80602          $1,145,000     
+House for sale  2900 Webster St, Wheat Ridge, CO 80033             $660,000       
+House for sale  3943 S Allison Ct, Lakewood, CO 80235              $799,950       
+House for sale  511 E Irwin Ave, Littleton, CO 80122               $624,500       
+House for sale  4700 E Montana Pl, Denver, CO 80222                $600,000       
+House for sale  2344 S Gray Dr, Lakewood, CO 80227                 $585,000       
+House for sale  5546 E 130th Dr, Thornton, CO 80241                $490,000       
+House for sale  2270 S Joyce St, Lakewood, CO 80228                $1,340,000     
+House for sale  12171 W Dakota Dr, Lakewood, CO 80228              $600,000       
+House for sale  6641 Miller St, Arvada, CO 80004                   $625,000       
+House for sale  3220 W Nevada Pl, Denver, CO 80219                 $510,000       
+House for sale  8630 W 64th Pl, Arvada, CO 80004                   $447,000       
+House for sale  5890 Wood Sorrel Dr, Littleton, CO 80123           $975,000       
+
",html +"Using findAll to extract text from Span Tag using Beautifulsoup returns an empty list

A beginner at web-scraping here. I'd like to extract "47" from the span class of the following HTML code:

+
<a href="https://www.walkscore.com/score/loc/lat=39.87797546386719/lng=-104.80396270751953/?utm_source=zillow2.com&amp;utm_medium=ws_api&amp;utm_campaign=ws_api" target="_blank" rel="nofollow" class="ws-value" aria-describedby="walk-score-text">
+   <span class="Text-c11n-8-48-0__sc-aiai24-0 hdp__sc-1af0wis-4 ifWvNt">
+       47
+   </span>
+</a>
+
+

I have tried this:

+

+from bs4 import BeautifulSoup
+import requests
+
+url = 'https://www.zillow.com/homedetails/9991-Joplin-St-Commerce-City-CO-80022/58649635_zpid/'
+headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"}
+
+soup = BeautifulSoup(requests.get(url, headers=headers).content, "html")
+
+info = soup.findAll('span', {'class': 'Text-c11n-8-48-0__sc-aiai24-0 hdp__sc-1af0wis-4 ifWvNt'})
+
+print(info)
+
+
+

But this returns an empty list. Can someone please help explain why?

","

The data you see ("Walk Score") is loaded dynamically via JavaScript. To get the value you can simulate Ajax request:

+
import requests
+
+api_url = "https://www.zillow.com/graphql/"
+
+property_id = 58649635
+
+headers = {
+    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
+}
+params = {"zpid": property_id, "operationName": "WalkAndTransitScoreQuery"}
+query = {
+    "clientVersion": "home-details/6.0.11.5878.master.4328f5c",
+    "operationName": "WalkAndTransitScoreQuery",
+    "query": "query WalkAndTransitScoreQuery($zpid: ID!) {\n  property(zpid: $zpid) {\n    id\n    walkScore {\n      walkscore\n      description\n      ws_link\n    }\n    transitScore {\n      transit_score\n      description\n      ws_link\n    }\n  }\n}\n",
+    "variables": {"zpid": property_id},
+}
+
+
+data = requests.post(api_url, headers=headers, params=params, json=query).json()
+
+print("Walk Score:", data["data"]["property"]["walkScore"]["walkscore"])
+
+

Prints:

+
Walk Score: 47
+
",html +"Dropdown Value change if I selected the 1st Dropdown

Currently, I'm having this problem when I tried changing the value of the 1st drop down to the 2nd one also inherit the value I've selected. Please help me with how can I fix this.

+

My goal is when I change the value of the first one the 2nd dropdown will not inherit the value of the first dropdown.

+

Please see the code below:

+

+
+
$("".nf-default-opt"").click(function() {
+  $(this).parent().toggleClass(""nf-active"");
+})
+
+$("".nf-opt-ul .nf-li"").click(function() {
+  var currentSelected = $(this).html();
+  $("".nf-default-opt .nf-li"").html(currentSelected);
+  $(this).parents("".nf-select-c"").removeClass(""nf-active"");
+})
+
.nf-dropdown {
+  position: relative;
+  width: 100%;
+}
+
+.nf-select-c {
+  position: relative;
+  user-select: none;
+}
+
+.nf-select-c .nf-default-opt {
+  background: #fff;
+  border-radius: 5px;
+  position: relative;
+  cursor: pointer;
+  box-shadow: rgb(207 213 218 / 30%) 0px 0px 0px 1px, rgb(207 213 218 / 60%) 0px 0px 2px 1px;
+  min-height: 44px;
+  line-height: 42px;
+  height: 44px;
+}
+
+.nf-select-c .nf-default-opt .nf-li {
+  padding: 0px 5px;
+}
+
+.nf-select-c .nf-default-opt::before {
+  content: """";
+  position: absolute;
+  top: 15px;
+  right: 18px;
+  width: 8px;
+  height: 8px;
+  border: 2px solid;
+  border-color: transparent transparent #555555 #555555;
+  transform: rotate(-45deg);
+}
+
+.nf-select-c .nf-opt-ul {
+  position: absolute;
+  top: 46px;
+  left: 0;
+  width: 100%;
+  background: #fff;
+  border-radius: 5px;
+  display: none;
+  box-shadow: rgb(60 64 67 / 30%) 0px 1px 2px 0px, rgb(60 64 67 / 15%) 0px 1px 3px 1px;
+  z-index: 1;
+}
+
+.nf-select-c .nf-opt-ul .nf-li {
+  padding: 0px 5px;
+  cursor: pointer;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:first-child:hover {
+  border-top-left-radius: 5px;
+  border-top-right-radius: 5px;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:last-child:hover {
+  border-top-left-radius: 5px;
+  border-top-right-radius: 5px;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:hover {
+  background: #edf6ff;
+}
+
+.nf-select-c .nf-opt {
+  display: flex;
+  align-items: center;
+  min-height: 44px;
+  line-height: 42px;
+  height: 44px;
+}
+
+.nf-icon {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+  background-repeat: no-repeat;
+  background-position: center;
+  width: 32px;
+  height: 32px;
+  margin-right: 15px;
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-s-ans {
+  background-image: url(../media/icons/noah-form-short-ans-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-para {
+  background-image: url(../media/icons/noah-forms-para-ans-icon18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-mchoice {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-checkbox {
+  background-image: url(../media/icons/noah-form-check-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-dropdown {
+  background-image: url(../media/icons/noah-form-dropdown-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-fupload {
+  background-image: url(../media/icons/noah-form-upload-icon-18x18-filled.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-date {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-time {
+  background-image: url(../media/icons/noah-form-time-btn-icon-18x18.png);
+}
+
+.nf-select-c.nf-active .nf-opt-ul {
+  display: block;
+}
+
+.nf-select-c.nf-active .nf-default-opt:before {
+  top: 21px;
+  transform: rotate(-225deg);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-default-opt {
+  box-shadow: rgb(60 64 67 / 15%) 0px 1px 2px 0px, rgb(60 64 67 / 10%) 0px 1px 3px 1px;
+  border: 0px;
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-default-opt::before {
+  border-color: transparent transparent #2a79c6 #2a79c6;
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-s-ans {
+  background-image: url(../media/icons/noah-form-short-ans-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-para {
+  background-image: url(../media/icons/noah-forms-para-ans-icon18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-mchoice {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-checkbox {
+  background-image: url(../media/icons/noah-form-check-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-dropdown {
+  background-image: url(../media/icons/noah-form-dropdown-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-fupload {
+  background-image: url(../media/icons/noah-form-upload-icon-18x18-filled.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-date {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-time {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-icon {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt-ul .nf-li:hover {
+  background: #ffffff;
+  color: #555555;
+  box-shadow: rgb(42 121 198 / 15%) 0px 2px 8px;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""nf-dropdown"">
+  <div class=""nf-select-c"">
+
+    <div class=""nf-default-opt"">
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+    </div>
+
+    <div class=""nf-opt-ul"">
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-short-ans"" data-value=""nf-short-ans"">
+          <div class=""nf-icon _nf-icon-s-ans""></div>
+          <div class=""nf-p"">Short Answer</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-multi-choice"" data-value=""nf-multi"">
+          <div class=""nf-icon _nf-icon-mchoice""></div>
+          <div class=""nf-p"">Multiple Choice</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-checkbox"" data-value=""nf-check"">
+          <div class=""nf-icon _nf-icon-checkbox""></div>
+          <div class=""nf-p"">CheckBoxes</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-dropdown"" data-value=""nf-dropdown"">
+          <div class=""nf-icon _nf-icon-dropdown""></div>
+          <div class=""nf-p"">Dropdown</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-file-upload"" data-value=""nf-upload"">
+          <div class=""nf-icon _nf-icon-fupload""></div>
+          <div class=""nf-p"">File Upload</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-date"" data-value=""nf-date"">
+          <div class=""nf-icon _nf-icon-date""></div>
+          <div class=""nf-p"">Date</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-time"" data-value=""nf-time"">
+          <div class=""nf-icon _nf-icon-time""></div>
+          <div class=""nf-p"">Time</div>
+        </div>
+      </div>
+      
+    </div>
+  </div>
+
+              </div>
+
+  <div class=""nf-select-c"">
+
+    <div class=""nf-default-opt"">
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+    </div>
+
+    <div class=""nf-opt-ul"">
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-short-ans"" data-value=""nf-short-ans"">
+          <div class=""nf-icon _nf-icon-s-ans""></div>
+          <div class=""nf-p"">Short Answer</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-multi-choice"" data-value=""nf-multi"">
+          <div class=""nf-icon _nf-icon-mchoice""></div>
+          <div class=""nf-p"">Multiple Choice</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-checkbox"" data-value=""nf-check"">
+          <div class=""nf-icon _nf-icon-checkbox""></div>
+          <div class=""nf-p"">CheckBoxes</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-dropdown"" data-value=""nf-dropdown"">
+          <div class=""nf-icon _nf-icon-dropdown""></div>
+          <div class=""nf-p"">Dropdown</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-file-upload"" data-value=""nf-upload"">
+          <div class=""nf-icon _nf-icon-fupload""></div>
+          <div class=""nf-p"">File Upload</div>
+        </div>
+      </div>
+      
+      <hr>
+      
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-date"" data-value=""nf-date"">
+          <div class=""nf-icon _nf-icon-date""></div>
+          <div class=""nf-p"">Date</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-time"" data-value=""nf-time"">
+          <div class=""nf-icon _nf-icon-time""></div>
+          <div class=""nf-p"">Time</div>
+        </div>
+      </div>
+      
+    </div>
+  </div>
+</div>
+
+
+

+

Can anyone help me with this?

","

Your issue is that $(".nf-default-opt .nf-li") will find all the default-opts, so you need to use this to refer to the current .nf-li and get the closest parent .nf-select-c then find the .nf-default-opt within that single drop down:

+
$(this).closest(".nf-select-c").find(".nf-default-opt .nf-li").html(currentSelected);
+
+

As you also removeClass, this can be combined:

+
  var currentSelected = $(this).html();
+  var wrapper = $(this).closest(".nf-select-c");
+  wrapper.find(".nf-default-opt .nf-li").html(currentSelected);
+  wrapper.removeClass("nf-active");
+
+

+
+
$("".nf-default-opt"").click(function() {
+  $(this).parent().toggleClass(""nf-active"");
+})
+
+$("".nf-opt-ul .nf-li"").click(function() {
+  var currentSelected = $(this).html();
+  var wrapper = $(this).closest("".nf-select-c"");
+  wrapper.find("".nf-default-opt .nf-li"").html(currentSelected);
+  wrapper.removeClass(""nf-active"");
+})
+
.nf-dropdown {
+  position: relative;
+  width: 100%;
+}
+
+.nf-select-c {
+  position: relative;
+  user-select: none;
+}
+
+.nf-select-c .nf-default-opt {
+  background: #fff;
+  border-radius: 5px;
+  position: relative;
+  cursor: pointer;
+  box-shadow: rgb(207 213 218 / 30%) 0px 0px 0px 1px, rgb(207 213 218 / 60%) 0px 0px 2px 1px;
+  min-height: 44px;
+  line-height: 42px;
+  height: 44px;
+}
+
+.nf-select-c .nf-default-opt .nf-li {
+  padding: 0px 5px;
+}
+
+.nf-select-c .nf-default-opt::before {
+  content: """";
+  position: absolute;
+  top: 15px;
+  right: 18px;
+  width: 8px;
+  height: 8px;
+  border: 2px solid;
+  border-color: transparent transparent #555555 #555555;
+  transform: rotate(-45deg);
+}
+
+.nf-select-c .nf-opt-ul {
+  position: absolute;
+  top: 46px;
+  left: 0;
+  width: 100%;
+  background: #fff;
+  border-radius: 5px;
+  display: none;
+  box-shadow: rgb(60 64 67 / 30%) 0px 1px 2px 0px, rgb(60 64 67 / 15%) 0px 1px 3px 1px;
+  z-index: 1;
+}
+
+.nf-select-c .nf-opt-ul .nf-li {
+  padding: 0px 5px;
+  cursor: pointer;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:first-child:hover {
+  border-top-left-radius: 5px;
+  border-top-right-radius: 5px;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:last-child:hover {
+  border-top-left-radius: 5px;
+  border-top-right-radius: 5px;
+}
+
+.nf-select-c .nf-opt-ul .nf-li:hover {
+  background: #edf6ff;
+}
+
+.nf-select-c .nf-opt {
+  display: flex;
+  align-items: center;
+  min-height: 44px;
+  line-height: 42px;
+  height: 44px;
+}
+
+.nf-icon {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+  background-repeat: no-repeat;
+  background-position: center;
+  width: 32px;
+  height: 32px;
+  margin-right: 15px;
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-s-ans {
+  background-image: url(../media/icons/noah-form-short-ans-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-para {
+  background-image: url(../media/icons/noah-forms-para-ans-icon18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-mchoice {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-checkbox {
+  background-image: url(../media/icons/noah-form-check-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-dropdown {
+  background-image: url(../media/icons/noah-form-dropdown-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-fupload {
+  background-image: url(../media/icons/noah-form-upload-icon-18x18-filled.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-date {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-select-c .nf-opt .nf-icon._nf-icon-time {
+  background-image: url(../media/icons/noah-form-time-btn-icon-18x18.png);
+}
+
+.nf-select-c.nf-active .nf-opt-ul {
+  display: block;
+}
+
+.nf-select-c.nf-active .nf-default-opt:before {
+  top: 21px;
+  transform: rotate(-225deg);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-default-opt {
+  box-shadow: rgb(60 64 67 / 15%) 0px 1px 2px 0px, rgb(60 64 67 / 10%) 0px 1px 3px 1px;
+  border: 0px;
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-default-opt::before {
+  border-color: transparent transparent #2a79c6 #2a79c6;
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-s-ans {
+  background-image: url(../media/icons/noah-form-short-ans-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-para {
+  background-image: url(../media/icons/noah-forms-para-ans-icon18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-mchoice {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-checkbox {
+  background-image: url(../media/icons/noah-form-check-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-dropdown {
+  background-image: url(../media/icons/noah-form-dropdown-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-fupload {
+  background-image: url(../media/icons/noah-form-upload-icon-18x18-filled.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-date {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt .nf-icon._nf-icon-time {
+  background-image: url(../media/icons/noah-form-calendar-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-icon {
+  background-image: url(../media/icons/noah-form-radio-btn-icon-18x18.png);
+}
+
+.nf-dropdown[nf-style=""2""] .nf-select-c .nf-opt-ul .nf-li:hover {
+  background: #ffffff;
+  color: #555555;
+  box-shadow: rgb(42 121 198 / 15%) 0px 2px 8px;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""nf-dropdown"">
+  <div class=""nf-select-c"">
+
+    <div class=""nf-default-opt"">
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+    </div>
+
+    <div class=""nf-opt-ul"">
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-short-ans"" data-value=""nf-short-ans"">
+          <div class=""nf-icon _nf-icon-s-ans""></div>
+          <div class=""nf-p"">Short Answer</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-multi-choice"" data-value=""nf-multi"">
+          <div class=""nf-icon _nf-icon-mchoice""></div>
+          <div class=""nf-p"">Multiple Choice</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-checkbox"" data-value=""nf-check"">
+          <div class=""nf-icon _nf-icon-checkbox""></div>
+          <div class=""nf-p"">CheckBoxes</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-dropdown"" data-value=""nf-dropdown"">
+          <div class=""nf-icon _nf-icon-dropdown""></div>
+          <div class=""nf-p"">Dropdown</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-file-upload"" data-value=""nf-upload"">
+          <div class=""nf-icon _nf-icon-fupload""></div>
+          <div class=""nf-p"">File Upload</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-date"" data-value=""nf-date"">
+          <div class=""nf-icon _nf-icon-date""></div>
+          <div class=""nf-p"">Date</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-time"" data-value=""nf-time"">
+          <div class=""nf-icon _nf-icon-time""></div>
+          <div class=""nf-p"">Time</div>
+        </div>
+      </div>
+    </div>
+  </div>
+
+
+  <div class=""nf-select-c"">
+
+    <div class=""nf-default-opt"">
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+    </div>
+
+    <div class=""nf-opt-ul"">
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-short-ans"" data-value=""nf-short-ans"">
+          <div class=""nf-icon _nf-icon-s-ans""></div>
+          <div class=""nf-p"">Short Answer</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-para"" data-value=""nf-para"">
+          <div class=""nf-icon _nf-icon-para""></div>
+          <div class=""nf-p"">Paragraph</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-multi-choice"" data-value=""nf-multi"">
+          <div class=""nf-icon _nf-icon-mchoice""></div>
+          <div class=""nf-p"">Multiple Choice</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-checkbox"" data-value=""nf-check"">
+          <div class=""nf-icon _nf-icon-checkbox""></div>
+          <div class=""nf-p"">CheckBoxes</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-dropdown"" data-value=""nf-dropdown"">
+          <div class=""nf-icon _nf-icon-dropdown""></div>
+          <div class=""nf-p"">Dropdown</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-file-upload"" data-value=""nf-upload"">
+          <div class=""nf-icon _nf-icon-fupload""></div>
+          <div class=""nf-p"">File Upload</div>
+        </div>
+      </div>
+      <hr>
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-date"" data-value=""nf-date"">
+          <div class=""nf-icon _nf-icon-date""></div>
+          <div class=""nf-p"">Date</div>
+        </div>
+      </div>
+
+      <div class=""nf-li"">
+        <div class=""nf-opt _nf-time"" data-value=""nf-time"">
+          <div class=""nf-icon _nf-icon-time""></div>
+          <div class=""nf-p"">Time</div>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"error code 401, HTTP Token: Access denied

I am new to using API's. +I've been trying to use this API called Carbon Interface. it supposed to give an estimate of your carbon footprint based on how much electricity you use. I created this quick project to test it but whenever I try to use it I get error code 401, I look it up and it's Unauthorized / HTTP Token: Access denied. Instead of token, I put my API key, I just used that for this question

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+    <title>Axios Crash Course</title>
+  </head>
+  <body>
+    <button id="submit">submit</button>
+    <script>
+        document.getElementById('submit').addEventListener("click", getdata)
+        function getdata() {
+            fetch('https://www.carboninterface.com/api/v1/estimates', {
+              method: 'POST',
+              header: {
+                'Authorization': 'Bearer Token'
+              },
+              data: {
+                "type": "electricity",
+                "electricity_unit": "mwh",
+                "electricity_value": 42,
+                "country": "us",
+                "state": "ca"
+              }
+              
+            }).then(response => response.json())
+              .then(data => console.log(data)).catch(error => {
+              console.error('There has been a problem with your fetch operation:', error);
+  });
+        }
+    </script>
+  </body>
+</html>
+
","

In your code,

+
header: {  'Authorization': 'Bearer Token'   },  
+
+

Token that you have written is supposed to be actual value of token. Not just some word. It should be token which is used for checking the authenticity.

+

Actual value of token looks something like this:

+
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYTkzODgxNmQyMGRiMDAxMWVmMjliMSIsInVzZXJuYW1lIjoic2FyaXRhZyIsInVzZXJUeXBlIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJmaXJzdE5hbWUiOiJzYXJpdGEiLCJsYXN0TmFtZSI6Imdhd2FkZSIsImlhdCI6MTYyNzAxOTI0MiwiZXhwIjoxNjU4NTc2ODQyfQ.JhdwWO_tdkq6M3aYWI-YxqZo7iLOQ9IBmFMb7Jqid5E
+
+

Here is one site: https://jwt.io/ where you can enter your payload and get the value of token. This site is at times quiet efficient.

+

Below is the code as to how I write to set auth token

+

import axios from "axios";

+
const setAuthToken = token => {
+  if (token) {
+    axios.defaults.headers.common["Authorization"] = "Bearer " + token;
+    axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
+    axios.defaults.headers['Access-Control-Allow-Origin'] = "*";
+  } else {
+    delete axios.defaults.headers.common["Authorization"];
+  }
+};
+
+export default setAuthToken;
+
+

Here is the code for generating and sending the token :

+
var jwt = require('jsonwebtoken');
+
+var createToken = function(tokenObj) {
+    const expiresIn = '5 days';
+    const secretOrKey = process.env.JWT_TOKEN_SECRET;
+    
+    const token = jwt.sign(tokenObj, secretOrKey, {
+        expiresIn: expiresIn
+    });
+    return token;
+}
+
+module.exports = {
+    generateToken: function(req, res, next) {
+        req.jwtToken = createToken(req.tokenObj);
+        return next();
+    },
+    sendToken: function(req, res) {
+        res.setHeader("Access-Control-Expose-Headers", "X-Auth-Token");
+        res.setHeader('x-auth-token', req.jwtToken);
+        return res.status(200).send(JSON.stringify(req.tokenObj));
+    }
+  };
+
+

I have shown you one such example. Hope this might help you.

",html +"How do I redirect to another page in a condition using php?

I want to redirect to index.html?id=div2 when the if condition is statisfied. And if not, then it should reload the page.

+

How do I do that?

+
if($checkAll > 0){
+    // Redirect to index.html?id=div2  
+} else{
+    //Reload page
+}
+
+

Thanks!

","

You have to use headers:

+
if($checkAll > 0){
+    header("Location: /index.html?id=div2"); 
+} else{
+    header("Refresh:0");
+}
+// die();
+
",html +"The button onclick in html has stopped working

I was making a website that using prompt popup to login. When I click the button, it didn't work. How to slove this problem?

+

Code here:

+

+<style>
+button {
+  background-color: #04AA6D;
+  color: white;
+  padding: 14px 20px;
+  margin: 8px 0;
+  border: none;
+  cursor: pointer;
+  width: 100%;
+}
+</style>
+<script>
+function myFunction() {
+  let person = prompt("Please enter your username:", "");
+  if (person == null || person == "") {
+    text = "User cancelled the prompt.";
+  } else if (person == "hi" || person == "test" || person == "1234") {
+    window.location.href = "youtube.com/c/呂殿下";
+  } else {
+    window.location.href = "youtube.com";
+}
+</script>
+<button onclick="myFunction();">Click me</button>
+</body></html>
+
","

Your function had a couple of errors:

+
    +
  • single = in first else if
  • +
  • no closing } for the else block
  • +
+

In order to make the branching visible, I am logging out the location instead of setting window.location.href for this example.

+

+
+
var text;
+
+function myFunction() {
+  let person = prompt(""Please enter your username:"", """");
+  if (person == null || person == """") {
+    text = ""User cancelled the prompt."";
+  } else if (person == ""hi"" || person == ""test"" || person == ""1234"") {
+    console.log(""setting href to sites.google.com/"");
+    //window.location.href = ""sites.google.com/"";
+  } else {
+    console.log(""setting href to google.com"");
+    //window.location.href = ""google.com"";
+    }
+}
+
button {
+  background-color: #04AA6D;
+  color: white;
+  padding: 14px 20px;
+  margin: 8px 0;
+  border: none;
+  cursor: pointer;
+  width: 100%;
+}
+
<button onclick=""myFunction()"">Click me</button>
+
+
+

",html +"How to know in real time when a website post a new content?

I would like to know if there are a way to see a new website page before it is posted in the home page, but after they posted it on Internet.

+

I tried with sitemaps, but the problem is that I want to monitor it 24/7, and the sitemps shows historical information, not real time.

+

For example, suppose this scenario:

+

BBC created an article around 23:05, but they shared it on its home page around 23:15. Are there a way to obtain the link of the article or title of the article before 23:15?

",

No. A file on a website is totally invisible unless some other page links to it.

,html +"How to replace multiple HTML elements into another type of element which is in a regular string form

I have this HTML:

+
<div>
+    <span class="content">Content 1</span>
+    <div>Hello</div>
+    <span class="content">Content 2</span>
+    <b>
+        <span class="content">Content 3</span>
+    </b>
+    <div class="content">Hello</div>
+</div>
+
+

I need to be able to get all elements with class "content" and then replace them with another element which is currently in a string form.

+

So its,

+
var stringHtml = "<input type='text' />";
+
+

This stringHtml should replace all the class="content" and be rendered as a regular input element in place of all the class="content" elements.

","

This is basically it:

+

+
+
var stringHtml = ""<input type='text' />"";
+
+document.querySelectorAll('.content').forEach(elm => {
+  elm.outerHTML = stringHtml;
+});
+
<div>
+  <span class=""content"">Content 1</span>
+  <div>Hello</div>
+  <span class=""content"">Content 2</span>
+  <b><span class=""content"">Content 3</span></b>
+  <div class=""content"">Hello</div>
+</div>
+
+
+

+

But you probably need a name for each of the input elements, so I will suggest this:

+

+
+
document.querySelectorAll('.content').forEach(elm => {
+  var name = elm.attributes['name'].value;
+  elm.outerHTML = `<input type=""text"" name=""${name}"" />`;
+});
+
<div>
+  <span class=""content"" name=""input1"">Content 1</span>
+  <div>Hello</div>
+  <span class=""content"" name=""input2"">Content 2</span>
+  <b><span class=""content"" name=""input3"">Content 3</span></b>
+  <div class=""content"" name=""input4"">Hello</div>
+</div>
+
+
+

",html +"How add elements like Javascript in Jquery - Table Problems

everything was going well until I had two problems with jquery, and this is the second.

+

I have this javascript code, inside a function, that creates "tr" elements and then through a for it adds them to a table already created in html.

+
for(let i = 1; i <= plazos; i++) {
+
+    pagosIntereses = parseFloat(valor*(tasas/100));
+    pagoAmortizacion = pagoMensual - pagosIntereses;
+    valor = parseFloat(valor-pagoAmortizacion);
+    
+    fechaX = hoy.setMonth(hoy.getMonth() + 1);
+    //creacion de las filas
+    const fila = document.createElement("tr");
+    fila.innerHTML = 
+    `   <td>${formatoFecha(fechaX)}
+        <td class="valorCuota">${pagoMensual.toFixed(2)}</td>
+        <td>${pagoAmortizacion.toFixed(2)}</td>
+        <td>${pagosIntereses.toFixed(2)}</td>
+        <td>${valor.toFixed(2)}</td>`;
+    datosTabla.appendChild(fila);
+}
+
+

Now I try to pass it to Jquery and I can't make it work, I tried to do the following which was what I logically came up with, but I couldn't

+
    const fila = $("tr").append(
+        `<td>${formatoFecha(fechaX)}
+        <td class="valorCuota">${pagoMensual.toFixed(2)}</td>
+        <td>${pagoAmortizacion.toFixed(2)}</td>
+        <td>${pagosIntereses.toFixed(2)}</td>
+        <td>${valor.toFixed(2)}</td>`);
+    datosTabla.appendChild(fila);
+
","

I appreciate all of your responses! They have helped me to reach this solution.

+
$("#tablaBody").append(`<tr><td>${formatoFecha(fechaX)}
+        <td class="valorCuota">${pagoMensual.toFixed(2)}</td>
+        <td>${pagoAmortizacion.toFixed(2)}</td>
+        <td>${pagosIntereses.toFixed(2)}</td>
+        <td>${valor.toFixed(2)}</td>`);
+
+

I thank you very much

",html +"How To align the input box as center inside the each column of the table

I am trying to center the input box inside the column of the table but not working . I am looking for a solution. I have given the column width size in style of the html

+

+
+
<style>
+   
+    .columnwidth{
+        width:5em;
+    }
+    .datewidth {
+        width: 8em;
+    }
+</style>
+
+
+<table id=""attendance"" class=""table cell-border"" style=""width:100%"">
+  <thead class=""thead-light"">
+  <tr>
+    <td style=""text-align:center;width:5em"">Sunday<br />NetHrs</td>
+    <td style=""text-align:center;width:5em"">Monday<br />NetHrs</td>
+   <td style=""text-align:center;width:5em"">Tuesday<br />NetHrs</td>
+   <td style=""text-align:center;width:5em"">Wednesday<br />NetHrs</td>
+   <td style=""text-align:center;width:5em"">Thursday<br />NetHrs</td>
+   <td style=""text-align:center;width:5em"">Friday<br />NetHrs</td>
+   <td style=""text-align:center;width:5em"">Saturday<br />NetHrs</td>
+ </tr>
+</thead>
+ <tbody>
+ <tr>
+                                              
+ <td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.SundayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control empHrs columnwidth format-text"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.MondayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control empHrs columnwidth  format-text"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.TuesdayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control  columnwidth empHrs"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.WednesdayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control columnwidth  empHrs"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.ThursdayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control columnwidth  empHrs"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.FridayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control columnwidth  empHrs"" } })</td>
+<td style=""text-align:center;vertical-align:middle;"">@Html.EditorFor(model => model.SaturdayNetHrs, new { htmlAttributes = new { type = ""text"", @class = ""form-control columnwidth  empHrs"" } })</td>
+</tr>
+ </tbody>
+ </table>
+
+
+

","

Not sure what is your empHrs css class. Except for empHrs, form-control class contains dispaly:block which influences the style:

+

+

You need add the following css style like below:

+
<style>
+    //...
+    input {
+        display: inline-block !important;
+    }
+</style>
+
+

Result: +

",html +"I´m unable to map elements of an array

Im trying to receive the data from my api into the charts at my website. +Im stuck trying to fill my charts with the data, I have the code for filling the charts but when I map the JSON data and try to split the data into Date and temperature to put it in the chart it just does not work.

+

This is the code:

+
 var xmlhttp = new XMLHttpRequest();
+var url = "http://localhost:8090/api/grafico/datos/temperatura/medicionAire/2059";
+xmlhttp.open("GET", url, true);
+xmlhttp.send();
+xmlhttp.onreadystatechange = function () {
+    if (this.readyState == 4 && this.status == 200) {
+        var data = JSON.parse(this.responseText);
+       //console.log(data);
+        
+        var dateG = data.map(function(elem) {
+            return elem.fecha;
+        });
+        var temperatureG = data.map(function(elem) {
+            return elem.temperatura;
+        });
+
+    }
+}
+
+

I tried debuging it and it look like it does not recognize "fecha" or "temperatura" inside the array eventhough "elem" has the array in it: +As you can see in this image, "elem" has the array in it, but "elem.fecha" is undefined and I dont know why. It should return me an array with only "fecha" of each line.

+

+

Log output of data:

+
[Array(4)]
+0: Array(4)
+0: {fecha: '2021-09-03T13:15:41.943Z', temperatura: 22.33}
+1: {fecha: '2021-09-03T13:15:41.230Z', temperatura: 22.33}
+2: {fecha: '2021-09-03T13:15:04.243Z', temperatura: 22.33}
+3: {fecha: '2021-09-03T13:14:06.923Z', temperatura: 16.56}
+length: 4
+[[Prototype]]: Array(0)
+length: 1
+[[Prototype]]: Array(0)
+
","

I believe if you were to modify you code into something like so:

+
    var dateG = data.map(function(elem) {
+        return elem.map(function(innerElem) {
+            return innerElem.fecha
+        });
+    });
+
+

You would end up with dateG as 2D array of fetcha values.

",html +"CSS: Properly align the edge of Section with Header and Footer

So I'm new to CSS and as part of practise trying to implement a simple layout. The layout is complete except for one problem, the right edge of "Section" is not properly aligned with the right edges of "Header" and "Footer". Can someone please point out what I'm doing wrong here? +I understand this can happen due to unnecessary margins but in my case there are no such extra margins.

+

Screenshot is attached for reference. +

+

The code is:

+
<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <meta http-equiv="X-UA-Compatible" content="IE=edge">
+        <title>Project-1: Simple Layout</title>
+        <meta name="description" content="">
+        <meta name="viewport" content="width=device-width, initial-scale=1">
+        <style>
+            *{
+                border-style: hidden;
+                border-width: 1px;
+                box-sizing: border-box;
+            }
+            body{
+                background-color: #2473f2;
+                margin-right: 10%;
+                margin-left: 10%;
+                color: white;
+                text-align: center;
+                font-family: Arial, Helvetica, sans-serif;
+            }
+            header, nav, section, footer{
+                border-style: solid;
+                border-radius: 5px;
+            }
+            nav, section,footer{
+                float: left;
+            }
+            nav, section{
+                padding: 300px 0px;
+            }
+            nav{
+                width: 200px;
+                margin-right: 20px;
+            }
+            section{
+                width: 1300px;
+            }
+            header, footer{
+                padding: 20px;
+            }
+            header{
+                margin-bottom: 20px;
+            }
+            footer{
+                margin-top: 20px;
+                width: 1540px;
+            }
+        </style>
+    </head>
+    <body>
+        <h1>Project-1: Simple Layout</h1>
+        <div>
+            <header>
+                HEADER
+            </header>
+            <nav>
+                NAV
+            </nav>
+            <section>
+                SECTION
+            </section>
+            <footer>
+                FOOTER
+            </footer>         
+        </div>
+    </body>
+</html>
+
","

There are various approaches to do so.

+
    +
  1. Calc()
  2. +
  3. Flex Box (CSS3)
  4. +
  5. Grid System (CSS3)
  6. +
+

I wrote you the correct form [ Flex Box ]

+
<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset="utf-8" />
+        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+        <title>Project-1: Simple Layout</title>
+        <meta name="description" content="" />
+        <meta name="viewport" content="width=device-width, initial-scale=1" />
+        <style>
+            * {
+                border-style: hidden;
+                border-width: 1px;
+                box-sizing: border-box;
+            }
+            body {
+                background-color: #2473f2;
+                margin-right: 10%;
+                margin-left: 10%;
+                color: white;
+                text-align: center;
+                font-family: Arial, Helvetica, sans-serif;
+            }
+            header,
+            nav,
+            section,
+            footer {
+                border-style: solid;
+                border-radius: 5px;
+            }
+            nav,
+            section,
+            footer {
+                float: left;
+            }
+            nav,
+            section {
+                padding: 300px 0px;
+            }
+            nav {
+                width: 200px;
+                margin-right: 20px;
+            }
+            section {
+                width: 1300px;
+            }
+            header,
+            footer {
+                padding: 20px;
+            }
+            header {
+                margin-bottom: 20px;
+            }
+            footer {
+                margin-top: 20px;
+                width: 1540px;
+            }
+            /* just added */
+            .main-body {
+                display: flex;
+                justify-content: space-between;
+            }
+        </style>
+    </head>
+    <body>
+        <h1>Project-1: Simple Layout</h1>
+        <div>
+            <header>
+                HEADER
+            </header>
+            <main class="main-body">
+                <nav>
+                    NAV
+                </nav>
+                <section>
+                    SECTION
+                </section>
+            </main>
+            <footer>
+                FOOTER
+            </footer>
+        </div>
+    </body>
+</html>
+
",html +"How can I bring my div to the foreground with its background color?

#Preface I am relatively new to HTML and CSS if this has been answered elsewhere I would appreciate direction to something that gives me a solution.

+

Below is the code I have, I want the .Divclass to appear infront of my backround element with it's red background.

+
* {
+  background-image: url(https://www.pixelstalk.net/wp-content/uploads/2016/05/Treugolnik-triangle-illuminati-Wallpapers-High-Resolution.jpg);
+        
+    background-repeat: no-repeat;
+    background-attachment: fixed;
+    background-position: center;
+    background-size: 1960px 1080px;
+}
+
+.divclass {
+  height: 230px;
+  width: 300px;
+  margin: 0px;
+  padding: 0px;
+  color: red;
+  border: solid 1px rgb(253, 253, 253);
+  text-align: center;   
+  font-size: x-large;
+}
+
","

Check the below snippet. The div is in front of the background image with a red background.

+

Let me know if this is what your desired output is

+

+
+
section {
+  background-image: url(https://www.pixelstalk.net/wp-content/uploads/2016/05/Treugolnik-triangle-illuminati-Wallpapers-High-Resolution.jpg);
+  background-repeat: no-repeat;
+  background-attachment: fixed;
+  background-position: center;
+  background-size: 1960px 1080px;
+  padding: 10px;
+}
+
+
+.divclass {
+  height: 230px;
+  width: 300px;
+  margin: 0px;
+  padding: 0px;
+  background-color: red;
+  border: solid 1px rgb(253, 253, 253);
+  text-align: center;   
+  font-size: x-large;
+}
+
<section>
+  <div class=""divclass"">Hi</div>
+</section>
+
+
+

",html +"Is it possible to apply the class changes to an element of selection.classed() in d3.js, or to set a CSS property value relative to its currentValue

I am using d3.js to add and remove classes to a selection of elements on mouseOver() and mouseOut() events. I'd like to make the class "isHovered" and make the values of the attributes I'm changing to be relative to the element's current value. Something like this:

+
function handleMouseOver(d, i) {
+        d3.selectAll('.classToSelect')
+        .classed('isHovered', 'true');
+};
+function handleMouseOut(d, i) {
+        d3.selectAll('.classToSelect')
+        .classed('isHovered', 'false');
+};
+
+

and make the isHovered class change the elements size/color:

+
.isHovered {
+    height:height*1.5;
+    width:width*1.5;
+    background-color:yellow;
+}
+
+

This adds the class, but doesn't actually make any changes to the elements attributes, except its classList. I'm trying to assign and unassigned the "isHovered" class, rather than having to store the pre-hovered size/color, and manually update them, and then manually revert back to them afterwards, which I don't think is possible since these elements are sized dynamically by d3.js scaling data:

+

+

So, can I make these newly added class changes actually take effect, and can the effect be relative to an element's properties' current values?

+

Alternatively:

+

Is it possible to access the element's width:svgAnimatedWidth and Height:svgAnimatedHeight properties & values directly, so that I can change them and revert them back manually? How?

","

There are various ways of altering the height/width on hover.

+

This snippet uses CSS variables to set the initial height and width in a class and then uses them to calculate new values in the isHovered class.

+

+
+
const div = document.querySelector('div');
+div.addEventListener('mouseover', function() {
+  div.classList.add('isHovered');
+});
+div.addEventListener('mouseout', function() {
+  div.classList.remove('isHovered');
+});
+
div {
+  --h: 100;
+  --w: 200;
+  height: calc(var(--h) * 1px);
+  width: calc(var(--w) * 1px);
+  background-color: blue;
+}
+
+.isHovered {
+  --hhovered: calc(var(--h) * 1.5);
+  --whovered: calc(var(--w) * 1.5);
+  height: calc(var(--hhovered) * 1px);
+  width: calc(var(--whovered) * 1px);
+  background-color: yellow;
+}
+
<div></div>
+
+
+

+

It is also possible to alter CSS variables using JS style.setProperty and to read them using style.getPropertyValue.

+

As a complete alternative if the aim is just to increase the height and width of an element on hover then the CSS transform scale could be used.

+

+
+
div {
+  height: 100px;
+  width: 200px;
+  background-color: blue;
+}
+
+div:hover {
+  transform: scale(1.5);
+  background-color: yellow;
+}
+
<div></div>
+
+
+

+

This has the advantage (or disadvantage, depending on what effect is actually required) of not affecting surrounding elements' positioning.

",html +"CSS media query not executing max-width

I am adjusting the page width in chrome, inspect>toggle device toolbar.

+

when the width is less than 600 it does not display the button for some reason. Can anybody spot what's wrong with this?

+

thanks in advance

+

+
+
.login-button {
+  font-size: 21px;
+  background-color: transparent;
+  border: none;
+  position: absolute;
+  right: 0;
+  margin: 8px 10px;
+  display: none;
+}
+
+@media screen and (max-width: 600px) {
+  .login-button {
+    display: initial;
+  }
+}
+
<button class=""login-button"">
+  <span><i class=""fas fa-bars""></i> Button</span>
+</button>
+
+
+

","

Try this:

+

+
+
 .login-button{
+   font-size: 21px;
+   background-color: transparent;
+   border: none;
+   position: absolute;
+   right: 0;
+   margin: 8px 10px;
+   visibility: hidden;
+
+}
+
+@media only screen and (max-width: 600px) {
+    .login-button {
+        visibility: visible;
+        font-size: 21px;
+        background-color: transparent;
+        border: none;
+        position: absolute;
+        right: 0;
+        margin: 8px 10px;
+    }
+}
+
+
+

",html +"Displaying all Intel CPU types as various option values in HTML

I have 8 option boxes on my UI that I'm designing. The goal is to have the dropdowns ask what CPU your computer has and auto populate the rest of the information.

+

I have code that will populate the dropdowns with "Intel", then display "Intel Family" (Core i7), but I need that to then ask what processor it has. This is going to be a large amount of information, as an Intel i7 has 77 Different versions. Just like an i3,i5,i9.In total there are 693 unique options.

+

e.g.

+
Intel > Core i7 > 7700
+
+Intel > Core i3 > 9300...
+
+

I just have my data stored on excel in a pivot table but I'm assuming ill need it in a JSON file which I'm not familiar with yet.

+

I have a screenshot of what I'm trying to explain, but the code at the moment is very messy.

+

+

+

Here is my current code with JS,

+

https://jsfiddle.net/f745nq0b/2/

+

+
+
$('#env-select').on('change', function(e) {
+  var source = $(this),
+    val = $.trim(source.val()),
+    target = $('#family-select');
+  $(target).empty();
+  if (typeof(_data[val]) != ""undefined"") {
+    var options = (typeof(_data[val]) != ""undefined"") ? _data[val] : {};
+    $('<option>-- Select --</option>').appendTo(target);
+    $.each(options, function(value, index) {
+      $('<option value=""' + value + '"">' + index + '</option>').appendTo(target);
+    });
+  }
+
+});
+
.form-control {
+  margin: 10px;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+  <head>
+    <meta charset=""UTF-8"" />
+    <title>Test</title>
+    <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"" />
+    <link rel=""stylesheet"" href=""./style.css"" />
+    <script>
+      var _data = {};
+      var _data = {
+        ""Intel"": {
+          ""Celeron"": ""Celeron"",
+          ""Celeron D"": ""Celeron D"",
+          ""Celeron Dual-Core"": ""Celeron Dual-Core"",
+          ""Celeron M"": ""Celeron M"",
+          ""Core 2 Duo"": ""Core 2 Duo"",
+          ""Core 2 Extreme"": ""Core 2 Extreme"",
+          ""Core 2 Quad"": ""Core 2 Quad"",
+          ""Core i3"": ""Core i3"",
+          ""Core i5"": ""Core i5"",
+          ""Core i7"": ""Core i7"",
+          ""Core i7 Extreme Edition"": ""Core i7 Extreme Edition"",
+          ""Core i9"": ""Core i9"",
+          ""Core i9 Extreme Edition"": ""Core i9 Extreme Edition"",
+          ""Pentium"": ""Pentium"",
+          ""Pentium 4"": ""Pentium 4"",
+          ""Pentium D"": ""Pentium D"",
+          ""Pentium Dual-Core"": ""Pentium Dual-Core"",
+          ""Pentium Extreme Edition"": ""Pentium Extreme Edition"",
+          ""Pentium III"": ""Pentium III"",
+        },
+        ""AMD"": {
+          ""APU A10-Series"": ""APU A10-Series"",
+          ""APU A12 Series"": ""APU A12 Series"",
+          ""APU A4-Series"": ""APU A4-Series"",
+          ""APU A6-Series"": ""APU A6-Series"",
+          ""APU A8-Series"": ""APU A8-Series"",
+          ""APU E-Series"": ""APU E-Series"",
+          ""Athlon"": ""Athlon"",
+          ""Athlon 64"": ""Athlon 64"",
+          ""Athlon 64 X2"": ""Athlon 64 X2"",
+          ""Athlon Dual Core"": ""Athlon Dual Core"",
+          ""Athlon II"": ""Athlon II"",
+          ""Athlon X2 Series"": ""Athlon X2 Series"",
+          ""Athlon X4 Series"": ""Athlon X4 Series"",
+          ""Athlon XP"": ""Athlon XP"",
+          ""Duron"": ""Duron"",
+          ""FX"": ""FX"",
+          ""K6"": ""K6"",
+          ""Opteron"": ""Opteron"",
+          ""Phenom"": ""Phenom"",
+          ""Phenom II"": ""Phenom II"",
+          ""Ryzen 3"": ""Ryzen 3"",
+          ""Ryzen 5"": ""Ryzen 5"",
+          ""Ryzen 7"": ""Ryzen 7"",
+          ""Ryzen 9"": ""Ryzen 9"",
+          ""Sempron"": ""Sempron"",
+          ""Threadripper"": ""Threadripper"",
+        }
+      };
+
+    </script>
+  </head>
+
+  <body>
+    <div class=""advanced_search_container"">
+      <div class=""advanced_search_title"">
+        <span>Search for CPU</span>
+      </div>
+      <lable>Type</lable>
+      <select class=""form-control"" id=""env-select"">
+        <option value="""">-- Select --</option>
+        <option value=""Intel"">Intel</option>
+        <option value=""AMD"">AMD</option>
+      </select>
+      <lable>Family</lable>
+      <select class=""form-control"" id=""family-select"">
+        <option value="""">-- Select --</option>
+      </select>
+      <lable>Processor</lable>
+      <select class=""form-control"" id=""processor-select"">
+        <option value="""">-- Select --</option>
+      </select>
+      <br>
+      <lable>Codename</lable>
+      <select class=""form-control"" id=""codename-autoselect"">
+        <option value="""">Auto Selected</option>
+      </select>
+      <lable>Frequency</lable>
+      <select class=""form-control"" id=""frequency"">
+        <option value="""">Auto Selected</option>
+      </select>
+      <br>
+      <lable>CPU Cores</lable>
+      <select class=""form-control"" id=""cpu-cores"">
+        <option value="""">Auto Selected</option>
+      </select>
+      <lable>CPU Threads</lable>
+      <select class=""form-control"" id=""cpu-threads"">
+        <option value="""">Auto Selected</option>
+      </select>
+      <br>
+      <lable>CPU Memory</lable>
+      <select class=""form-control"" id=""cpu-memory"">
+        <option value="""">Auto Selected</option>
+      </select>
+    </div>
+
+    <script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js""></script>
+    <script src=""./script.js""></script>
+  </body>
+
+</html>
+
+
+

","

Taking the cited XLS file and converting that to a JSON file using some simple PHP:

+
# codenames are based upon this array - for the dummy data only
+$dictionary=[
+    'degree','bicone','moneme','ibexes','eringo','dallan','condit','result','pyrene','joffre','humour','reemit','phenix',
+    'naseby','baffle','melder','crakow','anvers','swatch','snoozy','joanne','mitzie','bogong','steels','uniate','vestry',
+    'astron','fascia','murine','galosh','mudded','nebula','enmity','advert','pewter','jequi','waggon','sneesh','phuket',
+    'ifugao','elsene','bailie','outman','acetum','zillah','lauric','unnigh'
+];
+# function to build the dummy codename.
+function gencodename(){
+    global $dictionary;
+    $a=mt_rand(0,count($dictionary)-1);
+    $b=mt_rand(1,9);
+    $c=chr( mt_rand(65,90) );
+    return sprintf('%s-%s%s',$dictionary[$a],$b,$c);
+}
+
+
+
+# The saved CSV file taken from the original XLS.
+$file='cpu-info.csv';
+
+$out=array();
+$csv=new SplFileObject( $file );
+$csv->setFlags( SplFileObject::READ_CSV );
+
+foreach( $csv as $index => $line ){
+    if( $index > 1 && !empty( $line ) && array_key_exists( 1, $line ) && array_key_exists( 2, $line ) ){
+        /*
+            No fields for threads or codename so we generate our own numpty values.
+            Otherwise extend the below list(a,b,c,d,e....)=$line to include more vars
+            & use those values rather than the dummy ones.
+        */
+        list( $family, $processor, $codename, $speed, $cores, $memory, $notes )=$line;
+        $out[]=array(
+            'processor' =>  $processor,
+            'family'    =>  $family,
+            'frequency' =>  $speed,
+            'memory'    =>  $memory,
+            'cores'     =>  $cores,
+            'notes'     =>  $notes,
+            'codename'  =>  gencodename(),
+            'threads'   =>  mt_rand(1,16)
+        );
+    }
+}
+$json=sprintf('const json=%s;', json_encode( $out, JSON_PRETTY_PRINT ) );
+$file='cpu-extra.js';
+file_put_contents( $file, $json );
+
+

I note that the source XLS file has changed since first inspection and now has some rudimentary attempts at generating JSON strings using concatenation so it should be noted that the order within the PHP code above within list($a,$b..)=$line etc is dependant upon the column order in the spreadsheet/csv file!

+

With the JSON data saved as cpu-extra.js within the same working directory as the HTML that follows I believe you get the desired output.

+
<!DOCTYPE html>
+<html lang='en'>
+    <head>
+        <meta charset='utf-8' />
+        <title></title>
+        <style>
+            body *{
+                box-sizing:border-box;
+                font-family:monospace;
+            }
+            .form-control {
+                margin:0.25rem;
+                padding:0.5rem;
+                background:whitesmoke;
+            }
+            section{
+                display:flex;
+                flex-direction:row;
+                background:white;
+            }
+            label{ 
+                flex:1;
+                display:flex;
+                flex-direction:row;
+                justify-content:space-between;
+                align-content:center;
+                align-items:center;
+                padding:0.25rem;
+                max-width:33.4%;
+            }
+            .advanced_search_container{
+                width:50%;
+                border:1px solid black;
+                border-radius:1rem;
+                padding:1rem;
+                background:whitesmoke;
+            }
+            select{
+                min-width:140px;
+                background:white!important;
+            }
+            .advanced_search_title{
+                margin:0 0 1rem;
+                background:whitesmoke;
+            }
+            .advanced_search_title > span{
+                font-size:150%;
+                font-weight:bolder;
+            }
+            .active{
+                border:1px solid yellowgreen;
+            }
+            
+            section.notes,
+            section.notes label{ max-width:100% }
+            
+            textarea{
+                width:83%;
+                resize:none;
+                height:5rem;
+                
+            }
+        </style>
+    </head>
+    <body>
+    
+    
+    
+        <div class="advanced_search_container">
+        
+          <div class="advanced_search_title">
+            <span>Search for CPU</span>
+          </div>
+          
+          <!--
+          
+            Important to note that the names of the select
+            menus are keys within the individual JSON records.
+            
+            The JSON used was created in PHP after fudging around
+            with the raw XLS file cited in link. The XLS file was
+            used to generate a simple CSV file which is easily read
+            in PHP.
+            
+            Some parts of the generated JSON are nonsense - added only 
+            so that the menus received some content. Items such as 
+            "codename" and "threads" are ALL bogus unless by accident.
+            
+            Each Select menu has the ID removed as they served no purpose 
+            in this code and some have new classes assigned. Menus are 
+            grouped within `section` elements according to previous `break` 
+            tags - mostly.
+            
+            Modifying this DOM structure will have unforseen effects
+            upon the javascript below.
+            
+          -->
+          
+          <section class='controls'>
+              <label>Type:
+                  <select class="form-control" id="env-select" data-next='family' data-recycle='true'>
+                    <option selected hidden disabled>-- Select --
+                    <option>Intel
+                    <option>AMD
+                  </select>
+              </label>
+              
+              <label>Family:
+                  <select class="form-control" name='family' data-next='processor' data-recycle='true'>
+                    <option selected hidden disabled>-- Select --
+                  </select>
+              </label>
+              
+              <label>Processor:
+                  <select class="form-control dependant" name='processor'>
+                    <option selected hidden disabled>-- Select --
+                  </select>
+              </label>
+          </section>
+          
+          <section class='details'>
+              <label>Codename:
+                  <select class="form-control dependant" name='codename'>
+                    <option selected hidden disabled>Auto Selected
+                  </select>
+              </label>
+              
+              <label>Frequency:
+                  <select class="form-control dependant" name='frequency'>
+                    <option selected hidden disabled>Auto Selected
+                  </select>
+                  
+              </label>
+              
+              <label>CPU Cores:
+                  <select class="form-control dependant" name='cores'>
+                    <option selected hidden disabled>Auto Selected
+                  </select>
+              </label>
+          </section>
+          
+          <section class='details'>
+              <label>CPU Threads:
+                  <select class="form-control dependant" name='threads'>
+                    <option selected hidden disabled>Auto Selected
+                  </select>
+              </label>
+              
+              <label>CPU Memory:
+                  <select class="form-control dependant" name='memory'>
+                    <option selected hidden disabled>Auto Selected
+                  </select>
+              </label>
+          </section>
+          
+          <section class='notes'>
+            <label>Notes:
+                <textarea name='notes' class='dependant'></textarea>
+            </label>
+          </section>
+        </div>
+        
+        
+        
+        
+        
+        
+        
+        
+        
+        
+        <!--
+            cpu-extra.js contains the PHP generated JSON data.
+            This could be generated "on-the-fly" using PHP or
+            other server side language that can read the csv 
+            file.
+        -->
+        <script src='cpu-extra.js'></script>
+        <script>
+
+            var _data = {
+              "Intel": {
+                "Celeron": "Celeron",
+                "Celeron D": "Celeron D",
+                "Celeron Dual-Core": "Celeron Dual-Core",
+                "Celeron M": "Celeron M",
+                "Core 2 Duo": "Core 2 Duo",
+                "Core 2 Extreme": "Core 2 Extreme",
+                "Core 2 Quad": "Core 2 Quad",
+                "Core i3": "Core i3",
+                "Core i5": "Core i5",
+                "Core i7": "Core i7",
+                "Core i7 Extreme Edition": "Core i7 Extreme Edition",
+                "Core i9": "Core i9",
+                "Core i9 Extreme Edition": "Core i9 Extreme Edition",
+                "Pentium": "Pentium",
+                "Pentium 4": "Pentium 4",
+                "Pentium D": "Pentium D",
+                "Pentium Dual-Core": "Pentium Dual-Core",
+                "Pentium Extreme Edition": "Pentium Extreme Edition",
+                "Pentium III": "Pentium III",
+              },
+              "AMD": {
+                "APU A10-Series": "APU A10-Series",
+                "APU A12 Series": "APU A12 Series",
+                "APU A4-Series": "APU A4-Series",
+                "APU A6-Series": "APU A6-Series",
+                "APU A8-Series": "APU A8-Series",
+                "APU E-Series": "APU E-Series",
+                "Athlon": "Athlon",
+                "Athlon 64": "Athlon 64",
+                "Athlon 64 X2": "Athlon 64 X2",
+                "Athlon Dual Core": "Athlon Dual Core",
+                "Athlon II": "Athlon II",
+                "Athlon X2 Series": "Athlon X2 Series",
+                "Athlon X4 Series": "Athlon X4 Series",
+                "Athlon XP": "Athlon XP",
+                "Duron": "Duron",
+                "FX": "FX",
+                "K6": "K6",
+                "Opteron": "Opteron",
+                "Phenom": "Phenom",
+                "Phenom II": "Phenom II",
+                "Ryzen 3": "Ryzen 3",
+                "Ryzen 5": "Ryzen 5",
+                "Ryzen 7": "Ryzen 7",
+                "Ryzen 9": "Ryzen 9",
+                "Sempron": "Sempron",
+                "Threadripper": "Threadripper",
+              }
+            };
+            
+
+            /*
+                shorthand utility functions
+            */
+            const d=document;
+            const q=(e,n=d)=>n.querySelector(e);
+            const qa=(e,n=d)=>n.querySelectorAll(e);
+            
+            /*
+                nodelist of ALL select menus
+            */
+            const col=qa('.advanced_search_container > section > label > select');
+            
+            /*
+                utility to clear the HTML from within
+                a select menu but retain the first
+                element - the default value.
+            */
+            const recycle=(n)=>{
+                if( n.type!=='select-one' ){
+                    n.value='';
+                    return false;
+                }
+                let clone=n.firstElementChild.cloneNode( true );
+                    n.innerHTML='';
+                    n.appendChild( clone );
+                    n.classList.remove('active')
+                return n;
+            };
+            
+            const setactive=(n)=>n.classList.add('active')
+
+
+
+
+            col.forEach( select=>select.addEventListener('change',e=>{
+              setactive( e.target );
+              
+              /*******************************************
+                populate the initial Intel/AMD dropdown.. 
+                let battle commence!
+              */
+              if( e.target.id=='env-select' ){
+                // find the NEXT select menu to add options to
+                // done using the dataset attribute ( data-next )
+                let sel=q('select[name="'+e.target.dataset.next+'"]');
+                
+                let obj=_data[ e.target.value ]; // using original data variable
+                
+                // ensure the next element is empty
+                recycle( sel );
+                
+                // add all options based upon which Type is selected 
+                Object.keys( obj ).forEach( k=>{
+                  sel.appendChild( new Option( k, obj[k] ) );
+                });
+                
+                
+                return;
+              }
+              
+              
+              
+              // If the Type or Family is changed, clear all dependant select menus
+              if( e.target.dataset.recycle ){
+                qa('.dependant').forEach( n=>recycle(n) )
+              }
+              
+
+              
+              
+              
+              /*******************************************
+                Events registered on other dropdowns
+              */
+              if( e.target.hasAttribute('name') && json[0].hasOwnProperty( e.target.name ) ){
+                Object.keys( json ).some( key=>{
+                
+                    // The "name" is that of the SELECT menu 
+                    let name=e.target.name;
+                    
+                    // The "item" is the value from selected menu
+                    let item=json[ key ][ name ];               
+                
+                
+                    if( item==e.target.value ) {
+                        let value;
+                        
+                        // Now search through entire JSON file to find matches to the selected "item"
+                        Object.keys( json ).forEach( k=>{
+                            obj=json[ k ];
+                            if( obj[ name ]==item ){
+                                /*
+                                    Once the "processor" has been selected any dependant
+                                    select menus will have their values added and set as
+                                    selected.
+                                    
+                                    Changing the "family" will clear all dependant select
+                                    menus in readiness for a new Processor & associated 
+                                    details.
+                                */
+                                if( e.target.dataset.next ){
+                                    /*
+                                        Find the next select menu
+                                    */
+                                    value=obj[ e.target.dataset.next ];
+                                    q( 'select[ name="'+e.target.dataset.next+'" ]' ).appendChild( new Option( value, value ) );
+                                }else{
+                                    /*
+                                        target all dependant menus
+                                    */
+                                    qa( 'section.details select.dependant' ).forEach(n=>{
+                                        recycle(n);
+                                        value=obj[ n.name ];
+                                        n.appendChild( new Option( value, value ) );
+                                        n.value=value;
+                                    });
+                                    
+                                    q('textarea[name="notes"]').value=obj.notes
+                                }
+                            }
+                        });
+                        console.info( name, item );
+                        return true
+                    }
+                });
+              }
+            }));
+        </script>
+    </body>
+</html>
+
",html +"how to align fix align in screen bottom on scrollabe div in material ui react

I have created this component in react js using material UI +

+

what I am trying to achieve here is push that chat input at bottom of screen of desktop or mobile and its width should of same as,but somehow its width always is half and when I am changing its width from inherit to 100% it is going out of screen

+

<> +<Box style={{backgroundColor:'red'}}> + + + + + +{relativeUserinfo.name} +

+
                    </Grid>
+                </Grid>
+            </Box>
+            <Box sx={{ overflowY: "scroll",backgroundColor:'blue' }}>
+                <List sx={{ width: '100%', bgcolor: 'background.paper' }}>
+                    {Array.isArray(messageDetails) && messageDetails.map((message) =>
+                        <>
+                            <ListItem key={message._id}>
+                                <ListItemAvatar>
+                                    <Avatar>
+                                        <PersonOutline />
+                                    </Avatar>
+                                </ListItemAvatar>
+                                <ListItemText primary={getChatUsername(user, message.relativeUserId)} secondary={message.messageText} />
+                                <span style={{ color: "grey", fontSize: '10px' }}>{formatDistanceToNow(new Date(message.createdAt))} ago</span>
+                            </ListItem>
+                        </>)}
+                </List>
+                <Input
+                    style={{ backgroundColor: '#EEEEEE', padding: '10px' , width: 'inherit',position: 'fixed', bottom: '0'}}
+                    value={message_input}
+                    onChange={(e) => setMessageInput(e.target.value)}
+                    type="text"
+                    inputProps={{
+                        style: { padding: "10px" },
+                    }}
+                    disableUnderline
+                    fullWidth
+                    placeholder="Type message...."
+                    startAdornment={
+                        <TagFacesIcon
+                            sx={{
+                                paddingLeft: "20px",
+                                color: "#777",
+                            }}
+                        />
+                    }
+                    endAdornment={
+                        <IconButton sx={{ paddingRight: "20px", }} onClick={handleMessageSubmit}>
+                            <SendIcon
+                                sx={{ color: "#777" }}
+                            />
+
+                        </IconButton>
+
+                    }
+                />
+                
+            </Box> */}
+            </Box>
+            
+
+        </Box>
+    </>
+
+

when I am changing width to 100% this is happening,and chrome mobile screen it disappears,event though I did not any fix height to any of div

+

","

The reason why width: 100% doesn't do what you expected is because the element has a fixed position. It isn't relative to the container <Box/>, so width: 100% just means 100% of the width of the body (not the Box/container), which is likely rougly the size of your screen. You shouldn't use fixed in this scenario.

+

To fix this either use margins:

+
.box-class, .input-class { position: relative; width: 100%; }
+
+.list-class { margin-bottom: auto; } /* Push following elements to the bottom */
+
+/* or.. */
+.input-class { margin-top: auto; } /* Push it and following elements to the bottom */
+
+

or, preferably, use Flexbox:

+
.box-class { display: flex; flex-direction: column; height: 100%; }
+.list-class { flex-grow: 1; } /* Grow to fill available space */
+.input-class { position: relative; } /* Width should just automatically be the full width of the box, otherwise just add width: 100% */
+
+

Also, make sure to grow your containers to the desired height/width, e.g.:

+
html { height: 100%; width: 100%; }
+body { min-height: 100%; width: 100% }
+/* repeat for any other containers, which should preferably have a position: relative */
+
+

Hope that helps!

",html +"How to get text inside another element in li list - Javascript

I have a li tag that contain p tag, inside p contain some span tag

+

I want to get the text of the "role" in +<span class="tag">{{role}}</span>

+

I'm trying

+
Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="userJoinedList"] li')).forEach(function(element) {
+        console.log(element.innerHTML)
+}
+
+
<ul data-tag="userJoinedList">
+    {{#users}}
+       <li class="users">
+           <p>
+              <span class="users">{{username}}</span> 
+              <span class="tag">{{role}}</span>
+           </p>
+       </li>
+    {{/users}}
+</ul>
+
","

Why not just use a selector?

+
document.querySelectorAll('ul[data-tag="userJoinedList"] li p span.tag')
+    .forEach(function(element) { 
+        console.log(element.innerHTML)
+    }
+)
+
+
",html +"Responsive placement of Grid on a photo

I have designed like the photo below in mobile mode, but because I want it to be responsive, I used grid and flex-box, but according to the sample photo, I could not place the components. +

+

1- By placing a photo, the layout of the page is ruined. +

+

2- I tried putting the grid on the whole picture but failed.
+3- I also made the colored boxes with flex.
+4- Once, I put the photo in the CSS file using the background: URL() command, which improved its layout, but the problem was that I wanted the button and these colored boxes to be placed a little lower than the photo, but all the changes were only It was done in the background photo range and I could not change their location with the position. +

+
    +
  • Tell me what method should I use to implement this example so that it becomes responsive much more easily.
  • +
+
<style>
+    .grid--1×2 {
+      display: grid;
+      grid-template-columns: 1fr 1fr;
+    }
+
+    .pos--relative {
+      position: relative;
+    }
+
+    .pos--absolute {
+      position: absolute;
+    }
+
+    .side__box-time {
+      display: flex;
+      justify-content: center;
+      flex-direction: column;
+    }
+
+    .box {
+      border: 1px solid black;
+    }
+
+    .box--green {
+      background: green;
+    }
+
+    .box--blue {
+      background: blue;
+    }
+
+    .box--yellow {
+      background: yellow;
+    }
+
+    .container-flex {
+      display: flex;
+      flex-direction: column;
+    }
+
+    .btn {
+      border: 1px solid black;
+      background: black;
+      color: white;
+      padding: 6px;
+      bottom: 0;
+    }
+
+   .img {
+        width: 100%;
+   }
+  </style>
+</head>
+
+<body>
+  <div class="grid--1×2 pos--relative">
+    <img src="images/sandwich.jpg" class="img" alt="" />
+
+    <!--Empty cell-->
+    <div class="pos--reletive"></div>
+
+    <div class="container-flex">
+      <div class="box box--green">First Box</div>
+      <div class="box box--yellow">Second Box</div>
+      <div class="box box--blue">third Box</div>
+    </div>
+
+    <a class="btn pos--absolute" href="#">FULL RECIPE</a>
+  </div>
+</body>
+
+
","

+

+
+
:root {
+  /* change this values to make it more custum */
+  --height: 500px;
+  --width-childs: 40%;
+  --outside-value: 1rem;
+  --image-url: url(""https://picsum.photos/1000"")
+}
+
+.body-full {
+  height: 100vh;
+  margin: 0;
+}
+
+.centered {
+  display: grid;
+  place-items: center;
+}
+
+.pos--relative {
+  position: relative;
+}
+
+.pos--absolute {
+  position: absolute;
+}
+
+.container {
+  height: var(--height);
+  width: var(--height);
+}
+
+.bg-image {
+  background-image: var(--image-url);
+  background-position: center;
+  background-size: cover;
+  background-repeat: no-repeat;
+}
+
+.right-childs {
+  display: grid;
+  height: calc(100% + var(--outside-value));
+  width: var(--width-childs);
+  right: 0;
+}
+
+.outside-position {
+  --negative-outside-position: calc(var(--outside-value) * -1);
+  position: absolute;
+  bottom: var(--negative-outside-position);
+  left: var(--negative-outside-position);
+}
+
+.box--green {
+  background: green;
+}
+
+.box--blue {
+  background: blue;
+}
+
+.box--yellow {
+  background: yellow;
+}
+
+.btn {
+  border: 1px solid black;
+  background: black;
+  color: white;
+  padding: 6px;
+}
+
<body class=""body-full centered"">
+  <div class=""container pos--relative bg-image"">
+
+    <div class=""right-childs pos--absolute"">
+      <div class=""box box--green centered"">First Box</div>
+      <div class=""box box--blue centered"">Second Box</div>
+      <div class=""box box--yellow centered"">third Box</div>
+    </div>
+
+    <a class=""btn outside-position"" href=""#"">FULL RECIPE</a>
+  </div>
+</body>
+
+
+

",html +"Is there a way to place text over image without background-image, or position: relative?

My situation is that I don't want it as a background-image because I'm changing the opacity on hover, and so that it didn't affect the text as well I made them separate elements. +However, moving them using position: relative; means that I am left with blank space where their supposed to be in page flow.

+

Any help would be greatly appreciated.

+

+
+
.flex-container {
+    display: flex;
+    flex-direction: row;
+    flex-wrap: wrap;
+    justify-content: space-evenly;
+    width: 100%;
+}
+
+div {
+    width: 24%;
+    min-width: 400px;
+    height: 25em;
+    transition: 200ms;
+    margin: 1rem 0;
+}
+
+div.background-img {
+    width: 100%;
+    height: 100%;
+}
+
+#img-1 {
+    background-image: url(""imgs/tokyo.jpg"");
+}
+
+/* Later in code */ 
+
+.background-img:hover {
+    transition: 200ms;
+    filter: brightness(50%);
+    outline: 1px white solid;
+    outline-offset: -20px;
+    border-radius: 5%;
+}
+
+div .hidden-text {
+    transition: 200ms;
+    position: relative;
+    bottom: 100%;
+    color: white;
+    opacity: 0;
+    pointer-events: none;
+}
+
+div:hover .hidden-text {
+    transition: 200ms;
+    color: rgb(255, 255, 255, 1);
+    opacity: 1;
+}
+
<section class=""flex-container"">
+      <div>
+        <h1>Holiday Destinations</h1>
+        <span>This is a collection of locations that I either would love to visit, or loved visiting.</span>
+        <p>
+          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat totam
+          eum asperiores assumenda, amet rem molestiae pariatur at nulla sequi
+          debitis itaque voluptatem modi corrupti fugiat sed quod dolores
+          perspiciatis maiores in! Tenetur molestiae eum cupiditate obcaecati
+          consectetur. Culpa consequatur doloribus, non voluptates quia commodi
+          dolore mollitia cupiditate modi dolorem?
+        </p>
+      </div>
+      <div>
+        <div class=""background-img"" id=""img-1""></div>
+        <h2 class=""hidden-text"">Tokyo - Japan</h2>
+        <p class=""hidden-text"">Lorem ipsum dolor sit amet.</p>
+      </div>
+</section>
+
+
+

+

Website here --> https://dex-hewitt.github.io/holiday-destinations

+

Thank you!

+

Also please let me know if I've written question poorly or not included any necessary parts I am new to stackoverflow.

","

You can approach it this way if you don't want it to be as a background. Let me know

+

+
+
.flex-container {
+    display: flex;
+    flex-direction: row;
+    flex-wrap: wrap;
+    justify-content: space-evenly;
+    width: 100%;
+}
+
+div {
+    width: 24%;
+    min-width: 400px;
+    height: 25em;
+    transition: 200ms;
+    margin: 1rem 0;
+}
+
+div.background-img {
+    width: 100%;
+    height: 100%;
+    
+}
+
+div img {
+width: 500px;
+height: 500px;
+object-fit: cover;
+}
+
+/* Later in code */ 
+
+.background-img:hover {
+    transition: 200ms;
+    filter: brightness(50%);
+    outline: 1px white solid;
+    outline-offset: -20px;
+    border-radius: 5%;
+}
+
+div .hidden-text {
+    transition: 200ms;
+    position: relative;
+    bottom: 100%;
+    color: white;
+    opacity: 0;
+    pointer-events: none;
+    text-align: center;
+}
+
+div:hover .hidden-text {
+    transition: 200ms;
+    color: rgb(255, 255, 255, 1);
+    opacity: 1;
+}
+
<section class=""flex-container"">
+      <div>
+        <h1>Holiday Destinations</h1>
+        <span>This is a collection of locations that I either would love to visit, or loved visiting.</span>
+        <p>
+          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat totam
+          eum asperiores assumenda, amet rem molestiae pariatur at nulla sequi
+          debitis itaque voluptatem modi corrupti fugiat sed quod dolores
+          perspiciatis maiores in! Tenetur molestiae eum cupiditate obcaecati
+          consectetur. Culpa consequatur doloribus, non voluptates quia commodi
+          dolore mollitia cupiditate modi dolorem?
+        </p>
+      </div>
+     <div>
+        <img class=""background-img"" src=""https://thumbs.dreamstime.com/b/shinjuku-gyoen-national-garden-tokyo-japan-large-park-shibuya-lake-asian-153188061.jpg"" >
+        <h2 class=""hidden-text"">Tokyo - Japan</h2>
+        <p class=""hidden-text"">Lorem ipsum dolor sit amet.</p>
+      </div>
+</section>
+
+
+

",html +"getting jekyll variables to work within each other

is there any way to get one jekyll variable inside of another? like combine them, almost. see, i want to get {{ /games/{{ include.name }} | relative_url }} to work by getting /games/name-of-game and turning it into a relative URL. is there another solution or a reason why mine isn't working?

","

I am not sure what your problem is. It could be the order that liquid is executed or the order Jekyll renders your site. Typically, you don't see curly braces within curly braces.

+

What you could do is:

+

{{ "/games/" | append: include.name | relative_url }}

",html +"Auto select multiple dropdown with formBuilder

I've created a multiple select dropdown but in that list I would like to make auto select.

+

for example:

+
String[] names = ["ant", "bat", "cat", "dog"];
+String[] autoSelectName = ["bat", "dog"];
+
+

So what I exactly want that I would like to bat and dog should be selected when I'll open the dropdown.

+

.html

+
<mat-form-field id="name-dropdown">
+    <mat-select formControlName="names" multiple>
+         <mat-option *ngFor="let name of names" [value]="name">
+             {{name}}
+         </mat-option>
+    </mat-select>
+</mat-form-field>
+
+

Thanks in advance.

","

You only need "feed" with an array the formControl, e.g.

+

using pathValue:

+
this.form.pathValue({names:this.autoSelectName})
+
+

using setValue to the control:

+
this.form.get('names').setValue(this.autoselectName)
+
+

When you create the form using the contructors:

+
 this.form=new FormGroup({
+     names:new FormControl(this.autoSelectName,Validators.required)
+ })
+
+

Using formBuilder

+
 this.form=this.fb.group({
+    names:[this.autoSelectName,Validators.required]
+ })
+
+

Even you neen't an auxiliar variable

+
 this.form=this.fb.group({
+    names:[["bat", "dog"],Validators.required]
+ })
+
",html +"is there a way to automatically make a child in a grid element go down if the parent's width is 70% of the screen
css
+.imgcont {
+  width: 200px;
+  height: 200px;
+  overflow: hidden;
+}
+
+.imgcont img {
+  width: 400px;
+  max-height: 400px;
+  margin: -50% 0 0 -50%;
+}
+
+.imageconcon {
+max-width:70%;
+  width: max-content;
+  display: grid;
+  grid-template-columns: repeat(3, 0.7fr);
+
+  box-shadow: 0px 2px 10px black;
+}
+
+
<div class="imageconcon">
+  <div class="imgcont">
+    <img src="https://randomwordgenerator.com/img/picture-generator/55e2d5424a57ab14f1dc8460962e33791c3ad6e04e507440712b7bd29548cd_640.jpg"></div>
+  <div class="imgcont">
+    <img src="https://randomwordgenerator.com/img/picture-generator/55e6dc414a54af14f1dc8460962e33791c3ad6e04e5074417c2f7cd3924fc7_640.jpg"></div>
+  <div class="imgcont">
+    <img src="https://randomwordgenerator.com/img/picture-generator/55e4d5434a54a514f1dc8460962e33791c3ad6e04e5074417d2e72d1974ec1_640.jpg"></div>
+</div>
+
+

I want the imgconcon's children to go down and start a new column if the imgconcon's width is 70% of the screen, how do I do this?

","

you have to define the grid with

+

grid-template-columns: repeat(auto-fill, {sizeOfAColumn});

+

don't put the width at column or image level let the grid define it

+

+
+
.imgcont {
+  height: 200px;
+  overflow: hidden;
+}
+
+.imgcont img {
+  max-height: 400px;
+}
+
+.imageconcon {
+  max-width: 70%;
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 200px);
+  box-shadow: 0px 2px 10px black;
+}
+
<div class=""imageconcon"">
+  <div class=""imgcont"">
+    <img src=""https://randomwordgenerator.com/img/picture-generator/55e2d5424a57ab14f1dc8460962e33791c3ad6e04e507440712b7bd29548cd_640.jpg"" /></div>
+  <div class=""imgcont"">
+    <img src=""https://randomwordgenerator.com/img/picture-generator/55e6dc414a54af14f1dc8460962e33791c3ad6e04e5074417c2f7cd3924fc7_640.jpg"" /></div>
+  <div class=""imgcont"">
+    <img src=""https://randomwordgenerator.com/img/picture-generator/55e4d5434a54a514f1dc8460962e33791c3ad6e04e5074417d2e72d1974ec1_640.jpg"" /></div>
+</div>
+
+
+

",html +"Select and add an event listener to an element inside a template literal string

I want to add an event listener to icon img which first one to delete and second for edit. How can I select img from template string in this code?

+
function renderStudentList() {
+tableBody.innerHTML = "";
+studentList.map((student) => {
+    const studentRow = `
+        <tr>
+            <td>${student.id}</td>
+            <td>${student.name}</td>
+            <td>${student.surname}</td>
+            <td>${student.birthday}</td>
+            <td>${student.age}</td>
+            <td>${student.gender === "M" ? "Male" : "Female"}</td>
+            <td>
+                <img src="./icons/delete.svg" alt="delete">
+                <img src="./icons/edit.svg" alt="edit">
+            </td>
+        </tr>
+    `;
+    tableBody.insertAdjacentHTML("beforeend", studentRow);
+
+})
+}
+
","

You can set up the click handlers while generating the template. This way you don't have to query them afterwards. Like so:

+
function deleteClickHandler() {}
+function editClickHandler() {}
+
+function renderStudentList() {
+  tableBody.innerHTML = "";
+  studentList.map((student) => {
+    const studentRow = `
+      <tr>
+        <td>${student.id}</td>
+        <td>${student.name}</td>
+        <td>${student.surname}</td>
+        <td>${student.birthday}</td>
+        <td>${student.age}</td>
+        <td>${student.gender === "M" ? "Male" : "Female"}</td>
+        <td>
+          <img src="./icons/delete.svg" alt="delete" onclick="deleteClickHandler()" />
+          <img src="./icons/edit.svg" alt="edit" onclick="editClickHandler()" />
+        </td>
+      </tr>
+    `;
+    tableBody.insertAdjacentHTML("beforeend", studentRow);
+  });
+}
+
",html +"How to get all the characters not contained in anchor tags using RegEx in Javascript?

How can I use regex to get an array of all the individual characters not contained within anchor tags? +So for example, with this text:

+
DOWNLOAD <a href="https://this.com/" target="_blank">THIS</a> OR <a href="https://that.io/" target="_blank">THAT</a>
+
+

I want an array of the indices for the characters D,O,W,N,L,O,A,D, ,T,H,I,S, , ... etc.

+

I managed to figure out how to get everything I don't want selected, using this: /(?:<.*?>)

+

But I don't know how to use that to get all the characters outside of that group.

","

As already pointed out by @Cid, don't do this with regular expressions. Instead, use something like below and read the input character by character:

+

+
+
function reader(el) {
+  let i = 0;
+  let src = el.innerHTML;
+  
+  const r = {
+    done() {
+      return i >= src.length;
+    },
+    advance() {
+      i += 1;
+    },
+    char() {
+      let c = !r.done() ? src[i] : '';
+      r.advance();
+      return c;
+    },
+    peek() {
+      return !r.done() ? src[i] : '';
+    }
+  };
+  return r;
+}
+
+function collector(el) {
+  const r = reader(el);
+  
+  const skipUntil = char => {
+    while (r.peek() !== char) {
+     r.advance();
+    }
+    r.advance();
+  };
+  
+  return {
+    collect() {
+      const v = [];
+      while (!r.done()) {
+        if (r.peek() === '<') {
+          skipUntil('>');
+        } else if (r.peek() === '\n') {
+          r.advance();
+        } else {
+          v.push(r.char());
+        }
+      }
+      return v;
+    }
+  };
+}
+
+
+
+/* --- */
+
+const el = document.querySelector('#source');
+const cl = collector(el);
+console.log(cl.collect());
+
<div id=""source"">
+DOWNLOAD <a href=""#noop"">THIS</a> OR <a href=""#noop2"">THAT</a>
+</div>
+
+
+

",html +"How do I blur the right and left sides of a scroll container?

I am trying to make the left and right sides of the container have a blur effect using the box-shadow property. The container (boxes) contains what boxes are currently in view as there are multiple boxes in that container that can be scrolled through using 2 buttons (with ids backwards and forwards.

+

How do I add a fading blur effect to the edges of the container? The far edges shouldn't be visible and then it should gradually get lighter.

+

Example:

+

+

vs mine:

+

+

html:

+
<div class="boxes-container">
+    <div class="boxes">
+        <!-- box 1 -->
+        <div class="box">
+            <div class="img-container">
+                <img src="https://a0.muscache.com/pictures/b6005f78-45e6-403a-bc1d-3351ae83d149.jpg" alt="">
+            </div>
+            <h6>Why host on Airbnb?</h6>
+            <p>Hosts reveal what they love about sharing their space on Airbnb.</p>
+        </div>
+        <!-- box 2 -->
+        <div class="box">
+            <div class="img-container">
+                <img src="https://a0.muscache.com/pictures/9ac19f4a-a59c-47f9-8223-09120b52cd2d.jpg" alt="">
+            </div>
+            <h6>How to get started on Airbnb</h6>
+            <p>From creating your listing to prepping your space, learn how to start hosting.</p>
+        </div>
+        <!-- box 3 -->
+        <div class="box">
+            <div class="img-container">
+                <img src="https://a0.muscache.com/pictures/4d0cc0ed-ad85-4efd-b98e-386d22ab195a.jpg" alt="">
+            </div>
+            <h6>How to earn money on Airbnb</h6>
+            <p>Here's what every Host needs to know about pricing and payouts.</p>
+        </div>
+        <!-- box 4 -->
+        <div class="box">
+            <div class="img-container">
+                <img src="https://a0.muscache.com/pictures/4efaca33-ca90-4d94-a79b-381cf0179355.jpg" alt="">
+            </div>
+            <h6>Designing your space</h6>
+            <p>Designing your space for guests can be a quick way to boost your bookings.</p>
+        </div>
+        <!-- box 5 -->
+        <div class="box" id="last-box">
+            <div class="img-container">
+                <img src="https://a0.muscache.com/pictures/3cea79b0-79c3-4604-8fd9-7ef5cee4aa42.jpg" alt="">
+            </div>
+            <h6>Secrets from a seasoned Superhost</h6>
+            <p>Superhost Nikki shares her tips, from setting up to standing out.</p>
+        </div>
+    </div>
+</div>
+
+

css:

+
.boxes-container {
+    margin-top: 2rem;
+    width: 100%;
+    position: relative;
+}
+
+.boxes {
+    display: flex;
+    overflow-x: scroll;
+    -ms-overflow-style: none;
+    scrollbar-width: none;
+    scroll-behavior: smooth;
+    // border: 2px solid red;
+    position: relative;
+
+    &::before, &::after {
+        content: '';
+        position: absolute;
+        top: 0;
+        width: 2rem;
+        height: 100%;
+    }
+
+    &::before {
+        box-shadow: 50px 0 50px #fff inset;
+        left: 0;
+    }
+
+    &::after {
+        box-shadow: -50px 0 50px #fff inset;
+        // box-shadow: -80px 0 #fff inset;
+        right: 0;
+    }
+    
+    &::-webkit-scrollbar {display: none}
+
+    .box {
+        @include flexCenter(column);
+        align-items: flex-start;
+        gap: 1rem;
+        width: 332px;
+        max-width: 332px;
+        cursor: pointer;
+        margin-right: 2rem;
+        // background-color: green;
+
+        &#last-box {
+            padding-right: 2rem;
+        }
+
+        .img-container {
+            
+            img {
+                width: 322px;
+                max-width: 322px;
+                height: 200px;
+                object-fit: cover;
+                border-radius: 10px;
+            }
+        }
+
+        h6 {
+            font-size: 18px;
+        }
+
+        p {
+            font-size: 14.5px;
+            font-weight: lighter;
+            letter-spacing: 0.1px;
+        }
+    }
+}
+
","

Use mask. Here is simplified example:

+

+
+
.container {
+  display: flex;
+  gap: 20px;
+  overflow:hidden;
+  -webkit-mask: linear-gradient(90deg,#0000,#000 10% 80%,#0000)
+}
+
<div class=""container"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+  <img src=""https://picsum.photos/id/1069/200/150"">
+</div>
+
+
+

",html +"JsChart height issue

I am using jschart to render bar chart of the data. Everything work fine but the height of chart is not enough to show the data vertically. As you can see in attached image for 100% the 00% part is cut and only 1 is shown. I tried setting height within div tag and setting responsive:true but it stretches badly and labels,bars etc don't become clear. Below is my code

+

+
+
        document.addEventListener(""DOMContentLoaded"", function() {
+            var patternSize = 20;
+            // Bar chart
+            new Chart(document.getElementById(""mychart""), {
+                type: ""bar"",
+                data: {
+                    labels: [""1.1"",""1.2"",""1.3"",""1.4"",""1.5"",""2.1"",""2.2"",""2.3"",""2.4"",""2.5"",""2.6"",""2.7"",""2.8"",""3.1"",""3.2"",""3.3"",""3.4"",""3.5"",""4.1"",""4.2"",""4.3"",""4.4"",""4.5"",],
+                    datasets: [{
+                        label: ""Progress"",              
+                        backgroundColor:""#ff0000"",
+                        data: [74.5,70.8,20,16.7,0,90,43.3,17.8,37.5,100,11.3,4.6,0,100,12.5,0,15,0,44.4,0,0,0,20,],        
+                    }
+                ]
+                },
+                options: {  
+//                  responsive: true,           
+                    maintainAspectRatio: false, 
+                    legend: {
+                    display: true,
+                    position: 'bottom',
+                    },      
+                    scales: {
+                        yAxes: [{
+                            gridLines: {
+                                display: true
+                            },
+                            stacked: false,
+                            ticks: {
+                                stepSize: 20,
+                                callback: function(value, index, ticks) {
+                                return  value + '%';
+                                }
+                            },
+                            scaleLabel: {
+                                display: true,
+                                fontSize: 18,
+                                fontColor:""#000000"",
+                                fontStyle: ""bold"",
+                                labelString: 'Percentages'
+                            }
+                        }],
+                        xAxes: [{
+                            stacked: false,
+                            gridLines: {
+                                display:false
+                            },              
+                            ticks:{
+                                maxRotation: 90,
+                                minRotation: 90,
+                            },          
+                            scaleLabel: {
+                                display: true,
+                                fontSize: 18,
+                                fontColor:""#000000"",
+                                fontStyle: ""bold"",
+                                labelString: 'ACTIVITY'                         
+                            }
+                        }]
+                    },
+                }, //end options
+/**value on top of bar**/
+
+plugins: {
+          
+          afterDatasetsDraw: function (context, easing) {
+            var ctx = context.chart.ctx;
+            context.data.datasets.forEach(function (dataset) {
+              for (var i = 0; i < dataset.data.length; i++) {
+                if (dataset.data[i] != 0) {
+                  var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
+                  var textY = model.y + (dataset.type == ""line"" ? -3 : 15);
+
+                  ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
+                  ctx.textAlign = 'start';
+                  ctx.textBaseline = 'middle';
+                  ctx.fillStyle = dataset.type == ""line"" ? ""black"" : ""black"";
+                  ctx.save();
+                  ctx.translate(model.x, textY-15);
+                  ctx.rotate(4.7);
+                  data="" ""+dataset.data[i]+""%"";
+                  ctx.fillText(data, 0, 0);
+                  ctx.restore();
+                }
+              }
+            });
+          }
+        
+      }                                                 
+/**end value on top of bar**/
+            });
+        });
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js""></script>
+<div class=""chart chart-lg"" id=""chart-wrapper"">
+<canvas id=""mychart""></canvas>
+</div>
+
+
+

+

chart issue

","

I have tried your use case and the issue is not the clip but there is not space on top of chart area to draw your labels. You should add padding on top of the chart in order to show the labels, by options.layout.padding configuration.

+

+
+
const ctx = document.getElementById(""myChart"");   
+var patternSize = 21;
+Chart.plugins.register({
+  afterDatasetsDraw: function (context, easing) {
+    var ctx = context.chart.ctx;
+    context.data.datasets.forEach(function (dataset) {
+      for (var i = 0; i < dataset.data.length; i++) {
+        if (dataset.data[i] != 0) {
+          var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
+          var textY = model.y + (dataset.type == ""line"" ? -3 : 15);
+          ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
+          ctx.textAlign = 'start';
+          ctx.textBaseline = 'middle';
+          ctx.fillStyle = dataset.type == ""line"" ? ""black"" : ""black"";
+          ctx.save();
+          ctx.translate(model.x, textY-15);
+          ctx.rotate(4.7);
+          data="" ""+dataset.data[i]+""%"";
+          ctx.fillText(data, 0, 0);
+          ctx.restore();
+        }
+      }
+    });
+  }
+});
+const chart = new Chart(ctx, {
+  type: ""bar"",
+  data: {
+    labels: [""1.1"",""1.2"",""1.3"",""1.4"",""1.5"",""2.1"",""2.2"",""2.3"",""2.4"",""2.5"",""2.6"",""2.7"",""2.8"",""3.1"",""3.2"",""3.3"",""3.4"",""3.5"",""4.1"",""4.2"",""4.3"",""4.4"",""4.5"",],
+     datasets: [{
+       label: ""Progress"",  
+       backgroundColor:""#ff0000"",
+       data: [74.5,70.8,20,16.7,0,90,43.3,17.8,37.5,100,11.3,4.6,0,100,12.5,0,15,0,44.4,0,0,0,20,],        
+     }]
+  },
+  options: {  
+        layout: {
+          padding: {
+            top: 50
+          }
+        },
+        maintainAspectRatio: false, 
+        legend: {
+          display: true,
+          position: 'bottom',
+        },      
+        scales: {
+          yAxes: [{
+            gridLines: {
+              display: true
+            },
+            stacked: false,
+            ticks: {
+              stepSize: 20,
+              callback: function(value, index, ticks) {
+                return  value + '%';
+              }
+            },
+            scaleLabel: {
+              display: true,
+              fontSize: 18,
+              fontColor:""#000000"",
+              fontStyle: ""bold"",
+              labelString: 'Percentages'
+            }
+          }],
+          xAxes: [{
+            stacked: false,
+            gridLines: {
+              display:false
+            },  
+            ticks:{
+              maxRotation: 90,
+              minRotation: 90,
+            },          
+            scaleLabel: {
+              display: true,
+              fontSize: 18,
+              fontColor:""#000000"",
+              fontStyle: ""bold"",
+             labelString: 'ACTIVITY' 
+            }
+          }]
+        }
+    },
+});
+
.myChartDiv {
+  max-width: 617px;
+  max-height: 250px;
+}
+
<script src=""https://cdn.jsdelivr.net/npm/chart.js@2.4.0/dist/Chart.min.js""></script>
+<html>
+  <body>
+    <div class=""myChartDiv"">
+      <canvas id=""myChart"" width=""617"" height=""250""/>
+    </div>
+  </body>
+</html>
+
+
+

",html +"Add columns do DataTable with loop from html file

I want to add columns to my DataTable with the help of foreach from my <th> tags.
+I have some problem with it. I don't understand why there is an null exception. In my HTML file i don't have any empty tags.
+Fragment of my C# code:

+
DataTable dt = new DataTable();
+int i = 0;
+HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
+foreach (var row in table.SelectNodes("tr"))
+{
+    var headers = row.SelectNodes("th");
+    foreach (var el in headers)
+    {
+        if (headers != null)
+        {
+           dt.Columns.Add(headers[i].InnerText);
+           i++;
+        }
+    }
+}
+
+
+

There is a fragment of my HTML file:

+
<table>
+<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>
+<tr><th>id</th><th>inserted_at</th><th>DisplayName</th><th>DistinguishedName</th><th>Enabled</th><th>GivenName</th><th>HomeDirectory</th><th>Manager</th><th>Name</th><th>ObjectClass</th><th>ObjectGUID</th><th>SamAccountName</th><th>Surname</th><th>UserPrincipalName</th><th>RowError</th><th>RowState</th><th>Table</th><th>ItemArray</th><th>HasErrors</th></tr>
+
","

This works for your html:

+
var str = @"<table>
+<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>
+<tr><th>id</th><th>inserted_at</th><th>DisplayName</th><th>DistinguishedName</th><th>Enabled</th><th>GivenName</th><th>HomeDirectory</th><th>Manager</th><th>Name</th><th>ObjectClass</th><th>ObjectGUID</th><th>SamAccountName</th><th>Surname</th><th>UserPrincipalName</th><th>RowError</th><th>RowState</th><th>Table</th><th>ItemArray</th><th>HasErrors</th></tr>";
+
+var hdoc = new HtmlAgilityPack.HtmlDocument();
+
+hdoc.LoadHtml(str);
+
+var headerElements = hdoc.DocumentNode.Descendants("th");
+
+foreach(var headerElement in headerElements)
+{
+    Console.WriteLine(headerElement.InnerText);
+}
+
",html +"How can I handle multiple button?

I want to handle multiple buttons. My aim is when a user will click on the first button then the first paragraph will be changed, again when a user will click on the second button then the second paragraph will be changed. I tried, but not working. Please check my code and give me a solution....

+

+
+
var len = document.querySelectorAll("".myButton"").length
+var plen = document.querySelectorAll("".myP"").length
+for (i = 0; i < len; i++) {
+  for (j = 0; j < plen; j++) {
+    document.querySelectorAll("".myButton"")[i].addEventListener(""click"", function() {
+      if (document.querySelectorAll("".myButton"")[i] == document.querySelectorAll("".myP"")[j]) {
+        document.querySelectorAll("".myP"")[j].innerHTML = document.querySelectorAll("".myButton"")[i].innerHTML;
+      }
+    });
+  }
+}
+
<p class=""myP"">oke</p>
+<p class=""myP"">oke</p>
+
+<h1 class=""pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5"">00</h1><br>
+<hr style=""background-color:red; width:50%"">
+<button class=""btn bg-primary text-light mx-5 my-5 myButton"">one</button>
+<button class=""btn bg-primary text-light mx-5 my-5 myButton"">two</button>
+
+
+

+

error:

+
5_eventListener.html:43 Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
+    at HTMLButtonElement.<anonymous> (5_eventListener.html:43:119)
+
+

Error line:

+
document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;
+
","

Your code needs closures to work and that is quite tricky

+

Instead delegate - here I delegate from document, but if the buttons have a wrapper, you can delegate from that

+

Much simpler. Also use data attributes to give a target to the buttons

+

+
+
document.addEventListener(""click"", function(e) {
+  const tgt = e.target;
+  if (!tgt.matches("".myButton"")) return 
+  document.getElementById(tgt.dataset.target).innerHTML = tgt.innerHTML;
+})  
+
<p class=""myP"" id=""p1"">oke</p>
+<p class=""myP"" id=""p2"">oke</p>
+
+<h1 class=""pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5"">00</h1><br>
+<hr style=""background-color:red; width:50%"">
+
+<button class=""btn bg-primary text-light mx-5 my-5 myButton"" data-target=""p1"">one</button>
+<button class=""btn bg-primary text-light mx-5 my-5 myButton"" data-target=""p2"">two</button>
+
+
+

",html +"When selecting navbar option it disappears from the dropdown HTML JS

I think I'm doing something wrong but can't really figure out what.

+

I have a simple navigation dropdown to select a specific year. When I click on the year that I want, it should replace the label Year with the number.

+
<div class="dropdown">
+    <button onclick="myFunction()" class="dropbtn">Year</button>
+    <div id="myDropdown" class="dropdown-content">
+        <a onclick="tiptip(this)">2000</a>
+        <a href="">2001</a>
+        <a href="">2002</a>
+    </div>
+</div>
+
+<script>
+function tiptip(e) {
+    $('.dropbtn').html(e);
+
+}
+</script>
+
+

For now this is what I have. When selecting, for example 2000, I want that the text inside the button changes from 'Year' to '2000'. I'm able to do this, however the option '2000' seems to disappear from the dropdown.

+

Does anyone know what I'm doing wrong?

","

Into the original question you say you have a drop down, but I don't see any drop down in your code. So I will propose some different solutions one based on your code with the div HTML element with minor adjustments, and the other with an actual drop down, the HTML select element... and a bonus solution. +You will be free to choose and further adapt and optimize the one that best fits your needs. Also I will indicate you a short / one liner version of each solution.

+

Click on the blue button Run code snippet down each code snippet to actually see each one in action.

+

To see in action the one liner version you just have to:

+
    +
  1. click on the relative Copy snippet to answer
  2. +
  3. remove the 3 rows as indicated by the comment
  4. +
  5. de-comment the commented row as indicated by the comment
  6. +
  7. run it by clicking on Run code snippet
  8. +
+

1st Solution: using the "div" HTML element:

+

+
+
function changeYear(event)
+{
+    let tgtEl = document.getElementById(""myBtnId"");
+    let srcEl = event.target;
+    tgtEl.innerHTML = srcEl.innerHTML;
+
+    // The one liner version (remove or comment the 3 rows above and de-comment the following one):
+    // document.getElementById(""myBtnId"").innerHTML = event.target.innerHTML;
+}
+
<div class=""dropdown"">
+
+    <button id=""myBtnId"" onclick=""myFunction()"" class=""dropbtn"">Year</button>
+    
+    <div id=""myDropdown"" class=""dropdown-content"" onclick=""changeYear(event);"">
+        <a href=""javascript:void(0);"">2000</a> |
+        <a href=""javascript:void(0);"">2001</a> |
+        <a href=""javascript:void(0);"">2002</a> |
+        <a href=""javascript:void(0);"">2003</a>
+    </div>
+    
+
+
+

+

2nd Solution: using the "select" HTML element:

+

+
+
function changeYear(event)
+{
+    let tgtEl = document.getElementById(""myBtnId"");
+    let srcEl = event.target;
+    tgtEl.innerHTML = srcEl.value;
+
+    // The one liner version (remove or comment the 3 rows above and de-comment the following one):
+    // document.getElementById(""myBtnId"").innerHTML = event.target.value;
+}
+
<div class=""dropdown"">
+
+    <button id=""myBtnId"" onclick=""myFunction()"" class=""dropbtn"">Year</button>
+    
+    <select id=""myDropdown"" class=""dropdown-content"" onchange=""changeYear(event);"">
+        <option>2000</option>
+        <option>2001</option>
+        <option>2002</option>
+        <option>2003</option>
+    </select>
+</div>
+
+
+

+

How it works: +Basically the function changeYear(event) gets the source element that contains the year and extracts its content (innerHTML or value depending on the contingent need) and inject such a content into the target element that is the button innerHTML.

+

Also notice that if you wish to use in place of the <button></button> tag the <input type="button" value=""> tag, you must modify the code as follows: +in the first case using the combination of the div and the a HTML elements, the part

+
tgtEl.innerHTML = srcEl.value;
+
+

becomes

+
tgtEl.value = srcEl.value;
+
+

or

+

in the second case using the select HTML element, the part

+
    tgtEl.innerHTML = srcEl.value;
+
+

becomes

+
    tgtEl.value = srcEl.value;
+
+

While the one liner versions will be:

+

in the first case (with div+a):

+
    document.getElementById("myBtnId").value = event.target.innerHTML;
+
+

in the second case (with the select):

+
    document.getElementById("myBtnId").value = event.target.value;
+
+

The problem of the javascript:void(0); part:

+

Also notice that from the HTML part

+
    <a href="javascript:void(0);">200N</a> |
+
+

you can remove the code javascript:void(0); to make the HTML code cleaner and easier to maintain. By doing just that when you click on one of the a elements, the page will go to the href="" value that will be the empty string: "": this means that the browser will navigate to a blank page. +To prevent that unwanted behavior you can add to the function a single row:

+
function changeYear(event)
+{
+    event.preventDefault(); // the row to add to be able remove the code javascript:void(0); from the HTML code
+
+    // here you will keep the rest of the statements as in the original code
+}
+
+

Also you don't even need at all an a element: in fact you can use any element you want, like li or div or p and so on. You can even invent your own html element if you wish... Yea it is possible... I am going to demonstrate these possibilities as follows with a 3rd bonus solution that makes use of a mix of a standard span HTML element and an element that uses your nickname which is a completely invented or a custom tag or HTML element. It should work on modern HTML5 compatible browser. +I will use a little bit of css to style them and distinguish one from the other.

+

Please have a look at the

+

3rd Bonus Solution: using the "span" HTML element and a custom/invented HTML element/tag:

+

+
+
function changeYear(event)
+{
+    let tgtEl = document.getElementById(""myBtnId"");
+    let srcEl = event.target;
+    tgtEl.innerHTML = srcEl.innerHTML;
+
+    // The one liner version (remove or comment the 3 rows above and de-comment the following one):
+    // document.getElementById(""myBtnId"").innerHTML = event.target.innerHTML;
+}
+
#myDropdown
+{
+  background: yellow;
+}
+
+span, useer2332
+{
+  cursor: pointer;
+}
+
+span:hover
+{
+  background: red;
+}
+
+useer2332:hover
+{
+  background: lightgreen;
+}
+
<div class=""dropdown"">
+
+    <button id=""myBtnId"" onclick=""myFunction()"" class=""dropbtn"">Year</button>
+    
+    <div id=""myDropdown"" class=""dropdown-content"" onclick=""changeYear(event);"">
+        <span>2000</span> |
+        <span>2001</span> |
+        <span>2002</span> |
+        <span>2003</span> | 
+        <useer2332>2004</useer2332> |
+        <useer2332>2005</useer2332> |
+        <useer2332>2006</useer2332> |
+        <useer2332>2007</useer2332>
+    </div>
+
+
+

+

One final observation: using the 1nd and the 3rd solution, if the user clicks on the container div instead of on the a or the span or the useer2332 custom element, the button will be populated with all the values of all elements contained into the div it self. So you will get an unwanted side effect like 2000 | 2001 |2002 | [...] | 200N ... you don't want that to happen... to prevent this, is necessary to add some code that checks if it was clicked the right element, before executing the statements that populate the button text label.

+

Check the following solution out and compare its behavior with the behavior of the 1st and 3rd solutions by clicking on the yellow empty space, near the last year, (that is the div it self) and click in the same zone above, you'll notice a very different behavior:

+

3rd Bonus Solution with correction:

+

+
+
function changeYear(event)
+{
+    if (event.target.tagName == ""DIV""){return;}
+    let tgtEl = document.getElementById(""myBtnId"");
+    let srcEl = event.target;
+    tgtEl.innerHTML = srcEl.innerHTML;
+
+    // The one liner version (remove or comment the 3 rows above and de-comment the following one):
+    // document.getElementById(""myBtnId"").innerHTML = event.target.innerHTML;
+}
+
#myDropdown
+{
+  background: yellow;
+}
+
+span, useer2332
+{
+  cursor: pointer;
+}
+
+span:hover
+{
+  background: red;
+}
+
+useer2332:hover
+{
+  background: lightgreen;
+}
+
<div class=""dropdown"">
+
+    <button id=""myBtnId"" onclick=""myFunction()"" class=""dropbtn"">Year</button>
+    
+    <div id=""myDropdown"" class=""dropdown-content"" onclick=""changeYear(event);"">
+        <span>2000</span> |
+        <span>2001</span> |
+        <span>2002</span> |
+        <span>2003</span> | 
+        <useer2332>2004</useer2332> |
+        <useer2332>2005</useer2332> |
+        <useer2332>2006</useer2332> |
+        <useer2332>2007</useer2332>
+    </div>
+
+
+

",html +"Activate one input out of several in Angular

I have several inputs, and a button on each input that enable this input, I want the behavior of the button to be like this: when I click below, it is enable, and when I click on another, only this input is enable and the other are disabled as the photo shows +

+

How to do that?

+

Here is my code:

+

+
+
public enable(index: number) {
+  this.toggleInputs[index] = true;
+}
+
<input type=""text"" [disabled]=""!toggleInputs[i]"">
+<button title=""Modifier"" (click)=""enable(i)"">EDIT</button>
+
+
+

","
public enable(index: number) {
+  for (let i = 0; i < toggleInputs.length; i++) {
+    toggleInputs[i] = false;
+  }
+  this.toggleInputs[index] = true;
+}
+
",html +"HTML/JavaScript read from an xlsx or csv file on the server and put in a table

So here is the bulk of the code (Minus other pages, the css files, other js files, basically files unrelated to the question)

+

I am very happy with how this loads and creates the table and all of that. What I am trying to figure out now is how I can place this excel file on the server (Not on the user's pc) and have it automatically select the excel file on page load. The file will be stored in "Files/Data.xlsx"

+

This page is Inventory.html

+
<!DOCTYPE html>
+<html>
+
+<head>
+    <meta charset="utf-8" />
+    <title>Some Page</title>
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+
+    <!-- Reference the CSS File -->
+    <link rel="stylesheet" href="css/main.css">
+
+    <link rel="stylesheet" href="css/bootstrap.min.css">
+    <script type="text/javascript" src="js/xlsx.full.min.js"></script>
+</head>
+
+<body>
+    <div id="topMenu">
+        <ul>
+            <!--This I am using as a navigation bar and is unrelated-->
+        </ul>
+    </div>
+    <div class="container">
+        <div class="card">
+            <div class="card-body">
+                <input type="file" id="excel_file" />
+            </div>
+        </div>
+        <br />
+        <table id="myTable">
+            <tr id="search">
+                <!--This is some stuff used to filter the table and is unrelated-->
+            </tr>
+            <tbody id="excel_data" class="mt-5">
+            </tbody>
+        </table>
+    </div>
+</body>
+
+</html>
+
+<script>
+    const excel_file = document.getElementById('excel_file');
+    excel_file.addEventListener('change', (event) => {
+        if (!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']
+        .includes(event.target.files[0].type)) {
+            document.getElementById('excel_data').innerHTML = 
+            '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';
+            excel_file.value = '';
+            return false;
+        }
+
+        var reader = new FileReader();
+        reader.readAsArrayBuffer(event.target.files[0]);
+        reader.onload = function(event) {
+            var data = new Uint8Array(reader.result);
+            var work_book = XLSX.read(data, {
+                type: 'array'
+            });
+            var sheet_name = work_book.SheetNames;
+            var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {
+                header: 1
+            });
+            if (sheet_data.length > 0) {
+                var table_output = '<table class="table table-striped table-bordered">';
+                for (var row = 0; row < sheet_data.length; row++) {
+                    table_output += '<tr>';
+                    for (var cell = 0; cell < sheet_data[row].length; cell++) {
+                        if (row == 0) {
+                            table_output += '<th>' + sheet_data[row][cell] + '</th>';
+                        } else {
+                            table_output += '<td>' + sheet_data[row][cell] + '</td>';
+                        }
+                    }
+                    table_output += '</tr>';
+                }
+                table_output += '</table>';
+                document.getElementById('excel_data').innerHTML = table_output;
+            }
+            excel_file.value = '';
+        }
+    });
+</script>
+
+

My next big task will be figuring out how to write the data from the below form to the next empty row in the excel document....

+

This page is AddItem.html

+
<form>
+    <label for="prNumberInput">Enter the PR Number: </label>
+    <input type="text" name="prNumberInput" placeholder="Enter the PR Number" /><br>
+
+    <label for="netbuildNumberInput">Enter the NetBuild Number: </label>
+    <input type="text" name="netbuildNumberInput" placeholder="Enter the NetBuild Number" /><br>
+
+    <label for="trackingNumberInput">Enter the Tracking Number: </label>
+    <input type="text" name="trackingNumberInput" placeholder="Enter the Tracking Number" /><br>
+
+    <label for="partNumberInput">Enter the Part Number: </label>
+    <input type="text" name="partNumberInput" placeholder="Enter the Part Number" /><br>
+
+    <input type="button" onclick="AddItemSubmit()" value="Add Item">
+</form>
+
+

Any help at all is greatly appreciated

+

---------------UPDATED-------------------

+

Honestly, it won't actually be running on a server. This will just be stored on a computer and run by clicking the index.html file. The idea in saying it would be running on the server was because I know some browsers aren't big fans of you just grabbing a file on the user's PC randomly so I thought putting it in the folder with the rest of the files would be a work around on that. It's for a storage room, we thought to try to do it in HTML to help with security restrictions of running unsigned exe files on the computer. The idea was to load the xlsx/csv file into a table in the browser, checkboxes next to the items to move it to an archive file when it leaves the storage room for later reference if needed, and have a page to add items to the inventory when things are added to the storage room. I did not realize what I was using can only be used to access a file on the users PC. If you can't tell we aren't very good at this...I suppose will need to start from scratch Thank you for the help.

+

The idea behind the excel file is, I couldn't figure out how to add to a table on HTML. I mean it adds to the table but once you reload the page it goes away. I couldn't figure out how to make it actually add it to the HTML so if you close the page and reopen it, it is still there

","

The code which you have shared is executed in client's browser. it will never read files from server. to read file from servers directory you have to write code in server side then serve your excel file to client side!

+

if you have server side code please share that to clarify your question.

+

to achieve your desired results you can write you backend in express or any other backend language/framework in which you are comfortable in case you are using express first upload excel file to server then create http route read file(s).

",html +"calc() not working in css for setting width?

I'm making a text editor with a sidd nav-var. When the mouse hovers on the nav-bar its width increases and the editor width decreases. But the width of the editor doesn't change even when the width variable created by me is changing.

+

Here is my program:

+

+
+
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@200&display=swap');
+:root {
+  --nav-btn-width: 40px;
+  --nav-width: calc(100% - 60px);
+}
+
+* {
+  z-index: 1;
+}
+
+body {
+  padding: 0;
+  margin: 0;
+  background-color: #c73737;
+}
+
+#navbar {
+  position: absolute;
+  height: 100%;
+  width: 50px;
+  max-width: 200px;
+  background-color: #0068ad;
+  display: flex;
+  flex-direction: column;
+  transition: 0.35s ease-in-out;
+  padding-top: 10px;
+  box-sizing: border-box;
+  z-index: 2;
+}
+
+#navbar:hover {
+  width: 200px;
+  border-radius: 0 10px 10px 0;
+  --nav-btn-width: 190px;
+  --nav-width: calc(100% - 210px);
+}
+
+.nav-btn {
+  width: var(--nav-btn-width);
+  height: 40px;
+  background-color: rgb(0, 184, 70);
+  margin: 5px;
+  cursor: pointer;
+  border-radius: 50px;
+  transition: 0.35s ease-in-out;
+  box-sizing: border-box;
+  display: flex;
+  flex-direction: row;
+  padding-left: 7.5px;
+  overflow: hidden;
+  user-select: none;
+  z-index: 10;
+}
+
+.nav-btn:hover {
+  background-color: rgb(0, 255, 98);
+}
+
+#signout {
+  position: absolute;
+  bottom: 10px;
+}
+
+.nav-text {
+  position: relative;
+  top: 10px;
+  font-size: 12pt;
+  font-family: 'JetBrains Mono', monospace;
+  font-weight: bold;
+  text-align: center;
+  padding-left: 10px;
+}
+
+#editor {
+  position: absolute;
+  top: 0;
+  right: 0;
+  height: 100vh;
+  width: var(--nav-width);
+  background-color: rgb(78, 78, 78);
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Document</title>
+  <link rel=""stylesheet"" href=""style.css"">
+  <link href=""https://fonts.googleapis.com/icon?family=Material+Icons"" rel=""stylesheet"">
+</head>
+
+<body>
+  <div id=""body-container"" style=""width: 100vh;height:100vh"">
+    <div id=""navbar"">
+      <div id=""create"" class=""nav-btn"">
+        <img src=""add_black_24dp.svg"" alt="""" id=""create-icon"" class=""nav-icons"">
+        <div id=""create-text"" class=""nav-text"">Create</div>
+      </div>
+      <div id=""files"" class=""nav-btn"">
+        <img src=""description_black_24dp.svg"" alt="""" id=""files-icon"" class=""nav-icons"">
+        <div id=""files-text"" class=""nav-text"">My Files</div>
+      </div>
+      <div id=""feed"" class=""nav-btn"">
+        <img src=""article_black_24dp.svg"" alt="""" id=""feed-icon"" class=""nav-icons"">
+        <div id=""feed-text"" class=""nav-text"">Feed</div>
+      </div>
+      <div id=""challenges"" class=""nav-btn"">
+        <img src=""task_black_24dp.svg"" alt="""" id=""challenges-icon"" class=""nav-icons"">
+        <div id=""challenges-text"" class=""nav-text"">Challenges</div>
+      </div>
+      <div id=""leaderboard"" class=""nav-btn"">
+        <img src=""leaderboard_black_24dp.svg"" alt="""" id=""leaderboard-icon"" class=""nav-icons"">
+        <div id=""leaderboard-text"" class=""nav-text"">Leaderboard</div>
+      </div>
+      <div id=""notification"" class=""nav-btn"">
+        <img src=""notifications_black_24dp.svg"" alt="""" id=""notification-icon"" class=""nav-icons"">
+        <div id=""notification-text"" class=""nav-text"">Notifications</div>
+      </div>
+      <div id=""chat"" class=""nav-btn"">
+        <img src=""message_black_24dp.svg"" alt="""" id=""chat-icon"" class=""nav-icons"">
+        <div id=""chat-text"" class=""nav-text"">Dev Chat</div>
+      </div>
+      <div id=""settings"" class=""nav-btn"">
+        <img src=""settings_black_24dp.svg"" alt="""" id=""settings-icon"" class=""nav-icons"">
+        <div id=""settings-text"" class=""nav-text"">Settings</div>
+      </div>
+      <div id=""signout"" class=""nav-btn"">
+        <img src=""logout_black_24dp.svg"" alt="""" id=""signout-icon"" class=""nav-icons"">
+        <div id=""signout-text"" class=""nav-text"">Sign out</div>
+      </div>
+    </div>
+    <div id=""editor""></div>
+  </div>
+
+
+  <!-- include script.js and styler.js -->
+  <script src=""script.js""></script>
+  <script src=""styler.js""></script>
+  <script>
+  </script>
+</body>
+
+</html>
+
+
+

+

As you can see there is a 10px gap b/w the nav-bar and the editor and I have also updated the values when it is hovered. But when the nav-bar is hovered the width of the editor doesn't change.

+

Similar question: link

+

I have also tried what is mentioned in the Similar question but still it doesn't work...

+
+

The variable --nav-btn-width works as intended but the variable --nav-width doesn't work even though both are literally the same usages.

+
","

On the hover you are defining a variable that only has scope within the navbar element.

+

To define a variable for the editor element select on navbar hover plus editor, this will select for the editor element which comes immediately after the navbar.

+

+
+
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@200&display=swap');
+:root {
+  --nav-btn-width: 40px;
+  --nav-width: calc(100% - 60px);
+}
+
+* {
+  z-index: 1;
+}
+
+body {
+  padding: 0;
+  margin: 0;
+  background-color: #c73737;
+}
+
+#navbar {
+  position: absolute;
+  height: 100%;
+  width: 50px;
+  max-width: 200px;
+  background-color: #0068ad;
+  display: flex;
+  flex-direction: column;
+  transition: 0.35s ease-in-out;
+  padding-top: 10px;
+  box-sizing: border-box;
+  z-index: 2;
+}
+
+#navbar:hover {
+  width: 200px;
+  border-radius: 0 10px 10px 0;
+  --nav-btn-width: 190px;
+}
+#navbar:hover + #editor {
+  --nav-width: calc(100% - 210px);
+}
+
+.nav-btn {
+  width: var(--nav-btn-width);
+  height: 40px;
+  background-color: rgb(0, 184, 70);
+  margin: 5px;
+  cursor: pointer;
+  border-radius: 50px;
+  transition: 0.35s ease-in-out;
+  box-sizing: border-box;
+  display: flex;
+  flex-direction: row;
+  padding-left: 7.5px;
+  overflow: hidden;
+  user-select: none;
+  z-index: 10;
+}
+
+.nav-btn:hover {
+  background-color: rgb(0, 255, 98);
+}
+
+#signout {
+  position: absolute;
+  bottom: 10px;
+}
+
+.nav-text {
+  position: relative;
+  top: 10px;
+  font-size: 12pt;
+  font-family: 'JetBrains Mono', monospace;
+  font-weight: bold;
+  text-align: center;
+  padding-left: 10px;
+}
+
+#editor {
+  position: absolute;
+  top: 0;
+  right: 0;
+  height: 100vh;
+  width: var(--nav-width);
+  background-color: rgb(78, 78, 78);
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Document</title>
+  <link rel=""stylesheet"" href=""style.css"">
+  <link href=""https://fonts.googleapis.com/icon?family=Material+Icons"" rel=""stylesheet"">
+</head>
+
+<body>
+  <div id=""body-container"" style=""width: 100vh;height:100vh"">
+    <div id=""navbar"">
+      <div id=""create"" class=""nav-btn"">
+        <img src=""add_black_24dp.svg"" alt="""" id=""create-icon"" class=""nav-icons"">
+        <div id=""create-text"" class=""nav-text"">Create</div>
+      </div>
+      <div id=""files"" class=""nav-btn"">
+        <img src=""description_black_24dp.svg"" alt="""" id=""files-icon"" class=""nav-icons"">
+        <div id=""files-text"" class=""nav-text"">My Files</div>
+      </div>
+      <div id=""feed"" class=""nav-btn"">
+        <img src=""article_black_24dp.svg"" alt="""" id=""feed-icon"" class=""nav-icons"">
+        <div id=""feed-text"" class=""nav-text"">Feed</div>
+      </div>
+      <div id=""challenges"" class=""nav-btn"">
+        <img src=""task_black_24dp.svg"" alt="""" id=""challenges-icon"" class=""nav-icons"">
+        <div id=""challenges-text"" class=""nav-text"">Challenges</div>
+      </div>
+      <div id=""leaderboard"" class=""nav-btn"">
+        <img src=""leaderboard_black_24dp.svg"" alt="""" id=""leaderboard-icon"" class=""nav-icons"">
+        <div id=""leaderboard-text"" class=""nav-text"">Leaderboard</div>
+      </div>
+      <div id=""notification"" class=""nav-btn"">
+        <img src=""notifications_black_24dp.svg"" alt="""" id=""notification-icon"" class=""nav-icons"">
+        <div id=""notification-text"" class=""nav-text"">Notifications</div>
+      </div>
+      <div id=""chat"" class=""nav-btn"">
+        <img src=""message_black_24dp.svg"" alt="""" id=""chat-icon"" class=""nav-icons"">
+        <div id=""chat-text"" class=""nav-text"">Dev Chat</div>
+      </div>
+      <div id=""settings"" class=""nav-btn"">
+        <img src=""settings_black_24dp.svg"" alt="""" id=""settings-icon"" class=""nav-icons"">
+        <div id=""settings-text"" class=""nav-text"">Settings</div>
+      </div>
+      <div id=""signout"" class=""nav-btn"">
+        <img src=""logout_black_24dp.svg"" alt="""" id=""signout-icon"" class=""nav-icons"">
+        <div id=""signout-text"" class=""nav-text"">Sign out</div>
+      </div>
+    </div>
+    <div id=""editor""></div>
+  </div>
+
+
+  <!-- include script.js and styler.js -->
+  <script src=""script.js""></script>
+  <script src=""styler.js""></script>
+  <script>
+  </script>
+</body>
+
+</html>
+
+
+

",html +"Reduce speed of following image

I'm making a game where a gif is following the cursor. Is there any way to reduce the speed so that the image that follows the cursor moves at a constant (but slower) speed than the cursor itself?

+

Basically right now the gif I assigned is acting link a replacement cursor. I want the gif to follow and catch up to the cursor at its own speed.

+

Thanks

+

+
+
<script>
+document.querySelector("".testsite"").onmousemove = (e) => {
+  const x = e.pageX - e.target.offsetLeft;
+  const y = e.pageY - e.target.offsetTop;
+ 
+  e.target.style.setProperty(""--x"", `${x}px`);
+  e.target.style.setProperty(""--y"", `${y}px`);
+};
+ 
+</script>
+
<style>
+body {
+  justify-content: center;
+  align-items: center;
+  min-height: 100vh;
+}
+ 
+.testsite {
+/* container */
+  width: 500px;
+  height: 500px;
+  position: relative;
+  appearance: none;
+  background: grey;
+  padding: 10px 20px;
+  border: none;
+  color: white;
+  font-size: 1.2em;
+  cursor: none;
+  outline: none;
+  overflow: hidden;
+  border-radius: 10px;
+  box-shadow: black;
+}
+.testsite span {
+  position: relative;
+  pointer-events: none;
+}
+.testsite::before {
+  --size: 0;
+  content: """";
+  position: absolute;
+  left: var(--x);
+  top: var(--y);
+  width: 32px;
+  height: 32px;
+  background-image: url(""html5.gif"");
+  animation-duration: 1s;
+
+  transform: translate(-50%, -50%);
+}
+
+</style>
+
<html>
+<body>
+<div class=""testsite"">
+  
+</div>
+</body>
+</html>
+
+
+

","

You can make the x and y coordinate operations of your js into a function and then add a setTimeout to that function to run it every 100ms or how ever long you want the delay to be. Check it out here, note I also removed pointer:none; from .testsite :

+

+
+
document.querySelector("".testsite"").onmousemove = (e) => {
+  const x = e.pageX - e.target.offsetLeft;
+  const y = e.pageY - e.target.offsetTop;
+  
+  function runInt() {
+  e.target.style.setProperty(""--x"", `${x}px`);
+  e.target.style.setProperty(""--y"", `${y}px`);
+  }
+ setTimeout(runInt, 100);
+};
+
body {
+  justify-content: center;
+  align-items: center;
+  min-height: 100vh;
+}
+ 
+.testsite {
+/* container */
+  width: 500px;
+  height: 500px;
+  position: relative;
+  appearance: none;
+  background: grey;
+  padding: 10px 20px;
+  border: none;
+  color: white;
+  font-size: 1.2em;
+
+  outline: none;
+  overflow: hidden;
+  border-radius: 10px;
+  box-shadow: black;
+}
+.testsite span {
+  position: relative;
+  pointer-events: none;
+}
+.testsite::before {
+  --size: 0;
+  content: """";
+  position: absolute;
+  left: var(--x);
+  top: var(--y);
+  width: 32px;
+  height: 32px;
+  background-image: url(""https://www.springbrookanimalcarecenter.com/blog/wp-content/uploads/2017/10/Springbrook_iStock-612247460-150x150.jpg"");
+  animation-duration: 1s;
+  transform: translate(-50%, -50%);
+}
+
<html>
+<body>
+<div class=""testsite"">
+</div>
+</body>
+</html>
+
+
+

",html +"Issue with html and css image size

So I am trying to edit a simple webpage that's giving me headaches. +So on a simple pc, this webpage looks really nice, but on mobile it looks horrible. I tried editing it with some info I know from the internet, but nothing worked... Here is what I am talking about: PC, Phone

+

You can also check it by entering the website

+

Also, here is the code

+
{include file='header.tpl'}
+<style>
+:root {
+--header-background: linear-gradient(#212121 0,rgb(74 69 69 / 18%) 0%,#252323 90%);
+}
+#maintenance {
+    background: url(https://i.imgur.com/Ik4qFXl.jpg)!important;
+    width: 100%;
+    height: 320px;
+}
+
+#maintenance:before {
+    content: "";
+    position: absolute;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 320px;
+    background: var(--header-background);
+}
+.logo img {
+    width: 600px;
+    height:auto;
+}
+#maintenance .logo {
+    height: 160px;
+}
+#particles-js {
+    position: absolute;
+    height: 100%;
+    width: 100%;
+    margin: 0 auto;
+    left: 0;
+    right: 0;
+    margin-left: auto;
+    margin-right: auto;
+    pointer-events: none;
+}
+.maintenance-data {
+    text-align: center;
+}
+.maintenance-title {
+    font-size: 30px;
+    margin-top: 10px;
+    margin-bottom: 2ch;
+}.maintenance-mess {
+    font-size: 25px;
+    margin-top: 1.3ch;
+    margin-bottom: 3ch;
+}
+button.ui.primary.button {
+    margin-right: 20px;
+}
+.ui.buttons{
+ margin-top: 3ch;
+}
+.ui.buttons.button:first-child {
+    border-left: none;
+    margin-left: 0;
+    border-radius: .28571429rem;
+}.ui.buttons .button:last-child {
+    border-radius: .28571429rem;
+}
+.login-button {
+    background: var(--panel-body);
+    padding: 10px 18px;
+    color: var(--main-color);
+    margin-left: 30px;
+    border-radius: .28571429rem;
+    -webkit-box-shadow: 0 0 0 1px transparent inset, 0 0 0 0 rgb(34 36 38 / 15%) inset;
+    box-shadow: 0 0 0 1px transparent inset, 0 0 0 0 rgb(34 36 38 / 15%) inset;
+}
+#preloader {
+    z-index: -1;
+}
+</style>
+    <div class="ui container" id="maintenance">
+    <div id="particles-js"></div>
+    <div class="logo"><a href="https://lyrex.ro/discord"><img src="https://i.imgur.com/QghSfu2.png"></a></div>
+    </div>
+      <div class="maintenance-data">
+        <h2 class="maintenance-title">{$MAINTENANCE_TITLE}</h2>
+        <div class="maintenance-mess">{$MAINTENANCE_MESSAGE}</div>
+        <div class="ui buttons">
+          <button class="ui positive button" onclick="window.location.reload()">{$RETRY}</button>
+        </div>
+        {if isset($LOGIN)}
+          <a class="login-button" href="{$LOGIN_LINK}">{$LOGIN}</a>
+        {/if}
+      </div>
+    </div>
+ <script type="text/javascript">
+{literal}
+        particlesJS("particles-js", {
+            "particles": {
+                "number": {
+                    "value": 100,
+                    "density": {
+                        "enable": true,
+                        "value_area": 2000
+                    }
+                },
+                "color": {
+                    "value": "#dc3545"
+                },
+                "shape": {
+                    "type": "circle",
+                    "stroke": {
+                        "width": 0,
+                        "color": "#000000"
+                    },
+                    "polygon": {
+                        "nb_sides": 4
+                    },
+                    "image": {
+                        "src": "img/github.svg",
+                        "width": 100,
+                        "height": 100
+                    }
+                },
+                "opacity": {
+                    "value": 0.5,
+                    "random": true,
+                    "anim": {
+                        "enable": false,
+                        "speed": 0.5,
+                        "opacity_min": 0.1,
+                        "sync": false
+                    }
+                },
+                "size": {
+                    "value": 8,
+                    "random": true,
+                    "anim": {
+                        "enable": true,
+                        "speed": 2,
+                        "size_min": 0,
+                        "sync": false
+                    }
+                },
+                "line_linked": {
+                    "enable": false,
+                    "distance": 500,
+                    "color": "#ffffff",
+                    "opacity": 0.4,
+                    "width": 2
+                },
+                "move": {
+                    "enable": true,
+                    "speed": 2.8914764163227265,
+                    "direction": "top",
+                    "random": true,
+                    "straight": false,
+                    "out_mode": "out",
+                    "bounce": false,
+                    "attract": {
+                        "enable": false,
+                        "rotateX": 600,
+                        "rotateY": 1200
+                    }
+                }
+            },
+            "interactivity": {
+                "detect_on": "canvas",
+                "events": {
+                    "onhover": {
+                        "enable": false,
+                        "mode": "bubble"
+                    },
+                    "onclick": {
+                        "enable": false,
+                        "mode": "repulse"
+                    },
+                    "resize": true
+                },
+                "modes": {
+                    "grab": {
+                        "distance": 400,
+                        "line_linked": {
+                            "opacity": 0.5
+                        }
+                    },
+                    "bubble": {
+                        "distance": 400,
+                        "size": 4,
+                        "duration": 0.3,
+                        "opacity": 1,
+                        "speed": 3
+                    },
+                    "repulse": {
+                        "distance": 200,
+                        "duration": 0.4
+                    },
+                    "push": {
+                        "particles_nb": 4
+                    },
+                    "remove": {
+                        "particles_nb": 2
+                    }
+                }
+            },
+            "retina_detect": true
+        });
+        var count_particles, stats, update;
+{/literal}
+</script>    
+  </body>
+</html>
+
","

for responsive viewpoint please add these to your code

+
 .logo img {
+    width: 100%;
+    height: auto;
+    margin: auto;
+    max-width: 600px;
+}
+
+

Add margin:auto; and max-width:600px; to the logo img

",html +"html css custom div setup

I am trying to create some div setup shown in the image attached but not sure how to do so given my basic knowledge:

+

+

Help is greatly appreciated. Many Thanks

","

I use grid and flex box system together for this task.

+

+
+
.grid {
+  display: grid;
+  grid-template-columns: 1fr 1fr;  
+  background: black;
+}
+
+.flex-container {
+  display: flex;  
+  margin:5px;
+}
+.row {  
+  margin: 5px;
+}
+.box {
+  width: 50%;
+  background: green;
+  padding: 10px;
+  border: 1px solid #000;    
+}
+
<div id=""main"" class=""grid"">
+  <div class=""row"">
+    <div class=""flex-container"">
+      <div class=""box"">
+        1
+      </div>
+      <div class=""box"">
+        2
+      </div>
+    </div>
+    <div class=""flex-container"">
+      <div class=""box"">
+        3
+      </div>
+      <div class=""box"">
+        4
+      </div>
+    </div>
+    <div class=""flex-container"">
+      <div class=""box"">
+        5
+      </div>
+      <div class=""box"">
+        6
+      </div>
+    </div>    
+  </div>
+   
+  <div class=""row"">
+    <div class=""flex-container"">
+      <div class=""box"">
+        1
+      </div>
+      <div class=""box"">
+        2
+      </div>
+    </div>
+    <div class=""flex-container"">
+      <div class=""box"">
+        1
+      </div>
+      <div class=""box"">
+        2
+      </div>
+    </div>
+
+  </div>
+</div>
+
+
+

",html +"How to implement basic angular-like routing in plain javascript

I want to write a simple javascript implementation of Angular-like routing, but I can't figure out how to do it. Let's say I have an Index page and I'd like to navigate to Index/2 by a means of <a href="Index/2">Navigate Like in Angular</a> +, yet prevent the request being sent to the server and instead get some event which I can handle. I tried using the beforeunload event like this

+
<script>
+        window.onbeforeunload = function (ev) {
+ 
+            ev.preventDefault();
+            return '';
+        };
+ 
+    </script>
+
+

but this approach doesn't work. First, it displays a popup message which I'm not interested in, and second, if I press cancel, the url in the browser address control is still "http://.../Index" and I don't know a way to "silently" modify it to "http://.../Index/2". +Any help will be most appreciated.

+

--- UPDATE ---

+

In case someone needs, here is a minimal implementation of Angular-like (SPA) routing, thanks to the answer from Quentin.

+

Index.html, hosted in static website:

+
<!DOCTYPE html>
+
+<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <meta charset="utf-8" />
+    <title></title>
+</head>
+<body>
+    <button title="navigate without request to server" routing-link="/Index/2">Navigate 2</button>
+    <button title="navigate without request to server" routing-link="/Index/3">Navigate 3</button>
+
+    <div id="outlet"></div>
+    
+    <script>
+
+        function updateRoute(){ 
+            
+            relativeUrl = location.href.substring(location.origin.length + 1, location.href.length);
+            document.getElementById("outlet").innerHTML = relativeUrl + ", " + history.length;
+        }
+
+        window.addEventListener("click", ev => {
+
+            let routingLink = ev.target.attributes && ev.target.attributes['routing-link'];
+
+            if (routingLink && relativeUrl != routingLink.value) {
+                
+                history.pushState({ relativeUrl: routingLink.value }, "", location.origin + '/' + routingLink.value);
+                updateRoute();
+            }
+        });
+
+        window.addEventListener("popstate", ev => {
+
+            updateRoute()
+        });
+
+        
+        let relativeUrl = "";
+        
+        updateRoute();
+                
+    </script>
+
+</body>
+</html>
+
+

If you use, like me, IIS for hosting, don't forget to install the "URL Rewrite" module, and copy the following web.config to site's root:

+
<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+  <system.webServer>
+  <rewrite>
+    <rules>
+      <rule name="Angular Routes" stopProcessing="true">
+        <match url=".*" />
+        <conditions logicalGrouping="MatchAll">
+          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
+          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
+        </conditions>
+        <action type="Rewrite" url="./Index.html" />
+      </rule>
+    </rules>
+  </rewrite>
+  </system.webServer>
+</configuration>
+
+

This will take care of the cases in which a request is still sent to the server, e.g. due to browser refresh.

","

You can't intercept the browser leaving the page to achieve this.

+

You need to have a click event listener that captures the link being activated instead.

+

Then you can prevent the default behaviour, modify the DOM however you like, and then manipulate the URL using the History API.

+

You also need to handle popState events so that the back button continues to work.

+
+

Keep in mind that you do need to have the server deliver something useful when the browser asks for that new URL as an entry point to your SPA and that that is best provided by having a server-side rendered version of your application.

+

A hackier approach is to just deliver some skeleton HTML and bootstrap everything with client-side JS … but then you run into problems with determining when the server should report a 404 error.

",html +"Why am I getting this error when I try to switch HTML pages

I made basic HTML/CSS files, that I'm trying to run through Django, but every time I run it and try to switch pages, I get this error:

+
Page not found (404)
+Request Method: GET
+Request URL:    http://127.0.0.1:8000/about.html
+Using the URLconf defined in test.urls, Django tried these URL patterns, in this order:
+
+admin/
+[name='main']
+add [name='about']
+The current path, about.html, didn’t match any of these.
+
+

Here's what that my .urls file looks like:

+
from django.contrib import admin
+from django.urls import path
+from . import views
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('add',views.about,name='main.html'),
+    path('add',views.about,name='about.html')
+]
+
+

Here's my .views file looks like:

+
from django.shortcuts import render
+
+def main(request):
+    return render(request,'main.html')
+def about(request):
+    return render(request, 'about.html') 
+
+

Lastly Here's the section of my Settings file that I modified to find the file:

+
'DIRS': [os.path.join(BASE_DIR,'templates')],
+    'APP_DIRS': True,
+
+

Is there something else I'm supposed to do to make this work?

","

So the problem is here you should add the name of the URL of the page as an example http://127.0.0.1:8000/home

+

PS - in urls.py should write it like this home/

+
from django.contrib import admin
+from django.urls import path
+from . import views
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('Here/main.html/',views.main,name='main.html'),
+    path('here/about.html/',views.about ,name='about.html')
+]
+
+

UPDATE 05/01/2022

+

Follow these steps to get the same result

+
    +
  • Run-on your terminal django-admin startproject Tuto and django-admin startapp tutoApp like you're did in this project.

    +
  • +
  • Go to settings.py and add your app to INSTALLED_APPS

    +
  • +
  • Create a folder on your TutoApp and name it templates and create the following file index.html, about.html.

    +
  • +
  • Go to settings.py import os and on TEMPLATES change 'DIRS': [] with 'DIRS': [os.path.join(BASE_DIR),'templates']

    +
  • +
  • You need to add some functions to your views.py

    +
  • +
+
from django.shortcuts import render
+
+def homepage(request):
+    return render(request, 'index.html')
+
+def about(request):
+    return render(request, 'about.html')
+
+
+
    +
  • In /tuto/urls.py
  • +
+
from django.contrib import admin
+from django.urls import path, include
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('',include('tutoApp.urls'))
+
+]
+
+
+
    +
  • Back to you're app and create a file name urls.py
  • +
+
from . import views
+from django.urls import path
+
+urlpatterns = [
+    path('home/', views.homepage),
+    path('about/', views.about)
+]
+
+

add some HTML to these pages to recognize which page you're on.

+",html +"Bootstrap carousel controls not working and going to the next slide takes too long

My carousel is having some issues. It's taking a lot of time to go to the next slide. When I do it with controls, no matter how much I click on the controls, they don't work. I followed everything in the Bootstrap document but it's not working.

+

Code

+
            <div class="carousel-inner">
+              <div class="carousel-item active">
+                <img src="images/wonyoung.jpg" class="d-block w-100" alt="loading">
+              </div>
+              <div class="carousel-item">
+                <img src="images/seungyoun.jpg" class="d-block w-100" alt="loading">
+              </div>
+              <div class="carousel-item">
+                <img src="images/yuri.jpg" class="d-block w-100" alt="loading">
+              </div>
+            </div>
+
+            <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
+                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
+                <span class="visually-hidden">Previous</span>
+            </button>
+            <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
+                <span class="carousel-control-next-icon" aria-hidden="true"></span>
+                <span class="visually-hidden">Next</span>
+              </button>
+        </div>
+
","

Here's the code I used to get the carousel to work, pasting the whole .html file with bootstrap imports of CSS & JS. It should work locally if you copy/paste into a .html file and open it with a web browser.

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <meta
+      name="viewport"
+      content="width=device-width, initial-scale=1, shrink-to-fit=no"
+    />
+    <meta name="theme-color" content="#000000" />
+    <link
+      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
+      rel="stylesheet"
+      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
+      crossorigin="anonymous"
+    />
+    <title>Bootstrap Carousel Example</title>
+  </head>
+  <body>
+    <div>
+      <div
+        id="carouselExampleIndicators"
+        class="carousel slide"
+        data-bs-ride="carousel"
+      >
+        <div class="carousel-indicators">
+          <button
+            type="button"
+            data-bs-target="#carouselExampleIndicators"
+            data-bs-slide-to="0"
+            class="active"
+            aria-current="true"
+            aria-label="Slide 1"
+          ></button>
+          <button
+            type="button"
+            data-bs-target="#carouselExampleIndicators"
+            data-bs-slide-to="1"
+            aria-label="Slide 2"
+          ></button>
+          <button
+            type="button"
+            data-bs-target="#carouselExampleIndicators"
+            data-bs-slide-to="2"
+            aria-label="Slide 3"
+          ></button>
+        </div>
+        <div class="carousel-inner">
+          <div class="carousel-item active">
+            <img
+              src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270"
+              class="d-block w-100"
+              alt="..."
+            />
+          </div>
+          <div class="carousel-item">
+            <img
+              src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTBsbCAQtQimp5yI0Zx4vyR_FzPLUVzkdjDBN0N4_LAUo59inNQrSp6-Iz7qrfAXBENLGI&usqp=CAU"
+              class="d-block w-100"
+              alt="..."
+            />
+          </div>
+          <div class="carousel-item">
+            <img
+              src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRabXZSwdR-7wsXfdtb2Xdy0Tl9o6l1D-UcQnyVN0WxQ9TmPE8SkEh0s9opAyZy-x5DnYY&usqp=CAU"
+              class="d-block w-100"
+              alt="..."
+            />
+          </div>
+        </div>
+        <button
+          class="carousel-control-prev"
+          type="button"
+          data-bs-target="#carouselExampleIndicators"
+          data-bs-slide="prev"
+        >
+          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
+          <span class="visually-hidden">Previous</span>
+        </button>
+        <button
+          class="carousel-control-next"
+          type="button"
+          data-bs-target="#carouselExampleIndicators"
+          data-bs-slide="next"
+        >
+          <span class="carousel-control-next-icon" aria-hidden="true"></span>
+          <span class="visually-hidden">Next</span>
+        </button>
+      </div>
+    </div>
+    <script
+      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
+      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
+      crossorigin="anonymous"
+    ></script>
+  </body>
+</html>
+
",html +"transparent circle on opaque canvas

I'm trying to draw a transparent circle on the HTML Canvas. Here is the code:

+

+    const canvas = document.querySelector('#canvas');
+    let ctx = canvas.getContext('2d');
+    
+    
+    canvas.width = 700;
+    canvas.height = 700;
+    ctx.beginPath();
+    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
+    ctx.fillRect(0, 0, canvas.width, canvas.height);
+    ctx.globalCompositeOperation = 'destination-out';
+    ctx.clearRect(50, 50, 200, 200);
+    ctx.beginPath();
+    ctx.fillRect(50, 50, 200, 200);
+    ctx.moveTo(350, 150);
+    ctx.beginPath();
+    ctx.arc(350, 150, 80, 0, 2 * Math.PI, false);
+    ctx.closePath();
+    ctx.fill();
+
+
+

I was able to make the rectangle transparent with globalCompositeOperation set to destination-out but it failed to make the circle fully transparent. +Here is what MDN says about destination-out operation,

+

The existing content is kept where it doesn't overlap the new shape.

+

The circle has still some opaque color applied to it. How to make it fully transparent? +Here is the live demo.

+

Unable to understand what's wrong with the code. Any help would be appreciated.

","

You are using beginpath methods but the directives you use aren't paths.

+

The fully transparent rectangle is created by the clearRect and not by the fillRect method.

+

So you should set fillStyle to white and then the code works.

+

+
+
const canvas = document.querySelector('#canvas');
+let ctx = canvas.getContext('2d');
+
+canvas.width = 600;
+canvas.height = 400;
+    ctx.fillStyle = 'rgba(0, 0, 0, .5)';
+    ctx.fillRect(0, 0, canvas.width, canvas.height);
+    ctx.globalCompositeOperation = 'destination-out';
+    ctx.fillStyle = 'rgba(255, 255, 255, 1)';
+    ctx.fillRect(25, 25, 150, 150);
+    ctx.arc(275, 100, 60, 0, 2 * Math.PI, false);
+    ctx.fill();
+
body {
+  background-color: skyblue;
+    position: relative;
+}
+
+img, #canvas {
+    position: absolute;
+}
+
<body>
+    <img src=""https://images.unsplash.com/photo-1635315850978-44cd0b237006?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1770&q=80"" alt="""" width=600 height=390>
+  <canvas id=""canvas""></canvas>
+</body>
+
+
+

",html +"Sass variables nested styling

I try to optimize my styling which does have repeated styles mostly

+

i have like this

+
.ds-input.ds--valid .ds-input__control:not(#specificity-issue),
+.ds-select.ds--valid .ds-select__control:not(#specificity-issue) {
+  border-color: var(--my-color);
+
+  &:focus {
+    border-color: var(--my-border-color);
+  }
+}
+
+

what i tried to make variables but nested variables gives wrong result

+
$dsSelectors: "ds-select, ds-input";
+
+.#{$dsSelectors}.ds--valid.#{$dsSelectors}__control:not(#specificity-issue),
+ {
+        border-color: var(--my-color);
+    
+      &:focus {
+        border-color: var(--my-border-color);
+      }
+}
+
+

do we have any easy and short syntax to fix this

+

at the end, expected css will look like this

+
.ds-select.ds--valid .ds-select__control:not(#specificity-issue), .ds-input.ds--valid .ds-input__control:not(#specificity-issue) {
+    border-color: var(--my-border-color);
+}
+.ds-select.ds--valid .ds-select__control:not(#specificity-issue):focus, .ds-input.ds--valid .ds-input__control:not(#specificity-issue):focus {
+    border-color: var(--my-color);
+}
+
","

@each can use for this purpose. More information and examples: https://sass-lang.com/documentation/at-rules/control/each

+
+

The @each rule makes it easy to emit styles or evaluate code for each +element of a list or each pair in a map. It’s great for repetitive +styles that only have a few variations between them. It’s usually +written

+
+
$classes: ds-select, ds-input;
+@each $class in $classes {
+    .#{$class}.ds--valid .#{$class}__control:not(#specificity-issue)
+    {
+        border-color: var(--my-color);        
+        &:focus {
+            border-color: var(--my-border-color);
+        }
+    }
+}
+
+

Edit for marge styles:

+

To marge selectors with the same content, @function can be used.

+
@function mixToList() {
+    $list: ds-select, ds-input;
+    $result: ();
+    @each $a in $list {
+        $result: append($result, ".#{$a}.ds--valid .#{$a}__control:not(#specificity-issue)", $separator: comma);
+    }
+    @return #{$result};
+}
+
+#{mixToList()} {
+    border-color: var(--my-color);
+    &:focus {
+        border-color: var(--my-border-color);
+    }
+}
+
",html +"Centring an icon between text and another icon

I'm trying to get an icon (the play arrow with the ring around it) in the centre of the screen, in between the title ('Random Episodes') and the other icon (the monitor with the + in it).

+

I have tried too many combinations to remember, let alone list here. If you look at the code snippet below, which is just the header section of the page, you can see what I mean. (The upside down 'T' is just there to mark the centre.) If you remove the /* */ in the #add_show_icon tag in the style section you will see what I want it to look like (as long as your screen size is greater than 590px).
+Unfortunately, as you can see, the method I used to get it to look right was to, basically, just increase the width of the icon to match the width of the title (246.3px); this is obviously not a good final solution.

+

Any help with this would be appreciated as, although it is just for a personal project, I'm hopping it might be a good portfolio/'example of my work' type of project (after a bit... ok, a lot, of tidying up).

+

+
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>header test</title>
+
+  <link rel=""stylesheet"" href=""https://fonts.googleapis.com/icon?family=Material+Icons"">
+
+</head>
+
+<body>
+  <header id=""header"">
+    <h1>Random Episodes</h1>
+    <div class=""completely_random_outer"" onclick=""open_random_show_and_episode()"">
+      <i class=""material-icons button_icons "">autorenew</i>
+      <i class=""material-icons button_icons play_icon"">play_arrow</i>
+    </div>
+    <i id=""add_show_icon"" class=""material-icons button_icons"" >add_to_queue</i>
+  </header>
+  <div id=center_marker>T</div>
+</body>
+
+<style>
+   :root {
+    --all-shows-bg-color: #444
+  }
+  
+  body {
+    background-color: dimgrey;
+    margin: 0px;
+  }
+  
+  #header {
+    display: flex;
+    justify-content: space-between;
+    background: black;
+    color: white;
+    padding-left: 10px;
+    padding-right: 10px;
+  }
+  
+  .completely_random_outer {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+  }
+  
+  .completely_random_outer .play_icon {
+    position: absolute;
+    font-size: 250%;
+  }
+  
+  .completely_random_outer .button_icons {
+    opacity: 1;
+  }
+  
+  #add_show_icon {
+    opacity: 1;
+    /*
+    width: 246.3px; 
+    display: flex; 
+    justify-content: flex-end; 
+    */
+  }
+  
+  .button_icons {
+    opacity: 0;
+    cursor: pointer;
+    font-size: 470%;
+    z-index: 1;
+  }
+  
+  #center_marker {
+    display: flex;
+    justify-content: center;
+    font-size: 500%;
+    font-family: monospace;
+    transform: scale(-1);
+  }
+</style>
+
+</html>
+
+
+

+

Edit for clarification:
+I have tried using justify-content: space-between; The problem with is is that it just equalizes the space between the elements, end to end. As the text is wider then the icon on the other side, it pushes the center icon over a bit, and thus of center for the page as a whole.

+

problem, center icon is off-center

+

desired look, having to bodge it by increasing the width of the icon

+

SOLVED! by @Timor-Kodal
+Finished look! Thanks for the help Timor!

+
<header id="header">
+    <div id="container">
+        <div class="child"> 
+            <h1>Random Episodes</h1>
+        </div>
+        <div class="child">
+            <div class="completely_random_outer" onclick="open_random_show_and_episode()">
+                <i class="material-icons button_icons ">autorenew</i>
+                <i class="material-icons button_icons play_icon">play_arrow</i>
+            </div>
+        </div>
+        <div class="child">
+            <i id="add_show_icon" class="material-icons button_icons" >
+                add_to_queue
+            </i>
+        </div>
+    </div>
+</header>
+
+
    #container {
+        display: flex;
+    }
+    .child {
+        flex: 1;
+        display: flex;
+        justify-content: center;
+    }
+
+    .child:first-child > h1 { 
+        margin-right: auto; 
+    }
+
+    .child:last-child  > i { 
+        margin-left: auto;  
+    }
+
","

Does this help?

+

+
+
.flex-container {
+  display: flex;
+}
+.child {
+  flex: 1;
+  display: flex;
+  justify-content: center;
+}
+
+.child:first-child > span { margin-right: auto; }
+
+.child:last-child  > span { margin-left: auto;  }
+
<div class=""flex-container"">
+  <div class=""child""><span>short</span></div>
+  <div class=""child""><span>centered content</span></div>
+  <div class=""child""><span>a very very long text section on the right side </span></div>
+</div>
+
+
+

",html +"How to concat JSON field into another object

Here is the data in question:

+
[
+    {
+        "id": 3,
+        "owner": "http://localhost:8000/api/v1/users/3/",
+        "ingredients": [
+            {
+                "ingredient": {
+                    "id": 1,
+                    "category": "Fruit",
+                    "name": "Apple",
+                    "calories": 100.0,
+                },
+                "numOf": 4
+            },
+            {
+                "ingredient": {
+                    "id": 2,
+                    "category": "Vegetable",
+                    "name": "Potato",
+                    "calories": 10.0,
+                },
+                "numOf": 3
+            }
+        ],
+        "total_number": 0
+    }
+]
+
+
+

I want to concate numOf into hist parent ingredient for my table to render properly Right now given 2 ingredients my table has 4 rows

+

Edit

+

Desired result should look like this:

+
[
+    {
+        "id": 3,
+        "owner": "http://localhost:8000/api/v1/users/3/",
+        "ingredients": [
+            {
+                "ingredient": {
+                    "id": 1,
+                    "category": "Fruit",
+                    "name": "Apple",
+                    "calories": 100.0,
+                    "numOf": 4,
+                }
+            },
+            {
+                "ingredient": {
+                    "id": 2,
+                    "category": "Vegetable",
+                    "name": "Potato",
+                    "calories": 10.0,
+                    "numOf": 3,
+                }
+            }
+        ],
+        "total_number": 0
+    }
+]
+
+
+

The JSON file you see is my server response when queried about user's fridge. Then I want to dispaly all of his ingredient's in a table. +Here's how I declare the array in VueJS:

+
import axios from 'axios'
+export default {
+    name: 'Fridge',
+    data() {
+        return {
+            username: '',
+            fridge: {},
+            ingredients: []
+        }
+    },
+}
+
+

Here's the code that loops through response data and adds ingredients object and store's it in array called ingredients. I've tried declaring is a object but it didn't work.

+
for (let i = 0; i < res.data["ingredients"].length; i++) {
+ var obj = this.fridge.ingredients[i]
+ for (var key in obj) {
+  var value = obj[key]
+  this.ingredients.push(value)
+ }
+}
+
","

You can just loop through each item in the ingredient key of each item in the array of data and for each item add the numOf key in the ingredient object and remove the numOf on the parent item.

+

+
+
let data = [
+    {
+        ""id"": 3,
+        ""owner"": ""http://localhost:8000/api/v1/users/3/"",
+        ""ingredients"": [
+            {
+                ""ingredient"": {
+                    ""id"": 1,
+                    ""category"": ""Fruit"",
+                    ""name"": ""Apple"",
+                    ""calories"": 100.0,
+                },
+                ""numOf"": 4
+            },
+            {
+                ""ingredient"": {
+                    ""id"": 2,
+                    ""category"": ""Vegetable"",
+                    ""name"": ""Potato"",
+                    ""calories"": 10.0,
+                },
+                ""numOf"": 3
+            }
+        ],
+        ""total_number"": 0
+    }
+];
+
+data[0].ingredients.map((item, index) => {
+  item[""ingredient""][""numOf""] = item[""numOf""];
+  delete item[""numOf""];
+});
+
+console.log(data);
+
+
+

+

If you want to be more dynamic and not be specific as in the previous code

+

you can procide like this

+
data.forEach(dataItem => {
+  dataItem.ingredients.map((item, index) => {
+    item["ingredient"]["numOf"] = item["numOf"];
+    delete item["numOf"];
+  });
+});
+
",html +"state' is not defined no-undef

So I’m following a course on React and I can't figure out how to solve this. +It suggests me that I put Spread operator '...' instead of 'this.' to select elements from the array. But when I do that it still shows error 'state' is not defined no-undef'. Im new to React, so am I doing something wrong here?

+

+
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js""></script>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js""></script>
+import { render } from '@testing-library/react';
+import React from 'react';
+import { Component } from 'react/cjs/react.production.min';
+import './App.css';
+import Person from './Person/Person';
+
+class App extends Component {
+  state = {
+    persons: [{name: 'Max', age: 22},
+              {name: 'Manu', age: 19},
+              {name: 'Stephanie', age: 41},
+              {name: 'George', age: 40}
+            ]
+    
+  }
+
+  render() {
+  return (
+    <div className=""App"">
+     <h1>Hi, I am a React App</h1>
+    <p>This is really working!</p>
+    <button>Switch Name</button>
+    <Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>
+    <Person {this.persons[1].name} {this.state.persons[1].age}/>
+    <Person {this.state.persons[2].name} {this.state.persons[2].age}> My Hobbie is swimming.</Person>
+    <Person {this.state.persons[3].name} {this.state.persons[3].age}/>
+    </div>
+  );
+}
+}
+
+
+export default App;
+
+
+

","

Assuming <Person /> component accepts age and name properties you can spread entire object with matching properties to this component using spread syntax as following:

+

<Person {...{this.persons[0]}} />

+

The above is equivalent yet shorthand for

+

<Person name={this.persons[0].name} age={this.persons[0].age} />

+

+

Please also note a wrong syntax you were inserting:

+

<Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>

+

First, the space shouldn't be there as you need to pass a value to a given property unlike to the vanilla JS syntax where you can create a variable with or woithout spaces:

+

const x = 1; or const x=1;

+

Secondly, you are trying to pass age value to component but you haven't pointed out which property it should be assigned to.

+

Keep up and good luck.

",html +"CSS doesn't work

I want to create a website.

+

Prerequisites

+

CSS doesn't work.

+

Expected value

+

I want to set the size oflogo.svg to width: 120px;,height: 40px;.

+

Reproduction procedure

+

Run the code below.

+

index.html

+
<!DOCTYPE html>
+<html lang="ja">
+<head>
+    <meta charset="UTF-8">
+    <title>ポートフォリオサイト1</title>
+    <link rel="stylesheet" href="./dist/css/header.css" type="text/css">
+</head>
+<body>
+    <header class="header">
+        <a href="index.html" class="header__profile-button"><img src="image/logo.svg" alt="プロフィール"></a>
+        <nav class="header__breadcrumb-trail">
+                <a href="" class="header__breadcrumb-trail">About</a>
+                <a href="" class="header__breadcrumb-trail">Bicycle</a>
+        </nav>
+    </header>
+    <main class="main">
+        <div class="main__mainvisual">
+            <img class="main__mainvisual-image" src="image/mainvisual (1).jpg" alt="メインビジュアル">
+        </div>
+
+        <div class="main__about">
+            <p class="main__about-title">About</p>
+            <img class="main__profile-icon-image"src="image/about.jpg" alt="プロフィールアイコン">
+            <p class="main__name-text">Yusuke Oyama</p>
+            <p class="main__introduction-text">
+                初めまして。atago_ITと申します。
+                とある開発コミュニティで、QAエンジニアをやっています。
+                自転車と万年筆が大好きです。よろしくお願いいたします。
+            </p>
+        </div>
+
+        <div class="bicycle">
+           <div class="bicycle__bicycle-image">
+                <img src="image/bicycle1.jpg" alt="">
+           </div> 
+           <div class="bicycle__bicycle-image">
+                <img src="image/bicycle2.jpg" alt="">
+           </div>
+           <div class="bicycle__bicycle-image">
+                <img src="image/bicycle3.jpg" alt="">
+           </div>
+        </div>
+    </main>
+    <footer class="footer">
+        <p class="footer__text">
+            ©2021 atago_IT
+        </p>
+    </footer>
+</body>
+</html>
+
+

header.css

+
.header .header__profile_button {
+  width: 120px;
+  height: 40px;
+}
+
","

This looks like a very simple mistake that could have been easily overlooked. In your HTML, the <a> tag that surrounds your <img> has a class of header__profile-button whereas, your CSS calls for the class .header__profile_button. Just change either one so that the two match, and it should run smoothly.

+

A source that might be usefull: +https://www.w3schools.com/cssref/sel_class.asp

",html +"Optimization of code (HTML/CSS) for a simple case of border on a div

I'm a beginner on HTML5/CSS3, and even if I've found a way to solve the problem I'm faced, i'm pretty convinced I'm not solving it the right way.

+

Some explaination : I'm trying to reproducte the exact same thing (see below), in this case the problem was on the "border"/underline under each category, the little thin grey line, not the blue one.

+

+

Firstly I tried to put a border-bottom on all these with a padding, but the problem was that each grey line didn't have the same width.

+

Then I realized that the original grey border were maybe the border of the "block" of each sentences, not the sentence itself. So I created a class="border" that I duplicated for each sentence in my list, like this :

+

+

Which gives me the exact result I want. And I just wrote in my CSS (result on 2nd picture under):

+
.border{
+    border-bottom: 1px #b2b2b2 solid;
+}
+
+

+

But I don't find esthetic the way I wrote it on my HTML code.

+

Is there anyway to rewrote this pls ?

+

Thank's a lot people.

","

Figured it out, here's the answer

+

HTML:

+
    <nav id="liensarticle3">
+             <ul>
+                 <li><a href="#">Sed neque nisi consequat</a></li>
+                 <li><a href="#">Dapibus sed mattis blandit</a></li>
+                 <li><a href="#">Quis accumsan lorem</a></li>
+                 <li><a href="#">Suspendisse varius ipsum</a></li>
+                 <li><a href="#">Eget et amet consequat</a></li>
+             </ul>
+
+
+

CSS :

+
    #liensarticle3 > ul > li {
+    display: block;
+    border-bottom: 1px #b2b2b2 solid;
+}
+
",html +"How to load content from external file in JS to variable

I would like to make a simple website without cloning HTML files.

+

I want to store a content in separate text files (or html) in subdirectories (e.g. pages/pagehome.txt, pages/pageabout.txt, pages/pagecontact.txt). I used tag, but it does not allow to reuse css for that embedded content.

+

I want to import that files to variables and to change divs via innerHTML tag. +How can I import content from that files to variables? I don't want to use any complicated APIs or tons of code.

+

Is there available simply method to load files' content to variables using ONLY JS (No HTML or methods like invisible div with content)?

","

Use an XMLHttpRequest, and use the onload callback to get the response.

+
<body>
+  <div id="divv"></div>
+  <script>
+    var txtFile = new XMLHttpRequest();
+    txtFile.onload = function(e) {
+      document.getElementById("divv").innerHTML = txtFile.responseText; 
+    }
+    txtFile.open("GET", "file.txt", true); 
+    txtFile.send(null);
+  </script>
+</body>
+
+

EDIT: It seems you need to access local files, so you can use something like this

+
<body>
+  <div id="divv"></div>
+  <script>
+    window.onload = function() {
+        var iframe = document.createElement('iframe');
+        iframe.id = 'iframe';
+        iframe.style.display = 'none';
+        document.body.appendChild(iframe);
+        iframe.src = 'file.txt';
+        iframe.onload = function(){
+            var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
+            document.getElementById('divv').innerHTML = text;
+        };
+    }
+  </script>
+</body>
+
",html +"error while passing JSON from php to javascript

So I have this php file which have query thats extract data from the DB to draw it on a Chart (Note : I'm using Chart.js lib), btw the chart working fine but in order to pass the value to the chart I have to use json_encode() built-in function to move the array to the javascript side using AJAX to display the array value in the chart but I'm getting this error in the image below:

+

https://i.stack.imgur.com/B0DZH.png

+

My PHP code : https://pastebin.com/tNh18qGX

+

My HTML & JS code : https://pastebin.com/06k9xbe8

+

Thank you guys.

",

Make sure that when you go to you're .php file the only value/text/anything displayed on the page is the json u want to be retrieve by the request.

,html +"How an I make a background image fade out to reveal text on hover?

I'm trying to make a link's background-image disappear and the letter inside appear when hovering.

+

The closest I got is like this:

+

+
+
.slectercontainer {
+  width: auto;
+  height: 150px;
+  margin-top: 10%;
+  display: flex;
+  text-align: center;
+  justify-content: space-around;
+}
+
+.slectercontainer a {
+  font-size: 25px;
+  display: block;
+  color: transparent;
+  width: 150px;
+  height: 150px;
+}
+
+.select1 {
+  width: 150px;
+  height: 150px;
+  border-radius: 50%;
+  transition: 0.5s;
+  background-image: ""https://via.placeholder.com/150"";
+  background-size: cover;
+}
+
+.select1:hover {
+  opacity: 0.3;
+  color: rgb(255, 255, 255);
+}
+
<div class=""selectercontainer"">
+  <a href=""select1.html"">
+    <div class=""select1"">
+      select1
+    </div>
+  </a>
+  <a href=""/select2.html"">select2</a>
+  <a href=""/select3.html"">select3</a>
+  <a href=""/select4.html"">select4</a>
+</div>
+
+
+

+

and try with different way , but still not work

+

+
+
.slectercontainer{
+  width: auto;
+  height: 150px;
+  margin-top:10%;
+  display: flex;
+  text-align:center;
+  justify-content:space-around;
+}
+
+.slectercontainer a{
+  margin-bottom: 19px;
+    font-size: 25px;
+    display: block;
+    color: transparent;
+    width: 150px;
+   height: 150px;
+   transition: 0.5s;
+}
+
+.slectercontainer a:hover{
+  color:rgb(255, 255, 255);
+}
+
+.select1{
+  width: 150px;
+  height: 150px;
+  border-radius: 50%;
+  transition: 0.5s;
+}
+
+.select1:hover{
+  opacity: 0.3;
+  color:rgb(255, 255, 255);
+}
+
<div class=""slectercontainer"">
+        <a href=""/select1.html"">
+            <img src=""image/select1.jpg"" class=""select1"">
+            select1
+        </a>
+        <a href=""/select2.html"">select2</a>
+        <a href=""/select3.html"">select3</a>
+        <a href=""/select4.html"">select4</a>
+
+
+

+

I'm doing only this feature hold day , and still can't pull this off , appreciate the help

","

You can use from rgba instead opacity:

+

+
+
.slectercontainer {
+  width: auto;
+  height: 150px;
+  margin-top: 10%;
+  display: flex;
+  text-align: center;
+  justify-content: space-around;
+}
+
+.slectercontainer a {
+  font-size: 25px;
+  display: block;
+  color: transparent;
+  width: 150px;
+  height: 150px;
+}
+
+.select1 {
+  text-align: center;
+  width: 150px;
+  height: 150px;
+  border-radius: 50%;
+  transition: 0.5s;
+  background-image: url(""https://s4.uupload.ir/files/1-6-5_ssnb.jpg"");
+  background-size: cover;
+}
+
+.blur{
+  width: 100%;
+  height: 100%;
+  border-radius: 50%;
+}
+
+.blur:hover{
+   background: rgba(255, 255, 255, 0.6);
+}
+
<div class=""selectercontainer"">
+  <a href=""select1.html"">
+    <div class=""select1"">
+    <div class=""blur"">
+      select1
+    </div>
+    </div>
+  </a>
+  <a href=""/select2.html"">select2</a>
+  <a href=""/select3.html"">select3</a>
+  <a href=""/select4.html"">select4</a>
+</div>
+
+
+

",html +"How to create checkbox automatic from ajax call (Undefined currently)

Hi I needed some help on making it to auto create a checkbox to my ajax name how can i do it ? I have added the new answer to my code however currently i showing Undefinted with checkbox of the type i realize

+
<div id="modal">
+<section>
+<div id="recyclable_id"></div>
+</section>
+</div>
+
+

Ajax call sample for options

+
     $(document).ready(function() {
+                    $.ajax( {
+                        url: 'https://ecoexchange.dscloud.me:8090/api/get', 
+                        type: 'GET', 
+                        dataType: 'json',
+                        headers:{
+                            query: "RecyclableTypeGet()",
+                            // Gets the apikey from the sessionStorage
+                            apikey: sessionStorage.getItem("apikey")
+                        },
+                        success: function(data) {
+                        console.log(data);
+                        var html='';
+                        $.each(data, function(key, value) {
+                            html +='<input type="checkbox" name="recyclable_id[]" value="'+value.RecyclableID+'"><label style="padding-left: 10px;">'+value.Name+'</label><br>';
+                        }
+                        );
+                        $('#recyclable_id').html(html);
+                        }
+                    }
+                    );
+                    }
+
+                    );
+
+

this is my json response that i am going to use for the name only

+
[
+    {
+        "RecyclableID": 1,
+        "Name": "recyclable",
+        "RecyclableType": "test recyclable type"
+    },
+    {
+        "RecyclableID": 3,
+        "Name": "test recyclable 2",
+        "RecyclableType": "WASTE"
+    },
+    {
+        "RecyclableID": 129,
+        "Name": "test recyclable 4",
+        "RecyclableType": "test recyclable type"
+    },
+    {
+        "RecyclableID": 131,
+        "Name": "test recyclable 6",
+        "RecyclableType": "test recyclable type"
+    },
+    {
+        "RecyclableID": 132,
+        "Name": "test recyclable 7",
+        "RecyclableType": "test recyclable type"
+    },
+    {
+        "RecyclableID": 133,
+        "Name": "test recyclable 8",
+        "RecyclableType": "test recyclable type"
+    },
+    {
+        "RecyclableID": 134,
+        "Name": "test recyclable 34",
+        "RecyclableType": "WASTE"
+    },
+    {
+        "RecyclableID": 138,
+        "Name": "recyclable thing",
+        "RecyclableType": "WASTE"
+    },
+    {
+        "RecyclableID": 139,
+        "Name": "recyclable thing 2",
+        "RecyclableType": "Ewaste"
+    },
+    {
+        "RecyclableID": 153,
+        "Name": "test recyclable 10",
+        "RecyclableType": "Other"
+    },
+    {
+        "RecyclableID": 154,
+        "Name": "test recyclable 11",
+        "RecyclableType": "Ewaste"
+    },
+    {
+        "RecyclableID": 155,
+        "Name": "test recyclable 123",
+        "RecyclableType": "test recyclable type 2"
+    },
+    {
+        "RecyclableID": 159,
+        "Name": "some recyclable name",
+        "RecyclableType": "CC"
+    },
+    {
+        "RecyclableID": 161,
+        "Name": "some recyclable name 2",
+        "RecyclableType": "Ewaste"
+    },
+    {
+        "RecyclableID": 162,
+        "Name": "recyclable 2",
+        "RecyclableType": "test recyclable type 2"
+    },
+    {
+        "RecyclableID": 165,
+        "Name": "test recyclable 15",
+        "RecyclableType": "WASTE"
+    },
+    {
+        "RecyclableID": 166,
+        "Name": "test recyclable 18",
+        "RecyclableType": "testing type"
+    },
+    {
+        "RecyclableID": 167,
+        "Name": "some recyclable name 23",
+        "RecyclableType": "Ewaster"
+    }
+]
+
+

This is my picture showing undefined +I have try to change with the new anser given but it seem to be getting undefinied x 10 from type

","

Does this work? Copilot created the code xD

+

+
+
$(document).ready(function() {
+  $.ajax( {
+    url: 'http://localhost/recyclable/public/api/recyclable', type: 'GET', dataType: 'json', success: function(data) {
+      console.log(data);
+      var html='';
+      $.each(data, function(key, value) {
+        html +='<input type=""checkbox"" name=""recyclable_id[]"" value=""'+value.RecyclableID+'""><label style=""padding-left: 10px;"">'+value.Name+'</label><br>';
+      }
+      );
+      $('#recyclable_id').html(html);
+    }
+  }
+  );
+}
+
+);
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div id=""recyclable_id""></div>
+
+
+

",html +"Create element from its constructor (without knowing the element tag)

Is it possible to create an element if you have its constructor but don't know its tag name?

+

Example:

+
class CustomElement extends HTMLElement {}
+customElements.define(genRandomString(), CustomElement);
+
+

Is it possible to create a new instance of CustomElement? Or can you obtain its tag name in any way?

+

I'm asking this because I'm not sure what's the correct way to pass custom elements to functions that need them: do I need to pass around both the name and the constructor, in case one may need to either create an element (which requires the name) or to check whether an existing element is of this kind (which requires the constructor)?

","
+

Is it possible to create an element if you have its constructor but don't know its tag name?

+
+

If you have access to the constructor (like you said you have), you can just use

+
const instance = new CustomElement();
+
+

Please note that this might fail if the constructor doesn't conform to Custom Element constructor constraints.

",html +"Basic sorting of a table once by one column in one direction (desc) without a plugin

I have a basic table with x amount of columns. +The table needs to be sorted by the value in the first column which is an integer. +The sort only needs to happen once in descending order using jQuery or JavaScript without a plug-in.

+
Position   Event
+3          Investigation
+5          Triage
+4          Clinic
+1          MDT
+2          Other
+
","

You can use some spreads ('...') and a simple sort function

+

Inner spread is to make the rows sortable and outer spread is to change them back to html

+

The unary + is not even needed here because of subtraction (ascending numerical)

+

+
+
window.addEventListener(""load"",function() {
+  const tb = document.getElementById(""tb"");
+  const rows = tb.querySelectorAll(""tr"")
+  tb.append(...[...rows].sort((a,b) => {
+    const A = +a.querySelector(""td"").textContent;
+    const B = +b.querySelector(""td"").textContent;
+    return A-B;
+  })) 
+})
+
<table>
+  <thead>
+    <tr>
+      <th>Position</th>
+      <th>Event</th>
+    </tr>
+  </thead>
+  <tbody id=""tb"">
+    <tr>
+      <td>3</td>
+      <td>Investigation</td>
+    </tr>
+    <tr>
+      <td>5</td>
+      <td>Triage</td>
+    </tr>
+    <tr>
+      <td>4</td>
+      <td>Clinic</td>
+    </tr>
+    <tr>
+      <td>1</td>
+      <td>MDT</td>
+    </tr>
+    <tr>
+      <td>2</td>
+      <td>Other</td>
+    </tr>
+  </tbody>
+</table>
+
+
+

",html +"iFrame has fixed width of 300px, without any styling defining 300px

I'm using the iframe-resizer package to dynamically change the size of an iframe depending on content.

+

However, before even trying any dynamic resizing, I run into an issue with the basic iframe: it's always 300px in width. Whatever content I place inside the iframe, the width is always 300px. Will not move; overflow is hidden if I add something >300px and still takes up 300px if my content is smaller than that.

+

EDIT: To be clear, My problem is that I want to dynamically change the width of an iframe (cross-domain), but it always renders at 300px and will not change. I'm using the iframe-resizer package to successfully dynamically change the height, but that's nto working on the width.

+

In the parent site, I'm embedding the iframe as follows:

+
<script type="text/javascript"
+    src="https://cdn.jsdelivr.net/npm/iframe-resizer@4.2.11/js/iframeResizer.min.js">
+</script>
+<script type="text/javascript">
+    var i = new URLSearchParams(window.location.search).get("openWidget"); document.write('<iframe id="inlineFrameExample" title="Inline Frame Example" style="position: fixed; zIndex: 1000; bottom: 0; right: 0" frameBorder="0" scrolling="no" src="http://localhost:3001?openWidget=' + i + '"></iframe>');
+    window.iFrameResize({ log: true }, '#inlineFrameExample')
+</script>
+
+

And the content in my for my framed site, I have the following elements and styling:

+
    <div className="App" id="App2">
+      {openWidget && <div className="button">OK</div>}
+      {showMessage && <section>This is a message</section>}
+      <div>
+        <button className="button" onClick={() => setShowMessage(!showMessage)}>
+          Msg
+        </button>
+        <button className="button" onClick={() => setOpenWidget(!openWidget)}>
+          {openWidget ? "-" : "+"}
+        </button>
+      </div>
+    </div>
+
+.App {
+  text-align: center;
+  float: right;
+}
+
+.container {
+  display: flex;
+  justify-content: flex-end;
+  float: right;
+}
+
+section {
+  background-color: mediumseagreen;
+  color: white;
+  width: 500px;
+}
+
+.button {
+  width: 100px;
+  height: 100px;
+  background-color: mediumseagreen;
+  color: white;
+  text-align: center;
+  float: right;
+}
+
+

Note that there's nothing in there about width being 300px. There are other widths, but the iframe seems to ignore them and always set itself to 300px.

+

I also made two code sandboxes, and embedded one site in the other via an iframe. Unfortunately the iframe is hidden for some reason, but if you inspect and look for the iFrame with id="inlineFrameExample" (and not code sandbox's button iframe) you'll see it's 300px wide: https://exzts.csb.app/ +The code for the parent site is here: https://codesandbox.io/s/eloquent-flower-exzts?file=/index.html +The code for the framed site is here: https://codesandbox.io/s/iframe-test-ss8fs

+

UPDATE: I also removed all css styling from both the parent site and the framed site. Still always stuck at 300px. I also viewed the CSS specs which says default will be default set to 300px under certain conditions, but I cannot figure out how to dissatisfy those conditions so that the 300px rule doesn't apply.

+

I want the iframe to resize based on width. The current set up works perfectly on height, and I understand there's something in the default specs for iframes that sets them to 300px if x conditions are met: w3.org/TR/CSS2/visudet.html#inline-replaced-width What I need is whatever styling/setting/attribute will disable this, so the width will act in the same way as the height (i.e. completely dynamic).

","

The iframe-resizer doesn't resize iframe width by default. You have to explicitly specify it using sizeWidth setting.

+

+
+
window.iFrameResize({
+  log: false,
+  sizeWidth: true,
+  checkOrigin: false,
+  widthCalculationMethod: ""rightMostElement"",
+  heightCalculationMethod: ""lowestElement""
+}, ""#myFrame"");
+
body { background-color: wheat;}
+iframe { border: 3px dashed green; }
+span { font-size: 1.5rem;}
+
<script type=""text/javascript"" src=""https://cdn.jsdelivr.net/npm/iframe-resizer@4.2.11/js/iframeResizer.min.js""></script>
+
+<div>Following iframe grows automatically!</div>
+<iframe id=""myFrame"" scrolling=""no"" src=""https://mvyom.csb.app/""></iframe>
+<span></span>
+
+
+

+

The iframe content is animated so it affects iframe's width and height according to the specified width and height calculation methods. And the iframe-resizer updates dimensions on every animations start and end event. +
Also, the iframe source is from codesandbox and the parent document is this StackOverflow answer page, so we need to set checkOrigin: false as well. +

+Note: Had to set log: false because the animations are happening very fast creating ton of logs in console.

+
+

You can provide your own size calculations form inside the iframe.ref:

+
    <script>
+      window.iFrameResizer = {
+        widthCalculationMethod: function () {
+          return document.querySelector(".one").clientWidth;
+        }
+      };
+    </script>
+
+

In following demo the iframe resizes exactly to the width of green box.

+

+
+
window.iFrameResize({
+  log: false,
+  sizeWidth: true,
+  checkOrigin: false,
+  widthCalculationMethod: ""rightMostElement"",
+  heightCalculationMethod: ""lowestElement""
+}, ""#myFrame"");
+
body { background-color: wheat;}
+iframe { border: 3px dashed green; }
+span { font-size: 1.5rem;}
+
<script type=""text/javascript"" src=""https://cdn.jsdelivr.net/npm/iframe-resizer@4.2.11/js/iframeResizer.min.js""></script>
+
+<div>Following iframe grows automatically!</div>
+<iframe id=""myFrame"" scrolling=""no"" src=""https://mvyom.csb.app/custom.html""></iframe>
+<span></span>
+
+
+

+

Refer implementation of custom.html for better understanding. You can implement similar method for heightCalculationMethod.

",html +"JavaScript prevent button event on specified conditions

I have a webshop-like shopping cart function. It displayas the products that you have added. You can change the product quantity by clicking on the + and the - buttons. +On button click, an AJAX call will be sent to a PHP file that updates the database so you instantly save the actual quantity. +As you increase or decrease the selected quantity, a counter appears to indicate how many times the original product will be multiplied. You can increase or decrease the quantity between 1 and 30. As you reach for example 1, the counter stops, but the AJAX call will be sent regardless it shouldn't go below 1.

+

Preview video

+

+
+
let subt = 30; // The value from PHP after you sent the AJAX call and reloaded the page
+document.getElementById(""plus"").addEventListener(""click"", () => {
+  if (document.getElementById(""inp"").value < 30) {
+    document.getElementById(""inp"").value = Number(document.getElementById(""inp"").value) + 1;
+  }
+  if (document.getElementById(""inp"").value > 1) {
+    /*
+        var bsi__data = new FormData(); bsi__data.append(""pid"", '(product id)'); bsi__data.append(""quantity"", document.getElementById(""inp"").value); bsi__data.append(""price"", ""30"");
+        $.ajax({
+            enctype: ""multipart/form-data"", type: ""POST"", url: ""/assets/php/basket/q__up.php"", data: bsi__data, dataType: ""json"", contentType: false, processData: false,
+            success: function(data) { console.log(data); subt += Number('30'); document.getElementById(""subtotal"").textContent = formatter.format(subt); },
+            error: function (data) { console.log(""error""); console.log(data); }
+        });
+        */
+    subt += Number('30');
+    document.getElementById(""subtotal"").textContent = subt;
+    document.getElementById(""ind"").textContent = ""x "" + document.getElementById(""inp"").value;
+  }
+  if (document.getElementById(""inp"").value == 1) {
+    document.getElementById(""ind"").textContent = """";
+  }
+});
+document.getElementById(""min"").addEventListener(""click"", function dicr() {
+  if (document.getElementById(""inp"").value > 1) {
+    document.getElementById(""inp"").value = Number(document.getElementById(""inp"").value) - 1;
+  }
+  if (document.getElementById(""inp"").value >= 1) {
+    /*
+    var bsi__data = new FormData(); bsi__data.append(""pid"", ""(product id)""); bsi__data.append(""quantity"", document.getElementById(""inp"").value);
+    $.ajax({
+        enctype: ""multipart/form-data"", type: ""POST"", url: ""/assets/php/basket/q__up.php"", data: bsi__data, dataType: ""json"", contentType: false, processData: false,
+        success: function(data) { console.log(""decr""); subt -= Number(30); document.getElementById(""subtotal"").textContent = formatter.format(subt); },
+        error: function (data) { console.log(""error""); console.log(data); }
+    });
+    */
+
+    subt -= Number(30);
+    document.getElementById(""subtotal"").textContent = subt;
+    document.getElementById(""ind"").textContent = ""x "" + document.getElementById(""inp"").value;
+  }
+  if (document.getElementById(""inp"").value == 1) {
+    document.getElementById(""ind"").textContent = """";
+  }
+});
+
<div>
+  <span>Product name</span><span id=""price"">$30</span><span id=""ind""></span>
+  <div>
+    <span id=""plus"">+</span>
+    <input type=""number"" id=""inp"" min=""1"" max=""30"" value=""1"" />
+    <span id=""min"">-</span><br><br>
+    <span>Subtotal: $</span>
+    <span id=""subtotal"">30</span>
+  </div>
+</div>
+
+
+

","

https://jsfiddle.net/jnerx76z/

+
document.getElementById("plus").addEventListener("click", () => {
+  if (document.getElementById("inp").value < 30) {
+    document.getElementById("inp").value = Number(document.getElementById("inp").value) + 1;
+  }
+  if (document.getElementById("inp").value > 1) {
+    /*
+        var bsi__data = new FormData(); bsi__data.append("pid", '(product id)'); bsi__data.append("quantity", document.getElementById("inp").value); bsi__data.append("price", "30");
+        $.ajax({
+            enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
+            success: function(data) { console.log(data); subt += Number('30'); document.getElementById("subtotal").textContent = formatter.format(subt); },
+            error: function (data) { console.log("error"); console.log(data); }
+        });
+        */
+    subt += Number('30');
+    document.getElementById("subtotal").textContent = subt;
+    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
+  }
+  if (document.getElementById("inp").value == 1) {
+    document.getElementById("ind").textContent = "";
+  }
+});
+document.getElementById("min").addEventListener("click", function dicr() {
+    var newValue;
+  if (document.getElementById("inp").value > 1) {
+    newValue = Number(document.getElementById("inp").value) - 1;
+    document.getElementById("inp").value = newValue;
+  }
+  if (newValue >= 1) {
+  alert(newValue)
+    /*
+    var bsi__data = new FormData(); bsi__data.append("pid", "(product id)"); bsi__data.append("quantity", document.getElementById("inp").value);
+    $.ajax({
+        enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
+        success: function(data) { console.log("decr"); subt -= Number(30); document.getElementById("subtotal").textContent = formatter.format(subt); },
+        error: function (data) { console.log("error"); console.log(data); }
+    });
+    */
+
+    subt -= Number(30);
+    document.getElementById("subtotal").textContent = subt;
+    document.getElementById("ind").textContent = "x " + document.getElementById("inp").value;
+  }
+  if (document.getElementById("inp").value == 1) {
+    document.getElementById("ind").textContent = "";
+  }
+});
+
",html +"How to access the html value of this specific element?

This example has multiple products (instruments) and each one has a purchase button, when i click on the purchase button of a product its supposed to send the quantity value extracted from the html spinbox to the function myfunction.

+

Problem : +--I always end up getting the value of the first product in the myfunction with the the variable used 'a' (because all the products have the same id)

+

anyway to access the value of the spinbox of each HTML individually?

+
  {% for post in posts %}
+    <article class="media content-section">
+      <div class="media-body">
+        <div class="article-metadata">
+          <a class="mr-2" href="#">{{ post.type + " " + post.instrument }}</a>
+          <small class="text-muted">{{ post.date_posted }}</small>
+        </div>
+        <h2><a class="article-title" href="#">{{ post.name }} : {{post.brand}}</a></h2>
+        <div class="article-metadata">
+          {% if post.type not in "Guitar" or "bass" %}
+              <p class="article-content">{{"effects : " + post.frets + "\nColor : " + post.color + "\nportability : " + post.bridge}}</p>  
+          {% else %}
+              <p class="article-content">{{"Bridge : " + post.bridge + "\nColor : " + post.color + "\nFrets : " + post.frets}}</p>
+          {% endif %}
+        </div>
+        <a class="mr-2" href="#">{{"Quantity"}} : {{post.quantity}}</a>
+
+        <form>
+          <input class="quant" name="quant" id="a" type="number" min="1" max={{post.quantity}} required>
+          <br>
+          <a>{{"Price:"}}</a>
+          <a class="mr-2" href="#">{{post.price + "$"}}</a>
+          <button type="submit" class="purchase" onclick="myFunction({{post.quantity}},'{{post.brand}}', '{{post.name}}', '{{post.price}}')">Purchase</button>
+        </form>
+      </div>
+    </article>
+{% endfor %}
+
+
+        <script>
+          function ajaxcall(quantity, brand, name){
+            $.ajax({
+                    url : "{{ url_for('quantity_update') }}",
+                    type: 'POST',
+                    data: {new_quantity: JSON.stringify(quantity), brand: JSON.stringify(brand), name: JSON.stringify(name)}
+                });
+          }
+          function myFunction(quant, brand, name, price) {
+            var a = document.getElementById('a').value;
+            prix = parseInt(price) * a
+            let text = "Press a button!\n--OK to Purchase (Total price : " + prix + ")\n--Cancel to cancel.";
+            if (a) {
+              if(confirm(text)){
+                alert("Congrats, the product has been bought");
+                quantity = quant - a;
+                ajaxcall(quantity, brand, name);
+              }
+            } else {
+              alert("Please insert a value before buying")
+            }
+            document.getElementById("demo").innerHTML = text;
+          }
+          </script>
+
","

The reason the first quantity is being accessed is because having multiple elements with the same id is invalid HTML - and typically browsers will return the first element in the document matching an id value supplied to document.getElementById.

+

One solution would be remove the id value from the quantity input and instead, locate the input box as child of its parent form. The parent form of a button (and other form elements) is supplied as the form property of nested form elements.

+

This example passes the form element to function myFunction from the click handler instead of the quantity argument, and adds a type="button" attribute to purchase buttons to stop them generating a submit event by default.

+

+
+
""use strict"";
+function myFunction(form, name, brand, price) {
+   let quantity = form.querySelector("".quant"");
+   console.log(""quantity for purchase is "" + quantity.value);
+}
+
<form name=""whatever"">
+  <label>quantity: <input class=""quant"" value=""1""></label>
+  <button type=button onclick='myFunction( this.form, ""name"", ""brand"", ""price"")'>Purchase</button>
+</form>
+<form name=""whatever"">
+  <label>quantity: <input class=""quant"" value=""42""></label>
+  <button type=button onclick='myFunction( this.form, ""name"", ""brand"", ""price"")'>Purchase</button>
+</form>
+
+
+

+

Note that supplying event handlers in HTML is discouraged, and Emiels's excellent answer shows an approach to reworking the code to supply the click event listeners in JavaScript.

",html +"Hamburger button on bootstrap wont open

I have followed the code from BootStrap as follows:

+

+
+
<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"" rel=""stylesheet"" integrity=""sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"" crossorigin=""anonymous"">
+<script src=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"" integrity=""sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"" crossorigin=""anonymous""></script>
+
+<!-- Nav Bar -->
+<nav class=""navbar bg-dark navbar-expand-lg navbar-dark"">
+  <a class=""navbar-brand"" href=""index.html"">One Basket</a>
+  <button class=""navbar-toggler ms-auto"" type=""button"" data-mdb-toggle=""collapse"" data-mdb-target=""#navbarToggleExternalContent2"" aria- controls=""navbarToggleExternalContent2"" aria-expanded=""false"" aria-label=""Toggle navigation"">          
+         <span class=""navbar-toggler-icon""></span>
+       </button>
+  <div class=""collapse navbar-collapse"" id=""navbarToggleExternalContent2"">
+    <ul class=""navbar-nav ms-auto"">
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Contact</a>
+      </li>
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Pricing</a>
+      </li>
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Download</a>
+      </li>
+    </ul>
+  </div>
+</nav>
+
+
+

+

I have also added the CSS from the bootstrap documentation and the javascript to the HTML file. +The JS is at the end before the close body tag, just like it says on the bootstrap website.

+ +

The CSS is the first link tag in the head. +But when I try to press the button nothing happens.

","

You have wrong attributes to make it work by default, just replace data-mdb-toggle="collapse" data-mdb-target="#navbarToggleExternalContent2" with data-bs-toggle="collapse" data-bs-target="#navbarToggleExternalContent2", see (in my CodeSnippet I using BS v5.1):

+

+
+
<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"" rel=""stylesheet"" integrity=""sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"" crossorigin=""anonymous"">
+<script src=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"" integrity=""sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"" crossorigin=""anonymous""></script>
+
+
+<!-- Nav Bar -->
+<nav class=""navbar bg-dark navbar-expand-lg navbar-dark"">
+  <a class=""navbar-brand"" href=""index.html"">One Basket</a>
+  <button class=""navbar-toggler ms-auto"" type=""button"" data-bs-toggle=""collapse"" data-bs-target=""#navbarToggleExternalContent2"" aria- controls=""navbarToggleExternalContent2"" aria-expanded=""false"" aria-label=""Toggle navigation"">          
+     <span class=""navbar-toggler-icon""></span>
+   </button>
+  <div class=""collapse navbar-collapse"" id=""navbarToggleExternalContent2"">
+    <ul class=""navbar-nav ms-auto"">
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Contact</a>
+      </li>
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Pricing</a>
+      </li>
+      <li class=""nav-item"">
+        <a class=""nav-link"" href="""">Download</a>
+      </li>
+    </ul>
+  </div>
+</nav>
+
+
+

",html +"How to convert Base64 to HTML?

I need to convert Base64 to HTML in Flutter, but it fails.

+

This is my HTML encoded Base64 string:

+
"PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg=="
+
+

I already try to decode but the output format just an array of numbers.

+
import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:flutter_html/flutter_html.dart';
+
+var decoded = base64.decode(
+      "PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg==");
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      appBar: HeaderMenu(
+        title: Text(
+          'Base64 to HTML',
+          style: TextStyle(color: Colors.black, fontWeight: FontWeight.w600),
+        ),
+        isBack: true,
+        icon: [],
+        isCenter: true,
+      ),
+      body: Column(
+        children: [
+          Html(data: decoded.toString()),
+        ],
+      ),
+    );
+  }
+
","

The purpose of encoding something to base64 is to convert binary data to ASCII text. It doesn't make a lot of sense to base64-encode HTML, which is already text. (But I suppose maybe it was base64-encoded as some overzealous way of performing data sanitization.)

+

Anyway, when you decode a base64 string, the result is expected to binary data. To treat that sequence of bytes as a string, you will need to perform an additional decoding step to specify how those bytes should be interpreted: as ASCII text? as UTF-8-encoded text? UTF-16? UTF-32?

+

In your case, your base64 string appears to be UTF-8:

+
import 'dart:convert';
+
+void main() {
+  var base64String =
+      "PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg==";
+  var bytes = base64.decode(base64String);
+  var decoded = utf8.decode(bytes);
+  print(decoded);
+}
+
+

prints:

+
<html>
+<head>
+  <title>Title of the document</title>
+</head>
+
+<body>
+  <h1>This is a heading</h1>
+  <p>This is a paragraph.</p>
+</body>
+
+</html>
+
+

Using ascii.decode also would work in your particular case.

",html +"Hiding / showing a checkboxes based on a previously selected checkbox (based on the data-attribute) jquery

I have no idea how to hide / show checkboxes depending on the choice based on the data-attribute (data-profession attribute).

+

Code: https://codepen.io/caqoga/pen/RwQyRaQ

+
<head>
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
+</head>
+<div>
+            <div>
+                  <h2>Select profession</h2>
+                <div>
+                    <div class="form-check">
+                        <input class="form-check-input" type="checkbox" name="profession" value="1" data-profession="profession_1" id="profession1" checked="">
+                        <label class="form-check-label" for="profession1">Security guard</label>
+                    </div>
+                    <div class="form-check">
+                        <input class="form-check-input" type="checkbox" name="profession" value="2" data-profession="profession_2" id="profession2">
+                        <label class="form-check-label" for="profession2">Welder</label>
+                    </div>
+                           
+                </div>
+                   <h2>Expected salary</h2>
+                <div>
+                    <div class="form-check profession_1">
+                        <input class="form-check-input" type="checkbox" name="salary" value="1" data-profession="profession_1" id="salary1" checked="">
+                        <label class="form-check-label" for="salary1">1000 EUR</label>
+                    </div>
+                    <div class="form-check profession_1">
+                        <input class="form-check-input" type="checkbox" name="salary" value="2" data-profession="profession_1" id="salary2">
+                        <label class="form-check-label" for="salary2">1500 EUR</label>
+                    </div>
+                    <div class="form-check profession_2">
+                        <input class="form-check-input" type="checkbox" name="salary" value="3" data-profession="profession_2" id="salary3">
+                        <label class="form-check-label" for="salary3">3500 EUR</label>
+                    </div>
+                                        
+                </div>
+            </div>
+        </div>
+</div>
+
+
$( document ).ready(function() { 
+
+$('input[name="profession"]').change(function(){
+            if (!$(this).is(':checked')) {
+                $(this).prop('checked', true);
+            } else {
+                $(this).parent().siblings().find('input').prop('checked', false);
+            }
+        })
+
+$('input[name="salary"]').change(function(){
+            if (!$(this).is(':checked')) {
+                $(this).prop('checked', true);
+            } else {
+                $(this).parent().siblings().find('input').prop('checked', false);
+            }
+        })
+
+});
+
+

And now I would like to compare the data-profession in both inputs, if it is equal to or differs - depending on the .change - displaying or hiding the entire checkbox.

+

In this case, I would like only EUR 1000 and EUR 1500 for the Security Guard, and only EUR 3500 for the Welder.

+

Something like below:

+
$('input[name="profession"]').change(function(){
+
+var idprof=$(this).attr('data-profession');
+var idsalarytoprof=$('input[name="salary"]').attr('data-profession');
+       
+if (idprof == idsalarytoprof) {$('.proffesion_' + idsalarytoprof).show();} 
+else {$('.proffesion_' + idsalarytoprof).hide();}
+      
+});
+$('input[name="profession"]').trigger('change');
+
+

Thank you for your help.

","

2 ways for requirement of you :

+
    +
  1. Disable input of other profession (unchecked)
  2. +
  3. Hide input of other profession (unchecked)
  4. +
+

Code same as : +

+
+
$('.example-1 input').change(function(){
+  let profession = $(this).data('profession')
+  if (!$(this).is(':checked')) {
+    $(this).prop('checked', true);
+  } else {
+    $(this).parent().siblings().find('input').prop('checked', false);
+    $('.' + profession).find('input').attr('disabled',false)
+    $('.' + profession).siblings(':not(.' + profession + ')').find('input').attr('disabled',true).prop('checked', false)
+  }
+})
+
+$('.example-2 input').change(function(){
+  let profession = $(this).data('profession')
+  if (!$(this).is(':checked')) {
+    $(this).prop('checked', true);
+  } else {
+    $(this).parent().siblings().find('input').prop('checked', false);
+    $('.' + profession).removeClass('hide').find('input').attr('disabled',false)
+    $('.' + profession).siblings(':not(.' + profession + ')').addClass('hide').find('input').attr('disabled',true).prop('checked', false)
+  }
+})
+
.example-2 .hide {
+  display: none;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div>
+  <div class=""example-1"">
+    <h2>Select profession</h2>
+    <div>
+      <div class=""form-check"">
+        <input class=""form-check-input"" type=""checkbox"" name=""profession"" value=""1"" data-profession=""profession_1"" id=""profession1"" checked="""">
+        <label class=""form-check-label"" for=""profession1"">Security guard</label>
+      </div>
+      <div class=""form-check"">
+        <input class=""form-check-input"" type=""checkbox"" name=""profession"" value=""2"" data-profession=""profession_2"" id=""profession2"">
+        <label class=""form-check-label"" for=""profession2"">Welder</label>
+      </div>
+    </div>
+    
+    <h2>Expected salary</h2>
+    <div>
+      <div class=""form-check profession_1"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""1"" data-profession=""profession_1"" id=""salary1"">
+        <label class=""form-check-label"" for=""salary1"">1000 EUR</label>
+      </div>
+      <div class=""form-check profession_1"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""2"" data-profession=""profession_1"" id=""salary2"">
+        <label class=""form-check-label"" for=""salary2"">1500 EUR</label>
+      </div>
+      <div class=""form-check profession_2"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""3"" data-profession=""profession_2"" id=""salary3"" disabled>
+        <label class=""form-check-label"" for=""salary3"">3500 EUR</label>
+      </div>
+    </div>
+  </div>
+  <div class=""example-2"">
+    <h2>Select profession examle 2</h2>
+    <div>
+      <div class=""form-check"">
+        <input class=""form-check-input"" type=""checkbox"" name=""profession"" value=""1"" data-profession=""profession_11"" id=""profession11"" checked="""">
+        <label class=""form-check-label"" for=""profession1"">Security guard</label>
+      </div>
+      <div class=""form-check"">
+        <input class=""form-check-input"" type=""checkbox"" name=""profession"" value=""2"" data-profession=""profession_21"" id=""profession21"">
+        <label class=""form-check-label"" for=""profession2"">Welder</label>
+      </div>
+    </div>
+    <h2>Expected salary examle 2</h2>
+    <div>
+      <div class=""form-check profession_11"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""1"" data-profession=""profession_11"" id=""salary11"">
+        <label class=""form-check-label"" for=""salary1"">1000 EUR</label>
+      </div>
+      <div class=""form-check profession_11"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""2"" data-profession=""profession_11"" id=""salary21"">
+        <label class=""form-check-label"" for=""salary2"">1500 EUR</label>
+      </div>
+      <div class=""form-check profession_21 hide"">
+        <input class=""form-check-input"" type=""checkbox"" name=""salary"" value=""3"" data-profession=""profession_21"" id=""salary31"">
+        <label class=""form-check-label"" for=""salary3"">3500 EUR</label>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"Wordpress - How to add condition ""if user logged in"" for html/css/js menu

I'm working with elementor, in the html widget I wrote some code to create a menu and it works fine. Now I want to hide a part of the menu to make it visible only to logged in users. I understand that this is done with php, but elementor's html widget does not support php. So I'm wondering if there is an alternative to php or if there is a way to indirectly apply php to my menu ?

+

I'm working with elementor, in the html widget I wrote some code to create a menu and it works fine. Now I want to hide a part of the menu to make it visible only to logged in users. I understand that this is done with php, but elementor's html widget does not support php. So I'm wondering if there is an alternative to php or if there is a way to indirectly apply php to my menu?

+

Here is my test menu, it's just a test so there are only two items. Can anyone help me understand how I can accomplish this? Sorry but I'm new and I'm trying to learn.

+

I appreciate any response, thanks.

+

Edit with possible solution: in wp-content / themes / child-theme / I created a folder called custom_menu, inside this I added two files, menu_structure.php and menu_style.css. The php file contains the html code with the script, while in the css I inserted the styles.

+

Then I went to the functions.php file and added this line include_once get_theme_file_path ('/custom_menu/menu_structure.php'); This is to make wordpress understand that menu_structure.php must execute the functions, otherwise the shortcode would not work.

+

Finally, in the menu_structure.php file I added a shortcode, inside it I then added html menu and script. That's how...

+
add_shortcode( 'mob_menu' , 'mobile_menu' );
+function mobile_menu(){
+?>
+
+//Here I called the style css
+<link rel="stylesheet" href="https://motustrength.it/wp-content/themes/astra-child/custom_menu/menu_style.css" type="text/css">
+
+<?php if(is_user_logged_in()): ?> 
+
+//Here I put html div menu...
+
+<script>
+//Here I put the script...
+</script>
+
+<?php endif; ?>
+
+<?php
+}
+
+

This is the initial code that I have inside elementor html widget +

+
+
var menu = document.querySelector("".mob_menu_button"");
+      function mobile_menu(e) {
+        e.stopPropagation();
+        var x = document.getElementById(""mts_mobile_menu"");
+        if (!x.classList.contains(""active"")) {
+          x.classList.add(""active"");
+          menu.innerHTML = ""<span>Close menu</span>"";
+        } else {
+          x.classList.add(""side_hide"");
+          menu.innerHTML = ""<span>Open menu</span>"";
+
+          setTimeout(function () {
+            x.classList.remove(""active"");
+            x.classList.remove(""hide"");
+          }, 100);
+        }
+      }
+      
+      document.addEventListener(""click"", function (e) {
+        var x = document.getElementById(""mts_mobile_menu"");
+        if (e.target.id !== ""mts_mobile_menu"" && x.classList.contains(""active"")) {
+          x.classList.add(""hide"");
+          menu.innerHTML = ""<span>Open menu</span>"";
+
+          setTimeout(function () {
+            x.classList.remove(""active"");
+            x.classList.remove(""hide"");
+          }, 400);
+        }
+      });
+
* {
+        margin: 0;
+        padding: 0;
+        box-sizing: border-box;
+      }
+
+      /*Items menu*/
+      .user_menu {
+        display: flex;
+        flex-direction: column;
+      }
+
+      /*Menu header info*/
+      .display.name {
+        font-size: 15px;
+        font-weight: 500;
+        color: #303238;
+      }
+
+      .display.mail {
+        font-size: 13px;
+        color: #3d5afe;
+      }
+
+      hr.solid {
+        border-top: 1px solid #e0e0e0;
+        margin: 10px 0px 10px 0px;
+      }
+
+      /*Text Link css*/
+      .user_menu.item > a {
+        display: flex;
+        justify-content: flex-start;
+        align-items: center;
+        padding: 8px 0;
+        font-size: 13px;
+        color: #75777d;
+      }
+
+      .user_menu.item:hover > a {
+        color: #2e323a;
+      }
+
+      /*Icon Button Toggle Menu*/
+      .mob_menu_button {
+      
+       position: absolute;
+       top: 15px;
+       right: 15px;
+       width: 20%;
+       background: #fcfcfc!important;
+       font-weight: 500!important;
+      }
+
+      .icn_button {
+        margin: 0;
+        font-size: 14px;
+      }
+
+      .icn_button:before {
+        margin: 0;
+      }
+
+      .icn_button:after {
+        margin: 0;
+      }
+
+      /*Icon Items Menu*/
+      .icn_menu:before,
+      .icon_menu:after {
+        margin: 0px;
+        padding: 0px;
+        font-size: 16px;
+      }
+
+      .icn_menu {
+        margin-right: 10px;
+        display: flex !important;
+        align-items: center;
+        justify-content: center;
+        width: 22px;
+        height: 22px;
+      }
+
+      /* User Menu For header website */
+      .mts_mob_container {
+        display: flex;
+        position: fixed;
+        z-index: 999;
+        /* height: 100%; */
+        top: 0;
+        left: 0;
+        width: 100%;
+        background: #000000d6;
+      }
+      
+     .mts_sidenav_box {
+        display: block;
+        width: 100%;
+      }
+
+      .mts_sidenav_content {
+        display: none;
+        padding: 20px;
+        background-color: #fff;
+        min-width: 160px;
+        width: 280px;
+        border-radius: 3px;
+        overflow-x: hidden;
+        overflow-y: auto;
+        z-index: 999;
+        position: relative;
+        animation: animateFromLeft 0.4s;
+      }
+
+      @keyframes animateFromLeft {
+        from {
+          left: -500px;
+          opacity: 0;
+        }
+        to {
+          left: 0;
+          opacity: 1;
+        }
+      }
+
+      @keyframes animateToLeft {
+        from {
+          left: 0;
+          opacity: 1;
+        }
+        to {
+          left: -500px;
+          opacity: 0;
+        }
+      }
+
+    .active {
+      display: block !important;
+      height: 100vh;
+      overflow: hidden;
+      width: 75%;
+   }
+
+      .mts_sidenav_content.hide {
+        animation: animateToLeft 0.8s;
+      }
+
<button onclick=""mobile_menu(event)"" class=""mob_menu_button"">Open menu</button>
+
+      <div class=""mts_mob_container"">
+         <div id=""mts_mobile_menu"" class=""mts_sidenav_content""> 
+          <div class=""mts_sidenav_box"">
+          
+            <div class=""user_menu header"">
+              <span class=""display name"">Hello User</span>
+              <span class=""display mail"">mailtest@gmail.com</span>
+            </div>
+
+            <hr class=""solid"" />
+
+            <!--Anyone can see, so there is no need for conditions-->
+            <div class=""user_menu item"">
+              <a href=""/account"">
+                <i class=""icn_menu fa-regular fa-user"">1</i>
+                <span class=""link_text"">Public Link</span>
+              </a>
+            </div>
+            
+            <!--Only who is logged in can see-->
+            <div class=""user_menu item"">
+              <a href=""ordini"">
+                <i class=""icn_menu fa-regular fa-basket-shopping"">2</i>
+                <span class=""link_text"">Private Link</span>
+              </a>
+            </div>
+            
+          </div>
+        </div>
+      </div>
+
+
+

","

(css hacks may hide the menu item, but it will still be available to everyone whether logged in or not).

+

I don't use wordpress, but it's method for checking/returning login status seems to be is_user_logged_in(). See wordpress documentation. You would enclose the section you wish to hide in a conditional with that method.

+

I haven't tested the following, but it would look something like this:

+
<?php if(is_user_logged_in()): ?> 
+ <div class="user_menu item">
+  <a href="ordini">
+   <i class="icn_menu fa-regular fa-basket-shopping">2</i>
+   <span class="link_text">Private Link</span>
+  </a>
+ </div>
+<?php endif; ?>
+
+

There is probably a plugin that would allow you to add php, probably within a <script> tag or something.

",html +"What might reasons be of having a Content Security Policy error when a CSP is not even specified?

My web application is failing to load the static resources from a DigitalOcean Space, by throwing the following error in the browser console:

+
Content Security Policy: The page’s settings blocked the loading of a resource at https://somespace.digitaloceanspaces.com/static/css/mystyle.css (“style-src”).
+
+

I went through some reading regarding CSP, and on this resource I found the following statement:

+
+

This warning message means that due to the existence of a particular CSP directive, a resource wasn't loaded.

+
+

However, I have not provided any particular CSP directive. I am also providing a short snippet on how I am including the CSS file on my HTML document:

+
<head>
+  <meta charset="UTF-8">
+  <meta http-equiv="X-UA-Compatible" content="IE=edge">
+  <link href="https://somespace.digitaloceanspaces.com/static/css/mystyle.css" rel="stylesheet">
+  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+  <meta name="format-detection" content="telephone=no">
+  <meta name="msapplication-TileColor" content="#ffffff">
+</head>
+
+

Might there be another reason why this error is being thrown? What would be a workaround or at least a way to debug this problem?

","

You need to firstly check the response headers you are receiving. The Content-Security-Policy should be defined there. This header contains the configurations. You can learn more about them here: https://content-security-policy.com/

+

Then, you need to determine where this header is being added. In my case, it was being added through an old NGINX configuration.

",html +"how to write good anchors in react.js

I had code in react js but the are problem to write anchor with href . +form example this below code

+
import React from "react";
+
+function Browser() {
+  return (
+    <div>
+      <section className="flex bg-gray-100 py-16 px-4" id="browse-the-room">
+        <div className="container mx-auto">
+          <div className="flex flex-start mb-4">
+            <h3 className="text-2xl capitalize font-semibold">
+              browse the room <br className="" />
+              that we designed for you
+            </h3>
+          </div>
+          <div className="grid grid-rows-2 grid-cols-9 gap-4">
+            <div className="relative col-span-9 row-span-1 md:col-span-4 card" style={{ height: "180px" }}>
+              <div className="card-shadow rounded-xl">
+                <img src="./images/content/image-catalog-1.png" alt="" className="w-full h-full object-cover object-center overlay overflow-hidden rounded-xl" />
+              </div>
+              <div className="overlay left-0 top-0 bottom-0 flex justify-center flex-col pl-48 md:pl-72">
+                <h5 className="text-lg font-semibold">Living Room</h5>
+                <span className="">18.309 items</span>
+              </div>
+              <a href="details.html" className="stretched-link"></a>
+            </div>
+          </div>
+        </div>
+      </section>
+    </div>
+  );
+}
+
+export default Browser;
+
+

but they are warning when I used anchor with href

+
Search for the keywords to learn more about each warning.
+To ignore, add // eslint-disable-next-line to the line before.
+
+WARNING in src\components\Browser.js
+  Line 23:15:  Anchors must-have content and the content must be accessible by a screen reader  jsx-a11y/anchor-has-content
+  Line 33:15:  Anchors must-have content and the content must be accessible by a screen reader  jsx-a11y/anchor-has-content
+  Line 43:15:  Anchors must have content and the content must be accessible by a screen reader  jsx-a11y/anchor-has-content
+  Line 53:15:  Anchors must have content and the content must be accessible by a screen reader  jsx-a11y/anchor-has-content
+
+webpack compiled with 1 warning
+
+

can I solve this problem? +please help me to solve this problem

","

Put content inside the link so people:

+
    +
  • have something to click on
  • +
  • know where the link will take them
  • +
+

<a href="foo">Visit Foo</a>

",html +"Input placeholder text not displaying under responsive mode in WordPress search field

I have the following search code. The text Have a Question? Write here and press enter doesn't appear under responsive mode.

+
 <div class="input-group" id="suggest">
+            <input name="s" id="s" type="text" onKeyUp="suggest(this.value);" onBlur="fill();" class="search-query form-control pull-right" autocomplete="off" placeholder="'.esc_attr__('Have a Question? Write here and press enter','mywiki').'" data-provide="typeahead" data-items="4" data-source="">
+            <div class="suggestionsbox" id="suggestions" style="display: none;"> <img src="'.esc_url(get_template_directory_uri().'/img/arrow1.png').'" height="18" width="27" class="upArrow" alt="upArrow" />
+              <div class="suggestionlist" id="suggestionslist"></div>
+            </div>        
+        </div>
+
+

I suspect it has something to do with id="s" in the input because if I change it to id="sh" the placeholder text appears.

+

So my question is why not id="s" and I prefer to use this cos it seems to be a WordPress default. I hate to fix it here and break something else somewhere.

+

UPDATE: I realized the issue with the original theme that I'm using -> https://fasterthemes.com/demo/mywiki-wordpress-theme/

","

This could be caused by CSS code of, for example, your theme or that the color is the same as the input field background color.

",html +"creating lines between grid boxes using css only

I am trying to achieve something similar to this

+

An interesting Javascript task

+

Ive attempted the answers but the line doesnt seem to be showing up.

+

What i am truly trying to achieve + +There are lines between the grid boxes, horizontally and vertically. +This is what my code looks like +HTML

+
<section class="block-map">
+    <div class="bound-layout">
+        <div class="block_grid">
+            {% for item in items %}
+            
+            <div class="block_item">
+                <p class="need"><span class="bg"><span class="icon">{{ item.description|raw }}</span></span></p>
+            </div>
+            {% endfor %}
+           
+        </div>
+    </div>
+</section>
+
+

CSS

+
.block-map {
+     .block_grid {
+      display: grid;
+      grid-template-columns: auto auto auto;
+      padding: 10px;
+      column-gap: 30px;
+      row-gap: 30px;
+    }
+    .block_item {
+      background-color: #F5F5F5;
+      border-bottom: 5px solid #5B8726;
+      padding: 20px;
+      font-size: 30px;
+      text-align: left;
+      width:338px;
+      height: 149px;
+      align-items: center;
+      display: grid;
+    }
+    p.need {
+        color:@grey;
+        font-size:16px;
+        font-family: @serif;
+        font-weight: 700;
+        
+    }
+    
+    .block_grid .bg::after {
+      
+      letter-spacing: 20px; /* adjust this to control the blue line length */
+      font-size: 25px;
+      border-bottom: 2px solid blue;
+      vertical-align: top;
+    }
+  
+}
+
","

As the lines are sort of visual clues they can be drawn using pseudo before and after elements on each of the grid items.

+

The vertical lines are drawn using before pseudo elements positioned a the top and half way along each grid item. The grid items in the top row have their lines set to display: none.

+

The horizontal lines are drawn using after pseudo elements positioned at the right hand side half way down the item. The items at the end of the rows (ie every 3rd item) have their lines set to display: none.

+

The lines are made dashed by using a repeating background image which is a linear gradient.

+

Here is a simple example. Obviously you will want to change the dimensions to fit your particular requirements.

+

+
+
.grid {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+  --g: 3vw;
+  grid-gap: var(--g);
+}
+
+.grid>* {
+  width: 100%;
+  aspect-ratio: 2 / 1;
+  border: solid 1px gray;
+  background: lightgray;
+  position: relative;
+}
+
+.grid>*::before {
+  content: '';
+  height: var(--g);
+  width: 2px;
+  background-image: linear-gradient(gray 0 50%, transparent 50% 100%);
+  background-size: auto calc(var(--g) / 4);
+  position: absolute;
+  z-index: -1;
+  bottom: 100%;
+  left: 50%;
+}
+
+.grid>*:nth-child(1)::before,
+.grid>*:nth-child(2)::before,
+.grid>*:nth-child(3)::before {
+  display: none;
+}
+
+.grid>*::after {
+  content: '';
+  width: var(--g);
+  height: 2px;
+  background-image: linear-gradient(to right, transparent 0 50%, gray 50% 100%);
+  background-size: calc(var(--g) / 4);
+  position: absolute;
+  z-index: -1;
+  top: 50%;
+  left: 100%;
+}
+
+.grid>*:nth-child(3n)::after,
+.grid>*:last-child::after {
+  display: none;
+  ;
+}
+
<div class=""grid"">
+  <div>1</div>
+  <div>2</div>
+  <div>3</div>
+  <div>4</div>
+  <div>5</div>
+  <div>6</div>
+  <div>7</div>
+</div>
+
+
+

+

This produces this result:

+

",html +"Animate with Jquery through id

I am very new to Jquery. This is also my first time asking a question on here. I am trying to animate this id but I do not know how to apply it with an id. I want my name to move to the left, enlarge, and lessen the opacity right when the code runs, without a button.

+

+
+
$(document).ready(function(){
+  $(name).animate({
+    left: '250px',
+    opacity: '0.5',
+    height: '150px',
+    width: '150px'
+  });
+}); 
+
#name{
+    font-size:40px;
+    font-weight: 700;
+    font-family: Roboto;
+}
+
<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset=""utf-8"">
+        <meta name=""viewport"" content=""width=device-width, initial-scale=1"">
+        <link rel=""stylesheet"" type=""text/css"" href=""style.css"">
+        <link rel=""stylesheet"" href=""https://www.w3schools.com/w3css/4/w3.css"">
+        <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto'>
+        <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"">
+        <script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js""></script>
+        <script src=""resume-animations.js""></script>
+    </head>
+    <body>
+        <div id=""name"">Christy Kim</div>
+    </body>
+</html>
+
+
+

","

Firstly, selectors in jQuery follow CSS rules. Therefore to select the <div id="name"> element you should use $('#name') instead of $(name).

+

To actually have the element move position it needs to be set to position: absolute in CSS.

+

With those updates made, your code works fine:

+

+
+
$(document).ready(function() {
+  $('#name').animate({
+    left: '250px',
+    opacity: 0.5,
+    height: '150px',
+    width: '150px'
+  });
+});
+
#name {
+  font-size: 40px;
+  font-weight: 700;
+  font-family: Roboto;
+  position: absolute;
+}
+
<link rel=""stylesheet"" href=""https://fonts.googleapis.com/css?family=Roboto"" />
+<script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js""></script>
+
+<div id=""name"">Christy Kim</div>
+
+
+

",html +Can you use the 'action' attribute for a 'div' element?

My question is quite straight forward and simple. I am learning node JS and I know that the 'form' element has a 'action' attribute. I just want to know if even a div element has such an attribute...

,"

No, action attribute only works for form tag. +If you want to perform same as action does in form, you can use <a href="https://www.websiteurl.com">Wrap div with this</a>. +If you want to pass dynamic values like form you can provide in herf followed by url/?id=5. +You can also do it by using javascript by providing id to div

+
onClick="location.href='url-here'"
+
",html +"How to change radio button background color while checked

I have simple slideshow with 3 images, I need to make background color of the checked button(obviously, each button refers to one img). I tried literally all possible solutions in the google, I would be really thankful if anyone could help me. Thanks in advance!

+

Here is my slideshow code:

+

+
+
.slider {
+            transform: translateX(20%);
+            display: inline-block;
+            position: relative;
+            width: 61%;
+            overflow: hidden;
+            box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px 0px; 
+        }
+        
+        .images {
+            display: flex;
+            width: 100%;
+        }
+        
+        .images img {
+            width: 100%;
+            transition: all 0.15s ease;  
+        }
+        
+        .images input {
+            display: none; 
+        }
+        
+        .dots {
+            display: flex;
+            justify-content: center;
+            margin: 5px; 
+        }
+        
+        .dots label {
+            height: 15px;
+            width: 15px;
+            border-radius: 50%;
+            border: solid #13447E 3px;
+            cursor: pointer;
+            transition: all 0.15s ease;
+            margin: 5px;
+        } 
+       
+        #img1:checked ~ .m1 {
+            margin-left: 0;   
+        }
+         
+        #img2:checked ~ .m2 {
+            margin-left: -100%;
+        }
+        
+        #img3:checked ~ .m3 {
+            margin-left: -200%;
+        }
+
<div class=""slider"">
+  <div class=""images"">
+      <input type=""radio"" name=""slide"" id=""img1"" checked>
+      <input type=""radio"" name=""slide"" id=""img2"">
+      <input type=""radio"" name=""slide"" id=""img3"">
+
+
+      <img src=""img/img1.jpeg"" class=""m1"" alt=""img1"">
+      <img src=""img/img2.jpeg"" class=""m2"" alt=""img2"">
+      <img src=""img/img3.jpeg"" class=""m3"" alt=""img3"">
+
+  </div>
+  <div class=""dots"">
+      <label for=""img1""></label>
+      <label for=""img2""></label>
+      <label for=""img3""></label>
+
+  </div>
+</div>
+
+
+

","

Try to set radio button before label

+

+
+
.slider {
+        transform: translateX(20%);
+        display: inline-block;
+        position: relative;
+        width: 61%;
+        overflow: hidden;
+        box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px 0px; 
+    }
+    
+    .images {
+        display: flex;
+        width: 100%;
+    }
+    
+    .images img {
+        width: 100%;
+        transition: all 0.15s ease;  
+    }
+    
+    .images input {
+        display: none; 
+    }
+    
+    .dots {
+        display: flex;
+        justify-content: center;
+        margin: 5px; 
+    }
+    
+    .dots label {
+        height: 15px;
+        width: 15px;
+        border-radius: 50%;
+        border: solid #13447E 3px;
+        cursor: pointer;
+        transition: all 0.15s ease;
+        margin: 5px;
+    } 
+   
+    #img1:checked ~ .m1 {
+        margin-left: 0;   
+    }
+     
+    #img2:checked ~ .m2 {
+        margin-left: -100%;
+    }
+    
+    #img3:checked ~ .m3 {
+        margin-left: -200%;
+    }
+    [type=""radio""] {
+    display: none;
+}
+    input[type=""radio""]:checked+label{border-color:red;}
+
<div class=""slider"">
+        <div class=""images"">
+            <img src=""img/img1.jpeg"" class=""m1"" alt=""img1"">
+            <img src=""img/img2.jpeg"" class=""m2"" alt=""img2"">
+            <img src=""img/img3.jpeg"" class=""m3"" alt=""img3"">
+             
+        </div>
+        <div class=""dots"">
+        <input type=""radio"" name=""slide"" id=""img1"" checked>
+            <label for=""img1""></label>
+             <input type=""radio"" name=""slide"" id=""img2"">
+            <label for=""img2""> </label>
+             <input type=""radio"" name=""slide"" id=""img3"">
+            <label for=""img3""></label>
+             
+        </div>
+      </div>  
+
+
+

",html +"Text around the SVG

I'm absolutely beginner with SVG, and I need to put text around this moon... +I tried to make text around a path and could not get the right sizes and match it with the moon.

+

+

+
+
<svg viewBox=""-6 -6 30 40"">
+    <defs>
+        <mask id=""earth"">
+            <rect fill=""white"" x=""-5"" y=""-5"" width=""10"" height=""10""></rect>
+            <circle fill=""black"" cx=""3.141592654"" r=""5"" />
+        </mask>
+    </defs>
+    <circle r=""5"" fill=""currentColor"" mask=""url(#earth)"" transform=""rotate(-25)""/>
+</svg>
+
+
+

","

Draw the moon with a path. (and edit in: https://yqnn.github.io/svg-path-editor/)

+

The path is drawn counter-clockwise, if you want to draw the innermoon text like your design, it is easier to add a 2nd path drawn clockwise.

+

Setting pathLength helps in positioning with startoffset
+Look up all attributes you don't know in the docs.

+

+
+
<svg viewBox=""0 0 80 60"">
+  <rect width=""100%"" height=""100%"" fill=""skyblue""/>
+  <path id=""Moon"" pathLength=""10"" d=""m16 2a12 12 0 1018 13 1 1 0 01-18-13z""/>
+  <text>
+    <textPath href=""#Moon"" 
+              startoffset=""1"" text-anchor=""left"" dominant-baseline=""hanging""
+              fill=""blue"" font-size=""3px"">Outside moon</textPath>
+  </text>
+  <text>
+    <textPath href=""#Moon"" 
+              startoffset=""6"" text-anchor=""right"" dominant-baseline=""hanging""
+              fill=""rebeccapurple"" font-size=""4"">Inside moon</textPath>
+  </text>
+</svg>
+
+
+

",html +"What is the appropriate method to create this icon layout in CSS?

See the photo icons below:

+

+

If I'm just using vanilla HTML/CSS (no frameworks etc.), would the best way to create these overlapping icons be to use flexbox with negative margin-left for each img?

+

Or just use inline-block for each image and give negative margins to each one?

","

Both methods seem to work correctly, there is no rule to it. I personally prefer to use flex.

+

+
+
.user-overlap {
+  display: flex;
+}
+.users-overlap img:not(:first-child) {
+  margin-left: -15px;
+}
+.users-overlap img {
+  height: 50px;
+  width: 50px;
+  border-radius: 50%;
+  border: 4px solid #fff;
+}
+
<div class=""users-overlap"">
+  <img src=""https://picsum.photos/200/300?random=1"" height=""60"" alt="""">
+  <img src=""https://picsum.photos/200/300?random=2"" height=""60"" alt="""">
+  <img src=""https://picsum.photos/200/300?random=3"" height=""60"" alt="""">
+  <img src=""https://picsum.photos/200/300?random=4"" height=""60"" alt="""">
+</div>
+
+
+

",html +"CSS: tags not switching to hover state when HTML table row is highlighted

I'm building a site using a lot of HTML tables, styled with CSS.

+

I implemented an effect whereby hovering a row highlights the entire row:

+
.table {
+    margin-bottom: 1rem;
+    color: #212529;
+    vertical-align: top;
+    border-color: #dee2e6;
+    padding: 0.25rem 0.25rem;
+    font-family: 'Lato';
+    border-collapse: collapse;
+    border-spacing: 0;
+    max-width: 100%;
+  }
+
+.table-bordered tr {
+    border-bottom: 1px solid #ddd;
+}
+
+.table-hoverable tbody tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable div tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable a tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+

My issue is that some text and images do not go in their hover state when row is highlighted, for example:

+

+

You can see that the first column (<h2> tags) and date column do change to white font, but the website and social media columns (<a> tags) do not.

+

Here is one page example Live:

+

https://indexall.io/home-studio/brands/

+

and here the full CSS:

+

https://indexall.io/indeXall.css

+

How can I make it so that <a> tags - text or images - switch to their hover state when the row is highlighted?

+

Reproducible example:

+

+
+
@import url('https://fonts.googleapis.com/css?family=Roboto');
+@import url('https://fonts.googleapis.com/css?family=Lato');
+
+* {
+    margin: 0;
+    padding: 0;
+  }
+
+.header
+{
+    background-color: #000000;
+    margin: 0;
+    padding: 0;
+}
+
+.header a
+{
+    margin-left: 2rem;
+}
+
+.footer
+{
+    background-color: #000000;
+    color: #ffffff;
+    height: 100%;
+    text-align: left;
+    font-family: 'Lato';
+    padding-left: 1rem;
+    padding-bottom: 100%;
+    padding-top: 1rem;
+    margin: 0px;
+}
+
+.body {
+  margin: 0px;
+  padding: 0px;
+  font-family: 'Lato';
+}
+
+
+/* CLICKABLE CELLS */
+
+.clickable_cell
+{
+    font-family: 'Lato';
+    /* width: 100px; */
+    /* background-color: white; */
+    /* height: 100px; */
+}
+.clickable_cell a
+{
+    width: 100%;
+    height: 100%;
+    display: block;
+    color: #ffffff;
+    text-align: left; 
+}
+
+.clickable_cell a:visited {
+    display: inline-block;
+    text-decoration: underline;
+  }
+
+
+/* LINKS */
+
+a:link {
+    color: #000000;
+    display: inline-block;
+    text-decoration: underline;
+  }
+  
+a:visited {
+    color: #da2222;
+    /* text-align: center; */
+    /* text-decoration: none; */
+    display: inline-block;
+    text-decoration: underline;
+  }
+
+
+  a:hover, a:active {
+    color: #ffffff;
+    text-decoration: underline;
+  }
+
+/* LINK TAGS */
+
+.link_tag:link {
+    background-color: white;
+    color: black;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    border: 2px solid #000000;
+    /* line-height: 5em; */
+}
+
+.link_tag:visited {
+    background-color: white;
+    color: black;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    /* line-height: 5em; */
+}
+
+.link_tag:hover, .link_tag:active {
+    background-color: black;
+    color: white;
+    text-decoration: underline;
+    border: 2px solid white;
+}
+
+/* LINK FLAGS */
+
+.link_flag:link {
+    background-color: #ffffff;
+    /* color: white; */
+    padding-top: 0.2em;
+    padding-right: 0.5em;
+    padding-bottom: 0.2em;
+    padding-left: 0.5em;
+    text-align: left;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    border: 2px solid #000000;
+    /* line-height: 5em; */
+}
+
+.link_flag:visited {
+    /* background-color: black;
+    color: #ffffff;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block;
+    text-decoration: none;
+    border-radius: 5px; */
+    /* line-height: 5em; */
+}
+
+.link_flag:hover, .link_flag:active {
+    background-color: black;
+    color: white;
+    /* text-decoration: underline; */
+}
+
+
+/* LINK COUNTRY */
+
+.link_country:link {
+    background-color: #ffffff;
+    /* color: white; */
+    padding-top: 0.2em;
+    /* padding-right: 0.6em; */
+    padding-bottom: 0.2em;
+    /* padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block; */
+    /* text-decoration: none; */
+    border-radius: 4px;
+    border: 1.5px solid #000000;
+    /* line-height: 5em; */
+    font-size: 0.1rem;
+    /* vertical-align: middle; */
+}
+
+.link_country:visited {
+    /* background-color: black;
+    color: #ffffff;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block;
+    text-decoration: none;
+    border-radius: 5px; */
+    /* line-height: 5em; */
+}
+
+.link_country:hover, .link_country:active {
+    background-color: black;
+    color: white;
+    /* text-decoration: underline; */
+}
+
+
+/* ADD button */
+
+.link_add:link {
+    background-color: black;
+    color: white;
+    padding-top: 0.5em;
+    padding-right: 1em;
+    padding-bottom: 0.5em;
+    padding-left: 1em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    font-family: 'Roboto';
+    font-weight: 400;
+    /* line-height: 5em; */
+}
+
+.link_add:visited {
+    background-color: black;
+    color: #ffffff;
+    padding-top: 0.5em;
+    padding-right: 1em;
+    padding-bottom: 0.5em;
+    padding-left: 1em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    font-family: 'Roboto';
+    font-weight: 400;
+}
+
+.link_add:hover, .link_add:active {
+    background-color: black;
+    color: white;
+    text-decoration: underline;
+    font-family: 'Roboto';
+    font-weight: 600;
+}
+
+h6, h5, h4, h3, h2, h1 {
+    margin-top: 0;
+    margin-bottom: 0.5rem;
+    font-weight: 500;
+    line-height: 1.2;
+}
+
+.h1 {
+    font-size: 2.5rem;
+    padding-top: 2rem;
+    padding-left: 1rem;
+    font-family: 'Roboto';
+}
+
+h2 {
+    font-size: 1rem;
+}
+
+h3 {
+    font-size: calc(1.3rem + 0.6vw);
+}
+
+h4 {
+    font-size: calc(1.275rem + 0.3vw);
+}
+
+h5 {
+    font-size: 1.25rem;
+}
+
+h6 {
+    font-size: 1rem;
+}
+
+.table {
+    /* width: 100%; */
+    margin-bottom: 1rem;
+    color: #212529;
+    vertical-align: top;
+    border-color: #dee2e6;
+    padding: 0.25rem 0.25rem;
+    font-family: 'Lato';
+    border-collapse: collapse;
+    border-spacing: 0;
+    /* width:100%; messes up with index page */
+    /* display: table; */
+    max-width: 100%;
+  }
+
+.table-bordered tr {
+    border-bottom: 1px solid #ddd;
+    /* border-collapse: collapse; */
+    /* display: block; */
+}
+.table-striped tbody tr:nth-child(even) {
+    background-color:#f1f1f1;
+}
+
+.table-hoverable tbody tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable div tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable a tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table th {
+    padding-left: 1rem;
+    padding-top: 0.33rem;
+    padding-right: 1rem;
+    padding-bottom: 0.33rem;
+    /* display: table-cell; */
+    text-align: left;
+    vertical-align: top;
+    font-weight: bold;
+    font-size: 1.1rem;
+}
+
+.table td {
+    padding-left: 1rem;
+    padding-top: 0.33rem;
+    padding-right: 1rem;
+    padding-bottom: 0.33rem;
+    /* display: table-cell; */
+    /* display: block; # collapses rows */
+    text-align: left;
+    /* vertical-align: top; */
+}
+
+.nowrap {
+    white-space: nowrap;
+}
+
+ol,
+ul {
+  padding-left: 2rem;
+}
+
+ol ol,
+ul ul,
+ol ul,
+ul ol {
+  margin-bottom: 0;
+}
+
+b,
+strong {
+  font-weight: bolder;
+}
+
+.small {
+  font-size: 0.875em;
+}
+
+.country_div {
+    vertical-align: center;
+  }
+
<table class=""table table-hoverable table-bordered"">
+
+    <tr>
+        <th scope=""col""></th>
+        <th scope=""col"">Website</th>
+        <th scope=""col"">Social</th>
+        <th scope=""col"">Country</th>
+        <th scope=""col"">Est.</th>
+        <th scope=""col"">Products</th>
+    </tr>
+
+    
+    <tr>
+        <td><h2>12 Gauge Microphones</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.12gaugemicrophones.com/"" target=""_blank"" id=""12gaugemicrophones.com"">12gaugemicrophones.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class="""" href=""https://twitter.com/12gaugemics"" target=""_blank"" id=""https://twitter.com/12gaugemics""><img alt=""https://twitter.com/12gaugemics"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/c/12gaugemicrophones"" target=""_blank"" id=""https://www.youtube.com/c/12gaugemicrophones""><img alt=""https://www.youtube.com/c/12gaugemicrophones"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <img src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_light.svg"" alt=""no_instagram_account"" width=""25"" height=""25"" /> <a class="""" href=""https://www.facebook.com/12gaugemicrophones"" target=""_blank"" id=""https://www.facebook.com/12gaugemicrophones""><img alt=""https://www.facebook.com/12gaugemicrophones"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/us"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/us.svg"" alt=""US"" width=""19"" />US</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/us"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/us.svg"" alt=""US"" width=""19"" />US</div></a></td>
+
+        <td>2011</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/audio' target='_self' id='audio'>Audio</a></td>
+    </tr>
+    
+    <tr>
+        <td><h2>Ableton</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.ableton.com"" target=""_blank"" id=""ableton.com"">ableton.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class="""" href=""https://twitter.com/ableton"" target=""_blank"" id=""https://twitter.com/ableton""><img alt=""https://twitter.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/ableton"" target=""_blank"" id=""https://www.youtube.com/ableton""><img alt=""https://www.youtube.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.instagram.com/ableton"" target=""_blank"" id=""https://www.instagram.com/ableton""><img alt=""https://www.instagram.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.facebook.com/ableton"" target=""_blank"" id=""https://www.facebook.com/ableton""><img alt=""https://www.facebook.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td>
+
+        <td>1999</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/software' target='_self' id='software'>Software</a> <a class=""link_tag"" href='https://indexall.io/home-studio/products/controllers' target='_self' id='controllers'>Controllers</a></td>
+    </tr>
+    
+    <tr>
+        <td><h2>Adam Audio</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.adam-audio.com/"" target=""_blank"" id=""adam-audio.com"">adam-audio.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class="""" href=""https://twitter.com/adam_audio"" target=""_blank"" id=""https://twitter.com/adam_audio""><img alt=""https://twitter.com/adam_audio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/user/adamaudiospeakers"" target=""_blank"" id=""https://www.youtube.com/user/adamaudiospeakers""><img alt=""https://www.youtube.com/user/adamaudiospeakers"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.instagram.com/adam_audio"" target=""_blank"" id=""https://www.instagram.com/adam_audio""><img alt=""https://www.instagram.com/adam_audio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.facebook.com/AdamProAudio"" target=""_blank"" id=""https://www.facebook.com/AdamProAudio""><img alt=""https://www.facebook.com/AdamProAudio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td>
+
+        <td>1999</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/audio' target='_self' id='audio'>Audio</a></td>
+    </tr>
+    </table>
+
+
+

","

You need to switch color for your link as well as your social media icon.

+

I added this CSS:

+
/* Change only text of the second td using :nth-child(2) when hovering the line */
+tr:hover td:nth-child(2) a{
+  color:white;
+}
+/* Change only social icon of the third td using :nth-child(3) when hovering the line */
+tr:hover td:nth-child(3) a > img{
+  filter: invert(100%) sepia(0%) saturate(7499%) hue-rotate(230deg) brightness(99%) contrast(103%);
+}
+/* This will target img that are not in <a> tags */
+tr:hover td:nth-child(3) img{
+  filter: invert(73%) sepia(11%) saturate(14%) hue-rotate(329deg) brightness(91%) contrast(88%);
+}
+/* This will change color to twitter logo when you hover it */
+tr:hover td:nth-child(3) a.twitter-logo > img:hover{
+  filter: invert(51%) sepia(25%) saturate(5646%) hue-rotate(180deg) brightness(104%) contrast(90%);
+}
+
+

The image filter is coming from CSS filter generator to convert from black to target hex color

+

DEMO:

+

+
+
@import url('https://fonts.googleapis.com/css?family=Roboto');
+@import url('https://fonts.googleapis.com/css?family=Lato');
+
+* {
+    margin: 0;
+    padding: 0;
+  }
+
+.header
+{
+    background-color: #000000;
+    margin: 0;
+    padding: 0;
+}
+
+.header a
+{
+    margin-left: 2rem;
+}
+
+.footer
+{
+    background-color: #000000;
+    color: #ffffff;
+    height: 100%;
+    text-align: left;
+    font-family: 'Lato';
+    padding-left: 1rem;
+    padding-bottom: 100%;
+    padding-top: 1rem;
+    margin: 0px;
+}
+
+.body {
+  margin: 0px;
+  padding: 0px;
+  font-family: 'Lato';
+}
+
+
+/* CLICKABLE CELLS */
+
+.clickable_cell
+{
+    font-family: 'Lato';
+    /* width: 100px; */
+    /* background-color: white; */
+    /* height: 100px; */
+}
+.clickable_cell a
+{
+    width: 100%;
+    height: 100%;
+    display: block;
+    color: #ffffff;
+    text-align: left; 
+}
+
+.clickable_cell a:visited {
+    display: inline-block;
+    text-decoration: underline;
+  }
+
+
+/* LINKS */
+
+a:link {
+    color: #000000;
+    display: inline-block;
+    text-decoration: underline;
+  }
+  
+a:visited {
+    color: #da2222;
+    /* text-align: center; */
+    /* text-decoration: none; */
+    display: inline-block;
+    text-decoration: underline;
+  }
+
+
+  a:hover, a:active {
+    color: #ffffff;
+    text-decoration: underline;
+  }
+
+/* LINK TAGS */
+
+.link_tag:link {
+    background-color: white;
+    color: black;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    border: 2px solid #000000;
+    /* line-height: 5em; */
+}
+
+.link_tag:visited {
+    background-color: white;
+    color: black;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    /* line-height: 5em; */
+}
+
+.link_tag:hover, .link_tag:active {
+    background-color: black;
+    color: white;
+    text-decoration: underline;
+    border: 2px solid white;
+}
+
+/* LINK FLAGS */
+
+.link_flag:link {
+    background-color: #ffffff;
+    /* color: white; */
+    padding-top: 0.2em;
+    padding-right: 0.5em;
+    padding-bottom: 0.2em;
+    padding-left: 0.5em;
+    text-align: left;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    border: 2px solid #000000;
+    /* line-height: 5em; */
+}
+
+.link_flag:visited {
+    /* background-color: black;
+    color: #ffffff;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block;
+    text-decoration: none;
+    border-radius: 5px; */
+    /* line-height: 5em; */
+}
+
+.link_flag:hover, .link_flag:active {
+    background-color: black;
+    color: white;
+    /* text-decoration: underline; */
+}
+
+tr:hover td:nth-child(2) a{
+  color:white;
+}
+tr:hover td:nth-child(3) a > img{
+  filter: invert(100%) sepia(0%) saturate(7499%) hue-rotate(230deg) brightness(99%) contrast(103%);
+}
+tr:hover td:nth-child(3) img{
+  filter: invert(73%) sepia(11%) saturate(14%) hue-rotate(329deg) brightness(91%) contrast(88%);
+}
+tr:hover td:nth-child(3) a.twitter-logo > img:hover{
+  filter: invert(51%) sepia(25%) saturate(5646%) hue-rotate(180deg) brightness(104%) contrast(90%);
+}
+
+
+/* LINK COUNTRY */
+
+.link_country:link {
+    background-color: #ffffff;
+    /* color: white; */
+    padding-top: 0.2em;
+    /* padding-right: 0.6em; */
+    padding-bottom: 0.2em;
+    /* padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block; */
+    /* text-decoration: none; */
+    border-radius: 4px;
+    border: 1.5px solid #000000;
+    /* line-height: 5em; */
+    font-size: 0.1rem;
+    /* vertical-align: middle; */
+}
+
+.link_country:visited {
+    /* background-color: black;
+    color: #ffffff;
+    padding-top: 0.2em;
+    padding-right: 0.6em;
+    padding-bottom: 0.4em;
+    padding-left: 0.6em; */
+    text-align: left;
+    /* display: inline-block;
+    text-decoration: none;
+    border-radius: 5px; */
+    /* line-height: 5em; */
+}
+
+.link_country:hover, .link_country:active {
+    background-color: black;
+    color: white;
+    /* text-decoration: underline; */
+}
+
+
+/* ADD button */
+
+.link_add:link {
+    background-color: black;
+    color: white;
+    padding-top: 0.5em;
+    padding-right: 1em;
+    padding-bottom: 0.5em;
+    padding-left: 1em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    font-family: 'Roboto';
+    font-weight: 400;
+    /* line-height: 5em; */
+}
+
+.link_add:visited {
+    background-color: black;
+    color: #ffffff;
+    padding-top: 0.5em;
+    padding-right: 1em;
+    padding-bottom: 0.5em;
+    padding-left: 1em;
+    text-align: center;
+    display: inline-block;
+    text-decoration: none;
+    border-radius: 4px;
+    font-family: 'Roboto';
+    font-weight: 400;
+}
+
+.link_add:hover, .link_add:active {
+    background-color: black;
+    color: white;
+    text-decoration: underline;
+    font-family: 'Roboto';
+    font-weight: 600;
+}
+
+h6, h5, h4, h3, h2, h1 {
+    margin-top: 0;
+    margin-bottom: 0.5rem;
+    font-weight: 500;
+    line-height: 1.2;
+}
+
+.h1 {
+    font-size: 2.5rem;
+    padding-top: 2rem;
+    padding-left: 1rem;
+    font-family: 'Roboto';
+}
+
+h2 {
+    font-size: 1rem;
+}
+
+h3 {
+    font-size: calc(1.3rem + 0.6vw);
+}
+
+h4 {
+    font-size: calc(1.275rem + 0.3vw);
+}
+
+h5 {
+    font-size: 1.25rem;
+}
+
+h6 {
+    font-size: 1rem;
+}
+
+.table {
+    /* width: 100%; */
+    margin-bottom: 1rem;
+    color: #212529;
+    vertical-align: top;
+    border-color: #dee2e6;
+    padding: 0.25rem 0.25rem;
+    font-family: 'Lato';
+    border-collapse: collapse;
+    border-spacing: 0;
+    /* width:100%; messes up with index page */
+    /* display: table; */
+    max-width: 100%;
+  }
+
+.table-bordered tr {
+    border-bottom: 1px solid #ddd;
+    /* border-collapse: collapse; */
+    /* display: block; */
+}
+.table-striped tbody tr:nth-child(even) {
+    background-color:#f1f1f1;
+}
+
+.table-hoverable tbody tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable div tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table-hoverable a tr:hover {
+    background-color:#000000;
+    color: #ffffff;
+}
+
+.table th {
+    padding-left: 1rem;
+    padding-top: 0.33rem;
+    padding-right: 1rem;
+    padding-bottom: 0.33rem;
+    /* display: table-cell; */
+    text-align: left;
+    vertical-align: top;
+    font-weight: bold;
+    font-size: 1.1rem;
+}
+
+.table td {
+    padding-left: 1rem;
+    padding-top: 0.33rem;
+    padding-right: 1rem;
+    padding-bottom: 0.33rem;
+    /* display: table-cell; */
+    /* display: block; # collapses rows */
+    text-align: left;
+    /* vertical-align: top; */
+}
+
+.nowrap {
+    white-space: nowrap;
+}
+
+ol,
+ul {
+  padding-left: 2rem;
+}
+
+ol ol,
+ul ul,
+ol ul,
+ul ol {
+  margin-bottom: 0;
+}
+
+b,
+strong {
+  font-weight: bolder;
+}
+
+.small {
+  font-size: 0.875em;
+}
+
+.country_div {
+    vertical-align: center;
+  }
+
<table class=""table table-hoverable table-bordered"">
+
+    <tr>
+        <th scope=""col""></th>
+        <th scope=""col"">Website</th>
+        <th scope=""col"">Social</th>
+        <th scope=""col"">Country</th>
+        <th scope=""col"">Est.</th>
+        <th scope=""col"">Products</th>
+    </tr>
+
+    
+    <tr>
+        <td><h2>12 Gauge Microphones</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.12gaugemicrophones.com/"" target=""_blank"" id=""12gaugemicrophones.com"">12gaugemicrophones.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class=""twitter-logo"" href=""https://twitter.com/12gaugemics"" target=""_blank"" id=""https://twitter.com/12gaugemics""><img alt=""https://twitter.com/12gaugemics"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/c/12gaugemicrophones"" target=""_blank"" id=""https://www.youtube.com/c/12gaugemicrophones""><img alt=""https://www.youtube.com/c/12gaugemicrophones"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <img src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_light.svg"" alt=""no_instagram_account"" width=""25"" height=""25"" /> <a class="""" href=""https://www.facebook.com/12gaugemicrophones"" target=""_blank"" id=""https://www.facebook.com/12gaugemicrophones""><img alt=""https://www.facebook.com/12gaugemicrophones"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/us"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/us.svg"" alt=""US"" width=""19"" />US</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/us"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/us.svg"" alt=""US"" width=""19"" />US</div></a></td>
+
+        <td>2011</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/audio' target='_self' id='audio'>Audio</a></td>
+    </tr>
+    
+    <tr>
+        <td><h2>Ableton</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.ableton.com"" target=""_blank"" id=""ableton.com"">ableton.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class=""twitter-logo"" href=""https://twitter.com/ableton"" target=""_blank"" id=""https://twitter.com/ableton""><img alt=""https://twitter.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/ableton"" target=""_blank"" id=""https://www.youtube.com/ableton""><img alt=""https://www.youtube.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.instagram.com/ableton"" target=""_blank"" id=""https://www.instagram.com/ableton""><img alt=""https://www.instagram.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.facebook.com/ableton"" target=""_blank"" id=""https://www.facebook.com/ableton""><img alt=""https://www.facebook.com/ableton"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td>
+
+        <td>1999</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/software' target='_self' id='software'>Software</a> <a class=""link_tag"" href='https://indexall.io/home-studio/products/controllers' target='_self' id='controllers'>Controllers</a></td>
+    </tr>
+    
+    <tr>
+        <td><h2>Adam Audio</h2></td>
+        
+        <!-- <td class=""clickable_cell nowrap""> -->
+        <td class=""nowrap"">
+            
+            <div>
+                <a href=""https://www.adam-audio.com/"" target=""_blank"" id=""adam-audio.com"">adam-audio.com</a>
+            </div>
+        
+        </td>
+
+        <td class=""nowrap""><a class=""twitter-logo"" href=""https://twitter.com/adam_audio"" target=""_blank"" id=""https://twitter.com/adam_audio""><img alt=""https://twitter.com/adam_audio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_twitter_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.youtube.com/user/adamaudiospeakers"" target=""_blank"" id=""https://www.youtube.com/user/adamaudiospeakers""><img alt=""https://www.youtube.com/user/adamaudiospeakers"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_youtube_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.instagram.com/adam_audio"" target=""_blank"" id=""https://www.instagram.com/adam_audio""><img alt=""https://www.instagram.com/adam_audio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_instagram_black.svg"" width=""25"" height=""25""></a> <a class="""" href=""https://www.facebook.com/AdamProAudio"" target=""_blank"" id=""https://www.facebook.com/AdamProAudio""><img alt=""https://www.facebook.com/AdamProAudio"" src=""https://ik.imagekit.io/vhucnsp9j1u/logos/logo_facebook_black.svg"" width=""25"" height=""25""></a></td>
+
+        <!-- <td class=""clickable_cell nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td> -->
+        <td class=""nowrap""><a class=""link_flag"" href = ""https://indexall.io/home-studio/brands/de"" target = ""_self""><div class=""country_div""><img src=""https://ik.imagekit.io/vhucnsp9j1u/flags/de.svg"" alt=""Germany"" width=""19"" />Germany</div></a></td>
+
+        <td>1999</td>
+        <td><a class=""link_tag"" href='https://indexall.io/home-studio/products/audio' target='_self' id='audio'>Audio</a></td>
+    </tr>
+    </table>
+
+
+

",html +"""If"" shorthand on react component

I have a simple logic for check which menu is active.

+

I'm using:

+
const [activeMenu, setActiveMenu] = useState("0");
+
+

for the state.

+

and using if shorthand:

+
    +
  1. className={activeMenu === "2" && "active"}
  2. +
  3. className={activeMenu === "1" ? "active" : ""}
  4. +
+

but the first one gave me:

+
react_devtools_backend.js:4026 Warning: Received `false` for a non-boolean attribute `className`.
+
+If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}.
+
+

My question is why the first one gave me that warning? but my site is still working like charm. +Why is that say that received false?

","

if activeMenu is not 2, then className would be false (invalid)

+
className={activeMenu === "2" && "active"}
+
+

with this

+
className={activeMenu === "2" ? "active" : ""}
+
+

if activeMenu is not 2, then className would be an empty string (valid)

+

So, it's basically as the error says. className is not a boolean attribute.

+

run the code below in console, it's basically the same thing as your code. It will return false

+
false && "active" !== null
+
",html +"Using Flexbox ""justify-content: space-between"" when number of row items varies

Currently, I'm using Flexbox justify-content: space-between to align items horizontally on collections pages.

+

However, not all collections have enough items to fill a row. In such a situation, I'd like the first two items to be in the same horizontal position as the first two items on a collections page with enough items to fill a row.

+

I could use margins on each item instead of using justify-content: space-between, but I'm hoping there is a way solve this with Flexbox.

+

+
+
.flex-container {
+ display: flex;
+ justify-content: space-between;
+ margin-bottom:10px;
+}
+
+.item {
+  height:20px;
+  width:20px;
+  background:red;
+}
+
// some collections pages have enough items to fill a row like this
+<div class=""flex-container"">
+  <div class=""item""></div>
+  <div class=""item""></div>
+  <div class=""item""></div>
+  <div class=""item""></div>
+</div>
+
+// other collections pages don't have enough items to fill a row and have this situation
+<div class=""flex-container"">
+  <div class=""item""></div>
+  <div class=""item""></div>
+</div>
+
+
+

","

Not possible with flexbox without using some huge work around. +Instead use display grid.

+

+
+
.flex-container {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr)
+}
+
+.item {
+  height:20px;
+  width:20px;
+  background:red;
+}
+
// some collections pages have enough items to fill a row like this
+<div class=""flex-container"">
+  <div class=""item""></div>
+  <div class=""item""></div>
+  <div class=""item""></div>
+  <div class=""item""></div>
+</div>
+
+// other collections pages don't have enough items to fill a row and have this situation
+<div class=""flex-container"">
+  <div class=""item""></div>
+  <div class=""item""></div>
+</div>
+
+
+

",html +"How to stack divs by click on image

Is there any way to make a div appear stacked on top of another one, by clicking on a button/image?

+

The problem I have:
+I want a poster to appear if I click on it in the selector.
I want it to stay, once I click on another poster, which then will stack on top of the previous one.
Is it possible to make this a loop, so no matter how often I click different objects the old divs will always stay below the newest one?

+

(See pictures attached)

+

first click: +

+

second click: +

+

and so on...

+

Thanks in advance!

","

I will cut down the explaination to some documentations such as how to create an element through JS. Teachign every single step would blow the scope of Stackoverflow.

+

If you know how to create an element through JS you need a variable such as counter in my code that is raised by every single time you run the script with: counter = counter + 1

+

You set a z-index through JS with element.style.zIndex = variableand thanks to the rising counter it will set the new element over the other element (z-axis-wise).

+

To rotate the element you can use transform: rotate() which I randomized by calling a variable: rotation = Math.round(Math.random() * 40 - 20); which will randomize a number between -20 and 20.

+

+
+
var preview = document.querySelector('.preview'),
+    counter = '1';
+    picture = ''
+    
+function addRed() {
+  picture = 'red';
+  addPicture();
+}
+
+function addGreen() {
+  picture = 'green';
+  addPicture();
+}
+
+function addBlue() {
+  picture = 'blue';
+  addPicture();
+}
+
+function addYellow() {
+  picture = 'yellow';
+  addPicture();
+}
+
+function addPicture() {
+  var img = document.createElement('img'),
+      rotation = Math.round(Math.random() * 40 - 20);
+  switch (picture) {
+    case 'red':
+      img.src = 'https://via.placeholder.com/350.jpg/FF0000';
+      break;
+    case 'green':
+      img.src = 'https://via.placeholder.com/350.jpg/00FF00';
+      break;
+    case 'blue':
+      img.src = 'https://via.placeholder.com/350.jpg/0000FF';
+      break;
+    case 'yellow':
+      img.src = 'https://via.placeholder.com/350.jpg/FFFF00';
+      break;
+  }
+  img.style.position = 'absolute';
+  img.style.top = '50%';
+  img.style.left = '50%';
+  img.style.transform = 'translate(-50%, -50%) rotate(' + rotation + 'deg)';
+  img.style.zIndex = counter;  
+  preview.appendChild(img);
+  
+  var counter = counter + 1;
+}
+
.container {
+  display: grid;
+  grid-template-columns: repeat(4, 1fr);
+  grid-gap: 10px;
+}
+
+.preview {
+  grid-column: 1 / -1;
+  aspect-ratio: 1 / 1;
+  position: relative;
+}
+
+.selector {
+  padding: 10px;
+}
+
+.selector > img {
+  display: block;
+  object-fit: contain;
+  width: 100%;
+}
+
<div class=""container"">
+  <div class=""preview""></div>
+  <div class=""selector""><img src=""https://via.placeholder.com/100.jpg/FF0000"" onclick=""addRed()""></div>
+  <div class=""selector""><img src=""https://via.placeholder.com/100.jpg/00FF00"" onclick=""addGreen()""></div>
+  <div class=""selector""><img src=""https://via.placeholder.com/100.jpg/0000FF"" onclick=""addBlue()""></div>
+  <div class=""selector""><img src=""https://via.placeholder.com/100.jpg/FFFF00"" onclick=""addYellow()""></div>
+</div>
+
+
+

",html +"Position a button on the right of each row with overflow-x

I want to add a button next to each row of my table. Plot twist, the table is inside a div with a fixed width and overflow-x for responsiveness. I want the button to show next to each row outside the container div.

+

With my current code, the button does show up next to the row but stays in the fixed div.

+

+
+
<div style=""width:100px; overflow-x: scroll;"">
+  <table>
+    <thead>
+      <tr>
+        <th>ID</th><th>ID</th><th>ID</th><th>ID</th><th>ID</th>
+        <th></th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td>
+        <td>
+          <div style=""position:relative; width:0px;"">
+            <button style=""position:absolute;left:10px;"">Edit</button>
+          </div>
+        </td>
+      </tr>
+    </tbody>
+  </table>
+</div>
+
+
+

","

The solution is using position sticky on the last column.

+
position: sticky; right: 0px
+
+

Reference : W3 Schools.

+

Here's the snippet:

+

+
+
<div style=""width:100px; overflow-x: scroll;"">
+  <table>
+    <thead>
+      <tr>
+        <th>ID</th><th>ID</th><th>ID</th><th>ID</th><th>ID</th>
+        <th>Action</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td>
+        <td style=""position: sticky; right: 0px"">
+          <button>Edit</button>
+        </td>
+      </tr>
+    </tbody>
+  </table>
+</div>
+
+
+

",html +"How to send img to discord webhook with javascript

+
+
const params = new URLSearchParams(window.location.search);
+$(document).ready(_ => {
+  if (params.get(""url"") != null) {
+    $(""input"")[0].value = params.get(""url"");
+  }
+  if (params.get(""img"") != null) {
+    $(""input"")[1].value = params.get(""img"");
+  }
+});
+
+let url;
+let img;
+
+let submit = _ => {
+  url = $(""input"")[0].value;
+  img = $(""input"")[1].value;
+
+  if (!url.length) {
+    return alert('Please enter URL');
+  }
+
+}
+
+let send = _ => {
+
+  $.ajax({
+    type: ""POST"",
+    url: url,
+    async: true,
+    data: {
+      file: (img)
+    },
+  });
+}
+
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js""></script>
+<div class=""box"">
+  <p title=""Webhook url to send spam message"">Webhook URL</p><input required name=""inp1"" placeholder=""https://discord.com/api/webhooks/........."" type=""url"" autocomplete></input>
+</div>
+<div class=""box"">
+  <p title=""Message you want to spam it"">Image</p><input required name=""inp2"" placeholder=""Image Link"" type=""file""></input>
+</div>
+
+<a onclick=""submit()""><button id=""button"" >Send</button></a>
+
+
+

+

I want the attachment to be sent through the API in discord chat. I tried doing it like this but it doesn't work. The file:() I think might be the issue but also the input type I don't know

","

Without jQuery you might try something like this using the fetch api in conjunction with the FormData interface and the FileList

+

+
+
const d=document;
+const q=(e,n=d)=>n.querySelector(e);
+
+d.addEventListener('DOMContentLoaded', ()=>{
+  q('button#button').addEventListener('click', e=>{
+    e.preventDefault();
+
+    let url = q('input[name=""inp1""]').value;
+    let files = q('input[name=""inp2""]').files;
+
+    if (!url.length) return alert('Please enter URL');
+
+    let fd = new FormData();
+        fd.set('url', url);
+        fd.set('img', files.item(0));
+
+    fetch( url, { method:'post', body:fd } )
+      .then(r=>r.text())
+      .then(text=>{
+        alert(text)
+      })
+  })
+});
+
<div class=""box"">
+  <p title=""Webhook url to send spam message"">Webhook URL</p>
+  <input required name=""inp1"" placeholder=""https://discord.com/api/webhooks/........."" type=""url"" autocomplete />
+</div>
+
+<div class=""box"">
+  <p title=""Message you want to spam it"">Image</p>
+  <input required name=""inp2"" placeholder=""Image Link"" type=""file"" />
+</div>
+
+<button id=""button"">Send</button>
+
+
+

+

The jQuery version is quite probably not quite correct as the snippet yields an error with the $.post method and being unfamiliar with jQuery I cannot see the mistake

+

+
+
const params = new URLSearchParams( window.location.search );
+$(document).ready(() => {
+  let url;
+  let img;
+  let fd=new FormData();
+
+  if( params.get(""url"") != null ) {
+    $(""input[name='inp1']"")[0].value = params.get(""url"");
+  };
+
+  $('#button').click(e=>{
+    url = $(""input[name='inp1']"")[0].value;
+    img = $(""input[name='inp2']"")[0]; 
+
+
+    if( !url.length ) {
+      return alert('Please enter URL');
+    }
+    
+    fd.set('url',url);
+    fd.set('img',img.files.item(0));
+
+    $.ajax({
+      type:""POST"",
+      url:url,
+      data:fd,
+      success:r=>{console.log(r)},
+      error:e=>{console.warn(e)}
+    });
+  });
+});
+
<script src=""//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js""></script>
+
+<div class=""box"">
+  <p title=""Webhook url to send spam message"">Webhook URL</p>
+  <input required name=""inp1"" placeholder=""https://discord.com/api/webhooks/........."" type=""url"" autocomplete />
+</div>
+
+<div class=""box"">
+  <p title=""Message you want to spam it"">Image</p>
+  <input required name=""inp2"" placeholder=""Image Link"" type=""file"" />
+</div>
+
+<button id=""button"">Send</button>
+
+
+

+

Worth noting perhaps is that you cannot set the value of a file input element programmatically - only the user can set this value by browsing for and selecting a file.

",html +"Is there a way to set word-breaks at suffixes and prefixes?

Is there a way to tell the html or css to word-break a word not by individual letters but rather by suffixes and prefixes?

+

By setting a negative word-spacing: -#px i can acomplish the look of a single word that breaks where I want. The downside is that unless it is a monospace font I have to manually calculate how much word-spacing: I should remove. Also I don't know if that method negatively affects screen readers since it would not read it as a single word but rather as two or more.

","

Assuming you control the HTML output, you can insert soft hyphens (&shy;) in the correct places (after prefixes, before suffixes). Soft hyphens allow a word to break up in the specified place, and will show an otherwise invisible hyphen or dash when it does. There is no way to have a browser do this automatically; you need to specify where to place soft hyphens, either manually or by running the text through some scripting or programming language.

",html +"AMP web development amp-list won't highlight selected option

Please assist me. I am trying to make an AMP dropdown list that opens another list when selected. However, I don't know how to set the css on the outer list button to look active(selected). I don't know how to dynamically add the css to the button on the outer list.

+

It looks like this:

+

Image of list

+

and the code I have is this:

+

+
+
<!doctype html>
+<html ⚡ lang=""en"">
+
+<head>
+  <meta charset=""utf-8"">
+  <title>amp-list</title>
+  <script async src=""https://cdn.ampproject.org/v0.js""></script>
+  <!-- ## Setup -->
+  <!-- Import the `amp-list` component ... -->
+  <script async custom-element=""amp-list"" src=""https://cdn.ampproject.org/v0/amp-list-0.1.js""></script>
+  <!-- ... and the `amp-mustache` component in the header. -->
+  <script async custom-template=""amp-mustache"" src=""https://cdn.ampproject.org/v0/amp-mustache-0.2.js""></script>
+  <!-- Import the `amp-bind` component for dynamically changing the content of an `amp-list`. -->
+  <script async custom-element=""amp-bind"" src=""https://cdn.ampproject.org/v0/amp-bind-0.1.js""></script>
+  <link rel=""canonical"" href=""https://amp.dev/documentation/examples/components/amp-list/index.html"">
+  <meta name=""viewport"" content=""width=device-width"">
+  <style amp-custom>
+    * {
+      font-family: Verdana, Geneva, Tahoma, sans-serif;
+      text-decoration: none;
+      color: #00438e;
+      hyphens: auto;
+    }
+
+    div {
+      color: #000;
+      font-size: 15px;
+      line-height: 1.6;
+    }
+
+    .title {
+      font-size: 14px;
+      font-weight: 700;
+    }
+
+    .mb10 {
+      margin-bottom: 10px;
+    }
+
+    .p_widget {
+      margin: 20px 0;
+    }
+
+    .mt0 {
+      margin-top: 0;
+    }
+
+    .widget_tabs {
+      width: 310px;
+      border: 2px solid #e8f2fc;
+      border-radius: 5px;
+    }
+
+    .tabs {
+      background: #e8f2fc;
+      border-radius: 5px 5px 0 0;
+    }
+
+    .tab {
+      color: hsl(212, 100%, 28%);
+      padding: 10px;
+      border-bottom: 1px solid #fff;
+      cursor: pointer;
+      font-weight: 700;
+      font-size: 12px;
+    }
+
+    .tab_active {
+      background: #2578bb;
+      padding: 5px;
+      color: #fff;
+      text-shadow: 1px 1px 0 #000;
+      border: 1px solid #fff;
+      border-radius: 5px;
+      box-shadow: 1px 1px 5px rgba(0, 0, 0, .6);
+      font-weight: 700;
+      font-size: 12px;
+    }
+
+    .tab_active::before {
+      content: '\25BE ';
+    }
+
+    .active {
+      background: #2578bb;
+      color: #fff;
+      text-shadow: 1px 1px 0 #000;
+      border: 1px solid #fff;
+      border-radius: 5px;
+      box-shadow: 1px 1px 5px rgba(0, 0, 0, .6);
+    }
+
+    .tab_contents {
+      padding: 5px;
+    }
+
+   .tab::before {
+      content: '\25B8 ';
+    }
+
+    .favicon {
+      position: absolute;
+      top: 2px;
+      left: 0;
+    }
+
+    .shop {
+      display: block;
+      padding: 3px 5px;
+      border-bottom: 1px solid #ddd;
+      width: 290px;
+      position: relative;
+      top: 0;
+      left: 0;
+      font-size: 13px;
+    }
+
+    .price {
+      width: 90px;
+      padding: 0;
+      text-align: right;
+      position: absolute;
+      top: 3px;
+      left: auto;
+      right: 5px;
+      font-size: 13px;
+      line-height: 18px;
+      font-weight: 700;
+    }
+
+    .price::before {
+      content: """";
+    }
+
+    .table {
+      display: table;
+    }
+
+    .cell {
+      display: table-cell;
+      vertical-align: top;
+    }
+
+    .amazon_bar {
+      display: inline-block;
+      position: relative;
+      height: 25px;
+      background: url(//i.wfcdn.de/5/amazon_bar_sprite_2.png) 0 -50px repeat-x;
+      margin: 3px 0 0;
+      padding: 0 5px 0 25px;
+      font-size: 13px;
+      width: 270px;
+    }
+
+    .amazon_bar em {
+      display: block;
+      width: 25px;
+      left: 0;
+      background: url(//i.wfcdn.de/5/amazon_bar_sprite_2.png) no-repeat;
+    }
+
+    a {
+      padding: 0 5px 0 25px;
+    }
+
+    a:last-child {
+      display: inline-block;
+      height: 25px;
+      position: relative;
+      background: url(//i.wfcdn.de/5/amazon_bar_sprite_2.png) 0 -50px repeat-x;
+      padding: 0 5px 0 25px;
+      font-size: 13px;
+      width: 270px;
+    }
+
+    a :last-child.favicon {
+      display: block;
+      width: 25px;
+      left: 0;
+      background: url(//i.wfcdn.de/5/amazon_bar_sprite_2.png) no-repeat;
+      }
+
+    .info {
+      margin-top: 3px;
+      color: #999;
+      font-size: 10px;
+    }
+  </style>
+  <style amp-boilerplate>
+    body {
+      -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
+      -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
+      -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
+      animation: -amp-start 8s steps(1, end) 0s 1 normal both
+    }
+
+    @-webkit-keyframes -amp-start {
+      from {
+        visibility: hidden
+      }
+
+      to {
+        visibility: visible
+      }
+    }
+
+    @-moz-keyframes -amp-start {
+      from {
+        visibility: hidden
+      }
+
+      to {
+        visibility: visible
+      }
+    }
+
+    @-ms-keyframes -amp-start {
+      from {
+        visibility: hidden
+      }
+
+      to {
+        visibility: visible
+      }
+    }
+
+    @-o-keyframes -amp-start {
+      from {
+        visibility: hidden
+      }
+
+      to {
+        visibility: visible
+      }
+    }
+
+    @keyframes -amp-start {
+      from {
+        visibility: hidden
+      }
+
+      to {
+        visibility: visible
+      }
+    }
+  </style>
+  <noscript>
+    <style amp-boilerplate>
+      body {
+        -webkit-animation: none;
+        -moz-animation: none;
+        -ms-animation: none;
+        animation: none
+      }
+    </style>
+  </noscript>
+</head>
+<body>
+  <div class=""p_widget nointelliTXT"">
+    <amp-state id=""items"" src=""https://winfuture-amp.s3.eu-west-2.amazonaws.com/products.json""></amp-state>
+    <div class=""title"">Beliebte Smartwatches im Preisvergleich:</div>
+    <div class=""p_widget mt0 nointelliTXT"">
+      <div class=""widget_tabs"">
+        <div class=""tabs"">
+          <amp-list layout=""fixed-height"" height=""145"" src=""https://winfuture-amp.s3.eu-west-2.amazonaws.com/products.json"" [is-layout-container]=""true"" binding=""no"">
+            <template type=""amp-mustache"">
+              <div [class]=""active ? 'tab_active' : ''"" class=""tab"">
+                <span role=""button"" tabindex=""0"" on=""onclick:AMP.setState({name:'{{productName}}'}),onclick:AMP.setState({active:1})"">{{productName}}</span>
+              </div>
+            </template>
+          </amp-list>
+        </div>
+
+        <div class=""tab_contents"">
+          <amp-list layout=""fixed-height"" height=""85"" src=""https://winfuture-amp.s3.eu-west-2.amazonaws.com/first_ptoduct.json"" [src]=""items.items.filter(product => product.productName == name)"" [is-layout-container]=""true""
+                  binding=""no"">
+            <template type=""amp-mustache"">
+              <div class=""table"">
+                <div class=""cell"">
+                  {{#productStore}}
+                    <a href=""{{website}}"" target=""_blank"" rel=""nofollow noopener"" class=""shop"">
+                      <span>
+                        <amp-img class=""favicon"" width=""16"" height=""16"" src=""{{icon}}"" alt=""icon""></amp-img>
+                        {{websiteName}}
+                      </span>
+                      <span class=""price"">{{price}} €</span>
+                    </a>
+                  {{/productStore}}
+                  {{^productStore}}
+                  {{/productStore}}
+                </div>
+              </div>
+            </template>
+          </amp-list>
+          <div class=""info"">Preise vom 04.06.22 12:34 Uhr, können jetzt anders sein.</div>
+        </div>
+      </div>
+    </div>
+  </div>
+</body>
+</html>
+
+
+

","

Solved my own question, was quite simple actually. I just needed to do some reading on css.

+

I used pseudo-class :focus. Simple to :hover and :active you can apply css on certain events that happen as the user interacts with your interface.

+

Applying ":focus" solved my problem:

+

+
+
.tab:focus {
+  background: #2578bb;
+  width: 310px;
+  padding: 10px;
+  margin-bottom: 2px;
+  color: #fff;
+  text-shadow: 1px 1px 0 #000;
+  text-align: left;
+  border: 1px solid #fff;
+  border-radius: 5px;
+  box-shadow: 1px 1px 5px rgba(0, 0, 0, .6);
+  font-weight: 700;
+  font-size: 12px;
+}
+
+
+

",html +"How to change position for prev and next btn on Boostrap5 carousel?

I'm struggling to set the correct position for prev/next btns in a bootstrap5 carousel. The initial code I used as model was for a carousel that displays 4 images at once, I changed to 3 images at once. I added also some space between images.
+I know that prev/next btns have position:absolute, I changed to position:relative and tried to position it by changing margins but it was worse.
+Is there a solution on how to fix this problem?
+The buttons look like this now: buttons

+
<div class="container text-center my-3 mb-5 carousel2">
+                    <div class="row mx-5 my-5 justify-content-between align-items-center">
+                        <div id="Carousel-2" class="carousel slide" data-bs-ride="carousel">
+                            <div class="carousel-inner" role="listbox">
+                                <div class="carousel-item active">
+                                    <div class="col-md-4">
+                                        <div class="card">
+                                            <div class="card-img">
+                                                <img src="./images/woman1.jpg" class="img-fluid">
+                                            </div>
+                                            <div class="card-img-bottom"><strong>Jane Dow</strong>
+                                                <p class="mt-0 me-2" style="font-size: 13px;">CEO - AXA Group</p>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="carousel-item">
+                                    <div class="col-md-4">
+                                        <div class="card">
+                                            <div class="card-img">
+                                                <img src="./images/man1.jpg" class="img-fluid">
+                                            </div>
+                                            <div class="card-img-bottom"><strong>Dave Johnson</strong>
+                                                <p class="mt-0 me-2" style="font-size: 13px;">Marketing Manager - Johnson's & Co</p>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="carousel-item">
+                                    <div class="col-md-4">
+                                        <div class="card">
+                                            <div class="card-img">
+                                                <img src="./images/man2.jpg" class="img-fluid">
+                                            </div>
+                                            <div class="card-img-bottom"><strong>Roger Smith</strong>
+                                                <p class="mt-0 me-2" style="font-size: 13px;">CEO - Hi-Tech Intl.</p>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="carousel-item">
+                                    <div class="col-md-4">
+                                        <div class="card">
+                                            <div class="card-img">
+                                                <img src="./images/woman2.jpg" class="img-fluid">
+                                            </div>
+                                            <div class="card-img-bottom"><strong>Diana Russel</strong>
+                                                <p class="mt-0 me-2" style="font-size: 13px;">Manager - Creativity Hub</p>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </div>
+                            </div>
+                            <a class="carousel-control-prev bg-transparent w-aut" href="#Carousel-2" role="button" data-bs-slide="prev">
+                                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
+                            </a>
+                            <a class="carousel-control-next bg-transparent w-aut" href="#Carousel-2" role="button" data-bs-slide="next">
+                                <span class="carousel-control-next-icon" aria-hidden="true"></span>
+                            </a>
+                        </div>
+                    </div>
+                </div>
+
","

if you want to make them stable in fixed positions use this code +give your carousel position relative as a parent for your prev and next buttons.

+

the top and transform make your buttons stay in the middle of your container.

+
     .carousel {
+        position: relative;
+     }           
+     .carousel-control-prev , .carousel-control-next {
+        position: absolute;
+        top: 50%;
+        transform: TranslateY(-50%);
+     }
+     .carousel-control-prev {
+        right: auto;
+        left: 20px;
+     }
+     .carousel-control-next {
+        left: auto;
+        right: 20px;
+     }
+
",html +"javascript function not working (TableFilter library)

I'm trying to make a table in my web app filterable. The TableFilter library seems to be really good but I'm not able to make it work (only in the web app since it works with a simple html page).

+

this is the code of my page:

+
<html>
+<head>
+    <title>Show Elements In Table Page</title>
+
+    <script src="~/tableFilter/tablefilter.js"></script>
+    <script src="~/tableFilter/tablefilter_all.js"></script>
+    <script src="~/tableFilter/tablefilter_all_min.js"></script>
+    <script src="~/tableFilter/tablefilter_min.js"></script>
+</head>
+<body id="pageBody" onload="createTable(getLocalItem('selectedTable'), 'elementsTable');
+    hideElement('loading'); 
+    document.getElementById('tableName').innerHTML = getLocalItem('selectedTable');
+    prova();">
+
+    <h3 id="loading">loading...</h3>
+    <div style="margin-left: 1em; margin-top: 1em;">
+        <h3 id="tableName"></h3>
+        <table align="left" border="1" cellpadding="5" cellspacing="0" id="elementsTable">
+            <!--the table loads with the createTable() function-->
+        </table>
+    </div>
+
+    <script language="javascript" type="text/javascript">
+        setFilterGrid("elementsTable");
+        <!--this is not working-->
+    </script>
+</body>
+</html>
+
+

this is the createTable() js function:

+
function createTable(tableName, tableId) {
+    fetch(domain + urlParameters + tableName)
+        .then(r => r.text())
+        .then(j => JSON.parse(j))
+        .then(o => {
+
+            var cols = getVarNames(o);
+
+            //header
+            var tableHtml = "<thead><tr>";
+            for (var i = 0; i < cols.length; i++) {
+                tableHtml += "<th>" + cols[i] + "</th>";
+            }
+            tableHtml += "</tr></thead>";
+            //body
+            tableHtml += "<tbody><tr>";
+            for (var i = 0; i < o.length; i++) {
+                for (var j = 0; j < cols.length; j++) {
+                    tableHtml += "<td>" + o[i][cols[j]] + "</td>";
+                }
+                tableHtml += "</tr>";
+            }
+            tableHtml += "</tbody>";
+
+            //insertion in document
+            document.getElementById(tableId).innerHTML = tableHtml;
+        });
+}
+
+function getVarNames(list) {
+    var columns = [];
+
+    for (var i = 0; i < list.length; i++) {
+        var row = list[i];
+
+        for (var k in row) {
+            if ($.inArray(k, columns) == -1) {
+                columns.push(k);
+            }
+        }
+    }
+    return columns;
+}
+
+

the table is loaded but it is not filterable. the script in the body seems to not recognize the table. how could i solve?

","

i solved creating my own query methods in javascript. maybe this could be helpful for someone.

+
var tableObject; //variable storing the json object form the api
+
+    function createTable(tableName, tableId) {
+    fetch(domain + urlParameters + tableName)
+        .then(r => r.text())
+        .then(j => JSON.parse(j))
+        .then(o => {
+
+            tableObject = o;
+            //insert filtering variables
+
+            var cols = getVarNames(tableObject);
+
+            //header
+            var tableHtml = "<thead><tr>";
+            for (var i = 0; i < cols.length; i++) {
+                tableHtml += "<th>" + cols[i] + "</th>";
+            }
+
+            //insert selection and filtering tools
+            tableHtml += "<tr>";
+            for (var i = 0; i < cols.length; i++) {
+                tableHtml += "<td><textarea class=\"filter\" rows=\"1\" placeholder=\"input\" style=\"resize: none;\"></textarea></td>";
+                //add some kind of tag matching the column -> maybe a class? or an id?
+            }
+            tableHtml += "</tr>";
+            tableHtml += "</tr></thead>";
+
+            //body
+            tableHtml += "<tbody id=\"tableBody\"><tr>";
+            for (var i = 0; i < tableObject.length; i++) {
+                if (objectIncludesFilters(tableObject[i], cols, getValuesFilters())) {
+                    for (var j = 0; j < cols.length; j++) {
+                        tableHtml += "<td>" + tableObject[i][cols[j]] + "</td>";
+                    }
+                    tableHtml += "</tr>";
+                }
+            }
+            tableHtml += "</tbody>";
+
+            //insertion in document
+            document.getElementById(tableId).innerHTML = tableHtml;
+        });
+}
+
+function getVarNames(list) {
+    var columns = [];
+
+    for (var i = 0; i < list.length; i++) {
+        var row = list[i];
+
+        for (var k in row) {
+            if ($.inArray(k, columns) == -1) {
+                columns.push(k);
+            }
+        }
+    }
+    return columns;
+}
+
+function getValuesFilters() {
+    const collection = document.getElementsByClassName("filter");
+    var values = [];
+    for (var i = 0; i < collection.length; i++) {
+        var value = collection[i].value;
+        values.push(value);
+        if (value == null) {
+            values.push("");
+        }
+    }
+    return values;
+}
+
+function objectIncludesFilters(obj, cols, filters) {
+    var result = true;
+    for (var i = 0; i < filters.length; i++) {
+        if (!obj[cols[i]].toLowerCase().includes(filters[i].toLowerCase())) {
+            result = false;
+        }
+    }
+    return result;
+}
+
",html +"Trouble with edit button for To Do App JavaScript

I tried creating an edit button for editing a created task, and it works for the very first task that i create.

+
    +
  1. However for subsequent tasks, the edit button for the respective tasks focus on editing the input on my first task again.

    +
  2. +
  3. For every new task created, it changes the first task back to the very first original task that was written.

    + + + + + + To-Do List + + + + +
     <div class="container">
    +     <div class="row mb-5">
    +         <div class="col h1 text-white text-start text-center text-md-start text-lg-start">TO-DO APP</div>
    +     </div>
    +
    +     <div class="row">
    +         <div class="h6 text-white text-start text-center text-md-start text-lg-start">CREATE A TO-DO</div>
    +     </div>
    +
    +     <form id="todo-form">
    +         <div class="row mb-4">
    +             <div class="col">
    +                 <input class="form-control" name="newTask" type="text" placeholder="eg. Do the laundry"> 
    +             </div>     
    +         </div>
    +
    +         <div class="row">
    +             <div class="h6 text-white text-start text-center text-md-start text-lg-start">CATEGORY</div>
    +         </div>
    +
    +         <div class="row mb-3">
    +             <div class="col-6">
    +                 <input type="radio" class="btn-check" name="category" id="option1" value="Work">
    +                 <label class="col-12 btn btn-outline-danger p-4 text-white work-task" for="option1">Work</label>
    +             </div>
    +             <div class="col-6">
    +                 <input type="radio" class="btn-check" name="category" id="option2" value="Personal">
    +                 <label class="col-12 btn btn-outline-primary p-4 text-white personal-task" for="option2">Personal</label>
    +             </div>
    +         </div>
    +
    +         <div class="row mb-4">
    +             <div class="col"><button type="submit" class="btn btn-secondary p-2 w-100 add-task" active>ADD TO-DO</button></div>
    +         </div>
    +     </form>
    +
    +     <div class="row mb-2">
    +         <div class="h6 text-white text-start text-center text-md-start text-lg-start">TO-DO LIST</div>
    +     </div>
    +
    +     <div class="todoList">
    +
    +     </div>
    + </div>
    + <script src="main.js"></script>
    +
    + + +
  4. +
+

Javascript

+
const todoForm = document.getElementById("todo-form")
+
+window.addEventListener("load", () => {
+    todos = JSON.parse(localStorage.getItem("todos")) || []
+
+    todoForm.addEventListener("submit", (e) => {
+        e.preventDefault()
+        if (e.target.elements.newTask.value != "") {
+            const todo = {
+                task: e.target.elements.newTask.value,
+                category: e.target.elements.category.value
+            }
+    
+            todos.push(todo);
+    
+            localStorage.setItem("todos", JSON.stringify(todos));
+    
+            e.target.reset()
+    
+            showList()
+        }
+    })
+    
+    showList();
+})
+
+function showList() {
+    let outPut = '';
+    let taskListShow = document.querySelector(".todoList")
+    const taskName = document.querySelector(".todoContent")
+
+    todos.forEach((data, index)=> {
+
+        outPut += `
+        <div class="row todoList mb-3">
+            <div class="col-10 col-lg-8 col-md-7 col-sm-6">
+                <input class="todoContent no-border text-white text-center" value="${data.task}" readonly>
+            </div>
+            <div class="col">
+                <div class="row action">
+                    <div class="col-6">
+                        <button type="button" class="btn btn-secondary col-12" onClick="editItem()">Edit</button>
+                    </div>
+                    <div class="col-6">
+                        <button type="button" class="btn btn-danger col-12" onClick="deleteItem(${index})">Delete</button>
+                    </div>       
+                </div>
+            </div>
+        </div>`
+    });
+    taskListShow.innerHTML = outPut;
+}
+
+function deleteItem(index) {
+    todos.splice(index, 1)
+    localStorage.setItem("todos", JSON.stringify(todos))
+    showList()
+}
+
+function editItem() {
+    const taskName = document.querySelector(".todoContent")
+    taskName.removeAttribute('readonly')
+    taskName.focus()
+    taskName.addEventListener("blur", (e) => {
+        taskName.setAttribute('readonly', true)
+        taskName = e.target.value
+        localStorage.setItem('todos', JSON.stringify(todos))
+        showList()
+    })
+}
+
+

How can make this work?

","

Since all of the input class will have todoContent and when you look for a class using querySelector then JS will return you the first matching element with class todoContent.

+
const taskName = document.querySelector(".todoContent")
+
+

CODESANDBOX LINK

+

What you can do is look for all of the element with class todoContent and then take the particular input on which you have clicked by using the index of the clicked edit button as:

+
function editItem ( index ) {  // RECEVIVE INDEX
+const taskAllName = document.querySelectorAll( ".todoContent" );
+const taskName = taskAllName[index];  // USE SPECIFC ELEMENT
+
+

So you have to pass the index to function editItem as:

+
onClick="editItem(${index})">Edit</button>
+
",html +"HTML , CSS how to fix paragraph inside box only

hello i am new in HTML and CSS now i have a problem with paragraph text it is overlapping i don't know how to solve this. +here is the picture

+

+

here is the code i wrote.

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Document</title>
+</head>
+<body>
+<style>
+    .box{
+        padding: 10px;
+        width: 500px;
+        height: 200px;
+        border:1px solid red;
+    }
+</style>
+    <div class="box">
+        hello hello hello hello hello hello hello hello hello hello hello hello hello hello hellohello hello hello hello hello hello
+        hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello
+    </div>
+</body>
+</html>
+
","

Use word-break: break-word;

+

Here is a link to learn more

+

+
+
.box {
+     padding: 10px;
+     width: 500px;
+     height: 200px;
+     border:1px solid red;
+     word-break: break-word;
+ }
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <meta http-equiv=""X-UA-Compatible"" content=""ie=edge"">
+    <title>Document</title>
+</head>
+<body>
+    <div class=""box"">
+        hello hello hello hello hello hello hello hello hello hello hello hello hello hello hellohello hello hello hello hello hello
+        hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello
+    </div>
+</body>
+</html>
+
+
+

",html +"FastAPI Request body returns 'null' from 'checkbox' HTML Tag

Checkbox returns 'null' value

+

I'm having an issue with FastAPI request body return 'null' value from a checkbox when the checkbox isn't checked but on the otherhand when it's checked it returns True.

+
+

Error after POST request

+
+

{"detail":[{"loc":["body","is_active"],"msg":"field required","type":"value_error.missing"}]}

+
+
+

Main class

+
@app.post("/job/create")
+async def job_create(request: Request, response: Response, job: JobSchema = Depends(JobSchema.as_form), db: Session = Depends(get_db)):
+    job_ = models.Job(name=job.name, description=job.description, is_active=job.is_active)
+    db.add(job_)
+    db.commit()
+    db.refresh(job_)
+    url = f"/job/{job_.id}"
+    response = RedirectResponse(url=url)
+    return response
+
+
+

Schema class

+
class JobSchema(BaseModel):
+    name: str
+    description: str
+    is_active: bool = False
+
+    @classmethod
+    def as_form(cls, name: str = Form(...), description: str = Form(...), is_active: bool = Form(...)):
+        return cls(name=name, description=description, is_active=is_active)
+
+
+
+

Checkbox code

+
<div class="form-group">
+    <label for="is_active">Is Active</label>
+    <input type="checkbox" class="form-control" id="is_active" name="is_active"/>
+</div>
+
+

+

How would i get only True/False returns from the checkbox or is my only option to do some kind of validation on the checkbox?

","

HTML checkbox elements will not send a value to your sever when the element is unchecked (see MDN docs). But your validation is requiring an is_active field be sent. So the error occurs when the checkbox is unchecked. Also, you have not provided a value attribute of the checkbox element in your HTML, so the default value would be is_active=on.

+

You could change your as_form() method to accept an optional is_active field, and then convert it to True if it is present and equal to on.

+
class JobSchema(BaseModel):
+    name: str
+    description: str
+    is_active: bool = False
+
+    @classmethod
+    def as_form(
+        cls,
+        name: str = Form(...),
+        description: str = Form(...),
+        is_active: Union[str, None] = Form(None)
+    ):
+        is_active_bool = True if is_active == "on" else False
+        return cls(name=name, description=description, is_active=is_active_bool)
+
",html +"Printing a HTML + JavaScript variable from an external js to an index.html file using fetch + node.js

I was under the impression I could use node.js to do this but you cannot b/c of reasons given by the answer. Essentially I just wanted to use fetch and that's all you really need. Here is a very basic way of using it.

+

+async function fetch_weather() {
+    const response = await fetch('https://api.openweathermap.org/data/2.5/weather?zip=90210,us&appid={API-KEY}&units=imperial');
+    const weather = await response.json();
+    document.querySelector("#weather").innerHTML =
+
+<table>
+<caption>Current weather data using <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch" target="_blank"><code>fetch</code></a></caption>
+<br>
+
+<thead>
+  <tr>
+    <th>City/State</th>
+    <th>Current Temp</th>
+    <th>Feels Like:</th>
+    <th>Longitude:</th>
+    <th>Latitude:</th>
+    <th>Sunrise (Unix)</th>
+    <th>Sunset (Unix)</th>
+  </tr>
+</thead>
+<tbody>
+  <tr>
+    <td>${weather.name}, GA</td>
+    <td>${weather.main.temp}</td>
+    <td>${weather.main.feels_like}</td>
+    <td>${weather.coord.lon}</td>
+    <td>${weather.coord.lat}</td>
+    <td>${weather.sys.sunrise}</td>
+    <td>${weather.sys.sunset}</td>
+  </tr>
+
+</tbody>
+</table>
+
+};
+
+
+
+
+

Here was the non-working node.js code:

+

index.js

+
import fetch from './node-fetch';
+
+async function fetchWeatherJSON() {
+    const response = await fetch('https://api.openweathermap.org/data/.../&appid={API-KEY}');
+    const weather = await response.json();
+    return weather;
+}
+
+fetchWeatherJSON().then(weather => {
+document.querySelector("#weather").innerHTML = `Longitude: ${weather.coord.lon}`
+    console.log(`Longitude: ${weather.coord.lon}`);
+    console.log(`Latitude: ${weather.coord.lat}`);
+    console.log(`Current Temp: ${weather.main.temp}`);
+    console.log(`Feels Like: ${weather.main.feels_like}`);
+    console.log(`Sunrise: ${weather.sys.sunrise}`);
+    console.log(`Sunset: ${weather.sys.sunset}`);
+    console.log(`City/State: ${weather.name}, GA`);
+});
+
+
+

Inside fetchWeatherJSON().then(...) part I tried things like

+
document.querySelector("#weather").innerHTML = `Longitude: ${weather.coord.lon}`;
+
+

but none of those types of ways worked. I have no idea if there is just something I am doing wrong here as far as selectors or this isn't the best way (or any way) to do it.

+

I'd like to print this to an index.html page, here is a simple example of some HTML. It would be nice to be able to print whatever is shown the javascript console inside the opening an close <p> elements.

+

index.html

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Node.js Weather App</title>
+</head>
+<body>
+    <h2>Node.js Weather App</h2>
+    <div id="weather"></div>
+
+    <script type="text/javascript" src="index.js"></script>
+</body>
+</html>
+
","

This code cannot work. Not on node.js nor on the browser because:

+
    +
  1. Node.js has no fetch built in, so you need an extra library for it. For this you use node-fetch. But in the same .js file you try to access DOM elements with document.. Dom elements does not exist in Node.js, only inside the browser.

    +
  2. +
  3. This code wont work, because usually you have an bundler like Vite or webpack that bundles your npm packages. Anyway, node-fetch is only made for Node.js, not for the browser.

    +
  4. +
+

The browser already has an built-in fetch.

",html +"CSS - Align diagonal line inside concentric circles

I am stuck on how to align this diagonal line inside the inner circle. I have tried using position: absolute and display: flex and other methods, but cannot seem to get something that works.

+

+

jsFiddle: https://jsfiddle.net/Kaevonz/7edw8yuq/20/

+

+
+
.container {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: start;
+  height: 500px;
+  border: 1px solid gray;
+}
+
+.elem {
+  box-sizing: border-box;
+}
+
+.div1 {
+  border-top: 3px solid #0DA8AA;
+  border-left: 1px solid #0DA8AA;
+  border-right: 1px solid #0DA8AA;
+  height: 70px;
+  width: 70px;
+  background: white;
+}
+
+.div2 {
+  border: 1px solid blue;
+  border-radius: 50%;
+  width: 200px;
+  height: 200px;
+  background: white;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.div3 {
+  border: 1px solid green;
+  border-radius: 50%;
+  width: 180px;
+  height: 180px;
+  background: white;
+}
+
+.div4 {
+  border-top: 1px dashed #f00;
+  width: 50%;
+  transform: rotate(-45deg);
+  transform-origin: top middle;
+}
+
<div class=""container"">
+  <div class=""elem div1""></div>
+  <div class=""elem div2"">
+    <div class=""elem div3"">
+      <div class=""elem div4"">
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

","

You can center the line using flexbox on div3

+
  display: flex;
+  align-items: center;
+  justify-content: center;
+
+

Then adjust the transform of the line as required.

+

I'm assuming from the design this is supposed to be an clock of some kind and this a "second hand".

+

+
+
.container {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: flex-start;
+  height: 500px;
+  border: 1px solid gray;
+}
+
+.elem {
+  box-sizing: border-box;
+}
+
+.div1 {
+  border-top: 3px solid #0DA8AA;
+  border-left: 1px solid #0DA8AA;
+  border-right: 1px solid #0DA8AA;
+  height: 70px;
+  width: 70px;
+  background: white;
+}
+
+.div2 {
+  border: 1px solid blue;
+  border-radius: 50%;
+  width: 200px;
+  height: 200px;
+  background: white;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.div3 {
+  border: 1px solid green;
+  border-radius: 50%;
+  width: 180px;
+  height: 180px;
+  background: white;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.div4 {
+  border-top: 1px dashed #f00;
+  width: 50%;
+  transform: translateX(-50%) rotate(90deg);
+  transform-origin: right;
+  animation: spin 5s linear infinite;
+}
+
+@keyframes spin {
+  0% {
+    transform: translateX(-50%) rotate(90deg);
+  }
+  100% {
+    transform: translateX(-50%) rotate(450deg);
+  }
+}
+
<div class=""container"">
+  <div class=""elem div1""></div>
+  <div class=""elem div2"">
+    <div class=""elem div3"">
+      <div class=""elem div4"">
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"Creating or question in bootstrap form for better user experience

I am building a user form that using form-group and row. I wanted to see what options you guys are using when you want the user to understand that this is an or? The two questions are not require but they just need to under one of the question

+
<div class="form-group row">
+  <label for="enteredLink">Enter Link</label>
+  <input class="form-control" data-val="true" id="txtLink" name="enteredLink" type="text" value="">
+</div>
+
+<div class="form-group row">
+  <label for="enteredFile">Upload File</label>
+  <input class="form-control" id="txtFile" name="enteredFile" type="text" value="">
+</div>
+
","

This may seem a bit simplistic, but have you considered a simple bit of text saying 'or'

+

+
+
<div class=""container"">
+<div class=""form-group row"">
+  <label for=""enteredLink"">Enter Link</label>
+  <input class=""form-control"" data-val=""true"" id=""txtLink"" name=""enteredLink"" type=""text"" value="""">
+</div>
+<div class=""row""><p>or</p></div>
+<div class=""form-group row"">
+  <label for=""enteredFile"">Upload File</label>
+  <input class=""form-control"" id=""txtFile"" name=""enteredFile"" type=""file"" value="""">
+</div>
+</div>
+
+
+<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"" integrity=""sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"" crossorigin=""anonymous"">
+
+
+

+

It's not quite the same, but this is what the Gov.UK Design system does for radio button groups that are mutually exclusive - https://design-system.service.gov.uk/components/radios/#radio-items-with-a-text-divider

+

Edit - To highlight alternative used by SO

+

When posting this question I realised StackOverflow themselves do something similar to what you want. They essentially use an all in one box with clear calls to action to either drag and drop, browse or paste a link in

+

+

Clicking 'paste' sticks the text box on screen for users to paste their link in

+

+

It'll slightly depend on who your audience is and how tech savvy they are, and also what people mostly will do as to what option is best.

",html +"Add square beside text form

I want to place a square beside Yes and beside No text as:

+

+

I try:

+

+
+
.yesNoSquare {
+  width: 10px;
+  height: 10px;
+  border: 1px solid;
+}
+
<div>
+  <span class=""yesNoSquare"" /> YES
+  <span class=""yesNoSquare"" /> NO
+</div>
+
+
+

+

But it is adding the label inside square, how can I do my expected result?

","

Try this. Hope it helps.

+

+
+
.yesNoSquare {
+  width: 10px;
+  height: 10px;
+  border: 1px solid;
+  display: inline-block;
+}
+
    <div>
+      <span class=""yesNoSquare""></span>
+      <span> YES</span>
+      <span class=""yesNoSquare""></span>
+      <span> NO</span>
+    </div>
+
+
+

",html +"I can't seem to get these two buttons line up buttons like this. How can I do this?

Design:

+

+

Explanation: +So I used a div and added CSS (display: inline-block;) and width to it, they were perfectly fine, when I added a tag into it to actually make the buttons do something they went on top of each other, I have tried wrapping them tag in another div but can't seem to make it work.

+

Here is how they look right now:

+

+

HTML:

+
export default function About() {
+    return (
+
+        <div className="About--div">
+
+            <h3 className="About--name">Huzaifa Aziz</h3>
+            <h5 className="About--job">Frontend Developer</h5>
+            <a className="About--site"></a>
+            <div className="About--btn">
+                <div>
+                <form action="mailto:huzaifaaziz90@gmail.com">
+                    <button className="Email--btn" ><i className='fa fa-envelope'></i> Email</button>
+                </form>
+                <div className="About--btn--space"></div>
+                <form action="https://www.linkedin.com/in/huzaifah-aziz-63092996/">
+                    <button className="Linkedin--btn"><i className='fa fa-linkedin'></i> Linkedin</button>
+                </form>
+                 </div>
+                 </div>
+        </div>
+    )}
+
+

CSS:

+
* {
+    box-sizing: border-box;
+   
+}
+body{
+    border-radius: 20px;
+    background: #23252C;
+    margin: auto;
+    width: 100%;
+    border: 3px solid #1A1B21;
+    padding: 10px;
+    font-family: 'Inter', sans-serif;
+}
+
+.About--div{
+    text-align:center
+    
+    }
+
+.About--name{
+    color: white;
+} 
+   
+.About--job{
+    color: #F3BF99;
+
+}
+
+.About--site{
+    color: #F5F5F5;
+
+}
+.About--btn{
+    margin-top: 15px;
+}
+.About--btn--space{
+    width: 17px;
+    display: inline-block;
+}
+
+.Email--btn{
+    background: whitesmoke;
+    border: none;
+    width: 115px;
+    height: 34px;
+    border-radius: 5px;
+          
+}
+
+.Linkedin--btn{
+    background: #5093E2;
+    border: none;
+    width: 115px;
+    height: 34px;
+    color: white;
+    border-radius: 5px;
+    
+    
+}
+
+.fa fa-linkedin{
+   
+}
+
","

Using flexbox, all you would need to do is add the following to the parent element of the buttons:

+
display: flex;
+align-items: center;
+
+

Add a classname to that div just above your opening form tag and apply to that one. Other guys are right about the form tag being redundant but shouldn't be an issue.

",html +"How to change html element after text has been edited

I have this code that should change the contents of a table position when you change the contents of nameDiv which is var nameDiv = document.createElement('div'); (nameDiv.contentEditable = "true";) and it has some text

+
 nameDiv.onclick = event => {
+            allSectionsArray[sectionNumber][2] = event.value;
+ }
+
+

What happens here is basically: it updates the second I click on the div and not after some text is entered.

+

What I want is: to save changes after entering the text. Is there any substitute of onclick or any other method that I can achieve this?

","

For contenteditable, you can use the input event:

+
+

The input event fires when the value of an input element has been changed.

+
+

The change event isn't supported for contenteditable, but you can use the blur event instead which

+
+

fires when an element has lost focus

+
+

+
+
const example = document.querySelector(""#example"");
+
+example.addEventListener(""blur"", ()=>{
+  console.log(`Value is: ${example.textContent}`);
+});
+
#example {
+  border: solid 1px #000;
+  padding: 5px;
+}
+
<div id=""example"" contenteditable></div>
+
+
+

+
+

You can also browse the full list of events here.

",html +"How to Echo delete link into php?

I need to delete a row but I can't do it. Tell me please, how can this be done?

+
$id=0;
+while ($row=$res->fetch_assoc())
+{
+$id++;
+echo "<tr>";
+echo "<td>{$id}</td>";
+echo "<td>{$row["BTITLE"]}</td>";
+echo "<td>{$row["KEYWORDS"]}</td>";
+echo "<td><a href='{$row["FILE"]}' 
+target='_blank'>View</a></td>";
+echo "<td><a href='view_books.php?id={$id}'>Delete</a></td>";
+echo "</tr>";
+}
+
+

I added

+
<?php
+    session_start();
+    include "database.php";
+    if(!isset($_SESSION["AID"]))
+    {
+        $id=$_GET['id'];
+        $delete=mysqli_query($conn, "DELETE FROM `book` WHERE `BID`='$id'");
+        header("location:alogin.php");
+        die();
+    }
+?>
+
+

Where is my mistake?

","

Create a file delete.php that accept as parameter an id to delete. Then delete the row from table that corresponds to that id. I assume you can do it, if not, take some hints from file $row["FILE"].

+

Now your loop should look like:

+
while ($row=$res->fetch_assoc())
+{
+  $i++;
+  echo "<tr>";
+  echo "<td>{$i}</td>";
+  echo "<td>{$row["BTITLE"]}</td>";
+  echo "<td>{$row["KEYWORDS"]}</td>";
+  echo "<td><a href='{$row["FILE"]}' target='_blank'>View</a></td>";
+  echo "<td><a href='delete.php?id={$i}'>Delete</a></td>";
+  // OR, better if you know what it means:
+  echo "<td><a href='delete.php?id={$row["id"]}'>Delete</a></td>";
+  echo "</tr>";
+}
+
",html +"How to generate HTML text with a for loop?

I have a list of expenses, I want to create a html code to iterate over all the expenses and show their name. I am not working with the DOM, I literally want to save the html code in a variable, so I can generate a pdf file with it.

+

This is what I tried: +lets say I have this array

+
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
+
+    const testHtml = () => {
+         for(let i of spents) {
+            const title = `<h1>${i.expenseName}</h1>`
+          }
+        }
+        testHtml()
+
+

This is the result I want, something like:

+
+

htmlResult = "<h1>${i.expenseName}</h1> <h1>${i.expenseName}</h1>"

+
+

by the way, This is for a react native app.

","

I think this will work for you.

+
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
+
+const testHtml = () => {
+   let title = '';
+   for(let i of spents) {
+       title += `<h1>${i.expenseName}</h1>`
+   }
+   return title;
+}
+testHtml()
+
",html +"I can no longer get the links to work in my webpage

Firstly I apologise as I have only limited experience of HTML, CSS and Bootstrap so this may be something really simple that I have overlooked.

+

I created a website for a friend that has mailto links on a button. They were working but now they don't. Can't figure what I have done that stops it from working.

+

The code is:

+
<ol class="align-content-center btn btn-lg btn-secondary button2 mt-3" href="mailto:hello@wandering.yoga?subject=Website%20booking%20Online-Zoom">Book Here</ol>
+
+

The mailto link works by itself in isolation but clicking on the "Book now " button does nothing.

+

The page is here Yoga Website

","

href work only on <a> tag.

+

So try that :

+
<a href="mailto:hello@wandering.yoga?subject=Website%20booking%20Online-Zoom">
+    <ol class="align-content-center btn btn-lg btn-secondary button2 mt-3">Book Here</ol>
+</a>
+
",html +"How to Make a Page Inaccessible With a Button

I've been trying to figure out how to make a menu button that functions similarly to that of YouTube, where once clicked the rest of the page is darker and inaccessible until the button is clicked once more and the menu retracts. If anyone could help with this, I would greatly appreciate it. (and if possible, still retaining most or all of my original code). :)

+

+
+
menuBtn = document.getElementsByClassName('menuButton')[0];
+menuBtn.addEventListener('click', function() {
+  menu = document.getElementsByClassName('linkList')[0];
+  menu.style.webkitTransition = '0.6s';
+  if (menu.style.right == '0px') {
+    menu.style.right = '-150px';
+  } else {
+    menu.style.right = '0px';
+  }
+});
+
/* headerBar */
+
+.headerBar {
+  position: absolute;
+  width: 100%;
+  height: 80px;
+  top: 0px;
+  left: 0px;
+  background-color: #b0b0b0;
+}
+
+
+/* headerStrip */
+
+.headerStrip {
+  position: absolute;
+  width: 100%;
+  height: 5px;
+  top: 80px;
+  left: 0px;
+  background-color: #5e00bc
+}
+
+
+/* bodyBar */
+
+.bodyBar {
+  position: absolute;
+  width: 100%;
+  height: 100%;
+  top: 85px;
+  left: 0px;
+  background-color: #000000
+}
+
+
+/* jobLinks styles */
+
+.jobLinks {
+  text-decoration: none;
+  list-style: none;
+}
+
+.find {
+  position: absolute;
+  width: 80px;
+  height: 40px;
+  top: 30px;
+  left: 300px;
+  font-family: 'comfortaa';
+  font-size: 18px;
+  font-weight: 800;
+  color: #000000;
+  text-decoration: none;
+  text-align: center;
+  transition: ease-out 0.4s;
+  background-color: #e0e0e0;
+}
+
+.find:hover {
+  color: #5e00bc;
+}
+
+
+/* menu styles */
+
+.menuButton {
+  position: absolute;
+  width: 30px;
+  height: 30px;
+  top: 25px;
+  left: 1303px;
+  border: none;
+  outline: none;
+  transition: ease-out 0.5s;
+  background-image: url('/Images/Menu_Icon.png');
+  background-color: #e0e0e0;
+  cursor: pointer;
+}
+
+.links {
+  font-family: 'comfortaa';
+  font-size: 18px;
+  font-weight: 500;
+  color: #000000;
+  text-decoration: none;
+  transition: ease-out 0.4s;
+}
+
+.links:hover {
+  color: #5e00bc;
+}
+
+.linkList {
+  position: fixed;
+  width: 150px;
+  height: 100%;
+  right: -150px;
+  top: 85px;
+  transition: ease-out 0.5s;
+  background: #e0e0e0;
+}
+
+.linkList ul li {
+  list-style: none;
+  padding: 15px;
+}
+
+.menuButton:focus~.linkList {
+  right: 0px;
+}
+
<div class='headerBar'>
+</div>
+
+<div class='headerStrip'>
+</div>
+
+<div class='bodyBar'>
+</div>
+
+<div class='jobLinks'>
+  <li><a class='find' href='#'>Find</a></li>
+</div>
+
+<div class='menu'>
+  <button class='menuButton'></button>
+  <div class='linkList'>
+    <ul>
+      <li><a class='links' href='#'>Link 1</a></li>
+      <li><a class='links' href='#'>Link 2</a></li>
+      <li><a class='links' href='#'>Link 3</a></li>
+      <li><a class='links' href='#'>Link 4</a></li>
+      <li><a class='links' href='#'>Link 5</a></li>
+      <li><a class='links' href='#'>Link 6</a></li>
+      <li><a class='links' href='#'>Link 7</a></li>
+    </ul>
+  </div>
+</div>
+
+
+

","

Sorry OP, I know you asked for minimal change to your markup but what you were doing just seemed so backwards to me (also your snippet wasn't working for me??) -- take a look at the script in my snippet, I've set this up using click delegation on the body. This will detect every click anywhere on the page, but will only toggle the class if an element with id="toggle" is clicked.

+

As for the other parts, I had to add an overlay div which acts as the backdrop to the link list, this will cover the content. The overlay and the link list has z-index: 999 to make sure it will be above any absolute/relative/fixed position elements (so long as it has a z-index of less than 999). It doesn't cover the menu as this is where the button is to hide the overlay again, although clicking on the overlay will also hide it

+

I've also used display: grid a lot as this is much easier for the browser to calculate before painting than all the absolute positioned elements you had before

+

+
+
const main = document.getElementById('main');
+
+document.addEventListener('click', function(e) {
+  e.target.id === 'toggle' && main.classList.toggle('active');
+  e.target.id === 'overlay' && main.classList.toggle('active');
+},false );
+
* { box-sizing: border-box } body { margin: 0 }
+
+main {
+  display: grid;
+  grid-template-rows: 85px 1fr;
+
+  height: 100vh;
+  
+  overflow: hidden
+}
+
+header {
+  grid-area: 1/1/2/2;
+  
+  display: grid;
+
+  background-color: #b0b0b0;
+  border-bottom: 5px solid #5e00bc
+}
+
+#find, #toggle {
+  grid-area: 1/1/-1/-1;
+  margin: auto;
+  
+  padding: 0.5em 1em;
+
+  background-color: #e0e0e0;
+  border: 0;
+  border-radius: 0.375em;
+  cursor: pointer;
+  font-family: 'Comfortaa', cursive;
+  font-size: 18px;
+  font-weight: 800;
+  line-height: 1;
+
+  user-select: none; -moz-user-select: none; -webkit-user-select: none;
+
+  transition: color 400ms 0ms ease-in-out
+}
+#find:hover, #toggle:hover { color: #5e00bc }
+#toggle {
+  background-image: url(""data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512' height='18' width='18'%3E%3Cpath fill='currentColor' d='M0 96C0 78.33 14.33 64 32 64H416C433.7 64 448 78.33 448 96C448 113.7 433.7 128 416 128H32C14.33 128 0 113.7 0 96zM0 256C0 238.3 14.33 224 32 224H416C433.7 224 448 238.3 448 256C448 273.7 433.7 288 416 288H32C14.33 288 0 273.7 0 256zM416 448H32C14.33 448 0 433.7 0 416C0 398.3 14.33 384 32 384H416C433.7 384 448 398.3 448 416C448 433.7 433.7 448 416 448z'/%3E%3C/svg%3E"");
+  background-position: center;
+  background-repeat: no-repeat;
+  margin-right: 1em
+}
+
+
+section {
+  grid-area: 2/1/3/2;
+  
+  background-color: black;
+  color: white;
+  font-family: 'comfortaa';
+  overflow: scroll;
+  padding: 1.5em
+}
+
+#overlay, #linkList {
+  grid-area: 2/1/3/2;
+  z-index: 999;
+
+  transform: translateY( 100vh );
+  
+  transition: transform 600ms 0ms ease-in-out
+}
+
+#overlay {  
+  background: #5e00bc;
+  opacity: 0.825
+}
+#linkList {
+  display: flex;
+  flex-direction: column;
+  margin: auto;
+  max-height: 100%;
+  overflow: scroll;
+  padding: 0 1em
+}
+#linkList a {
+  background-color: rgba(0, 0, 0, 0.5 );
+  border-radius: 0.375em;
+  color: white;
+  font-family: 'comfortaa';
+  font-size: 18px;
+  font-weight: 700;
+  margin-bottom: 0.25em;
+  padding: 0.5em;
+  text-decoration: none;
+  
+  transition: background-color 400ms 0ms ease-in-out, color 400ms 0ms ease-in-out, transform 400ms 0ms ease-in-out
+}
+#linkList a:hover {
+  color: #5e00bc;
+  background-color: white;
+  transform: scale(1.075)
+}
+
+#linkList a:first-child { margin-top: 1em }
+#linkList a:last-child { margin-bottom: 1em }
+
+#main.active #overlay,
+#main.active #linkList {
+  transform: translateY( 0 );
+}
+
<link href=""https://fonts.googleapis.com/css2?family=Comfortaa:wght@400;500;600;700&display=swap"" rel=""stylesheet"">
+
+<main id=""main"">
+  <header>
+    <button id=""find"">Find</button>
+    <button id=""toggle"">&nbsp;</button>
+  </header>
+  <section>
+    <p>Nunc a porta a lacus a vitae a vulputate a a a class scelerisque sociosqu parturient habitant a quam platea nec a purus sem accumsan dui mauris dis. A pharetra mi porta parturient ultrices ac nisi ad aliquet taciti ullamcorper consequat ullamcorper conubia rhoncus magnis a condimentum risus in at suspendisse cum himenaeos non per ante.</p>
+  </section>
+  <div id=""overlay""></div>
+  <div id='linkList'>
+    <a href='#'>This is Link 1</a>
+    <a href='#'>This is Link 2</a>
+    <a href='#'>This is Link 3</a>
+    <a href='#'>This is Link 4</a>
+    <a href='#'>This is Link 5</a>
+    <a href='#'>This is Link 6</a>
+    <a href='#'>This is Link 7</a>
+  </div>
+</main>
+
+
+

",html +"Problem with responsivity of card in grid layout of css

[https://codepen.io/TA0011/pen/VwXKKgG]

+

When viewed in mobile version, the width of the card exceeds the Content hr (horizontal line). What can be done so that it does not exceed the horizontal line? Do not go with the 5 fr or 1fr unit. I can manage the 1 fr or 5fr scene. But only problem is with the card that exceeds the hr line which is blue in color.

+

+
+
.container-a {
+  margin-top: 10px;
+  width: calc(100% - 100px);
+  margin: 10px auto;
+  position: relative;
+}
+
+.container-a span {
+  background-color: #007bff;
+  padding: 5px 10px;
+  position: relative;
+  color: #fff;
+  z-index: -1;
+  background-blend-mode: multiply;
+}
+
+.container-a hr {
+  width: 100%;
+  color: #007bff;
+  margin-top: 4px;
+  height: 1px;
+  position: relative;
+  z-index: -2;
+}
+
+.container-a .wrapper {
+  display: grid;
+  height: 100%;
+  grid-template-columns: repeat(5, 1fr);
+  grid-template-areas: ""blog-container blog-container blog-container blog-container blog-sidebar"";
+  grid-gap: 10px;
+}
+
+.container-a .blog-container {
+  grid-area: blog-container;
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
+  grid-gap: 10px;
+}
+
+.card {
+  min-width: 280px;
+  flex: 1;
+  -webkit-box-flex: 1;
+  -ms-flex: 1;
+  height: 180px;
+  width: 100%;
+  border: 1px solid #ccc;
+  background: #FF7F50;
+  font-weight: 500 !important;
+  position: relative;
+  color: #fff;
+}
+
+.container-a .blog-sidebar {
+  grid-area: blog-sidebar;
+}
+
+.blog-sidebar .widgets {
+  background: #fff;
+  border: 1px solid #ccc;
+  margin-bottom: 10px;
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
+  grid-gap: 10px;
+  padding: 5px;
+}
+
+.widgets img {
+  width: 100%;
+  float: none;
+  display: block;
+  object-fit: fill;
+}
+
+.blog-sidebar h3 {
+  color: #007bff;
+  text-align: center;
+  margin-top: 2px 0 2px 0;
+  margin: -1px 0 -1px 0;
+}
+
+@media(max-width: 768px) {
+  .container-a {
+    width: calc(100% - 60px);
+  }
+  .container-a span {
+    font-size: 12px;
+  }
+  .container-a hr {
+    margin-top: 3px;
+  }
+  .container-a {
+    width: calc(100% - 60px);
+    margin-bottom: 100px;
+  }
+  .container-a .wrapper {
+    grid-template-rows: auto;
+    grid-template-columns: 1fr;
+    grid-template-areas: ""blog-container"" ""blog-sidebar"";
+  }
+  .card {
+    min-width: 244px;
+  }
+}
+
<section class=""container-a"" aria-label=""blog-content"">
+  <span>Content</span>
+  
+  <hr>
+  
+  <div class=""wrapper"">
+    <div class=""blog-container"">
+      <div class=""card"">Card 1</div>
+      <div class=""card"">Card 2</div>
+      <div class=""card"">Card 3</div>
+      <div class=""card"">Card 4</div>
+      <div class=""card"">Card 5</div>
+    </div>
+    
+    <div class=""blog-sidebar"">
+      <h3>Sidebar</h3>
+      
+      <div class=""widgets"">
+        <div class=""card"">Card 1</div>
+        <div class=""card"">Card 2</div>
+      </div>
+    </div>
+  </div>
+</section>
+
+
+

","

[I have done it , you can view it][1]

+
  [1]: https://codepen.io/TA0011/pen/ZExJgmr
+
",html +"How do I add a class to a div in HTML using jQuery?

I want to use jQuery to add a class named container-c-ml to my HTML code. I have the following code below:

+
<div id="container">
+<button>This is a button</button>
+</div>
+
+

I have my HTML doc linked to a JavaScript file and I have jQuery added via the <head> tag of my doc. What should I do?

","

You can use the following jQuery code:

+
$(document).ready(function() {
+  $("#container").addClass("container-c-ml");
+});
+
+

Good luck with further learning to code!

",html +"Using Handlebars.js to iterate over a list of names

I have a Bootstrap select dropdown, and I'm attempting to use Handlebars JS to output the desired options into my selection, but they aren't appearing. I've read some examples here so not sure what is stopping my code from correctly rendering, any pointers would be appreciated.

+

HTML:

+
  <select class="custom-select" id="inputGroupSelect01" onChange="takeSelectedSourceValue(this);">
+  <option id="source-language" value="" selected disabled>Auto</option>
+  
+  <div id="myForm"></div>
+  <script type="text/handlebar-template" id="selectPersonTemplate">
+  {{#each people}}
+    <option value="{{valueLang}}">{{htmlLang}}</option>
+  {{/each}}
+  </select>
+  </script>
+
+ <script src="https://twitter.github.io/typeahead.js/js/handlebars.js"></script>
+
+

JS:

+
$(function () {
+    // Define an array of people.
+  var people = [
+    { valueLang: 'DE', htmlLang: 'DE' },
+    { valueLang: 'FR', htmlLang: 'FR' },
+    { valueLang: 'IT', htmlLang: 'IT' },
+    { valueLang: 'ES', htmlLang: 'ES' },
+    { valueLang: 'SV', htmlLang: 'SV' },
+    { valueLang: 'DA', htmlLang: 'DA' }
+  ];
+  
+  // Get the text for the Handlebars template from the script element.
+  var templateText = $("#selectPersonTemplate").html();
+  
+  // Compile the Handlebars template.
+  var selectPersonTemplate = Handlebars.compile(templateText);
+  
+  // Evaluate the template with an array of people.
+  var html = selectPersonTemplate({ people: people });
+  
+  // Take the HTML that was created with the Handlebars template and
+  // set the HTML in the myForm div element.
+  $("#myForm").html(html);
+});
+
","

There are a few things wrong with your HTML.

+

First, your closing select tag, </select> is within your template script tag.

+

What is within your script tag is ignored by the HTML parser because you have defined the script as type="text/handlebar-template". Therefore, the parser does not see a closing select tag.

+

Second, <div> elements are not valid children of select, <select>, elements.

+

I am not sure if all browsers handle this invalid tag the same way, but I am trying it using Chrome and it seems that Chrome is completely ignoring the <div id="myForm"></div> when rendering. So there is no element to which to add the html produced by your template function. The html value should be appended to the <select>.

+

I would advise taking the template <script> tag out from within the <select>, just for clarity. This will make the HTML easier to read and clearly separate the <select> menu from the template.

+
<select class="custom-select" id="inputGroupSelect01" onChange="takeSelectedSourceValue(this);">
+  <option id="source-language" value="" selected disabled>Auto</option>
+</select>
+  
+<script type="text/handlebar-template" id="selectPersonTemplate">
+  {{#each people}}
+    <option value="{{valueLang}}">{{htmlLang}}</option>
+  {{/each}}
+</script>
+
+

Next, we want to be sure to append html to our #inputGroupSelect01 element.

+
// append the HTML to the #inputGroupSelect01 select element.
+$("#inputGroupSelect01").append(html);
+
+

I have created a fiddle for your reference.

",html +"| character is not allowed for attribute href on element link

I have a link element in .html file:

+
<link href="https://fonts.googleapis.com/css?family=Lora|Merriweather:300,400" rel="stylesheet">
+
+

When I throw it in https://validator.w3.org/, it displays this error:

+
+

Bad value https://fonts.googleapis.com/css?family=Lora|Merriweather:300,400 for attribute href on element link: Illegal character in query: | is not allowed.

+
+

How can I fix that?

","

To display non-standard letters and characters in browsers and plug-ins you need to use hexadecimal values. In your case instead of | you need to use %7C.

+
 <link href="https://fonts.googleapis.com/cssfamily=Lora%7CMerriweather:300,400" rel="stylesheet">
+
+

You can check more here

",html +"How to make an image fit its content

[Tree with all its leaves off the brancges[1] +[1]: https://i.stack.imgur.com/hfQGM.png

+

Im trying to make the image fit to the bottom left and top of the inside border, but not the right i just want it to fit in that certain space.

+

This is what i have so far...

+
  <section class="winter">
+  <div class="outside-border">
+    <div class="section-heading">
+      <h2>Winter</h2>
+    </div>
+    <div class="inside-border">
+      <div class="winter-image">
+        <a href="winter.html">
+          <img src="assets/images/winter.jpg" alt="Winter Image">
+        </a>
+      </div>
+      <div class="section-content">
+        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit dolore enim sequi dignissimos vel fugit
+          reiciendis minus voluptatem nostrum, at repellat odio libero cum eveniet officiis, cumque veritatis, qui
+          eaque.</p>
+      </div>
+    </div>
+  </div>
+
+

css

+
.outside-border{
+  border: 2px solid var(--winter-primary);
+  margin: auto;
+  max-width: 1000px;
+  background-color: white;
+  padding: 20px;
+  margin-bottom: 20px;
+}
+
+.section-heading{
+  width: 100%;
+  background-color: var(--winter-primary);
+  text-align: center;
+}
+
+.section-heading>h2 {
+  margin: 0;
+}
+
+.inside-border{
+border: 2px solid var(--winter-primary);
+display: flex;
+align-items: center;
+background-color: var(--winter-light);
+
+}
+
+.section-content{
+  background-color: var(--winter-light);
+}
+
+
+
+.winter-image{
+display: inline-flex;
+background-size: cover;
+
+
+}
+
+p{
+  margin-left: 1em;
+  text-align: center; 
+  padding: 10px;
+
+
+
+}
+
+

Now im just saying the same thing over and over again because im a stupid newbe coder that is having trouble with this problem. Stack overflow says i need to add more words because all i have is code right now.

","

try to put margin and padding 0. +hope this helps

+

+
+
.winter-image{
+display: inline-flex;
+background-size: cover;
+margin: 0;
+padding: 0;
+}
+
+
+

",html +"Javascript dynamically inserted later on: how to make it run?

I have scripts In my React app that are inserted dynamically later on. The scripts don't load.

+

In my database there is a field called content, which contains data that includes html and javascript. There are many records and each record can include multiple scripts in the content field. So it's not really an option to statically specify each of the script-urls in my React app. The field for a record could for example look like:

+
<p>Some text and html</p>
+<div id="xxx_hype_container">
+    <script type="text/javascript" charset="utf-8" src="https://example.com/uploads/hype_generated_script.js?499892"></script>
+</div>
+<div style="display: none;" aria-hidden="true"> 
+<div>Some text.</div> 
+Etc…
+
+

I call on this field in my React app using dangerouslySetInnerHTML:

+
render() {
+    return (
+        <div data-page="clarifies">
+            <div className="container">
+                <div dangerouslySetInnerHTML={{ __html: post.content }} />
+                ... some other data
+            </div>
+        </div>
+    );
+}
+
+

It correctly loads the data from the database and displays the html from that data. However, the Javascript does not get executed. I think the script doesn't work because it is dynamically inserted later on. How can I make these scripts work/run?

+

This post suggest a solution for dynamically inserted scripts, but I don't think I can apply this solution because in my case the script/code is inserted from a database (so how to then use nodeScriptReplace on the code...?). Any suggestions how I might make my scripts work?

+
+

Update in response to @lissettdm their answer:

+
constructor(props) {
+    this.ref = React.createRef();
+}
+
+componentDidUpdate(prevProps, prevState) {
+    if (prevProps.postData !== this.props.postData) {
+        this.setState({
+            loading: false,
+            post: this.props.postData.data,
+            //etc
+        });
+        setTimeout(() => parseElements());
+
+        console.log(this.props.postData.data.content);
+        // returns html string like: `<div id="hype_container" style="margin: auto; etc.`
+        const node = document.createRange().createContextualFragment(this.props.postData.data.content);
+        console.log(JSON.stringify(this.ref));
+        // returns {"current":null}
+        console.log(node);
+        // returns [object DocumentFragment]
+        this.ref.current.appendChild(node);
+        // produces error "Cannot read properties of null"
+    }
+}
+
+render() {
+    const { history } = this.props;
+    /etc.
+    return (
+        {loading ? (
+            some code
+        ) : (
+            <div data-page="clarifies">
+                <div className="container">
+                    <div ref={this.ref}></div>
+                    ... some other data
+                </div>
+            </div>
+        );
+    );
+}
+
+

The this.ref.current.appendChild(node); line produces the error:

+
+

TypeError: Cannot read properties of null (reading 'appendChild')

+
","

If your are sure about HTML string content is safety and contains a string with valid HTML you can use Range.createContextualFragment() (executes scripts )

+
function App() {
+  const ref = useRef();
+
+  useEffect(() => {
+    /* convert your HTML string into DocumentFragment*/
+    const node = document.createRange().createContextualFragment(HTML);
+    ref.current.appendChild(node);
+  }, []);
+
+  return (
+    <div>
+      <h1>HTML String</h1>
+      <div>
+        <div ref={ref}></div>
+      </div>
+    </div>
+  );
+}
+
+
+

See how script content is executed on JavaScript console working example

+

If your are using class component create ref within class constructor, then update node content, I did it in componentDidMount just for testing:

+
class App extends React.Component {
+  constructor(props) {
+    super(props);
+    this.ref = React.createRef();
+  }
+
+  componentDidMount() {
+    const node = document.createRange().createContextualFragment(HTML);
+    this.ref.current.appendChild(node);
+  }
+
+  render() {
+    return (
+      <div>
+        <h1>HTML String</h1>
+        <div>
+          <div ref={this.ref}></div>
+        </div>
+      </div>
+    );
+  }
+}
+
+
+

see this working example

",html +"Nav bar logo wont show up

Something strange is happening. I have added my logo to the top right of my website and it shows up perfectly when I look at my website in my localhost on my live server. However, when I look on my publicly hosted website (using GitHub pages) the logo does not show up. Any suggestions on how to fix this or what the issue might be?

+

CSS Code

+
            .bd-grid{
+                max-width: 1024px;
+                display: grid;
+                grid-template-columns: 100%;
+                grid-column-gap: 2rem;
+                width: calc(100% - 2rem);
+                margin-left: var(--mb-2);
+                margin-right: var(--mb-2);
+            }
+            .l-header{
+                width: 100%;
+                position: fixed;
+                top: 0;
+                left: 0;
+                z-index: var(--z-fixed);
+                background-color: var(--first-color);
+            }
+
+            /*===== NAV =====*/
+            .nav{
+                height: var(--header-height);
+                display: flex;
+                justify-content: space-between;
+                align-items: center;
+                font-size: 20px;
+            }
+            @media screen and (max-width: 768px){
+                .nav__menu{
+                    position: fixed;
+                    top: var(--header-height);
+                    right: -100%;
+                    width: 50%;
+                    height: 100%;
+                    padding: 2rem;
+                    background-color: rgba(219, 236, 244, 0.852);
+                    transition: .5s;
+                    backdrop-filter: blur(10px);
+                    font-size: 25px;
+                    text-align: left;
+                    box-shadow: -2px 0px 4px 1px var(--first-color);
+                }
+            }
+            .nav__item{
+                margin-bottom: var(--mb-4);
+                padding: var(--mb-2);
+            }
+
+            .nav__link{
+                position: relative;
+                color: var(--dark-color);
+            }
+            .nav__link:hover{
+                color: var(--first-color);
+                font-weight: 900;
+            }
+            .nav__logo{
+                color: var(--white-color);
+                font-family: Snell Roundhand, cursive;
+            }
+            .nav__toggle{
+                color: var(--white-color);
+                font-size: 1.5rem;
+                cursor: pointer;
+            }
+
+            .nav__logo{
+                text-transform: uppercase;
+                font-weight: 700;
+                letter-spacing: -1px;
+                display: inline-flex;
+                align-items: center;
+                column-gap: .5rem;
+                transition: .3s;
+            }
+            
+            .logo-image{
+                width: 150px;
+                height: 150px;
+                border-radius: 50%;
+            }
+            
+            
+            .nav__logo-icon{
+                font-size: 10px;
+                color: var(--first-color);
+            }
+
+

HTML Code + +

+
            <a class="nav__logo" href="/">
+                <div class="logo-image">
+                      <img src="/assets/img/logosignature.png" class="nav__logo-icon">
+                </div>
+            </a>
+
+            <div class="nav__menu" id="nav-menu">
+                <ul class="nav__list">
+                    <li class="nav__item"><a href="#home" class="nav__link active">Home</a></li>
+                    <li class="nav__item"><a href="#about" class="nav__link">About</a></li>
+                    <li class="nav__item"><a href="#skills" class="nav__link">Skills</a></li>
+                    <li class="nav__item"><a href="#portfolio" class="nav__link">Portfolio</a></li>
+                    <li class="nav__item"><a href="#contact" class="nav__link">Contact</a></li>
+                </ul>
+            </div>
+
+            <div class="nav__toggle" id="nav-toggle">
+                <i class='bx bx-menu'></i>
+            </div>
+        </nav>
+    </header>
+
+

+

","

There can be multiple cases why this is happening:

+
    +
  1. File names and extensions are case sensitive on GitHub pages so check if you have entered it correctly in src attribute of image.
  2. +
  3. Try removing the initial '/' character in src attribute of image.
  4. +
  5. Path specified might be incorrect
  6. +
",html +"How to reset all other nested data inside parent onclick Alpine.js

I have multiple groups and multiple choices inside each group. When I click on a choice inside a group the groupcount should always + 1 and the clicked choicecount should be set to 1 while the other choicecount's inside the group should be reset to 0.

+

I have tried using $dispatch to reset all choicecount's inside the group to 0 before setting choicecount = 1 and groupcount++, but $dispatch doesn't seem to trigger the other nested choicecount's inside the group.

+

For example, in the snippet below (Group 1): +Only one of G1 Option 1, G1 Option 2, G1 Option 3 should be allowed to equal 1 at a time. +If G1 Option 2 = 1 then G1 Option 1 and G1 Option 3 should = 0. The groupcount's are working fine.

+

Note: This is stripped down, radio buttons aren't suitable for the feature I'm creating and I'm not using x-for because these groups and choices will be generated from a PHP loop. The number of groups and choices will vary.

+

+
+
<script src=""https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js""></script>
+
+<!-- GROUP 1 -->
+<div x-data=""{ groupcount: 0 }"">
+  <label>Group 1 Count</label>
+  <input x-model=""groupcount"" type=""text"">
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G1 Option 1
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G1 Option 2
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G1 Option 3
+      </button>
+    </div>
+  </div>
+
+</div>
+<hr>
+
+<!-- GROUP 2 -->
+<div x-data=""{ groupcount: 0 }"">
+  <label>Group 2 Count</label>
+  <input x-model=""groupcount"" type=""text"">
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G2 Option 1
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G2 Option 2
+      </button>
+    </div>
+  </div>
+
+</div>
+<hr>
+
+<!-- GROUP 3 -->
+<div x-data=""{ groupcount: 0 }"">
+  <label>Group 3 Count</label>
+  <input x-model=""groupcount"" type=""text"">
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G3 Option 1
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:resetAllCountsInGroup=""choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('resetAllCountsInGroup'),choicecount=1,groupcount++"">
+        G3 Option 2
+      </button>
+    </div>
+  </div>
+
+</div>
+
+
+

","

There are three issues with the example. First, due to event bubbling, we need to use the .window modifier on the event listeners. Second, camelCasing is not supported inside HTML attributes, so we need to use dashes in the event name (or use the .camel modifier), I will use reset-group in the example. The last issue is that the resetting event now acts on every group, so we need to limit its scope to the current group. For that, I added a groupid property to each group, which is unique and it is included in the event as well, so we can check its value inside the event listener with if (groupid == $event.detail) choicecount=0 before resetting a group.

+

+
+
<script src=""https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js""></script>
+
+<div x-data=""{ groupcount: 0, groupid: 1 }"">
+  <label>Group 1 Count</label>
+  <input x-model=""groupcount"" type=""text"">
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G1 Option 1
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G1 Option 2
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G1 Option 3
+      </button>
+    </div>
+  </div>
+</div>
+
+<div x-data=""{ groupcount: 0, groupid: 2 }"">
+  <label>Group 2 Count</label>
+  <input x-model=""groupcount"" type=""text"">
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G2 Option 1
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G2 Option 2
+      </button>
+    </div>
+  </div>
+
+  <div x-data=""{ choicecount: 0 }"">
+    <div x-on:reset-group.window=""if (groupid == $event.detail) choicecount=0"">
+      <input x-model=""choicecount"" type=""text"">
+      <button type=""button"" x-on:click=""$dispatch('reset-group', groupid),choicecount=1,groupcount++"">
+        G2 Option 3
+      </button>
+    </div>
+  </div>
+</div>
+
+
+

",html +"How to get user input from contenteditable div in a grid?

I have been trying to create a wordle-type game, but I don't know how to get the user input from the contenteditable div's. What I want to happen is if the user inputs the letter 'a' for example, the letter in the div would turn green, whilst the other letters in the other div's are a different color.

+

So basically, when the user is done typing in every letter for a guess, they would click enter and the letter 'a' would turn green. (The word in this case would be absolute) +Also if possible making sure the user actually fills out all the boxes in the row before making the function possible.

+
let word = "absolute";
+
+
+
+function inputFunc() {
+
+event.target.nextElementSibling.focus();
+
+}
+
+document.getElementById('amo1').addEventListener('keypress', function(e) {
+    document.getElementById('amo1').value = this.innerHTML;
+});
+
+

Here is my full code in JSFiddle, including all the divs, CSS, HTML and JS code: https://jsfiddle.net/Infui/c7q30gez/1/

","

https://codepen.io/codmitu/pen/LYegzNN?editors=0011

+

html:

+
<p>absolute</p>
+<div contenteditable="true" style="border: 5px solid; padding: 5px"></div>
+<button>check</button>
+
+

js:

+
const pText = document.querySelector("p").innerText
+const div = document.querySelector("div")
+const button = document.querySelector("button")
+
+
+button.addEventListener("click", () => {
+  const text = div.textContent
+  //checking for numbers
+  if (text.match(/\d/gi)) {
+    div.innerText = text
+    return 
+  }
+
+    div.innerHTML = ""
+    text.split("").forEach(letter => {
+    if (pText.includes(letter)) {
+      div.innerHTML += `<span style="color: green">${letter}</span>`
+    } else {
+      div.innerHTML += `<span style="color: grey">${letter}</span>`
+    }
+  })
+})
+
+//blur the div if text is longer than 8 letters
+div.addEventListener("keydown", (e) => {
+   if (div.innerText.length > 7 || e.keyCode == 32) {
+     div.blur()
+   }
+})
+
+//clear on focus
+div.addEventListener("focus", () => {
+   div.innerHTML = ""
+})
+
",html +"Gatsbyjs reach-router import error breaking site

I was working on my Gatsby project and tried adding the React Cookie Consent package. After installing it and trying to implement it, my site broke down, proving me with this error:

+
   warn ./.cache/root.js
+    Attempted import error: 'BaseContext' is not exported from '@gatsbyjs/reach-router' (imported as 'BaseContext').
+
+

I can't seem to find a fix, nor do I know why it is happening. Localhost is throwing me this error:

+
_gatsbyjs_reach_router__WEBPACK_IMPORTED_MODULE_2__.BaseContext is undefined
+
+

Any help is welcome! Thank you :)

","

Upon trying deleting the cache folder by running:

+
gatsby clean
+
+

If the issue persist, try bypassing the SSR limitation by adding the following to your gatsby-node.js:

+
exports.onCreateWebpackConfig = ({actions, loaders, stage}) => {
+    if (stage === "build-html") {
+        actions.setWebpackConfig({
+            module: {
+                rules: [
+                    {
+                        test: /react-cookie-consent/,
+                        use: loaders.null(),
+                    },
+                ],
+            }
+        })
+    }
+};
+
+

Or using a dynamic import:

+
useEffect(() => {
+  (async () => {
+    const { getCookieConsentValue, Cookies } = await import('react-cookie-consent')
+
+    getCookieConsentValue('test')
+    Cookies.get()
+  })()
+}, [])
+
+

You can check for further approaches at: https://github.com/Mastermindzh/react-cookie-consent/issues/136

",html +"Flickity-fade slider not working after following the installation docs from github; flickity just run like the regular slider

I'm following this flickity slide fade docs +FlickityFade Installation

+
+

Here is the css cdn package

+
+
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">
+<link rel="stylesheet" href="https://unpkg.com/flickity-fade@2/flickity-fade.css">
+
+
+

Here is the carousel html and the script set up

+
+
<div class="testimonial-carousel">
+     ....carousels div....
+</div>
+
+<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
+<script src="https://unpkg.com/flickity-fade@2/flickity-fade.js"></script>
+<script>
+    $('.testimonial-carousel').flickity({
+        // options
+        fade: true,
+        cellAlign: 'left',
+        contain: true,
+        prevNextButtons: false
+    });
+</script>
+
+

i don't figure out why this slide fade not working, only run in the dom like i am using normal flickity package +but, it shown error like link below

+

Error screenshot from my console log

","

Found the solution here Flickity issues

",html +"How to replace onclick with eventlistener for sidebar navigation

How would I replace onclick with eventlistener in order to make my collapsible sidebar work. Right now the sidebar does not work in one click (when I add the other onsite links to the navigation- and it doesn't work on their pages as well). I have to be clicking more than once in order to get it to work and when pressed, it deletes all of the user input on the page which I do not want.

+

I was told that using onclick was the source of my problem and to replace as mentioned above. Unfortunately, I am in no possession of knowledge on how to use JavaScript, Jquery, etc. I tried to replace it using outside sources but most of them was to display some text output?

+

Any advice on how my code should look would be great. (worth mentioning that I'm not able to post all the other html sites in the folder which when included, the sidebar doesn't work properly)

+

+
+
h1 {
+    font-family: Georgia, 'Times New Roman', Times, serif;
+    font-size: 250%;
+    text-shadow: 1px 2px 3px rgb(0, 0, 0);
+    color: #75c3f3;
+    padding-top: 0px;
+    padding-bottom: 35px;
+    text-align:center;
+}
+
+#review {
+    background-color: #4CAF50;
+    border: none;
+    border-radius: 10px;
+    color: white;
+    padding: 10px 15px;
+    text-align: center;
+    text-decoration: none;
+    display: inline-block;
+    font-size: 17px;
+}
+
+#review:hover {
+    cursor: pointer;
+    background-color:#5cbf2a;
+}
+
+#reset {
+    background-color: #af4c4c;
+    border: none;
+    border-radius: 10px;
+    color: white;
+    padding: 5px 10px;
+    text-align: center;
+    text-decoration: none;
+    display: inline-block;
+    font-size: 14px;
+}
+
+#result {
+    width:fit-content;
+    min-width: 200px;
+    border-radius: 5px;
+    text-align: center;
+    background-color: rgb(255, 255, 255);
+    color: rgba(0, 0, 0, 0.692);
+    padding: 3px;
+    margin-left: 370px;
+    border: 3px;
+    min-height: 70px;
+    max-width: 975px;
+}
+
+table {
+    height: 3px;
+}
+
+select {
+    margin-left: 20px;
+    position:absolute;
+}
+
+#typeOfCSR {
+    margin-left: 48px;
+    position: absolute;
+}
+
+#nameOfCert {
+    margin-left: 54px;
+    position: absolute;
+}
+
+#FQDN {
+    margin-left: 72px;
+    position: absolute;
+}
+
+#altName {
+    margin-left: 193px;
+    position: absolute;
+}
+
+
+#CN {
+    margin-left: 168px;
+    position:absolute;
+}
+
+textarea {
+    height: 20px;
+    width: 50%;
+    max-width:50%;
+}
+
+body {
+    font-size: large;
+    background: #74ebd5;  /* fallback for old browsers */
+    background: -webkit-linear-gradient(to right, #ACB6E5, #74ebd5);  /* Chrome 10-25, Safari 5.1-6 */
+    background: linear-gradient(to right, #ACB6E5, #74ebd5); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
+    padding: 20px;
+    padding-top: 10px;
+    min-width: fit-content;
+    background-repeat: no-repeat;
+    background-attachment: fixed;
+}
+
+.container #input {
+    position:relative ;
+    margin-right: auto;
+    resize: horizontal;;
+}
+
+.container {
+    color: white;
+    background-color: rgba(0, 0, 0, 0.7);
+    padding: 20px;
+    padding-top: 1%;
+    border-radius: 10px;
+    min-width: 720px;
+}
+
+.sidebar {
+    height: 100%;
+    width: 0;
+    position: fixed;
+    z-index: 1;
+    top: 0;
+    left: 0;
+    background-color: #111;
+    overflow-x: hidden;
+    transition: 0.5s;
+    padding-top: 60px;
+  }
+  
+  .sidebar a {
+    padding: 8px 8px 8px 32px;
+    text-decoration: none;
+    font-size: 25px;
+    color: #818181;
+    display: block;
+    transition: 0.3s;
+  }
+  
+  .sidebar a:hover {
+    color: #f1f1f1;
+  }
+  
+  .sidebar .closebtn {
+    position: absolute;
+    top: 0;
+    right: 25px;
+    font-size: 36px;
+    margin-left: 50px;
+  }
+  
+  .openbtn {
+    font-size: 20px;
+    cursor: pointer;
+    background-color: #111;
+    color: white;
+    padding: 10px 15px;
+    border: none;
+    border-radius: 10px;
+  }
+  
+  .openbtn:hover {
+    background-color: #444;
+  }
+  
+  #main {
+    transition: margin-left .5s;
+    padding: 15px;
+  }
+  
+  pre code {
+    background-color: #eee;
+    border: 1px solid #999;
+    display: block;
+    color: #111;
+    max-width: fit-content;
+    padding: 20px;
+  }
+
+/** linear-gradient(135deg, #71b7e6, #9b59b6) **/
+/** #008ce4; **/
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <link rel=""stylesheet"" href=""site.css"" />
+
+    <title>CMS Cert Creation Form</title>
+    <style>
+        pre code {
+  background-color: #eee;
+  border: 1px solid #999;
+  display: block;
+  padding: 20px;
+}
+    </style>
+</head>
+
+<body> 
+
+    <form action=""#""> 
+
+        <div class=""container"">
+
+            <div id=""mySidebar"" class=""sidebar"">
+                <a href=""javascript:void(0)"" class=""closebtn"" onclick=""closeNav()"">×</a>
+                <a href=""CMS-CERT.html"">CMS</a>
+                <a href=""extra.html"">Extra</a>
+                <a href=""extra2.html"">Extra2</a>
+                <a href=""extra3.html"">Extra3</a>
+              </div>
+        
+              <div id=""main"">
+                <button class=""openbtn"" onclick=""openNav()"">☰ Open Sidebar</button>
+
+        <h1>CMS Cert Creation Form</h1>
+   
+<div id=""input"">
+        <div>
+            <label for=""typeOfCSR"">Choose the type of CSR you want to request</label>
+            <select name=""typeOfCSR"" id=""typeOfCSR"" onkeyup=""allowAlphaNumericSpace(this)"">
+                <option value="""">Select an Option </option>
+                <option value=""One"">One</option>
+                <option value=""Two"">Two</option>
+                <option value=""Three"">Three</option>
+            </select>
+        </div>
+<br />
+<br />
+        <div>
+            <label for=""nameOfCert""> Enter the name you want to give to the Cert</label>
+            <textarea cols=""100"" rows=""1"" id=""nameOfCert"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+        </div>
+<br />
+<br />
+        <div>
+            <label for=""FQDN""> Enter the FQDN of all your CMS servers</label>
+            <textarea cols=""100"" rows=""1"" id=""FQDN"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+        </div>
+<br />
+<br />
+        <div>
+            <label for=""alternateName""> Enter the alternate name</label>
+            <textarea cols=""100"" rows=""1"" id=""altName"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+        </div>
+ <br />
+ <br />
+        <div>
+            <label for=""CN""> Enter the CN of your server</label>
+            <textarea cols=""100"" rows=""1"" id=""CN"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+        </div>
+<br />
+<br />
+
+<table id=""result"">
+      <tr height=""50px"">
+        <td>Result will show here</td>
+      </tr>
+</table>
+
+</div>
+
+<br />
+<br />
+
+
+        <button type=""button"" id=""review"">Generate String</button>
+        <br /> <br />
+        <input type=""reset"" value=""Reset Input"" id=""reset"">
+<br/>
+<br/>
+    <br />
+</form>
+      </div>
+</div>
+
+    <script>
+        const btn = document.getElementById('review');
+        btn.addEventListener('click',()=>{
+            let typeOfCSR = document.getElementById('typeOfCSR').value;
+            let CN = document.getElementById('CN').value;
+            let FQDN = document.getElementById('FQDN').value;
+            let altName = document.getElementById('altName').value;
+            let nameOfCert = document.getElementById('nameOfCert').value;
+
+            document.getElementById('result').textContent =  typeOfCSR +"" ""+ nameOfCert +"" ""+ FQDN +"" ""+ altName +"" ""+ CN;
+        })
+
+        function allowAlphaNumericSpace(thisInput) {
+  thisInput.value = thisInput.value.split(/[^a-zA-Z0-9 ]/).join('');
+}
+
+function openNav() {
+  document.getElementById(""mySidebar"").style.width = ""250px"";
+  document.getElementById(""main"").style.marginLeft = ""250px"";
+}
+
+function closeNav() {
+  document.getElementById(""mySidebar"").style.width = ""0"";
+  document.getElementById(""main"").style.marginLeft= ""0"";
+}
+
+    </script>
+</body>
+
+</html>
+
+
+

","
    +
  1. Your button to open the side navigation didn't have type="button" which was causing the form to post when clicking it, I added type="button" to your HTML markup

    +
  2. +
  3. Used document.querySelector to get your button and anchor with the appropriate className and added the click events via addEventListener

    +
  4. +
  5. Removed the inline click events on the anchor and button

    +
  6. +
+

Please see snippet below:

+

+
+
h1 {
+        font-family: Georgia, 'Times New Roman', Times, serif;
+        font-size: 250%;
+        text-shadow: 1px 2px 3px rgb(0, 0, 0);
+        color: #75c3f3;
+        padding-top: 0px;
+        padding-bottom: 35px;
+        text-align:center;
+    }
+
+    #review {
+        background-color: #4CAF50;
+        border: none;
+        border-radius: 10px;
+        color: white;
+        padding: 10px 15px;
+        text-align: center;
+        text-decoration: none;
+        display: inline-block;
+        font-size: 17px;
+    }
+
+    #review:hover {
+        cursor: pointer;
+        background-color:#5cbf2a;
+    }
+
+    #reset {
+        background-color: #af4c4c;
+        border: none;
+        border-radius: 10px;
+        color: white;
+        padding: 5px 10px;
+        text-align: center;
+        text-decoration: none;
+        display: inline-block;
+        font-size: 14px;
+    }
+
+    #result {
+        width:fit-content;
+        min-width: 200px;
+        border-radius: 5px;
+        text-align: center;
+        background-color: rgb(255, 255, 255);
+        color: rgba(0, 0, 0, 0.692);
+        padding: 3px;
+        margin-left: 370px;
+        border: 3px;
+        min-height: 70px;
+        max-width: 975px;
+    }
+
+    table {
+        height: 3px;
+    }
+
+    select {
+        margin-left: 20px;
+        position:absolute;
+    }
+
+    #typeOfCSR {
+        margin-left: 48px;
+        position: absolute;
+    }
+
+    #nameOfCert {
+        margin-left: 54px;
+        position: absolute;
+    }
+
+    #FQDN {
+        margin-left: 72px;
+        position: absolute;
+    }
+
+    #altName {
+        margin-left: 193px;
+        position: absolute;
+    }
+
+
+    #CN {
+        margin-left: 168px;
+        position:absolute;
+    }
+
+    textarea {
+        height: 20px;
+        width: 50%;
+        max-width:50%;
+    }
+
+    body {
+        font-size: large;
+        background: #74ebd5;  /* fallback for old browsers */
+        background: -webkit-linear-gradient(to right, #ACB6E5, #74ebd5);  /* Chrome 10-25, Safari 5.1-6 */
+        background: linear-gradient(to right, #ACB6E5, #74ebd5); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
+        padding: 20px;
+        padding-top: 10px;
+        min-width: fit-content;
+        background-repeat: no-repeat;
+        background-attachment: fixed;
+    }
+
+    .container #input {
+        position:relative ;
+        margin-right: auto;
+        resize: horizontal;;
+    }
+
+    .container {
+        color: white;
+        background-color: rgba(0, 0, 0, 0.7);
+        padding: 20px;
+        padding-top: 1%;
+        border-radius: 10px;
+        min-width: 720px;
+    }
+
+    .sidebar {
+        height: 100%;
+        width: 0;
+        position: fixed;
+        z-index: 1;
+        top: 0;
+        left: 0;
+        background-color: #111;
+        overflow-x: hidden;
+        transition: 0.5s;
+        padding-top: 60px;
+      }
+      
+      .sidebar a {
+        padding: 8px 8px 8px 32px;
+        text-decoration: none;
+        font-size: 25px;
+        color: #818181;
+        display: block;
+        transition: 0.3s;
+      }
+      
+      .sidebar a:hover {
+        color: #f1f1f1;
+      }
+      
+      .sidebar .closebtn {
+        position: absolute;
+        top: 0;
+        right: 25px;
+        font-size: 36px;
+        margin-left: 50px;
+      }
+      
+      .openbtn {
+        font-size: 20px;
+        cursor: pointer;
+        background-color: #111;
+        color: white;
+        padding: 10px 15px;
+        border: none;
+        border-radius: 10px;
+      }
+      
+      .openbtn:hover {
+        background-color: #444;
+      }
+      
+      #main {
+        transition: margin-left .5s;
+        padding: 15px;
+      }
+      
+      pre code {
+        background-color: #eee;
+        border: 1px solid #999;
+        display: block;
+        color: #111;
+        max-width: fit-content;
+        padding: 20px;
+      }
+
+    /** linear-gradient(135deg, #71b7e6, #9b59b6) **/
+    /** #008ce4; **/
+
<!DOCTYPE html>
+    <html lang=""en"">
+
+    <head>
+        <meta charset=""UTF-8"">
+        <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+        <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+        <link rel=""stylesheet"" href=""site.css"" />
+
+        <title>CMS Cert Creation Form</title>
+        <style>
+            pre code {
+      background-color: #eee;
+      border: 1px solid #999;
+      display: block;
+      padding: 20px;
+    }
+        </style>
+    </head>
+
+    <body> 
+
+        <form action=""#""> 
+
+            <div class=""container"">
+
+                <div id=""mySidebar"" class=""sidebar"">
+                    <a class=""closebtn"">×</a>
+                    <a href=""CMS-CERT.html"">CMS</a>
+                    <a href=""extra.html"">Extra</a>
+                    <a href=""extra2.html"">Extra2</a>
+                    <a href=""extra3.html"">Extra3</a>
+                  </div>
+            
+                  <div id=""main"">
+                    <button type=""button"" class=""openbtn"">☰ Open Sidebar</button>
+
+            <h1>CMS Cert Creation Form</h1>
+       
+    <div id=""input"">
+            <div>
+                <label for=""typeOfCSR"">Choose the type of CSR you want to request</label>
+                <select name=""typeOfCSR"" id=""typeOfCSR"" onkeyup=""allowAlphaNumericSpace(this)"">
+                    <option value="""">Select an Option </option>
+                    <option value=""One"">One</option>
+                    <option value=""Two"">Two</option>
+                    <option value=""Three"">Three</option>
+                </select>
+            </div>
+    <br />
+    <br />
+            <div>
+                <label for=""nameOfCert""> Enter the name you want to give to the Cert</label>
+                <textarea cols=""100"" rows=""1"" id=""nameOfCert"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+            </div>
+    <br />
+    <br />
+            <div>
+                <label for=""FQDN""> Enter the FQDN of all your CMS servers</label>
+                <textarea cols=""100"" rows=""1"" id=""FQDN"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+            </div>
+    <br />
+    <br />
+            <div>
+                <label for=""alternateName""> Enter the alternate name</label>
+                <textarea cols=""100"" rows=""1"" id=""altName"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+            </div>
+     <br />
+     <br />
+            <div>
+                <label for=""CN""> Enter the CN of your server</label>
+                <textarea cols=""100"" rows=""1"" id=""CN"" onkeyup=""allowAlphaNumericSpace(this)""></textarea>
+            </div>
+    <br />
+    <br />
+
+    <table id=""result"">
+          <tr height=""50px"">
+            <td>Result will show here</td>
+          </tr>
+    </table>
+
+    </div>
+
+    <br />
+    <br />
+
+
+            <button type=""button"" id=""review"">Generate String</button>
+            <br /> <br />
+            <input type=""reset"" value=""Reset Input"" id=""reset"">
+    <br/>
+    <br/>
+        <br />
+    </form>
+          </div>
+    </div>
+
+        <script>
+            const btn = document.getElementById('review');
+            btn.addEventListener('click',()=>{
+                let typeOfCSR = document.getElementById('typeOfCSR').value;
+                let CN = document.getElementById('CN').value;
+                let FQDN = document.getElementById('FQDN').value;
+                let altName = document.getElementById('altName').value;
+                let nameOfCert = document.getElementById('nameOfCert').value;
+
+                document.getElementById('result').textContent =  typeOfCSR +"" ""+ nameOfCert +"" ""+ FQDN +"" ""+ altName +"" ""+ CN;
+            });
+            //****adding click events via addEventListener****
+            const navopen = document.querySelector('button.openbtn');
+            const navclose = document.querySelector('a.closebtn');
+            navopen.addEventListener('click', openNav);
+            navclose.addEventListener('click', closeNav);
+            //****End new block****
+
+            function allowAlphaNumericSpace(thisInput) {
+      thisInput.value = thisInput.value.split(/[^a-zA-Z0-9 ]/).join('');
+    }
+
+    function openNav() {
+      document.getElementById(""mySidebar"").style.width = ""250px"";
+      document.getElementById(""main"").style.marginLeft = ""250px"";
+    }
+
+    function closeNav() {
+      document.getElementById(""mySidebar"").style.width = ""0"";
+      document.getElementById(""main"").style.marginLeft= ""0"";
+    }
+
+        </script>
+    </body>
+
+    </html>
+
+
+

",html +"Links in Table not detected by screen reader

I have a link button in my code where if it's focused by tabbing or clicking, a div will come down. I'm able to focus child table elements (the a href building inside td . See child code) using tab but screen reader is not providing audio feedback of the link.

+

Button code:

+
 <a
+      tabindex="0"
+      class="button dropdown secondary status_button"
+      id="twh-dd-anchor2"
+      type="button"
+      data-toggle="thisweek-dropdown2"
+      data-closable=""
+      aria-controls="thisweek-dropdown2"
+      data-is-focus="false"
+      data-yeti-box="thisweek-dropdown2"
+      aria-haspopup="true"
+      aria-expanded="false"
+      >Building Status</a
+    >
+
+

Page that pops up on button click:

+
<div
+  class="dropdown-pane is-open has-position-bottom has-alignment-right"
+  id="thisweek-dropdown2"
+  aria-labelledby="twh-dd-anchor2"
+  data-dropdown=""
+  data-hover="true"
+  data-hover-pane="true"
+  aria-hidden="true"
+  data-yeti-box="thisweek-dropdown2"
+  data-resize="thisweek-dropdown2"
+  data-n="u4ighp-n"
+  data-events="resize"
+  style="top: 78.1797px; left: -226.719px"
+>
+  <table class="quick-link-list unstriped">
+    <thead class="show-for-sr">
+      <tr>
+        <th>Space/Service</th>
+      </tr>
+      <tr>
+        <th>Status</th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr>
+        <td>
+          <a href="/about/spaces/building" role="link"> Building</a>
+        </td>
+      </tr>
+    </tbody>
+  </table>
+</div>
+
","

Check your data attributes on your child div, you set: +aria-hidden="true"

+

That is going to prevent screen readers from reading out what's inside this div.

+

As soon as I removed that I used NVDA and could hear it read out "Building".

+

https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden

",html +"How to fix this bug: border-image with transform will have lines

These are the bug lines +enter image description here

+

run code snippet, you will see thoes lines.

+

+
+
* {
+  box-sizing: border-box;
+}
+
+body {
+  margin: 0;
+}
+
+.a {
+  width: 650px;
+  height: 350px;
+  transition: all 1s linear;
+  transform: scale(1.1);
+  border: 60px solid transparent;
+  border-image: url('https://i.stack.imgur.com/wEz5D.png') 60 stretch;
+}
+
<div class=""a""></div>
+
+
+

",

Change img base64 data to svg,now it work fine

,html +"make responsive flexible images that are rotated on a single line in tailwind css?

i want to recreate this effect that is visible on https://www.tella.tv/ in tailwind css:

+

+

i tried to inspect their source code but i couldn't make it work in my code.

+

my markup looks like:

+
<div class="lg:space-x-15 -mr-6 flex items-end justify-end space-x-4 sm:space-x-8 md:space-x-12 lg:-mr-0 lg:justify-center">
+  <div class="shadow-gentle-backdrop w-35 lg:w-74 relative flex-shrink-0 rotate-3 transform overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2 sm:w-44 md:w-56">
+    <img class="" src="https://picsum.photos/300/400" alt="" />
+  </div>
+
+  <div class="shadow-gentle-backdrop w-30 sm:w-38 md:w-42 relative flex-shrink-0 -rotate-3 transform overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2 lg:w-64">
+    <img class="" src="https://picsum.photos/300/300" alt="" />
+  </div>
+
+  <div class="shadow-gentle-backdrop w-54 sm:w-66 lg:w-133 relative mb-8 flex-shrink-0 rotate-2 transform overflow-hidden rounded-lg transition hover:rotate-0 focus:outline-none focus:ring-2 md:w-96">
+    <img src="https://picsum.photos/500/400" alt="" />
+  </div>
+</div>
+
+<div class="lg:-ml-100 xl:-ml-50 lg:space-x-15 -ml-20 flex items-end justify-center space-x-4 sm:space-x-8 md:space-x-12">
+  <div class="shadow-gentle-backdrop w-35 md:w-68 lg:w-84 relative -mt-4 flex-shrink-0 -rotate-3 transform self-start overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2 sm:w-52">
+    <img class="" src="https://picsum.photos/200/200" alt="" />
+  </div>
+
+  <div class="shadow-gentle-backdrop w-37 md:w-76 lg:w-92 rotate-4 relative flex-shrink-0 transform overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2 sm:w-56">
+    <img class="" src="https://picsum.photos/200/300" alt="" />
+  </div>
+
+  <div class="shadow-gentle-backdrop w-42 md:w-82 relative flex-shrink-0 -rotate-2 transform overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2 sm:w-60 lg:w-96">
+    <img class="" src="https://picsum.photos/500/300" alt="" />
+  </div>
+
+  <div class="shadow-gentle-backdrop w-35 sm:w-58 md:w-76 lg:w-85 relative -mt-8 flex-shrink-0 rotate-2 transform self-start overflow-hidden rounded-lg opacity-80 transition hover:rotate-0 hover:opacity-100 focus:outline-none focus:ring-2">
+    <img class="" src="https://picsum.photos/600/300" alt="" />
+  </div>
+</div>
+
+

but i don't have the desired results in the same ratio.

+

i would love to recreate the above thing. even though i did copy the code from the tella website itself with a little change, the desired results depend on the image size.

+

personally, i want them to look like the screenshot above & every image is of the same size of 1439*793

+

the ui should look the same even if you make the screen size responsive.

+

how do i make that happen?

+

tailwind play → https://play.tailwindcss.com/5OXcK7F8qb?layout=horizontal

","

The issue with your code is that you didn't add the container div for the rows.

+

I did that and recreated the grid with pretty much the same code as the tella website. I made it a bit asymmetrical but you can easily make it symmetrical by copying the first section and pasting over the second.

+

If you want it to be as responsive as the other website you will have to design new breakpoints and behavior for those. I didn't do that because I have no idea how many images you would like to have on each row or what height the images should be. It is at least a bit responsive now :).

+

I hope this can be a good start for you: https://play.tailwindcss.com/hEJgrTUbPb?layout=horizontal&size=1836x720

",html +"How do I add position/overlay these images and a div?

I'm building a website for one of my friends, and I'm having trouble placing a div to the left, and then images ontop of each others corners to the right. Here's a diagram to explain: Diagram

+

I don't really know how to position this all, while also keeping it responsive for mobile +Any help appreciated!

","

Let's FIRST create the left and right parts and then create those three elements

+

You can use flex box to create two parts of your design +Or you can use bootstrap if you don't want to code a lot

+

This example is Pure CSS

+
.parent{
+     display: flex;
+     flex-wrap: wrap;
+}
+.left,.right{
+     width: 50%;
+}
+@media (max-width:768px){
+    .left,.right{
+         width: 100%;
+    }
+}
+
+

Or if you link bootstrap files then no extra CSS is necessary(former div will be the left one and latter will be the right one)

+
<div class="col-12 col-md-6"></div>
+<div class="col-12 col-md-6"></div>
+
+

Now, For those three elements you should use CSS Positioning

+

I Can't explain all about positioning because it's a lot,, but +We have 2 types of positions that are needed in your case

+

Position : absolute

+

Position : relative

+

If you position an element Relative and use properties like: top, bottom, right, left, z-index. The element will move according to its own default position

+

But if you position an element Absolute, the element will be extracted from his own father (no longer considered father's content) and if you use properties like top, bottom, left, right your element will be moved according to his first non-static father

+

It means CSS will look elements father, if father has a position property set to any value BUT static (which is default for position) CSS will move element according to that father, if father has static position, CSS will look up for element's grandfather and so on until a non-static parent can be found, if it does not found CSS will position element according to body element

+

Now, you have three items that you want them to be placed inside your right element, let's name them .item1 .item2 .item3 you can set their position to absolute AND set their father's(right's) position to relative

+

This way three items can be moved across their father using top, bottom, left, right and z-index

+

Here's the sample

+
.right{
+     position: relative ;
+}
+.item1,.item2,.item3{
+    position: absolute ;
+}
+.item1{
+    left: 50%;
+    top: 20px;
+}
+.item2{
+    left: 70%;
+    top: 120px;
+}
+.item3{
+    left: 50%;
+    top: 220px;
+}
+
+

(numbers are just for example)

+

By default elements that are placed later in your html will appear on top of others in CSS Positions, you can change and modify this using z-index +It's rules are simple, higher number means higher layer order...

",html +"How to modify qtwebbrowser defaults?

While playing with qtqwebbrowser

+

https://code.qt.io/cgit/qt-apps/qtwebbrowser.git

+

the two questions arise:

+

1.) How can I set an initial URL when opening the browser ? +2.) How can I disable the virtual keyboard when using desktop platforms ?

","

Qtwebbrwoser is an example application in beta state which contains issues related to both questions:

+

1.) The app's initlalURL argument must not contain "-" (in contradiction to the other app args) so just the plain URL. Then in Browserwindow.qml navigation.load(); has to be changed to navigation.load(url)

+

2.) Disabling the virtual keyboard is not supported by default. However, it can be achieved by introducing the visibility property in the respective QML file (Main.qml) and set it from the C++ end via e.g. object->setProperty("keyboardVisible", false);

",html +"Add a button for random playback of tracks in the player

I want to add a small player to my site to listen to music. I found a beautiful example that I liked and want to change and finish it a little.

+

Specifically, I want to add a button here to randomly play tracks.

+

To start, I add this button to the html:

+
<button type="submit" id="btn-random">
+   <i class="fas fa-random"></i>
+</button>
+
+

Next, I add a check to the next track switching function, if the random button has an active class, then the tracks will play randomly:

+
else if (to == 'next') {
+        stop();
+        if (document.getElementById("btn-random").classList.contains("active")) {
+          let songs = document.getElementById("sourceUrl").length - 1;
+          let randomSong = Math.floor(Math.random() * songs) + 1;
+        } else {
+          currentSong = (++currentSong)%playlist.length;
+        }
+        playpause();
+    }
+
+

Next, it remains to make sure that when you click on the random button, the active class turns on and off. To do this, I make a onclick function for this button and implement it:

+
<button type="submit" id="btn-random" onclick="random()">
+   <i class="fas fa-random"></i>
+</button>
+
+//
+
+var randomTrack = false;
+
+function random() {
+  if (randomTrack) {
+        document.getElementById('btn-random').classList.add("active");
+        randomTrack = false;
+    }
+    else {
+        document.getElementById('btn-random').classList.remove("active");
+        randomTrack = true;
+    }
+}
+
+

But in the end, when the random button has an active class and I try to switch the song, instead of a random track, the current track plays in a circle.

+

What could be the problem?

+

+
+
var song = new Audio;
+var isStopped = true;
+var currentSong = 0;
+var playlist = [];
+var playlistVisible = false;
+var randomTrack = false;
+
+function skip(to) {
+    if (to == 'prev') {
+        stop();
+        currentSong = (--currentSong)%playlist.length;
+        if (currentSong < 0) {
+            currentSong += playlist.length;
+        }
+        playpause();
+    }
+    else if (to == 'next') {
+        stop();
+        if (document.getElementById(""btn-random"").classList.contains(""active"")) {
+          let songs = document.getElementById(""sourceUrl"").length - 1;
+              let randomSong = Math.floor(Math.random() * songs) + 1;
+        } else {
+          currentSong = (++currentSong)%playlist.length;
+        }
+        playpause();
+    }
+}
+
+function playpause() {
+  if (!song.paused) {
+        song.pause();
+        document.getElementById(""glow"").classList.add(""disable-animation"");
+    }
+  else if (playlist.length == 0){
+    togglePlaylist();
+  }
+    else {
+      if (isStopped) {
+            song.src = playlist[currentSong];
+        }
+        song.play();
+        songFile = playlist[currentSong].split(""/"");
+        songName = document.getElementById(""songName"");
+        songName.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
+        document.getElementById(""glow"").classList.remove(""disable-animation"");
+        isStopped = false;
+    }
+}
+
+function random() {
+  if (randomTrack) {
+        document.getElementById('btn-random').classList.add(""active"");
+        randomTrack = false;
+    }
+    else {
+        document.getElementById('btn-random').classList.remove(""active"");
+        randomTrack = true;
+    }
+}
+
+function stop() {
+    song.pause();
+    document.getElementById(""glow"").classList.add(""disable-animation"");
+    song.currentTime = 0;
+    document.getElementById(""seek"").value = 0;
+    isStopped = true;
+    document.getElementById(""songName"").innerHTML = ""playing track.."";
+}
+
+function setPos(pos) {
+    song.currentTime = pos;
+}
+
+function mute() {
+    if (song.muted) {
+        song.muted = false;
+        document.getElementById('mute').className = ""fa fa-volume-up"";
+    }
+    else {
+        song.muted = true;
+        document.getElementById('mute').className = ""fa fa-volume-off"";
+    }
+}
+
+function setVolume(volume) {
+    song.volume = volume;
+}
+
+function togglePlaylist() {
+    if (playlistVisible) {
+        document.getElementById('playlist').className = ""hide"";
+        document.getElementById('player').className = """";
+        playlistVisible = false;
+    }
+    else {
+        document.getElementById('player').className = ""hide"";
+        document.getElementById('playlist').className = """";
+        playlistVisible = true;
+    }
+}
+
+function addList() {
+    sourceUrl = document.getElementById('sourceUrl').value;
+    sourceUrl.split("","").forEach((file) => {
+        fileUrl = file.trim();
+        if (fileUrl != """" && playlist.indexOf(fileUrl) == -1) {
+            parent = document.getElementById('list');
+            listItem = document.createElement('div');
+            listItem.setAttribute('class','list-item');
+
+            wrapper = document.createElement('div');
+            wrapper.setAttribute('class','wrap-text');
+
+            span = document.createElement('span');
+      songFile = fileUrl.split(""/"");
+            span.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
+
+            wrapper.appendChild(span);
+            listItem.appendChild(wrapper);
+
+            btn = document.createElement('button');
+            btn.setAttribute('onclick','removeList(this)');
+            btn.innerHTML = '&times;';
+
+            listItem.appendChild(btn);
+            parent.appendChild(listItem);
+            playlist.push(fileUrl);
+        }
+    });
+  document.getElementById('sourceUrl').value = '';
+}
+
+function removeList(item) {
+    index = playlist.indexOf(item.parentElement.firstChild.innerText);
+    if (index != -1){
+        playlist.splice(index,1);
+        item.parentElement.remove();
+    }
+}
+
+song.addEventListener('error', function(){
+    stop();
+    document.getElementById(""songName"").innerHTML = ""error loading audio"";
+});
+
+song.addEventListener('timeupdate', function() {
+    curtime = parseInt(song.currentTime,10);
+    document.getElementById('seek').max = song.duration;
+    document.getElementById('seek').value = curtime;
+});
+
+song.addEventListener(""ended"", function() {
+    song.pause();
+    song.currentTime = 0;
+    document.getElementById('seek').value = 0;
+    if ((currentSong + 1) >= playlist.length) {
+        currentSong = 0;    
+    }
+    else {
+        currentSong++;
+    }
+    stop();
+    song.src = playlist[currentSong];
+    playpause();
+});
+
+var input = document.getElementById(""sourceUrl"");
+input.addEventListener(""keyup"", function(event) {
+    if (event.keyCode === 13) {
+        event.preventDefault();
+        addList();
+    }
+});
+
+
+// This area of code is only for preview purposes only
+
+document.getElementById('sourceUrl').value = [""https://www.bensound.com/bensound-music/bensound-summer.mp3"",
+""https://www.bensound.com/bensound-music/bensound-anewbeginning.mp3"",
+""https://www.bensound.com/bensound-music/bensound-littleidea.mp3"",
+""https://www.bensound.com/bensound-music/bensound-cute.mp3"",
+""https://www.bensound.com/bensound-music/bensound-memories.mp3""];
+addList();
+document.getElementById(""glow"").classList.remove(""disable-animation"");
+
+// Code for preview ends here
+
* {
+  box-sizing: border-box;
+}
+html {
+  background: #000000;
+}
+html,
+body,
+.container {
+  height: 100%;
+  margin: 0;
+  font-family: Arial, Helvetica, sans-serif;
+  white-space: nowrap;
+  user-select: none;
+  -webkit-touch-callout: none;
+  -webkit-user-select: none;
+  -khtml-user-select: none;
+  -moz-user-select: none;
+  -ms-user-select: none;
+}
+.container {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+.glow {
+  position: absolute;
+  width: 300px;
+  height: 300px;
+  background: linear-gradient(0deg, #000000, #262626);
+  border-radius: 50%;
+}
+.glow::before,
+.glow::after {
+  content: """";
+  position: absolute;
+  top: -2px;
+  left: -2px;
+  background: linear-gradient(
+    45deg,
+    #ebc6df,
+    #ebc6c9,
+    #e1c6eb,
+    #c6c9eb,
+    #c6e8eb,
+    #e373fb,
+    #f787e6,
+    #cb87f7,
+    #87a9f7,
+    #87f7ee
+  );
+  background-size: 400%;
+  max-width: calc(300px + 4px);
+  max-height: calc(300px + 4px);
+  width: calc(300px + 4px);
+  height: calc(300px + 4px);
+  z-index: -1;
+  animation: animate 20s linear infinite;
+  border-radius: 50%;
+}
+.disable-animation::before,
+.disable-animation::after {
+  animation-play-state: paused;
+}
+.glow::after {
+  filter: blur(28px);
+}
+#player,
+#playlist {
+  width: 243px;
+  height: 212px;
+  text-align: center;
+  position: relative;
+  top: 50%;
+  left: 50%;
+  transform: translate(-50%, -50%);
+}
+#songName {
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  padding: 0 30px;
+}
+.playlist-btn {
+  width: 243px;
+  margin-top: 30px;
+  text-align: center;
+  position: relative;
+  left: 50%;
+  transform: translateX(-50%);
+}
+.hide {
+  display: none;
+}
+#list {
+  height: 118px;
+  max-height: 118px;
+  margin-top: 16px;
+  font-size: 12px;
+  overflow-x: hidden;
+  overflow-y: scroll;
+  color: #fff;
+  text-align: left;
+  padding-left: 8px;
+  border: 2px solid #262626;
+  border-radius: 5px;
+}
+.list-item {
+  line-height: 30px;
+  height: 30px;
+  margin-top: 4px;
+}
+.list-container button {
+  width: 30px;
+  padding: 0;
+  float: right;
+  margin-right: 4px;
+}
+.add-list {
+  padding: 4px 6px;
+}
+.wrap-text {
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  max-width: 190px;
+  display: inline-block;
+}
+#sourceUrl {
+  background: none;
+  padding: 8px;
+  border: 2px solid #1f1f1f;
+  border-radius: 47px;
+  outline: none;
+  color: white;
+  height: 30px;
+  width: 192px;
+}
+#sourceUrl:active,
+#sourceUrl:focus {
+  border: 2px solid #0088ff;
+}
+.text {
+  color: #ffffff;
+  display: block;
+}
+button {
+  background: #000000;
+  color: #ffffff;
+  background: linear-gradient(0deg, #000000, #262626);
+  font-size: 14px;
+  border: none;
+  outline: none;
+  padding: 0px 15px;
+  width: 55px;
+  height: 30px;
+  line-height: 30px;
+  border-radius: 32px;
+}
+button:hover {
+  box-shadow: 0 0 8px 0px #ffffff61;
+}
+button:active {
+  box-shadow: inset 0 0 6px 0px #ffffff61;
+}
+
+#seek,
+#volume {
+  -webkit-appearance: none;
+  border: 1px solid #000000;
+  height: 5px;
+  vertical-align: middle;
+  border-radius: 20px;
+  background-color: #232323;
+  outline: none;
+}
+#seek::-webkit-slider-thumb,
+#volume::-webkit-slider-thumb {
+  -webkit-appearance: none;
+  width: 20px;
+  height: 20px;
+  border: 1px solid #000000;
+  border-radius: 10px;
+  background: #ffffff;
+}
+#seek {
+  display: block;
+  width: 230px;
+}
+.scrollbar::-webkit-scrollbar {
+  max-width: 5px;
+  max-height: 5px;
+}
+.scrollbar::-webkit-scrollbar-thumb {
+  border-radius: 10px;
+  background: #333;
+}
+.scrollbar::-webkit-scrollbar-thumb:hover {
+  box-shadow: inset 0 0 1px 1px #5c6670;
+}
+
+.scrollbar::-webkit-scrollbar-track:hover {
+  border: 1px solid #000000;
+  border-radius: 20px;
+  background-color: #232323;
+}
+
+@keyframes animate {
+  0% {
+    background-position: 0 0;
+  }
+  50% {
+    background-position: 400% 0;
+  }
+  100% {
+    background-position: 0 0;
+  }
+}
+
<link href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"" rel=""stylesheet"" type=""text/css"">
+<div class=""container"">
+  <div id=""glow"" class=""glow disable-animation"">
+    <div id=""player"">
+      <span class=""text"">iu player</span>
+      <br>
+      <span id=""songName"" class=""text"">playing track..</span>
+      <br>
+      <div class=""playback_controls"">
+        <button onclick=""skip('prev')"">
+          <i class=""fa fa-fast-backward""></i>
+        </button>
+        <button onclick=""playpause()"">
+          <i class=""fa fa-play""></i><i class=""fa fa-pause""></i>
+        </button>
+        <button onclick=""stop()"">
+          <i class=""fa fa-stop""></i>
+        </button>
+        <button onclick=""skip('next')"">
+          <i class=""fa fa-fast-forward""></i>
+        </button>
+      </div>
+      <br>
+      <div id=""seekbar"">
+        <input type=""range"" oninput=""setPos(this.value)"" id=""seek"" value=""0"" max="""">
+      </div>
+      <br>
+      <div class=""volume_controls"">
+        <button onclick=""mute()"">
+          <i id=""mute"" class=""fa fa-volume-up""></i>
+        </button>
+        <input type=""range"" id=""volume"" oninput=""setVolume(this.value)"" min=""0"" max=""1"" step=""0.01"" value=""1"">
+      </div>
+    </div>
+
+    <div id=""playlist"" class=""hide"">
+      <span class=""text"">iu playlist</span>
+      <div class=""list-container"">
+
+        <div id=""list"" class=""scrollbar""></div>
+
+        <div class=""add-list"">
+          <input id=""sourceUrl"" type=""text"" placeholder=""enter audio url"" />
+          <button onclick=""addList()"">+</button>
+        </div>
+
+      </div>
+    </div>
+
+    <div class=""playlist-btn"">
+      <button id=""btn-random"" onclick=""random()"">
+        <i class=""fas fa-random""></i>
+      </button>
+      <button onclick=""togglePlaylist()"">
+        <i id=""playlist-btn"" class=""fa fa-list""></i>
+      </button>
+    </div>
+
+  </div>
+</div>
+
+
+

","

You are never reading your randomSong variable.

+

Just set currentSong to Math.floor(Math.random() * playlist.length) in that case:

+
if (
+    document.getElementById("btn-random").classList.contains("active")
+) {
+    currentSong = Math.floor(Math.random() * playlist.length);
+} else {
+    currentSong = ++currentSong % playlist.length;
+}
+playpause();
+
",html +"show label when hover over image

I want to create when the user hover over the image show something like this: +

+

how can I create like this with HTML and css +thanks, everyone!

","

You can show the text when you hover the container. Set the container to position:relative and the text to position:absolute.

+

+
+
.container{
+  border:1px solid black;
+  width:fit-content;
+  position:relative;
+}
+img{
+  width:200px;
+}
+.text{
+  display:none;
+  color:white;
+  background-color:red;
+  border-radius:20px;
+  padding:5px 10px;
+}
+.container:hover .text{
+  display:block;
+  position:absolute;
+  top:10px;
+  left:10px;
+}
+
<div class=""container"">
+  <img src=""https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png"" alt="""">
+  <div class=""text"">Hello</div>
+</div>
+
+
+

",html +"Content breaking when screen gets smaller bootstrap

This is not breaking as i want it to, i'd like for the image to be above the button but below the words when the screens size gets smaller, like phone size. Im new to bootstrap you i haven't tried much besides look in the docs but haven't found my solution. Could sonmeone please help me and point out where this issue is and why its occuring? Thanks!

+
        <div class="row">
+          <div class="col-sm-6 text-center h-80 text-center">
+              <p style="display: flex;
+              padding-inline-start: 140px;
+              justify-content: center;
+              margin: 0;
+              align-items: center;
+              text-align: center;
+              font-family: Dancing Script, 'sans serif';
+              width: 80%;
+              height: 50%;
+              color: white;
+              font-size: 80px">So you want to travel the world</p>
+              <p style=" display: flex;
+              color: white;
+              padding-inline-start: 60px;
+              width: 100%;
+              height: 20%;
+              font-size: 30px;">I do not have millions in the bank but I am making it happen without stress or worry.</p>
+              <button style="border: none;
+              color: white;
+              font-size: 30px;
+              background-color: rgba(201,115,116,255);
+              border-radius: 5px;
+              height: 60px;
+              cursor: pointer;
+              width: 400px;">Download!</button>
+          </div>
+          <div class="col-md-6  text-center">
+            <img src="images/Digital Download! (1).png" id="img-fluid" class="img-fluid" style="height: 700px; width: 1300px;" alt="">
+          </div>
+        </div>
+      </div>
+
","

The image can never be above the button as they are in separate columns.

+

+
+
<div class=""container"">
+<div class=""row"">
+          <div class=""col-sm"">
+              <p>So you want to travel the world</p>
+              <p>I do not have millions in the bank but I am making it happen without stress or worry.</p>
+          </div>
+          <div class=""col-sm"">
+            <img src=""images/Digital Download! (1).png"" id=""img-fluid"" class=""img-fluid"" style=""height:   700px; width: 700px;"" alt="""">
+          </div>
+          
+          <div class=""col-sm-12"">
+              <button> Download!</button>
+          </div>
+        </div>
+</div>
+
+
+

+

This is basically what you want right? The download button is below the text and image except on a small screen where they all stack? I would also follow the advice given above to move all your CSS into an external file and use the bootstrap utility classes.

+

I would also avoid using characters other than A-z/0-9 in your filenames if possible.

",html +"Why am I getting ""Form elements do not have associated labels"" even though there's a label associated with the input?

I have this code this react code

+
const Icon = styled.div`...`
+const ToggleInput = styled.input`...`
+const Lines = styled.label`...`
+const Line = styled.div`...`
+
+return (
+  <Icon>
+    <ToggleInput
+      id="NavigationMenuToggler"
+      name="NavigationMenuToggler"
+      role="button"
+      aria-controls={DOMConfig.aria.mobileMenu}
+      type="checkbox" />
+    <Lines for="NavigationMenuToggler" aria-controls="MobileNavigationMenu">
+      <Line />
+      <Line />
+      <Line />
+    </Lines>
+  </Icon>
+)
+
+

which generates this HTML

+
<div>
+  <input type="checkbox" id="NavigationMenuToggler" name="NavigationMenuToggler" role="button" aria-controls="MobileNavigationMenu" class="sc-jffIyK kktnkO">
+  <label for="NavigationMenuToggler" aria-controls="MobileNavigationMenu" class="sc-gSYCTC eRjJOo"></label>
+</div>
+
+

The label's for attribute is equal to the input's id. In lighthouse, however, I'm still seeing the "Form elements do not have associated labels" warning. Why is this happening?

","

The <label> is present and is correctly linked to the <input>, but it is completely empty. +As a consequence, it is like if it was not present.

+

Your label must have some text content, so that screen readers can say something when landing on the input. +If you don't want that text to be displayed on screen, you can send it off screen, by using the visually hidden text technique. +Alternatively, you can add a an attribute aria-label on the input, which must also be non-empty for the same reason.

",html +"How to show count of selected checkboxes in a table
Array.prototype.shuffle = function() {
+  let m = this.length, i;
+  while (m) {
+    i = (Math.random() * m--) >>> 0;
+    [this[m], this[i]] = [this[i], this[m]]
+  }
+  return this;
+}
+
+$('#select_random').on('click', function() {
+  if ($(this).prop('checked')) {
+    let minnum = 3, maxnum = 6
+    let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) + minnum)
+    //create our keys array
+    let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
+    keyArray.forEach((chk_i, i) => {
+      if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
+    })
+  } else {
+    $('.check').prop('checked', false);
+  }
+});
+
+const selectedElm = document.getElementById('selected');
+
+function showChecked(){
+  selectedElm.innerHTML = document.querySelectorAll('input[name=check]:checked').length;
+}
+
+document.querySelectorAll("input[name=check]").forEach(i=>{
+ i.onclick = () => showChecked();
+});
+
+

Using this script to select random amount of checkboxes in table. +Want to show count number of selected checkboxes count. +Tried some sample not working. Tried this example, not working for me. Tring to get result in div span area like below.

+
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
+<label>Select Random <input type='checkbox' id="select_random"></label>
+<div id="result">Total Number of Items Selected = <span id="selected">0</span></div>
+ 
+<div class='cb'>
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+  <input type="checkbox" name="check[]" class="check"> checkbox <br />
+
","

Solution

+
let checked = $(".check:checked");
+
+

in your case :

+
$(".check:checked").length // will return count of checked checkboxes;
+
+

i hope it was useful

",html +Set min/max value for input field with CSS

Is there a way to set the min/max values of a HTML input form based on the ID with CSS?

,"

You can do this by getting the input's DOM node: +Every time the input loses focus, determine whether the value is within the range you specified, if not, correct it and prompt

+

+
+
function change(){
+        const searchBox = document.getElementById(""myInput"");
+       if(searchBox.value>100){
+      searchBox.value=100
+      alert(""the max value is 100"")
+      }
+      if(searchBox.value<0){
+        searchBox.value=0
+        alert(""the min value is 0"")
+      }
+    }
+
<input type=""text"" value="""" id=""myInput"" onBlur=""change"">
+
+
+

+

If you want to change the style by changing the ID: +Then you can first get his DOM through class, and then you can forcefully modify his id according to DOM.id

+

But it is not recommended to do so

",html +"Show/hide div in JS

I'm pretty fresh to JS.

+

For n amount of bar divs I have n amount foo divs. By clicking on bar[1], I want foo[1] to show or hide. The same goes for bar[2]/foo[2], bar[5]/foo[5], bar[3]/foo[3],...bar[n]/foo[n] in no exact order.

+

With this code I am able to show and hide, but only all of the divs at the same time. What should I change, so that I am able to hide or show only one of the divs?

+

+
+
function getContent() {
+  var x = document.getElementsByClassName(""foo"");
+  for (var i = 0; i < x.length; i++) {
+    if (x[i].style.display === ""none"") {
+      x[i].style.display = ""block"";
+    } else {
+      x[i].style.display = ""none"";
+    }
+  }
+}
+
+document.querySelector("".bar"").addEventListener(""click"", getContent);
+
.foo {
+  display: none;
+}
+
+.bar {
+  padding: 5px;
+  display: block;
+}
+
+
+

+
<div>
+     <div class="bar" onclick="getContent()">bar</div>
+</div>
+<div class="foo">foo</div>
+
","

No need to use JS here, HTML is more powerful than you think: if you want to show-or-hide information, the <details> element's got you covered.

+

+
+
.all-or-nothing summary {
+  display: inline-block;
+  cursor: pointer;
+}
+
<details class=""all-or-nothing"">
+  <summary>Toggle all divs</summary>
+  <div>
+    The first div
+  </div>
+  <div>
+    The second div
+  </div>
+    <div>
+    The third div
+  </div>
+</details>
+
+
+

",html +"How move leafle control layers to above map?

I have a leaflet map, I use this Leaflet-Ruler plugin and add ruler control layer to map in this link. I want move ruler control layers to above map as shown as:

+

+

How Can I do?

","

Just need move one DIV element inside another DIV with JQuery $("#source").appendTo("#destination"); for example I move DIV ruler control that class name was leaflet-ruler move to the my special DIV <div id='move-control-layer-ruler-to-here'></div> .

+

You can move any control layer leaflet to any DIV.

+

This link is jsfiddle solved my problem.

+

]

",html +"How do i make my LinkedIn badge transition smoothly fade in and out?

How do I make my LinkedIn badge transition smoothly fade in and out?

+

I know the basics of Web Developing and I have been using and learning HTML and CSS on visual studio code for 3 or 4 days, recently I was creating a personal website which is still in the making and I came across a confusion in which the transition command of CSS is not working for me I don't know why I want the LinkedIn badge to Fade in and Fade out in approximately 2 or 3 seconds smoothly but it is not letting me.

+

This is the Code: https://jsfiddle.net/JadeDoe/1jvs6rhy/9/

+

CSS :

+
    .badge-base {
+        display: none;
+        position: absolute;
+        top: 24px;
+        left: 16%;
+
+        transition: 1s;
+    }
+
+    .Heading:hover+.badge-base {
+        display: inline;
+    }
+
+    .Heading:hover .badge-base,
+    .badge-base:hover {
+        display: block;
+    }
+
","

You can't transtion display none to block. You can however do it using opacity (although it's not the exact thing because the element would still take up space)

+

+
+
.badge-base {
+  position: absolute;
+  top: 24px;
+  left: 40%;
+  transition: 1s;
+  opacity: 0;
+  pointer-events: none;
+}
+
+.Heading:hover+.badge-base {
+  display: inline;
+  opacity: 1;
+  pointer-events: all;
+}
+
+.Heading:hover .badge-base,
+.badge-base:hover {
+  display: inline;
+  opacity: 1;
+  pointer-events: all;
+}
+
<body>
+  <div>
+    <h1 class=""Heading"">Jane D Walker</h1>
+    <div class=""badge-base LI-profile-badge"" data-locale=""en_US"" data-size=""medium"" data-theme=""dark"" data-type=""VERTICAL"" data-vanity=""g-mail-assistance-704528251"" data-version=""v1"">
+      <a class=""badge-base__link LI-simple-link"" href=""https://pk.linkedin.com/in/g-mail-assistance-704528251?trk=profile-badge""></a>
+    </div>
+  </div>
+
+  <script src=""https://platform.linkedin.com/badges/js/profile.js"" async defer type=""text/javascript""></script>
+
+</body>
+
+
+

",html +"How to I get a specific part of an element when clicking anywhere in that element with Vanilla Javascript (NO JQuery)?

I want to get from the following html "only" the number 0 or the number 1 depending on which table row I click (FYI: there will be many rows with different numbers):

+ + +
<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <script src="../static/js/test.js"></script>
+    <title>Document</title>
+</head>
+<body>
+  <table>
+    <tbody id="toAppend">
+      <tr class="newEle" onclick="setUnstakeNumber()">
+        <th>
+          "Stake No"
+          <div class="d-inline-block"></div>
+        </th>
+          <td class="p3 unstakeIdx">0</td>
+          <td class="p3">Joo: 1</td>
+          <td class="p3">9/22/2022, 5:02:30</td>
+        </tr>
+      <tr class="newEle" onclick="setUnstakeNumber()">
+        <th>
+          "Stake No"
+          <div class="d-inline-block"></div>
+        </th>
+          <td class="p3 unstakeIdx">1</td>
+          <td class="p3">Joo: 2</td>
+          <td class="p3">9/22/2022, 5:04:18</td>
+        </tr>
+    </tbody>
+  </table>
+</body>
+</html>
+
+

This is how it looks visually:

+

+

This is how the html looks in console view:

+

+

This is my javascript function:

+
function setUnstakeNumber() {
+  let selection = document.getSelection();
+  let finalSelection = selection.anchorNode.data
+  let activeTextarea = document.activeElement;
+  let parent = document.documentElement.parentElement; // Returns the <html> element 
+  console.log(selection);
+  console.log(finalSelection);
+  console.log(parent);
+  console.log(activeTextarea);
+}
+
+

But none of the above works.

+

The closest one is the finalSelection, but I need to really click exactly on top of the number I want rather then anywhere in its row.

+

How do I get the number by clicking anywhere in its element?

+

So If I would click anywhere in the first row I would get the number 0 and if I would click anywhere in the second row I would get the number 1 with only Vanilla Javascript (No JQuery)?

","

Try this!

+

+
+
function setUnstakeNumber() {
+let selection = document.getSelection();
+// get selected row
+let selectedRow = selection.anchorNode.parentNode.parentNode;   
+let index = selectedRow.childNodes[3].innerText;
+console.log(index);
+}
+
<html>
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <script src=""../static/js/test.js""></script>
+    <title>Document</title>
+</head>
+<body>  
+  <table>
+    <tbody id=""toAppend"">
+      <tr class=""newEle"" onclick=""setUnstakeNumber()"">
+        <th>
+          ""Stake No""
+          <div class=""d-inline-block""></div>
+        </th>
+          <td class=""p3 unstakeIdx"">0</td>
+          <td class=""p3"">Joo: 1</td>
+          <td class=""p3"">9/22/2022, 5:02:30</td>
+        </tr>
+      <tr class=""newEle"" onclick=""setUnstakeNumber()"">
+        <th>
+          ""Stake No""
+          <div class=""d-inline-block""></div>
+        </th>
+          <td class=""p3 unstakeIdx"">1</td>
+          <td class=""p3"">Joo: 2</td>
+          <td class=""p3"">9/22/2022, 5:04:18</td>
+        </tr>
+    </tbody>
+  </table>
+</body>
+</html>
+
+
+

+

First get the selected row and then select the which includes the index.

",html +"Limit characters user can enter in input in django view OR html?

I had various occasions where I wanted to but couldn’t limit characters user types in html input. For example what would I do if I would only want numbers and letters? No other like £-“<#>{[. And what would I do if I would want them to only enter uppercase letters? +Thanks for help:)

","

There's a couple of ways you can do this, through Django Form validation, HTML attributes or Javascript.

+

Django Validation + HTML attributes

+
class TheForm(forms.ModelForm):
+    class Meta:
+        model = ModuleChoice
+        fields = (
+            'text',
+            )
+
+    def __init__(self,  *args, **kwargs):
+        super(TheForm, self).__init__(*args, **kwargs)
+
+        # HTML attributes:
+            # Max Length, user physically couldn't type more than 35
+            # some fields also can have the `pattern` attribute which allows you to have REGEX
+        self.fields['text'].widget.attrs={'class': 'form-control', 'maxlength': '35'}
+
+
+    def is_valid(self):
+        valid = super(TheForm, self).is_valid()
+        if not self.cleaned_data.get('text'):
+            self.add_error('text', 'text needs a Value')
+            valid = False
+
+        invalidChars = [ '£', '-', '“', '<', '#', '>', '{', '[' ]
+        if any([c in self.cleaned_data.get('text') for c in invalidChars]):
+            # error ( {field}, {msg} )
+            self.add_error('text', 'These £-“<#>{[ characters are Illegal.')
+            valid = False
+
+        if self.cleaned_data.get('text').islower():
+            self.add_error('text', 'All Letters Must be all Upper Case.')
+            valid = False
+
+        # you could also do Regex:
+        import re
+        if re.findall('^Nealium.*Uncool$', self.cleaned_data.get('text')):
+            self.add_error('text', 'You cannot say Nealium is Uncool.')
+            valid = False
+
+        # the sky is the limit..
+        if The.objects.filter(text=self.cleaned_data.get('text')).count():
+            self.add_error('text', 'Duplicate Text.')
+            valid = False
+
+        return valid
+
+

you would then put, below, in your template and if you re-render the page with the invalid form it'll show them.

+
{% if form.errors %}{{form.errors}}{% endif %}
+
+

Or you can use, below, so access your errors in the template

+
print(form.errors)
+print(form.errors.as_data())
+
+

Doing it through Javascript is very Similar to the is_valid() in Django Forms, you'd just override the default form.save event and add a few if statements above submitting it

+
+

Edit

+

Yes, you could do it in the View- Specifically in the POST:

+
def theview(request):
+    if request.method == 'POST'
+        valid = True
+        text = request.POST.get('text')
+
+        invalidChars = [ '£', '-', '“', '<', '#', '>', '{', '[' ]
+        if any([c in text for c in invalidChars]):
+            msg = 'These £-“<#>{[ characters are Illegal.'
+            valid = False
+
+        # other validation
+
+        if valid:
+            The.object.create(text=text)
+            render(request, 'success.html')
+        # not valid
+
+

Or you could do it in the Template if you're manually rendering the Form fields

+
<form method="post">
+    <input id="id_text" name="text" maxlength="35"/>
+    <submit>Submit</submit>
+</form>
+
+
+

but if you are rendering your forms in the Template like:

+
<form method="post">
+    {% csrf_token %}
+    {{ form }}
+    <input type="submit" value="Submit">
+</form>
+
+

or:

+
<form method="post">
+    {% csrf_token %}
+    {{ form.text }}
+    <input type="submit" value="Submit">
+</form>
+
+

and your View looks like:

+
def theview(request):
+    form = TheForm()
+
+    if request.method == 'POST'
+        form = TheForm(request.POST)
+        if form.is_valid():
+            form.save()
+
+            render(request, 'success.html')
+      
+    data = {
+        'form': form,
+    }
+    return render(request, 'form.html', data)
+
+

You might as well do it through the Form object (which was the 1st example)

",html +"How to adjust margin-top (mt-) based on screen height using HTML and Tailwind CSS?

I'm building a simple HTML/Tailwind CSS site.

+

Margin-top of "md:mt-52" (generally) works well on screens greater than 767px wide, such as an Nexus 10 tablet in portrait mode (viewport = 800px x 1280px). Please see the screenshot immediately below: +

+

Margin-top of "mt-12" works well for displaying the first line of text where I want it on screens smaller than 640px wide, such as an iPhone 11 Pro in portrait mode (viewport = 375px x 812px). Please see the screenshot immediately below: +

+

Problem: When the above iPhone 11 Pro it rotated 90 degrees, to landscape mode, the viewport width becomes 812px, so the screen size becomes "md" and "md:mt-52" is applied, pushing the text below where it's visible. Please see the screenshot immediately below: +

+

In the case immediately above, when screen height is so much smaller, I'd want "mt-16" to apply. How can I do this with HTML and Tailwind CSS?

+

Thanks for any help!

","

You can define a custom breakpoint in the tailwind.config.

+

For example:

+
extend: {
+  screens: {
+    // ml stands for 'mobile landscape'
+    ml: {
+      raw: '(min-width: 480px) and (max-width: 960px) and (max-height: 480px)',
+    },
+  },
+
+

And then use that as you would with other breakpoints, like +class="mt-12 ml:mt-16 md:mt-52"

",html +"Align a line with the baseline of a text

I have some text and a line between it. I would like that the line is align with the baseline of the text. +Now to create the line I use the container border but I think this is not the right way to do it.

+

Here the code:

+

+
+
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto:400,500,600&display=swap');
+
+body, html {
+  margin: 0; 
+  padding: 0;
+  font-family: 'Roboto mono', sans-serif;
+}
+
+.root {
+  width: 100vw;
+}
+
+.container {
+  color: black;
+  display: flex;
+  column-gap: 10px;
+  width: 100%;
+  font-size: 16px;
+}
+
+.second-text {
+  color: tomato;
+}
+
+.line {
+  display: flex;
+  flex-grow: 1;
+  border-bottom: 1px solid tomato;
+}
+
<div class=""root"">
+  <div class=""container"">
+    <div>Etiam felis neque, suscipit aliquet elit</div>
+    <div class=""second-text"">est quis</div>
+    <div class=""line""></div>
+    <div class=>20.45</div>
+  </div>
+</div>
+
+
+

+

The result is:

+

+

but the red line should be some pixel above, aligned with the baseline of the text.

","

You can solve your problem by giving your container the below property:

+
align-items: baseline;
+
",html +"how to rotate a single element that inisde another rotating element

i have a circle to contain some spinning elements. i have a div.tool contain a svg in circle. While a rotate div.tool, the image inside it also rotating, but i want that image remain straight. how can i fix that

+

HTML

+
<div class="circle">
+        <div class="tool" id="css"> <img src="css.svg"></div>
+    </div>
+
+
+

CSS

+

+.circle{
+    position: relative;
+    background-color: #f5f5ff;
+    border-radius: 50%;
+    width: 500px;
+    height: 500px;
+    border: 2px solid black;
+
+}
+
+.tool{
+    position: absolute;
+    height: 100%;
+    width: 100%;
+    text-align: center;
+    --rotation:0;
+    transform: rotate(var(--rotation));
+    padding-top: 10px;
+    
+}
+
+img{
+    width: 75px;
+    transform: rotate(calc(-1 * var(--rotation)));
+}
+
+#css{
+    --rotation: 0deg;
+    --spin-initial: 0;
+    animation: spin 30s linear infinite;
+}
+
+@keyframes spin {
+    from{
+        transform: rotate(calc(var(--spin-initial) * 1deg));
+    }
+    to{
+        transform: rotate(  calc(calc(360 + var(--spin-initial))*1deg)  );
+    }
+}
+
","

Rotate the image the other way.

+

+
+
.circle {
+  position: relative;
+  background-color: #f5f5ff;
+  border-radius: 50%;
+  width: 400px;
+  height: 400px;
+  border: 2px solid black;
+}
+
+.tool {
+  position: absolute;
+  height: 100%;
+  width: 100%;
+  text-align: center;
+  --rotation: 0;
+  transform: rotate(var(--rotation));
+  padding-top: 10px;
+}
+
+img {
+  width: 75px;
+  transform: rotate(calc(-1 * var(--rotation)));
+  animation: spin 30s linear infinite reverse;
+}
+
+#css {
+  --rotation: 0deg;
+  --spin-initial: 0;
+  animation: spin 30s linear infinite;
+}
+
+@keyframes spin {
+  from {
+    transform: rotate(calc(var(--spin-initial) * 1deg));
+  }
+  to {
+    transform: rotate(calc(calc(360 + var(--spin-initial)) * 1deg));
+  }
+}
+
<div class=""circle"">
+  <div class=""tool"" id=""css""> <img src=""https://clipartix.com/wp-content/uploads/2017/06/Free-simple-basketball-clip-art.png""></div>
+</div>
+
+
+

",html +"How grow a text area height on top when it overflows

I found the code below but the text area height grows at the bottom.

+

backspace increases value of scrollheight

+

How could I grow it from top to up direction?

+

It is for a chat application I am building, and this would be the typing area.

+

I spent some time on the net looking for the solution but it apparently is not that easy.

+

Edit: Looking at how the snipped behaves here in stackoverflow, I am thinking now that it may be related with how the parent wrapper is set on css, but still do not know how to fix it.

+

+
+
document.querySelectorAll('textarea').forEach( element => {
+  element.style.height = `${element.scrollHeight}px`;
+  element.addEventListener('input', event => {
+    event.target.style.height = 'auto'; 
+    event.target.style.height = `${event.target.scrollHeight}px`;
+  })
+})
+
/* style.css */
+main, header {
+  max-width: 600px;
+  margin: auto;
+}
+
+textarea {
+  font-family: 'Times New Roman', Times, serif;
+  font-size: 1em;
+  border-style: hidden;
+  outline: none;
+  padding: 0.1em;
+  margin: none;
+  resize: none;
+  width: 80%;
+  border-radius: 0.2em;
+  border: 1px solid #EEE;
+}
+
+textarea:focus {
+  border: 1px solid #DDD;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""utf8"" />
+  <meta name=""viewport"" content=""width=device-width"" , initial-scale=""1.0"" />
+  <title>Data Management</title>
+  <link href=""style.css"" rel=""stylesheet"" type=""text/css"">
+  <script type=""module"" src=""script.js"" defer></script>
+</head>
+
+<body>
+  <header>
+    <h1>Growing textarea</h1>
+  </header>
+  <main>
+    <p><textarea class=""data p"" id=""article"" ></textarea></p>
+  </main>
+</body>
+
+</html>
+
+
+

","

For expanding the textarea to the top you can use position:absolute and bottom: 0 in a container with position:relative. This way the text-area will always stick to the bottom of the container with 0 margin.

+

Also, you can set the default rows of the textarea to 1 to look like a text input when the text fits inside one line:

+
<textarea rows="1"></textarea>
+
+

+
+
document.querySelectorAll('textarea').forEach( element => {
+  element.style.height = `${element.scrollHeight}px`;
+  element.addEventListener('input', event => {
+    event.target.style.height = 'auto'; 
+    event.target.style.height = `${event.target.scrollHeight}px`;
+  })
+})
+
/* style.css */
+main, header {
+  max-width: 600px;
+  margin: auto;
+}
+
+textarea {
+  font-family: 'Times New Roman', Times, serif;
+  font-size: 1em;
+  border-style: hidden;
+  outline: none;
+  padding: 0.1em;
+  margin: none;
+  resize: none;
+  width: 80%;
+  border-radius: 0.2em;
+  border: 1px solid #EEE;
+  position:absolute;
+  bottom:0
+}
+
+main{
+  position: relative;
+}
+
+textarea:focus {
+  border: 1px solid #DDD;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""utf8"" />
+  <meta name=""viewport"" content=""width=device-width"" , initial-scale=""1.0"" />
+  <title>Data Management</title>
+  <link href=""style.css"" rel=""stylesheet"" type=""text/css"">
+  <script type=""module"" src=""script.js"" defer></script>
+</head>
+
+<body>
+  <header>
+    <h1>Growing textarea</h1>
+  </header>
+  <main>
+    <textarea rows=""1"" class=""data p"" id=""article""></textarea>
+  </main>
+</body>
+
+</html>
+
+
+

",html +"Stop the page to refresh after the form button is clicked and error is shown

I have seen other questions too but i want to stop my page from refreshing after signup form is filled and with validation from php it shows an error in a span. or not refreshing the form data or not clearing the form data will also work. I just want the form data to be exact as it is but the error to be shown. please find the code

+
  <form action="signup.php" id="form" method="POST" onsubmit="">
+  <a style="text-decoration:none ;" href="index.php"><h1 >Mero <span>Notes</span></h1></a>
+  <h3>Register Your Account</h3>  
+  <?php 
+      echo '<p style="margin-top:10px;color:red;">'.$message.'</p>';
+       ?>        
+        <p id="validationSpan"></p>
+      
+        <input placeholder="Full Name" type="text" required="required" name="fullName" value=""/>
+        <input placeholder="Email" type="text" required="required" name="email" />
+        <input placeholder="Password" type="password" name="password" required="required" id="id_password" minlength="8" onkeyup="passValidation();"/>
+        <input placeholder="Confirm Password" type="password" name="conPassword" required="required" id="id_conPassword" onkeyup="passValidation();"/>
+        <input placeholder="Contact" type="number" required="required" name="contactNum" />
+        <button type="submit" class="regButton" type="submit" value="Sign Up" id="regBtn" onclick="return passValidationAlert()">SignUp </button>
+    <h4 style="text-align: right; color:black;font-size:12px;">
+      Already Have an Account ?
+      <a class="buttomLogin" href="index.php">Login here</a>
+    </h4>
+  </form>
+
+ + +

The php code looks like this

+
if(mysqli_num_rows($result)>0){
+  $_SESSION['error']=true;
+    $message='The Entered Email is Already Taken'; 
+      }
+        elseif($password!=$confirmPassword){
+           $message='Password did not match';
+      }
+      {
+           $epassword=password_hash($password,PASSWORD_BCRYPT);
+            $sql = "INSERT INTO signupdatabasemn (fullName, email, password, phoneNumber) 
+              VALUES ( '$fullName', '$email', '$epassword', $phoneNumber) ";
+                $result2= mysqli_query($conn, $sql);
+
+
+ if ($result2>0) {
+    header('Location: /demosite3fnl/index.php');
+  } else {
+  }
+ 
+}
+?>
+
","

The simplest solution would be to put the post data in the input value so that when page get refreshed, it stays where it should be. In example:

+
<input placeholder="Email" type="text" required="required" name="email" value="<?= $_POST['email'] ?>"/>
+
+

Updated. Just seen your updated code. Looks like form is sending request to different php file. In this case, try return posted data using get. See more here

",html +"Why firefox console showing unnecessary things

i want just to see the content of the div but firefox is showing me a lot of null and non unnecessary attributes. please help me to hide those attibutes??

+

enter image description here

","

That's part of the page itself. Using Chrome to post, but using Firefox I get that thing on a test website:

+

+

On Chrome the same thing happens:

+

+

Source:

+
<!DOCTYPE html>
+<html>
+    <body>
+        <div id="this-is-an-id" class="this-is-a-class" custom-attribute="this-is-a-custom-attribute">This is the content of the div</div>
+    </body>
+</html>
+
",html +"Bootstrap postion Button Right

this is my source code:

+
<p class="h1 p-3 mb-2 bg-danger text-white text-danger">Lagerbestand unter Mindestmenge! </p>
+<br />
+
+<div class="border  text-center">
+<p class="h5 text-center">Durch Ihre Entnahme fällt der Lagerbestand unter die vom Administrator festgelegte Mindestmenge! </p>
+<br>
+<p class="h5">Sie sind dazu angehalten das Order-Managment zu Informieren! Mach Sie das indem Sie auf den Nachfolgenden Button drücken </p>
+</div>
+
+<br />
+<button class="btn btn-warning btn-lg" onclick="sendMail()">Informieren</button>
+<a asp-controller="Inventar" asp-action="EntnahmeSuccess" id="weiter" class="btn btn-primary btn-lg">Weiter</a>
+
+

and here is a photo where i want my button. I am literally not able to place it there :( Can you help?

","

Use Bootstrap's Flex classes with space-between:

+
    +
  • d-flex --> display: flex
  • +
  • justify-content-between --> justify-content: space-between
  • +
+
<div class="d-flex justify-content-between">
+  <button class="btn btn-warning btn-lg" onclick="sendMail()">Informieren</button>
+  <a asp-controller="Inventar" asp-action="EntnahmeSuccess" id="weiter" class="btn btn-primary btn-lg">Weiter</a>
+</div>
+
+
+

+
+
<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css"" rel=""stylesheet""/>
+<p class=""h1 p-3 mb-2 bg-danger text-white text-danger"">Lagerbestand unter Mindestmenge! </p>
+<br />
+
+<div class=""border  text-center"">
+<p class=""h5 text-center"">Durch Ihre Entnahme fällt der Lagerbestand unter die vom Administrator festgelegte Mindestmenge! </p>
+<br>
+<p class=""h5"">Sie sind dazu angehalten das Order-Managment zu Informieren! Mach Sie das indem Sie auf den Nachfolgenden Button drücken </p>
+</div>
+
+<br />
+
+<div class=""d-flex justify-content-between"">
+  <button class=""btn btn-warning btn-lg"" onclick=""sendMail()"">Informieren</button>
+  <a asp-controller=""Inventar"" asp-action=""EntnahmeSuccess"" id=""weiter"" class=""btn btn-primary btn-lg"">Weiter</a>
+</div>
+
+
+

",html +"Force VS Code to Syntax Highlight a part of a file differently

My most current HTML/CSS/TS project is being done with HTML components. And, in that context, it's pretty common to use strings to set up the inner HTML of components. So we have stuff like this everywhere:

+
this.innerHtml = `
+  <p>Blah blah</p>
+`
+
+

Since the syntax highlighter only sees a string, everything within it is typically green or whatever other color. But I wish there was a way of making it highlighted as HTML code. Is there a way? Is there maybe a VS Code Extension for it?

+

I imagine a VS Code Extension could work by putting a comment on the line before (or two) the HTML code, something like this:

+
// extension:begin:html
+this.innerHtml = ` 
+  <p>Blah Blah</p>
+`
+// extension:end
+
","

As @epascarello pointed out, the es6-string-html mostly does what I wanted.

+

The only thing I would change is I would have HTML as some sort of default in the settings, since, in my project, that's the only thing I need.

",html +"How to use class binding with font-awesome icon?

I'm trying to display two different icons based on the value of a variable. I want to show up arrow if it's true or down arrow if it's false. But it seems like it's not working at all and I can't figure out why. Here's the code-

+
<div class="custom-class" (click)="changeValue()">
+<i class="fa fa-lg " [ngClass]="isValue ? 'fa-chevron-circle-up' : 'fa-chevron-circle-down'"></i>
+</div>
+
+

My component class has something like this-

+
private isValue: boolean = true;
+changeValue() {
+    this.isValue = !this.isValue;
+  }
+
+

I don't know why it doesn't work properly. I'm using font-awesome v6 and angular 14. Can anyone help me with this?

","

I switched to angular-fontawesome and it seems to be working with that. +ngClass does not work with @fortawesome/fontawesome-free@5.9.0 correctly because the <i> dom is replaced with an <svg> dom. +Here's the link to the github issue.

",html +".getBoundingClientRect() not changing values on scroll

I am trying to make a side pagination bar, and I want it to change colors when different parts of the page come into view, so I am using the .getBoundingClientRect in javascript. However, everytime I scroll, the position of the element is the same in the console logs, even if I have scrolled all the way to the bottom.

+

Can someone help me so that the values change when they are meant to?

+

+
+
var aboutPage = document.getElementById('about');
+var aboutBounding = aboutPage.getBoundingClientRect();
+
+window.addEventListener(""scroll"", () => {
+
+    console.log(aboutBounding);
+
+    if (
+        aboutBounding.top >= 0 &&
+        aboutBounding.left >= 0 &&
+        aboutBounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
+        aboutBounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
+    ) {
+        console.log('In the viewport!');
+    } else {
+        console.log('Not in the viewport... whomp whomp');
+    }
+})
+
/* SIDE PAGEINTATION */
+
+.side-pagination {
+  position: fixed;
+  top: 50%;
+  left: 72px;
+  height: 138px;
+  width: 24px;
+  transform: translateY(-50%);
+  z-index: 10;
+}
+
+.page-circle {
+  width: 24px;
+  height: 24px;
+  border-radius: 50%;
+  background-color: #bcbcbc;
+  cursor: pointer;
+}
+
+.page-circle.menuactive {
+  background-color: var(--secondary-clr);
+}
+
+.page-circle:nth-child(1) {
+  margin-bottom: 14px;
+}
+
+.page-circle:nth-child(2) {
+  margin-bottom: 14px;
+}
+
+.page-circle:nth-child(3) {
+  margin-bottom: 14px;
+}
+
+.landing-main-body {
+  position: absolute;
+  top: 0%;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  z-index: 2;
+  background-color: gray;
+}
+
+.work-main-body {
+  position: absolute;
+  top: 200%;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  z-index: 2;
+  background-color: pink;
+}
+
+.about-main-body {
+  position: absolute;
+  top: 100%;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  z-index: 2;
+  background-color: purple;
+}
+
<div class=""side-pagination"">
+  <div class=""page-2 page-circle""></div>
+  <div class=""page-3 page-circle""></div>
+  <div class=""page-4 page-circle""></div>
+</div>
+<div class=""landing-main-body"">
+</div>
+<div class=""about-main-body"" id=""about"">
+
+</div>
+<div class=""work-main-body"" id=""work"">
+
+</div>
+
+
+

+

EDIT: I will try using IntersectionObserver in the morning, stay put till then :D.

","

When you store the getBoundingClientRect value outside the scroll event listener, you're only storing the rect value once. In other words, it won't update as the scroll event fires.

+

You need to read the getBoundingClientRect value inside the scroll event listener like so:

+
var aboutPage = document.getElementById('about');
+// var aboutBounding = aboutPage.getBoundingClientRect(); <-- Don't read it here
+
+window.addEventListener("scroll", () => {
+
+    var aboutBounding = aboutPage.getBoundingClientRect(); // <-- Read it inside the scroll listener
+    console.log(aboutBounding);
+
+    if (
+        aboutBounding.top >= 0 &&
+        aboutBounding.left >= 0 &&
+        aboutBounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
+        aboutBounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
+    ) {
+        console.log('In the viewport!');
+    } else {
+        console.log('Not in the viewport... whomp whomp');
+    }
+})
+
+

As an alternative approach you might want to consider using Intersection Observer to check when an element is in view or not. I find its API easy to understand and simpler to use than the scroll event listener with getBoundingClientRect approach.

",html +"How do I change the width of the hr Element, if the input is focused but in an other span?

I am using Telerik to generate a textbox. Now I would like to equip this with an animation.

+

The problem is that Telerik wraps a span around the input, so I don't know how to change the hr element when the input is focused.

+

My Code:

+

+
+
span.inputanimation {
+    width: 100%;
+}
+
+// Here is what i dont know how to do !
+span.inputanimation > .input > input:focus hr.underline {
+    width: 100%;
+}
+
+hr.underline {
+    width: 0%;
+    transition: width 0.5s ease-in-out;
+    background-color: #17e13f;
+    height: 2px;
+    border: none;
+    margin-top: 2px;
+    
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Document</title>
+    <link href=""styles.css"" rel=""stylesheet"" type=""text/css""></style>
+</head>
+<body>
+
+<!-- Generated with TelerikTextBox -->
+<span class=""inputanimation"">
+  <span class=""input"">
+    <input id=""Vorname"">
+</span>
+<hr class=""underline"">
+</span>
+
+</body>
+</html>
+
+
+

+

I removed some of the CSS classes and HTML Properties so it is better to look at.

+

My Telerik Code:

+
<span class="inputanimation">
+        <TelerikTextBox @bind-Value="Value"
+                        Id="@Id"
+                        PlaceHolder="@Label"
+                        Class="input">
+        </TelerikTextBox>
+        <hr class="underline" >
+
+    </span>
+
","

Looking at various posts on hover and focus, it seems that the two elements have to be related, such as child or sibling. Which would be easy if you weren't using Telerik.

+

One solution is to use javascript. I am using ids to show the concept.

+

+
+
let search = document.getElementById('Vorname');
+let ruler = document.getElementById('Ruler');
+
+search.onfocus = function(){ ruler.style.width = '100%'; }
+
span.inputanimation {
+    width: 100%;
+}
+
+
+hr.underline {
+    width: 0%;
+    transition: width 0.5s ease-in-out;
+    background-color: #17e13f;
+    height: 2px;
+    border: none;
+    margin-top: 2px;
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Document</title>
+    <link href=""styles.css"" rel=""stylesheet"" type=""text/css""></style>
+</head>
+<body>
+
+<!-- Generated with TelerikTextBox -->
+<span class=""inputanimation"">
+  <span class=""input"">
+    <input id=""Vorname"">
+</span>
+<hr id=""Ruler"" class=""underline"">
+</span>
+
+</body>
+</html>
+
+
+

+

Another solution is to use focus-within

+

+
+
span.inputanimation {
+    width: 100%;
+}
+
+span.inputanimation:focus-within hr.underline {
+    width: 100%;;
+}
+
+hr.underline {
+    width: 10%;
+    transition: width 0.5s ease-in-out;
+    background-color: #17e13f;
+    height: 2px;
+    border: none;
+  margin-top: 2px;}
+  
+ 
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Document</title>
+    <link href=""styles.css"" rel=""stylesheet"" type=""text/css""></style>
+</head>
+<body>
+
+<!-- Generated with TelerikTextBox -->
+<span class=""inputanimation"">
+  <span class=""input"">
+    <input id=""Vorname"">
+ </span>
+   <hr id='Ruler' class=""underline"">
+</span>
+
+</body>
+</html>
+
+
+

",html +"How to select first two children of an element without :nth pseudo-classes?

I am currently preparing myself for a regional championship in web development for high-school students. Preparation tasks are one the championships website to solve. I have the following HTML code:

+
<h2>Task 5</h2>
+<article id="task-5">
+    <div class="marble"></div>
+    <div class="marble"></div>
+    <section>
+        <div class="marble" data-target></div>
+        <div class="marble" data-target></div>
+        <section>
+            <div class="marble"></div>
+            <div class="marble"></div>
+        </section>
+    </section>
+</article>
+
+

My goal is to select the divs with the marble class marked with data-target, but under following requirements:

+
    +
  • I am not allowed to use these CSS pseudo-classes or CSS selectors: +
      +
    • :nth-child
    • +
    • :nth-last-child
    • +
    • :nth-of-type
    • +
    • :nth-last-of-type
    • +
    • [data-target]
    • +
    • nor any use of + or ~
    • +
    +
  • +
  • Only one selector is allowed.
  • +
+

I have tried the following selector, but it still selects the third div (the one not marked with data-target):

+
#task-5 section > div:not(:last-child):not(:is(:first-child:is(:last-child)))
+
+

Can you please help me. Thank you very much

","

First you can select the section that has another section as a descendant. Then you can select the divs that are not descendants of a section which is the descendant of a section.

+

+
+
section:has(section) div:not(section section div) {
+  width: 100px;
+  height: 100px;
+  background: red;
+}
+
<h2>Task 5</h2>
+<article id=""task-5"">
+  <div class=""marble"">1</div>
+  <div class=""marble"">2</div>
+  <section>
+    <div class=""marble"" data-target>3</div>
+    <div class=""marble"" data-target>4</div>
+    <section>
+      <div class=""marble"">5</div>
+      <div class=""marble"">6</div>
+    </section>
+  </section>
+</article>
+
+
+

+

Note: currently :has is supported on Firefox only if a flag is set.

",html +"How to dynamically extract the last digits in a flask website URL to set a path to it using python?

Okay so I'm working on my project and I want the user to be able to visit other users profile so I'll have a link in the HTML page <a href = "/user/5"> User X </a> and I want them to be redirected to @app.route("/user/" and having user_id at the end of that path in python using flask which user_id is the 5 but that code doesn't work, is there a way to extract the number after the /user/ so when he clicks on it from an HTML page it would send him to @app.route("/user/5") and save the 5 in a variable in the python code? so later I can use the 5 in my SQL code to extract the info I need, then when he goes into the site the URL would be something.com/user/5 and the user would be able to to change the 5 to 6 in the url and it would still work taking him to a user number 6 without me having to hard-code a path to every single user?

","
@app.route("/user/<int:user_id>"
+def users(user_id):
+    print(user_id)  # its the url parameter - prints 5 in case of "/user/5"
+
",html +"How would I be able to extract the words in my label, including the space in between words but not any additional spaces afterwards?

I'm currently lost as to how I would be able to properly use the label in my HTML as variables for my JS.

+
[HTML]
+<div> <!--Main Toppings-->
+  <label for = "mtop"> Main Toppings: </label>
+  <select name="mainToppings" id = "toppingsoption" required>
+  <option disabled selected id = 'emptyoption'> -- select an option -- </option>
+  <option id='pepperoniOverload' class = "mtopchoice">Pepperoni Overload - &#8369 100</option>
+  <option id='hawaiian' class = "mtopchoice">Hawaiian - &#8369 50</option>
+  <option id='meatOverload' class = "mtopchoice">Meat Overload - &#8369 125</option>
+  </select>
+</div>
+
+[JavaScript]
+var toppings = document.getElementById("toppingsoption");
+    if (toppings.options[toppings.selectedIndex].id == 'emptyoption') {
+        var toppingsName = '';
+        var toppingsValue = 0;
+    } else {
+        var toppingsText = toppings.options[toppings.selectedIndex].innerHTML;
+        var toppingsName = toppingsText.replace(/[^a-z]/gi, '');
+        var toppingsValue = parseInt(toppingsText.replace(/\D/g,''));
+    
+        console.log(toppingsName, toppingsValue, "getMainToppings() working");
+    }
+
+

While the current code works just fine for dealing with the 'Hawaiian' option, 'Pepperoni Overload' and 'Meat Overload' is messing with the way I extract the text out of the labels. What would be the correct way so that I would be able to extract the words Pepperoni Overload and Meat Overload, maintaining the space between words but not extracting the additional spaces that follow afterwards?

","

Just extract everything until the - symbol. +Something like the following should work:

+
/(.*)-/g
+
+

And then you could just extract the first group and should get what you want.

",html +"How can I set the state and return JSX with the same function

I am trying to create a function that when gets called, it sets the state to the object {item: 'whatever the user types', list: [...list, todo]}; However, I don't know how to set the new state and return <li>{todo}</li> at the same time. I have been stuck for a while so I'd appreciate if you can help me out.

+
const Todo = () => {
+  const [state, setState] = useState({ item: '', list: [] });
+
+  const setTodoValue = (e) => {
+    setState((previousState) => {
+      return { ...previousState, item: e.target.value };
+    });
+  };
+
+  const addTodo = () => {
+    setState((previousState) => {
+      return {
+        ...previousState,
+        list: [...previousState.list, previousState.item],
+      };
+    });
+  };
+
+  return (
+    <div>
+      <input onChange={setTodoValue} type="text" />
+      <button onClick={addTodo}> + </button>
+      {}
+    </div>
+  );
+};
+
","

You can't, or won't, update state and simultaneously return JSX. You enqueue a state update, React updates the state, and you describe how to render the JSX from the state. The render return should take the state and map it to a bunch of list item li elements.

+

For more details on rendering JSX from arrays, see Lists and Keys.

+

Example rendering state.list into an unordered list:

+
const Todo = () => {
+  const [state, setState] = useState({ item: '', list: [] });
+
+  const setTodoValue = (e) => {
+    setState((previousState) => {
+      return { ...previousState, item: e.target.value };
+    });
+  };
+
+  const addTodo = () => {
+    setState((previousState) => {
+      return {
+        ...previousState,
+        list: [...previousState.list, previousState.item],
+      };
+    });
+  };
+
+  return (
+    <div>
+      <input onChange={setTodoValue} type="text" />
+      <button type="button" onClick={addTodo}> + </button>
+      <ul>
+        {state.list.map(todo => (
+          <li key={todo}>{todo}</li>
+        ))}
+      </ul>
+    </div>
+  );
+};
+
",html +"Countdown CSS visual formatting

I am trying to match the format in the image below. +

+

Here is the code I have now: https://codepen.io/Brite1/pen/wvPrggj (looks like I just need to add spacing and center all numbers/text). I am not sure how to add spacing and how to center all text and numbers correctly. Please help, thanks!

+
    body {
+  align-items: center;
+  background-color: transparent;
+  display: flex;
+}
+
+
+.container {
+  color: transparent;
+  margin: 0 auto;
+  text-align: center;
+}
+
+.circle-time{
+      color: #FE7030;
+    font-size: 60px;
+    font-family: "Roboto Slab", Helvetica, Arial, sans-serif;
+    font-weight: bold; 
+  text-align: center;
+
+}
+
+.timer-font{
+      font-family: "Roboto Slab", Helvetica, Arial, sans-serif;
+    font-weight: bold;
+    color: #027B46;
+    font-size: 25px;
+
+}
+
","

Use a wrapper and remove flex from the body. After removing the flex property from body add it in the wrapper and then use text-align to center the text.

+

+
+
function getNextDayOfWeek(date, dayOfWeek, hour) {
+  var resultDate = new Date(date.getTime());
+  resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
+  resultDate.setHours(hour, 0, 0, 0);
+  return resultDate;
+}
+
+var countDownDate = getNextDayOfWeek(new Date(), 5, 15);
+
+// Update the count down every 1 second
+var x = setInterval(function() {
+
+  // Get todays date and time
+  var now = new Date().getTime();
+
+  // Find the distance between now an the count down date
+  var distance = countDownDate - now;
+
+  // Time calculations for days, hours, minutes and seconds
+  var days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString();
+  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
+  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString();
+  var seconds = Math.floor((distance % (1000 * 60)) / 1000).toString();
+
+  // Display the result in the element with id=""timer""
+  document.getElementById(""circle-days"").innerHTML = days + ""<div class='timer-font'>Days</div>"";
+  document.getElementById(""circle-hours"").innerHTML = hours + ""<div class='timer-font'>Hours</div>"";
+  document.getElementById(""circle-minutes"").innerHTML = minutes + ""<div class='timer-font'>Minutes</div>"";
+  document.getElementById(""circle-seconds"").innerHTML = seconds + ""<div class='timer-font'>Seconds</div>"";
+
+  // If the count down is finished, write some text 
+  if (distance < 0) {
+    clearInterval(x);
+    document.getElementById(""timer"").innerHTML = ""Drawing Winners..."";
+  }
+}, 1000);
+
* {
+  margin: 0;
+  padding: 0;
+  width: 100%;
+}
+
+body {
+  background-color: transparent;
+}
+
+.wrapper {
+  display: flex;
+  gap: 10%;
+  align-items: center;
+  justify-content: center;
+}
+
+.container {
+  color: transparent;
+  margin: 0 auto;
+  text-align: center;
+}
+
+.circle-time {
+  color: #FE7030;
+  font-size: 60px;
+  font-family: ""Roboto Slab"", Helvetica, Arial, sans-serif;
+  font-weight: bold;
+  text-align: center;
+}
+
+.timer-font {
+  font-family: ""Roboto Slab"", Helvetica, Arial, sans-serif;
+  font-weight: bold;
+  color: #027B46;
+  font-size: 25px;
+}
+
+span {
+  text-align: center;
+}
+
<div class=""wrapper"">
+  <span style=""margin-right: 20px;"">
+          <span id=""circle-days"" class=""circle-time""></span>
+  </span>
+  <span style=""margin-right: 20px;"">
+          <span id=""circle-hours"" class=""circle-time""></span>
+  </span>
+  <span style=""margin-right: 20px;"">
+          <span id=""circle-minutes"" class=""circle-time""></span>
+  </span>
+  <span id=""circle-seconds"" class=""circle-time""></span> <span id=""timer""></span>
+</div>
+
+
+

",html +"Update position of seeker (i.e html input type range) while an audio is playing

I want the range slider automatically change while audio play.

+
<input type="range" name="seek" id="seeker" min="0" max="100" value="0" > 
+
+

+
+
let music = new Audio('https://www.computerhope.com/jargon/m/example.mp3');
+music.play();
+
<input type=""range"" name=""seek"" id=""seeker"" min=""0"" max=""100"" value=""0"" > 
+
+
+

","

Since new Audio() actually creates a new <audio> element (it is just not injected into your DOM), you can still listen to DOM events. For your use-case, you will want to listen to the timeupdate event, and get the progress of the play through by dividing the total duration of the audio clip with currentTime:

+
music.addEventListener('timeupdate', () => {
+  const percent = music.currentTime / music.duration * 100;
+  seeker.value = percent;
+});
+
+

However, if you want the users to use the <input> element to seek through the audio clip (I assumed that since you named your element #seeker), then you will also need to listen to the input event from the element. You can use simple math to calculate what currentTime value you have to set on the audio element.

+

Here is a proof-of-concept example. I have ensured that play() is only triggered by a button click, since most browsers do not autoplay audio files today.

+

+
+
const music = new Audio('https://www.computerhope.com/jargon/m/example.mp3');
+const seeker = document.querySelector('#seeker');
+
+music.addEventListener('timeupdate', () => {
+  const percent = music.currentTime / music.duration * 100;
+  seeker.value = percent;
+});
+
+// Allow seeking
+seeker.addEventListener('input', (e) => {
+  music.currentTime = e.target.value / 100 * music.duration;
+});
+
+document.querySelector('#play-button').addEventListener('click', () => {
+  music.play();
+});
+
<input type=""range"" name=""seek"" id=""seeker"" min=""0"" max=""100"" value=""0"">
+<button type=""button"" id=""play-button"">Play</button>
+
+
+

",html +"mPDF (PHP) does not recognize html check mark

I am showing a table in HTML on my web page where a check mark is shown properly (I am using &#10004; for the bold check mark).

+

I am using classic-asp to display the HTML. The html buildup (tableOutput) is then posted to a PHP script ($output = $_POST["output"]) that uses mPDF.php (version 6.0) to print to PDF the same HTML table and somehow the check mark wont print correctly (%u2714 in printed on my PDF). All the rest of the table is printed correctly, only the check mark has a problem.

+

I tried adding the Symbola.ttf and Symbola_hint.ttf fonts in the mpdf\ttfonts folder but it didnt do the trick.

+

HTML (classic-asp):

+
tableOutput = tableOutput & "<TD class='center pass_x' style='font-family:symbola;'>&#10004;</TD>"
+
+
+

PHP (create_report_pdf.php):

+
$output = $_POST["output"];  //This is the html buildup tableOutput discussed previously
+$header = Irrelevant;
+$footer= Irrelevant;
+
+$mpdf = new mPDF( 'utf-8', 'A4-L', 0, '', 5, 5, 20, 20);
+$mpdf->allow_charset_conversion = true;
+$mpdf->WriteHTML($style,1);
+$mpdf->SetHTMLHeader( $header );
+$mpdf->SetHTMLFooter( $footer );
+$mpdf->WriteHTML( $output );
+$mpdf->Output($temp ,'F' );
+
+

config_fonts.php (I addded symbola.ttf and Symbola_hint.ttf in the mpdf\ttfonts folder):

+
$this->fontdata = array (
+        "symbola"  => array (
+                'R' => "Symbola.ttf",
+                'I' => "Symbola_hint.ttf",
+        ),
+
+

CSS (PHP $style variable points to create_report_pdf.css):

+
.report-table{ 
+    border: 1px solid black;
+    border-collapse: collapse;
+    font-size: 7pt; 
+    width: 100%;
+} 
+
+th,td{ 
+    font-size: 7pt; 
+    border: 1px solid black !important;
+    vertical-align : middle;
+}
+
+.center{ text-align: center; vertical-align: middle; }
+
+INPUT{
+    border-color:#ffffff !important;
+}
+
+.pf{ width: 45px; }
+.fix-cell{ width: 90px; }
+.dr-column, .dr-input{ width: 100px; }
+.comments, .comments-input{ width: 130px; }
+
+
+

Thank you very much for your help

","

There are two possible solutions:

+
    +
  • Replacing manually the %u2714 with the respective html entity &#10004; by doing the following:
  • +
+
$output = str_replace('%u2714', '&#10004;', $output);
+
+
    +
  • Implement more generic approach that will handle all such special chars. The approach is based on the fact that %uXXXX is a non-standard notation scheme for URL-encoding Unicode characters. So you need to convert %uXXXX notation to HTML entity notation &#xXXXX; and then this can be decoded to actual UTF-8 by html_entity_decode.
  • +
+
$output = preg_replace('/%u([0-9A-F]+)/', '&#x$1;', $output);
+$output = html_entity_decode($output, ENT_COMPAT, 'UTF-8');
+
",html +"Prevent label text from overlapping input text

I created an input field, but when a user clicks off the user input, the span text overlays the input text. How can I prevent this from happening? I feel like I have tried everything!

+

+
+
.label {
+  display: inline-block;
+  margin: 10px;
+}
+
+.form-input {
+  margin: 10px;
+}
+
+.label span {
+  z-index: 1;
+  position: absolute;
+  cursor: text;
+  pointer-events: none;
+  color: #999;
+  padding-left: 10px;
+  line-height: 54px;
+  font-family: Arial, Helvetica, sans-serif;
+  transition: all ease-out 0.1s;
+}
+
+.label:focus-within>span {
+  /* Move span text up on focus */
+  line-height: 26px;
+  font-size: 12px;
+  transition: ease-in-out 0.2s;
+  color: rgb(29, 161, 242);
+}
+
+.label input {
+  z-index: 0;
+  width: 258px;
+  height: 22px;
+  padding-bottom: 14px;
+  padding-top: 14px;
+  padding-left: 9px;
+  font-size: 16px;
+  font-family: Arial, Helvetica, sans-serif
+}
+
+.label input:focus {
+  padding-top: 20px;
+  padding-bottom: 8px;
+  transition: all ease-in-out 0.1s;
+}
+
<div>
+  <form class='form-input'>
+    <label class='label'>
+      <span class='span-text'>Email</span>
+      <input value=''></input>
+    </label>
+  </form>
+</div>
+
+
+

+

Codepen: https://codepen.io/pen?template=GROaJZM

","

i have some changes of your html & css code with less code.

+

First you need changes in Elements:

+
 <label class='label'>
+  <span class='span-text'>Email</span>
+  <input value=''></input>
+</label>
+
+

Apply To :

+
 <label class="label">
+  <input type="text" class="inputText" required/>
+  <span class="span-text">Email</span>
+</label>
+
+

Second Changes In CSS

+

On Focus changes :

+

Remove CSS:

+
 .label input:focus {
+  padding-top: 20px;
+  padding-bottom: 8px;
+  transition: all ease-in-out 0.1s;
+}
+
+

ADD CSS :

+
input:focus ~ .span-text,
+    input:not(:focus):valid ~ .span-text{
+      top: 16px;
+      font-size: 12px;
+      opacity: 1;
+      color: rgb(29, 161, 242);
+    }
+
+

For label tag :

+

Remove CSS:

+
.label span {
+  z-index: 1;
+  position: absolute;
+  cursor: text;
+  pointer-events: none;
+  color: #999;
+  padding-left: 10px;
+  line-height: 54px;
+  font-family: Arial, Helvetica, sans-serif;
+  transition: all ease-out 0.1s;
+}
+
+

Add CSS :

+
.span-text {
+      position: absolute;
+      pointer-events: none;
+      left: 20px;
+      top: 27px;
+      color: #999;
+      transition: 0.2s ease all;
+    }
+
+

+
+
 input:focus ~ .span-text,
+    input:not(:focus):valid ~ .span-text{
+      top: 16px;
+      font-size: 12px;
+      opacity: 1;
+      color: rgb(29, 161, 242);
+    }
+
+    .inputText {
+         width: 258px;
+        height: 22px;
+           padding-bottom: 10px;
+        padding-top: 20px;
+        padding-left: 9px;
+        font-size: 16px;
+    }
+
+    .span-text {
+      position: absolute;
+      pointer-events: none;
+      left: 20px;
+      top: 27px;
+      color: #999;
+      transition: 0.2s ease all;
+    }
+
 <form class='form-input'>
+    <div class=""label"">
+      <input type=""text"" class=""inputText"" required/>
+      <span class=""span-text"">Email</span>
+    </div>
+</form>
+
+
+

",html +"How to put columns resize feature like bootstrap using inline css for html email design?

When we use bootstrap CSS in the HTML page there is a Grid layout where a column showing on half-page will expand to the full page if the screen is smaller. In bootstrap, we declare this using grid columns like col-sm-12 and col-md-6 etc.

+

I am designing an email client where inline CSS is the option for designing but whatever div size we put for web browser does not work well for mobile as it does not resize. Do you have any suggestions please how to achieve the same feature as bootstrap in email template using inline CSS?

","

Typically we will want to make the default mobile-first, which is also the approach that Bootstrap takes. So that means 100% width by default.

+

For desktops then, which is typically anything above 600px (vary as desired), we want the width to be half.

+

In fact, there is also stacking involved in this so let's say there are two columns at 300px each for desktop.

+

You say "inline" but I think that's a general HTML Email thing. We are in fact allowed some CSS.

+

What I've got is a 100% width for anything below 600px (the width of the email). Otherwise, it's half (and the second column comes alongside it).

+
<!-- /* GENERAL BOILERPLATE */ -->
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"  xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
+  <head>
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+  <!--[if !mso]><!-->
+  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+  <!--<![endif]-->
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <meta name="format-detection" content="telephone=no" />
+  <meta name="x-apple-disable-message-reformatting" />
+  <title></title>
+  <!--[if (gte mso 9)|(IE)]>
+  <style type="text/css">
+  table {border-collapse: collapse !important;}
+  </style>
+  <![endif]-->
+  <!--[if gte mso 9]><xml>
+  <o:OfficeDocumentSettings>
+    <o:AllowPNG/>
+    <o:PixelsPerInch>96</o:PixelsPerInch>
+  </o:OfficeDocumentSettings>
+</xml><![endif]-->
+
+<style type="text/css">
+@-ms-viewport { 
+    width: device-width; 
+}
+</style>
+<!-- /* COLUMN WIDTH FOR DESKTOPS (BUT NOT OUTLOOK DESKTOP ON WINDOWS) */ -->
+      <style type="text/css">
+          @media screen and (min-width:600px) {
+              .column {
+                  max-width:300px!important;
+              }
+          }
+      </style>
+</head>
+ <!-- END HEAD -->
+    <body style="margin:0;padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;min-width:100%;background-color:#ffffff;">
+    <center id="wrapper" class="wrapper" style="width:100%;table-layout:fixed;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">
+        <div style="max-width:600px;">
+            <!--[if (gte mso 9)|(IE)]>
+            <table width="600" align="center" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;border-spacing:0;font-family:Arial, sans-serif;color:#333333;" >
+            <tr>
+            <td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;border-collapse:collapse;" >
+            <![endif]-->
+            <table align="center" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;border-spacing:0;font-family:Arial, sans-serif;color:#333333;margin:0 auto;width:100%;max-width:600px;">
+            <tr>
+                <td class="two-column" style="padding:0;border-collapse:collapse;background-color:blue;font-size:0;" >
+                <!--[if (gte mso 9)|(IE)]>
+                <table width="100%" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;border-spacing:0;font-family:Arial, sans-serif;color:#333333;" role="presentation">
+                    <tr>
+<!-- /* OUTLOOK WIDTH */ -->
+                        <td width="50%" valign="top" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;border-collapse:collapse;" >
+                        <![endif]-->
+<!-- /* MAX-WIDTH 100% by DEFAULT, WILL GET OVERRIDDEN ON DESKTOP */ -->
+                    <div class="column" style="width:100%;max-width:100%;display:inline-block;vertical-align:top;background-color:red;font-size:16px;">
+                        <p>Spicy jalapeno bacon ipsum dolor amet occaecat enim andouille capicola tempor mollit shoulder cillum biltong ea labore dolore id strip steak. Picanha sausage laboris turducken non. Nostrud kevin laborum beef. Doner prosciutto leberkas cow, salami landjaeger fugiat tri-tip pancetta voluptate cillum ullamco. Meatloaf tri-tip sed, laboris bacon sunt ut aliquip kielbasa in nostrud.</p>
+                    </div>
+                        <!--[if (gte mso 9)|(IE)]>
+                        </td>
+<!-- /* OUTLOOK WIDTH (2nd column) */ -->
+                        <td width="50%" valign="top" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0;border-collapse:collapse;" >
+                        <![endif]-->
+<!-- /* (2nd column) */ -->
+                    <div class="column" style="width:100%;max-width:100%;display:inline-block;vertical-align:top;background-color:green;font-size:16px;">
+                        <p>Hot and Spicy jalapeno bacon ipsum dolor amet occaecat enim andouille capicola tempor mollit shoulder cillum biltong ea labore dolore id strip steak. Picanha sausage laboris turducken non. Nostrud kevin laborum beef. Doner prosciutto leberkas cow, salami landjaeger fugiat tri-tip pancetta voluptate cillum ullamco. Meatloaf tri-tip sed, laboris bacon sunt ut aliquip kielbasa in nostrud.</p>
+                    </div>
+                        <!--[if (gte mso 9)|(IE)]>
+                        </td>
+                    </tr>
+                </table>
+                <![endif]-->
+                </td>
+            </tr>
+            </table>
+            <!--[if (gte mso 9)|(IE)]>
+            </td>
+            </tr>
+            </table>
+            <![endif]-->
+        </div>
+    </center>
+</body>
+</html>
+
+

Why not flex? Flex is not supported on Outlook, but we can do other code for Outlook. But flex is also not supported on Gmail iOS/Android where the user does not use a Gmail account. So I don't think it's quite ready for prime-time yet.

+

Width:100% & max-width:100% get us through the mobile experience by making each block the full width of the available screen.

+

But once we hit desktop terrain (600px in this case; being the max-width of the template), we'll need to switch to a max-width of 300px (50%). That's where the @media query comes in which is supported surprisingly well on all desktops except for Outlook.

+

Outlook gets its own table with two td's at 50%, with its proprietary conditional code (if mso).

+

This has been tested on all major email environments. For those very few desktop environments that do not support @media queries, they will get the mobile version: that is, full width stacked columns. It's a pretty nice fallback for these 0.01% of users.

",html +"Why aren't divs full height in a vertical flexbox?

Consider the following code snippet:

+

+
+
<style>
+.v {
+    display: flex;
+    flex-direction: column;
+    overflow-y: scroll;
+    height: 100%;
+}
+.e {
+    height: 100px;
+    width: 200px;
+}
+.q {
+    overflow: hidden;
+    height: 500px;
+}
+</style>
+<div class=""q"">
+  <div class=""v"">
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+      <div class=""e"">hello1</div>
+      <div class=""e"">hello2</div>
+  </div>
+<div>
+
+
+

+

The divs are not full height, despite having height: 100px. +How would I make the divs be full height?

+

Note, this snippet looks different locally, but the issue is the same (the divs are not full height).

","

flex-direction: column will prevent the divs from taking up full space +You can use min-height instead of height. so that the div e will have min height all time.

+
.e {
+    min-height: 100px;
+    width: 200px;
+}
+
",html +"Change the color of a button when clicked with javascript

i want to change the color of a button ONLY when clicked, and when i click OTHER element i want it to change to its original color, I already get how to change the color, but i dont know what could be the logic to return it back to the original background when I click other button

+
<div class="button-categories">
+  <a href="#" class="button-categories-link">Candidates</a>
+</div>
+<div class="button-categories">
+  <a href="#" class="button-categories-link">Contacts/Guests</a>
+</div>
+<div class="button-categories">
+  <a href="#" class="button-categories-link">Jobs</a>
+</div>
+<div class="button-categories">
+  <a href="#" class="button-categories-link">Clients</a>
+</div>
+
+<script>
+  categoriesButton.forEach(function (button, index) {
+    button.addEventListener('click', function (e) {
+      this.style.background = '#1976d2';
+      this.style.color = '#fff';
+    });
+  });
+</script>
+
","

You'll need to set up an event handler so that when any button gets clicked, all the buttons are reset so that no one of them is active. Then, set the clicked button to be active by styling it. But, instead of setting up multiple handlers, just set up one at the document level that will receive any clicks via bubbling ("event delegation").

+

+
+
// Get all the buttons into a node list
+let buttons = document.querySelectorAll("".button-categories-link"");
+
+// Set an event handler on the document so that when
+// any element is clicked, the event will bubble up to it
+document.addEventListener(""click"", function(evt){
+  // Check to see if it was a button that was clicked
+  if(evt.target.classList.contains(""button-categories-link"")){
+    // Loop over all the buttons & remove the active class
+    buttons.forEach(function(button){
+      button.classList.remove(""active"");
+    });
+    // Make the clicked button have the active class
+    evt.target.classList.add(""active"");
+  }
+});
+
.active { background-color:#ff0;  }
+
<div class=""button-categories"">
+  <a href=""#"" class=""button-categories-link"">Candidates</a>
+</div>
+<div class=""button-categories"">
+  <a href=""#"" class=""button-categories-link"">Contacts/Guests</a>
+</div>
+<div class=""button-categories"">
+  <a href=""#"" class=""button-categories-link"">Jobs</a>
+</div>
+<div class=""button-categories"">
+  <a href=""#"" class=""button-categories-link"">Clients</a>
+</div>
+
+
+

+

But, you really shouldn't be using hyperlinks if you aren't using them for navigation. That's semantically incorrect and will cause problems for users who rely on assistive technologies for web page access. Instead, any visible element can be made to be clickable by setting up a click event handler for it. But, in your case, since you want "button-like" behavior, why not use the button element? You can style them however you like if you don't like the native presentation.

+

+
+
// Get all the buttons into a node list
+let buttons = document.querySelectorAll("".button-categories"");
+
+// Set an event handler on the document so that when
+// any element is clicked, the event will bubble up to it
+document.addEventListener(""click"", function(evt){
+  // Check to see if it was a button that was clicked
+  if(evt.target.classList.contains(""button-categories"")){
+
+    // Loop over all the buttons & remove the active class
+    buttons.forEach(function(button){
+      button.classList.remove(""active"");
+    });
+    // Make the clicked button have the active class
+    evt.target.classList.add(""active"");
+    
+  }
+});
+
button.button-categories {
+  display:block;
+  border:none;
+  background-color:rgba(0,0,0,0);
+}
+
+button.button-categories.active { 
+  background-color:rgba(255,255,0,1); 
+}
+
<button class=""button-categories"">Candidates</button>
+<button class=""button-categories"">Contacts/Guests</button>
+<button class=""button-categories"">Jobs</button>
+<button class=""button-categories"">Clients</button>
+
+
+

",html +"CSS, how to bring a div to the top of its sibling elements while it's below in the HTML?

I have a div after some other divs and that's why it is not at the exact top of the viewport. But I want to bring it to the top without actually changing its position in HTML.

+

The HTML is like :

+
<div class = "some other divs"></div>
+<div class = "some other divs"></div>
+<div class = "some other divs"></div>
+<div class = "some other divs"></div>
+
+<div class = "main div"></div>
+
","

You could use css's flexbox and the order propriety of it, like so: +

+
+
body{
+ display:flex;
+ flex-direction:column;
+ gap:2rem
+}
+/* just to have som visuals */
+div{
+  background-color:black;
+  height:50px;
+}
+
+.main{
+ background-color:red;
+ /* bring it to the top */
+ order:-1
+}
+
<div class = ""some other divs""></div>
+<div class = ""some other divs""></div>
+<div class = ""some other divs""></div>
+<div class = ""some other divs""></div>
+
+<div class = ""main div""></div>
+
+
+

",html +"querySelectorAll exclude all children

I'm using querySelectorAll and want to exclude all children of a number of elements. Trying this does not work.

+

+
+
document.querySelectorAll("".h:not(.p)"").forEach(function(e){
+  e.style.color = ""red"";
+});
+
<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+
+
+

+

How can I achieve only selecting parent elements? Does such a selector exist?

","

This is only selecting the .h elements:

+
document.querySelectorAll(".h")
+
+

But what are you doing with those elements? You're setting the text color to red:

+
e.style.color = "red";
+
+

So all text within those elements will be red, unless styled otherwise. If the .p elements should be something else, style them as such:

+

+
+
document.querySelectorAll("".h"").forEach(function(e){
+  e.style.color = ""red"";
+});
+
.p {
+  color: black;
+}
+
<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+<div class=""h"">
+  Hello World!
+  <p class=""p"">This is a paragraph.</p>
+</div>
+
+
+

+

Alternatively you might consider re-structuring your HTML. For example:

+
<div>
+  <span class="h">Hello World!</span>
+  <p class="p">This is a paragraph.</p>
+</div>
+<div>
+  <span class="h">Hello World!</span>
+  <p class="p">This is a paragraph.</p>
+</div>
+<div>
+  <span class="h">Hello World!</span>
+  <p class="p">This is a paragraph.</p>
+</div>
+
+

Then you can specifically target the content you want without having to find ways to "exclude" other content.

",html +"How can I catch a browser timeout and execute my own error message?

I have a web page (classic asp) with a link to a local IP address, as follows:

+
<a href="http://192.168.1.89">Link</a>
+
+

If the local IP address is unavailable the web browser eventually times out and displays its own error message.

+

What I want to do is: catch the timeout before the browser displays its default error page and display an error on the same web page, next to the "Link".

+

e.g. <a href="http://192.168.1.89">Well Pump</a><div id="timeoutmsg">offline</div>

+

I am guessing I need some JavaScript and the timeout function, but I don't know where to begin.

","

Found this awesome workaround using pure javascript, no JScript, no ajax, no external libraries.
+Works at treat:
+Just need to upload a "test.gif" file to the local site(s).

+
var url = 'http://192.168.1.89';
+var img = new Image();
+img.src = url + '/test.gif';
+img.onload = function() {
+    document.getElementById("msg").innerHTML = "";
+    window.location.href = url;
+}
+img.onerror = function() {
+    document.getElementById("msg").innerHTML = "offline";
+}
+
",html +"passing HTML with event.currenttarget to a template literal to use it as inner HTML

so there is an event listener that going to give its own HTML to the function called aww with event.currenttarget in order to render it again with innerHTML, I pass it with a const called choose when I log the choose, its give the HTML correctly but when I render the page in its place this will show up : +[object HTMLDivElement] so tried to use JSON.parse on it to remove string but it didn't work :

+
document.querySelector(".h1").addEventListener("click",aaw)
+document.querySelector(".h2").addEventListener("click",aaw)
+document.querySelector(".h3").addEventListener("click",aaw)
+function aaw(event) {
+    const choose = event.currentTarget
+    document.body.innerHTML =
+        `
+    <div class="container">
+    ${ choose}
+    <div class="monster">
+        <div class="monster-up">
+            <h2>mordkaiser</h2>
+            <div class="outside-bar">
+                <div class="inside-bar">
+
+                </div>
+            </div>
+            
+
+        </div>
+        <div class="monster-down">
+            <div class="dicerools">
+
+            </div>
+            
+        </div>
+        
+    </div>
+
+    <button>attack</button>
+</div>
+    
+    
+    `
+}
+
+
+

How can we put that e.currenttarget into the template literal to use it with innerHTML?

","

You're trying to interpolate a node, typeof object, with a string, which will annoyingly give you [object Object] or in your case, [object HTMLDivElement]. If you want to embed the node's HTML, you can easily access it with the innerHTML attribute:

+
const choose = event.currentTarget.innerHTML; // <-- Will return something like "<div>hello</div>"
+
+

And it will be rendered as HTML in your string interpolation.

+

Edit

+

If you want the HTML including its parent, simply change innerHTML to outerHTML:

+
const choose = event.currentTarget.outerHTML; // <-- Will return something like "<div><div id="child">blah</div>helllo<button>cool</button></div>"
+
",html +"Only getting a portion of text on edit function php

Here's my code first

+
// Initiate curl session in a variable (resource)
+    $curl_handle = curl_init();
+
+    $url = "xxxxxxxxxx";
+    
+    // Set the curl URL option
+    curl_setopt($curl_handle, CURLOPT_URL, $url);
+    
+    // This option will return data as a string instead of direct output
+    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
+    
+    // Execute curl & store data in a variable
+    $curl_data = curl_exec($curl_handle);
+    
+    curl_close($curl_handle);
+    
+    // Decode JSON into PHP array
+    $response_data = json_decode($curl_data);
+    
+    // Print all data if needed
+    // print_r($response_data);
+    // die();
+    
+    // All user data exists in 'data' object
+    $user_data = $response_data;
+    $counter = 0;
+
+
+

on my HTML

+

+
+
<table id=""example2"" class=""table table-bordered table-hover"">
+  <thead>
+    <tr>
+      <th>#</th>
+      <th>Quotes Lists</th>
+      <th>Actions</th>
+    </tr>
+  </thead>
+  <tbody>
+    <?php if(!empty($user_data)) { ?>
+    <?php foreach($user_data as $user){ ?>
+    <tr>
+      <td>
+        <?php echo ++$counter; ?>
+      </td>
+      <td>
+        <?php echo $user->name; ?>
+      </td>
+      <td>
+        <div class=""row"">
+          <div class=""col-md-6"">
+            <button type='button' class='btn btn-primary addAttr' data-toggle='modal' data-target='#modal-edit' data-id=<?php echo $user->id; ?> data-value=<?php echo $user->name; ?>>Edit</button>
+          </div>
+
+          <div class=""col-md-6"">
+            <button type='button' class='btn btn-danger addAttr' data-toggle='modal' data-target='#modal-delete' data-id=<?php echo $user->id; ?>>Delete</button>
+          </div>
+        </div>
+        <!-- Modal Start-->
+        <div class=""modal fade"" id=""modal-edit"">
+          <div class=""modal-dialog"">
+            <div class=""modal-content"">
+              <div class=""modal-header"">
+                <h4 class=""modal-title"">Edit Item</h4>
+                <button type=""button"" class=""close"" data-dismiss=""modal"" aria-label=""Close"">
+                                                      <span aria-hidden=""true"">&times;</span>
+                                                    </button>
+              </div>
+              <div class=""modal-body"">
+                <form>
+                  <textarea id=""name"" name=""name"" class=""form-control"" rows=""5"" spellcheck=""false"">
+                                                        
+                                                      </textarea>
+                </form>
+              </div>
+              <div class=""modal-footer justify-content-between"">
+                <button type=""button"" class=""btn btn-default"" data-dismiss=""modal"">Close</button>
+                <button type=""button"" class=""btn btn-primary"">Save changes</button>
+              </div>
+            </div>
+            <!-- /.modal-content -->
+          </div>
+          <!-- /.modal-dialog -->
+        </div>
+        <!-- /.modal -->
+      </td>
+    </tr>
+    <?php } ?>
+    <?php } ?>
+  </tbody>
+</table>
+
+
+

+

and on my JS

+

+
+
 $('.addAttr').on('click',function() {
+    var id = $(this).attr('data-id');    
+    var name = $(this).attr('data-value');
+    $('#name').val(name);
+    } );
+
+
+

+

I have this data

+

+

Now the problem is that whenever I tried to edit data it's only getting the portion of a text like this

+

+

I am stuck to why I am only getting a portion of a text. Someone, please enlighten me.

","

Looks like you need to quote the output of $user->name in the HTML.

+

e.g

+
<!-- What you have: -->
+<button
+    type='button'
+    class='btn btn-primary addAttr'
+    data-toggle='modal'
+    data-target='#modal-edit'
+    data-id=<?php echo $user->id; ?>
+    data-value=<?php echo $user->name; ?>
+>Edit</button>
+
+<!-- With quotes: -->
+<button
+    type='button'
+    class='btn btn-primary addAttr'
+    data-toggle='modal'
+    data-target='#modal-edit'
+    data-id="<?php echo $user->id; ?>"
+    data-value="<?php echo $user->name; ?>"
+>Edit</button>
+
",html +"How do I change the font family of a paragraph when it is clicked? Im using jQuery

so, I've been trying to make a jQuery function that would change the font style of a paragraph once it is clicked.

+

Here is the code I've tried:

+

+
+
$(document).ready(function() {
+  $(""#story-p"").click(function() {
+    $(this).css({
+      ""font-family"": ""Arial, Helvetica, sans-serif"",
+      ""font-size"": ""200%"",
+    });
+  });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+<body>
+  <img class=""background"" src=""restaurant.jpg"" style=""display: none"" />
+  <h1 class=""heading"">Fuego</h1>
+  <div class=""container"">
+    <h1 class=""story"">Our Story</h1>
+    <p class=""story-p"">
+      Test
+    </p>
+</body>
+
+
+

+

I can't figure out why it wouldn't work?

+

Am I missing something?

+

Many thanks

","

Its not working because you selector to attach the click event uses $('#story-p') which means its targeting an element with id=story-p but your paragraph does not have an id instead it has the class as story-p.

+

So change your selector like below and it will start working.

+

+
+
$(document).ready(function() {
+  $("".story-p"").click(function() {
+    $(this).css({
+      ""font-family"": ""Arial, Helvetica, sans-serif"",
+      ""font-size"": ""200%"",
+    });
+  });
+});
+
<body>
+  <img class=""background"" src=""restaurant.jpg"" style=""display: none"" />
+  <h1 class=""heading"">Fuego</h1>
+  <div class=""container"">
+    <h1 class=""story"">Our Story</h1>
+    <p class=""story-p"">
+      We are an Asian inspired streetfood restaurant located in the Cape Town CBD. We pool together recipes from Vietnam, Thailand and Japan and create an authentic Asian food experience here in South Africa. Our owners, have spent years working in restaurants
+      all over Asia and have collaborated to create a collection of their favourite and most popular dishes. We have been open now for 2 years and plan to continue this journey well into the future. Come and visit us!
+    </p>
+</body>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+
+

",html +"How do I place a menu bar and logo inline with css

I have a menu bar that I am trying to float right, I also have a logo that I would like to keep to the left.

+

I have been able to get the menu to float to the right and keep the logo on the right however the menu is being pushed down in is not in line with the logo.

+

How do I get the menu in line with the logo?

+

+

If I put float left on the logo it leaves a weird gap at the top and messes up the layout.

+

+

Here is my code

+

+
+
    .navbar-collapse ul a {
+        font-family: ""Barlow"", sans-serif;
+        color: white;
+        text-decoration: none;
+        vertical-align: top;
+      }
+      .navbar-collapse ul a:hover {
+        background-color: white;
+        color: #23303e;
+        border-radius: 50px;
+        text-transform: uppercase;
+        font-weight: 900;
+        font-family: ""Fraunces"", serif;
+        padding: 10px 30px 10px;
+      }
+    }
+
+  .navbar-collapse ul {
+    padding: 0;
+    margin: 0;
+    float: right;
+    display: flex;
+  }
+
+      .navbar-collapse li {
+        display: inline;
+        float: left;
+      }
+
+  .logo {
+    width: 20%;
+    margin: 0 auto;
+    padding: 7.5px 10px 7.5px 0;
+  }
+}
+
+
+

+

+
+
 <nav>
+      <div class=""container-fluid"">
+        <a class=""nav-brand"" href=""#page-top""><img src=""images/logo.svg"" class=""logo"" alt=""Sunnyside Logo""></a>
+        <button class=""navbar-toggle"" type=""button"">
+            <img src=""images/icon-hamburger.svg"" class=""hamburger"" alt=""hamburger"">
+          </button>
+        <div class=""navbar-collapse"">
+          <ul>
+            <li class=""nav-link text-center""><a href=""#"">About</a></li>
+            <li class=""nav-link text-center""><a href=""#"">Services</a></li>
+            <li class=""nav-link text-center""><a href=""#"">Projects</a></li>
+            <li class=""nav-link text-center""><a href=""#"">Contact</a></li>
+          </ul>
+        </div>
+      </div>
+    </nav>
+
+
+

","

You need to put display: flex for .container-fluid that helps all your menu items on the same line as logo. To align right for menu items, you should put margin-left: auto for .navbar-collapse

+

Here is the full code

+

+
+
.navbar-collapse ul a {
+  font-family: ""Barlow"", sans-serif;
+  color: white;
+  text-decoration: none;
+  vertical-align: top;
+}
+
+.container-fluid {
+  display: flex;
+}
+
+.navbar-collapse {
+  margin-left: auto;
+}
+
+.navbar-collapse ul a:hover {
+  background-color: white;
+  color: #23303e;
+  border-radius: 50px;
+  text-transform: uppercase;
+  font-weight: 900;
+  font-family: ""Fraunces"", serif;
+  padding: 10px 30px 10px;
+}
+
+
+}
+.navbar-collapse ul {
+  padding: 0;
+  margin: 0;
+  float: right;
+  display: flex;
+}
+.navbar-collapse li {
+  display: inline;
+  float: left;
+}
+.logo {
+  width: 20%;
+  margin: 0 auto;
+  padding: 7.5px 10px 7.5px 0;
+}
+
+}
+
<nav>
+  <div class=""container-fluid"">
+    <a class=""nav-brand"" href=""#page-top""><img src=""images/logo.svg"" class=""logo"" alt=""Sunnyside Logo""></a>
+    <button class=""navbar-toggle"" type=""button"">
+       <img src=""images/icon-hamburger.svg"" class=""hamburger"" alt=""hamburger"">
+     </button>
+    <div class=""navbar-collapse"">
+      <ul>
+        <li class=""nav-link text-center""><a href=""#"">About</a></li>
+        <li class=""nav-link text-center""><a href=""#"">Services</a></li>
+        <li class=""nav-link text-center""><a href=""#"">Projects</a></li>
+        <li class=""nav-link text-center""><a href=""#"">Contact</a></li>
+      </ul>
+    </div>
+  </div>
+</nav>
+
+
+

",html +"Why is my XPath returning only text without tags?

I am using Google Sheets to send an update to my Discord server every time there is an update from a forum site.

+

However, when I scrape this link,

+

https://forum.mir4global.com/board/patchnote

+

using this XPath,

+
string((//*[@id="viewContent"])[1])
+
+

via use IMPORTXML I get this result:

+
+

" + We strive to provide a fun and fair gaming experience for all our players. Our team carefully monitors and actively removes players who do not adhere to the Operational Policy and Terms of Use.>> Operational Policy>> Terms of UseWe maintain a zero-tolerance policy against the use of unauthorized programs or software, manipulation or tampering of game data, and intentional exploitation of game systems. To date, we have permanently restricted more than 11,062,000 accounts. [Accounts Banned or Restricted]- Applicable Date: Wednesday, Mar. 16th, 2022- Number of Accounts: 114,952 (Total 11,062,063) - Reason: Use of unauthorized programs & Violation of Operational Policy*If you wish to make an appeal for the restriction imposed onto your account, please submit a support ticket through our official website. (https://cs.mir4global.com/customer)Inquiry Route : Contact Us > Account > Objection of restriction※ Please note that it may take a long time to receive an answer if you don't submit your inquiry ticket through the route above. We will continue to do our best in order to ensure a safe, fair, and fun gaming environment for all our players. "

+
+

How can I get the same format like in the forum site?

","

The whole point of the XPath function, string(), is to return the string-value (just the text without any markup) of the given node.

+

If you want the markup, remove the wrapping string() function.

",html +"How to capture `Ctrl+1` hotkey on Chrome browser keydown event?

I'm now developing a website for mindmap manipulation, and now want to make some hotkeys to make operations better.

+

In XMind, Ctrl+1 stands for adding a label with number 1, but I found the keydown event cannot capture the event. Instead, Ctrl+1 leads to activating the first Chrome tab, even though I call the e.preventDefault().

+

So the priority of the chrome browser is the most significant so cannot be intercepted. If I want to make the Ctrl+1 hotkey act as expect, is there any solution?

+
document.addEventListener('keydown', function(e) {
+    if (e.ctrlKey && e.code === 'Digit1') {
+        // ...
+        e.preventDefault()
+    }
+})
+
","
document.addEventListener('keydown', function (e) {
+    console.log(e.keyCode)
+    if (e.ctrlKey && [49, 50, 51].includes(e.keyCode)) {
+        e.preventDefault()
+        console.log('hahahah')
+    }
+})
+
",html +"Remove all div elements from string using vb.net

I want to remove all elements, including the ones with attributes like class, from my string. +I already checked here, so regex is apparently not the answer: RegEx match open tags except XHTML self-contained tags

+

I currently already have something with regex that replaces all tags from a string (note, I'm never parsing a full HTML document if that matters) and preserves the content: Regex.Replace(s, "<[^>]*(>|$)", String.Empty). However, I just want the div tags removed and preserve the content.

+

So I have:

+
<div class=""fade-content""><div><span>some  content</span></div></div>
+<div>some  content</div> 
+
+

Desired output:

+
<span>some  content</span>
+some  content
+
+

I was going the regex path stil, and trying something like: <div>.*<\/div>, but that excludes divs with attributes.

+

How can I remove div elements only, using VB.NET?

","

There are several ways to do this. One, short and simple, is the following one:

+
Regex.Replace(s, "</?div.*?>", String.Empty)
+
+

Here is an example:

+
    's simulates your html file
+    Dim s As String = "<div class="""" fade-content""""><div><span>some  content</span></div></div>" + Environment.NewLine + "<div>some  content</div>"
+
+    'let's store the result in s1
+    Dim s1 As String = Text.RegularExpressions.Regex.Replace(s, "</?div.*?>", String.Empty)
+
+    'output
+    MessageBox.Show(s1)
+
+

Output:

+

",html +"Angular how to freeze mat table

I'm trying to freeze a mat table. Inside the table I have inputs, checkboxes and so on. Somehow, I'm trying to freeze it based on a variable in ts, so the user could not change the table. I tried to put an overlay div, but the table is still not freeze. If I put position:fixed the table will not be shown anymore, so this is not a solution. How can I do it? +HTML:

+
<div [id]="requestInProgress ? 'overlay' : ''">
+    <div class="mat-elevation-z8 layout-container">
+       ...//table
+    </div>
+</div>
+
+

CSS:

+
#overlay {
+  z-index: 10000;
+  opacity: 0.5;
+  background-color: grey;
+}
+
+
","

You just need to disable the pointer-events to prevent user clicks/interaction.

+

HTML

+
<div [ngClass]="{'overlay' : requestInProgress}">
+    <div class="mat-elevation-z8 layout-container">
+       ...//table
+    </div>
+</div>
+
+

CSS

+
.overlay{
+    pointer-events: none; // The magic line
+
+    z-index: 10000;
+    opacity: 0.5;
+    background-color: grey;
+}
+
",html +"navbar items shaking on hover

I am new to learning web designing. I am creating a sample website for my practice. I am stuck on the navbar item issue. after adding a hover effect on list items my items start shaking when I hover on them.

+

Here is my code:

+
<nav>
+            <div>
+            </div>
+            <ul>
+                <li><a>one</a></li>
+                <li><a>two</a></li>
+                <li><a>three</a></li>
+            </ul>
+        </nav>
+
+

CSS style:

+
nav {
+    display: flex;
+    justify-content: space-around;
+    flex-direction: row;
+    align-content: center;
+    align-items: center;
+    width: 100%;
+    background-color: #a33454;
+}
+
+nav div {
+    height: 60px;
+    width: 150px;
+    margin: 0.5rem;
+}
+
+nav ul {
+    display: flex;
+    list-style: none;
+    justify-content: space-between;
+    margin: 0.5rem;
+    align-items: center;
+    align-content: center;
+}
+
+nav ul li {
+    font-size: 1.3rem;
+    padding: 0.5rem;
+    margin: 0.2rem 0.6rem;
+}
+
+nav ul li:hover{
+    border-bottom: 4px solid #022222;
+}
+
+

I also created a sandbox demo

","

This is happening due to the border-bottom which appears when hovering. That is adding 4px to the height.

+

The best way around it is to also have a border in the not-hovered state but make it invisible.

+
nav ul li {
+    font-size: 1.3rem;
+    padding: 0.5rem;
+    margin: 0.2rem 0.6rem;
+    border-bottom: 4px solid transparent;
+}
+
+nav ul li:hover{
+    border-bottom: 4px solid #022222;
+}
+
+

By setting color to transparent, it will be invisible.

",html +"JS Alarmclock needs adjustment

I'm trying to set an alarmclock for the webapp I'm creating with Django. To do so, I followed some tutorials and adjusted the code for my needs and all. It works. +My problem is, I want to set the time and date, manually, with the variables I get from Django views (I passed the hour and min variables into my HTML file). +Here is my alarm.html file:

+
{% extends 'mainapp_hf/base.html' %}
+{% block content %}
+
+ {{ js_hour  }}
+
+
+      <div style="width: 100%; display: flex; justify-content: center; ">
+
+          <div id="clock"></div>
+
+
+    <script> 
+        const display = document.getElementById('clock');
+        
+        
+        const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
+        audio.loop = true;
+        let alarmTime = null;
+        let alarmTimeout = null;
+        
+        
+        function updateTime() {
+            const date = new Date();
+        
+            const hour = formatTime(date.getHours());
+            const minutes = formatTime(date.getMinutes());
+            const seconds = formatTime(date.getSeconds());
+        
+        
+        
+            display.innerText=`${hour} : ${minutes} : ${seconds}`
+        }
+        
+        function formatTime(time) {
+            if ( time < 10 ) {
+                return '0' + time;
+            }
+            return time;
+        }
+        
+        function setAlarmTime(value) {
+        
+            alarmTime = value;
+        }
+        
+        function setAlarm() {
+            if(alarmTime) {
+                const current = new Date();
+                const timeToAlarm = new Date(alarmTime);
+        
+                if (timeToAlarm > current) {
+                    const timeout = timeToAlarm.getTime() - current.getTime();
+                    alarmTimeout = setTimeout(() => audio.play(), timeout);
+                    setTimeout(clearAlarm, timeout + 5000);
+                    alert( value );
+                }
+            }
+        }
+        
+        function clearAlarm() {
+            audio.pause();
+            if (alarmTimeout) {
+                clearTimeout(alarmTimeout);
+                alert("value");
+            }
+        }
+        
+        setAlarmTime
+        setAlarm
+        alert( value )
+        
+        setInterval(updateTime, 1000);
+    </script>
+    </div>
+{% endblock %}
+
+

I'm newborn JS learner. I have no clue how to go further at this point, just to understand and adjust this current code took me hours. +For starter, I'm okay to ignore all other variables (like date, minute, second). Can anyone guide me to just to get the realtime hour and then compare it with my django variable {{ js_hour }} (data type is number, and lets say its equal to 15) and if they match, ring the sound (regardless of date or minute).

+

The variable "value" in setAlarmTime, is the user input that is being submitted via a form, but since I dont want that form anymore, (instead, I want to use my django variables), I didnt include that part of the code here.

+

The form user normally submits, has HTML input field that has type of "datetime-local". I tried to write my js_hour python variable in this format, like following

+

views.py

+
js_hour = "2022-03-29T11:00"
+
+

and then adjusted following part:

+

alarm.html

+
        function setAlarmTime(value) {
+        
+            alarmTime = {{ js_hour  }};
+        }
+
+

Thought this should do the trick. +When I dont play around and just get the user input, type of alarmTime is [object HTMLInputElement], and when I replace it with {{ js_hour }}, data type turns into an object. +And no alarm rings, code stop working.

+

Any suggestions?

","

Just do

+
setAlarmTime("{{ js_time }}");
+setAlarm()
+
+

and remove the alerts - you do not have a var called value

+

+
+
const display = document.getElementById('clock');
+const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
+audio.loop = true;
+let alarmTime = null;
+let alarmTimeout = null;
+
+
+function updateTime() {
+  const date = new Date();
+
+  const hour = formatTime(date.getHours());
+  const minutes = formatTime(date.getMinutes());
+  const seconds = formatTime(date.getSeconds());
+  display.innerText = `${hour} : ${minutes} : ${seconds}`
+}
+
+function formatTime(time) {
+  if (time < 10) {
+    return '0' + time;
+  }
+  return time;
+}
+
+function setAlarmTime(value) {
+  alarmTime = value;
+}
+
+function setAlarm() {
+  if (alarmTime) {
+    const current = new Date();
+    const timeToAlarm = new Date(alarmTime);
+console.log(timeToAlarm)
+    if (timeToAlarm > current) {
+      const timeout = timeToAlarm.getTime() - current.getTime();
+      alarmTimeout = setTimeout(() => audio.play(), timeout);
+      setTimeout(clearAlarm, timeout + 5000);
+    }
+    else { console.log(""time has passed"") }
+  }
+}
+
+function clearAlarm() {
+  audio.pause();
+  if (alarmTimeout) {
+    clearTimeout(alarmTimeout);
+    console.log(""Cleared"");
+  }
+}
+setAlarmTime(""2022-03-29T12:23""); // ""{{ js_time }}"";
+// debug
+let d = new Date()
+d.setSeconds(d.getSeconds() + 10)
+setAlarmTime(d.toString())
+// end debug
+
+setAlarm()
+setInterval(updateTime, 1000);
+
<div style=""width: 100%; display: flex; justify-content: center; "">
+
+  <div id=""clock""></div>
+</div>
+
+
+

",html +"Bootstrap 5 Carousel Slide Indicator Not Working

Currently, I am working on a carousel for a revamp of my mom's website, and everything besides the functionality of the slide indicator is working. Whenever you go to the prev/next image, the indicator will move, but if you click on the indicator button it does not take you to the given image. I cannot figure out what's wrong, probably something stupid like forgetting to close a div or something.

+

My code is below:

+

+
+
<!-- Landing Carousel -->
+<section class=""bg"">
+
+  <body>
+    <div class=""container max-high d-flex align-items-center bg-dark pt-lg-5 pt-md-3 pt-3"" id=""carousel"">
+      <div id=""carouselExampleCaptions"" class=""carousel slide"" data-bs-interval=""7500"" data-bs-ride=""carousel"">
+        <!-- Slide Indicators -->
+        <div class=""carousel-indicators"">
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""0"" class=""active"" aria-current=""true"" aria-label=""Slide 1""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""1"" aria-current=""true"" aria-label=""Slide 2""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""2"" aria-current=""true"" aria-label=""Slide 3""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""3"" aria-current=""true"" aria-label=""Slide 4""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""4"" aria-current=""true"" aria-label=""Slide 5""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""5"" aria-current=""true"" aria-label=""Slide 6""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""6"" aria-current=""true"" aria-label=""Slide 7""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""7"" aria-current=""true"" aria-label=""Slide 8"">    
+                    </button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""8"" aria-current=""true"" aria-label=""Slide 9""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""9"" aria-current=""true"" aria-label=""Slide 10""></button>
+          <button type=""button"" data-bs-target=""carouselExampleCaptions"" data-bs-slide-to=""10"" aria-current=""true"" aria-label=""Slide 11""></button>
+        </div>
+        <div class=""carousel-inner"">
+          <div class=""carousel-item active"">
+            <img src=""images/1.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/2.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/3.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/4.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/5.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/6.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/7.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/8.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/9.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/10.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+          <div class=""carousel-item"">
+            <img src=""images/11.png"" alt=""First Picture of Katie"" class=""d-block w-100"" />
+
+          </div>
+        </div>
+
+        <!-- Buttons -->
+        <div class=""buttons-container"">
+
+          <!-- Previous -->
+          <button class=""carousel-control-prev"" type=""button"" data-bs-target=""#carouselExampleCaptions"" data-bs-slide=""prev"">
+                        <span 
+                            class=""carousel-control-prev-icon"" 
+                            aria-hidden=""true""
+                        >
+                        </span>
+                        <span class=""visually-hidden"">Previous</span>
+                    </button>
+
+          <!-- Next -->
+          <button class=""carousel-control-next"" type=""button"" data-bs-target=""#carouselExampleCaptions"" data-bs-slide=""next"">
+                        <span 
+                            class=""carousel-control-next-icon"" 
+                            aria-hidden=""true""
+                        >
+                        </span>
+                        <span class=""visually-hidden"">Next</span>
+                    </button>
+        </div>
+      </div>
+    </div>
+  </body>
+</section>
+
+
+

","

This is working perfectly. Just add the following resources in head tag.

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Document</title>
+    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
+
+    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
+</head>
+<body>
+    <!-- Landing Carousel -->
+<section class="bg">
+    <body>
+        <div class="container max-high d-flex align-items-center bg-dark pt-lg-5 pt-md-3 pt-3" id="carousel">
+            <div
+                id="carouselExampleCaptions" 
+                class="carousel slide"
+                data-bs-interval="7500"
+                data-bs-ride="carousel"
+            >
+            <!-- Slide Indicators -->
+                <div class="carousel-indicators">
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="0"
+                        class="active"
+                        aria-current="true"
+                        aria-label="Slide 1"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="1"
+                        aria-current="true"
+                        aria-label="Slide 2"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="2"
+                        aria-current="true"
+                        aria-label="Slide 3"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="3"
+                        aria-current="true"
+                        aria-label="Slide 4"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="4"
+                        aria-current="true"
+                        aria-label="Slide 5"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="5"
+                        aria-current="true"
+                        aria-label="Slide 6"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="6"
+                        aria-current="true"
+                        aria-label="Slide 7"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="7"
+                        aria-current="true"
+                        aria-label="Slide 8"
+                    >    
+                    </button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="8"
+                        aria-current="true"
+                        aria-label="Slide 9"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="9"
+                        aria-current="true"
+                        aria-label="Slide 10"
+                    ></button>
+                    <button
+                        type="button"
+                        data-bs-target="carouselExampleCaptions"
+                        data-bs-slide-to="10"
+                        aria-current="true"
+                        aria-label="Slide 11"
+                    ></button>
+                </div>
+                <div class="carousel-inner">
+                    <div class="carousel-item active">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="ihttps://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                    <div class="carousel-item">
+                        <img 
+                        src="https://blog.getbootstrap.com/assets/img/2020/06/v5-new-logo.png" 
+                        alt="First Picture of Katie"
+                        class="d-block w-100"
+                        />
+
+                    </div>
+                </div>
+
+                <!-- Buttons -->
+                <div class="buttons-container">
+                    
+                    <!-- Previous -->
+                    <button 
+                        class="carousel-control-prev" 
+                        type="button"
+                        data-bs-target="#carouselExampleCaptions"
+                        data-bs-slide="prev"
+                    >
+                        <span 
+                            class="carousel-control-prev-icon" 
+                            aria-hidden="true"
+                        >
+                        </span>
+                        <span class="visually-hidden">Previous</span>
+                    </button>
+
+                    <!-- Next -->
+                    <button 
+                        class="carousel-control-next" 
+                        type="button"
+                        data-bs-target="#carouselExampleCaptions"
+                        data-bs-slide="next"
+                    >
+                        <span 
+                            class="carousel-control-next-icon" 
+                            aria-hidden="true"
+                        >
+                        </span>
+                        <span class="visually-hidden">Next</span>
+                    </button>
+                </div>
+            </div>
+        </div>
+    </body>
+</section>
+</body>
+<script>
+</script>
+</html>
+
",html +"Append div 10 times each time button clicked using javascript

This is my code:

+

+
+
$(document).ready(function () {
+          $('<button class=""btn more"">View More</button>')
+         .appendTo("".listing-item-container"")
+         .click(function() {
+            $(this).closest("".listing-item-container"").removeClass(""collapsed"");
+          });
+          $('<button class=""btn less"">View Less</button>')
+         .appendTo("".listing-item-container"")
+         .click(function() {
+           $(this).closest("".listing-item-container"").addClass(""collapsed"");
+         });
+      });   
+
.listing-item-container.collapsed > :nth-of-type(n+3) {
+      display:none;
+    }
+    
+    .listing-item-container > .more {
+      display:none;
+    }
+    .listing-item-container > .less {
+      display:block;
+    }
+    
+    .listing-item-container.collapsed > .more {
+      display:block;
+    }
+    .listing-item-container.collapsed > .less {
+      display:none;
+    }
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""listing-item-container collapsed"">
+        <div class=""listing-item"">
+            <p>FEATURES</p>
+            <ul class=""no-list-style"">
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+            </ul>
+        </div>
+        <div class=""listing-item"">
+            <p>FEATURES</p>
+            <ul class=""no-list-style"">
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+            </ul>
+        </div>
+        <div class=""listing-item"">
+            <p>FEATURES</p>
+            <ul class=""no-list-style"">
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+            </ul>
+        </div><div class=""listing-item"">
+            <p>FEATURES</p>
+            <ul class=""no-list-style"">
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+            </ul>
+        </div>
+        <div class=""listing-item"">
+            <p>FEATURES</p>
+            <ul class=""no-list-style"">
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+                <li>list content</li>
+            </ul>
+        </div>
+        <!--  100 more listing-item divs present here   -->
+    </div>
+
+
+

+

In above code when I click view more, it will display all remaining 'listing item' div and when I click view less, all divs are collapsed and display only 2 divs.

+

My expected output is, when I click view more it should only display next 2 'listing item' div and view more button. Again If I click view more, it should display next 2 'listing item' div and view more button. This should continue for all 100 more 'listing item' div. In the end it should display view less button. When I click view less button, each time it should collapse last 2 'listing item' div.

+

How can I modify my code to get the expected output?

","

The key here is in the use of jquery slice() (same as javascript slice() but on a jquery collection).

+
var howManyItemsToShow = 2;
+$(".listing-item").hide().slice(howManyItemsToShow).show();
+
+

this will hide all the items, then show the first 2. The UI update will be combined into a single action. If you add animation (.slideDown / .fadeIn) then this will need to be different.

+

You then add your "pagesize" (2 in the example) each time you click; and update.

+

Add a check for start/end and utilising the css trick to show/hide the more/less buttons gives you:

+

+
+
var lines = 2;
+var pagesize = 2;
+
+// assuming they don't change, load them up-front for small efficiency gain (and DRY)
+var items = $("".listing-item-container .listing-item"");
+
+$(document).ready(function() {
+  $('<button class=""btn more"">View More</button>')
+    .appendTo("".listing-item-container"")
+    .click(function() {
+    
+      lines += pagesize;
+      items
+        .show()
+        .slice(lines).hide();
+        
+      if (lines >= items.length)
+        $(this).closest("".listing-item-container"").removeClass(""collapsed"");
+    });
+
+  $('<button class=""btn less"">View Less</button>')
+    .appendTo("".listing-item-container"")
+    .click(function() {
+      // same for ""less"" but -= and different check
+      // this can of course be combined with the ""more"" button (DRY)
+      // shown separately for clarity
+      lines -= pagesize;
+      items.show();
+      items.slice(lines).hide();
+      if (lines <= pagesize)
+        $(this).closest("".listing-item-container"").addClass(""collapsed"");
+    });
+});
+
.listing-item-container.collapsed> :nth-of-type(n+3) {
+  display: none;
+}
+
+.listing-item-container>.more {
+  display: none;
+}
+
+.listing-item-container>.less {
+  display: block;
+}
+
+.listing-item-container.collapsed>.more {
+  display: block;
+}
+
+.listing-item-container.collapsed>.less {
+  display: none;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""listing-item-container collapsed"">
+  <div class=""listing-item"">
+    <p>FEATURES</p>
+    <ul class=""no-list-style"">
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+    </ul>
+  </div>
+  <div class=""listing-item"">
+    <p>FEATURES</p>
+    <ul class=""no-list-style"">
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+    </ul>
+  </div>
+  <div class=""listing-item"">
+    <p>FEATURES</p>
+    <ul class=""no-list-style"">
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+    </ul>
+  </div>
+  <div class=""listing-item"">
+    <p>FEATURES</p>
+    <ul class=""no-list-style"">
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+    </ul>
+  </div>
+  <div class=""listing-item"">
+    <p>FEATURES</p>
+    <ul class=""no-list-style"">
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+      <li>list content</li>
+    </ul>
+  </div>
+  <!--  100 more listing-item divs present here   -->
+</div>
+
+
+

",html +"I cannot get links in the header to center along the cross axis on a Flex-Row, left to right assignment

CodePen

+

I am doing the Odin Project course. I'm on the flex box section and a little confused. I am not sure what I am doing wrong with aligning along the cross axis in Flex, left to right.

+

So in the code, I need the "one two three" and "four five six" to be centered on the cross access.

+

I tried align-content/items, though I think I am suppose to be using items. I have tried center, flex-start / flex-end to see if it moves, it does not move on the cross at all.

+

I have googled quite a bit, trying for about an hour while I am working to try different things. Nothing seems to work. I was having trouble spacing them, however I was able to fix that and the margin to get them off the sides.

+

My assumption; I think I might be missing something about height? Does the container not have enough positive space to move around in? Is it so tight vertically that I AM centering but do not see it as the top and bottom are against the content / links as I took away padding and margin?

+

+
+
.header {
+  font-family: monospace;
+  background: papayawhip;
+  display: flex;
+  justify-content: center;
+  align-content: center;
+}
+
+.logo {
+  font-size: 48px;
+  font-weight: 900;
+  color: tomato;
+  background: white;
+  padding: 4px 32px;
+  margin: 0em 3em 0em 3em;
+}
+
+ul {
+  /* this removes the dots on the list items*/
+  list-style-type: none;
+  padding: 0;
+  margin: 0;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+}
+
+a {
+  font-size: 22px;
+  background: white;
+  padding: 8px;
+  /* this removes the line under the links */
+  text-decoration: none;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Flex Header</title>
+  <link rel=""stylesheet"" href=""style.css"">
+</head>
+
+<body>
+  <div class=""header"">
+    <div class=""left-links"">
+      <ul>
+        <li><a href=""#"">ONE</a></li>
+        <li><a href=""#"">TWO</a></li>
+        <li><a href=""#"">THREE</a></li>
+      </ul>
+    </div>
+    <div class=""logo"">LOGO</div>
+    <div class=""right-links"">
+      <ul>
+        <li><a href=""#"">FOUR</a></li>
+        <li><a href=""#"">FIVE</a></li>
+        <li><a href=""#"">SIX</a></li>
+      </ul>
+    </div>
+  </div>
+</body>
+
+</html>
+
+
+

","

Add height: 100%; to ul to make the centering you already have effective for the full height of its parent:

+

+
+
.header {
+  font-family: monospace;
+  background: papayawhip;
+  display: flex;
+  justify-content: center;
+  align-content: center;
+}
+
+.logo {
+  font-size: 48px;
+  font-weight: 900;
+  color: tomato;
+  background: white;
+  padding: 4px 32px;
+  margin: 0em 3em 0em 3em;
+}
+
+ul {
+  /* this removes the dots on the list items*/
+  list-style-type: none;
+  padding: 0;
+  margin: 0;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  height: 100%;
+}
+
+a {
+  font-size: 22px;
+  background: white;
+  padding: 8px;
+  /* this removes the line under the links */
+  text-decoration: none;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Flex Header</title>
+  <link rel=""stylesheet"" href=""style.css"">
+</head>
+
+<body>
+  <div class=""header"">
+    <div class=""left-links"">
+      <ul>
+        <li><a href=""#"">ONE</a></li>
+        <li><a href=""#"">TWO</a></li>
+        <li><a href=""#"">THREE</a></li>
+      </ul>
+    </div>
+    <div class=""logo"">LOGO</div>
+    <div class=""right-links"">
+      <ul>
+        <li><a href=""#"">FOUR</a></li>
+        <li><a href=""#"">FIVE</a></li>
+        <li><a href=""#"">SIX</a></li>
+      </ul>
+    </div>
+  </div>
+</body>
+
+</html>
+
+
+

",html +"Carousel with backend data showing all images or no images

I am running a Django application where I receive the list of images and in my template, I have the following code for Carousel.

+

The issue is if I use this class "carousel-inner active" while iterating all images are set active and all images are shown on a single screen, if not if I remove active and just keep carousel-inner no image is shown

+
<div id="demo" class="carousel slide" data-bs-ride="carousel">
+  <!-- Indicators/dots -->
+  <div class="carousel-indicators">
+    <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button>
+    <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button>
+  </div>
+
+  <!-- The slideshow/carousel -->
+  <div class="carousel-inner active">
+      {% for image in data.images %}
+    <div class="carousel-item active">
+      <img src="{{ image }}" alt="image 1" class="d-block" style="width:100%">
+    </div>
+      {% endfor %}
+
+  <!-- Left and right controls/icons -->
+  <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
+    <span class="carousel-control-prev-icon"></span>
+  </button>
+  <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
+    <span class="carousel-control-next-icon"></span>
+  </button>
+</div>
+
","

The answer was to use a for-loop container inside div

+
<div class="carousel-inner">
+{% for image in data.images %}
+    <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}" id="slide{{ forloop.counter }}">
+        <img src="{{ image }}" class="d-block" style="width:100%">
+    </div>
+{% endfor %}
+</div>
+
",html +"Little problem with HTML form and input tags and with PHP get method (Warning: Undefined array key)

I am trying to get some basic information from the user -

+
<body>
+  <form action = "index.php" method="get">
+    Name: <input type="text" name="username">
+    <br>
+    Age: <input type="number" name="age">
+    <input type="submit">
+  </form>
+  <br>
+  Your name is <?php echo $_GET["username"] ?>
+  <br>
+  Your age is <?php echo $_GET["age"] ?>
+ </body>
+
+

This code is functional, but when I look to the browser prior to filling in the name and age, there is kind of a glitch, which can be seen underneath the submit button.

+
Your name is
+Warning: Undefined array key "username" in path\index.php on line 15
+
+Your age is
+Warning: Undefined array key "age" in path\index.php on line 17
+
+

However, when I enter in some information, then that error disappears, but it would be nice, if it was not there in the first place.

+

Could anybody give me any advice on how to fix this bug?

","

Wrap your echo under isset() condition. It will prevent the execution of the code if $_GET["username"] is not set or in other words, it will prevent the display if the form is not submitted(like on page load)

+
if(isset($_GET["username"])){
+   echo $_GET["username"];
+ }
+
",html +"VS Code: HTML file not pulling functions from attached javascript

Doing some basic practice/testing for a project I'm working on and can't get my html file to access the functions written in the attached javascript file. I feel like there's something super basic that I'm missing but I can't put my finger on it.

+

I pulled the basic button from here: Creating an ON/OFF button with javascript +And I tried the solutions here: HTML file not pulling information from javascript file

+

My html:

+
<!DOCTYPE html>
+<head>
+  <script type="text/javascript" src="app.js"></script>
+  <link rel="stylesheet" href="style.css">
+</head> 
+<body>
+    <input type="button" value="X" id="turn" onclick="turn();">
+</body>
+</html>
+
+

My js:

+
function turn(){
+    currentvalue = document.getElementById('turn').value;
+    if(currentvalue == "X"){
+        document.getElementById("turn").value="O";
+    }
+    else{
+        document.getElementById("turn").value="X";
+    }
+}
+
+

The function itself works when embedded in a script tag within <body> but not when pulled from the attached javascript file. What am I missing?

","

+
+
function turn(){
+    currentvalue = document.getElementById('turn').value;
+    if(currentvalue == ""X""){
+        document.getElementById(""turn"").value=""O"";
+    }
+    else{
+        document.getElementById(""turn"").value=""X"";
+    }
+}
+
<!DOCTYPE html>
+<head>
+  <script type=""text/javascript"" src=""app.js"" defer></script>
+  <link rel=""stylesheet"" href=""style.css"">
+</head> 
+<body>
+    <input type=""button"" value=""X"" id=""turn"" onclick=""turn();"">
+</body>
+</html>
+
+
+

+

You need to add defer atrribute.

",html +"Seam forming between adjacent SVG images in flexbox

I have split a single SVG image into parts and placed them in a single row of a CSS flexbox. The goal is to keep a constant height but allow the width to change. I can horizontally stretch parts certain parts of the image without causing aspect ratio issues while leaving the other parts constant.

+

The issue is that, specifically in firefox, a seam is visible between the adjacent SVG images:

+

+

+
+
.gb-top-border {
+  width: 70%;
+  margin-left: auto;
+  margin-right: auto;
+  display: flex;
+  flex-direction: row;
+}
+
+.gb-top-border-column-fix {
+  flex: 0 0 auto;
+  display: flex;
+}
+
+.gb-top-border-column-flex-1 {
+  flex: 10 10 auto;
+  display: flex;
+}
+
+.gb-top-border-column-flex-2 {
+  flex: 5 5 auto;
+  display: flex;
+  min-width: 0;
+}
+
+.gb-img-vfill {
+  width: 100%;
+  max-height: 100px;
+}
+
+.gb-img-top {
+  max-height: 100px;
+}
+
+.pad {
+  padding: 5px;
+}
+
<div class=""gb-top-border"">
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/feD.svg"" class=""gb-img-top pad""></div>
+  <div class=""gb-top-border-column-flex-1""><img src=""https://svgshare.com/i/fge.svg"" class=""gb-img-vfill pad""></div>
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/fgL.svg"" class=""gb-img-top pad""></div>
+  <div class=""gb-top-border-column-flex-2""><img src=""https://svgshare.com/i/fge.svg"" class=""gb-img-vfill pad""></div>
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/fff.svg"" class=""gb-img-top pad""></div>
+</div>
+<br>
+
+<div class=""gb-top-border"">
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/feD.svg"" class=""gb-img-top""></div>
+  <div class=""gb-top-border-column-flex-1""><img src=""https://svgshare.com/i/fge.svg"" class=""gb-img-vfill""></div>
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/fgL.svg"" class=""gb-img-top""></div>
+  <div class=""gb-top-border-column-flex-2""><img src=""https://svgshare.com/i/fge.svg"" class=""gb-img-vfill""></div>
+  <div class=""gb-top-border-column-fix""><img src=""https://svgshare.com/i/fff.svg"" class=""gb-img-top""></div>
+</div>
+
+
+

+

Here is a live demo showing the flexbox with padding and without: +https://codepen.io/ScottMastro/pen/mdpmwEy

+

I think this might be just an unavoidable feature of firefox so I've given thought to workarounds. If I can horizontally stretch the second and fourth segments of the image slightly beyond the boundary of their div containers, it will prevent a seam. I have not been able to come up with CSS capable of doing this.

","

I used background images instead of img tags, and added some margins, so that there are no white seams even at different zoom levels. +However, at some zoom levels, the top border of the dark brown areas may look slightly different in the stretchy parts than in the fixed-width parts.

+

+
+
.gb-top-border {
+  width: 70%;
+  margin-left: auto;
+  margin-right: auto;
+  display: flex;
+  flex-direction: row;
+}
+
+.gb-top-border-column-fix {
+  flex: 0 0 auto;
+  display: flex;
+}
+
+.gb-top-border-column-flex-1 {
+  flex: 10 10 auto;
+  display: flex;
+}
+
+.gb-top-border-column-flex-2 {
+  flex: 5 5 auto;
+  display: flex;
+  min-width: 0;
+}
+
+.gb-img-vfill {
+  width: 100%;
+  max-height: 100px;
+}
+
+.gb-img-top {
+  max-height: 100px;
+}
+
+.pad {
+  padding: 5px;
+}
+
<div class=""gb-top-border"">
+    <div class=""gb-top-border-column-fix"" style=""background-image:url('https://svgshare.com/i/feD.svg'); height: 100px; width:123px; background-repeat: no-repeat; background-size: auto 102px""></div>
+    <div class=""gb-top-border-column-flex-1"" style=""background-image:url('https://svgshare.com/i/fge.svg'); height: 100px; margin-left:-1px ; background-size: 7px 102px""></div>
+    <div class=""gb-top-border-column-fix"" style=""background-image:url('https://svgshare.com/i/fgL.svg'); height: 100px; width:224px; background-position: -3px 0; margin-right: -3px; background-repeat: no-repeat;background-size: auto 102px""></div>
+    <div class=""gb-top-border-column-flex-2"" style=""background-image:url('https://svgshare.com/i/fge.svg'); height: 100px; margin-left:-3px; margin-right: -3px; background-size: 7px 102px""></div> 
+    <div class=""gb-top-border-column-fix"" style=""background-image:url('https://svgshare.com/i/fff.svg'); height: 100px; width:59px; background-position: -3px 0; background-repeat: no-repeat; background-size: auto 102px""></div>
+</div>
+<br>
+
+
+

",html +"Wordpress Frontend user field with HTML

I was wondering if someone could please help me clean up how this displays on the fronted, I use this to display a directory of users that are entered in a ACF field on some posts. Each field will have multiple users. I would like to have a bullet point for each user followed by their info and then each email address to be a mailto link.

+
<?php
+$users = get_field('pds_construction_coordinators', '');
+echo "<ul>";
+foreach($users as $user){
+    $user_id = $user['ID'];
+    $user_email = $user['user_email'];
+    $user_display_name = $user['display_name'];
+    $user_company = get_field('company_name', 'user_'.$user_id);
+    $user_phone = get_field('phone_number', 'user_'.$user_id);
+
+
+    echo "<li> $user_company, $user_display_name, <a href="mailto:<?php echo ($user_email); ?>"><?php echo $user_email; ?></a>, $user_phone </li>";
+
+    echo "<br />";
+}
+echo "</ul>";
+
","

Below is what ended up working for me, not the cleanest, but it works:

+
<?php
+$users = get_field('pds_construction_coordinators', '');
+echo "<ul>";
+foreach($users as $user){
+
+$user_id = $user['ID'];
+$user_email = $user['user_email'];
+$user_display_name = $user['display_name'];
+$user_company = get_field('company_name', 'user_'.$user_id);
+$user_phone = get_field('phone_number', 'user_'.$user_id);
+
+echo "<li>";
+echo "<strong>$user_company</strong> <br/>";
+echo "$user_display_name <br/>";
+echo "$user_phone <br/>";
+echo "<a href='mailto:$user_email'>$user_email</a><br/>";
+echo "</li>";
+}
+echo "<ul>";
+
",html +"Center text over Image (and make responsive)?

In col-2, I am trying to center the "WHAT" text over the image.

+
<div class="row">
+  <div class="col-2">
+     <div class="stackParent">
+           <img class="stack-Img" src="img/base.png">
+           <div class="stack-Txt">
+              <div class="fourWsText stack-Txt-child">WHAT</div>
+           </div>
+     </div>
+  </div>
+  <div class="col-10">
+    ...Variable length content...
+  </div>
+</div>
+
+

As we resize the browser, the row height will change so that everything in col-10 fits. I am using object-fit:contain to keep the image proportions correct. I need the "stack-Txt" div to resize with the image so that the text will stay centered over the image

+

Or maybe you know of a better way to achieve this?

+

Current Idea: +Put WHAT in another child div, make flex, center text with justify-content/align-items +& +JS addEventListener to window resize, get the img div and set nextSibling size equal to this.

+

These were the css classes at some point... but the only important thing is that the img doesn't overflow the col-2 or the height (which is variable based on the length of col-10)

+
.stackParent {
+  position: relative;
+  object-fit: contain;
+  max-width: inherit;
+  height: 20vh;
+}
+
+.stack-Txt {
+  position: absolute;
+  text-align: center;
+  width: 100%;
+  max-height: 15vh;
+  min-height: 15vh;
+  z-index: 4;
+}
+
+.stack-Txt-child {
+}
+
+.stack-Img {
+  position: absolute;
+  object-fit: contain;
+  max-width: inherit;
+  min-height: 15vh;
+  max-height: 15vh;
+  top: 0%;
+  left: 0%;
+  z-index: 3;
+}
+
+

*Note: I also have media queries to resize text, but this shouldn't make a difference.

","

If you are using Bootstrap 5 you can just use the built-in classes to achieve so.

+
    +
  • Apply .position-relative to the main div parent
  • +
  • Apply .img-fluid to <img /> to make image responsive
  • +
  • Apply .position-absolute, .top-50, .start-50, translate-middle to stack-Txt to center it vertically and horizontally over the image.
  • +
+

+
+
<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"" rel=""stylesheet"" integrity=""sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"" crossorigin=""anonymous"">
+
+<div class=""row"">
+  <div class=""col-2"">
+    <div class=""stackParent position-relative"">
+      <img class=""stack-Img img-fluid"" src=""https://source.unsplash.com/random"">
+      <div class=""stack-Txt position-absolute top-50 start-50 translate-middle"">
+        <div class=""fourWsText stack-Txt-child text-white"">WHAT</div>
+      </div>
+    </div>
+  </div>
+  <div class=""col-10"">
+    ...Variable length content...
+  </div>
+</div>
+
+
+

+

If you don't, just edit your CSS as follow:

+

+
+
.stackParent {
+  position: relative
+}
+
+
+/* make image responsive */
+.stack-Img {
+  max-width: 100%;
+  height: auto;
+}
+
+.stack-Txt {
+  position: absolute;
+  left: 50%;
+  top: 50%;
+  transform: translate(-50%, -50%);
+  color: white;
+}
+
<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"" rel=""stylesheet"" integrity=""sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"" crossorigin=""anonymous"">
+
+<div class=""row"">
+  <div class=""col-2"">
+    <div class=""stackParent"">
+      <img class=""stack-Img"" src=""https://source.unsplash.com/random"">
+      <div class=""stack-Txt"">
+        <div class=""fourWsText stack-Txt-child"">WHAT</div>
+      </div>
+    </div>
+  </div>
+  <div class=""col-10"">
+    ...Variable length content...
+  </div>
+</div>
+
+
+

",html +"How do I add a space between my fontawesome icon and

element?

I want to add a <p> text in the same line as that of my fontawesome icon, with a space in between the icon and the text. This is my code below:

+
<i class="fas fa-exclamation-circle">&nbsp;</i><p id="first-info">Only <p style="color: greenyellow;">Admin</p> is allowed full priviledges whereas <p style="color: red;">User</p> is 
+        allowed partial priviledges.</p>
+
+

But the text starts always from the next line. Where have I gone wrong? Please help me

","

If you do not change the display of a p tag, then it will ALWAYS start on a new line

+

So use spans or display: inline-block

+

+
+
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"" integrity=""sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="" crossorigin=""anonymous"" referrerpolicy=""no-referrer"" />
+
+<i class=""fas fa-exclamation-circle"">&nbsp;</i><span class=""first-info"">Only <span style=""color: greenyellow;"">Admin</span> is allowed full priviledges whereas <p style=""color: red;"">User</span> is allowed partial priviledges.</span>
+            
+
+
+

+

+
+
p.first-info { display: inline-block }
+
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"" integrity=""sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="" crossorigin=""anonymous"" referrerpolicy=""no-referrer"" />
+
+<i class=""fas fa-exclamation-circle"">&nbsp;</i><p class=""first-info"">Only <span style=""color: greenyellow;"">Admin</p> is allowed full priviledges whereas <p style=""color: red;"">User</span> is allowed partial priviledges.</p>
+            
+
+
+

",html +"HTML align last navbar item to the right

I have a problem. I created the following navbar:

+

+
+
* {
+    box-sizing: border-box;
+    font-family: -apple-system, BlinkMacSystemFont, ""segoe ui"", roboto, oxygen, ubuntu, cantarell, ""fira sans"", ""droid sans"", ""helvetica neue"", Arial, sans-serif;
+    font-size: 16px;
+    -webkit-font-smoothing: antialiased;
+    -moz-osx-font-smoothing: grayscale;
+    margin: 0;
+    padding: 0;
+}
+
+body {
+    background: linear-gradient( rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3) ), url(src/assets/images/background2.jpg);
+    background-position: center center;
+    background-repeat: no-repeat;
+    background-attachment: fixed;
+    background-size: cover;
+    background-color:#464646;
+}
+
+
+a {
+    text-decoration: none;
+}
+
+li {
+    list-style: none;
+}
+
+.navbar {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    padding: 20px;
+    background-color: #547430;
+    color: #fff;
+}
+
+.nav-links a {
+    color: #fff;
+}
+
+
+/* LOGO */
+
+.logo {
+    font-size: 2vw;
+    font-family: Rockwell;
+    text-align: center;
+    position: absolute;
+    width: 30%;
+    left: 50%;
+    margin-left: -15%;
+}
+
+
+/* NAVBAR MENU */
+
+.menu {
+    display: flex;
+    gap: 1em;
+    font-size: 18px;
+    z-index: 9;
+}
+
+.menu li:hover {
+    background-color: #7ead47;
+    border-radius: 5px;
+    transition: 0.3s ease;
+}
+
+.menu li {
+    padding: 5px 14px;
+    font-weight: bold;
+}
+
+
+/* DROPDOWN MENU */
+
+.services {
+    position: relative;
+}
+
+.dropdown {
+    background-color: rgb(1, 139, 139);
+    padding: 1em 0;
+    position: absolute;
+    /*WITH RESPECT TO PARENT*/
+    display: none;
+    border-radius: 8px;
+    top: 35px;
+}
+
+.dropdown li+li {
+    margin-top: 10px;
+}
+
+.dropdown li {
+    padding: 0.5em 1em;
+    width: 8em;
+    text-align: center;
+}
+
+.dropdown li:hover {
+    background-color: #4c9e9e;
+}
+
+.account {
+    position: absolute;
+    right: 0;
+}
+
+.services:hover .dropdown {
+    display: block;
+}
+
+
+/*RESPONSIVE NAVBAR MENU STARTS*/
+
+
+/* CHECKBOX HACK */
+
+input[type=checkbox] {
+    display: none;
+}
+
+
+/*HAMBURGER MENU*/
+
+.hamburger {
+    display: none;
+    font-size: 24px;
+    user-select: none;
+}
+
+
+/* APPLYING MEDIA QUERIES */
+
+@media (max-width: 1000px) {
+    .menu {
+        display: block;
+        position: absolute;
+        background-color: #547430;
+        margin-top: 5px;
+        text-align: left;
+        height: 100%;
+        width: 100%;
+        padding: 16px 0;
+        transition: all 0.3s ease;
+        left: -100%;
+    }
+    .logo {
+        font-size: 5vw;
+    }
+    .menu li:hover {
+        display: inline-block;
+        background-color: #7ead47;
+        transition: 0.3s ease;
+    }
+    .menu li+li {
+        margin-top: 12px;
+    }
+    input[type=checkbox]:checked~.menu {
+        left: 0%;
+    }
+    .hamburger {
+        display: block;
+    }
+    .dropdown {
+        left: 50%;
+        top: 30px;
+        transform: translateX(35%);
+    }
+    .dropdown li:hover {
+        background-color: #4c9e9e;
+    }
+}
+
+
+
+
+
+
+/*RESPONSIVE NAVBAR MENU STARTS*/
+/* CHECKBOX HACK */
+input[type=checkbox]{
+  display: none;
+}
+/*HAMBURGER MENU*/
+.hamburger {
+  display: none;
+  font-size: 24px;
+  user-select: none;
+}
+/* APPLYING MEDIA QUERIES */
+@media (max-width: 1000px) {
+
+  .menu {
+    display: block;
+    position: absolute;
+    background-color: #547430;
+    margin-top: 5px;
+    text-align: left;
+    height: 100%;
+    width: 100%;
+    padding: 16px 0;
+    transition: all 0.3s ease;
+    left: -100%;
+  }
+
+  .logo {
+    font-size: 5vw;
+  }
+
+  .menu li:hover {
+    display: inline-block;
+    background-color: #7ead47;
+    transition: 0.3s ease;
+  }
+
+  .menu li + li {
+    margin-top: 12px;
+  }
+
+  input[type=checkbox]:checked ~ .menu{
+    left: 0%;
+  }
+
+  .hamburger {
+    display: block;
+  }
+
+  .dropdown {
+    left: 50%;
+    top: 30px;
+    transform: translateX(35%);
+  }
+
+  .dropdown li:hover {
+    background-color: #4c9e9e;
+  }
+
+}
+
<nav class=""navbar"">
+  <div class=""logo"">Audio Diary</div>
+  <ul class=""nav-links"">
+
+    <!-- USING CHECKBOX HACK -->
+    <input type=""checkbox"" id=""checkbox_toggle"" />
+    <label for=""checkbox_toggle"" class=""hamburger"">&#9776;</label>
+
+    <!-- NAVIGATION MENUS -->
+    <div class=""menu"">
+      <li><a href=""/"">Home</a></li>
+      <li><a href=""/"">Explore</a></li>
+      <li><a href=""/"">Info</a></li>
+      <li class=""account"" id=""login""><a href=""/login"">Login</a></li>
+      <li class=""services"">
+        <a href=""/"">Services</a>
+        <ul class=""dropdown"">
+          <li><a href=""/"">Dropdown 1 </a></li>
+          <li><a href=""/"">Dropdown 2</a></li>
+          <li><a href=""/"">Dropdown 2</a></li>
+          <li><a href=""/"">Dropdown 3</a></li>
+          <li><a href=""/"">Dropdown 4</a></li>
+        </ul>
+      </li>
+    </div>
+  </ul>
+</nav>
+
+
+

+

But now I want the items in the navbar with the class: account to be aligned on the right. I already tried

+
float:right;
+
+

and

+
margin-left: auto
+
+

in the .account class in the css, but that doesn't result in any changes. What am I doing wrong and how can I achieve this?

","

Use position: absolute with right: 0 to align to the left

+

+
+
* {
+  box-sizing: border-box;
+  font-family: -apple-system, BlinkMacSystemFont, ""segoe ui"", roboto, oxygen, ubuntu, cantarell, ""fira sans"", ""droid sans"", ""helvetica neue"", Arial, sans-serif;
+  font-size: 16px;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+  margin: 0;
+  padding: 0;
+}
+
+body {
+  background: linear-gradient( rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url(src/assets/images/background2.jpg);
+  background-position: center center;
+  background-repeat: no-repeat;
+  background-attachment: fixed;
+  background-size: cover;
+  background-color: #464646;
+}
+
+a {
+  text-decoration: none;
+}
+
+li {
+  list-style: none;
+}
+
+.navbar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  padding: 20px;
+  background-color: #547430;
+  color: #fff;
+}
+
+.nav-links a {
+  color: #fff;
+}
+
+
+/* LOGO */
+
+.logo {
+  font-size: 2vw;
+  font-family: Rockwell;
+  text-align: center;
+  position: absolute;
+  width: 30%;
+  left: 50%;
+  margin-left: -15%;
+}
+
+
+/* NAVBAR MENU */
+
+.menu {
+  display: flex;
+  gap: 1em;
+  font-size: 18px;
+  z-index: 9;
+}
+
+.menu li:hover {
+  background-color: #7ead47;
+  border-radius: 5px;
+  transition: 0.3s ease;
+}
+
+.menu li {
+  padding: 5px 14px;
+  font-weight: bold;
+}
+
+
+/* DROPDOWN MENU */
+
+.account {
+  position: relative;
+}
+
+.dropdown {
+  background-color: rgb(1, 139, 139);
+  padding: 1em 0;
+  position: absolute;
+  /*WITH RESPECT TO PARENT*/
+  display: none;
+  border-radius: 8px;
+  top: 35px;
+}
+
+.dropdown li+li {
+  margin-top: 10px;
+}
+
+.dropdown li {
+  padding: 0.5em 1em;
+  width: 8em;
+  text-align: center;
+}
+
+.dropdown li:hover {
+  background-color: #4c9e9e;
+}
+
+.account {
+  position: absolute;
+  right: 0;
+}
+
+.account:hover .dropdown {
+  display: block;
+}
+
+
+/*RESPONSIVE NAVBAR MENU STARTS*/
+
+
+/* CHECKBOX HACK */
+
+input[type=checkbox] {
+  display: none;
+}
+
+
+/*HAMBURGER MENU*/
+
+.hamburger {
+  display: none;
+  font-size: 24px;
+  user-select: none;
+}
+
+
+/* APPLYING MEDIA QUERIES */
+
+@media (max-width: 1000px) {
+  .menu {
+    display: block;
+    position: absolute;
+    background-color: #547430;
+    margin-top: 5px;
+    text-align: left;
+    height: 100%;
+    width: 100%;
+    padding: 16px 0;
+    transition: all 0.3s ease;
+    left: -100%;
+  }
+  .logo {
+    font-size: 5vw;
+  }
+  .menu li:hover {
+    display: inline-block;
+    background-color: #7ead47;
+    transition: 0.3s ease;
+  }
+  .menu li+li {
+    margin-top: 12px;
+  }
+  input[type=checkbox]:checked~.menu {
+    left: 0%;
+  }
+  .hamburger {
+    display: block;
+  }
+  .dropdown {
+    left: 50%;
+    top: 30px;
+    transform: translateX(35%);
+  }
+  .dropdown li:hover {
+    background-color: #4c9e9e;
+  }
+}
+
<nav class=""navbar"">
+  <div class=""logo"">Audio Diary</div>
+  <ul class=""nav-links"">
+
+    <!-- USING CHECKBOX HACK -->
+    <input type=""checkbox"" id=""checkbox_toggle"" />
+    <label for=""checkbox_toggle"" class=""hamburger"">&#9776;</label>
+
+    <!-- NAVIGATION MENUS -->
+    <div class=""menu"">
+      <li><a href=""/"">Home</a></li>
+      <li><a href=""/"">Explore</a></li>
+      <li><a href=""/"">Info</a></li>
+      <li class=""account"" id=""login""><a href=""/login"">Login</a></li>
+    </div>
+  </ul>
+</nav>
+
+
+

+

Update:

+

As the dropdown disappears when go to it . Well the reason for this to disappear is that there is some space between dropdown and btn on hover . So when you try to go to dropdown the space remove the hover event on btn and dropdown disappears . This behavior will not seen when go to dropdown fastly .

+

Solution :

+
    +
  • Either trigger dropdown when clicked on btn and close it when clicked again or outside

    +
  • +
  • Or by removing the space between btn and dropdown

    +
  • +
+

I have shown the 2nd solution and reduced .dropdown {top: 35px;} to .dropdown {top: 30px;}

+

+
+
* {
+  box-sizing: border-box;
+  font-family: -apple-system, BlinkMacSystemFont, ""segoe ui"", roboto, oxygen, ubuntu, cantarell, ""fira sans"", ""droid sans"", ""helvetica neue"", Arial, sans-serif;
+  font-size: 16px;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+  margin: 0;
+  padding: 0;
+}
+
+body {
+  background: linear-gradient( rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url(src/assets/images/background2.jpg);
+  background-position: center center;
+  background-repeat: no-repeat;
+  background-attachment: fixed;
+  background-size: cover;
+  background-color: #464646;
+}
+
+a {
+  text-decoration: none;
+}
+
+li {
+  list-style: none;
+}
+
+.navbar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  padding: 20px;
+  background-color: #547430;
+  color: #fff;
+}
+
+.nav-links a {
+  color: #fff;
+}
+
+
+/* LOGO */
+
+.logo {
+  font-size: 2vw;
+  font-family: Rockwell;
+  text-align: center;
+  position: absolute;
+  width: 30%;
+  left: 50%;
+  margin-left: -15%;
+}
+
+
+/* NAVBAR MENU */
+
+.menu {
+  display: flex;
+  gap: 1em;
+  font-size: 18px;
+  z-index: 9;
+}
+
+.menu li:hover {
+  background-color: #7ead47;
+  border-radius: 5px;
+  transition: 0.3s ease;
+}
+
+.menu li {
+  padding: 5px 14px;
+  font-weight: bold;
+}
+
+
+/* DROPDOWN MENU */
+
+.services {
+  position: relative;
+}
+
+.dropdown {
+  background-color: rgb(1, 139, 139);
+  padding: 1em 0;
+  position: absolute;
+  /*WITH RESPECT TO PARENT*/
+  display: none;
+  border-radius: 8px;
+  top: 30px;
+}
+
+.dropdown li+li {
+  margin-top: 10px;
+}
+
+.dropdown li {
+  padding: 0.5em 1em;
+  width: 8em;
+  text-align: center;
+}
+
+.dropdown li:hover {
+  background-color: #4c9e9e;
+}
+
+.account {
+  position: absolute;
+  right: 0;
+}
+
+.services:hover .dropdown {
+  display: block;
+}
+
+
+/*RESPONSIVE NAVBAR MENU STARTS*/
+
+
+/* CHECKBOX HACK */
+
+input[type=checkbox] {
+  display: none;
+}
+
+
+/*HAMBURGER MENU*/
+
+.hamburger {
+  display: none;
+  font-size: 24px;
+  user-select: none;
+}
+
+
+/* APPLYING MEDIA QUERIES */
+
+@media (max-width: 1000px) {
+  .menu {
+    display: block;
+    position: absolute;
+    background-color: #547430;
+    margin-top: 5px;
+    text-align: left;
+    height: 100%;
+    width: 100%;
+    padding: 16px 0;
+    transition: all 0.3s ease;
+    left: -100%;
+  }
+  .logo {
+    font-size: 5vw;
+  }
+  .menu li:hover {
+    display: inline-block;
+    background-color: #7ead47;
+    transition: 0.3s ease;
+  }
+  .menu li+li {
+    margin-top: 12px;
+  }
+  input[type=checkbox]:checked~.menu {
+    left: 0%;
+  }
+  .hamburger {
+    display: block;
+  }
+  .dropdown {
+    left: 50%;
+    top: 30px;
+    transform: translateX(35%);
+  }
+  .dropdown li:hover {
+    background-color: #4c9e9e;
+  }
+}
+
+
+/*RESPONSIVE NAVBAR MENU STARTS*/
+
+
+/* CHECKBOX HACK */
+
+input[type=checkbox] {
+  display: none;
+}
+
+
+/*HAMBURGER MENU*/
+
+.hamburger {
+  display: none;
+  font-size: 24px;
+  user-select: none;
+}
+
+
+/* APPLYING MEDIA QUERIES */
+
+@media (max-width: 1000px) {
+  .menu {
+    display: block;
+    position: absolute;
+    background-color: #547430;
+    margin-top: 5px;
+    text-align: left;
+    height: 100%;
+    width: 100%;
+    padding: 16px 0;
+    transition: all 0.3s ease;
+    left: -100%;
+  }
+  .logo {
+    font-size: 5vw;
+  }
+  .menu li:hover {
+    display: inline-block;
+    background-color: #7ead47;
+    transition: 0.3s ease;
+  }
+  .menu li+li {
+    margin-top: 12px;
+  }
+  input[type=checkbox]:checked~.menu {
+    left: 0%;
+  }
+  .hamburger {
+    display: block;
+  }
+  .dropdown {
+    left: 50%;
+    top: 30px;
+    transform: translateX(35%);
+  }
+  .dropdown li:hover {
+    background-color: #4c9e9e;
+  }
+}
+
<nav class=""navbar"">
+  <div class=""logo"">Audio Diary</div>
+  <ul class=""nav-links"">
+
+    <!-- USING CHECKBOX HACK -->
+    <input type=""checkbox"" id=""checkbox_toggle"" />
+    <label for=""checkbox_toggle"" class=""hamburger"">&#9776;</label>
+
+    <!-- NAVIGATION MENUS -->
+    <div class=""menu"">
+      <li><a href=""/"">Home</a></li>
+      <li><a href=""/"">Explore</a></li>
+      <li><a href=""/"">Info</a></li>
+      <li class=""account"" id=""login""><a href=""/login"">Login</a></li>
+      <li class=""services"">
+        <a href=""/"">Services</a>
+        <ul class=""dropdown"">
+          <li><a href=""/"">Dropdown 1 </a></li>
+          <li><a href=""/"">Dropdown 2</a></li>
+          <li><a href=""/"">Dropdown 2</a></li>
+          <li><a href=""/"">Dropdown 3</a></li>
+          <li><a href=""/"">Dropdown 4</a></li>
+        </ul>
+      </li>
+    </div>
+  </ul>
+</nav>
+
+
+

",html +"Fuse or Merge of Search Button and Search Form

My Goal

+

To have a search bar (which is a post method form) and its submit button merged/fused as one. Like this:

+

+
    +
  • Platform: WordPress
  • +
  • Builder: Elementor (Pro)
  • +
  • Widget: Custom HTML
  • +
+

What I Have

+

I have tried (with my limited knowledge) and this is what I am sitting with:

+

+

+
+
.domSearchWrap {
+  position: relative;
+  display: inline;
+}
+
+.domSearchWrap .searchTerm {
+  border: 3px solid #0a7c82;
+  border-right: none;
+  border-radius: 20px 0px 0px 20px;
+  outline: none;
+  color: #0a7c82;
+  height: 60px;
+}
+
+.searchTerm:focus {
+  outline: none;
+}
+
+.domSearchWrap .searchButton {
+  width: 40px;
+  height: 60px;
+  border: 1px solid #0a7c82;
+  background: #0a7c82;
+  text-align: centre;
+  border-radius: 0px 20px 20px 0px;
+}
+
<div class=""domSearchWrap"">
+  <div class=""domSearch"">
+    <form action=""https://XX.XXXX.com/cart.php?a=add&domain=register"" method=""post"">
+      <input type=""text"" class=""searchTerm"" placeholder=""Type your desired domain name here..."" name=""query"">
+      <button type=""submit"" class=""searchButton"">
+                  <i class=""fa fa-search""></i>
+            </button>
+    </form>
+  </div>
+</div>
+
+
+

+

What am I doing wrong?

","

You can solve this problem in more than one ways.

+

First : Put icon inside input element in a form

+

and more but my solve is here =>

+
    +
  1. your input and button component must have parent element.
  2. +
  3. the css solution is here
  4. +
+

+
+
.domSearchWrap {
+  position: relative;
+  display: inline;
+}
+
+.parent { /* */
+  display:flex;
+  align-items:center;
+}
+.domSearchWrap .searchTerm {
+    border: 3px solid #0a7c82;
+    border-right: none;
+    border-radius: 20px 0px 0px 20px;
+    outline: none;
+    color: #0a7c82;
+    height: 60px;
+}
+.searchTerm:focus {
+    outline: none;
+
+}
+.domSearchWrap .searchButton {
+    width: 40px;
+    height: 68px; /*   */
+    border: 1px solid #0a7c82;
+    background: #0a7c82;
+    text-align: center;
+    border-radius: 0px 20px 20px 0px;
+}
+
<div class=""domSearchWrap"">
+    <div class=""domSearch"">
+        <form action=""https://XX.XXXX.com/cart.php?a=add&domain=register"" method=""post"">
+            <div class=""parent"">
+            <input type=""text"" class=""searchTerm"" placeholder=""Type your desired domain name here..."" name=""query"">
+            <button type=""submit"" class=""searchButton"">
+                    <i class=""fa fa-search""></i>
+            </button>
+            </div> 
+        </form>
+    </div>
+</div>
+
+
+

",html +"How to make dynamic cards with array/string html

I have a data

+
    {
+        "data": {
+            "count": 8,
+            "rows": [
+                {
+                    "session_name": "1_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                },
+                {
+                    "session_name": "WEB506_09092021_M1",
+                    "date": "09-09-2021",
+                    "p_id": "WEB506",
+                    "sub_id": "Physiotherapy"
+                }
+            ]
+        }
+    }
+
+

which I get from a post API(nodejs, express) by handling an ajax. I'm saving this data in localstorage and accessing it by localstorage on the next page. Then I want to create dynamic cards with passing some values from this data. the problem is I'm getting this data inside my script on the next page but foreach is not working when I create cards. please help.

+

my ajax,

+
    $.ajax({
+                type: 'POST',
+                data: JSON.stringify(data),
+                 contentType: 'application/json',
+                 dataType: 'json',
+                 url: "http://localhost:5000/SessionData",                      
+                 success: function(data) {
+                
+                     console.log(data);
+    
+                    
+                     localStorage.setItem('myData', JSON.stringify(data));
+                     window.location.href = 'nextpage'
+                    },
+                    
+                  error: function(){
+                    alert("Error")
+                    console.log('error occured')
+                  }
+            })
+
+

and in my next page,

+
     <script>
+        var data = localStorage.getItem('myData');
+        console.log(data);
+        var arr = new Array(data);
+        console.log(arr,"arr");
+        const container = document.getElementById('aa');
+    
+    arr.data.forEach((result, idx) => {
+      // Create card element
+      const card = document.createElement('div');
+      card.classList = 'card-body';
+    
+      // Construct card content
+      const content = `
+        <div class="card" style="width:700px;height: 150px">
+      
+         
+        
+    
+        
+          <div class="card-body">
+    
+            <li> Session Name :${result.sub_id}</li>
+            <li> Date :${result.date}</li>
+            <li> Patient ID : ${result.p_id}</li>
+            <button class="btn btn-link" style="width: 60px;height: 30px;background-color:#d1b147;color data-toggle="collapse" data-target="#collapse-${idx}" aria-expanded="true" aria-controls="collapse-${idx}">
+              View
+            </button>
+          </div>
+        </div>
+      </div>
+    </div>
+      `;
+    
+      
+      container.innerHTML += content;
+    })
+        
+      </script>
+
","

You need to convert the stored string back to an object,e.g. using JSON.parse():

+
const parsedData = JSON.parse(localStorage.getItem('myData'));
+parsedData.data.rows.forEach((result, idx) => {
+   ...
+});
+
",html +"Quantize an image with 8 selected colors (JavaScript)

I am writing a code that takes an image and quantizes it with the 8 selected colors that I have chosen. What I am wanting the program to do is to find a color that is closest with one of the 8 colors that I have chosen in my array and replace that pixel with that color that I have in my array. The thing is I currently have the quantized image in grayscale and I am having difficulties getting it to display color. What I have tried is that I used the distance function to get the distance of how far the color on the image is to the pixel of the image. And with that, my code still does not seem to work. I have also tried replacing the RGBA values with the functions but that did not work either. If there are any suggestions to solving my problem please give me an answer!

+

This is my code:

+
for(let x = 0; x < image.width; x++){
+    for(let y = 0; y < image.height; y++){
+
+        let i = y * image.width + x;
+
+    
+        let i_r = i*4+0;
+        let i_g = i*4+1;
+        let i_b = i*4+2;
+
+        
+        let L = 0.2126*rgba[i_r] + 0.7152*rgba[i_g] + 0.0722*rgba[i_b];
+
+
+        let palette = [ [240, 242,254], [179, 168, 164], [121,192, 246], [103,185,183], [255,201,157], [215,134,94], [67,38,158], [165,104,57]];
+
+        let qL = (L/255) * (palette.length - 1);
+
+
+        qL = Math.round(qL);
+
+        qL = qL/(palette.length - 1) * 255;
+
+        rgba[i_r] = qL;
+        rgba[i_g] = qL;
+        rgba[i_b] = qL;
+
+        
+
+    }
+}
+
","

This might be a fix for your issue:

+
for(let x = 0; x < image.width; x++){
+    for(let y = 0; y < image.height; y++){
+
+        let i = y * image.width + x;
+
+    
+        let i_r = i*4+0;
+        let i_g = i*4+1;
+        let i_b = i*4+2;
+
+        
+        let L = 0.2126*rgba[i_r] + 0.7152*rgba[i_g] + 0.0722*rgba[i_b];
+
+
+        
+        // this line should be improved
+        let qL = (L/255) * (palette.length - 1);
+
+
+        qL = Math.round(qL);
+
+        // fix - remove this line
+        // qL = qL/(palette.length - 1) * 255;
+
+        // fix
+        rgba[i_r] = palette[qL][0];
+        rgba[i_g] = palette[qL][1];
+        rgba[i_b] = palette[qL][2];
+    }
+}
+
+

Please take a look on +

+
graph.add(function(x) { return Math.round(8*x/255.0); });
+
+

As you see, the first section (values mapped to 0) has only 16 values on x-axis, the next one has 32... The last one has 16 values too and it's mapped to value 8 - so guess app will fail here (as max index of palette should be 7). Maybe you would like to improve this.

+

You may need something like (note x - 16 in eq)

+

",html +"How to Add a click Event Listener to nested class element

I'm trying to add a click event listener to all the "question classes" nested deep inside the container class. I can't seem to figure out the issue here.

+

+
+
let colorChange = document.querySelectorAll("".container .dropdowns .dropdown-function .question"")
+  for(i = 0; i < colorChange.length; i++){
+    colorChange.addEventListener(""click"", function(){
+      colorChange[i].classList.add(""change-color"");
+    });
+}
+
.change-color{
+  color: green
+}
+
<div class = ""container"">
+  <main class = ""dropdowns"">
+    <h1 class = ""title"">FAQ</h1>
+    <div class = ""dropdown-function"">
+      <h2 class = ""question""> Question 1 </h2>
+      <p class = ""dropdown-content""> Answer 1 </p>
+    </div>
+    <div class = ""dropdown-function"">
+       <h2 class = ""question""> Question 2 </h2>
+       <p class = ""dropdown-content""> Answer 2 </p>
+    </div>
+  </main>
+</div>
+
+
+

","

First, I will suggest you to notice if there is any error in console.

+

You are trying to attach the event (click) to the NodeList, not an individual element. Also declare the variable using let to create a block scope for the variable:

+

+
+
let colorChange = document.querySelectorAll("".container .dropdowns .dropdown-function .question"")
+  for(let i = 0; i < colorChange.length; i++){
+    colorChange[i].addEventListener(""click"", function(){
+      colorChange[i].classList.add(""change-color"");
+    });
+}
+
.change-color{
+  color: green
+}
+
<div class = ""container"">
+  <main class = ""dropdowns"">
+    <h1 class = ""title"">FAQ</h1>
+    <div class = ""dropdown-function"">
+      <h2 class = ""question""> Question 1 </h2>
+      <p class = ""dropdown-content""> Answer 1 </p>
+    </div>
+    <div class = ""dropdown-function"">
+       <h2 class = ""question""> Question 2 </h2>
+       <p class = ""dropdown-content""> Answer 2 </p>
+    </div>
+  </main>
+</div>
+
+
+

",html +"Why doesn't Safari 15 on Desktop respect my theme-color setting?

My site ( https://knpw.rs ) has a tag in the <head> as such:

+
<meta name="theme-color" content="#F9F9F9"/>
+
+

On Safari Mobile (iOS) the theme-color is respected for the header:

+

+

But on Safari Desktop, the theme-color is not respected:

+

+

Compare to https://registry.terraform.io which has theme-color set to #5c4ee5:

+

+

Which is also respected on mobile:

+

+

Why isn't my theme-color respected on Safari 15 Desktop?

","

This could be because your theme-color value is resulting in a bad contrast for the current system preferred layout (too bright for the user’s choice of having all dark layout). I think it is mentioned in this video from Apple Developer, that Safari will ignore your custom value if it doesn’t meet a certain threshold: +https://developer.apple.com/videos/play/wwdc2021/10029/

+

This article is also mentioning that behavior/limitation: https://css-tricks.com/meta-theme-color-and-trickery/

+

To resolve this, you need to add 2 theme-color values, one for each preferred color scheme dark/light, and stay within the thresholds. Example:

+
<meta name="theme-color" content="#f9f9f9" media="(prefers-color-scheme: light)">
+<meta name="theme-color" content="#872e4e" media="(prefers-color-scheme: dark)">
+
",html +"How to have elements under position fixed div?

I need to use position:fixed; for top div so the animation happens then I want to show other content and elements under it .

+

+

Right now the hello divs are over the container which I want them to be under the blue container .

+

This is the Codesandbox link

","

It looks the body is the blue container, so you can't put anything outside of that, but you could style another element as the blue container. z-index can be used to control what appears above/below other positioned elements.

",html +"Part of the back of the flip card disappears

I have just started to learn about coding in school, and I'm trying to make a simple project. +I have created a flip card consisting of the Finnish flag and an image. The problem is that when I hover over the flag and it flips, half the picture doesn't show.

+

+
+
.wallpaper {
+  background: green;
+  height: 2000px;
+  width: 1920px;
+  position: absolute;
+}
+
+.flag {
+  height: 310px;
+  width: 550px;
+  background: white;
+  position: relative;
+}
+
+.horizontal {
+  position: relative;
+  background: rgba(0, 54, 128, 255);
+  height: 75px;
+  top: 40%;
+}
+
+.vertical {
+  position: relative;
+  top: -75px;
+  bottom: 0;
+  left: -75px;
+  right: 0;
+  margin: auto;
+  background: rgba(0, 54, 128, 255);
+  height: 310px;
+  width: 75px;
+}
+
+.vodka {
+  height: 200px;
+  width: 200px;
+}
+
+img {
+  position: relative;
+  top: 900px;
+  bottom: 0;
+  left: 525px;
+  right: 0;
+  width: 350px;
+  height: 250px;
+}
+
+.text {
+  position: absolute;
+  left: 450px;
+  top: 100px;
+}
+
+.mannen {
+  color: white;
+  position: relative;
+  top: 200px;
+  left: 75px;
+}
+
+.myten {
+  color: rgba(0, 54, 128, 255);
+  position: relative;
+  top: 200px;
+  left: 200px;
+}
+
+.legenden {
+  color: white;
+  position: relative;
+  left: 300px;
+  top: 200px;
+}
+
+.container {
+  background: rgba(0, 54, 128, 255);
+  position: fixed;
+  height: 100px;
+  width: 1920px;
+  top: 0;
+}
+
+.mikko {
+  color: white;
+  position: relative;
+  left: 800px;
+}
+
+.group {
+  position: relative;
+  left: 250px;
+}
+
+.flip-card {
+  background: transparent;
+  width: 550px;
+  height: 310px;
+  perspective: 1000px;
+  position: absolute;
+  top: 500px;
+  left: 450px;
+}
+
+.flip-card-inner {
+  position: relative;
+  width: 100%;
+  height: 100%;
+  transition: transform 0.8s;
+  transform-style: preserve-3d;
+}
+
+.flip-card:hover .flip-card-inner {
+  transform: rotateY(180deg);
+}
+
+.flip-card-front,
+.flip-card-back {
+  position: absolute;
+  width: 100%;
+  height: 100%;
+  backface-visibility: hidden;
+}
+
+.image {
+  position: relative;
+  top: -900px;
+  left: 525px;
+  transform: scale(-1, 1);
+  z-index: -1;
+}
+
<div class=""wallpaper"">
+  <div class=""group"">
+    <div class=""text"">
+      <h1 style=""font-family: Verdana"">
+        <div class=""mannen"">Mannen,</div>
+        <div class=""myten"">myten,</div>
+        <div class=""legenden"">legenden!</div>
+      </h1>
+    </div>
+    <div class=""vodka"">
+      <img src=""https://folkofolk.se/sites/default/files/styles/article_large/public/2016-02/Finlandia_0.jpg.jpeg?itok=2vkru5VU"" />
+    </div>
+    <div class=""flip-card"">
+      <div class=""flip-card-inner"">
+        <div class=""flip-card-front"">
+          <div class=""flag"">
+            <div class=""horizontal""></div>
+            <div class=""vertical""></div>
+          </div>
+        </div>
+        <div=""flip-card-back"">
+          <div class=""image"">
+            <img src=""https://primatelounge.se/wp-content/uploads/2017/03/mikko-tahtinen-500x748.jpg"" style=""width:550px;height:310px;"" />
+          </div>
+      </div>
+    </div>
+  </div>
+</div>
+<div class=""container"">
+  <div class=""mikko"">
+    <h1 style=""font-family: Verdana"">Mikko Tähtinen</h1>
+  </div>
+</div>
+</div>
+
+
+

","

Removed some of the top/left properties of the person image and added

+
  height: 310px;
+  width: 550px;
+  object-fit: cover;
+
+

to the .image class and some minor changes .

+
+

Style according to need and it is advised not to use such a positioning using all from top/bottom as these will be hard to debug and know the behavior

+
+

+
+
.wallpaper {
+  background: green;
+  height: 2000px;
+  width: 1920px;
+  position: absolute;
+}
+
+.flag {
+  height: 310px;
+  width: 550px;
+  background: white;
+  position: relative;
+}
+
+.horizontal {
+  position: relative;
+  background: rgba(0, 54, 128, 255);
+  height: 75px;
+  top: 40%;
+}
+
+.vertical {
+  position: relative;
+  top: -75px;
+  bottom: 0;
+  left: -75px;
+  right: 0;
+  margin: auto;
+  background: rgba(0, 54, 128, 255);
+  height: 310px;
+  width: 75px;
+}
+
+.vodka {
+ 
+  height: 200px;
+  width: 200px;
+ 
+}
+
+img {
+  position: relative;
+  bottom: 0;
+  right: 0;
+ 
+}
+
+.text {
+  position: absolute;
+  left: 450px;
+  top: 100px;
+}
+
+.mannen {
+  color: white;
+  position: relative;
+  top: 200px;
+  left: 75px;
+}
+
+.myten {
+  color: rgba(0, 54, 128, 255);
+  position: relative;
+  top: 200px;
+  left: 200px;
+}
+
+.legenden {
+  color: white;
+  position: relative;
+  left: 300px;
+  top: 200px;
+}
+
+.container {
+  background: rgba(0, 54, 128, 255);
+  position: fixed;
+  height: 100px;
+  width: 1920px;
+  top: 0;
+}
+
+.mikko {
+  color: white;
+  position: relative;
+  left: 800px;
+}
+
+.group {
+  position: relative;
+  left: 250px;
+}
+
+.flip-card {
+  background: transparent;
+  width: 550px;
+  height: 310px;
+  perspective: 1000px;
+  position: absolute;
+  top: 500px;
+  left: 450px;
+}
+
+.flip-card-inner {
+  position: relative;
+  width: 100%;
+  height: 100%;
+  transition: transform 0.8s;
+  transform-style: preserve-3d;
+}
+
+.flip-card:hover .flip-card-inner {
+  transform: rotateY(180deg);
+}
+
+.flip-card-front,
+.flip-card-back {
+  position: absolute;
+  width: 100%;
+  height: 100%;
+  backface-visibility: hidden;
+}
+
+.image {
+  height: 310px;
+  width: 550px;
+  object-fit: cover;
+  position: relative;
+  transform: scale(-1, 1);
+  z-index: -1;
+}
+
<div class=""wallpaper"">
+  <div class=""group"">
+    <div class=""text"">
+      <h1 style=""font-family: Verdana"">
+        <div class=""mannen"">Mannen,</div>
+        <div class=""myten"">myten,</div>
+        <div class=""legenden"">legenden!</div>
+      </h1>
+    </div>
+    <div class=""vodka"">
+      <img src=""https://folkofolk.se/sites/default/files/styles/article_large/public/2016-02/Finlandia_0.jpg.jpeg?itok=2vkru5VU"" style=""width:550px;height:310px;"" />
+    </div>
+    <div class=""flip-card"">
+      <div class=""flip-card-inner"">
+        <div class=""flip-card-front"">
+          <div class=""flag"">
+            <div class=""horizontal""></div>
+            <div class=""vertical""></div>
+          </div>
+        </div>
+        <div=""flip-card-back"">
+          <div class=""image"">
+            <img src=""https://primatelounge.se/wp-content/uploads/2017/03/mikko-tahtinen-500x748.jpg"" style=""width:550px;height:310px;"" />
+          </div>
+      </div>
+    </div>
+  </div>
+</div>
+<div class=""container"">
+  <div class=""mikko"">
+    <h1 style=""font-family: Verdana"">Mikko Tähtinen</h1>
+  </div>
+</div>
+</div>
+
+
+

+

Simple image flip from above :

+

+
+
.flag {
+  height: 310px;
+  width: 550px;
+  background: white;
+  position: relative;
+  margin: 20px;
+}
+
+.horizontal {
+  position: relative;
+  background: rgba(0, 54, 128, 255);
+  height: 75px;
+  top: 40%;
+}
+
+.vertical {
+  position: relative;
+  top: -75px;
+  left: -75px;
+  margin: auto;
+  background: rgba(0, 54, 128, 255);
+  height: 310px;
+  width: 75px;
+}
+
+.flipImage1 {
+  position: absolute;
+  top: 0;
+  left: 0;
+  background-color:white;
+  z-index: -10;
+  transform: rotateY(180deg);
+}
+
+.flag:hover {
+  transform: rotateY(180deg);
+  transform-style: preserve-3d;
+}
+
<div class=""flag"">
+  <div class=""horizontal""></div>
+  <div class=""vertical""></div>
+  <img src=""https://primatelounge.se/wp-content/uploads/2017/03/mikko-tahtinen-500x748.jpg"" style=""width:550px;height:310px;"" class=""flipImage1"" />
+</div>
+
+
+

",html +"Multiline selection

I'm wanting to implement a multiline selection section in html that looks like:

+ +

But with <span> tags and css, the closest I've been able to come up with is:

+ +

Code pen

+
.textblock {
+  width:200px;
+  /* I don't want justified text, but this straightens the ratty edge */
+  text-align: justify;
+}
+.highlighted {
+  border-radius: 10px 0 10px 0;
+  background-color: rgb(61, 107, 39);
+  border: 1px solid rgb(61, 107, 39); /* bit of a cheat*/
+  /* the following almost works */
+  /* box-shadow: 10px 10px 10px black; */
+ }
+
+

This isn't so great because:

+
    +
  • the corners aren't all rounded
  • +
  • I didn't really want justified text (hack to make right edge line up)
  • +
  • Enabling box shadow results in disaster
  • +
+

Any tips on how to make this better?

+

Right now I'm wondering if I may have to craft the shape I want in javascript and draw it on a lower layer. Maybe I could use something like offsetLeft and friends to get the span's dimensions...?

+

Of course, if there's a simpler way in css, I'd love to do that instead!

","

you can use box-decoration-break: clone; to change how lines get styled and for the radius you can use box-shadow to hide the lines that get extra border-radius that you don't want. In the end, your code will end up like this:

+

+
+
.textblock {
+  width:200px;
+  text-align: justify;
+  line-height: calc(1rem + 6px); 
+}
+
+.highlighted {
+  display: inline;
+  background-color: rgb(61, 107, 39);
+  box-shadow: 5px 0 0 rgb(61, 107, 39), -5px 0 0 rgb(61, 107, 39), 5px 5px 0 rgb(61, 107, 39), -5px 5px rgb(61, 107, 39), 2px 6px 6px #000000, -2px 6px 6px #000000;
+  box-decoration-break: clone;
+  padding: 4px;
+  border-radius: 5px;
+ }
+
<div class=""textblock""> 
+    Four score and seven years ago our fathers brought forth upon this continent,<span class=""highlighted"">a new nation, conceived in Liberty, and dedicated to the proposition  that all men are created equal.
+
+    Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war</span>. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
+
+    But, in a larger sense, we can not dedicate—we can not consecrate—we can not hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.
+
+—Abraham Lincoln
+</div>
+
+
+

+

I also set line-height to manage the space between lines and make them fit perfectly for some fonts it is different.

+

Edit

+

You can remove the text-align: justify; on the textblock class but you need to add float: left; in order to have a full-width background.

+
+

Be aware this technique will move the highlighted section to a completely new block.

+
+

+
+
.textblock {
+  width:200px;
+  line-height: calc(1rem + 6px); 
+}
+
+.highlighted {
+  display: inline;
+  float: left;
+  background-color: rgb(61, 107, 39);
+  box-shadow: 5px 0 0 rgb(61, 107, 39), -5px 0 0 rgb(61, 107, 39), 5px 5px 0 rgb(61, 107, 39), -5px 5px rgb(61, 107, 39), 2px 6px 6px #000000, -2px 6px 6px #000000;
+  box-decoration-break: clone;
+  padding: 4px;
+  border-radius: 5px;
+ }
+
<div class=""textblock""> 
+    Four score and seven years ago our fathers brought forth upon this continent,<span class=""highlighted"">a new nation, conceived in Liberty, and dedicated to the proposition  that all men are created equal.
+
+    Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war</span>. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
+
+    But, in a larger sense, we can not dedicate—we can not consecrate—we can not hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.
+
+—Abraham Lincoln
+</div>
+
+
+

",html +"How can I insert new items into a grid in the top row?

I am inserting items from list to grid.

+

When I am inserting 2 items with same grid-column it's inserted one after another (which is good). But if next item is Could fit at top of rows I would like to place it there.

+

+
+
.container {
+  display: grid;
+  grid-gap: 20px;
+  grid-template-columns: repeat(7, 1fr);
+}
+
+.item1 {
+  grid-column: 3 / 4;
+  background-color: coral;
+}
+
+.item2 {
+  grid-column: 5 / 5;
+  background-color: red;
+}
+
<div class=""container"">
+  <div class='item1'>1</div>
+  <div class='item1'>2</div>
+  <div class='item2'>3</div>
+</div>
+
+
+

+

https://jsfiddle.net/epr5atvw/

+

How can i move item 3 so it will be next to item 1? My list is sorted and i cannot change it.

","

Use grid-auto-flow:column;

+

+
+
.container {
+  display: grid;
+  grid-gap: 20px;
+  grid-template-columns: repeat(7, 1fr);
+  grid-auto-flow: column;
+}
+
+.item1 {
+  grid-column: 3 / 4;
+  background-color: coral;
+}
+
+.item2 {
+  grid-column: 5 / 5;
+  background-color: red;
+}
+
<div class=""container"">
+  <div class='item1'>1</div>
+  <div class='item1'>2</div>
+  <div class='item2'>3</div>
+</div>
+
+
+

",html +"jQuery prevent autoplay after user closes video

I'm writing a script that will pop-up a video and autoplay it following this example. Everything is working fine, however when the user closes the video, it continues playing in the background. How can I tell the browser to turn off autoplay after the user closes the video?

+

+
+
$(document).ready(function() {
+  $('#headerVideoLink').magnificPopup({
+    type: 'inline'
+  });
+});
+
#headerPopup {
+  width: 75%;
+  margin: 0 auto;
+  position: relative;
+  top: 80px;
+}
+
+#headerPopup iframe {
+  width: 100%;
+  margin: 0 auto;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div id=""headerPopup"" class=""mfp-hide"">
+  <iframe width=""854"" height=""480"" src=""https://www.youtube.com/embed/qN3OueBm9F4?autoplay=1"" frameborder=""0"" allow=""autoplay"" allowfullscreen></iframe>
+</div>
+
+
+

","

From my point of view, there is no straight forward answer to your problem. This is a common thing people encounter when trying to show videos on websites.

+

The best approach to do this, is by using the Bootstrap CSS framework, because it has modals (pop ups) where you can add a video and whenever you close or open them it exposes events that can trigger functionalities.

+

In this case, you need jQuery to do something when opening and closing the modal. To avoid the video from playing on the background when the user closes the modal, one way would be to remove the content of the src attribute of the iframe, that will prevent the iframe to continue playing the video. And then when the user opens the modal add the link back. If you don't do this, what will happen is that the user may click on the video one time, it will work fine, but then after jQuery removed the link of the video, it wont work.

+

jQuery script I use for this purpose:

+
$(document).ready(function(){
+            
+     // Save the url of the video in a variable
+     var url = $("#MyVideo").attr('src');
+            
+     // When the modal is closed remove the url of the iframe
+     $("#myModal").on('hide.bs.modal', function(){
+        $("#MyVideo").attr('src', '');
+     });
+            
+     // When the modal is opened, add the url to the iframe
+     $("#myModal").on('show.bs.modal', function(){
+        $("#MyVideo").attr('src', url);
+     });
+});
+
+

You can read more about how Bootstrap modals work here. The details and explanations of the events are on the bottom of the page.

",html +"CSS div is larger than border of the div its within

As it stands, I'm trying to write a form which is responsive for the device that is displaying the webpage. However, I have an issue that, for the styling, I can't get the div which holds the form content to be within the main dic, which I proved with adding borders to the div. I know there is probably a simple answer, but I can't figure it out.

+

As viewed from a mobile device, this is what I currently see, with a div that is not centred within the page.

+

+

And this is what the content div looks like

+

+

This is what the new_user css is (the div within the div)

+
.form.new_user {
+            display: inline-block;
+            width: 100%;
+            min-width: 230pt;
+            max-width: 270pt;
+            border-color: #3e3e3e;
+            border-width: 1px;
+            border-style: solid;
+            padding: 5pt;
+        }
+
+        @media screen and (max-width: 600pt){
+            .form.new_user {
+                min-width: 100px;
+                max-width: inherit;
+            }
+        }
+
+

And then also the css for the content div

+
.content {
+    padding: 7pt;
+    margin: 7pt;
+}
+
+

Thank you in advance.

+

EDIT:

+

HTML code below.

+
<body>
+<div class="content">
+<div class="form new_user>
+</div>
+</div>
+</body>
+
+

And also I have the css for body as

+
body {
+    margin: 0;
+    font-family: Helvetica, sans-serif;
+}
+
","

Because..

+
+

By default in the CSS box model, the width and height you assign to an +element is applied only to the element's content box. If the element +has any border or padding, this is then added to the width and height +to arrive at the size of the box that's rendered on the screen.

+
+

Just add *{box-sizing: border-box;} You can find more info here

+

+
+
*{box-sizing: border-box;}
+body {
+    margin: 0;
+    font-family: Helvetica, sans-serif;
+}
+.form.new_user {
+            display: inline-block;
+            width: 100%;
+            min-width: 230pt;
+            max-width: 270pt;
+            border-color: #3e3e3e;
+            border-width: 1px;
+            border-style: solid;
+            padding: 5pt;
+        }
+.content {
+    padding: 7pt;
+    margin: 7pt;
+}
+
+        @media screen and (max-width: 600pt){
+            .form.new_user {
+                min-width: 100px;
+                max-width: inherit;
+            }
+        }
+
<body>
+<div class=""content"">
+<div class=""form new_user"">
+</div>
+</div>
+</body>
+
+
+

",html +"Why the CSS rule does not apply on real HTML page but does on JSFiddle?

In my website, I write the following CSS rule:

+
.holder-features ul li:before {
+  content: "";
+  background-image: url(/image/icons/check.svg);
+  display: block;
+  width: 10px;
+  height: 10px;
+  background-position: center center;
+  background-size: contain;
+  background-repeat: no-repeat;
+}
+
+

Then in the web page http://www.sybase-recovery.com/outlook-repair/, when clicking "Features" tab, and select one of the listing item, I use DevTools to inspect the element, but cannot find the rule .holder-features ul li:before is applied.

+

I then copy the listing and the CSS code to JSFiddle, and then simplified the listing codes, then try again, but find the CSS rule does apply. See https://jsfiddle.net/alanccw/9oucLfrx/10/

+

Why?

","

The issue is caused by a typo you have commented multiple inside a single css and caused the error

+

+

consider changing it into

+

+
+
/*
+.holder-features ul li:before {
+    display: none;
+    font-style: normal;
+    font-variant: normal;
+    text-rendering: auto;
+    -webkit-font-smoothing: antialiased;
+    font-family: ""Font Awesome 5 Free"";
+    font-weight: 900;
+    content: ""\f00c"";
+    content: url(""/images/icons/check.svg"");
+}
+*/
+
+
+

+

After changing this you will see the :before as you expected

+

",html +"How do I rearrange the cards in ascending order django

I have a page where the customer name in the cards is not rearrange in ascending order via alphabetical order Ex: B,M,S. How do I make it to arrange in alphabetical order so that the cards with the customer name Bangkok airways will appear first follow by the cards with malaysia airlines will appear next and so on?

+

+

views.py

+
def outgoinggallery(request):
+    user = request.user
+
+    category = request.GET.get('category')
+
+    if category == None:
+        alloutgoinglru = OutgoingLRU.objects.filter(category__user=user)
+    else:
+        alloutgoinglru = OutgoingLRU.objects.filter(category__name=category, category__user=user)
+        # if query:
+        # return OutgoingLRU.objects.filter(title__icontains=query)
+
+
+
+    categories = Category.objects.filter(user=user)
+    context = {'categories': categories, 'alloutgoinglru': alloutgoinglru}
+
+    return render(request, 'Outgoing/outgoinggallery.html', context)
+
+

outgoinggallery.html

+
{% extends "logisticbase.html" %}
+{% block content %}
+    <!-- CSS only -->
+    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
+        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
+
+    <style>
+
+
+
+td, th {
+  border: 1px solid #dddddd;
+  text-align: left;
+  padding: 8px;
+  border-radius: 15px;
+}
+        .image-thumbail {
+            height: 200px;
+            object-fit: cover;
+        }
+
+
+        .list-group-item a {
+            text-decoration: none;
+            color: black;
+        }
+    </style>
+
+
+
+
+    <br>
+
+
+   <div style="padding-left:16px">
+
+        <div class="row">
+
+
+            <div class="col-md-9">
+                <div class="row">
+                    <h5>View Outgoing LRU</h5>
+                    <div class="col-md-7">
+                    
+                    </div>
+                    <br>
+                    <div class="col-md-9">
+                <div class="row">
+
+                    {% for OutgoingLRU in alloutgoinglru %}
+                    <div class="col-md-4">
+                        <div class="card my-4">
+                            <img class="image-thumbail" src="{{OutgoingLRU.image.url}}" >
+
+                            <div class="card-body">
+                                <small>Customer Name: {{OutgoingLRU.category.name}}</small>
+                                <br>
+                                <small>Delivery Order: {{OutgoingLRU.Deliveryor}}</small>
+                            </div>
+                            <a href="{% url 'viewlruphoto' OutgoingLRU.id %}"  style="width:265px" class="btn btn-outline-dark btn-sm m-1">View</a>
+                            <form action="{% url 'deleteoutgoing' OutgoingLRU.id %}" method="post">
+                                {% csrf_token %}
+                                <button type="submit" style="width:270px" class="btn btn-sm btn-danger">Delete</button>
+                            </form>
+
+                        </div>
+                    </div>
+                    {% empty %}
+                    <h3>No photos...</h3>
+                    {% endfor %}
+
+
+
+
+
+
+
+
+                </div>
+            </div>
+        </div>
+   </div>
+
+
+{% endblock %}
+
+

models.py

+
class OutgoingLRU(models.Model):
+    class Meta:
+        verbose_name = 'OutgoingLRU'
+        verbose_name_plural = 'OutgoingLRUs'
+
+    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
+    image = models.ImageField(null=False, blank=False)
+    equipmentimages = models.ImageField(null=False, blank=False)
+    boximages = models.ImageField(null=False, blank=False)
+    documentimage = models.ImageField(null=False, blank=False)
+
+    datetime = models.DateTimeField()  # datetime is the date and time the form was created
+    serialno = models.TextField()  # serialno stand for serial number
+    partno = models.TextField()  # partno stand for part number
+    Deliveryor = models.TextField()  # deliveryor stand for delivery order
+    MCO = models.TextField()
+    descriptionequipment = models.TextField()  # A short description about the equipment (*Optional)
+    descriptionequipmentbox = models.TextField()  # A short description of the equipment in the box (*optional)
+    descriptionbox = models.TextField()  # A short description of the box (*optional)
+    document = models.TextField()  # A short description of the delivery note document (*optional)
+
+
+    def __str__(self):
+        return self.descriptionequipment
+
","

models.py

+
class Category(models.Model):
+    user = models.ForeignKey(
+      User, on_delete=models.SET_NULL, null=True, blank=True)
+    name = models.CharField(max_length=100, null=False, blank=False)
+   
+    class Meta:
+       ordering = ('name',)
+       verbose_name = 'Category'
+       verbose_name_plural = 'Categories'
+
+   def __str__(self):
+       return self.name
+
+
+class OutgoingLRU(models.Model):
+
+    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
+    image = models.ImageField(null=False, blank=False)
+    equipmentimages = models.ImageField(null=False, blank=False)
+    boximages = models.ImageField(null=False, blank=False)
+    documentimage = models.ImageField(null=False, blank=False)
+
+    datetime = models.DateTimeField()  # datetime is the date and time the form was created
+    serialno = models.TextField()  # serialno stand for serial number
+    partno = models.TextField()  # partno stand for part number
+    Deliveryor = models.TextField()  # deliveryor stand for delivery order
+    MCO = models.TextField()
+    descriptionequipment = models.TextField()  # A short description about the equipment (*Optional)
+    descriptionequipmentbox = models.TextField()  # A short description of the equipment in the box (*optional)
+    descriptionbox = models.TextField()  # A short description of the box (*optional)
+    document = models.TextField()  # A short description of the delivery note document (*optional)
+
+    class Meta:
+        verbose_name = 'OutgoingLRU'
+        verbose_name_plural = 'OutgoingLRUs
+        ordering = ('category__name',)
+
+    def __str__(self):
+        return self.descriptionequipment
+
+

after that:
+1)run python manage.py makemigrations
+2)run python manage.py migrate

",html +"I want to blur only the image but it affects everything

I wanted to creat a background image blur I applied it and everything just blurred so here is the html and this is just fast re creation of the full project and if you didn't understand the class names talk to me

+
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8">
+  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+
+  <title>HTML</title>
+  
+  <!-- HTML -->
+  
+
+  <!-- Custom Styles -->
+  <link rel="stylesheet" href="style.css">
+</head>
+
+<body>
+ <div class="trbp"><button class="trb">sign up</button></div>
+ <div class="aio">
+<h2 class="btp">welcom to</h2>
+<h2 class="bth">our site</h2>
+<button class="blb">about us</button></div>
+  <script src="main.js"></script>
+</body>
+</html>
+
+

Here's the css to help

+
    font-size: 15pt;
+    width: 500px;
+    height: 500px;
+    background-image: url("bto.jpg");
+    filter: blur(8px)
+}
+.trbp{
+  width: 500px;
+  height: 40px;
+  border: black;
+}
+.trb{
+  position: relative;
+  left: 440px;
+  width: 60px;
+  background-color: cyan;
+  border-radius: 5px;
+}
+
+.btp{
+  position: relative;
+  top: 120px;
+  left: 30px;
+}
+.bth{
+  position: relative;
+  top: 100px;
+  left: 30px;
+}
+.blb{
+  position: relative;
+  top: 80px;
+  left: 60px;
+  border-radius: 4px;
+  background-color: #0731D2;
+}
+
","

Using the code given in the question, and assuming it's the body that the background is required on, you can add a pseudo before element to the body and put the background on that and blur it.

+

That way only the image gets blurred, not everything else.

+

+
+
body {
+  font-size: 15pt;
+  width: 500px;
+  height: 500px;
+}
+
+body::before {
+  background-image: url(""https://picsum.photos/id/1015/1024/768"");
+  filter: blur(8px);
+  background-size: cover;
+  position: absolute;
+  top: 0;
+  left: 0;
+  width: 100%;
+  height: 100%;
+  display: inline-block;
+  content: '';
+  z-index: -1;
+}
+
+.trbp {
+  width: 500px;
+  height: 40px;
+  border: black;
+}
+
+.trb {
+  position: relative;
+  left: 440px;
+  width: 60px;
+  background-color: cyan;
+  border-radius: 5px;
+  display: inline-block;
+}
+
+.btp {
+  position: relative;
+  top: 120px;
+  left: 30px;
+}
+
+.bth {
+  position: relative;
+  top: 100px;
+  left: 30px;
+}
+
+.blb {
+  position: relative;
+  top: 80px;
+  left: 60px;
+  border-radius: 4px;
+  background-color: #0731D2;
+}
+
<div class=""trbp""><button class=""trb"">sign up</button></div>
+<div class=""aio"">
+  <h2 class=""btp"">welcom to</h2>
+  <h2 class=""bth"">our site</h2>
+  <button class=""blb"">about us</button></div>
+<script src=""main.js""></script>
+
+
+

",html +"Displaying input image form the user to website

I'm creating a social media application. +I got the image input from the user, but I was stuck in displaying the image.

+

Here is my HTML file

+
<form id="form">
+   <div id="closeForm"><i class="fas fa-window-close"></i></div>
+   <label>
+     <p>Enter the title:</p>
+     <input id="newTitle" placeholder="Art Title" type="text">
+   </label>
+   <label>
+     <p>Select your image:</p>
+     <input id="newImg" class="imgInput" accept="image/*" type="file">
+   </label>
+   <input id = "formBtn" type="button" acc value="Upload">
+</form>
+
+

This is my JS file

+
document.getElementById('formBtn').onclick=()=>{
+    let newTitle = document.getElementById('newTitle').value;
+    let newImg =  document.getElementById('newImg').value;
+
+    let fragment = `
+       <img class="art_img" src="${newImg}" alt="" srcset="">
+       <p id="title">${newTitle}</p>`;
+
+artContainer.innerHTML+=fragment;
+}
+
","

Use the FileReader object to create a blob and attach it to the element.

+

Example:

+
        const reader = new FileReader();
+        reader.onload = (e) => {
+                imgElm.src = e.target.result;
+        };
+        // do some checks to make sure its not empty
+        reader.readAsDataURL(input.files[0]);
+
",html +"HTML button isn’t showing up

Ok, I’m new to all this, and this is a test website, and I’ve been searching the web for solutions for like an hour. This button in html isn’t showing up even though I used the right tags and stuff… is there a piece of code I need to input to import JavaScript or something? I know is a thing but I’ve seen people put it inside the tags like I did. I don’t know what I’m doing wrong.

+
<!doctype html>
+<html> 
+<head><h1>Do you like pineapple on pizza?</h1></head><br>
+<body> 
+<label for="pizza-select">Tell the truth. C'mon...</label>
+<select id="pizza-select">
+<option value= "">Pick one goddamn it.</option>
+<option value= "yes">Yes, I feel special for having an unpopular opinion</option>
+<option value= "no">No, I am close minded and hate having fun</option> <br>
+<button onclick="alert('eh idc')">Done</button>
+</body> 
+</html>
+
","

Main problem

+

Looks like you forgot to close your select tag which is the root of your button issue.

+

Further notes

+

Using an h1 in the head is not allowed, and will not work. If you are looking for a tab/page title I would recommend using the <title> tag as shown below. You can use the h1 as your content headline, but make sure to keep it in your body.

+

+
+
<!doctype html>
+<HTML> 
+
+<head>
+<title>Do you like pineapple on pizza?</title>
+</head>
+
+<body> 
+<h1>Do you like pineapple on pizza?</h1>
+<label for=""pizza-select"">Tell the truth. C'mon...</label>
+<select id=""pizza-select"">
+<option value= """">Pick one goddamn it.</option>
+<option value= ""yes"">Yes, I feel special for having an unpopular opinion</option>
+<option value= ""no"">No, I am close minded and hate having fun</option>
+</select>
+<br>
+<button onclick=""alert('eh idc')"">Done</button>
+</body> 
+</html>
+
+
+

",html +"Yellow underline CSS randomly not applied to full width of span

Example: +https://flowster.app/flowster-affiliate-program-activation-bonus/

+

You can see that the yellow underline (highlight) only makes it as far as the "A", but it should be underneath "Flowster Affiliate Program": +

+

However, the HTML looks like this:

+
<h1 class="elementor-heading-title elementor-size-default">
+  <span class="yellowhighlight">Flowster Affiliate Program</span> -
+  Activation Bonus
+</h1>
+
+

And the yellowhighlight CSS class looks like:

+
span.yellowhighlight {
+  position: relative;
+  z-index: 0;
+}
+
+span.yellowhighlight::after {
+  content: "";
+  position: absolute;
+  left: -0.15em;
+  right: -0.15em;
+  top: 0.8em;
+  height: 0.4em;
+  border-radius: 2em;
+  background: #fffa50;
+  z-index: -1;
+}
+
+

It's odd because on other pages it looks proper.

+

+
+
span.yellowhighlight {
+  position: relative;
+  z-index: 0;
+}
+
+span.yellowhighlight::after {
+  content: """";
+  position: absolute;
+  left: -0.15em;
+  right: -0.15em;
+  top: 0.8em;
+  height: 0.4em;
+  border-radius: 2em;
+  background: #fffa50;
+  z-index: -1;
+}
+
<h1 class=""elementor-heading-title elementor-size-default"">
+  <span class=""yellowhighlight"">Flowster Affiliate Program</span> -
+  Activation Bonus
+</h1>
+
+
+

","

Use background to achieve this:

+

+
+
span.yellowhighlight {
+  --s:0.4em; /* control the size */
+  --d:2px;  /* control the distance */
+  background:
+    linear-gradient(#fffa50 0 0) 50% calc(100% - var(--d))/calc(100% - var(--s)) var(--s),
+    radial-gradient(farthest-side,#fffa50 98%,#0000) bottom var(--d) left  0/var(--s) var(--s),
+    radial-gradient(farthest-side,#fffa50 98%,#0000) bottom var(--d) right 0/var(--s) var(--s);
+  background-repeat:no-repeat;
+  -webkit-box-decoration-break:clone;
+          box-decoration-break:clone;
+}
+
<h1 class=""elementor-heading-title elementor-size-default"">
+  <span class=""yellowhighlight"">Flowster Affiliate Program</span> -
+  Activation Bonus
+</h1>
+
+<h1 class=""elementor-heading-title elementor-size-default"">
+  <span class=""yellowhighlight"">Flowster Affiliate<br> Program</span> -
+  Activation Bonus
+</h1>
+
+
+

+

To understand the trick use a different coloration for each background layer:

+

+
+
span.yellowhighlight {
+  --s:0.4em; /* control the size */
+  background:
+    linear-gradient(pink 0 0) bottom/calc(100% - var(--s)) var(--s),
+    radial-gradient(farthest-side,blue 98%,#0000) bottom left /var(--s) var(--s),
+    radial-gradient(farthest-side,red 98%,#0000) bottom right/var(--s) var(--s);
+  background-repeat:no-repeat;
+  -webkit-box-decoration-break:clone;
+          box-decoration-break:clone;
+}
+
<h1 class=""elementor-heading-title elementor-size-default"">
+  <span class=""yellowhighlight"">Flowster Affiliate Program</span> -
+  Activation Bonus
+</h1>
+
+<h1 class=""elementor-heading-title elementor-size-default"">
+  <span class=""yellowhighlight"">Flowster Affiliate<br> Program</span> -
+  Activation Bonus
+</h1>
+
+
+

",html +"how to hide a input type radio in IE and collect the value?

i have a "vue" application working properly in all browsers except internet explorer. +The main error I find in IE is the fact that it does not recognize the value of an input if I hide it and wrap it with an image. +This would be my html

+
      <div class="item-wrapper">
+        <form class="item-form" @submit.prevent="onSubmit">
+          <div class="cie-item-image" v-on:click="imageSelected = true">
+            <div class="cie-item-column">
+              <label>
+                <input
+                  type="radio"
+                  name="selectedItem"
+                  value="1"
+                  v-model="itemFormInfo.selectedItem"
+                  @change="onChangeItem($event)"
+                />
+                <img src="../../assets/1.png" />
+              </label>
+              <p class="cie-item-subtitle">Pen</p>
+            </div>
+            <div class="cie-item-column">
+              <label>
+                <input
+                  type="radio"
+                  name="selectedItem"
+                  value="2"
+                  v-model="itemFormInfo.selectedItem"
+                  @change="onChangeItem($event)"
+                />
+                <img src="../../assets/2.png" />
+              </label>
+              <p class="cie-item-subtitle">Pencil</p>
+            </div>
+            <div class="cie-item-column">
+              <label>
+                <input
+                  type="radio"
+                  name="selectedItem"
+                  value="3"
+                  v-model="itemFormInfo.selectedItem"
+                  @change="onChangeItem($event)"
+                />
+                <img src="../../assets/3.png" />
+              </label>
+              <p class="cie-item-subtitle">Rubber</p>
+            </div>
+          </div>
+
+
+
+
+

and here as the hidden with css

+

+.cie-item-image {
+  display: flex;
+  justify-content: space-around;
+}
+
+.cie-item-column img {
+  display: block; /* removes the spacing underneath the image */
+  width: 365px; /* sets the width to the parents width */
+  height: 244px; /* set the height to the parents height */
+  object-fit: cover; /* prevents image from stretching */
+  border: 3px solid transparent;
+  cursor: pointer;
+}
+
+.cie-item-column:hover .cie-item-subtitle:before,
+.cie-item-column:focus .cie-item-subtitle:before {
+  visibility: visible;
+  transform: scaleX(1);
+}
+
+.cie-item-column:hover img {
+  border: 3px solid $secondaryColor;
+  cursor: pointer;
+  opacity: 1;
+}
+
+/* IMAGE STYLES */
+[type="radio"] + img {
+  cursor: pointer;
+}
+
+/* CHECKED STYLES */
+[type="radio"]:checked + img {
+  outline: 2px solid $secondaryColor;
+  opacity: 1;
+}
+
+[type="radio"] + img {
+  opacity: 0.4;
+}
+
+.sub-title {
+  padding: 5px 0px 5px 0px;
+  display: flex;
+  justify-content: center;
+  color: $tertiaryColor;
+  font-family: "RalewayRegular";
+  font-weight: italic;
+  font-size: 20px;
+  margin-top: 30px;
+  font-weight: bolder;
+}
+
+
+
+

Here I leave a link in which you can see the correct operation, in which if I select an image is selected and the method onchange returns me the correct data.

+

https://codepen.io/CharlieJS/pen/QWNJvXz

+

As I explained before, in all browsers it is working correctly except in IE, in which if I don't show the input and select it directly it doesn't recognize the value when selecting the image (neither returns value nor gives the style of selected)

+

Why do I get this error only in internet explorer? +What can you do to unify the style criteria and apply something similar in IE?

+

a greeting and thank you all for your time and help

","

I have found a solution from @Qtax

+
label{
+    display: inline-block;
+}
+label img{
+    pointer-events: none;
+}
+
+

with this link

+

http://jsfiddle.net/VdJ9m/

+

and it works perfect

",html +"Select box doesn't obey css style?

I want the input box and select box to look the same and have the same size. The input box seems to obey the CSS style, but the select box gets a little smaller...

+
<!DOCTYPE html>
+<html>
+  <head>
+    <style>
+      .formfld {width:200px; height:50px; margin:0; padding:0;
+        border:1px; border-style:solid; border-color:black;}
+    </style>
+  </head>
+  <body>
+      <input type="text" name="amount" class="formfld" value="" />
+      <br/>
+      <select name="cardtype" class="formfld">
+        <option value="Visa">Visa</option>
+        <option value="Mastercard">Mastercard</option>
+      </select>
+  </body>
+</html>
+
","

Because of the select is default CSS style box-sizing: border-box; and inputhas not default css style box-sizing: border-box;

+

You should try this code or add in style box-sizing: border-box;

+

+
+
<!DOCTYPE html>
+<html>
+  <head>
+    <style>
+      .formfld {width:200px; height:50px; margin:0; padding:0;
+        border:1px; border-style:solid; border-color:black;box-sizing: border-box;}
+    </style>
+  </head>
+  <body>
+      <input type=""text"" name=""amount"" class=""formfld"" value="""" />
+      <br/>
+      <select name=""cardtype""  class=""formfld"">
+        <option value=""Visa"">Visa</option>
+        <option value=""Mastercard"">Mastercard</option>
+      </select>
+  </body>
+</html>
+
+
+

",html +"What is a good way to automatically access a file after it has been uploaded?

I have a input tag which I disabled and binded to another input tag to create a custom text together with the ability to open file explorer via it.

+

HTML:

+
<input id="fileInput" type="file" accept="application/JSON" style="display:none;" />
+
+<input title="Load a existing JSON file from your PC" id="btnUploadJSON" type="button"  value="Upload JSON" 
+onclick="document.getElementById('fileInput').click();"
+onMouseOver="this.style.backgroundColor='#efcc00'"onMouseOut="this.style.backgroundColor='#eee600'"/>
+
+

I have looked at a example here example of how to upload a json into variable but it uses 2 buttons. 1 to open explorer and second one to parse and display the json. I would like to achieve this only with 1 button. Ideally with something that checks if a file has been uploaded once file explorer closes and then automatically performs the import function.

+

So my question probably is, Is there a way to detect when file explorer closes and if a file has been selected?

+

Here is my JS function, the problem is it triggers before I can choose a file so length <= 0 is triggered before file explorer. Is it possible to make it wait until file explorer closes and then perform the onclick()?

+

JavaScript:

+
document.getElementById('btnUploadJSON').onclick = function() {
+    //uploading a json file via file explorer
+    var files = document.getElementById('fileInput').files
+    console.log(files)
+    if (files.length <= 0) {
+        alert("Json file seems to be empty or incorrect format, please double check you are uploading the right file!")
+        return false
+    }
+
","

Simply change this line:

+
- document.getElementById('btnUploadJSON').onclick = function() {
++ document.getElementById('fileInput').onchange = function() {
+
",html +"`div` not obeying event coordinates

My current code is (courtesy Peter):

+
$(document).ready(function() {
+    $.ajax({
+        type: 'GET',
+        url: '', //contains a list of paths
+        data: { get_param: 'value' },
+        dataType: 'json',
+        success: function (data) {
+            element = data[0];
+            $.each(data, function (index, element) {
+                $(".gallery").append($(`<li><img src="${`images/square/${element.path}`}" 
+                alt="${element.title}"id="${element.path}"city="${element.city}"
+                taken="${element.taken}"/></li>`));
+            });
+        },
+    });
+});
+
+var df = $.Deferred();
+const xOffset = 3;
+const yOffset = 3;
+
+$(document).on('mouseenter', '.gallery li', function() {
+    $(this).find('img').addClass("gray");
+    var imgs = `<div class="preview"> <img src="images/medium/${$(this).find('img').attr('id')}"
+                alt="${$(this).find('img').attr('alt')}"/>`;
+    var info = `<p>
+                'Title': ${$(this).find('img').attr('alt')}<br>
+                'City': ${$(this).find('img').attr('city')}<br>
+                'Date Taken': ${$(this).find('img').attr('taken')}
+                </p></div>`;
+    imgs += info;
+    // $(".images_append").html($(imgs));
+    let imgObj = $(imgs);
+    imgObj.attr("id", "preview-"+$(this).index());
+    $("body").append(imgObj );
+    df.resolve( true );
+});
+
+$.when( df ).done(function ( v ) {
+    if(v) {
+        $(document).on("mousemove", '.gallery li', function(event) {
+            event.stopPropagation();
+            $("#preview-"+$(this).index())
+              .css("top",((event.pageY) + xOffset)+"px")
+              .css("left",((event.pageX) + yOffset)+"px");
+        });
+  
+        $(document).on("mouseout", '.gallery li', function() {
+            $("#preview-"+$(this).index()).remove();
+            $(this).find('img').removeClass("gray");
+        });
+    }
+  });
+
+

Basically when mouse is hovered, load up a bigger image, and when it is removed, remove the preview class.

+

Currently the output shows up like this. Images show up at the bottom for some reason and not following event coordinates from mousemove.

+

Here's the CSS

+
#preview {
+    position: absolute;
+    padding: 10px 10px 0 10px;
+    /* display: none; */
+    background-color: #424242;
+    /* z-index: 9999; */
+    /* display: flex; */
+}
+#preview p {
+    color: white; 
+    margin-top: 3px;
+    margin-bottom: 3px;
+}
+
+.gray {
+     filter: grayscale(100%);
+    -webkit-filter: grayscale(100%);
+}
+
+

I'm basically not touching HTML. So it's a simple HTML page.

+

Can you please suggest why is it not following these coordinates ?

","

You have to slightly change your CSS. In the code you posted the URL's of the images are not working, but with the following CSS you will see the #preview-... element.

+

I also need to explain better the changes that are applied in the snippet at the end of the answer.

+

First: thing that it is changed is that the id of the container element displayed on hover is not preview but preview-1, preview-2, ... where 0,1,2,...,n is the index of the li element where the image is located. You can understand why this is done, it is ideal to have unique identification of elements. It works better when you have to handle those elements with Javascript.

+

Second: To work using $.Deffered is optional you could skip it if you want (check the last code snippet). But since it is used in this paradigm then it is needed that the CSS of the [id^="preview-"] elements to have display: none and to switch to display: block only after it is correctly positioned to the DOM. That is why there is this small addition in Javascript.

+
$("#preview-"+$(this).index())
+ .css("top",((event.pageY) + xOffset)+"px")
+ .css("left",((event.pageX) + yOffset)+"px")
+ .css("display","block"); 
+
+

The above was needed because without this sometimes the [id^="preview-"] element appeared in the bottom of the page (the similar effect you are currently facing).

+

PS: If there is any other CSS that is included in your actual project, and the elements of the example are affected, then those values have to be overridden.

+

+
+
$(document).ready(function() {
+    $.ajax({
+        type: 'GET',
+        url: 'https://raw.githubusercontent.com/prajjwal1/uploads/master/data.json',
+        data: { get_param: 'value' },
+        dataType: 'json',
+        success: function (data) {
+            element = data[0];
+            $.each(data, function (index, element) {
+                $("".gallery"").append($(`<li><img src=""${`images/square/${element.path}`}"" 
+                alt=""${element.title}""id=""${element.path}""city=""${element.city}""
+                taken=""${element.taken}""/></li>`));
+            });
+        },
+    });
+});
+
+var df = $.Deferred();
+const xOffset = 3;
+const yOffset = 3;
+
+$(document).on('mouseenter', '.gallery li', function() {
+    $(this).find('img').addClass(""gray"");
+    var imgs = `<div class=""preview""> <img src=""images/medium/${$(this).find('img').attr('id')}""
+                alt=""${$(this).find('img').attr('alt')}""/>`;
+    var info = `<p>
+                'Title': ${$(this).find('img').attr('alt')}<br>
+                'City': ${$(this).find('img').attr('city')}<br>
+                'Date Taken': ${$(this).find('img').attr('taken')}
+                </p></div>`;
+    imgs += info;
+    // $("".images_append"").html($(imgs));
+    let imgObj = $(imgs);
+    imgObj.attr(""id"", ""preview-""+$(this).index());
+    $(""body"").append(imgObj );
+    df.resolve( true );
+});
+
+$.when( df ).done(function ( v ) {
+    if(v) {
+        $(document).on(""mousemove"", '.gallery li', function(event) {
+            event.stopPropagation();
+            $(""#preview-""+$(this).index())
+              .css(""top"",((event.pageY) + xOffset)+""px"")
+              .css(""left"",((event.pageX) + yOffset)+""px"")
+              .css(""display"",""block"");
+        });
+  
+        $(document).on(""mouseout"", '.gallery li', function() {
+            $(""#preview-""+$(this).index()).remove();
+            $(this).find('img').removeClass(""gray"");
+        });
+    }
+  });
+
[id^=""preview-""] {
+  position: absolute;
+  z-index: 9999;
+  padding: 10px;
+  display: none;
+  background-color: #424242;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  align-content: center;
+  width: 11rem; // you may use percentage e.g. 20% or viewport units here e.g. 10vw
+}
+[id^=""preview-""] img {
+  width: 100%;
+  height: auto;
+}
+
+.gray {
+  filter: grayscale(100%);
+  -webkit-filter: grayscale(100%);
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<main class=""container"">
+  <ul class=""gallery"">
+  </ul>
+</main>
+
+
+

+

Same example without $.Deffered.

+

+
+
$(document).ready(function() {
+  $.ajax({
+    type: 'GET',
+    url: 'https://raw.githubusercontent.com/prajjwal1/uploads/master/data.json',
+    data: {
+      get_param: 'value'
+    },
+    dataType: 'json',
+    success: function(data) {
+      element = data[0];
+      $.each(data, function(index, element) {
+        $("".gallery"").append($(`<li><img src=""${`images/square/${element.path}`}"" 
+                alt=""${element.title}""id=""${element.path}""city=""${element.city}""
+                taken=""${element.taken}""/></li>`));
+      });
+    },
+  });
+});
+
+
+const xOffset = 3;
+const yOffset = 3;
+
+$(document).on('mouseenter', '.gallery li', function() {
+  $(this).find('img').addClass(""gray"");
+  var imgs = `<div class=""preview""> <img src=""images/medium/${$(this).find('img').attr('id')}""
+                alt=""${$(this).find('img').attr('alt')}""/>`;
+  var info = `<p>
+                'Title': ${$(this).find('img').attr('alt')}<br>
+                'City': ${$(this).find('img').attr('city')}<br>
+                'Date Taken': ${$(this).find('img').attr('taken')}
+                </p></div>`;
+  imgs += info;
+  let imgObj = $(imgs);
+  imgObj.attr(""id"", ""preview-"" + $(this).index());
+  $(""body"").append(imgObj);
+});
+
+
+$(document).on(""mousemove"", '.gallery li', function(event) {
+  event.stopPropagation();
+  $(""#preview-"" + $(this).index())
+    .css(""top"", ((event.pageY) + xOffset) + ""px"")
+    .css(""left"", ((event.pageX) + yOffset) + ""px"");
+});
+
+$(document).on(""mouseout"", '.gallery li', function() {
+  $(""#preview-"" + $(this).index()).remove();
+  $(this).find('img').removeClass(""gray"");
+});
+
[id^=""preview-""] {
+  position: absolute;
+  z-index: 9999;
+  padding: 10px;
+  background-color: #424242;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  align-content: center;
+  width: 11rem; // you may use percentage e.g. 20% or viewport units here e.g. 10vw
+}
+
+[id^=""preview-""] img {
+  width: 100%;
+  height: auto;
+}
+
+.gray {
+  filter: grayscale(100%);
+  -webkit-filter: grayscale(100%);
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<main class=""container"">
+  <ul class=""gallery"">
+  </ul>
+</main>
+
+
+

",html +"Items inside flexbox container are flowing out of container

I am creating a portfolio page in which I am showing my 6 projects, 3 in a row using flexbox. The items inside are flowing out of the flexbox even though I have used flex-wrap. I am relatively new to this so I don't know what is happening.

+

+

The red border is my flexbox container and it contains six div elements. Inside each div element, there is one image and another div element which is like a caption. Each image is of a different size

+

HTML Code:

+
<section id="work">
+    <h1><u>These are some of my projects</u></h1>
+    <div id="work-container">
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/tribute.jpg" alt="">
+            <div id="project-title">Tribute Page</div>
+        </div>
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/random-quote-machine.png" alt="">
+            <div id="project-title">Random Quote Machine</div>
+        </div>
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/calc.png" alt="">
+            <div id="project-title">JavaScript Calculator</div>
+        </div>
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/map.jpg" alt="">
+            <div id="project-title">Map Data Across the Globe</div>
+        </div>
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/wiki.png" alt="">
+            <div id="project-title">Wikipedia Viewer</div>
+        </div>
+        <div class="work-block">
+            <img src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/tic-tac-toe.png" alt="">
+            <div id="project-title">Tic Tac Toe Game</div>
+        </div>
+    </div>
+    <button id="view-more"></button>
+</section>
+
+

CSS Used:

+
#work-container{
+    display: flex;
+    flex-direction: row;
+    justify-content: space-around;
+    flex-wrap: wrap;
+    width: 100%;
+    border: 5px solid red;
+
+}
+
+.work-block{
+    width: 28%;
+    margin: 20px;
+}
+
+@media (max-width: 1000px) {
+    .work-block{
+        width: 45%;
+    }
+}
+
+#work-container img{
+    height: calc(100% );
+    width:100%;
+    margin:0;
+    padding: 0;
+    object-fit: cover;
+    flex:none;
+} 
+
+

There is one particular line which is enabling equal height for all images height: calc(100% );. I don't know how it works, I took it from the internet. It was used to have the equal height for each image.

+

Also, the bottom and the top margin between blocks is not working.

+

I want some help in wrapping content inside container properly and understanding how height: calc(100% ); works.

+

Complete Code: https://codepen.io/tushar_432/pen/poyxmyZ

","

Don't make the image height:100%, this will make the image take all the space pushing the text outside thus the overflow. Use flexbox to make it fill all the space minuse the text space:

+

+
+
#work-container {
+  display: flex;
+  flex-direction: row;
+  justify-content: space-around;
+  flex-wrap: wrap;
+  width: 100%;
+  border: 5px solid red;
+}
+
+.work-block {
+  width: 28%;
+  margin: 20px;
+}
+
+@media (max-width: 1000px) {
+  .work-block {
+    width: 45%;
+  }
+}
+.work-block {
+  display:flex; /* here */
+  flex-direction:column; /* here */
+}
+.work-block img {
+  width: 100%;
+  margin: 0;
+  padding: 0;
+  object-fit: cover;
+  flex: 1; /* here */
+}
+
<section id=""work"">
+  <h1><u>These are some of my projects</u></h1>
+  <div id=""work-container"">
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/tribute.jpg"" alt="""">
+      <div id=""project-title"">Tribute Page</div>
+    </div>
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/random-quote-machine.png"" alt="""">
+      <div id=""project-title"">Random Quote Machine</div>
+    </div>
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/calc.png"" alt="""">
+      <div id=""project-title"">JavaScript Calculator</div>
+    </div>
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/map.jpg"" alt="""">
+      <div id=""project-title"">Map Data Across the Globe</div>
+    </div>
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/wiki.png"" alt="""">
+      <div id=""project-title"">Wikipedia Viewer</div>
+    </div>
+    <div class=""work-block"">
+      <img src=""https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/images/tic-tac-toe.png"" alt="""">
+      <div id=""project-title"">Tic Tac Toe Game</div>
+    </div>
+  </div>
+</section>
+
+
+

",html +"place at middle and left end

I have a screen where I want to place the first, main text item (Filter)in the exact middle of the screen while the second item (All Delete) should be at the right end. Both of them should be in the same line.

+

I would prefer not to use padding/margins since they can vary in different phone sizes. I am already using text-align but it doesn't work for me.

+

+export default function App() {
+  return (
+    <View style={styles.container}>
+       <View style={styles.topTextContainer}>
+            <Text style={styles.filterText}>Filter</Text>
+            <Text style={styles.deleteAllText}>All Delete</Text>
+          </View>
+    </View>
+  );
+}
+
+const styles = StyleSheet.create({
+  container: {
+    flex: 1,
+},
+  topTextContainer: {
+    paddingTop: moderateScale(35),
+    flexDirection: 'row',
+    justifyContent: 'center',
+    alignItems: 'center',
+  },
+  filterText: {
+    fontSize: moderateScale(15),
+    fontWeight: 'bold',
+    textAlign: 'center'
+  },
+  deleteAllText: {
+    fontSize: moderateScale(13),
+    color: '#363636',
+    fontWeight: '300',
+    marginLeft: moderateScale(75),
+  },
+});
+
+

Codesandbox: https://snack.expo.io/@nhammad/frowning-bagel

","

You can use a absolute position for the delete button and set right:0 like below.

+
deleteAllText: {
+    fontSize: moderateScale(13),
+    color: '#363636',
+    fontWeight: '300',
+    position: 'absolute',
+    right: 0
+  }
+
+

The other option is to use marginLeft:'auto' for the both the texts which can help but wont keep the first one in center.

",html +"Have background drawn over a div

So I have a div that displays a big title with two lines on its sides that fill the rest of the width.

+

However now I need to have some text drawn behind this, and because I am drawing the title's bars with background-color they are drawn behind the text.

+

How can I draw it in such a way that the displayed components from back to front are [bg background-color]->[bg:before]->[title:before/after background-color]->[title]?

+

Here is the code I have:

+

+
+
#bg
+{
+  width: 100%;
+  height: 100%;
+  background-color: silver;
+  z-index: -1;
+}
+
+#bg:before
+{
+  content: 'Background';
+  position: absolute;
+  font-size: 3em;
+  color: white;
+  user-select: none;
+}
+
+#bg *
+{
+  z-index: 0;
+}
+
+.title
+{
+  display: flex;
+  flex-direction: row;
+  align-items: center;
+}
+
+.title:after, .title:before
+{
+  content: '';
+  width: 50%;
+  background-color: black;
+  height: 0.2em;
+  margin-left: 20px;
+  margin-right: 20px;
+}
+
+.section_titre h1
+{
+  font-size: 1em;
+  margin: 0px;
+}
+
<div id=""bg"">
+  <div class=""title"">
+    <h1>Example</h1>
+  </div>
+</div>
+
+
+

","
+

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.

+
+

We use z-index

+

The of Back to front

+
    +
  • [bg background-color] -> [bg:before] -> [title:before/after background-color] -> [title]
  • +
+

So,

+

Firstly add z-index(1) to bg background-color

+
#bg{
+  z-index: 1;
+  position:relative;// z-index work with other than static position
+}
+
+

Here,I used position:relative;. Why? Using positioning in z-index?

+
+

z-index has no effect on this element since it’s not a positioned element. Try setting its position property to something other than static.

+
+

Then add z-index(2) to bg:before

+
#bg:before {z-index:2;}
+
+

Then add z-index(3) to title:before/after background-color

+
.title:after, .title:before {z-index:3;}
+
+

Finally z-index(4) to title

+
.title{z-index:4;position:relative;}
+
+

Working Demo

+

+
+
#bg{
+  width: 100%;
+  height: 100%;
+  background-color: silver;
+  z-index: 1;
+  position:relative;
+}
+
+#bg:before{
+  content: 'Background';
+  position: absolute;
+  font-size: 3em;
+  color: white;
+  user-select: none;
+  z-index:2;
+}
+
+.title{
+  display: flex;
+  flex-direction: row;
+  align-items: center;
+  z-index:4;
+  position:relative;
+}
+
+.title:after, .title:before{
+  content: '';
+  width: 50%;
+  background-color: black;
+  height: 0.2em;
+  margin-left: 20px;
+  margin-right: 20px;
+  z-index:3;
+}
+
+.section_titre h1{
+  font-size: 1em;
+  margin: 0px;
+}
+
<div id=""bg"">
+  <div class=""title"">
+    <h1>Example</h1>
+  </div>
+</div>
+
+
+

",html +"Floating a canvas next to a paragraph

I'm trying to achieve this placement, where the canvas is floating to the right of a paragraph:

+

+

I've been following similar settings that work for floating images, but I'm not having much luck with canvases.

+

Here's what I've tried:

+

CSS

+
.container
+{
+    overflow: hidden;
+    width: 100%;
+}
+.container p
+{
+    display: block;
+    width: 50%;
+    margin: 0;
+}
+.container canvas
+{
+    margin: 0;
+    float: right;
+    border:0.2vw solid blue;
+}
+
+

HTML

+
<div class="container">
+    <p>Lorem ipsum dolor sit amet...</p>
+    <canvas>Your browser does not support the canvas element.</canvas>
+</div>
+
","

you can add another div and set width to 50% for float right the canavs or set the canvas float:left , container p width: 25%; with padding right for adjust your space

+

+
+
.container
+{
+    overflow: hidden;
+    width: 100%;
+}
+.container p
+{
+    width: 25%;
+    margin: 0;
+    margin: 0;
+    float: left;
+    padding-right: 20px;
+}
+.container canvas
+{
+    margin: 0;
+    float: left;
+    border:0.2vw solid blue;
+}
+
<div class=""container"">
+    <p>Lorem ipsum dolor sit amet... Lorem ipsum dolor sit amet..Lorem ipsum dolor sit amet..Lorem ipsum dolor sit amet..Lorem ipsum dolor sit amet..</p>
+    <canvas>Your browser does not support the canvas element.</canvas>
+</div>
+
+
+

",html +"How can I constrain column widths without text clipping or wrapping?

I would like to constraint table columns width with no text clipping (no wrapping).

+

I came accross many many threads on Stackoverflow (sorry for duplicates), but none of them really gives straightforward solutions, even though I believe it is a rather simple issue...

+

First all of all, do I have to contrainst both header and content column width ?

+

I don't really want to insert div inside th / td (I haven't found straightforward solution anyway).

+

I believe that the white-space: nowrap; and text-overflow: clip; table styles width <th style="width: 100px>...</th> (idem td) would be enought, but it doesn't work). Does the CSS order of them matter?

+

I don't understand why something as simple as follows doesn't work..

+
<th style="width: 72px; text-overflow: clip; white-space: nowrap;">ABCDEFGHIJKLMNOPQRSTUVWXY abcdefghijklmnopqrstuvwyz</th><!-- Of course, specified in CSS file -->
+
+

and would like to see something like:

+
----------------
+   |ABCDEFG|
+----------------
+
+

UPDATE

+

CSS styles

+
th {
+    max-width: 72px;
+    white-space: nowrap;
+    text-overflow: clip;
+    overflow: hidden;
+}
+
+td {
+    max-width: 72px;
+    white-space: nowrap;
+    text-overflow: clip;
+    overflow: hidden;
+}
+
+

Razor page

+
<tH @Html.Raw(Helpers.HTMLTagAttribute(Enums.FieldType.Date))>
+...
+<td @Html.Raw(Helpers.HTMLTagAttribute(Enums.FieldType.Date))>
+...
+
+

Where the helper method HTMLBodyTagStyleAttributes(FieldType fieldType) uses the HTMLWidth(FieldType fieldType) defined as follows with FieldType an enum relative to each column:

+
private static string HTMLWidth(FieldType fieldType)
+{
+    string width;
+
+    switch (fieldType)
+    {
+        case FieldType.Date:
+            width = "72px";
+            break;
+        // ...
+        default:
+            width = "86px";
+            break;
+    }
+
+    return width != "" ? $"max-width: {width};" : "";
+}
+
+

Thanks for any insights!

","

try adding a max-width and overflow: hidden, e.g.:

+
th {
+  max-width: 72px;
+  text-overflow: clip; 
+  white-space: nowrap;
+  overflow: hidden;
+}
+
",html +"How to send props to a component in react with conditional?

I'm trying to pass a prop to a relative child in react, only if it meets certain conditions.

+

I know that you can make a type of conditional to send props like this:

+

+
+
<SomeComponent
+
+ConditionalProp={
+(this.state.exampleData === 'some string') ? this.state.exampleData : null
+}
+
+/>
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js""></script>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js""></script>
+
+
+

+

But I need to do more validations, so far this is what I have:

+

+
+
<MyComponent
+
+ConditionalProps={ 
+  (this.props.channel && this.props.some) ?  
+    (this.props.some.conv && (this.props.some.conv.id === this.props.channel.conv.id) ? 
+        this.props.channel :''
+    (this.state.contentId === this.props.channel)? this.props.channel:''
+): null
+
+}
+
+/>
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js""></script>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js""></script>
+
+
+

+

Let me explain, what I want to do is: if channel and some exist, two possible cases will be validated: if some.conv exists and also some.conv.id is === channel.conv.id? then it must be passed as prop channel.

+

If that is false and contentId exists and also is exactly equal to channel then channel is passed.

+

If neither of those cases is true, a null or an empty string must be passed '' (I have no problem with either of the two)

+

I am not very sure that what I did is correct and what I am sure is that it is not the best way to carry it out

","

If you are using ES7, you can try null propagation operator:

+
this.props.channel?.conv?.id === this.props.some?.conv?.id
+
+

So you don't have to check if this.props.channel and this.props.channel.conv exists.

+

Also you can try anonymous function:

+
<MyComponent
+  ConditionalProps={(() => {
+    if (this.props.some?.conv?.id === this.props.channel?.conv?.id) {
+      // some more code
+      // return ...
+    }
+
+    return null;
+  })()}
+/>;
+
+

Also, your code won't work because you try to compare something with Object at:

+
this.state.contentId === this.props.channel
+
+

such as {} === {} will be false. Use JSON.stringify() and compare two strings.

",html +"How can I put my header in top of everything?

My header have the property "position: fixed", but, some images in the body has the property "filter: grayscale(100%)", when I scroll the page, the images are showed in front of my header.

+

HTML:

+
<header><header>
+<img>
+<img>
+<img>
+
+
+

CSS:

+
header{
+    position: fixed;
+}
+
+img{
+    filter: grayscale(100%);
+}
+
+

How can i put them behind my header?

","

Have you tried

+
header {
+  z-index: 1;
+  position: fixed;
+}
+
+

If you have other elements with z-index`s set, you'll need to manage them in order.

+

You can read more about z-index here

",html +"Maintaining header/footer position when using grid layout + bootstrap + table overflow

Given the following page layout I need to make sure that the page itself is not scrollable (page height == 100vh), but the table within, if needed is provides the scrolling. +The header and the footer should be placed at the top and bottom of the page, not effected by the table's content. Meaning, if the table content exceeds the available vertical space, it can not push the footer downward and instead provide scrolling in place.

+

The current layout is a root div that starts with a Bootstrap4 navbar following it a page_container that sets up a grid layout for its internal header, content, footer divs.

+

JSFiddle with a layout containing a table that does not exceeds page height: https://jsfiddle.net/kvdyg4q5/

+

JSFiddle with a layout containing a table that exceeds page height: https://jsfiddle.net/1nv7hqg6/

+

AS you can see, the table is pushing the footer down.. that is the issue.

+

The css in use

+
<style type="text/css">
+    #root {
+      height: 100%;
+      min-height: 100vh;
+      max-height: 100vh;
+    }
+
+    .page_container {
+      max-height: calc(100vh - 70px);
+      height: calc(100vh - 70px);
+      min-height: calc(100vh - 70px);
+    }
+
+    .table_container {
+      display: grid;
+      height: 100%;
+      grid-template-rows: auto 1fr auto;
+    }
+
+    .table_body {
+      display: block;
+      height: 100%;
+      overflow-y: scroll;
+    }
+</style>
+
+

The HTML layout

+
<body>
+<div id="root">
+    <nav class="navbar navbar-expand-lg navbar-dark bg-dark"><a class="navbar-brand" href="#">Company</a>
+        <div class="collapse navbar-collapse" id="navbarNav">
+            <ul class="navbar-nav mr-auto">
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar1</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar2</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar3</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar4</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar5</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar6</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar7</a></li>
+                <li class="nav-item"><a id="vehicles_navbar" class="nav-link" href="#">navbar8</a></li>
+
+            </ul>
+        </div>
+    </nav>
+    <div style="padding: 6px;">
+        <div class="page_container">
+            <div class="table_container">
+                <div>
+                    <h1>HEADER</h1>
+                </div>
+                <div>
+                    <div>
+                        <table class="table">
+                            <thead>
+                                <tr>
+                                    <th scope="col">Column 1</th>
+                                    <th scope="col">Column 2</th>
+                                    <th scope="col">Column 3</th>
+                                    <th scope="col"> Column 4 </th>
+                                    <th scope="col">Column 5</th>
+                                </tr>
+                            </thead>
+                            <tbody class="table_body">
+                                <tr>
+                                    <td colspan="5">
+                                        <h3>Row</h3>
+                                    </td>
+                                </tr>
+                                <tr>
+                                    <td colspan="5">
+                                        <h3>Row</h3>
+                                    </td>
+                                </tr>
+                                <tr>
+                                    <td colspan="5">
+                                        <h3>Row</h3>
+                                    </td>
+                                </tr>
+                                <tr>
+                                    <td colspan="5">
+                                        <h3>Row</h3>
+                                    </td>
+                                </tr>
+                                <!-- more rows...-->
+
+                            </tbody>
+                        </table>
+                    </div>
+                </div>
+                <div>
+                    <h2>Footer</h2>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+
","

You don't need CSS grid for this, You can simply use flexbox and make content flex:1 0 0 with overflow:auto

+

+
+
[root] {
+  height: 100vh;
+  display: flex;
+  flex-direction: column;
+}
+
+[page] {
+  flex: 1;
+  display: flex;
+  flex-direction: column;
+}
+
+[content] {
+  flex: 1 0 0;
+  overflow: auto;
+}
+
+
+/* Sticky Header */
+table {
+  position: relative;
+}
+
+th {
+  position: sticky;
+  top: 0;
+  background: black;
+  color: white;
+}
+
<link rel=""stylesheet"" href=""https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"" integrity=""sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"" crossorigin=""anonymous"">
+<div root>
+  <div navbar>
+    <nav class=""navbar navbar-expand-lg navbar-dark bg-dark""><a class=""navbar-brand"" href=""#"">Company</a><button class=""navbar-toggler"" type=""button"" data-toggle=""collapse"" data-target=""#navbarNav"" aria-controls=""navbarNav"" aria-expanded=""false"" aria-label=""Toggle navigation""><span class=""navbar-toggler-icon""></span></button>
+      <div class=""collapse navbar-collapse"" id=""navbarNav"">
+        <ul class=""navbar-nav mr-auto"">
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar1</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar2</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar3</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar4</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar5</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar6</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar7</a></li>
+          <li class=""nav-item""><a id=""vehicles_navbar"" class=""nav-link"" href=""#"">navbar8</a></li>
+
+        </ul>
+      </div>
+    </nav>
+  </div>
+  <div page>
+    <div header>
+      <h1>HEADER</h1>
+    </div>
+    <div content>
+      <div>
+        <table class=""table"">
+          <thead>
+            <tr>
+              <th scope=""col"">Column 1</th>
+              <th scope=""col"">Column 2</th>
+              <th scope=""col"">Column 3</th>
+              <th scope=""col""> Column 4 </th>
+              <th scope=""col"">Column 5</th>
+            </tr>
+          </thead>
+          <tbody class=""table_body"">
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+            <tr>
+              <td colspan=""5"">
+                <h3>Row</h3>
+              </td>
+            </tr>
+          </tbody>
+        </table>
+      </div>
+    </div>
+    <div footer>
+      <h2>Footer</h2>
+    </div>
+  </div>
+</div>
+
+
+

",html +"How do I overcome browser lag because of large file upload with AJAX (axios)?

I've implemented a simple multiple file upload function with ReactJS in the frontend using axios for AJAX requests.

+
const FileUploader = () => {
+
+  const uploadFiles = files => {
+
+    const formData = new FormData();
+    files.forEach( file => {
+      formData.append("files", file );
+    })
+
+    axios
+    ({
+      method: "POST",
+      url: '...',
+      data: formData,
+      headers: { "Content-Type": "multipart/form-data", },
+      onUploadProgress: e => console.log(e.loaded, e.total)
+    })
+    .then(( response ) => console.log( response ))
+    .catch(( error )   => console.error( error ))
+  }
+
+  return (
+   
+    <input type="file" onChange={ e => uploadFiles( e.target.files ) } />
+
+  )
+}
+
+

I've noticed that while uploading large or many files at a time, not just the browser but my OS seems to lag.

+

Looking for a workaround, I learned the need to use Streams API to tackle this problem by sending files over the network chunk by chunk and not whole at a time.

+

https://developer.mozilla.org/en-US/docs/Web/API/Streams_API

+
+

The Streams API allows JavaScript to programmatically access streams of data received over the network and process them as desired by the developer.

+
+

https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams

+

https://developer.mozilla.org/en-US/docs/Web/API/WritableStream

+

However, I see very few resources on the internet on this topic probably because Streams API is a relatively new introduction to the web and is still experimental.

+

There are lots of articles out there explaining the implementation in the backend but very few on the frontend.

+

Where do I begin? What might the code look like?

","

Notice that Streams are aimed at reading/processing the file on the client and not for uploading.

+
+

With Streams being available to JavaScript, this all changes — you can +now start processing raw data with JavaScript bit by bit as soon as it +is available on the client-side, without needing to generate a buffer, +string, or blob.

+
+

However, you can achieve chunked uploads using XHR. There are several libraries that support it.

+

For React, there's react-uploady. Check out its chunked upload support. It also supports resumable uploads (Tus) for servers that also implement the protocol

",html +"How to select the input with jquery?

I want to get the value of a input and i want to do it with jquery.

+

I just want to get the value of the hidden input with name="picture"when I click on حذف این بخش button which have onclick="deleteDefaultSection($(this)). +I have used .parent() function to come out of that scope. But when I'm in the div with class="ribbon-wrapper card". I cant go into the div with class="col-md-12" and select the value of hidden input with class="picture" in it.

+

+
+
<div class=""ribbon-wrapper card"">
+  <div class=""card-header"">
+    <div class=""ribbon ribbon-default pull-right"">
+      <input type=""text"" style=""height: 24px;
+      border-radius: 3px;
+      border: none;
+      padding: 5px;
+      font-size: 12px;
+      width: 130px;
+      text-align: center;
+      font-weight: normal;"" name=""name"" class=""nameSection"" placeholder=""بازه زمانی را وارد کنید"" value=""<%= analysis.timeFrames[i] %>"" />
+    </div>
+  </div>
+  <div class=""card-body"">
+    <div style=""float: right;
+    top: 15px;
+    right: 20px;"">
+      <button type=""button"" class=""btn btn-sm btn-outline-primary"" data-toggle=""modal"" data-target=""#AddSection"" data-type="""">اضافه
+                                                    کردن عکس
+                                                </button>
+      <button type=""button"" class=""btn btn-sm btn-outline-danger"" onclick=""deleteDefaultSection($(this))"">حذف این بخش
+                                                </button>
+    </div>
+  </div>
+  <!-- This row is for showing the uploaded image and its description -->
+  <div class=""row"">
+    <div class=""col-md-12"" style=""text-align: center;"">
+      <input type=""hidden"" class=""picture"" name=""picture"" value=""<%= analysis.images[i] %>"">
+      <input type=""hidden"" class=""details"" name=""details"" value=""<%= analysis.imagesDesc[i] %>"">
+      <input type=""hidden"" class=""sectionname"" name=""timeFrames"" value=""<%= analysis.timeFrames[i] %>"">
+      <div class=""boxUploadImage Active"" data-typeSection=""<%= i %>"" data-name=""<%= i + 64 %>"">
+        <img onclick=""viewPicture($(this))"" src=""<%= analysis.images[i] %>"" width=""80%"" height=""200px"">
+        <div data-toggle=""modal"" data-target=""#viewDiscription"" onclick=""viewDetails($(this))"" class=""p "">
+          <%= analysis.imagesDesc[i] %>
+        </div>
+        <div class=""boxBotton row my-5"">
+          <div class=""col-lg-7 mr-4"">
+            <button class=""btn btn-block btn-sm btn-twitter"" data-toggle=""modal"" data-target=""#EditSection"" onclick=""editSection($(this), event)"">ویرایش</button>
+          </div>
+          <div class=""col-lg-4"">
+            <button class=""btn btn-block btn-sm btn-danger deleteSection"" onclick=""deleteSection($(this))"">حذف</button>
+          </div>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

","

You can do it like this:

+
function deleteDefaultSection(obj) {
+  var pic = obj.closest(".card").find('[name="picture"]');
+  console.log(pic.val());
+}
+
+

.closest(".card") travels up in the html and selects the first element with the class card it finds.

+

Then you can use .find() and combine it with [name="picture"] to get the element that has the name attribute with the value picture of it

+

Demo

+

+
+
function deleteDefaultSection(obj) {
+  var pic = obj.closest("".card"").find('[name=""picture""]');
+  console.log(pic.val());
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""ribbon-wrapper card"">
+  <div class=""card-header"">
+    <div class=""ribbon ribbon-default pull-right"">
+      <input type=""text"" style=""height: 24px;
+                                                border-radius: 3px;
+                                                border: none;
+                                                padding: 5px;
+                                                font-size: 12px;
+                                                width: 130px;
+                                                text-align: center;
+                                                font-weight: normal;"" name=""name"" class=""nameSection"" placeholder=""بازه زمانی را وارد کنید"" value=""<%= analysis.timeFrames[i] %>"" />
+    </div>
+  </div>
+  <div class=""card-body"">
+    <div style=""float: right;
+                                                top: 15px;
+                                                right: 20px;"">
+      <button type=""button"" class=""btn btn-sm btn-outline-primary"" data-toggle=""modal"" data-target=""#AddSection"" data-type="""">اضافه
+                                                    کردن عکس
+                                                </button>
+      <button type=""button"" class=""btn btn-sm btn-outline-danger"" onclick=""deleteDefaultSection($(this))"">حذف این بخش
+                                                </button>
+    </div>
+  </div>
+  <!-- This row is for showing the uploaded image and its description -->
+  <div class=""row"">
+    <div class=""col-md-12"" style=""text-align: center;"">
+      <input type=""hidden"" class=""picture"" name=""picture"" value=""Hiddenvalue"">
+      <input type=""hidden"" class=""details"" name=""details"" value=""<%= analysis.imagesDesc[i] %>"">
+      <input type=""hidden"" class=""sectionname"" name=""timeFrames"" value=""<%= analysis.timeFrames[i] %>"">
+      <div class=""boxUploadImage Active"" data-typeSection=""<%= i %>"" data-name=""<%= i + 64 %>"">
+        <img onclick=""viewPicture($(this))"" src=""<%= analysis.images[i] %>"" width=""80%"" height=""200px"">
+        <div data-toggle=""modal"" data-target=""#viewDiscription"" onclick=""viewDetails($(this))"" class=""p "">
+          <%= analysis.imagesDesc[i] %>
+        </div>
+        <div class=""boxBotton row my-5"">
+          <div class=""col-lg-7 mr-4"">
+            <button class=""btn btn-block btn-sm btn-twitter"" data-toggle=""modal"" data-target=""#EditSection"" onclick=""editSection($(this), event)"">ویرایش</button>
+          </div>
+          <div class=""col-lg-4"">
+            <button class=""btn btn-block btn-sm btn-danger deleteSection"" onclick=""deleteSection($(this))"">حذف</button>
+          </div>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"Best way to access a value from a database with Ruby on Rails

I'm creating an educaional managemnet system that allows you to keep track of students, classes, departments, sections, professors, and semesters using ruby on rails. Every table except sections_student was created using rails g scaffold. Here is my current ERD. +ERD

+

I'm trying to edit the _form.html.erb for students to display checkboxes so the student can add classes. I have it set up and it shows there are courses but they don't show the course number. I believe it is showing the address of the course object Student _form.html

+

This is the piece of code I'm using to show the checkboxes. I tried changing :course to :course.number but it says "undefined method `number' for :course:Symbol". :

+
<div class="field">
+  <%= form.label :section_id %>
+  <%= form.collection_check_boxes(:section_ids, @sections, :id, :course) %>
+</div>
+
+

I'm confused because in students/show.html.erb I'm able to display the course number easily with section.course.number here:

+
<ol>
+ <% @student.sections.each do |section| %>
+  <li><%=section.course.number%> Credit Hours: <%=section.course.hours%> <%=section.professor.name %> 
+  </li>
+ <% end %>
+</ol>
+
+

Here is what it looks like Working course display

+

If you need any more information please let me know. Thank you!

","

Right now collection_check_boxes is calling .course on every section. You probably want to call course.number. One way to achieve this would be to add something like

+
def course_number
+  course.number
+end
+
+

to your Section-Model, and then use it:

+
<%= form.collection_check_boxes(:section_ids, @sections, :id, :course_number) %> 
+
",html +"Making multiple posts

am having problem with my above script

+

i need help, i want to make multiple ajax post. i have two url files and i want to send request on each of them

+

i want to send request and get response

+

and then send other post automatically after previous one on success call

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Hello World! Site Title</title>
+    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
+    <script>
+  $(document).ready(function () {
+    $("#Submit").click(function(event) {
+       Execute();
+       
+    });
+
+    function Execute(){
+      $.ajax({
+        type: 'POST',
+        url: 'file1.php',
+        data: { 'text': $("input[name='text']").val()
+        },
+         success: function(res) {
+    $('#result_1').text(res.msg);
+    
+    // after success of provious post now make this post
+    $.ajax({
+        type: 'POST',
+        url: 'file2.php',
+        data: { 'text': $("input[name='text']").val()
+        },
+         success: function(res) {
+    $('#result_2').text(res.msg);
+  }
+  
+  // after success now reload some part of my html div1
+  function update(){
+    $('#div1').load("index.html #div1");
+}
+setInterval( function(){
+   update();
+}, 1000 );
+  },
+  
+  // stop reload or div1 updating if url: 'file2.php', success msg eq to 'thanks'
+  
+        error: function() {
+          alert("something went bad");
+        }
+      });
+    };
+
+  });
+</script>
+
+  </head>
+  <body>
+  <div id="div1">
+    <h1 id="result_1"></h1>
+    <h1 id="result_2"></h1>
+    </div>
+    <input type="button" id="Submit" value="Submit"/>
+  </body>
+</html>
+
","

It looks like you forgot to mention the dataType: dataType: 'json' in the options object:

+
function Execute(){
+    let inp = $("input[name='text']").val();
+    $.ajax({
+        type: 'POST',
+        url: 'file1.php',
+        dataType: 'json',
+        data: { 'text': inp },
+         success: function(res) {
+    $('#result_1').text(res.msg);
+    
+    // after success of previous post now make this post:
+    $.ajax({
+        type: 'POST',
+        url: 'file2.php',
+        dataType: 'json',
+        data: { 'text': inp },
+         success: function(res) {
+    $('#result_2').text(res.msg);
+  }})}});
+}
+
+

The following snippet demonstrates the two step AJAX action. As POST cannot be performed using this test-environment based on window.URL.createObjectURL() the $.get() below uses GET instead. The principle should be the same though:

+

+
+
// for AJAX testing: mirror data back as a JSON string:
+function echoURL(data) {
+  return URL.createObjectURL(new Blob([JSON.stringify(data)],{type: ""text/json""}));
+}
+
+$(""#Submit"").click(function(ev){
+  $.ajax({type: 'GET', url: echoURL({msg:""first""}), dataType: 'json', 
+         // data: { 'text': inp },
+     success: function(res) { 
+       $('#result_1').text(res.msg); 
+       $.ajax({type: 'GET', url: echoURL({msg:""second""}), dataType: 'json', 
+               // data: { 'text': inp },
+         success: function(res) { 
+           $('#result_2').text(res.msg); 
+       }})
+  }})
+})
+$('button').click(function(ev){$('h1').text("""")})
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div id=""div1"">
+    <h1 id=""result_1""></h1>
+    <h1 id=""result_2""></h1>
+</div>
+<input type=""button"" id=""Submit"" value=""Submit""/>
+<button>clear</button>
+
+
+

",html +"Image modal not opening while clicking images. JavaScript not working

I made gallery modal images that I wanted to open on click, but it's not happening. Basically, I want to pass the image id of each image as they are clicked, to the JavaScript. And the Script must open the respective image as a popup or modal along with the close button.

+

Below is CSS

+
<style>
+/* The grid: Four equal columns that floats next to each other */
+.column {
+  float: left;
+  width: 25%;
+  padding: 10px;
+}
+
+/* Style the images inside the grid */
+.column img {
+  opacity: 0.8; 
+  cursor: pointer; 
+}
+
+.column img:hover {
+  opacity: 1;
+}
+
+/* Clear floats after the columns */
+.row:after {
+  content: "";
+  display: table;
+  clear: both;
+}
+
+/* The expanding image container */
+.imgcontainer {
+  position: relative;
+  display: none;
+}
+
+
+
+/* Closable button inside the expanded image */
+.closebtn {
+   position: absolute;
+  top: 15px;
+  right: 35px;
+  color: #f1f1f1;
+  font-size: 40px;
+  font-weight: bold;
+  transition: 0.3s;
+}
+
+.closebtn:hover,
+.closebtn:focus {
+  color: #bbb;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+
+.modal {
+  display: none; /* Hidden by default */
+  position: fixed; /* Stay in place */
+  z-index: 1; /* Sit on top */
+  padding-top: 100px; /* Location of the box */
+  left: 0;
+  top: 0;
+  width: 100%; /* Full width */
+  height: 100%; /* Full height */
+  overflow: auto; /* Enable scroll if needed */
+  background-color: rgb(0,0,0); /* Fallback color */
+  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
+}
+.modal-content {
+  margin: auto;
+  display: block;
+  width: 80%;
+  max-width: 700px;
+}
+
+
+/* Add Animation */
+.modal-content {  
+  -webkit-animation-name: zoom;
+  -webkit-animation-duration: 0.6s;
+  animation-name: zoom;
+  animation-duration: 0.6s;
+}
+
+@-webkit-keyframes zoom {
+  from {-webkit-transform:scale(0)} 
+  to {-webkit-transform:scale(1)}
+}
+
+@keyframes zoom {
+  from {transform:scale(0)} 
+  to {transform:scale(1)}
+}
+
+</style>
+
+

Below is HTML

+
<div id="myModal" class="modal">
+  <span class="closebtn">&times;</span>
+  <img class="modal-content" id="expandedImg">
+</div>
+
+<!-- The four columns -->
+<div class="row">
+  <div class="column">
+    <img src="img/content/services/serv-71.jpg" alt="Nature" style="width:100%" onclick="myFunction(this);">
+  </div>
+  <div class="column">
+    <img src="img/content/services/serv-72.jpg" alt="Snow" style="width:100%" onclick="myFunction(this);">
+  </div>
+  <div class="column">
+    <img src="img/content/services/serv-73.jpg" alt="Mountains" style="width:100%" onclick="myFunction(this);">
+  </div>
+  <div class="column">
+    <img src="img/content/services/serv-74.jpg" alt="Lights" style="width:100%" onclick="myFunction(this);">
+  </div>
+  
+</div>    
+
+</div>
+</div>
+
+

Here is the JavaScript

+
<script>
+function myFunction(imgs) {
+// Get the modal
+var modal = document.getElementById("myModal");
+
+// Get the image and insert it inside the modal - use its "alt" text as a caption
+var img = document.getElementById("imgs");
+var modalImg = document.getElementById("img");
+img.onclick = function(){
+  modal.style.display = "block";
+  modalImg.src = this.src;
+}
+
+// Get the <span> element that closes the modal
+var span = document.getElementsByClassName("closebtn")[0];
+
+// When the user clicks on <span> (x), close the modal
+span.onclick = function() { 
+  modal.style.display = "none";
+}}
+
+</script>
+
","

This fixes your code, I have added two separate functions one for opening and setting of src attribute of modal accordingly and the other for closing the modal.

+

+
+
function myFunction(event) {
+  var modal = document.getElementById(""myModal"");
+  modal.style.display = ""block"";
+  document.getElementById(""expandedImg"").setAttribute('src', event.target.getAttribute(""src""));
+
+}
+
+function closeModal(event) {
+  const modal = document.getElementById(""myModal"");
+  modal.style.display = ""none"";
+}
+
/* The grid: Four equal columns that floats next to each other */
+.column {
+  float: left;
+  width: 25%;
+  padding: 10px;
+}
+
+/* Style the images inside the grid */
+.column img {
+  opacity: 0.8;
+  cursor: pointer;
+}
+
+.column img:hover {
+  opacity: 1;
+}
+
+/* Clear floats after the columns */
+.row:after {
+  content: """";
+  display: table;
+  clear: both;
+}
+
+/* The expanding image container */
+.imgcontainer {
+  position: relative;
+  display: none;
+}
+
+
+
+/* Closable button inside the expanded image */
+.closebtn {
+  position: absolute;
+  top: 15px;
+  right: 35px;
+  color: #f1f1f1;
+  font-size: 40px;
+  font-weight: bold;
+  transition: 0.3s;
+}
+
+.closebtn:hover,
+.closebtn:focus {
+  color: #bbb;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+
+.modal {
+  display: none;
+  /* Hidden by default */
+  position: fixed;
+  /* Stay in place */
+  z-index: 1;
+  /* Sit on top */
+  padding-top: 100px;
+  /* Location of the box */
+  left: 0;
+  top: 0;
+  width: 100%;
+  /* Full width */
+  height: 100%;
+  /* Full height */
+  overflow: auto;
+  /* Enable scroll if needed */
+  background-color: rgb(0, 0, 0);
+  /* Fallback color */
+  background-color: rgba(0, 0, 0, 0.9);
+  /* Black w/ opacity */
+}
+
+.modal-content {
+  margin: auto;
+  display: block;
+  width: 80%;
+  max-width: 700px;
+}
+
+
+/* Add Animation */
+.modal-content {
+  -webkit-animation-name: zoom;
+  -webkit-animation-duration: 0.6s;
+  animation-name: zoom;
+  animation-duration: 0.6s;
+}
+
+@-webkit-keyframes zoom {
+  from {
+    -webkit-transform: scale(0)
+  }
+
+  to {
+    -webkit-transform: scale(1)
+  }
+}
+
+@keyframes zoom {
+  from {
+    transform: scale(0)
+  }
+
+  to {
+    transform: scale(1)
+  }
+}
+
<!-- Put your HTML here  -->
+<div id=""myModal"" class=""modal"">
+  <span class=""closebtn"" onclick=""closeModal(event)"">&times;</span>
+  <img class=""modal-content"" id=""expandedImg"">
+</div>
+
+<!-- The four columns -->
+<div class=""row"">
+  <div class=""column"">
+    <img src=""img/content/services/serv-71.jpg"" alt=""Nature"" style=""width:100%"" onclick=""myFunction(event);"">
+  </div>
+  <div class=""column"">
+    <img src=""img/content/services/serv-72.jpg"" alt=""Snow"" style=""width:100%"" onclick=""myFunction(event);"">
+  </div>
+  <div class=""column"">
+    <img src=""img/content/services/serv-73.jpg"" alt=""Mountains"" style=""width:100%"" onclick=""myFunction(event);"">
+  </div>
+  <div class=""column"">
+    <img src=""img/content/services/serv-74.jpg"" alt=""Lights"" style=""width:100%"" onclick=""myFunction(event);"">
+  </div>
+
+</div>
+
+
+

",html +"How to put the % symbol at the end of the text in a text-box permanently?

I have a textbox that displays the percentage.

+

I want the % symbol at the end of the text, the % symbol should not be editable but the text in the text box should be editable.

+

How can this be implemented?

","

You can do it in pure CSS using the :after pseudo-element.

+

+
+
.inputbox-container:after {
+    content: ""\0025"";
+    margin-left: -25px;
+    margin-right: 25px;
+    padding-left: 6px;
+}
+
+input {
+  padding-right: 20px;
+}
+
<div class=""inputbox-container""><input type=""text""></div>
+
+
+

",html +"How can I fix the stop-start process within this Javascript stopwatch-clock?

I have a JavaScript stopwatch here, I require the start-stop button to keep the same time when continuing. +Currently, if I stop and continue the clock diff is something ridiculous such as '-19330839:-3:-53'

+

Can anyone explain how this is fixed?

+

I have various method stopwatches made; however I would rather use real date time instead of a counter, this is because (I have tested after being made aware of this) that counters are very inaccurate over a period of time.

+

Any help is much appreciated.

+

html:

+

Please ignore the reset button for now. I will configure this later.

+
        <input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
+        <input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();"/>   
+        <div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
+
+

JS:

+
    const outputElement = document.getElementById("outputt");
+    var startTime = 0;
+    var running = false;
+    var splitcounter = 0;
+    
+    
+    function startstop() {
+      if (running == false) {
+        running = true;
+        startTime = new Date(sessionStorage.getItem("time"))
+        if (isNaN(startTime)) startTime = Date.now();
+        startstopbutton.value = 'Stop';
+        document.getElementById("outputt").style.backgroundColor = "#2DB37B";
+        updateTimer();
+      } else {
+        running = false;
+        logTime();
+        startstopbutton.value = 'Start';
+        document.getElementById("outputt").style.backgroundColor = "#B3321B";
+      }
+    }
+    
+    function updateTimer() {
+      if (running == true) {
+        let differenceInMillis = Date.now() - startTime;
+        sessionStorage.setItem("time", differenceInMillis)
+        let {
+          hours,
+          minutes,
+          seconds
+        } = calculateTime(differenceInMillis);
+        let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
+        
+        outputElement.innerText = timeStr;
+        requestAnimationFrame(updateTimer);
+      }
+    }
+    
+    function calculateTime(milliS) {
+      const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
+      const MINUTES = 60;
+      const HOURS = 60;
+      const RESET = 60;
+      
+      let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
+      let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
+      let seconds = Math.floor(milliS / SECONDS) % RESET;
+      
+      return {
+        hours,
+        minutes,
+        seconds
+      };
+    }
+    
+    function pad(time) {
+      return time.toString().padStart(2, '0');
+    }
+
+

I just need the timer to continue on from where it was stopped at.

","

Issue with your code:

+
    +
  • You start with initial value for sessionStorage as Date.now but then save difference on update.
  • +
  • You interact a lot with session storage. Any communication with external API is expensive. Instead use local variables and find an event to initialise values.
  • +
  • Time difference logic is a bit off. +
      +
    • Date.now - startTime does not considers the difference between stop action and start action.
    • +
    • You can use this logic: If startTime is defined, calculate difference and add it to start time. If not, initialise it to Date.now()
    • +
    +
  • +
+

Suggestions:

+
    +
  • Instead of adding styles, use classes. That will help you in reset functionality
  • +
  • Define small features and based on it, define small functions. That would make reusability easy
  • +
  • Try to make functions independent by passing arguments and only rely on them. That way you'll reduce side-effect
  • +
+

Note: as SO does not allow access to Session Storage, I have removed all the related code.

+

+
+
const outputElement = document.getElementById(""outputt"");
+var running = false;
+var splitcounter = 0;
+var lastTime = 0;
+var startTime = 0;
+
+function logTime() {
+  console.log('Time: ', lastTime)
+}
+
+function resetclock() {
+  running = false;
+  startTime = 0;
+  printTime(Date.now())
+  applyStyles(true)
+}
+
+function applyStyles(isReset) {
+  startstopbutton.value = running ? 'Stop' : 'Start';
+  document.getElementById(""outputt"").classList.remove('red', 'green')
+  if (!isReset) {
+    document.getElementById(""outputt"").classList.add(running ? 'red' : 'green')
+  }
+}
+function startstop() {
+  running = !running;
+  applyStyles();
+  if (running) {
+    if (startTime) {
+      const diff = Date.now() - lastTime;
+      startTime = startTime + diff;
+    } else {
+      startTime = Date.now()
+    }
+    
+    updateTimer(startTime);
+  } else {
+    lastTime = Date.now()
+    logTime();
+  }
+}
+
+function printTime(startTime) {
+  let differenceInMillis = Date.now() - startTime;
+  let {
+    hours,
+    minutes,
+    seconds
+  } = calculateTime(differenceInMillis);
+  let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
+  outputElement.innerText = timeStr;
+}
+
+function updateTimer(startTime) {
+  if (running == true) {
+    printTime(startTime)
+    requestAnimationFrame(() => updateTimer(startTime));
+  }
+}
+
+function calculateTime(milliS) {
+  const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
+  const MINUTES = 60;
+  const HOURS = 60;
+  const RESET = 60;
+
+  let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
+  let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
+  let seconds = Math.floor(milliS / SECONDS) % RESET;
+
+  return {
+    hours,
+    minutes,
+    seconds
+  };
+}
+
+function pad(time) {
+  return time.toString().padStart(2, '0');
+}
+
.red {
+  background-color: #2DB37B
+}
+
+.green {
+  background-color: #B3321B
+}
+
<input id=""startstopbutton"" class=""buttonZ"" style=""width: 120px;"" type=""button"" name=""btn"" value=""Start"" onclick=""startstop();"">
+<input id=""resetbutton"" class=""buttonZ"" style=""width: 120px;"" type=""button"" name=""btnRst1"" id='btnRst1' value=""Reset"" onclick=""resetclock();"" />
+<div id=""outputt"" class=""timerClock"" value=""00:00:00"">00:00:00</div>
+
+
+

",html +"Multiple circle lines with gradient color CSS

I want achieve design of banner with multiple circle lines with gradient background color. I've research more regarding this. I'm unable to find questions related my concern.

+

+

Bellow code is used to create solid color background banner.

+
.blue-cross-banner{
+    background: #0FA2EB;
+    border-radius: 30px;
+    padding: 4em;
+    margin: 1em;
+}
+
+

I cannot upload svg format of banner. It shows the gradient shade color of circle lines. +I found some what related to my question in here https://css-tricks.com/gradient-borders-in-css/. +But it doesn't help to my concern.

+
#grad2 {
+background: linear-gradient(90deg, rgba(15, 162, 235, 0) 33.16%, #0FA2EB 85.35%);
+border-radius: 30px;
+}
+
+

Above css is need to use background gradient color of circle lines.

","

You can do it like below:

+

+
+
.box {
+  height: 150px;
+  background: linear-gradient(90deg, red, yellow);
+  position: relative;
+  overflow: hidden;
+  border-radius:20px;
+}
+
+.box::before {
+  content: """";
+  position: absolute;
+  width: 100%;
+  height: 200%;
+  top: 0;
+  left: 50%;
+  background: repeating-radial-gradient(circle, transparent 0 20px, blue 21px 23px);
+  clip-path: circle(farthest-side); /* to cut extra circles*/
+}
+
<div class=""box"">
+
+</div>
+
+
+

",html +"Masonry images design issue with MaterializeCSS ""materialboxed"" class

I had created masonry images design with pure CSS. +
+Link here to codepen (only html and css) No materialize CSS and JS

+
+However, I want the effect of `materialboxed` class from materializeCSS +

Link to materialbox class from materializeCSS

+
+

The problem is that when I add materialboxed class to image, the masonry layout is changed

+

link to codepen with masonary design + materializeCSS

+

Expected Result

+

Actual Result

+

Expected Result

+

+
+
.gallery {
+  position: relative;
+  height: auto;
+  width: 100%;
+  margin: auto;
+  display: grid;
+  grid-template-columns: auto auto auto auto;
+  grid-gap: 2vh;
+  grid-auto-flow: dense;
+}
+.gallery .img {
+  position: relative;
+  height: 100%;
+  width: 100%;
+  overflow: hidden;
+}
+
+.gallery .img:first-child {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(2n + 3) {
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(4n + 5) {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(6n + 7) {
+  grid-row-start: span 1;
+}
+.gallery .img:nth-child(8n + 9) {
+  grid-column-start: span 1;
+  grid-row-start: span 1;
+}
+
+.gallery .img img {
+  height: 100%;
+  width: 100%;
+  object-fit: cover;
+  filter: brightness(0.5) grayscale(100);
+  transition: all 0.3s ease-in-out;
+}
+.gallery .img:hover img {
+  filter: brightness(1) grayscale(0);
+}
+
+@media only screen and (max-width: 768px) {
+  .gallery {
+    grid-template-columns: auto auto auto;
+  }
+  .gallery .img img {
+    filter: brightness(1) grayscale(0);
+  }
+}
+
+@media only screen and (max-width: 425px) {
+  .gallery {
+    display: block;
+  }
+  .gallery .img {
+    display: block;
+    width: 100%;
+    height: 100%;
+    margin: 10px 0;
+  }
+  .gallery .img img {
+    display: block;
+    filter: brightness(1) grayscale(0);
+  }
+}
+
<section class=""container"">
+  <div class=""gallery"">
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+    <div class=""img"">
+      <img  src=""https://placeimg.com/640/480/any"" alt=""image"">
+    </div>
+
+  </div>
+</section>
+
+
+

+

Example with design not working with class materializedbox

+

+
+
document.addEventListener(""DOMContentLoaded"", function () {
+  var elems = document.querySelectorAll("".materialboxed"");
+  M.Materialbox.init(elems);
+});
+
.gallery {
+  position: relative;
+  height: auto;
+  width: 100%;
+  margin: auto;
+  display: grid;
+  grid-template-columns: auto auto auto auto;
+  grid-gap: 2vh;
+  grid-auto-flow: dense;
+}
+.gallery .img {
+  position: relative;
+  height: 100%;
+  width: 100%;
+  overflow: hidden;
+}
+
+.gallery .img:first-child {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(2n + 3) {
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(4n + 5) {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(6n + 7) {
+  grid-row-start: span 1;
+}
+.gallery .img:nth-child(8n + 9) {
+  grid-column-start: span 1;
+  grid-row-start: span 1;
+}
+
+.gallery .img img {
+  height: 100%;
+  width: 100%;
+  object-fit: cover;
+  filter: brightness(0.5) grayscale(100);
+  transition: all 0.3s ease-in-out;
+}
+.gallery .img:hover img {
+  filter: brightness(1) grayscale(0);
+}
+
+@media only screen and (max-width: 768px) {
+  .gallery {
+    grid-template-columns: auto auto auto;
+  }
+  .gallery .img img {
+    filter: brightness(1) grayscale(0);
+  }
+}
+
+@media only screen and (max-width: 425px) {
+  .gallery {
+    display: block;
+  }
+  .gallery .img {
+    display: block;
+    width: 100%;
+    height: 100%;
+    margin: 10px 0;
+  }
+  .gallery .img img {
+    display: block;
+    filter: brightness(1) grayscale(0);
+  }
+}
+
    <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"" />
+
+    <section class=""container"">
+      <div class=""gallery"">
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+      </div>
+    </section>
+
+    <script defer src=""https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js""></script>
+
+
+

","

You can add full width and height to material-placeholder to get it working.

+

+
+
document.addEventListener(""DOMContentLoaded"", function () {
+  var elems = document.querySelectorAll("".materialboxed"");
+  M.Materialbox.init(elems);
+});
+
.gallery {
+  position: relative;
+  height: auto;
+  width: 100%;
+  margin: auto;
+  display: grid;
+  grid-template-columns: auto auto auto auto;
+  grid-gap: 2vh;
+  grid-auto-flow: dense;
+}
+.gallery .img {
+  position: relative;
+  height: 100%;
+  width: 100%;
+  overflow: hidden;
+}
+
+.gallery .img:first-child {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(2n + 3) {
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(4n + 5) {
+  grid-column-start: span 2;
+  grid-row-start: span 2;
+}
+
+.gallery .img:nth-child(6n + 7) {
+  grid-row-start: span 1;
+}
+.gallery .img:nth-child(8n + 9) {
+  grid-column-start: span 1;
+  grid-row-start: span 1;
+}
+
+.gallery .img img {
+  height: 100%;
+  width: 100%;
+  object-fit: cover;
+  filter: brightness(0.5) grayscale(100);
+  transition: all 0.3s ease-in-out;
+}
+.gallery .img:hover img {
+  filter: brightness(1) grayscale(0);
+}
+.material-placeholder {
+  position: relative;
+  width: 100%;
+  height: 100%;
+}
+
+@media only screen and (max-width: 768px) {
+  .gallery {
+    grid-template-columns: auto auto auto;
+  }
+  .gallery .img img {
+    filter: brightness(1) grayscale(0);
+  }
+}
+
+@media only screen and (max-width: 425px) {
+  .gallery {
+    display: block;
+  }
+  .gallery .img {
+    display: block;
+    width: 100%;
+    height: 100%;
+    margin: 10px 0;
+  }
+  .gallery .img img {
+    display: block;
+    filter: brightness(1) grayscale(0);
+  }
+}
+
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"" />
+
+    <section class=""container"">
+      <div class=""gallery"">
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+        <div class=""img"">
+          <img class=""materialboxed"" src=""https://placeimg.com/640/480/any"" alt=""image"">
+        </div>
+      </div>
+    </section>
+
+    <script defer src=""https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js""></script>
+
+
+

",html +"What is the problem with my Uncaught TypeError: Cannot set property 'src' of null

I have trying to change my code with .setAttribute too, the same thing appear..

+

In Javascript

+
document.getElementById("MyImg").src = "./sea.jpg";
+
+

In HTML :

+
<img src="./earth.jpg" id="MyImg">
+
+

Thank you for any futer answer !

","
+

Uncaught TypeError: Cannot set property 'src' of null

+
+

The null is the important part. Your DOM search (getElementById) failed.

+

Some ideas off the top of my head:

+
    +
  1. The script is running in a different page
  2. +
  3. The tag is not actually there
  4. +
  5. There is a misspelling in the id (looks good in your example though)
  6. +
+

If you need an example to work off of: https://www.w3schools.com/jsref/prop_img_src.asp

",html +"How to reset all buttons colour back to its original and add a new specific colour when a specific button is clicked?

I am trying to make my buttons change colour when clicked. The easy button turns green, medium turns yellow, hard turns red and insane turns black. When I click any button on the first try it works however when I click on another button it is supposed to reset all the buttons back to white and change the button I clicked to the specified colour. Right now my code is resetting it back to default and not showing the clicked button colour.

+

+
+
document.querySelectorAll("".difficulty-button"").forEach((gameMode) => {
+  gameMode.addEventListener(""click"", function() {
+    let linkColour = window.getComputedStyle(gameMode);
+    document.querySelectorAll("".difficulty-button"").forEach((item) => {
+      item.style.backgroundColor = ""green"";
+      item.style.color = ""black"";
+    });
+    gameMode.style.backgroundColor = linkColour.backgroundColor;
+  });
+});
+
ul {
+  display: flex;
+  justify-content: center;
+}
+
+ul li {
+  padding: 0;
+  list-style: none;
+}
+
+button {
+  box-shadow: none;
+  outline: none;
+  width: 10em;
+  height: 3.5em;
+  transition: 0.25s linear;
+  cursor: pointer;
+  background-color: white;
+}
+
+li:nth-child(1) button:hover {
+  background-color: rgb(51, 165, 50);
+  color: white;
+}
+
+li:nth-child(2) button:hover {
+  background-color: rgb(255, 255, 0);
+}
+
+li:nth-child(3) button:hover {
+  background-color: rgb(204, 50, 50);
+  color: white;
+}
+
+li:nth-child(4) button:hover {
+  background-color: black;
+  color: white;
+}
+
<ul>
+  <li><button class=""difficulty-button"">Easy</button></li>
+  <li><button class=""difficulty-button"">Medium</button></li>
+  <li><button class=""difficulty-button"">Hard</button></li>
+  <li><button class=""difficulty-button"">Insane</button></li>
+</ul>
+
+
+

","

The reason this only works the first time is to do with the way you get the colour to apply to the button, and how you apply the new colour.

+

Why it doesn't work:

+

You are using getComputedStyle to get the colour of the button when it is clicked. The first time it's clicked the hover class is applied, so to use is the one you clicked.

+

However then the javascript changes all the buttons to green directly using inline styles. These will override any other CSS being applied. Now every time you click, all the buttons are set to green so that colour is getting applied again.

+

Getting it to work: How to Swap CSS Classes on Click

+

You could hardcode the colours into the JS function and have an if to check which button it is. But a more flexible way to do this is to use your classes again.

+

1. Set up your CSS Classes. We already have rules set up for the colours you want, so if we give then a class name we can use them in the js, e.g.

+
.colorbutton-1,   /* give the existing 1st button CSS a class called "colorbutton-1" */
+li:nth-child(1) button:hover{
+    background-color: rgb(51, 165, 50);
+    color: white;
+}
+
+

Do this for each button, and also set one up for the default unselected state, e.g.

+
.colorbutton-0{
+    background-color:green;
+    color: black;
+}
+
+

Note the classes all start with the same name colorbutton - this is important! This is what we will use in the js later.

+

2. Write a function to swap the classes on the buttons depending on what was clicked. We'll pass in the button and which button number this is (i.e. 1,2,3,4).

+

In the function we remove all classes starting with colorbutton, and then add the new class - this is made up of the colorbutton- and the number of the button. If we want to apply the unselected style, we use 0.

+
function swapClass(btnElement, btnNum){
+    // remove all existing classes  starting with "colorbutton"
+    btnElement.classList.forEach(className => {
+        if (className.startsWith('colorbutton')) 
+            btnElement.classList.remove(className);
+    });
+     // now add the new class
+    btnElement.classList.add('colorbutton-'+ btnNum);
+}
+
+

3. Add your click listeners to listen for clicks and change the classes depending on which button was clicked.

+
// add a "counter" in forEach that passes the index of the element being processed, e.g. 0,1,2 etc
+document.querySelectorAll(".difficulty-button").forEach((gameMode, btnNum) => {
+    // add the click listener for the current button
+    gameMode.addEventListener("click", function () {
+        // on a click, remove all 'colorbutton' classes and set them to the default
+        document.querySelectorAll(".difficulty-button").forEach((item) => {
+            swapClass(item, 0);
+        });
+        // add the class for this button, passing in the class number to generate the classname
+        swapClass(this, (btnNum+1));
+    });
+});
+
+

Working Example Putting this all together:

+

+
+
document.querySelectorAll("".difficulty-button"").forEach((gameMode, btnNum) => {
+    gameMode.addEventListener(""click"", function () {
+        document.querySelectorAll("".difficulty-button"").forEach((item) => {
+            changeClass(item, 0);
+        });
+        changeClass(this, (btnNum+1));
+    });
+});
+
+function changeClass(btnElement, classRef){
+    // remove all existing classes  starting with ""colorbutton""
+    btnElement.classList.forEach(className => {
+        if (className.startsWith('colorbutton')) 
+            btnElement.classList.remove(className);
+    });
+     // now add the new class
+    btnElement.classList.add('colorbutton-'+classRef);
+}
+
ul {
+    display: flex;
+    justify-content: center;
+}
+ul li {
+    padding: 0;
+    list-style: none;
+}
+button {
+    box-shadow: none;
+    outline: none;
+    width: 10em;
+    height: 3.5em;
+    transition: 0.25s linear;
+    cursor: pointer;   
+    background-color: white;
+}
+
+.colorbutton-0{
+    background-color:green;
+    color: black;
+}
+.colorbutton-1,
+li:nth-child(1) button:hover{
+    background-color: rgb(51, 165, 50);
+    color: white;
+}
+.colorbutton-2,
+li:nth-child(2) button:hover{
+    background-color: rgb(255, 255, 0);
+}
+.colorbutton-3,
+li:nth-child(3) button:hover{
+    background-color: rgb(204,50,50);
+    color: white;
+}
+.colorbutton-4,
+li:nth-child(4) button:hover{
+    background-color: black;
+    color: white;
+}
+
<ul>
+  <li><button class=""difficulty-button"">Easy</button></li>
+  <li><button class=""difficulty-button"">Medium</button></li>
+  <li><button class=""difficulty-button"">Hard</button></li>
+  <li><button class=""difficulty-button"">Insane</button></li>
+</ul>
+
+
+

",html +"CSS content counter for nav bar

I'm trying to use a counter in my nav bar but only for selected items. I don't want the counter to display for sub-menu items, only for the main nav headings(Home, Commissions, Personal, Info, Contact). +Right now when the counter hovers over a sub-menu item, the counter is on top of my li headings.

+

I've placed numbers for where some headings will be as the client hasn't decided what to put there yet.

+

I'm fairly new to coding and still trying to grasp the concept of :before and :after.

+

+
+
body {
+  min-height: 100vh;
+  max-width: 100%;
+  position: relative;
+  background: #f4f3ee;
+  font-size: 12px;
+  line-height: 1.4em;
+  color: #010101;
+  counter-reset: counter;
+}
+
+.nav-bar {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  min-height: 15vh;
+  position: absolute;
+  left: 0;
+  padding: 2rem;
+}
+
+
+.nav-bar ul li:before {
+  position: absolute;
+  left: 13px;
+  counter-increment: counter;
+  content: ""0"" counter(counter);
+  transform: translateY(7px);
+  transition: opacity 0.2s ease-out, transform 0.1s ease-out;
+}
+
+.nav-bar ul li a:after {
+  content: """";
+  transition: opacity 0.1s ease-out;
+}
+
+.nav-bar ul li span:after {
+  content: """";
+  transition: opacity 0.1s ease-out;
+}
+
+.sub-menu {
+  position: absolute;
+  margin-left: 104px;
+  margin-top: -23px;
+}
+
+a,
+span.a {
+  text-decoration: none;
+  color: inherit;
+  cursor: pointer;
+  text-transform: uppercase;
+  line-height: 1.4rem;
+  font-size: 14px;
+}
+
+.nav-bar li:hover .nav-links {
+  display: block;
+}
+
<nav class=""nav-bar"">
+        <ul>
+          <li>
+            <a href="""">Home</a>
+          </li>
+          <li>
+            <span class=""a"">Commissions</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">1</a></li>
+                <li><a href="""">2</a></li>
+                <li><a href="""">3</a></li>
+                <li><a href="""">4</a></li>
+                <li><a href="""">5</a></li>
+                <li><a href="""">6</a></li>
+              </ul>
+            </div>
+          </li>
+          <li>
+            <span class=""a"">Personal</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">1</a></li>
+                <li><a href="""">2</a></li>
+                <li><a href="""">3</a></li>
+              </ul>
+            </div>
+          </li>
+          <li>
+            <span class=""a"">Info</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">Clients</a></li>
+                <li><a href="""">About</a></li>
+              </ul>
+            </div>
+          </li>
+          <li><a href="""">Contact</a></li>
+        </ul>
+      </nav>
+
+
+

","

I believe this is what you need. Somehow you need to select only the "top-level" elements but since your structure does not allow it, I added the a class on the top level elements to target them.

+

+
+
body {
+  min-height: 100vh;
+  max-width: 100%;
+  position: relative;
+  background: #f4f3ee;
+  font-size: 12px;
+  line-height: 1.4em;
+  color: #010101;
+  counter-reset: counter;
+}
+
+.nav-bar {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  min-height: 15vh;
+  position: absolute;
+  left: 0;
+  padding: 2rem;
+}
+
+.a:before {
+  position: absolute;
+  left: 13px;
+  counter-increment: counter;
+  content: ""0"" counter(counter);
+  transform: translateY(3px);
+  transition: opacity 0.2s ease-out, transform 0.1s ease-out;
+}
+
+.nav-bar ul li:before {
+  
+}
+
+.nav-bar ul li a:after {
+  content: """";
+  transition: opacity 0.1s ease-out;
+}
+
+.nav-bar ul li span:after {
+  content: """";
+  transition: opacity 0.1s ease-out;
+}
+
+.sub-menu {
+  position: absolute;
+  margin-left: 104px;
+  margin-top: -23px;
+}
+
+a,
+span.a {
+  text-decoration: none;
+  color: inherit;
+  cursor: pointer;
+  text-transform: uppercase;
+  line-height: 1.4rem;
+  font-size: 14px;
+}
+
+.nav-bar li:hover .nav-links {
+  display: block;
+}
+
<nav class=""nav-bar"">
+        <ul>
+          <li>
+            <a class=""a"" href="""">Home</a>
+          </li>
+          <li>
+            <span class=""a"">Commissions</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">1</a></li>
+                <li><a href="""">2</a></li>
+                <li><a href="""">3</a></li>
+                <li><a href="""">4</a></li>
+                <li><a href="""">5</a></li>
+                <li><a href="""">6</a></li>
+              </ul>
+            </div>
+          </li>
+          <li>
+            <span class=""a"">Personal</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">1</a></li>
+                <li><a href="""">2</a></li>
+                <li><a href="""">3</a></li>
+              </ul>
+            </div>
+          </li>
+          <li>
+            <span class=""a"">Info</span>
+            <div class=""sub-menu"">
+              <ul class=""nav-links"">
+                <li><a href="""">Clients</a></li>
+                <li><a href="""">About</a></li>
+              </ul>
+            </div>
+          </li>
+          <li><a class=""a"" href="""">Contact</a></li>
+        </ul>
+      </nav>
+
+
+

",html +"How do we change class name from script

Hello is there any way to edit html tag class name from script? +For example:

+

html:

+
<div id="ThisIsId" class= "ThisIsName"> ... </div>
+
+

Script:

+
<script>
+document.getElementById("ThisIsId").changeClassName("thisIsNewClassName") 
+</script>
+
","
<script>
+document.getElementById("ThisIsId").classList.remove("ThisIsName").add("thisIsNewClassName") 
+</script>
+
",html +"CSS: background-image: is not displaying my image (First time making a website and first time using stack overflow)

As the title says Im really new and I was watching a youtube tutorial but my background-image doesnt display anything. The code is really symple and the url path is correct. Im not sure whats going on. Any suggestions?

+
/* home-info
+========================== */
+
+.home-info {
+    background: url(C:\Users\XXXXX\Desktop\Programs\Websites\MyLife\images\aes.jpg);
+    /* background-color: rgb(118, 182, 141); */
+    padding: 10em 0;
+    background-size: cover; 
+}
+
+
+

this part of the code that is set to be a comment works fine.

+
/* background-color: rgb(118, 182, 141); */
+
+

I have tried putting ("..\aes.jpg"); and ('..\aes.jpg'); and it still doesnt work. +Could it be the image resolution it self (its 2048x1442)?

+

Also here is a part of my html code that has some meta inside

+
<meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1"> 
+    <title>My Life</title>
+    <link href="styles.css" rel="stylesheet" type="text/css">  
+
+

As far as I know that should allow the website to be resised without it looking weird and that also works.

+

Any suggestions are really appreciated. +Thank you!

","

You shouldn't use the absolute path that's related to your computer, because it wont work elsewhere!

+

I think the problem comes from the use of \ in your paths. Try replacing them by '/'. I don't know exactly about your folders architecture but try something like this : images/aes.jpg

",html +"Is there a way to submit a form that's loaded from a separate page via ajax within the same window?

I have this form:

+
<form method="post" action="/cart" id="ajax">
+  {...}
+  <div>
+  {{ product.option | hidden_option_input }}
+  </div>
+  <button name="submit" type="submit" title="add to cart">Add to Cart</button>
+</form>
+
+

The form is being loaded to the page via ajax, and its action page also preloaded via ajax in a different link in the navbar. I'd like to submit the form but prevent it from opening a new page when submitted. How can I go about this? I've tried:

+
<a href="/cart" class="new_popup mfp-ajax" onclick="this.parentNode.submit();return false;">Add to Cart</a>
+
+

to replace the button, but even though I've attempted to negate the default behavior with "return false;" it still reloads a new page on click. I can see the linked popup window just before the new page load, but it does not submit until the new page appears. I believe it's because the form is being loaded via ajax when a user clicks the link to it, therefore I cannot attach a script to it specifically because until it's on screen, it does not technically exist.

","

If I understand your question, you would like to just update a portion of the current page. If so, you will have to use AJAX for this:

+

Keep the "submit" button but make it a standard button and give it an id such as "submit":

+
<button id="submit" name="submit" title="add to cart">Add to Cart</button>
+
+

Then your JavaScript would handle the click event on the button as follows:

+
$(function() {
+    let submit = $('#submit');
+    submit.click( function() { //
+        submit.prop('disabled', true); // prevent a re-submission
+        var form = $('#ajax');
+        var request = $.ajax({
+            url: form.attr('action'), // get the action from the form
+            type: form.attr('method'), // get the method from the from
+            dataType: 'html', // the assumption is that we are dealing HTML here
+            data: form.serialize()
+        });
+
+        request.done(function(ajaxResult) {
+            // update the DOM with the results
+            $('#some_div').html(ajaxResult); // replace contents of <div id="some_div"></div> with new html
+            submit.prop('disabled', false); // re-enable the submit
+        });
+
+    });
+});
+
+

You have to arrange for the results sent back to be just the HTML that is required to be updated.

+

Update

+

Since responding, you have added a comment with a link that suggests I may have misunderstood your intent. The phrase you used, "submit the form but prevent it from opening a new page when submitted" definitely can lead one to my original interpretation.

",html +"Form Multiselect option is only returning 1 option in message

this is my first time making a form, and I have multi-select option but I think I'm missing out something because the form is working but when selecting multiple options the email I receive is only showing 1 option.

+
<form action="send.php" method="POST">
+<p>Name</p> <input type="text" name="name">
+<p>Email</p> <input type="text" name="email">
+<p>Services</p>
+<select data-placeholder="Responsible For...." multiple class="chosen-select full_width"  name="service" tabindex="-1">
+<option value="Medical">Medical</option>
+<option value="Finance">Finance</option>
+<option value="Construction">Construction</option>
+<option value="IT Services">IT Services</option>
+</select>
+
+<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
+<input type="submit" value="Send"><input type="reset" value="Clear">
+</form>
+
+

send.php

+
<?php
+$name = $_POST['name'];
+$email = $_POST['email'];
+$service = $_POST['service'];
+$message = $_POST['message'];
+$formcontent=" From: $name \n Type: $service \n Message: $message";
+$recipient = "itssonu4564@gmail.com";
+$subject = "Message";
+$mailheader = "From: $email \r\n";
+mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
+echo "Thank You!";
+?>
+
","

You need to do a small change in your HTML. Add a bracket pair to the name attribute, to make PHP it recognize it as an array.

+
<select multiple name="service[]">
+
+

Afterwards in PHP you can use

+
$service = implode(', ', $_POST['service']);
+
+

To get all services as a comma separated list.

",html +"Is it possible to smooth text change in JavaScript

I was working on a content changing click feature with JavaScript and jQuery and it works but is clunky. Is there anyway to make this transition smoother within JS or jQuery?

+

+
+
$(document).ready(function() {
+  $(""h1"").click(function() {
+    if (document.getElementById(""frst_hd"").innerHTML === ""World"") {
+      document.getElementById(""frst_hd"").innerHTML = ""Hello"";
+    } else {
+      document.getElementById(""frst_hd"").innerHTML = ""World"";
+    }
+  });
+});
+
<!DOCTYPE html>
+<html>
+
+<head>
+  <title>Example</title>
+  <script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+</head>
+
+<body>
+  <h1 id=""frst_hd"">Hello</h1>
+</body>
+
+</html>
+
+
+

+

I'm pretty new in this language so I'm sorry if this issue is easy to solve. Thanks for your help

","

+
+
$(document).ready(function() {
+  $(""h1"").click(function() {
+    if (document.getElementById(""frst_hd"").innerHTML === ""World"") {
+      $(""#frst_hd"").hide().text(""Hello"").fadeIn(1000);
+    } else {
+      $(""#frst_hd"").hide().text(""World"").fadeIn(1000);
+    }
+  });
+});
+
<!DOCTYPE html>
+<html>
+
+<head>
+  <title>Example</title>
+  <script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+</head>
+
+<body>
+  <h1 id=""frst_hd"">Hello</h1>
+</body>
+
+</html>
+
+
+

",html +"Cannot make PHP variable option in on change

Using PHP, I retrieve several data lines from a MySQL database into a HTML table. +At the end of each line, I added a "select" element that shows a property that a user can modify. +If someone selects another property (via one of the "select") than the one that is stored in the database, I want to update this line/field inside the database.

+

Below, one of the "select" element:

+
<select class="browser-default" id="FKPRIORITYUSER" name="FKPRIORITYUSER486">
+  <option value="99">TBD</option>
+  <option value="1">Critical</option>
+  <option value="2">High</option>
+  <option value="3" selected="selected">Low</option>
+</select>
+
+

All those "select" elements are the same, except that their "name" is different : FKPRIORITYUSER486, FKPRIORITYUSER487, etc.

+

To detect the change of value via the select, I'm using a simple jQuery function. For now, I'm just trying to "alert" the name of the "select" component which triggered this function:

+
var $select2 = $('select.browser-default');
+
+$select2.on('change', function (e) {
+  alert ( $('select').attr('name') );
+  alert( e.target.value );
+});
+
+

But, the problem is that this alert() function only returns the name "FKPRIORITYUSER486"... +It's ok if I click on the corresponding "select", but fails when I'm changing a value of the "select" named FKPRIORITYUSER487 :)

+

Any help would be much appreciated!

","

Firstly the ID of an element is supposed to be unique. You do not really need an ID here but incase you do, do the same as what you did with Name attribute (use the same value).

+ +

Now the code to get the name of the select that is changed. You are calling the function on change of any select but alerting the name of first select by hard coding $('select'). You need to use $(this) reference to refer to THE select that was changed, like this:

+ +
var $select2 = $('select.browser-default');
+
+$select2.on('change', function (e) {
+  alert ( $(this).attr('name') );  
+});
+
+ +

This is the fix to the issue at hand. The best way to do what you want to do is assign data-id to each select. like this:

+ +
<select class=""browser-default"" data-id=""486"" name=""FKPRIORITYUSER486"">
+
+ +

and then read the id like this

+ +
var changedId = $(this).data('id');
+
+ +

and get the selected/changed value like this

+ +
var changedValue = $(this).val();
+
+ +

and then pass the data to your server side script/code to update database by sending id and changed value.

",html +"Few field values are not showing up in the final output, i'm using nodejs

index.html

+ +
<form action=""http://127.0.0.1:5555/sign"" method=""POST"">
+      <div class=""main"">
+        <div class=""name-container"">
+          <input type=""text"" class=""input"" placeholder=""First Name"" id=""fname"" />
+          <input type=""text"" class=""input"" placeholder=""Last Name"" id=""lname"" />
+        </div>
+        <div class=""gender_date"">
+          <div class=""gen"">
+            <input type=""radio"" name=""gender"" value=""male"" id=""male"" />
+            <label for=""male"">Male</label>
+            <input type=""radio"" name=""gender"" value=""female"" id=""female"" />
+            <label for=""female"">Female</label>
+            <input type=""radio"" name=""gender"" value=""other"" id=""other"" />
+            <label for=""other"">Other</label>
+          </div>
+          <div class=""date-con"">
+            <input type=""date"" class=""input"" id='date' name=""bday"" />
+          </div>
+        </div>
+      </div>
+    </form>
+
+ +

the post request works properly but the names aren't showing up. +back-end nodejs file => serve.js

+ +
const express = require(""express"");
+const fs = require(""fs"");
+const bodyParser = require(""body-parser"");
+const app = express();
+var urlencodedParser = bodyParser.urlencoded({ extended: false });
+
+app.get(""/sign"", (req, res) => {
+  res.send(""Hello"");
+});
+app.post(""/sign"", urlencodedParser, (req, res) => {
+  res.send(req.body);
+  let student = req.body;
+  let students = [];
+  students.push(student);
+  let data = JSON.stringify(students, null, 2);
+
+  fs.writeFile(""./file.json"", data, err => console.log(""success""));
+  console.log(students);
+});
+
+const PORT = 5555;
+app.listen(PORT, err => {
+  console.log(`Server Running at port: ${PORT}`);
+});
+
+ +

file.json: Output

+ +
[
+  {
+    ""gender"": ""male"",
+    ""bday"": ""1999-07-05""
+  }
+]
+
+ +

The value from ""First Name"" and ""Last Name"" fields aren't showing up in the final output. +No matter what I change I couldn't get it to work properly. +Thank you in advance.

","

Try it

+ +
<form action=""http://127.0.0.1:5555/sign"" method=""POST"">
+  <div class=""main"">
+    <div class=""name-container"">
+      <input type=""text"" class=""input"" placeholder=""First Name"" name=""fname"" />
+      <input type=""text"" class=""input"" placeholder=""Last Name"" name=""lname"" />
+    </div>
+    <div class=""gender_date"">
+      <div class=""gen"">
+        <input type=""radio"" name=""gender"" value=""male"" id=""male"" />
+        <label for=""male"">Male</label>
+        <input type=""radio"" name=""gender"" value=""female"" id=""female"" />
+        <label for=""female"">Female</label>
+        <input type=""radio"" name=""gender"" value=""other"" id=""other"" />
+        <label for=""other"">Other</label>
+      </div>
+      <div class=""date-con"">
+        <input type=""date"" class=""input"" id='date' name=""bday"" />
+      </div>
+    </div>
+  </div>
+</form>
+
",html +"Supplied Data is not a valid base64-String jsPDF in ReactJS

Hi i am trying to capture screenshoot, put it into PDF and download with ReactJS Application. +I've created method that after click should generate PDF:

+ +
generatePDF = () => {
+    const printArea = document.getElementById(""field"")
+    html2canvas(printArea).then(canvas => {
+      const imgData = canvas.toDataURL('image/png');
+      const pdf = new jsPDF();
+      pdf.addImage(imgData, 'PNG', 0, 0, 200, 200);
+      pdf.save(""download.pdf"");
+
+    })
+  }
+
+ +

It returns me an error: ""Supplied Data is not a valid base64-String jsPDF.convertStringToImageData ""

+ +

This is my render method:

+ +
render() {
+    return (
+      <div>
+        <div className=""nav""></div>
+        <div className=""field"" id=""field"">
+          {
+            this.createTables()
+          }
+        </div>
+        <button onClick={this.generatePDF} style={{ marginTop: 500 }}>Generate PDF</button>
+      </div>
+
+    )
+  }
+
+ +

I was checking, generatePDF properly gives me div, problem appears on screen when addImage is executing.

","

I would encourage you to use refs instead of document.getElementById(""field"")

",html +"How do i get the date that is 15 days more from the date selected in datepicker?

I picked this code from jQuery forum.

+ +

+
+
$(function () {
+    $(""#selectedDate"").datepicker({
+        dateFormat: 'yy-mm-dd',
+        onSelect: function(_date) {
+            var myDate = $(this).datepicker('getDate');
+            console.log(myDate);
+            myDate.setDate(myDate.getDate() + 15);
+            $('#retrieveDate').text($.datepicker.formatDate('yy-dd-mm', myDate));
+        }
+    });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<script src=""https://code.jquery.com/ui/1.12.1/jquery-ui.min.js""></script>
+<div class=""form-group"">
+    <label>Selected Date in Datepicker</label>
+    <input type=""text"" name=""selected_date"" class=""form-control datepicker""
+           id=""selectedDate"">
+</div>
+<div class=""form-group"">
+    <label>Retrieve Date</label>
+    <input type=""text"" id=""retrieveDate"" name=""retrieve_date""
+           class=""form-control"">
+</div>
+
+
+

+ +

When I select the date in first input, the second input must be automatically filled with the date that is 15 days more from the selected date in the datepicker.

","

change this line:

+ +
$('#retrieveDate').text($.datepicker.formatDate('yy-dd-mm', myDate));
+
+ +

by this: to add text by jQuery you should use val()

+ +
$('#retrieveDate').val($.datepicker.formatDate('yy-dd-mm', myDate));
+
",html +"How the select function automatically turn into ""Please Select"" word?

I have a question about the ""select"" function. I have two input ""select"" functions. When I select the first input option, then I select the second input option. If I go back to the first input option to change other options, how can the second one automatically turn into ""Please Select""word?

+ +

Below is my coding:

+ +
     <label for=""cp8"" class=""control-label col-lg-4"">Merchant</label>
+    <div class=""col-lg-5"">
+
+                            <select class=""form-control required"" id=""branch_id3"" name=""branch_id3"">
+                                <option value="""" selected>Please Select</option>
+                                <!--<option value=""0"" selected>All</option>-->
+                            <?php
+                            $sql_branch = 'SELECT * FROM merchant_list;';
+                            $arr_branch = db_conn_select($sql_branch);
+                            foreach ($arr_branch as $rs_branch) {
+                                echo '<option value=""' . $rs_branch['id'] . '"">' . $rs_branch['shop_name'] . '</option>';
+                            }
+                            ?>
+                            </select>
+                                </div><br><br><br>
+                                 <label for=""cp8"" class=""control-label col-lg-4"">Merchant Types</label>
+<div class=""col-lg-5"">
+
+                            <select class=""form-control required"" id=""merchant_type"" name=""merchant_type"">
+                                <option value="""" selected>Please Select</option>
+                           <option value=""1"">Event Sponsored</option>
+                                <option value=""2"">Normal Merchant</option>
+                            </select>
+                                </div><br><br><br>
+
+ +

Below is my output picture:

+ +

Output

+ +

For example:

+ +

First I choose the Merchant option is ""PALVO"", then I choose the Merchant Types is ""Event Sponsored"". After that, if I want go back the Merchant to change other option, the Merchant Types will automatically turn to ""Please Select"" option. So that, my question is how to automatically make Merchant Types turn to ""Please Select"" option? Thanks for helping.

","

i hope this is what you looking for

+ +

+
+
$('#option').change(function(){
+$('#type').val(0);
+})
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<select id=""option"">
+  <option>Please Select</option>
+  <option>Option</option>
+  <option>Option1</option>
+  <option>Option2</option>
+</select>
+
+<select id=""type"">
+  <option value=""0"">Please Select</option>
+  <option>Type</option>
+  <option>Type1</option>
+  <option>Type2</option>
+</select>
+
+
+

",html +"changing text inside a div to negative html code using javascript

I have this div:

+
<div class="signs" id="signs" onclick="toggle()">&#43;</div>
+
+

which displays the positive sign. when clicking on it, I want to change it to the negative sign with html code &#8722;:

+
function toggle() {
+  var x = document.getElementById("signs");
+  if (x.textContent === `&#43`) {
+    x.textContent = `&#8722;`;
+  } else {
+    x.textContent = `&#43;`;
+  }
+}
+
+

But toggle function changes the positive sign to plain text &#8722; and not the negative sign! How can I achieve changing the positive to negative sign using javascript with my structure above?

","

can you try

+
        function toggle() {
+            var x = document.getElementById("signs");
+            if (x.textContent == `+`) {
+                x.textContent = `-`;
+            } else {
+                x.textContent = `+`;
+            }
+        }
+
+

this?

",html +"Javascript Click on Svg/object element dosen't trigger with mobile

Hi I have a problem getting click/touch to work show it will toggle a div in the DOM outside the Svg to show, on a element inside a svg, when using object to embed the SVG. I've tried many different ways but nothing do it. Are there a friendly person here, that can give me the correct way to do this

+

I have tried to use touchstart I've also tried another code I have, that is not used with svg that works on both desktop and mobile. But when I use that script for this, it can't read inside the svg. It dose feel like the problem is that the mobile doesn't read in svg the same way, and therefore the code doesn't work.

+

I did look though a lot of the post in here, but most of them have nothing to do with click events, and I really don't have the skill to rewrite them.

+

so here is the structure: +First I have my.

+

Under that I load the script ( I did try using it over the object, and in html head still nothing)

+
<object class="nSvg" type="image/svg+xml" data="img/emne.svg"></object>
+
+
+
+
+<div id="boxOpen" class="boxOpenHidden">
+    <div id="naturSkiferBruges">
+        <h2>test</h2>
+        <p>test</p>
+    </div>
+</div>
+<script type="text/javascript">
+   var nSvg = document.getElementsByClassName("nSvg")[0];
+   nSvg.addEventListener("load",function(){
+               var sSvg = nSvg.contentDocument;
+               var subEle = sSvg.getElementsByClassName("myclass")[0];
+               subEle.addEventListener("click",function(){
+                       $('#boxOpen').toggleClass('boxOpenVis');
+                }, false);
+             }, false);
+</script>
+
+

Here is the svg element I'm trying to make a click on:

+
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="2000" viewBox="0 0 1920 2000">
+<text class="myclass" data-name="myclass" x="158.25" y="1298.112">Hvor kan Kobbertag et bruges?</text>
+</svg>
+
","

Here you go buddy:

+

HTML:

+
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="2000" viewBox="0 0 1920 2000" class="nSvg">
+  <text class="myclass" data-name="myclass" x="158.25" y="1298.112">Hvor kan Kobbertag et bruges?</text>
+</svg>
+
+

JS:

+
   var Svg = document.getElementsByClassName("nSvg")[0];
+   let texts = Svg.getElementsByClassName("myclass");
+
+   for (text of texts) {
+     text.addEventListener("click", function() {
+       alert("OK");
+     }, false);
+   }
+
+

LIVE DEMO: https://jsfiddle.net/mr39e54h/

+
+

PS: Trying clicking on the text

+
+

Update: +You can bind an event on the loaded svg by traversing through the children of the contentDocument.

+
var nSvg = document.getElementsByClassName("nSvg")[0];
+nSvg.addEventListener("load", function() {
+  var text = nSvg.contentDocument.getElementsByClassName('myclass')[0];
+  text.addEventListener("click", function() {
+     $('#boxOpen').toggleClass('boxOpenVis');
+  }, false);
+}, false);
+
",html +"Python/Flask - Trying to take user input from one page, and display on another

So, I've seen a few posts on this, but can't seem to get this to work.

+

Basically, I have a two page site (home.html and result.html). The home.html has a user input for a name and submit button, and the result.html should display that name once submitted.

+

The goal is for a name to be input into the name field on the home.html page, and once submitted, the result page would load with the name being displayed. Currently, when submitted, only None shows.

+

Here are the files below:

+

home.html

+
{% extends 'base.html' %}
+{% block head %}
+<title>Home Page</title>
+{% endblock %}
+{% block body %}
+
+  <div class="content-container">
+    <form action="{{ url_for('result') }}" method="post">
+      <h2>Input your name:</h2>
+      <input type="text" class="name-input name mb-3" id="name">
+      <input class="btn btn-outline-primary" type="submit" value="Submit">
+    </form>
+  </div>
+
+{% endblock %}
+
+

result.html

+
{% extends 'base.html' %}
+{% block head %}
+<title>Result Page</title>
+{% endblock %}
+{% block body %}
+
+  <div class="content-container">
+    <h2>{{ name }}</h2>
+  </div>
+
+{% endblock %}
+
+

main.py

+
from flask import Flask, render_template, request, url_for, redirect
+
+app = Flask(__name__)
+
+
+@app.route('/', methods=['GET', 'POST'])
+def home():
+    if request.method == 'POST':
+        name = request.form["name"]
+        return redirect(url_for('result', name=name))
+    return render_template('home.html')
+
+
+@app.route("/result", methods=['GET', 'POST'])
+def result():
+    name = request.form.get('name')
+    return render_template("result.html", name=name)
+
+
+if __name__ == "__main__":
+    app.run()
+
+

I'm 99.9% sure that what I'm missing is small, and once pointed out, I'll feel bad for missing it. Regardless, I'm seeking help from the high counsel, PLEASE HELP!!! TIA!!!

","

input field should have an attribute called name which you refer as request.form[name]. So it should be

+
<input type="text" class="name-input name mb-3" id="name" name="name">
+
",html +"Thymeleaf: Iterate over enum values and use them in a list filter

I am struggling using enum values in list filters in Thymeleaf.

+

I know how to iterate over enum values and how to compare them against constant values. However, I want to compare it against a 'variable' value. How can I achieve it?

+

In my example below, I want to iterate trough all colors (enum) and then filter a list of cars by the current color enum and display their names.

+

How do I specify the list filter in the second <div> correctly?

+
<div th:each="currentColorEnum : ${T(de.my.enum.color).values()}">
+    <div th:each="currentCar, carStatus : ${model.carList.?[#this.colorEnum eq __${currentColorEnum}__]}">                  
+        <textarea th:field="*{carList[__${carStatus.index}__].carName}"></textarea>
+    </div>
+</div>
+
+

Current error message:

+
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'red' cannot be found on object of type 'de.my.class.car' - maybe not public or not valid?
+
","

No need for preprocessing in this case. It's failing because ${model.carList.?[#this.colorEnum eq __${currentColorEnum}__]} resolves to ${model.carList.?[#this.colorEnum eq red]}. Which means it looking for cars where car.colorEnum == car.red -- hence the error field 'red' cannot be found on object of type 'de.my.class.car'.

+

Your Thymeleaf should look something like:

+
<div th:each="currentColorEnum : ${T(de.my.enum.color).values()}">
+    <div th:each="currentCar, carStatus : ${model.carList.?[colorEnum eq #root.currentColorEnum]}">                  
+        <textarea th:field="*{carList[__${carStatus.index}__].carName}"></textarea>
+    </div>
+</div>
+
",html +"Why is CSS transition not working upon clicking menu button?

Whenever I click upon the menu, a class 'active' gets added to the 'div' and the 'section' as shown.

+

+

The javascript code used to do the above mentioned is

+
<script>
+    const menuToggle = document.querySelector('.toggle')
+    const frontpage = document.querySelector('.front-page')
+
+    menuToggle.addEventListener('click', () =>{
+      menuToggle.classList.toggle('active')
+      frontpage.classList.toggle('active')
+    }) 
+</script>
+
+

The CSS for the class front-page and toggle are as shown

+

+

So the page moves to the right but no transition takes place as shown

+

+

I am a noob , so please kindly tell me why is this transition not working

+

Index File: https://github.com/rajas2716/rajas2716.github.io/blob/master/index.html

+

CSS File: https://github.com/rajas2716/rajas2716.github.io/blob/master/css/styles.css

+

Github link to project: https://github.com/rajas2716/rajas2716.github.io

","

You need to add a right value of 0 to the default state in the .front-page rule (i.e. a value from which the transition starts), and you need to write "all" or "right" into the transition setting, like transition: all 0.5s.

",html +"D3 scatter plot points not displaying correctly

I'm new to d3, and I'm attempting a basic scatter plot using an example I found. Instead of using the read csv function in the example, I'm trying to add my own data.

+

Using the following code, it displays the axes, but only shows a single point at [0,10]. See picture below. What might I be missing?

+

+
+
// set the dimensions and margins of the graph
+    var margin = {top: 10, right: 30, bottom: 30, left: 60},
+        width = 460 - margin.left - margin.right,
+        height = 400 - margin.top - margin.bottom;
+
+    // append the svg object to the body of the page
+    var svg2 = d3.select(""#my_dataviz2"")
+        .append(""svg"")
+        .attr(""width"", width + margin.left + margin.right)
+        .attr(""height"", height + margin.top + margin.bottom)
+        .append(""g"")
+        .attr(""transform"", ""translate("" + margin.left + "","" + margin.top + "")"");
+
+    //Read the data
+    
+    var data = [
+        {""name"": ""point1"", ""x"":1, ""y"":2},
+        {""name"": ""point2"", ""x"":3, ""y"":4},
+        {""name"": ""point3"", ""x"":5, ""y"":6},
+        {""name"": ""point4"", ""x"":7, ""y"":8}
+    ];
+
+    // Add X axis
+    var x = d3.scaleLinear()
+        .domain([0, 10])
+        .range([ 0, width ]);
+    svg2.append(""g"")
+        .attr(""transform"", ""translate(0,"" + height + "")"")
+        .call(d3.axisBottom(x));
+
+    // Add Y axis
+    var y = d3.scaleLinear()
+        .domain([0, 10])
+        .range([ height, 0]);
+    
+    svg2.append(""g"")
+        .call(d3.axisLeft(y));
+
+    // Add dots
+    svg2.append(""g"")
+        .selectAll(""dot"")
+        .data(data)
+        .enter()
+        .append(""circle"")
+        .attr(""r"", 3.5)
+        .style(""fill"", ""#000"");
+
<script src=""https://cdn.jsdelivr.net/npm/d3@7""></script>
+
+<div id=""my_dataviz2""></div>
+
+
+

+

","

It always helps to inspect your page when debugging D3 visualizations. When you do so here, you'll notice that all the points are added, they are just on top of each other at [0, 0] (in pixels).

+

This means we have have a positioning problem. Looking at your code you don't set where the circles should be on the page. Let's set cx and cy attributes by scaling the data as follows:

+
    .attr("cx",d=>x(d.x))
+    .attr("cy",d=>y(d.y))
+
+

+
+
// set the dimensions and margins of the graph
+    var margin = {top: 10, right: 30, bottom: 30, left: 60},
+        width = 460 - margin.left - margin.right,
+        height = 400 - margin.top - margin.bottom;
+
+    // append the svg object to the body of the page
+    var svg2 = d3.select(""#my_dataviz2"")
+        .append(""svg"")
+        .attr(""width"", width + margin.left + margin.right)
+        .attr(""height"", height + margin.top + margin.bottom)
+        .append(""g"")
+        .attr(""transform"", ""translate("" + margin.left + "","" + margin.top + "")"");
+
+    //Read the data
+    
+    var data = [
+        {""name"": ""point1"", ""x"":1, ""y"":2},
+        {""name"": ""point2"", ""x"":3, ""y"":4},
+        {""name"": ""point3"", ""x"":5, ""y"":6},
+        {""name"": ""point4"", ""x"":7, ""y"":8}
+    ];
+
+    // Add X axis
+    var x = d3.scaleLinear()
+        .domain([0, 10])
+        .range([ 0, width ]);
+    svg2.append(""g"")
+        .attr(""transform"", ""translate(0,"" + height + "")"")
+        .call(d3.axisBottom(x));
+
+    // Add Y axis
+    var y = d3.scaleLinear()
+        .domain([0, 10])
+        .range([ height, 0]);
+    
+    svg2.append(""g"")
+        .call(d3.axisLeft(y));
+
+    // Add dots
+    svg2.append(""g"")
+        .selectAll(""dot"")
+        .data(data)
+        .enter()
+        .append(""circle"")
+        .attr(""r"", 3.5)
+        .style(""fill"", ""#000"")
+        .attr(""cx"",d=>x(d.x))
+        .attr(""cy"",d=>y(d.y))
+
<script src=""https://cdn.jsdelivr.net/npm/d3@7""></script>
+
+<div id=""my_dataviz2""></div>
+
+
+

",html +"BEM: how to make sure rules of the right class (parent block) take precedence?

In BEM all selectors (classes) are supposed to have the same specificity. Meanwhile blocks are independent entities and you are supposed to be able to nest blocks in any combination and mix the class definitions of their elements. +How do I make parent block rules to have higher priority than the child block rules while following BEM methodology?

+

Suppose we have two blocks: menu and social. Since blocks are independent sometimes first block will be a part of the second, sometimes the second block will be a part of the first one.

+
<div class="menu">
+  <div class="menu__social social">
+      <h1>social content in a menu</h1>
+  </div>
+</div>
+
+<div class="social">
+  <div class="social__menu menu">
+      <h1>a menu in social content</h1>
+  </div>
+</div>
+
+

naturally, in such a situation, I need rules of the class menu__social be able to overwrite rules of the class social, so when I have social inside a menu I can style it according to the needs of the parent element.
+And wise versa: rules of the class social__menu need to be able to overwrite rules of the class menu, so when menu is a child I can restyle it according to the needs of the parent. +How do I do it?

+

If I simply define rules for each block in a separate file and then merge them together - then rules of the one block come first and are always overwritten by the rules of another block, the order of classes in html is ignored.

+
/* menu block definition */
+.menu {
+  background: red;
+}
+
+.menu__social {
+  background: pink;
+}
+
+/* social block definition */
+.social {
+  background: blue;
+}
+.social__menu {
+  background: green;
+}
+
+

in this example background will always be blue or green, i.e. every-time I mix menu* with social* the rules of the menu-block are ignored.

+

http://jsfiddle.net/oq2arsv3/

","

Let me structure everything I've found out. +There are several approaches:

+

--------- 1

+

First of all, you can reorganize rules between blocks so they don't need to be overwritten in the first place. +The main use of mixes is an ability to divide css styles between blocks: external stuff is defined in the parent block and internal in the child block you mix the definitions and you get all element styles needed. BEM just like OOP is based on Single responsibility principle. So if you have one style (color) defined both in parent and child block may be this is the problem on its own and should be changed.

+

------------------ 1.1

+

One way to do it is modifiers. Define two different styles of the child block in the child block itself and use them depending on the context (and this is exactly what modifiers are needed for):

+
<div class="menu">
+  <div class="social social_color_pink">
+      <h1>social content in a menu</h1>
+  </div>
+</div>
+
+<div class="social">
+  <div class="menu menu_color_green">
+      <h1>a menu in social content</h1>
+  </div>
+</div>
+
+/* menu block definition */
+.menu {
+  background: red;
+}
+
+.menu_color_green {
+  background: green;
+}
+
+
+/* social block definition */
+.social {
+  background: blue;
+}
+
+.social_color_pink {
+  background: pink;
+}
+
+

------------------ 1.2

+

Another way to do it is what Stefan Bajić suggested - avoid nesting and make a child block a part of the parent block (an element). This will lead to the code duplication, but will allow you to avoid a lot of dependency issues in the future, and, since you can't separate responsibilities of the parent and child block (who defines the color), it is probably the most natural way.

+
<div class="menu">
+  <div class="menu__social">
+      <h1>social content in a menu</h1>
+  </div>
+</div>
+
+<div class="social">
+  <div class="social__menu">
+      <h1>a menu in social content</h1>
+  </div>
+</div>
+
+/* menu block definition */
+.menu {
+  background: red;
+}
+
+.menu__social {
+  background: pink;
+}
+
+
+/* social block definition */
+.social {
+  background: blue;
+}
+
+.social__menu {
+  background: green;
+}
+
+

--------- 2

+

You can use context. This is not the best way, since it increases rules specificity and makes HTML less readable, but it is allowed by BEM if nothing else fits.

+
<div class="menu">
+  <div class="social">
+      <h1>social content in a menu</h1>
+  </div>
+</div>
+
+<div class="social">
+  <div class="menu">
+      <h1>a menu in social content</h1>
+  </div>
+</div>
+
+/* menu block definition */
+.menu {
+  background: red;
+}
+
+.menu .social {
+  background: pink;
+}
+
+
+/* social block definition */
+.social {
+  background: blue;
+}
+
+.social .menu {
+  background: green;
+}
+
+

--------- 3

+

You can combine all the ways above, so it fits your specific task the most. For example, if social block is huge and menu is small, you can duplicate some code of menu and make menu an element of the social block, and add modifier to the social block and use it in the menu block definition so you don't need to duplicate social code.

+
<div class="menu">
+  <div class="social_color_pink">
+      <h1>social content in a menu</h1>
+  </div>
+</div>
+
+<div class="social">
+  <div class="social__menu">
+      <h1>a menu in social content</h1>
+  </div>
+</div>
+
+/* menu block definition */
+.menu {
+  background: red;
+}
+
+/* social block definition */
+.social {
+  background: blue;
+}
+
+.social__menu {
+  background: green;
+}
+
+.social_color_pink {
+  background: pink;
+}
+
+

Note, that all solutions result in absence of the mixes. This happens just because there is only one css-rule in the example. And thereby, this doesn't mean that you need to get rid of the mixes, you still can and most probably will need to use mixes, but you must avoid overwriting css styles in them, since then the result will depend on the order in which blocks are defined.

",html +"How to display string HTML containing inline style tag from angular component

I want to show a saved HTML containing inline style tag, from an angular component, +I have tried encapsulation: ViewEncapsulation.None, but it's not working.

+

Component:

+
@Component({
+  selector: 'app-page-content',
+  templateUrl: './page-content.component.html',
+  styleUrls: ['./page-content.component.css'],
+  encapsulation: ViewEncapsulation.None,
+})
+
+

Get data from HTTP get in the ts component:

+
description=<p class="ql-direction-rtl ql-align-right" style="text-align: center;"><strong><span style="color: #236fa1;">test</span></strong></p>
+
+

Showing the data: +<div [innerHtml]=description></div>

","

Angular doesn't allow you to directly pass styles into a variable because of security issues. So you have to explicitly tell it that your string is safe.

+

You do it as follows:

+
import {DomSanitizer} from '@angular/platform-browser'
+
+
+

....

+
export class AppComponent {
+  description;
+  constructor(private sanitizer: DomSanitizer) {
+    this.description = sanitizer.bypassSecurityTrustHtml(`<p class="ql-direction-rtl ql-align-right" style="text-align: center;"><strong><span style="color: #236fa1;">test</span></strong></p>`)
+  }
+}
+
",html +"How can I add a active class to a svg path?

I want to add a active class so that whenever I click on a path it will be active until I click the other one. The minimal way of doing this would be appreciable. I already made this svg clickable using jquery. . Here is my jquery code-

+
$(document).ready(function () {
+$('#mySVG').load("bd-map.html", function () {
+
+    $("#bd-map").click(function (evt) {
+        switch (evt.target.id) {
+            case "panchagarh":
+                $('#info').load('info.html #panchagarh')     //loading data from info.html
+                break;
+            case "bandarban":
+                $('#info').load('info.html #bandarban')     //loading data from info.html
+                break;
+            case "comilla":
+                $('#info').load('info.html #comilla')
+                break;
+            case "sylhet":
+                $('#info').load('info.html #sylhet')
+                break;
+        }
+    });
+});
+
+

})

","

This should do it, assuming the element you want the class added to is an SVG that lives inside the #bd-map container. The trick is that you're either clicking on the path or text element, so you have to sniff for tagName and then react accordingly. The path to the path from the text element is $(evt.target).parent().prev('path') (keeping things in jQuery)

+
$("#bd-map").click(function(evt) {
+  $("#bd-map").find('path').removeClass('active');
+  let targ = evt.target.tagName === 'path' ? $(evt.target) : $(evt.target).parent().prev('path');
+  console.log(targ.attr('id'))
+  targ.addClass('active')
+  switch (targ.attr('id')) {
+    case "panchagarh":
+      $('#info').load('info.html #panchagarh') //loading data from info.html
+      break;
+    case "bandarban":
+      $('#info').load('info.html #bandarban') //loading data from info.html
+      break;
+    case "comilla":
+      $('#info').load('info.html #comilla')
+      break;
+    case "sylhet":
+      $('#info').load('info.html #sylhet')
+      break;
+  }
+});
+
",html +"How to append a div inside another div?

I'm pretty new to JS, and still learning. I'm trying to practice making some fun projects, but I simply just can't figure this one out.

+

I want to append a with the class message-wrapper, inside another , with the username, date and message inside.

+
// Output message to DOM
+function outputMessage(message) {
+    const div = document.createElement('div');
+    div.classList.add('message-wrapper');
+    const div2 = document.createElement('div');
+    div.classList.add('message');
+
+    if(message.username === username) {
+        div.classList.add('me');
+    }
+
+    div.innerHTML = `<p class="meta">${message.username} <span>${message.time}</span></p>
+    <p class="text">
+        ${message.text}
+    </p>`;
+    document.querySelector('.chat-messages').appendChild(div);
+};
+
+

Just to clarify I want this end result as HTML

+
<div class="message-wrapper">
+   <div class="message me">
+      <p class="meta">username <span>time</span></p>
+      <p class="text">Lorem ipsum dolar sit amet</p>
+   </div>
+</div>
+
","

Corrected code below, see embedded comments.

+
function outputMessage(message) {
+    const div = document.createElement('div');
+    div.classList.add('message-wrapper');
+    const div2 = document.createElement('div');
+    div2.classList.add('message'); // make sure you add the class to the second div
+
+    if(message.username === username) {
+        div2.classList.add('me'); // same, add class to div2, not div
+    }
+
+    div2.innerHTML = `<p class="meta">${message.username} <span>${message.time}</span></p>
+    <p class="text">
+        ${message.text}
+    </p>`; // make sure you are setting the inner HTML of the second div (div2), the one with classes "message", "me", not the outer div
+
+    document.querySelector('.chat-messages').appendChild(div);
+    // after appending the outer div to a node in the DOM, append the second div as a child of the "message-wrapper" div
+    document.querySelector('.message-wrapper').appendChild(div2);
+};
+
",html +"Get iteration variable from js file

I have to loop over Array of objects consist of [{ title: '', desc: '', svg: '' }, ...]. As SVG code is too large and I don't want to clutter my .pug file with lots of SVG codes.

+

Is there anything by which I can import this Array from another JS file and just use it without outputting/generating array in it to compiled html just like a normal inlie JS in PUG:

+
someMagicImport data.js
+
+each feature in data.features
+  li= feature.title
+
+

data file: data.js

+
const features = [
+ { title: '...', desc: '...', svg: '...' },
+ // .... other objects
+]
+
+

So, the simple question is how can I use the above features array defined in data.js and use it in my .pug file for iteration.

+

Regards.

+

Update 1: More detailed question. +Update 2: I am not using any backend framework like expressJS or Django. I am just generating HTML markup from PUG.

","

Now knowing that you're just using PugJS, you can approach it this way. Create a new pug file with an unbuffered code block, declare a variable with your data object, and then include that file wherever you need it.

+

features.pug

+
-
+  const features = [
+    { title: '...', desc: '...', svg: '...' },
+    // .... other objects
+  ]
+
+

index.pug (now you can access the features object)

+
include features
+
+ul 
+  each feature in features
+    li= feature.title
+
",html +"how to correctly saving a profile instance in django

I have a problem with creating a profile instance in Django. when I try to update a profile the images of the profile don't save in the database My guess is that the form.save(commit=False) does not upload the photo nor update the field as it should but I do not understand why : +here is my code:

+

models.py

+
class Profile(models.Model):
+user         = models.OneToOneField(User, primary_key =True, on_delete=models.CASCADE, related_name= 'profile')
+image        = models.OneToOneField(UserImage, on_delete=models.SET_NULL, null=True, blank=True)
+phone_number = models.CharField(max_length=50, null = True, blank = True)
+followers    = models.ManyToManyField(User, related_name='follower', blank=True)
+following    = models.ManyToManyField(User, related_name='following', blank=True)
+biography    = models.TextField(max_length=250, null=True, blank=True)
+
+class UserImage(models.Model):
+avatar       = models.ImageField(blank=True, null=True,upload_to='avatar_pic')                                  
+header_image = models.ImageField(blank=True, null=True,upload_to='header_pic')
+                                    
+                                    
+
+

forms.py

+
class ProfileForm(ModelForm):
+class Meta:
+    model = Profile
+    fields = (
+        'phone_number',
+        'biography',
+        )
+
+class ImageProfileForm(ModelForm):
+
+class Meta:
+    model = UserImage
+    fields = (
+        'avatar',
+        'header_image',
+        )
+
+

views.py

+
@login_required
+def CompleteSignUp(request):
+
+if request.method == 'POST':
+    profile_form = ProfileForm(request.POST,request.FILES ,instance=request.user.profile)
+    image_profile_form = ImageProfileForm(request.POST, instance=request.user.profile.image)
+    if profile_form.is_valid() and image_profile_form.is_valid():
+        profile = profile_form.save(commit=False)
+        images  = image_profile_form.save()
+        profile.user = request.user
+        profile.social = social
+        profile.image = images
+        profile_form.save()
+        return redirect('blog:Home')
+else:
+    profile_form = ProfileForm(
+                                initial={
+                                    'phone_number':request.user.profile.phone_number,
+                                    'biography':request.user.profile.biography
+                                    }
+                            )
+    if request.user.profile.image:
+        image_profile_form = ImageProfileForm(
+                                            initial={
+                                                'avatar':request.user.profile.image.avatar,
+                                                'header_image':request.user.profile.image.header_image
+                                            }
+                                    )
+    else:
+        image_profile_form = ImageProfileForm()
+    return render(request, 'user/createprofile.html', {'form_p': profile_form, 'form_i': image_profile_form})
+
+

templates

+
{% block content %}
+<form method="POST" enctype="multipart/form-data">
+    {% csrf_token %}
+    <div>
+        {{ form_p.biography }}
+        biography 
+    </div>
+    <div>
+        {{ form_p.phone_number }}
+        phone_number
+    </div>
+    <div>
+        {{ form_i.avatar }}
+        avatar
+    </div>
+    <div>
+        {{ form_i.header_image }}
+        header
+    </div>
+
+
+ <br>
+    <input type="submit" value="Register">
+</br>
+
+</form>
+    {% for field in form_s %}
+        {% for error in field.errors %}
+        <p style="color: rgba(255, 0, 0, 0.678)">{{ error }}</p>
+        {% endfor %}
+    {% endfor %}
+
+{% endblock %}
+
+

profile save but the image of the profile doesn't save what's my fault. +...

","

Change:

+
        profile.user = request.user
+        profile.social = social
+        profile.image = images
+        profile_form.save()
+
+

To:

+
        profile.user = request.user
+        profile.social = social
+        profile.image = images
+        profile.save() # Use this
+
+

You need to save profile instead of the form with commit=False, because you did custom stuff to profile.

",html +"Insert/Append single child element to multiple parent elements with vanilla javascript

I have 5 div's with the class .faq, how to append a new child element at the end of each divs

+

This is what i have so far:

+
const faqBoxes = document.querySelectorAll('.faq')
+const toggler = document.createElement('i')
+toggler.className = `toggler fas fa-chevron-down`
+faqBoxes.forEach(box => {
+    // box.insertAdjacentHTML('beforeend', toggler) 
+        -- returned [object HTMLElement]
+    // box.appendChild(toggler) 
+        -- but this appends the new element only on the last div
+})
+
+

i am adding only a single div, instead of 5 for the sake of simplicity

+

HTML(before inserting element):

+
<div class="faq">
+    <h3 class="faq-title">How many team members can i invite?</h3>
+    <p class="faq-content">You can invite up to 2 additional users on the Free plan. There is no limit on
+    team members for the Premium plan.</p>
+</div>
+
+

HTML(After inserting element):

+
<div class="faq">
+    <h3 class="faq-title">How many team members can i invite?</h3>
+    <p class="faq-content">You can invite up to 2 additional users on the Free plan. There is no limit on
+    team members for the Premium plan.</p>
+    <i class="toggler fas fa-chevron-down></i> <!-- new element-->
+</div>
+
+

+
+
const faqContainer = document.querySelector('.faq-box')
+const faqBoxes = document.querySelectorAll('.faq')
+
+const displayIcons = () => {
+  const toggler = document.createElement('i')
+  toggler.className = `toggler fas fa-chevron-down`
+  faqBoxes.forEach(box => {
+    // box.insertAdjacentHTML('beforeend', toggler)
+    box.appendChild(toggler)
+  })
+}
+
+window.addEventListener('DOMContentLoaded', displayIcons)
+
+const showFaqContent = event => {
+  if (event.target.classList.contains('toggler') || event.target.classList.contains('faq-title')) {
+    const parentElem = event.target.parentElement
+    parentElem.classList.add('active')
+  }
+}
+
+faqContainer.addEventListener('click', showFaqContent)
+
*,
+*::before,
+*::after {
+  margin: 0;
+  padding: 0;
+  box-sizing: border-box;
+  list-style-type: none;
+  text-decoration: none;
+}
+
+body {
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  min-height: 100vh;
+  overflow: hidden;
+  font-family: 'poppins';
+  background: #ECE9E6;
+  /* fallback for old browsers */
+  background: -webkit-linear-gradient(to right, #FFFFFF, #ECE9E6);
+  /* Chrome 10-25, Safari 5.1-6 */
+  background: linear-gradient(to right, #FFFFFF, #ECE9E6);
+  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
+}
+
+.main-container {
+  height: 100%;
+  width: 90%;
+}
+
+.main-container h1 {
+  position: relative;
+  color: rgb(54, 94, 128);
+}
+
+.main-container h1 i {
+  font-size: 1.5rem;
+}
+
+.main-container h1::before {
+  content: '';
+  position: absolute;
+  width: 100%;
+  height: 3px;
+  bottom: 0;
+  background-color: rgba(70, 131, 180, 0.507);
+}
+
+.main-container h1::after {
+  content: '';
+  position: absolute;
+  width: 25%;
+  height: 3px;
+  bottom: 0px;
+  left: 0;
+  background-color: rgb(70, 131, 180);
+}
+
+.faq-box {
+  background-color: #fff;
+  border-radius: 8px;
+  box-shadow: 4px 4px 8px hsl(0, 0%, 80%);
+}
+
+.faq {
+  position: relative;
+  padding: .8rem 1rem;
+  margin: .5rem;
+  border-bottom: .5px solid rgba(221, 221, 221, 0.829);
+}
+
+.faq-title {
+  color: steelblue;
+  font-weight: 400;
+  cursor: pointer;
+}
+
+.faq.active h3 {
+  font-weight: bold;
+}
+
+.faq-content {
+  display: none;
+  font-family: 'nunito', 'sans-serif';
+  background-color: rgb(235, 235, 235);
+  border-radius: 5px;
+  border-left: 5px solid rgb(54, 94, 128);
+  margin-top: 10px;
+  padding: 1rem;
+  font-size: .9rem;
+  color: hsl(208, 41%, 20%);
+  transition: display .4s ease-in;
+}
+
+.faq.active .faq-content {
+  display: block;
+}
+
+.faq .toggler {
+  position: absolute;
+  top: 1.25rem;
+  right: 1rem;
+  cursor: pointer;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Day-12 Faq Boxes</title>
+  <!-- google api/fonts -->
+  <link rel=""preconnect"" href=""https://fonts.googleapis.com"">
+  <link rel=""preconnect"" href=""https://fonts.gstatic.com"" crossorigin>
+  <link href=""https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700&display=swap"" rel=""stylesheet"">
+  <!-- custom css -->
+  <link rel=""stylesheet"" href=""style.css"" type=""text/css"">
+</head>
+
+<body>
+
+  <div class=""main-container"">
+    <h1><i class=""fas fa-info-circle""></i> FAQ</h1>
+    <div class=""faq-box hide"">
+      <div class=""faq active"">
+        <h3 class=""faq-title"">How many team members can i invite?</h3>
+        <p class=""faq-content"">You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.</p>
+      </div>
+      <div class=""faq"">
+        <h3 class=""faq-title"">What is the maximux file upload size?</h3>
+        <p class=""faq-content"">No more than 2GB. All files in your account must fit your allotted storage space.</p>
+      </div>
+      <div class=""faq"">
+        <h3 class=""faq-title"">How do i reset my password?</h3>
+        <p class=""faq-content"">Click “Forgot password” from the login page or “Change password” from your profile page. A reset link will be emailed to you.</p>
+      </div>
+      <div class=""faq"">
+        <h3 class=""faq-title"">Can i cancel my subscription?</h3>
+        <p class=""faq-content"">Yes! Send us a message and we’ll process your request no questions asked.</p>
+      </div>
+      <div class=""faq"">
+        <h3 class=""faq-title"">Do you provide any additional support?</h3>
+        <p class=""faq-content"">Chat and email support is available 24/7. Phone lines are open during normal business hours.</p>
+      </div>
+    </div>
+  </div>
+
+  <!-- fontawesome script -->
+  <script src=""https://kit.fontawesome.com/39350fd9df.js""></script>
+  <!-- Custom Javascript -->
+  <script src=""main.js"" type=""text/javascript""></script>
+</body>
+
+
+

","

Add your createElement code to your loop so you create one new element on each iteration.

+

+
+
const faqBoxes = document.querySelectorAll('.faq');
+
+faqBoxes.forEach(box => {
+
+  const toggler = document.createElement('i');
+
+  toggler.textContent = 'Hallo';
+  toggler.className = 'red';
+
+  box.appendChild(toggler);
+
+});
+
.red { color: red; }
+
<div class=""faq"" />
+<div class=""faq"" />
+<div class=""faq"" />
+
+
+

",html +"Color specific text

I would like to have a specific text colored differently in HTML/PHP/CSS/JS.

+

I have a text similar to this structure:

+
+

@john please move the invite to the next week.

+
+

What i would like to achieve is to have the wording "@john" colored in green while the rest of the text characters should remain in black. In other words the "@" and the first space " " right after the @, are the delimiters of the green text.

+

Can you please advise on how to achieve this?

+

Thanks, +Slim

","

You can use Regular expressions for this; the character \@ will just match a "@", and the character \w+ will match a word - a word is a set of characters which are unseparated by commas, spaces, full stops, etc.

+

Lastly, you will need to use a String Iterator to find all matches and loop through them, and, of course, re-color them.

+

Here is how you would do this:

+

+
+
function color_text(text) {
+    let matches = text.matchAll(/\@\w+/g);
+    let current_match;
+    while(!current_match?.done) {
+        current_match = matches.next();
+        if(current_match?.done) {
+            break;
+        }
+        let value = current_match?.value[0];
+        text = text.replace(value, ""<span style='color: #00db58'>"" + value + ""</span>"");
+    }
+    return text;
+}
+
+
+// TESTING HERE  -- - - -- - - -
+
+document.write(color_text(""@john please move the invite to the next week.""));
+document.write(""<br>"");
+document.write(color_text(""@john please tell @josh to stop being annoying.""));
+
+
+

",html +"Delete modal contents and display new contents

Hi friends I have a modal that has a button inside

+

I want the current contents of my modal to be deleted when that button is clicked

+

And then the new content, which is an input, appears after a few seconds of loading

+
<div id="myModal" class="modal">
+        <div class="modal-content">
+            <span class="close">&times;</span>
+            <p>Connect</p>
+            <div class="wall">
+                <div class="sc-bYSBpT kxgAIA">
+                    <div class="sc-kTUwUJ hsKMjF">
+                        <button  class="sc-jbKcbu sc-dNLxif sc-uJMKN licBat">
+                                <div class="sc-jqCOkK irnmqJ">
+                                    <div color="#E8831D" class="sc-jnlKLf fFNbAV">Install</div>
+                                </div>
+                                
+                            </button>
+                        </div>
+                </div>
+            </div>
+        </div>
+    </div>
+
+
+<script>
+        var modal = document.getElementById("myModal");
+
+        var btn = document.getElementById("myBtn");
+
+        var span = document.getElementsByClassName("close")[0];
+
+        btn.onclick = function() {
+            modal.style.display = "block";
+        }
+
+        span.onclick = function() {
+            modal.style.display = "none";
+        }
+
+        window.onclick = function(event) {
+            if (event.target == modal) {
+                modal.style.display = "none";
+            }
+        }
+    </script>
+
","

if another content is in the modal

+

+
+
var modal = document.getElementById(""myModal"");
+var startContent = document.getElementById(""startContent"");
+
+var btn = document.getElementById(""myBtn"");
+
+var span = document.getElementsByClassName(""close"")[0];
+
+var btnInstall = document.getElementById(""btnInstall"");
+        
+var newContent = document.getElementById(""newContent"");
+
+btn.onclick = function() {
+   modal.style.display = ""block"";                       
+}
+        
+btnInstall.onclick = function() {
+   startContent.style.display = ""none"";            
+   newContent.style.display = ""block"";
+}
+
+span.onclick = function() {
+   modal.style.display = ""none"";
+}                       
+
+window.onclick = function(event) {
+   if (event.target == modal) {
+      modal.style.display = ""none"";
+   }
+}
+    
+
<button id=""myBtn"" >
+   myBtn
+</button>
+<div id=""myModal"" class=""modal""  style=""display:none"">
+   <div class=""modal-content"" id=""startContent"">
+      <span class=""close"">&times;</span>
+      <p>Connect</p>
+      <div class=""wall"">
+         <div class=""sc-bYSBpT kxgAIA"">
+            <div class=""sc-kTUwUJ hsKMjF"">
+               <button  class=""sc-jbKcbu sc-dNLxif sc-uJMKN licBat"">
+                  <div class=""sc-jqCOkK irnmqJ"">
+                     <div color=""#E8831D"" id=""btnInstall"" class=""sc-jnlKLf fFNbAV"">Install</div>
+                     </div>
+               </button>
+            </div> 
+         </div>
+      </div>
+   </div>
+   <div id=""newContent"" style=""display:none"">
+      <input type=""text"">           
+   </div>
+</div>
+
+
+

",html +"How to change link color on hover and change it back (with per-link styling)?

Each of the links on my website has a unique color, which is defined within the style argument within each <a> tag. I want to be able to change the background color of each link on the page to aqua and change the text color to white on hover. However, because of the separate color per link, the text color does not change and is overwritten. How can I get around this?

+

Here is my code:

+

+
+
a {
+  color: black;
+}
+
+a:hover {
+  background-color: aqua;
+  color: white;
+}
+
<a href=about style=""color:cyan"">About</a><br>
+<a href=how style=""color:magenta"">How this site was made</a><br>
+<a href=changelog style=""color:goldenrod"">Upcoming Changes & Changelog</a><br>
+
+
+

+

Edit: To clarify, I want the links to remain the color they are, but I want them to change to white on hover, and change back on non-hover. The highlight color change already works.

","

Use CSS variables instead of inline color so you don't have to deal with !important and specificity issues:

+

+
+
a {
+  color: var(--c,black);
+}
+
+a:hover {
+  background-color: aqua;
+  color: white;
+}
+
<a href=about style=""--c:cyan"">About</a><br>
+<a href=how style=""--c:magenta"">How this site was made</a><br>
+<a href=changelog style=""--c:goldenrod"">Upcoming Changes & Changelog</a><br>
+
+
+

",html +"Why the Alegreya font doesn't display correctly in some browsers?

I use the following minimal HTML code for reproducing the problem:

+

+
+
<html>
+
+<body>
+  <link rel=""preconnect"" href=""https://fonts.gstatic.com"">
+  <link href=""https://fonts.googleapis.com/css2?family=Alegreya&display=swap"" rel=""stylesheet"">
+
+  <style>
+    body {
+      font-family: ""Alegreya""
+    }
+  </style>
+
+  <h1>Testing the web font Alegreya</h1>
+  Testing the web font Alegreya
+</body>
+
+</html>
+
+
+

+

The document is displayed like this: +

+

As you can see, there is a weird outline around some letters. This behavior appears only for H1 tags and only for the webfont Alegreya. In normal text, it works. With another font, it works. With the Alegreya font installed on the system, it works too. It has to be downloaded as a webfont to see the bug.

+

Tested on Windows 10, on two computers. It doesn't work on Opera, Edge and Chrome. It does work on IE and Firefox though.

+

What's happening here?

","

I had the same issue. It seems related to the font-weight applied. +I fixed it by specifying explicitly the font weight(s) to be loaded in the URL. +See the code snippet below.

+

+
+
<html>
+
+<body>
+  <link rel=""preconnect"" href=""https://fonts.gstatic.com"">
+  <link href=""https://fonts.googleapis.com/css2?family=Alegreya:wght@400;700&display=swap"" rel=""stylesheet"">
+
+  <style>
+    body {
+      font-family: ""Alegreya""
+    }
+  </style>
+
+  <h1>Testing the web font Alegreya</h1>
+  Testing the web font Alegreya
+</body>
+
+</html>
+
+
+

",html +"My slide navigation menu does not hide the content that it was sliding over

I tried my best to make sense of the title but for more references, I am giving screenshots below the menu when it slides over the page covering the content the content should be hidden but its not

+

Before: +https://imgur.com/PTNwfdA

+

After: +https://imgur.com/B2Iz4IE

+

Here's the CSS for my navigation:

+
/* navbar Start*/
+
+* {
+    margin: 0;
+    padding: 0;
+    box-sizing: border-box;
+}
+
+.wrapper {
+    position: fixed;
+    top: 0;
+    right: -100%;
+    height: 100%;
+    width: 100%;
+    background-color: #F68B50;
+    /*background: linear-gradient(375deg, #F68B50, #4114a1, #f92c78);*/
+    /* background: linear-gradient(375deg, #1cc7d0, #2ede98); */
+    /* background: linear-gradient(-45deg, #e3eefe 0%, #efddfb 100%);*/
+    transition: all 0.6s ease-in-out;
+}
+
+#active:checked~.wrapper {
+    /*left: 0;*/
+    right: 0;
+}
+
+.menu-btn {
+    position: absolute;
+    z-index: 2;
+    right: 20px;
+    /*left: 20px; */
+    top: 20px;
+    height: 50px;
+    width: 50px;
+    text-align: center;
+    line-height: 50px;
+    border-radius: 50%;
+    font-size: 20px;
+    cursor: pointer;
+    /*color: #fff;*/
+    /*background: linear-gradient(90deg, #f92c78, #4114a1);*/
+    /* background: linear-gradient(375deg, #1cc7d0, #2ede98); */
+    /* background: linear-gradient(-45deg, #e3eefe 0%, #efddfb 100%); */
+    transition: all 0.3s ease-in-out;
+}
+
+.menu-btn span,
+.menu-btn:before,
+.menu-btn:after {
+    content: "";
+    position: absolute;
+    top: calc(50% - 1px);
+    left: 30%;
+    width: 40%;
+    border-bottom: 3px solid #000000;
+    transition: transform .6s cubic-bezier(0.215, 0.61, 0.355, 1);
+}
+
+.menu-btn:before {
+    transform: translateY(-8px);
+}
+
+.menu-btn:after {
+    transform: translateY(8px);
+}
+
+.close {
+    z-index: 1;
+    width: 100%;
+    height: 100%;
+    pointer-events: none;
+    transition: background .6s;
+}
+
+
+/* closing animation */
+
+#active:checked+.menu-btn span {
+    transform: scaleX(0);
+}
+
+#active:checked+.menu-btn:before {
+    transform: rotate(45deg);
+    border-color: #fff;
+}
+
+#active:checked+.menu-btn:after {
+    transform: rotate(-45deg);
+    border-color: #fff;
+}
+
+.wrapper ul {
+    position: absolute;
+    top: 60%;
+    left: 50%;
+    height: 90%;
+    transform: translate(-50%, -50%);
+    list-style: none;
+    text-align: right;
+}
+
+.wrapper ul li {
+    height: 10%;
+    margin: 15px 0;
+}
+
+.wrapper ul li a {
+    text-decoration: none;
+    font-size: 30px;
+    font-weight: 500;
+    padding: 5px 30px;
+    color: #fff;
+    border-radius: 50px;
+    position: absolute;
+    line-height: 50px;
+    margin: 5px 30px;
+    opacity: 0;
+    transition: all 0.3s ease;
+    transition: transform .6s cubic-bezier(0.215, 0.61, 0.355, 1);
+}
+
+.wrapper ul li a:after {
+    position: absolute;
+    content: "";
+    background: #fff;
+    /*background: linear-gradient(#14ffe9, #ffeb3b, #ff00e0);*/
+    /*background: linear-gradient(375deg, #1cc7d0, #2ede98);*/
+    width: 100%;
+    height: 100%;
+    left: 0;
+    top: 0;
+    border-radius: 50px;
+    transform: scaleY(0);
+    z-index: -1;
+    transition: transform 0.3s ease;
+}
+
+.wrapper ul li a:hover:after {
+    transform: scaleY(1);
+}
+
+.wrapper ul li a:hover {
+    color: #4114a1;
+}
+
+input[type="checkbox"] {
+    display: none;
+}
+
+.product a img {
+    display: none;
+    position: absolute;
+    left: -400px;
+    top: -200px;
+}
+
+.product a img {
+    display: none;
+}
+
+.product a:hover img {
+    display: inherit;
+}
+
+.content {
+    position: absolute;
+    top: 50%;
+    left: 50%;
+    transform: translate(-50%, -50%);
+    z-index: -1;
+    text-align: center;
+    width: 100%;
+    color: #202020;
+    overflow-y: hidden;
+}
+
+.content .title {
+    font-size: 40px;
+    font-weight: 700;
+}
+
+.content p {
+    font-size: 35px;
+    font-weight: 600;
+}
+
+#active:checked~.wrapper ul li a {
+    opacity: 1;
+    align-items: center;
+}
+
+.wrapper ul li a {
+    transition: opacity 1.2s, transform 1.2s cubic-bezier(0.215, 0.61, 0.355, 1);
+    transform: translateX(100px);
+    font-family: 'LemonMilk';
+    align-items: center;
+}
+
+#active:checked~.wrapper ul li a {
+    transform: none;
+    transition-timing-function: ease, cubic-bezier(.1, 1.3, .3, 1);
+    /* easeOutBackを緩めた感じ */
+    transition-delay: .6s;
+    transform: translateX(-100px);
+}
+
+.pages-nav--open {
+    pointer-events: auto;
+    opacity: 1;
+    -webkit-transform: translate3d(0, 0, 0);
+    transform: translate3d(0, 0, 0);
+}
+
+.pages-nav__item {
+    display: flex;
+    flex-direction: row;
+    min-height: 300vh;
+}
+
+.pages-nav .pages-nav__item--social {
+    width: 100%;
+    opacity: 0;
+    -webkit-transition: -webkit-transform 1.2s, opacity 1.2s;
+    transition: transform 1.2s, opacity 1.2s;
+    -webkit-transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
+    transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
+    -webkit-transform: translate3d(0, 20px, 0);
+    transform: translate3d(0, 20px, 0);
+}
+
+.pages-nav--open .pages-nav__item--social {
+    opacity: 1;
+    -webkit-transition-delay: 0.35s;
+    transition-delay: 0.35s;
+    -webkit-transform: translate3d(0, 0, 0);
+    transform: translate3d(0, 0, 0);
+}
+
+.link {
+    font-size: 0.85em;
+    font-weight: bold;
+    position: relative;
+    letter-spacing: 1px;
+    text-transform: uppercase;
+}
+
+.link:hover,
+.link:focus {
+    color: #fff;
+}
+
+.link--page {
+    display: block;
+    color: #cecece;
+    text-align: center;
+}
+
+.link--page:not(.link--faded)::before {
+    content: '';
+    position: absolute;
+    top: 100%;
+    left: 50%;
+    width: 50%;
+    height: 2px;
+    margin: 5px 0 0 -15px;
+    background: #fff;
+    -webkit-transition: -webkit-transform 0.3s;
+    transition: transform 0.3s;
+    -webkit-transform: scale3d(0, 1, 1);
+    transform: scale3d(0, 1, 1);
+}
+
+.link--page:hover:before {
+    -webkit-transform: scale3d(1, 1, 1);
+    transform: scale3d(1, 1, 1);
+}
+
+.link--faded {
+    color: #4f4f64;
+}
+
+.link--faded:hover,
+.link--faded:focus {
+    color: #5c5edc;
+}
+
+.link--page.link--faded {
+    font-size: 0.65em;
+}
+
+.link--social {
+    font-size: 1.5em;
+    margin: 0 0.75em;
+}
+
+.text-hidden {
+    position: absolute;
+    display: block;
+    overflow: hidden;
+    width: 0;
+    height: 0;
+    color: transparent;
+}
+
+@media screen and (max-width: 40em) {
+    .js .pages-nav {
+        display: block;
+        padding: 10px 20px 0 20px;
+        text-align: left;
+    }
+    .pages-nav__item {
+        width: 100%;
+    }
+    .pages-nav__item--small {
+        display: inline-block;
+        width: auto;
+        margin-right: 5px;
+    }
+    .pages-nav__item--social {
+        font-size: 0.9em;
+    }
+    .menu-button {
+        top: 15px;
+        right: 10px;
+        left: auto;
+    }
+    .info {
+        font-size: 0.85em;
+    }
+    .poster {
+        margin: 1em;
+    }
+}
+
+/* ///////////////////// navbar end ///////////////////////// */
+
+

and here's my css for the page this is on:

+
.typewritter {
+  height: 80vh;
+  /*This part is important for centering*/
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.typing-demo {
+  width: 28%;
+  animation: typing 4s steps(22), blink .5s step-end infinite alternate;
+  white-space: nowrap;
+  overflow: hidden;
+  border-right: 3px solid;
+  font-family: monospace;
+  font-size: 2em;
+}
+
+@keyframes typing {
+  from {
+    width: 0
+  }
+}
+
+@keyframes blink {
+  50% {
+    border-color: transparent
+  }
+}
+
+
+body {
+    margin: 0px;
+}
+
+#container {
+    /* Center the text in the viewport. */
+    position: absolute;
+
+  display: flex;
+    margin: auto;
+    width: 100vw;
+    height: 80pt;
+    top: 0;
+    bottom: 0;
+
+    /* This filter is a lot of the magic, try commenting it out to see how the morphing works! */
+    filter: url(#threshold) blur(0.6px);
+}
+
+/* Your average text styling */
+#text1, #text2 {
+    position: absolute;
+    width: 100%;
+    display: inline-block;
+
+    font-family: 'Raleway', sans-serif;
+    font-size: 80pt;
+
+    text-align: center;
+
+    user-select: none;
+}
+
+

If any more info is needed I'll be happy to provide it!

","

all you need to do is just set a greater z-index to .wrapper also u need to give a z-index to .menu-btn else it would be below the wrapper +this should be your code

+

+
+
.menu-btn{
+  position: absolute;
+  z-index: 12;
+  right: 20px;
+  /*left: 20px; */
+  top: 20px;
+  height: 50px;
+  width: 50px;
+  text-align: center;
+  line-height: 50px;
+  border-radius: 50%;
+  font-size: 20px;
+  cursor: pointer;
+  /*color: #fff;*/
+  /*background: linear-gradient(90deg, #f92c78, #4114a1);*/
+  /* background: linear-gradient(375deg, #1cc7d0, #2ede98); */
+ /* background: linear-gradient(-45deg, #e3eefe 0%, #efddfb 100%); */
+  transition: all 0.3s ease-in-out;
+}
+.wrapper{
+  position: fixed;
+  z-index: 10;
+  top: 0;
+  right: -100%;
+  height: 100%;
+  width: 100%;
+  background-color: #F68B50;
+  /*background: linear-gradient(375deg, #F68B50, #4114a1, #f92c78);*/
+  /* background: linear-gradient(375deg, #1cc7d0, #2ede98); */
+ /* background: linear-gradient(-45deg, #e3eefe 0%, #efddfb 100%);*/
+  transition: all 0.6s ease-in-out;
+}
+
+
+

",html +"Share image via social media from PWA

In my Nuxt PWA I have a function that converts my HTML to Canvas using this package. The generated image is in base 64. Now I want to be able to share that image via: Whatsapp, Facebook, email, Instagram etc. I have found several packages but they all don't seem to support sharing files only URLs and Text.

+

This is my share function:

+
shareTicket(index) {
+  html2canvas(this.$refs['ticket-' + index][0], {
+    backgroundColor: '#efefef',
+    useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem
+  }).then((canvas) => {
+    let url = canvas.toDataURL('image/png') // finally produced image url
+
+    if (navigator.share) {
+      navigator.share({
+        title: 'Title to be shared',
+        text: 'Text to be shared',
+        url: this.url,
+      })
+    }
+  })
+
+

When I take out the if (navigator.share) condition I get an error in my console that navigator.share is not a function. I read somewhere that it only works on HTTPS so I uploaded to my staging server and tried but still got the same error.

+

Just to be clear I want to be able to share the generated image itself and not a URL.

","

Tell me if this URL works for you: https://nuxt-share-social-media.netlify.app
+If it does, you can find the Github repo here: https://github.com/kissu/so-share-image-bounty

+

The code is

+
<template>
+  <div>
+    <div id="capture" ref="element" style="padding: 10px; background: #f5da55">
+      <h4 style="color: #000">Hello world!</h4>
+    </div>
+
+    <br />
+    <br />
+    <button @click="share">share please</button>
+  </div>
+</template>
+
+<script>
+import html2canvas from 'html2canvas'
+
+export default {
+  methods: {
+    share() {
+      // iife here
+      ;(async () => {
+        if (!('share' in navigator)) {
+          return
+        }
+        // `element` is the HTML element you want to share.
+        // `backgroundColor` is the desired background color.
+        const canvas = await html2canvas(this.$refs.element)
+        canvas.toBlob(async (blob) => {
+          // Even if you want to share just one file you need to
+          // send them as an array of files.
+          const files = [new File([blob], 'image.png', { type: blob.type })]
+          const shareData = {
+            text: 'Some text',
+            title: 'Some title',
+            files,
+          }
+          if (navigator.canShare(shareData)) {
+            try {
+              await navigator.share(shareData)
+            } catch (err) {
+              if (err.name !== 'AbortError') {
+                console.error(err.name, err.message)
+              }
+            }
+          } else {
+            console.warn('Sharing not supported', shareData)
+          }
+        })
+      })()
+    },
+  },
+}
+</script>
+
+

Inspired from @denvercoder9!

+
+

More info about the answer

+
    +
  • I've used an IIFE because I was not sure how the whole thing works, but it's works great in a method context!
  • +
  • I've added a missing async because ESlint and in case you wanted to make something after
  • +
  • I've used $refs because this is how you should select specific parts of the DOM in the Vue ecosystem
  • +
  • I've striped some things to keep it simple, hosted on Netlify to have some simple HTTPS and tested it on Chrome (v91), working perfectly fine!
  • +
  • Here is the link again to the MDN documentation of the Web Share API.
  • +
+
+

Compatibility

+

This is my experience for the browsers (tested on the MDN example and on my app, exact same results)

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
whereworking
iPad chromeyes
iPad firefoxyes
iPad safariyes
windows chromeyes
windows firefoxno
android chromeyes
android firefoxno
desktop linux chromeno
desktop linux firefoxno
+
+

For me, this was a mobile only feature (like for Android). But it looks like even some desktop browsers are handling this too. I have to admit that I was really surprised to even see this one work on Windows.
+Here is an interesting post from Google that correlates this compatibility: https://web.dev/web-share/#browser-support

+

Reading MDN again, it says

+
+

The navigator.share() method of the Web Share API invokes the native sharing mechanism of the device.

+
+

So, I guess that the "(desktop) device" mostly do not support the Share API.

+

TLDR: this is working totally as intended but the compatibility is really subpar so far.

",html +"Not Able to See Entire Page Source of Website using Selenium,Python

I am trying to scrape this website + https://script.google.com/a/macros/cprindia.org/s/AKfycbzgfCVNciFRpcpo8P7joP1wTeymj9haAQnNEkNJJ2fQ4FBXEco/exec

+ +

I am using selenium and python.I am not able to view entire page source,Basically i have to scrape the table inside it and click on next button,but the code of next and table not visible on page source.Here is my code

+ +
from selenium import webdriver
+from selenium.webdriver.support.ui import Select
+from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.common.exceptions import TimeoutException
+from bs4 import BeautifulSoup
+
+
+from selenium import webdriver
+
+browser = webdriver.PhantomJS()
+browser.get(link)
+
+
+pass1 = browser.find_element_by_xpath(""/html/body/div[2]/table[2]/tbody/tr[1]/td/div/div/div[2]/div[2]"")
+pass1.click()
+
+time.sleep(30)
+
+ +

I am getting this error,NoSuchElementException.

","

There are two iframes present on the page, so you need to first switch on those iframe and then you need to click on the element.
+And you can apply explicit wait on the element so that the script waits until the element is visible on the page.
+You can do it like:

+ +
browser = webdriver.PhantomJS()
+browser.get(link)
+browser.switch_to.frame(driver.find_element_by_id('sandboxFrame'))
+browser.switch_to.frame(driver.find_element_by_id('userHtmlFrame'))
+WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, ""//div[contains(@class,'charts-custom-button-collapse-left')]//div""))).click()
+
+ +

Note: You have to add the following imports:

+ +
from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+
",html +"Placeholder for contenteditable div with minimal JS

I created a div tag with the contenteditable attribute. +I want to put the placeholder in here, and I found the following code.

+ +

+
+
[contenteditable=true]:empty:before {
+  content: attr(placeholder);
+  display: block;
+  /* For Firefox */
+}
+
<div class=""test"" contenteditable=""true"" placeholder=""test""></div>
+
+
+

+ +

In a chromium-based engine, it looks like it's working. But I heard there is an error here that requires JavaScript. I couldn't find the error. Can you tell me what the problem is?

+ +

I'm also not sure that content:attr(); is the web standard in css. Is it a standardized CSS property?

","

The problem is that a <br> is automatically inserted inside a contenteditable div when it is empty. I think that they added <br> to prevent it from collapsing. Here's where they discussed this: Bugzilla.

+ +

Here's an example of the collapse prevention I mentioned. You can see that, initially, div has 0 height. However, you can still focus on it. Try typing, then erasing everything. Browser automatically inserts <br> to prevent it from returning to 0 height by adding a <br> which is one line-height high.

+ +

+
+
div {
+  border: 1px solid black;
+}
+
<div contenteditable=""true"" data-placeholder=""Test""></div>
+
+
+

+ +

So we can simply use <span>, which does not insert a random <br>, instead of <div> to do what you want like so. Try typing, then erasing the characters. The placeholder will be there exactly as you want it to be.

+ +

+
+
* {
+  box-sizing: border-box;
+}
+
+span {
+  display: block;
+  width: 100%;
+  border: 1px solid black;
+  border-radius: 5px;
+  font-family: sans-serif;
+  padding: 10px;
+  cursor: text;
+}
+
+span:empty::before {
+  content: attr(data-placeholder);
+  display: block;
+  height: 100%;
+  color: #00000066;
+}
+
<span contenteditable=""true"" data-placeholder=""Test""></span>
+
+
+

+ +

If you really have to use div, then you can erase the <br> manually using JS:

+ +

+
+
const editable = document.querySelector('#editable')
+editable.addEventListener('keyup', e => {
+  if (editable.innerText === '\n') editable.innerHTML = ''
+})
+
* {
+  box-sizing: border-box;
+}
+
+#editable {
+  display: block;
+  width: 100%;
+  border: 1px solid black;
+  border-radius: 5px;
+  font-family: sans-serif;
+  padding: 10px;
+  cursor: text;
+}
+
+div:empty::before {
+  content: attr(data-placeholder);
+  display: block;
+  height: 100%;
+  color: #00000066;
+}
+
<div id=""editable"" contenteditable=""true"" data-placeholder=""Test""></div>
+
+
+

+ +

Using attr() function in CSS with content is not experimental. With other CSS properties like color, though, it is still experimental. Read further on this MDN page.

",html +"How can I force the name property on the input fields in Angular 9?

I'm trying to switch off autofill Chrome built-in function in my Angular 9 app. I found the Chrome attach the autofill suggestions to the name of the input field.

+ +

I have this Angular 9 HTML code:

+ +
<input
+  [class]=""inputClass""
+  [(ngModel)]=""model[field]""
+  [id]=""field""
+  [name]=""field + '_' + random""
+  [placeholder]=""getPlaceholder()""
+  [disabled]=""disabled""
+  [type]=""type""
+  [autocomplete]=""random""
+  (keyup)=""validateField()"">
+
+ +

And I get this in the generated HTML code if I run the app:

+ +
<input
+  _ngcontent-cbv-c111=""""
+  class=""form-control ng-pristine ng-valid ng-touched""
+  ng-reflect-model=""""
+  id=""name""
+  ng-reflect-name=""name_6xuz5""
+  placeholder=""My placeholder""
+  type=""text""
+  autocomplete=""6xuz5"">
+
+ +

Now here isn't a name property on input tag. And that's because I use this syntax: [name]=""..."". If I use the name=""..."" syntax then the name property will be presented.

+ +

How can I force the name property on the input fields and still use the [name]=""..."" syntax to give a calculated value?

","

Using [name] tells Angular that this is a property binding (like an input), but you want to set an HTML attribute. For this you can instead use

+ +
<input [attr.name]=""field + '_' + random"" …>
+
+ +

which tells Angular that you want to set it as an attribute.

+ +

Alternatively, you can also use

+ +
<input name=""{{ field + '_' + random }}"" …>
+
+ +

but arguably that doesn't look as pretty.

+ +
+ +

This is a bit confusing in Angular, and there are plans to at least improve the documentation, see this.

",html +"How to display a message and close settings window in HTML?

I am working on a chrome extension and I want to be able to have a response when the 'done' button is clicked, the settings window should close and the user would receive a message :

+ +

Here is the code for the settings page: +settings.html

+ +
    <html>
+   <head>
+      <meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />
+      <link rel=""stylesheet"" type=""text/css"" href=""../styles/settings.css"">
+      <link rel=""stylesheet"" type=""text/css"" href=""https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"">
+      <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"">
+      <title>SSS- Settings</title>
+   </head>
+   <body>
+      <div class=""wrapper"">
+         <div class=""card"">
+            <div class=""card__header"">
+               <div class=""toolbar"">
+                  <div class=""toolbar__item toolbar__item--close""></div>
+                  <div class=""toolbar__item toolbar__item--min""></div>
+                  <div class=""toolbar__item toolbar__item--max""></div>
+.....................................................(other settings)
+<br>
+                     <div class=""buttons""><a href=""#""></a><button onclick=""closeFunction()"" id = ""save_settings"" class=""button"">Done</button></div>
+                  </div>
+               </div>
+            </div>
+         </div>
+      </div>
+      <script src=""../assets/js/settings.js""></script>
+      <script>
+      function closeFunction() {
+          close();
+      }
+      </script>
+   </body>
+</html>
+
+ +

settings.js

+ +
console.clear();
+
+toggle = document.querySelectorAll('.toggle');
+const fno = document.getElementById('fake-news-opt');
+const hso = document.getElementById('hate-speech-opt');
+const cbo = document.getElementById('click-baits-opt');
+const pwo = document.getElementById('profanity-words-opt');
+const save_button = document.getElementById('save_settings');
+
+
+
+
+.............
+
","

So from my understanding, you are trying to close the window when the ""DONE"" button is clicked, if so: +You can remove the onclick attribute from the button tag and attach an EventListener to the button itself like so:

+ +
save_button.addEventListener(""click"", () => {
+    close();
+}
+
",html +"Why does appendChild change based on order of elements?

https://jsfiddle.net/L835jsym/6/

+ +

I want to move to elements from one div to another using JavaScript. When I loop through and the divs they are moving TO is first it works. But when the div they are moving FROM is first it doesn't work. Why?

+ +

+
+
const newButtonEls = document.getElementsByClassName(""new-button"");
+for (let i = 0; i < newButtonEls.length; i++) {
+  const container = document.getElementsByClassName('new-media-btn-container')[0];
+  container.appendChild(newButtonEls[i]);
+}
+
<div class = ""new-media-btn-container"">
+  <p>Should be inserted below</p>
+</div>
+<div class = ""two"">
+  <p>Should not be inserted below here anymore</p>
+  <button class = ""new-button"">New Audio</button>
+  <button class = ""new-button"">New Folder</button>
+</div>
+
+
+

+ +

+
+
const newButtonEls = document.getElementsByClassName(""new-button"");
+for (let i = 0; i < newButtonEls.length; i++) {
+  const container = document.getElementsByClassName('new-media-btn-container')[0];
+  container.appendChild(newButtonEls[i]);
+}
+
<div class = ""two"">
+  <p>Should not be inserted below here anymore</p>
+  <button class = ""new-button"">New Audio</button>
+  <button class = ""new-button"">New Folder</button>
+</div>
+<div class = ""new-media-btn-container"">
+  <p>Should be inserted below</p>
+</div>
+
+
+

","

getElementsByClassName returns a live node list.

+ +

In the first example, when you move New Audio it is still the 0th item in the collection because you moved it to earlier in the document.

+ +

In the second example, when you move New Audio to later in the document it becomes the 1st element in the collection (you are changing the order of the elements that are members of that class) so when you increment i to 1 you append New Audio again and you never append New Folder (because you skipped over it when it was moved to position 0).

+ +

You probably want to use Array.from to convert the live node list into a static array.

",html +"How to get the ID value of a parent element by class that is not immediate? jQuery

I know how to get the value of an immediate parents class,id..etc.. But how do you get the ID value of a parent that is not immediate, and not the grandest-parent, but of a known class name? I know you would think just to get the ID value based on the class name. But I have a lot of dynamically loaded content, with the same classes. So I must have the class that is a parent of THIS element. Thanks!

+ +
<div class=""A"">
+    <div class=""B"" id=""1"">
+        <div class=""C"">
+            <div class=""D"">
+                <input class=""need-ID-of-class-B"" value="""">
+            </div>
+        </div>
+    </div>
+</div>
+
","

You can try with .parents() OR .closest():

+ +

+
+
console.log($('.need-ID-of-class-2').closest('.2').attr('id'));
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""1"">
+  <div class=""2"" id=""1"">
+    <div class=""3"">
+      <div class=""4"">
+        <input class=""need-ID-of-class-2"" value="""">
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"Is it possible to add a vue component to a traditional html form?

Is it possible to add a vue input component to a standard html form? I know this is not the ideal way to handle vue forms, but I'm curious about the possibility as a ""quick and dirty"" way for adding custom elements into pre existing html forms. Here's a hypothetical example:

+ +
<form action=""/users"" accept-charset=""UTF-8"" method=""post"">
+  <input type=""email"" name=""user[email]"" />
+  <input type=""password"" name=""user[password]"" />
+  <my-custom-fancy-vue-component />
+  <input type=""submit""value=""Sign up"">
+</form>
+
+ +

I'm wondering if the browser can read the value exposed by an input element withen the vue component and send that as a param when the user submit the form. Is there any other way to tell the browser how to access the value from a vue component if for example it doesn't use a native input internally, perhaps using a web component as a wrapper or using shadow dom?

","

Any <input> elements within the form should be included by the browser when the form is submitted. The browser won't care that the <input> is inside a Vue component.

+ +

For components that don't already have an <input> (or other suitable form element) you can add a hidden input, <input type=""hidden"">, to hold the value.

+ +

If the component you want to include is a third-party component then you won't be able to add the hidden input directly. However, you could still add it by using a wrapper component. The example below illustrates how you could handle that scenario.

+ +

+
+
const thirdPartyComponent = {
+  template: `
+    <button
+      @click=""onClick""
+      type=""button""
+    >
+      Increment {{ value }}
+    </button>
+  `,
+  
+  props: ['value'],
+  
+  methods: {
+    onClick () {
+      this.$emit('input', this.value + 1)
+    }
+  }
+}
+
+const myCustomFancyVueComponent = {
+  template: `
+    <div>
+      <third-party-component v-model=""counter"" />
+      <input type=""hidden"" :value=""counter"">
+    </div>
+  `,
+  
+  components: {
+    thirdPartyComponent
+  },
+  
+  data () {
+    return {
+      counter: 4
+    }
+  }
+}
+
+new Vue({
+  el: 'form',
+  
+  components: {
+    myCustomFancyVueComponent
+  }
+})
+
<script src=""https://unpkg.com/vue@2.6.11/dist/vue.js""></script>
+
+<form action=""/users"" accept-charset=""UTF-8"" method=""post"">
+  <input type=""email"" name=""user[email]"">
+  <input type=""password"" name=""user[password]"">
+  <my-custom-fancy-vue-component></my-custom-fancy-vue-component>
+  <input type=""submit"" value=""Sign up"">
+</form>
+
+
+

",html +"Updating HTML field filled with a Django value real-time

Say I have two form fields and another HTML paragraph that is basically just a Django value.

+ +

Number A:

+ +

<input ...>

+ +

Number B:

+ +

<input ...>

+ +

<p>{{ sum }}</p>

+ +

I want sum to update ""real time"" (i.e. after both numbers were input, the sum will be computed and input automatically by the system).

+ +

I have no idea where to start, I think it has something to do with some sort of javascript, but I have no idea how to link anything JS to Django and vice-versa.

","
+

You need add them in javascript but after add it only have on the browser side, you need to call ajax call I give link for how to call ajax in django

+
+ +
<input type='number' id='val1'/>
+<input type='number' id='val2'/>
+<input type='number' id='answer'/>
+
+ +

I geuss you have above three text

+ +

After creat blur on val2 +In body of blur event call ajax with django +Ajax call in django

",html +"Viewing list wrong on firefox

So i have this problem:

+ +

-On Chrome its showing this:

+ +

''' + +'''

+ +

-On Mozzila Firefox its showing this:

+ +

''' + +'''

+ +

I want to look like on chrome does on every platform.

+ +

+
+
<h3>Servicii</h3>
+</br>
+<ul>
+<li><a href=""#><h4 style=""color:#2e3760;"">Beneficiari publici</h4></a></li>
+<li><a href=""#""><h4 style=""color:#2e3760;"">Beneficiari privati</h4></a></li>
+<li><a href=""#""><h4 style=""color:#2e3760;"">HelpDesk</h4></a></li>
+</ul>
+
+
+

+ +

Firefox doesnt like the heading tag inside <a> tag, it seems.

","

Headings can't shouldn't be nested inside a phrasing content like a link or weird layout issues could happen, so try this structure instead

+ +
<h3>Servicii</h3>
+<br>
+<ul>
+<li><h4 style=""color:#2e3760;""><a href=""#>Beneficiari publici</a></h4></li>
+<li><h4 style=""color:#2e3760;""><a href=""#>Beneficiari privati</a></h4></li>
+<li><h4 style=""color:#2e3760;""><a href=""#"">HelpDesk</a></h4></li>
+</ul>
+
+ +

As a side note, there's no a </br> tag

",html +"creating a course registration form with paypal payment

I want to create a page that lists class, allows the user to choose a course + fill out their name and email, lets the user pay with paypal and if they paid the form writes the data to a database.

+ +

I know how to make an HTML and PHP form with the required fields, I know how to write data to a database, I researhed how to create a paypal business account to accept payments, but how do I write the form data to the database AFTER the paypal page? The browser is redirected to paypal's site for the payment isn't it?. +
+https://i.stack.imgur.com/KK34c.jpg
+how can I keep variables from page 1 and use them on page 3 to write to the database?

","

I would recommend implementing this server-side checkout pattern: https://developer.paypal.com/demo/checkout/#/pattern/server

+ +

API calls happen on your server to set up and capture the transaction: https://developer.paypal.com/docs/checkout/reference/server-integration/

+ +

When the API call to capture returns success, that is when you can immediately write the successful registration record in your database, and show the confirmation to the user.

",html +"Toggle text of a button when clicked

I have been trying to change the text of a button when it gets clicked.

+ +

this is the button

+ +
 <button id=""1"" onclick=""showhide(); toggle();"" > Open </button>
+
+ +

this is the js

+ +
function toggle(button)
+  {
+    if(document.getElementById(""1"").value==""Open""){
+     document.getElementById(""1"").value=""Close"";}
+
+    else if(document.getElementById(""1"").value==""Close""){
+     document.getElementById(""1"").value=""Open"";}
+
+ +

It never changes from ""Open"" however. Thanks for any help

","

Try this function, but you can directly call the toggle function directly from the button.

+ +
<button id=""button_1"" onclick=""toggle()"">Open</button>
+
+ +

+
+
function showhide() {
+  // Extra code here...
+  toggle();
+}
+
+function toggle() {
+  var button = document.getElementById('button_1');
+  
+  if (button.innerHTML == ""Open"") {
+    button.innerHTML = ""Close"";
+  } else {
+    button.innerHTML = ""Open"";
+  }
+}
+
<button id=""button_1"" onclick=""showhide()"">Open</button>
+
+
+

",html +"Creating styled url for finished react app

After deploying my react app, I noticed that when I am sharing it on whatsapp for example, The link looks really basic.

+ +

Title is ""React App"" and descriptions is ""website created with create-react app"".

+ +

I have managed to change title and description from the meta inside index.html and got something like:

+ +

My App

+ +

My description

+ +

I am trying to make it look like that:

+ +

+ +

I have read about React helmet but I did not understand if it is right for my case.

+ +

Thanks in advance!

","

React helmet is helpful if you need to customise the meta data on a per page basis, if you just need one set of data to be shown for your entire site it's not necessary for you to use it.

+ +

You should look into Open Graph tags. To break down the example image you provided there is 4 noteworthy sections (taken from their source code):

+ +
<meta property=""og:title"" content=""National Geographic: Stories of Animals, Nature, and Culture"">
+<meta property=""og:image"" content=""https://www.nationalgeographic.com/content/dam/ngdotcom/rights-exempt/homepage/nationalgeographicog.ngsversion.1530540626597.adapt.1900.1.jpg"">
+<meta property=""description"" content=""Explore National Geographic. A world leader in geography, cartography and exploration."">
+<meta property=""og:url"" content=""https://www.nationalgeographic.com"">
+
+ +

You can take a look at the page source to see this information and match it up if you would prefer to learn by seeing.

+ +

If you do look, you'll notice there is a seeming repetition of some tags, e.g. twitter:image, this allows you to provide images in different aspect ratios for these platforms to pull.

+ +

Note: It can sometimes take time for the crawler to pick up on changes to your meta tags, so be aware changes might not be immediately reflected.

",html +"Access the object of appended element

I'm trying to access the elements that are appended by a library that I use in my code, but I can't access them. I have this line in my html.

+ +
<div class=""bonds"" id=""original"" style=""display:block;""></div>
+
+ +

The library that I use will append some elements in here. So from the DOM inspector, it shows something like this.

+ +
<div class=""bonds"" id=""original"" style=""display:block;"">
+    <!-- append start -->
+    <div class=""FL-main fieldsLinker"">
+        <div class=""FL-left"">
+            <select></select>
+            <ul>
+                <li data-offset=""0""></li>
+                <li data-offset=""1""></li>
+                <li data-offset=""2""></li>
+            </ul>
+        </div>
+    </div>
+    <!-- append ended -->
+</div>
+
+ +

I'm trying to access the <ul></ul> element using the methods below but nothing works.

+ +
    +
  1. $('#original').children().children().children();

  2. +
  3. var original = $('#original').find('ul');

  4. +
+ +

My goal is to append <span class=""icon-close""></span> in each of <li></li> element when the page is loaded.

","

You could use JQuery find method to find the ul and loop over it's children. +Add your script at the end of all scripts. (library scripts).

+ +
$('#original').find('ul li').each(function(i) {
+   $(this).append('<span class=""icon-close""></span>');
+});
+
",html +"How to delete 2 specific th in a dynamically created table

I'm trying to delete 2 specific th depending on which delete button I press

+ +

Here is the relevant code :

+ +
<!--HTML-->
+<button type=""button"" class=""collapsible"">Gérer les formules</button>
+<div class=""form-group content"">
+<br />
+    <button type=""button"" class=""ajout-formule""><i class=""fas fa-plus-circle""> Ajouter une formule</i></button>
+    <div class=""panel-body add-formule"">
+    </div>
+</div>
+
+ +
// Javascript
+// add formule
+$('body').on('click', '.ajout-formule', function() {
+
+    const $formule = $('<div>').addClass('div-formule');
+
+    const $ligne_formule = $('<div>').addClass('ligne-formule');
+    const $btn_formule = $('<th>');
+    const $tableau_formule = $('<table class=""table"" id=""formule"">');
+    const $head_formule = $('<thead>');
+    const $tr_formule = $('<tr>');
+
+
+
+    $btn_formule.append('<button type=""button"" class=""btn spr-champs""><i class=""fas fa-trash""></i></button>');
+    $btn_formule.append('<button class=""btn nbr-champs"" type=""button""><i class=""fas fa-sort-numeric-down""></i></button>');
+    $btn_formule.append('<button class=""btn list-champs"" type=""button""><i class=""far fa-list-alt""></i></button>');
+    $btn_formule.append('<input type=""number"" name=""champs"" id=""champs"" class=""form-control pull-left"" value=""0""/>');
+
+    $tr_formule.append('<th><input type=""text"" name=""titre-formule"" id=""titre-formule"" class=""form-control pull-left"" /></th>');
+    $tr_formule.append('<th style=""width:16px;padding-bottom: 16px;""><i class=""fas fa-equals""></i></th>');
+    $tr_formule.append($btn_formule);
+
+    $head_formule.append($tr_formule);
+    $tableau_formule.append($head_formule);
+
+    $ligne_formule.append('<label class=""panel-heading"">Introduisez la formule : </label>');
+    $ligne_formule.append($tableau_formule);
+
+    $formule.append($ligne_formule);
+    $formule.append('<button type=""button"" class=""btn ajout-champs""><i class=""fas fa-plus-circle""> Ajouter un champ</i></button>');
+    $formule.append('<button type=""button"" class=""btn save-formule""><i class=""fas fa-check-square""> Enregistrer</i></button>');
+    $formule.append('<button type=""button"" class=""btn del-formule""><i class=""fas fa-trash""> Supprimer</i></button>')
+    $(this).parent().find('.add-formule').append($formule);
+});
+
+// add field
+$('body').on('click', '.ajout-champs', function(event) {
+    const $operateur = $('<select id=""operateur"">').addClass('ligne-formule operateur').css({""border-radius"": ""5px"",""padding-left"":""3px"",""padding-right"":""3px"",""margin-bottom"":""5px""}).prop(""name"",""operateur"");
+    const $btn_formule = $('<th>');
+    const $th_operateur = $('<th>');
+    var nb_cols = document.getElementById('formule').rows[0].cells.length;
+
+    $operateur.append('<option value=""plus"">&#xf067;</option>');
+    $operateur.append('<option value=""moins"">&#xf068;</option>');
+    $operateur.append('<option value=""fois"">&#xf00d;</option>');
+    $operateur.append('<option value=""divise"">&#xf529;</option>');
+
+    $btn_formule.append('<button type=""button"" class=""btn spr-champs""><i class=""fas fa-trash""></i></button>');
+    $btn_formule.append('<button class=""btn nbr-champs"" type=""button""><i class=""fas fa-sort-numeric-down""></i></button>');
+    $btn_formule.append('<button class=""btn list-champs"" type=""button""><i class=""far fa-list-alt""></i></button>');
+    $btn_formule.append('<input type=""number"" name=""champs"" id=""champs"" class=""form-control pull-left"" value=""0""/>');
+
+    $th_operateur.append($operateur);
+
+    if (nb_cols == 2)
+    {
+        $(this).parent().find('.table thead tr').append($btn_formule);
+    }
+    else
+    {
+        $(this).parent().find('.table thead tr').append($th_operateur);
+        $(this).parent().find('.table thead tr').append($btn_formule);
+    }
+});
+// del field
+$('body').on('click', '.spr-champs', function(event) {
+    var ndx = $(this).parent().index() + 1;
+
+    $('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
+
+});
+
+ +

This does work as intended which is not what I want

+ +

Here is what this does :

+ +
    +
  • Each time I press the ""Delete"" button above my field, it only deletes that whole th
  • +
+ +

Here is what I want :

+ +
    +
  • Depending on which delete button I press, delete that specific th but also delete the ""Operator"" th next to it
  • +
+ +

Here a screen of what I want :

+ +

+ +

Here a screen of how to use the snippet :

+ +

+ +

+
+
// collapsible
+var coll = document.getElementsByClassName(""collapsible"");
+var i;
+
+for (i = 0; i < coll.length; i++) {
+    coll[i].addEventListener(""click"", function() {
+        this.classList.toggle(""active"");
+        var content = this.nextElementSibling;
+        if (content.style.maxHeight){
+            content.style.maxHeight = null;
+        } else {
+            content.style.maxHeight = content.scrollHeight + ""px"";
+        }
+    });
+}
+
+// add formule
+$('body').on('click', '.ajout-formule', function() {
+
+    const $formule = $('<div>').addClass('div-formule');
+
+    const $ligne_formule = $('<div>').addClass('ligne-formule');
+    const $btn_formule = $('<th>');
+    const $tableau_formule = $('<table class=""table"" id=""formule"">');
+    const $head_formule = $('<thead>');
+    const $tr_formule = $('<tr>');
+
+
+
+    $btn_formule.append('<button type=""button"" class=""btn spr-champs""><i class=""fas fa-trash""></i></button>');
+    $btn_formule.append('<button class=""btn nbr-champs"" type=""button""><i class=""fas fa-sort-numeric-down""></i></button>');
+    $btn_formule.append('<button class=""btn list-champs"" type=""button""><i class=""far fa-list-alt""></i></button>');
+    $btn_formule.append('<input type=""number"" name=""champs"" id=""champs"" class=""form-control pull-left"" value=""0""/>');
+
+    $tr_formule.append('<th><input type=""text"" name=""titre-formule"" id=""titre-formule"" class=""form-control pull-left"" /></th>');
+    $tr_formule.append('<th style=""width:16px;padding-bottom: 16px;""><i class=""fas fa-equals""></i></th>');
+    $tr_formule.append($btn_formule);
+
+    $head_formule.append($tr_formule);
+    $tableau_formule.append($head_formule);
+
+    $ligne_formule.append('<label class=""panel-heading"">Introduisez la formule : </label>');
+    $ligne_formule.append($tableau_formule);
+
+    $formule.append($ligne_formule);
+    $formule.append('<button type=""button"" class=""btn ajout-champs""><i class=""fas fa-plus-circle""> Ajouter un champ</i></button>');
+    $formule.append('<button type=""button"" class=""btn save-formule""><i class=""fas fa-check-square""> Enregistrer</i></button>');
+    $formule.append('<button type=""button"" class=""btn del-formule""><i class=""fas fa-trash""> Supprimer</i></button>')
+    $(this).parent().find('.add-formule').append($formule);
+});
+
+// add field
+$('body').on('click', '.ajout-champs', function(event) {
+    const $operateur = $('<select id=""operateur"">').addClass('ligne-formule operateur').css({""border-radius"": ""5px"",""padding-left"":""3px"",""padding-right"":""3px"",""margin-bottom"":""5px""}).prop(""name"",""operateur"");
+    const $btn_formule = $('<th>');
+    const $th_operateur = $('<th>');
+    var nb_cols = document.getElementById('formule').rows[0].cells.length;
+
+    $operateur.append('<option value=""plus"">&#xf067;</option>');
+    $operateur.append('<option value=""moins"">&#xf068;</option>');
+    $operateur.append('<option value=""fois"">&#xf00d;</option>');
+    $operateur.append('<option value=""divise"">&#xf529;</option>');
+
+    $btn_formule.append('<button type=""button"" class=""btn spr-champs""><i class=""fas fa-trash""></i></button>');
+    $btn_formule.append('<button class=""btn nbr-champs"" type=""button""><i class=""fas fa-sort-numeric-down""></i></button>');
+    $btn_formule.append('<button class=""btn list-champs"" type=""button""><i class=""far fa-list-alt""></i></button>');
+    $btn_formule.append('<input type=""number"" name=""champs"" id=""champs"" class=""form-control pull-left"" value=""0""/>');
+
+    $th_operateur.append($operateur);
+
+    if (nb_cols == 2)
+    {
+        $(this).parent().find('.table thead tr').append($btn_formule);
+    }
+    else
+    {
+        $(this).parent().find('.table thead tr').append($th_operateur);
+        $(this).parent().find('.table thead tr').append($btn_formule);
+    }
+});
+
+// del field
+$('body').on('click', '.spr-champs', function(event) {
+    var ndx = $(this).parent().index() + 1;
+
+    $('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
+
+});
+
/* Style the header with a grey background and some padding */
+* {box-sizing: border-box;}
+
+body {
+    margin: 0;
+    font-family: Arial, Helvetica, sans-serif;
+}
+
+.header, .collapsible {
+    overflow: hidden;
+    background-color: #f1f1f1;
+    padding: 20px 10px;
+}
+
+.header a, .panel-body button.collapsible {
+    float: left;
+    color: black;
+    text-align: center;
+    padding: 12px;
+    text-decoration: none;
+    font-size: 18px;
+    line-height: 25px;
+    border-radius: 4px;
+}
+
+.header a.logo, .panel-body button.collapsible {
+    font-size: 25px;
+    font-weight: bold;
+}
+
+.header a:hover, .panel-body button.collapsible:hover {
+    background-color: #ddd;
+    color: black;
+}
+
+.header a.active {
+    background-color: dodgerblue;
+    color: white;
+}
+
+.header-right {
+    float: right;
+}
+
+@media screen and (max-width: 500px) {
+    .header a, .panel-body button.collapsible {
+        float: none;
+        display: block;
+        text-align: left;
+    }
+
+    .header-right {
+        float: none;
+    }
+}
+
+.contenuaccueil {
+    text-align: center;
+    position : absolute;
+    width : 100%;
+    color : black;
+    top:50%;
+    left:50%;
+    transform:translate(-50%,-50%);
+}
+
+.background
+{
+    margin-top : 10%;
+    margin-bottom : 10%;
+    position:relative;
+    text-align: center;
+}
+
+.img
+{
+    background-repeat: repeat-x;
+    width: 100%;
+    height: auto;
+    text-align: center;
+}
+
+footer {
+    text-align : center;
+    padding-top: 10px;
+    padding-bottom: 0px;
+    bottom:0;
+    width:100%;
+    color     : #A5A5A5;
+    font-family    : ""Lato"", sans-serif;
+    font-size    : 15px;
+    font-weight    : 400;
+    text-transform   : uppercase;
+    text-decoration   : none;
+    letter-spacing   : 3px;
+}
+
+.box
+{
+    width:800px;
+    margin:0 auto;
+}
+.active_tab1
+{
+    background-color:#fff;
+    color:#333;
+    font-weight: 600;
+}
+.inactive_tab1
+{
+    background-color: #f5f5f5;
+    color: #333;
+    cursor: not-allowed;
+}
+.has-error
+{
+    border-color:#cc0000;
+    background-color:#ffff99;
+}
+
+/* Styles go here */
+
+.table-content {
+    padding: 20px;
+}
+
+.form-control {
+    width: 90px;
+}
+
+/* Style buttons */
+.ajout-lig,.ajout-col,.ajout-graph,.ajout-formule,.save-formule,.ajout-champs, .del-formule {
+    background-color: DodgerBlue; /* Blue background */
+    border: none; /* Remove borders */
+    color: white; /* White text */
+    padding: 12px 16px; /* Some padding */
+    font-size: 16px; /* Set a font size */
+    cursor: pointer; /* Mouse pointer on hover */
+    border-radius: 5px;
+    margin-bottom: 1%;
+}
+
+/* Darker background on mouse-over */
+.ajout-lig:hover,.ajout-col:hover,.ajout-graph,.ajout-formule,.save-formule,.ajout-champs, .del-formule {
+    background-color: RoyalBlue;
+}
+
+.graph, .formule {
+    display: block;
+    margin : 0.75%;
+    width: 50%;
+    height: 34px;
+    padding: 6px 12px;
+    font-size: 14px;
+    line-height: 1.42857143;
+    color: #555;
+    background-color: #fff;
+    background-image: none;
+    border: 1px solid #ddd;
+    border-radius: 4px;
+    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
+    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
+    -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
+    -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
+    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
+}
+
+.add, .add-formule {
+    background-color: #fff;
+    background-image: none;
+    border: 1px solid transparent;
+    border-radius: 4px;
+}
+
+.div-graph, .div-formule {
+    padding: 15px;
+    background-color: #fff;
+    background-image: none;
+    border: 1px solid #ddd;
+    border-radius: 4px;
+}
+
+.grad, .axe-x, .axe-y {
+    width: 19.7%;
+    display : initial;
+}
+
+.grad {
+    width: 15%;
+    margin-bottom: 5%;
+}
+
+.collapsible {
+    width: 100%;
+    background-color: #eee;
+}
+
+.content {
+    padding: 0 18px;
+    max-height: 0;
+    overflow: hidden;
+    transition: max-height 0.2s ease-out;
+    background-color: #f1f1f1;
+}
+
+.collapsible:after {
+    content: '\02795'; /* Unicode character for ""plus"" sign (+) */
+    font-size: 13px;
+    color: white;
+    float: right;
+    margin-left: 5px;
+}
+
+.collapsible.active:after {
+    content: ""\2796""; /* Unicode character for ""minus"" sign (-) */
+}
+
+#previous_btn_personal_details, #btn_personal_details, .ajout-champs, .save-formule, .del-formule{
+    margin-top : 2.5%;
+}
+
+.save-formule, .del-formule{
+    margin-left:1%;
+    float:right;
+}
+
+.operateur {
+    font-family: FontAwesome, sans-serif;
+    -moz-appearance: none;
+    -webkit-appearance: none;
+}
+
+.operateur::-ms-expand{
+    display:none;
+}
+
+.add-formule, .div-formule{
+    background-color: #f1f1f1;
+}
+
+.div-formule{
+    margin-bottom: 2%;
+}
+
<html>
+<head>
+    <title>Innovatech</title>
+    <meta charset=""utf-8"" />
+    <link rel=""stylesheet"" href=""css/custom.css"" />
+    <script src=""https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js""></script>
+    <script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js""></script>
+    <link href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"" rel=""stylesheet"" />
+    <script src=""https://kit.fontawesome.com/38b99a3f0e.js"" crossorigin=""anonymous""></script>
+</head>
+
+<body>
+<!-- Titre + Menu -->
+<div class=""header"">
+    <a href=""index.php"" class=""logo"">Innovatech</a>
+    <div class=""header-right"">
+        <a href=""index.php"">Accueil</a>
+        <a class=""active"" href=""ajout.php"">Création</a>
+        <a href=""modif.php"">Nouveau</a>
+        <a href=""help.php"">Mode d'emploi</a>
+    </div>
+</div>
+
+<!-- Contenu du site web -->
+<div class=""contenu"">
+    <br />
+    <div class=""container box"">
+        <br />
+        <h2 align=""center"">Création d'un nouvel audit</h2><br />
+        <?php echo $message; ?>
+        <form method=""post"" id=""register_form"">
+            <ul class=""nav nav-tabs"">
+                <li class=""nav-item"">
+                    <a class=""nav-link active_tab1"" style=""border:1px solid #ccc"" id=""list_login_details"">Informations à propos de l'entreprise</a>
+                </li>
+                <li class=""nav-item"">
+                    <a class=""nav-link inactive_tab1"" id=""list_personal_details"" style=""border:1px solid #ccc"">Grille d'audit</a>
+                </li>
+                <li class=""nav-item"">
+                    <a class=""nav-link inactive_tab1"" id=""list_contact_details"" style=""border:1px solid #ccc"">Génération des graphiques</a>
+                </li>
+            </ul>
+            <div class=""tab-content"" style=""margin-top:16px;"">
+                <div class=""tab-pane active"" id=""personal_details"">
+                    <div class=""panel panel-default"">
+                        <div class=""panel-heading"">Grille d'audit</div>
+                        <div class=""panel-body"">
+                            <div class=""table-content"">
+
+                                <button class=""ajout-col"" type=""button"" id=""ajout-col""><i class=""fas fa-columns""> Ajouter une colonne</i></button>
+                                <br />
+                                <div class=""table-responsive"">
+                                    <table class=""table"" id=""grille"">
+                                        <thead>
+                                        <tr>
+                                            <th></th>
+                                            <th>
+                                                <button class=""btn remove-col"" type=""button""><i class=""fas fa-trash""></i></button>
+                                                <button class=""btn text-col"" type=""button""><i class=""fas fa-sort-alpha-down""></i></button>
+                                                <button class=""btn nbr-col"" type=""button""><i class=""fas fa-sort-numeric-down""></i></button>
+                                                <button class=""btn list-col"" type=""button""><i class=""far fa-list-alt""></i></button>
+                                                <input type=""text"" class=""form-control pull-left"">
+                                            </th>
+                                        </tr>
+                                        </thead>
+                                        <tbody>
+                                        <tr>
+                                            <td>
+                                                <button class=""btn remove-row"" type=""button""><i class=""fas fa-trash""></i></button>
+                                            </td>
+                                            <td>
+                                                <input type=""text"" class=""form-control"">
+                                            </td>
+                                        </tr>
+                                        </tbody>
+                                    </table>
+                                </div>
+                                <button class=""ajout-lig"" type=""button""><i class=""fas fa-list-ul""> Ajouter une ligne</i></button>
+                            </div>
+                            <div class=""form-group"" align=""center"">
+                                <span id=""error_grille"" class=""text-danger""></span>
+                                <span id=""error_nom_grille"" class=""text-danger""></span>
+                            </div>
+                            <button type=""button"" class=""collapsible"">Gérer les formules</button>
+                            <div class=""form-group content"">
+                                <br />
+                                <button type=""button"" class=""ajout-formule""><i class=""fas fa-plus-circle""> Ajouter une formule</i></button>
+                                <div class=""panel-body add-formule"">
+                                </div>
+                            </div>
+                            <br />
+                            <div align=""center"">
+                                <button type=""button"" name=""previous_btn_personal_details"" id=""previous_btn_personal_details"" class=""btn btn-default btn-lg"">Précédent</button>
+                                <button type=""button"" name=""btn_personal_details"" id=""btn_personal_details"" class=""btn btn-info btn-lg"">Suivant</button>
+                            </div>
+                            <br />
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </form>
+    </div>
+</div>
+
+<!-- Le pied de page -->
+<footer>
+    <p>
+        Innovatech <?php echo date(""Y"");?> - All rights reserved
+    </p>
+</footer>
+
+<script src=""jss/ajout.js""></script>
+<script src=""jss/gengrille.js""></script>
+<script src=""jss/gengraph.js""></script>
+<script src=""jss/genformule.js""></script>
+</body>
+</html>
+
+
+

","

Solution found :

+ +
// del field
+$('body').on('click', '.spr-champs', function(event) {
+    var th_spr = $(this).parent();
+    var num_th = th_spr.parent().children(1).index($(this).parent());
+
+    if (num_th == 2)
+    {
+        if (th_spr.next('th'))
+        {
+            th_spr.next('th').remove();
+        }
+        th_spr.remove();
+    }
+    else
+    {
+        th_spr.prev('th').remove();
+        th_spr.remove();
+    }
+});
+
+ +

1) Found which th it is var num_th = th_spr.parent().children(1).index($(this).parent());

+ +

2) Do a simple if -> if it's the first button : delete the field and the operator next to it, else : delete the field and the operator before it

",html +"How to append table row to one table to another table using checkbox checked in javascript

I have two tables, 1st table having check-boxes, if I click that checkbox that row only append to 2nd table including values, if I uncheck that checkbox that row going to delete 2nd table..

+ +

here, my problem is 1st row is a static row its work for only static rows, I don't want to work with static row, I want to work for only dynamic rows.

+ +

Example: if I clicked checkbox that checked row only (closest) want to append second table.

+ +

I write some code to append rows to another table.

+ +

Here is my code.

+ +

Full code is here..

+ +

Sample here..

+ +

+
+
// Create New table
+
+var counter = -1;
+window.updateIds = function() {
+  $.each($(""[row-number]""), function(index, item) {
+    $(this).attr(""row-number"", (index - 1));
+    $(""[id^=itemNo]"", $(this)).attr(""id"", ""itemNo"" + (index - 1));
+  });
+}
+window.createTable = function() {
+
+  counter++;
+
+  var itemNo = document.getElementById(""serialNo"").value;
+  var itemName = $(""#it_name1 option:selected"").text();
+  // var itemCode = document.getElementById(""it_code1"").value;
+  var itemCode = $(""#it_code1 option:selected"").text();
+  var description = document.getElementById(""it_desc1"").value;
+  var itemUom = document.getElementById(""uomTable1"").value;
+  var qty = document.getElementById(""qty1"").value;
+  // var reqNo = document.getElementById(""reqNo1"").value;
+  var reqNo = $(""#reqNo1 option:selected"").text();
+
+  $('#totalRowCount').text(counter - 0);
+  var htmlText = '';
+  htmlText += '<tr class=""first"" row-number=""' + counter + '"">';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 80px;"">';
+  htmlText += '<input type=""checkbox"" class=""led-btn checkNew"" name=""selpoNO[' + counter + '].valu"" id=""selpoNO' + counter + '"" style=""width: 13px;"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 80px;"">';
+  htmlText += '<input type=""text"" id=""itemNo' + counter + '"" class=""form-control"" name=""serialNo[' + counter + '].valu"" value=""' + itemNo + '"" readonly>';
+  htmlText += '</td>';
+
+  htmlText += '<td>';
+  htmlText += '<select class=""form-control"" id=""itemName' + counter + '"">';
+  htmlText += '<option>' + itemName + '</option>';
+  htmlText += '</select>';
+  htmlText += '</td>';
+
+  htmlText += '<td>';
+  htmlText += '<select class=""form-control"" id=""itemCode' + counter + '"">';
+  htmlText += '<option>' + itemCode + '</option>';
+  htmlText += '</select>';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"">';
+  htmlText += '<input type=""text"" id=""itemDescript' + counter + '"" placeholder=""Description"" class=""form-control"" placeholde=""Description"" name="""" value=""' + description + '"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px;"">';
+  htmlText += '<input type=""text"" id=""itemUom' + counter + '"" class=""form-control"" placeholder=""Enter Uom in kg"" name="""" value=""' + itemUom + '"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px;"">';
+  htmlText += '<input type=""text"" id=""qty' + counter + '"" class=""form-control"" name="""" placeholder=""Quantity"" value=""' + qty + '"">';
+  htmlText += '</td>';
+
+  // htmlText += '<td class=""itemNumber"">';
+  // htmlText += '<input type=""text"" id=""itemAval' + counter + '"" class=""form-control"" name="""" value=""' + itemAval + '"">';
+  // htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px !important;"">';
+  htmlText += '<button type=""button"" class=""dlRow del""><i onclick=""deleteRows();"">Delete</button></i>';
+  htmlText += '</td>';
+  htmlText += '</tr>';
+  htmlText += '</tbody>';
+  htmlText += '</table>';
+
+  $('#tableBody').append(htmlText);
+  var sum = 0;
+  $('.tAmount').each(function() {
+    sum += parseFloat($(this).val());
+  });
+  $('#grandTotal').val(sum);
+  updateIds();
+  removeStaticVal();
+}
+
+// Delete rows
+window.deleteRows = fdeleteRows = function() {
+
+  $('.del').click(function() {
+    $(this).parent().parent().remove();
+    var sum = 0;
+    $('.tAmount').each(function() {
+      sum += parseFloat($(this).val());
+    });
+    $('#grandTotal').val(sum);
+    updateIds();
+  });
+}
+
+
+
+// table checkbox function
+
+$("":checkbox"").on(""click"", function() {
+  if ($(this).is("":checked"")) {
+    alert(""if"");
+    // $(this).closest(""td"").siblings(""td"").each(function() {
+    $(this).closest('tr').find(""td:eq(0) .checkNew"").each(function() {
+      // $(""#tab_logic2 tbody"").append($(this).text());
+      alert('executed');
+      var sno = $(this).closest('tr').find(""td:eq(1) input"").val();
+      var iName = $(this).closest('tr').find(""td:eq(2) input"").val();
+      var iCode = $(this).closest('tr').find(""td:eq(3) input"").val();
+      var iDect = $(this).closest('tr').find(""td:eq(4) input"").val();
+      var iUom = $(this).closest('tr').find(""td:eq(5) input"").val();
+      var iQty = $(this).closest('tr').find(""td:eq(6) input"").val();
+
+      $(""#tab_logic2 tbody"").append('<tr><td style=""min-width: 80px;""><input type=""text"" id=""sm_supp"" value=""' + sno + '"" class=""form-control newStyle1"" name=""sm_supp"" readonly></td><td style=""min-width: 140px;""><select class=""form-control"" id=""iReqNo"" name=""iReqNo""><option>Choose Requitition no</option></select></td><td style=""min-width: 140px;""><select class=""form-control"" id=""inames"" name=""inames"" value=""' + iName + '""><option>Choose Item name</option></select></td><td style=""min-width: 140px;""><select class=""form-control"" id=""icode"" name=""icode"" value=""' + iCode + '""><option>Choose Item code</option></select></td><td style=""min-width: 350px;""><input type=""text"" id="""" value=""' + iDect + '"" class=""form-control"" name=""sm_code"" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iUom + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iQty + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><button type=""button"" class=""dlRow del"">x</button></a></td></tr>');
+    });
+  } else {
+    alert('else section');
+    $(""#tab_logic2 tbody"").html("""");
+    // $("":checkbox:checked"").closest(""td"").siblings(""td"").each(function() {
+    $(this).closest('tr').find(""td:eq(0) .checkNew"").each(function() {
+      $(""#tab_logic2 tbody"").append('<tr><td style=""min-width: 80px;""><input type=""text"" id=""sm_supp"" value=""' + sno + '"" class=""form-control newStyle1"" name=""sm_supp"" readonly></td><td style=""min-width: 140px;""><select class=""form-control"" id=""iReqNo"" name=""iReqNo""><option>Choose Requitition no</option></select></td></td><td style=""min-width: 140px;""><select class=""form-control"" id=""inames"" name=""inames"" value=""' + iName + '""><option>Choose Item name</option></select></td><td style=""min-width: 140px;""><select class=""form-control"" id=""icode"" name=""icode"" value=""' + iCode + '""><option>Choose Item code</option></select></td><td style=""min-width: 350px;""><input type=""text"" id="""" value=""' + iDect + '"" class=""form-control"" name=""sm_code"" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iUom + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iQty + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><button type=""button"" class=""dlRow del"">x</button></a></td></tr>');
+    });
+  }
+});
+
<script src=""https://code.jquery.com/jquery-3.1.0.js""></script>
+<script src=""https://code.jquery.com/jquery.min.js""></script>
+<link href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"" rel=""stylesheet"" type=""text/css"" />
+<script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js""></script>
+
+<!-- Table -->
+
+<div class=""container"">
+  <div class=""row clearfix"">
+    <div class=""col-md-12 column"">
+      <div class=""table-wrapper"">
+        <div class=""table-scroll"">
+          <table class=""table table-bordered"" id=""tab_logic"">
+            <thead>
+              <tr style=""background-color: #680779; color: #fff;"">
+                <th style=""min-width: 80px;"">
+                  #
+                </th>
+                <th style=""min-width: 80px;"">
+                  S.no
+                </th>
+                <th class=""text-center"">
+                  Item Name
+                </th>
+                <th class=""text-center"">
+                  Item Code
+                </th>
+                <th style=""min-width: 350px;"">
+                  Description
+                </th>
+                <th style=""min-width: 140px;"">
+                  UOM
+                </th>
+                <th style=""min-width: 140px;"">
+                  Quantity
+                </th>
+                <th style=""min-width: 140px !important;"">
+                  Action
+                </th>
+              </tr>
+            </thead>
+            <tbody id=""tableBody"">
+              <tr class=""first"" row-number=""0"" style=""padding-bottom: 20%;"">
+                <td style=""min-width: 80px;"">
+                  <input type=""checkbox"" class=""led-btn checkNew"" name=""selpoNO"" id=""selpoNO"" value=""PO"" style=""width: 13px;"">
+                </td>
+                <td style=""min-width: 80px;"">
+                  <input type=""number"" value=""1"" id=""serialNo"" class=""form-control"" name=""serialNo"" placeholder=""S.No"" readonly/>
+                </td>
+                <td class=""common_td"">
+                  <select class=""form-control newRw3 clrRow sel_text"" id=""it_name1"" name=""it_name"">
+                    <option value="""">Choose an items</option>
+                    <option value=""1"">100</option>
+                    <option value=""2"">200</option>
+                    <option value=""3"">300</option>
+                    <option value=""4"">400</option>
+                    <option value=""5"">500</option>
+                  </select>
+                </td>
+                <td class=""common_td"">
+                  <select class=""form-control"" id=""it_code1"" name=""it_code1"">
+                    <option value="""">Choose item code</option>
+                    <option value=""1"">100</option>
+                    <option value=""2"">200</option>
+                    <option value=""3"">300</option>
+                    <option value=""4"">400</option>
+                    <option value=""5"">500</option>
+                  </select>
+                </td>
+                <td style=""min-width: 350px;"">
+                  <input type=""text"" id=""it_desc1"" class=""form-control"" name=""it_desc"" placeholder=""Item Description"" />
+                </td>
+                <td style=""min-width: 140px;"">
+                  <input type=""text"" id=""uomTable1"" class=""form-control newRw3 clrRow sel_text required"" name=""uomTable"" placeholder=""Enter Uom in kg"" />
+                </td>
+                <td style=""min-width: 140px;"">
+                  <input type=""text"" id=""qty1"" name=""qty"" class=""form-control"" placeholder=""Quantity"" />
+                </td>
+
+                <td style=""min-width: 140px !important;"">
+                  <input type=""button"" class=""dlRow"" id=""total1"" value=""Add"" onclick=""createTable();"">
+                </td>
+              </tr>
+            </tbody>
+          </table>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+<!-- Second table -->
+
+
+<div class=""container"">
+  <div class=""row clearfix"">
+    <div class=""col-md-12 column"">
+      <div class=""table-wrapper"">
+        <div class=""table-scroll"">
+          <table class=""table table-bordered"" id=""tab_logic2"">
+            <thead>
+              <tr style=""background-color: #680779; color: #fff;"">
+                <th style=""min-width: 80px;"">
+                  S.no
+                </th>
+                <th style=""min-width: 140px;"">
+                  Requistition No
+                </th>
+                <th style=""min-width: 140px;"">
+                  Item Name
+                </th>
+                <th style=""min-width: 140px;"">
+                  Item Code
+                </th>
+                <th style=""min-width: 350px;"">
+                  Description
+                </th>
+                <th style=""min-width: 140px;"">
+                  UOM
+                </th>
+                <th style=""min-width: 140px;"">
+                  Quantity
+                </th>
+                <th style=""min-width: 140px;"">
+                  Action
+                </th>
+              </tr>
+            </thead>
+            <tbody id=""myNewtbody"">
+            </tbody>
+          </table>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

","

You can use delegation approach to attach the event along with :gt()(greater than) selector.

+ +

Change:

+ +
$("":checkbox"").on(""click"", function() {
+
+ +

To:

+ +
//This will raise the event on all the checkboxes except the first one
+$(""table"").on(""click"", "":checkbox:gt(0)"", function() { 
+
+ +

+
+
// Create New table
+
+var counter = -1;
+window.updateIds = function() {
+  $.each($(""[row-number]""), function(index, item) {
+    $(this).attr(""row-number"", (index - 1));
+    $(""[id^=itemNo]"", $(this)).attr(""id"", ""itemNo"" + (index - 1));
+  });
+}
+window.createTable = function() {
+
+  counter++;
+
+  var itemNo = document.getElementById(""serialNo"").value;
+  var itemName = $(""#it_name1 option:selected"").text();
+  // var itemCode = document.getElementById(""it_code1"").value;
+  var itemCode = $(""#it_code1 option:selected"").text();
+  var description = document.getElementById(""it_desc1"").value;
+  var itemUom = document.getElementById(""uomTable1"").value;
+  var qty = document.getElementById(""qty1"").value;
+  // var reqNo = document.getElementById(""reqNo1"").value;
+  var reqNo = $(""#reqNo1 option:selected"").text();
+
+  $('#totalRowCount').text(counter - 0);
+  var htmlText = '';
+  htmlText += '<tr class=""first"" row-number=""' + counter + '"">';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 80px;"">';
+  htmlText += '<input type=""checkbox"" class=""led-btn checkNew"" name=""selpoNO[' + counter + '].valu"" id=""selpoNO' + counter + '"" style=""width: 13px;"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 80px;"">';
+  htmlText += '<input type=""text"" id=""itemNo' + counter + '"" class=""form-control"" name=""serialNo[' + counter + '].valu"" value=""' + itemNo + '"" readonly>';
+  htmlText += '</td>';
+
+  htmlText += '<td>';
+  htmlText += '<select class=""form-control"" id=""itemName' + counter + '"">';
+  htmlText += '<option>' + itemName + '</option>';
+  htmlText += '</select>';
+  htmlText += '</td>';
+
+  htmlText += '<td>';
+  htmlText += '<select class=""form-control"" id=""itemCode' + counter + '"">';
+  htmlText += '<option>' + itemCode + '</option>';
+  htmlText += '</select>';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"">';
+  htmlText += '<input type=""text"" id=""itemDescript' + counter + '"" placeholder=""Description"" class=""form-control"" placeholde=""Description"" name="""" value=""' + description + '"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px;"">';
+  htmlText += '<input type=""text"" id=""itemUom' + counter + '"" class=""form-control"" placeholder=""Enter Uom in kg"" name="""" value=""' + itemUom + '"">';
+  htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px;"">';
+  htmlText += '<input type=""text"" id=""qty' + counter + '"" class=""form-control"" name="""" placeholder=""Quantity"" value=""' + qty + '"">';
+  htmlText += '</td>';
+
+  // htmlText += '<td class=""itemNumber"">';
+  // htmlText += '<input type=""text"" id=""itemAval' + counter + '"" class=""form-control"" name="""" value=""' + itemAval + '"">';
+  // htmlText += '</td>';
+
+  htmlText += '<td class=""itemNumber"" style=""min-width: 140px !important;"">';
+  htmlText += '<button type=""button"" class=""dlRow del""><i onclick=""deleteRows();"">Delete</button></i>';
+  htmlText += '</td>';
+  htmlText += '</tr>';
+  htmlText += '</tbody>';
+  htmlText += '</table>';
+
+  $('#tableBody').append(htmlText);
+  var sum = 0;
+  $('.tAmount').each(function() {
+    sum += parseFloat($(this).val());
+  });
+  $('#grandTotal').val(sum);
+  updateIds();
+  removeStaticVal();
+}
+
+// Delete rows
+window.deleteRows = fdeleteRows = function() {
+
+  $('.del').click(function() {
+    $(this).parent().parent().remove();
+    var sum = 0;
+    $('.tAmount').each(function() {
+      sum += parseFloat($(this).val());
+    });
+    $('#grandTotal').val(sum);
+    updateIds();
+  });
+}
+
+
+
+// table checkbox function
+
+$(""table"").on(""click"", "":checkbox:gt(0)"", function() {
+  if ($(this).is("":checked"")) {
+    var id = $(this).attr('id'); //get the id of the current checkbox
+    $(this).closest('tr').find(""td:eq(0) .checkNew"").each(function() {
+      // $(""#tab_logic2 tbody"").append($(this).text());
+      //alert('executed');
+      var sno = $(this).closest('tr').find(""td:eq(1) input"").val();
+      var iName = $(this).closest('tr').find(""td:eq(2) input"").val();
+      var iCode = $(this).closest('tr').find(""td:eq(3) input"").val();
+      var iDect = $(this).closest('tr').find(""td:eq(4) input"").val();
+      var iUom = $(this).closest('tr').find(""td:eq(5) input"").val();
+      var iQty = $(this).closest('tr').find(""td:eq(6) input"").val();
+      
+      //set the custom attribute to the appending tr
+      $(""#tab_logic2 tbody"").append('<tr data='+ id +'><td style=""min-width: 80px;""><input type=""text"" id=""sm_supp"" value=""' + sno + '"" class=""form-control newStyle1"" name=""sm_supp"" readonly></td><td style=""min-width: 140px;""><select class=""form-control"" id=""iReqNo"" name=""iReqNo""><option>Choose Requitition no</option></select></td><td style=""min-width: 140px;""><select class=""form-control"" id=""inames"" name=""inames"" value=""' + iName + '""><option>Choose Item name</option></select></td><td style=""min-width: 140px;""><select class=""form-control"" id=""icode"" name=""icode"" value=""' + iCode + '""><option>Choose Item code</option></select></td><td style=""min-width: 350px;""><input type=""text"" id="""" value=""' + iDect + '"" class=""form-control"" name=""sm_code"" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iUom + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><input type=""text"" id="""" value=""' + iQty + '"" class=""form-control"" name="""" readonly></td><td style=""min-width: 140px;""><button type=""button"" class=""dlRow del"">x</button></a></td></tr>');
+    });
+  } else {
+    //alert('else section');
+    //remove by maching the custom attribute with the check box id
+    $(""#tab_logic2 tbody [data=""+$(this).attr('id')+""]"").remove(); 
+  }
+});
+
+function removeStaticVal(){
+}
+
<script src=""https://code.jquery.com/jquery-3.1.0.js""></script>
+<script src=""https://code.jquery.com/jquery.min.js""></script>
+<link href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"" rel=""stylesheet"" type=""text/css"" />
+<script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js""></script>
+
+<!-- Table -->
+
+<div class=""container"">
+  <div class=""row clearfix"">
+    <div class=""col-md-12 column"">
+      <div class=""table-wrapper"">
+        <div class=""table-scroll"">
+          <table class=""table table-bordered"" id=""tab_logic"">
+            <thead>
+              <tr style=""background-color: #680779; color: #fff;"">
+                <th style=""min-width: 80px;"">
+                  #
+                </th>
+                <th style=""min-width: 80px;"">
+                  S.no
+                </th>
+                <th class=""text-center"">
+                  Item Name
+                </th>
+                <th class=""text-center"">
+                  Item Code
+                </th>
+                <th style=""min-width: 350px;"">
+                  Description
+                </th>
+                <th style=""min-width: 140px;"">
+                  UOM
+                </th>
+                <th style=""min-width: 140px;"">
+                  Quantity
+                </th>
+                <th style=""min-width: 140px !important;"">
+                  Action
+                </th>
+              </tr>
+            </thead>
+            <tbody id=""tableBody"">
+              <tr class=""first"" row-number=""0"" style=""padding-bottom: 20%;"">
+                <td style=""min-width: 80px;"">
+                  <input type=""checkbox"" class=""led-btn checkNew"" name=""selpoNO"" id=""selpoNO"" value=""PO"" style=""width: 13px;"">
+                </td>
+                <td style=""min-width: 80px;"">
+                  <input type=""number"" value=""1"" id=""serialNo"" class=""form-control"" name=""serialNo"" placeholder=""S.No"" readonly/>
+                </td>
+                <td class=""common_td"">
+                  <select class=""form-control newRw3 clrRow sel_text"" id=""it_name1"" name=""it_name"">
+                    <option value="""">Choose an items</option>
+                    <option value=""1"">100</option>
+                    <option value=""2"">200</option>
+                    <option value=""3"">300</option>
+                    <option value=""4"">400</option>
+                    <option value=""5"">500</option>
+                  </select>
+                </td>
+                <td class=""common_td"">
+                  <select class=""form-control"" id=""it_code1"" name=""it_code1"">
+                    <option value="""">Choose item code</option>
+                    <option value=""1"">100</option>
+                    <option value=""2"">200</option>
+                    <option value=""3"">300</option>
+                    <option value=""4"">400</option>
+                    <option value=""5"">500</option>
+                  </select>
+                </td>
+                <td style=""min-width: 350px;"">
+                  <input type=""text"" id=""it_desc1"" class=""form-control"" name=""it_desc"" placeholder=""Item Description"" />
+                </td>
+                <td style=""min-width: 140px;"">
+                  <input type=""text"" id=""uomTable1"" class=""form-control newRw3 clrRow sel_text required"" name=""uomTable"" placeholder=""Enter Uom in kg"" />
+                </td>
+                <td style=""min-width: 140px;"">
+                  <input type=""text"" id=""qty1"" name=""qty"" class=""form-control"" placeholder=""Quantity"" />
+                </td>
+
+                <td style=""min-width: 140px !important;"">
+                  <input type=""button"" class=""dlRow"" id=""total1"" value=""Add"" onclick=""createTable();"">
+                </td>
+              </tr>
+            </tbody>
+          </table>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+<!-- Second table -->
+
+
+<div class=""container"">
+  <div class=""row clearfix"">
+    <div class=""col-md-12 column"">
+      <div class=""table-wrapper"">
+        <div class=""table-scroll"">
+          <table class=""table table-bordered"" id=""tab_logic2"">
+            <thead>
+              <tr style=""background-color: #680779; color: #fff;"">
+                <th style=""min-width: 80px;"">
+                  S.no
+                </th>
+                <th style=""min-width: 140px;"">
+                  Requistition No
+                </th>
+                <th style=""min-width: 140px;"">
+                  Item Name
+                </th>
+                <th style=""min-width: 140px;"">
+                  Item Code
+                </th>
+                <th style=""min-width: 350px;"">
+                  Description
+                </th>
+                <th style=""min-width: 140px;"">
+                  UOM
+                </th>
+                <th style=""min-width: 140px;"">
+                  Quantity
+                </th>
+                <th style=""min-width: 140px;"">
+                  Action
+                </th>
+              </tr>
+            </thead>
+            <tbody id=""myNewtbody"">
+            </tbody>
+          </table>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>
+
+
+

",html +"IText7 PDFHtml generator with header and footer for C#

I am trying to generating a PDF from predefined HTML content. I managed to generate the content, yet without the required HTML Header, HTML Footer, and Arabic language is not supported as well.

+ +

My requirements:

+ +
    +
  1. Arabic language support.
  2. +
  3. The ability to generate more than 10 pages.
  4. +
  5. The footer may differ from one page to another.

  6. +
  7. There is a web application that sends a request to a WCF service, and the service returns a byte array containing the PDF.

  8. +
+ +

So, I have been searching for a couple of days for a good tool and I found SelectPdf, it is perfect except that it is NOT free, so the only solution is IText7 PDFHtml. +The thing is this library has good documentation for JAVA, and I am really struggling in following the C# examples and converting from JAVA API to C# code. +Anyone has done something similar before with c#?

","

After a long process of searching and trying, I have got it working and achieved the following features:

+ +
    +
  1. Image in the header.

  2. +
  3. Base64 image in the footer, in addition to the ability to write some text in the other side in the footer.

  4. +
  5. Generating the same footer for all pages except for the last one.
  6. +
  7. the number of the generated pages was unlimited.
  8. +
  9. Page numbering.
  10. +
+ +

All the previous features were free of charge, however, supporting Arabic language needs a license, so I have to pay anyway :)

+ +

Kindly find below my C# code and post your improvements if you have any.

+ +
public class Pdfgenerator
+{
+    public const string FONT = ""Fonts/NotoNaskhArabic-Regular2.ttf"";
+    public static string HEADER_TEXT = ""<table width=\""100%\"" border=\""0\""><tr><td>Header</td><td align=\""right\"">Some title</td></tr></table>"";
+    public static string FOOTER_TEXT = ""<table width=\""100%\"" border=\""0\""><tr><td>Footer</td><td align=\""right\"">Some title</td></tr></table>"";
+    public MemoryStream createPdf()
+    {
+        string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
+        MemoryStream file = new MemoryStream();
+        PdfDocument pdfDocument = null;
+        PdfDocument pdfDoc = null;
+        PdfDocument pdfDocument1 = null;
+        try
+        {
+
+            using (file)
+            {
+                PdfFont f = PdfFontFactory.CreateFont(apPath + FONT, PdfEncodings.IDENTITY_H);
+                string header = ""pdfHtml Header and footer example using page-events"";
+                Header headerHandler = new Header(header);
+                Footer footerHandler = new Footer();
+                ConverterProperties converterProperties = new ConverterProperties();
+                PdfWriter writer1 = new PdfWriter(apPath + ""test1.pdf"");
+                pdfDocument1 = new PdfDocument(writer1);
+                pdfDocument1.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
+                pdfDocument1.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);
+                converterProperties = new ConverterProperties().SetBaseUri(apPath);
+
+                HtmlConverter.ConvertToDocument(File.ReadAllText(apPath + ""content.html""), pdfDocument1, converterProperties);
+                footerHandler.lastPage = pdfDocument1.GetLastPage();
+
+                pdfDocument1.Close();
+            }
+        }
+        catch (Exception ex)
+        {
+
+        }
+        finally
+        {
+            file.Dispose();
+        }
+
+        return new MemoryStream();
+    }
+}
+
+ +

Generating the header:

+ +
class Header : IEventHandler
+{
+    private string header;
+    private Image image;
+    public Header(string header)
+    {
+        string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
+        this.header = header;
+        image = new Image(ImageDataFactory.Create(apPath + ""Images/RANDOM_PHOTO.jpg""));
+
+    }
+
+    public void HandleEvent(Event @event)
+    {
+        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
+        PdfDocument pdf = docEvent.GetDocument();
+        PdfPage page = docEvent.GetPage();
+        Rectangle pageSize = page.GetPageSize();
+
+        Canvas canvas = new Canvas(new PdfCanvas(page), pdf, pageSize);
+        canvas.SetFontSize(18);
+
+
+        // Write text at position
+        canvas.Add(image);
+        canvas.Close();
+    }
+}
+
+ +

Generating the footer:

+ +
class Footer : IEventHandler
+{
+    public PdfPage lastPage = null;
+    protected PdfFormXObject placeholder;
+    protected float side = 20;
+    protected float x = 300;
+    protected float y = 25;
+    protected float space = 4.5f;
+    protected float descent = 3;
+
+    public Footer()
+    {
+        placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
+    }
+
+    public void HandleEvent(Event @event)
+    {
+        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
+        PdfDocument pdf = docEvent.GetDocument();
+        PdfPage page = docEvent.GetPage();
+        int pageNumber = pdf.GetPageNumber(page);
+        Rectangle pageSize = page.GetPageSize();
+        // Creates drawing canvas
+        PdfCanvas pdfCanvas = new PdfCanvas(page);
+        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
+
+        IList<iText.Layout.Element.IElement> elements = HtmlConverter.ConvertToElements(""<table border=\""0\""><tr><td><img src=\""data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==\"" alt=\""Italian Trulli\""></td></tr></table>"");
+        Paragraph p = new Paragraph();
+
+        foreach (iText.Layout.Element.IElement e in elements)
+        {
+            if (e is IBlockElement) {
+                p.Add((IBlockElement)e);
+            }
+        }
+        if (lastPage == docEvent.GetPage()) {
+
+        }
+        else
+        {
+            canvas.ShowTextAligned(p, 25, 75, TextAlignment.LEFT);
+        }
+
+        canvas.Close();
+
+        // Create placeholder object to write number of pages
+        pdfCanvas.AddXObject(placeholder, x + space, y - descent);
+        pdfCanvas.Release();
+    }
+
+    public void writeTotal(PdfDocument pdf)
+    {
+        Canvas canvas = new Canvas(placeholder, pdf);
+        canvas.ShowTextAligned(pdf.GetNumberOfPages().ToString(),
+                0, descent, TextAlignment.LEFT);
+        canvas.Close();
+    }
+}
+
+ +

I was trying to get a stream as an output, so if you want that as well you can use the following in your main service:

+ +
public byte[] GetData()
+    {
+        MemoryStream stream = new Pdfgenerator().createPdf();
+        byte[] arr = stream.ToArray();
+        return stream.ToArray();
+    }
+
",html +"CSS focus-within to show label

Taking an example from the end of https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_build_custom_form_controls:

+ +

+
+
.select label {
+  display: none;
+}
+
+.select:focus-within label {
+  display: initial;
+}
+
+input:checked + label {
+  display: initial;
+}
+
 <fieldset class=""select"">
+  <legend>Pick a fruit</legend>
+      <input type=""radio"" name=""fruit"" value=""Cherry"" id=""fruitCherry"" checked>
+   <label for=""fruitCherry"">Cherry</label>
+      <input type=""radio"" name=""fruit"" value=""Lemon"" id=""fruitLemon"">
+   <label for=""fruitLemon"">Lemon</label>
+      <input type=""radio"" name=""fruit"" value=""Banana"" id=""fruitBanana"">
+   <label for=""fruitBanana"">Banana</label>
+  </fieldset>
+
+
+

+ +

(I have simplified the example to better illustrate the point). Note how you can click on one of the labels, and since focus is inside the select after that, all labels become visible. However, as soon as you try to click on label of another item, the labels disappear before selecting that item, since there is a brief period before the mouse button is released where no element is focused. I assume the the browser only handles the click event when the mouse button is released.

+ +

Is there any way to keep the focus while holding down the mouse button as well, without JavaScript? I experienced this on Firefox and Chrome on Linux.

+ +

I am also surprised by the fact that it acts differently depending on whether you click-and-hold on the label or the radio button.

","
+

By default <label> is not a focusable Element.

+
+ +

When you try to click a label it's as if you're clicking away to remove the focus from what you previously clicked.

+ +

In order to make an element focusable we use the tabindex attribute with a negative value so it doesn't interfere with the navigation because our sole purpose is to make the element focusable

+ +

+
+
.select label {
+  display: none;
+}
+
+.select:focus-within label {
+  display: initial;
+}
+
+input:checked+label {
+  display: initial;
+}
+
<fieldset class=""select"">
+  <legend>Pick a fruit</legend>
+  <input type=""radio"" name=""fruit"" value=""Cherry"" id=""fruitCherry"" checked>
+  <label tabindex=""-1"" for=""fruitCherry"">Cherry</label>
+  <input type=""radio"" name=""fruit"" value=""Lemon"" id=""fruitLemon"">
+  <label tabindex=""-1"" for=""fruitLemon"">Lemon</label>
+  <input type=""radio"" name=""fruit"" value=""Banana"" id=""fruitBanana"">
+  <label tabindex=""-1"" for=""fruitBanana"">Banana</label>
+</fieldset>
+
+
+

",html +"Cannot change the HTML table's column sizes despite of giving width

I have a table which is set to ?

+ +

I need to change the size of the columns. These are the column names and I have set width to 30 and 70. but it doesn't change. It is now displaying as 50:50.

+ +

+
+
table {
+  width: 100%;
+}
+
+table,
+th,
+td {
+  border: 1px solid black;
+  border-collapse: collapse;
+}
+
+th,
+td {
+  padding: 10px;
+  text-align: left;
+  align-content: center;
+  width: 25px;
+}
+
+th {
+  background-color: #eeeeee;
+}
+
+td {
+  max-width: 100px;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  height: 38px;
+  align-content: center;
+}
+
<table height=""100"">
+  <tr>
+    <th width=""30"">Control Name</th>
+    <th width=""70"">Image</th>
+  </tr>
+</table>
+
+
+

","

You can make classes and set them on your cells. You can probably name them better then I did in my example, but that is just a hint on how you can do it.

+ +

+
+
table {
+  width: 100%;
+}
+
+table,
+th,
+td {
+  border: 1px solid black;
+  border-collapse: collapse;
+}
+
+th,
+td {
+  padding: 10px;
+  text-align: left;
+  align-content: center;
+  width: 25px;
+}
+
+th {
+  background-color: #eeeeee;
+}
+
+td {
+  max-width: 100px;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  height: 38px;
+  align-content: center;
+}
+
+.cell-width-30 {
+  width: 30%;
+}
+
+.cell-width-70 {
+  width: 70%;
+}
+
<table height=""100"">
+  <tr>
+    <th class=""cell-width-30"">Control Name</th>
+    <th class=""cell-width-70"">Image</th>
+  </tr>
+</table>
+
+
+

",html +"Google Extension Window

I Made A Google Extension That Displays The Date And Every Thing Went Fine But..

+

+

I Want To Put This Wed Dec 2020 in One Line Not Two.

+

And I Want To Know How To Change The Extension Window Size

","

Not really sure about chrome ext. development, but it seems it works on html css, then you can wrap date in a p tag and give it white-space: nowrap;

+

To increase size of the window, you can use height, width on body and html tag, but it has limits.

+
+

Chrome extension popups can have a maximum height of 600px and maximum +width of 800px.

+
+

Source: How Can I Expand The Popup Window of My Chrome Extension +

+

+
+
date.innerHTML = new Date();
+
p{
+  white-space:nowrap;
+  width:100px;
+  background:#ddd;
+}
+
<p id=""date""></p>
+
+
+

",html +"Why does the Awesomplete JavaScript object fail to be created when new'ed?

I found the Awesomplete JavaScript/jQuery plug-In here. It's a combobox/drop-down list widget that displays a list of case-less matches while the user types characters into a input text element. The provided link shows the section of the widget's web-page that shows how multiple entries can be entered into the input element, which is exactly what I need. A live-demo in this section shows that the widget works.

+

Unfortunately, the examples shown at the Awesomplete web-page don't provide a complete example of how to properly use the widget, so I cobbled the following together in order to begin integrating it into my own web-page, but my attempt gets an error when the script tries to create the Awesomplete object, saying:

+
awesomplete.html: 61 Uncaught ReferenceError: Awesomplete is not defined
+at awesomplete.html: 61
+(anonymous) @ awesomplete.html: 61
+
+

Here is my code:

+
<!DOCTYPE html>
+<html lang="en" >
+  <head>
+    <meta charset="UTF-8">
+    <title>Awesomplete: Multiple values</title>
+    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
+    <script src="awesomplete.js" async></script>
+    <link rel="stylesheet" href="awesomplete.css" />
+    <style>
+      .visually-hidden { display: none; }
+    </style>
+  </head>
+  <body translate="no" >
+    <h2>Awesomplete: Multiple values</h2>
+    <label for="browserInput">browser List:&nbsp;</label>
+    <input type="text" id="browserInput"
+           style="width: 245px;"
+           maxlength="100"
+           autocomplete="off"
+           autofocus
+           required
+           placeholder="Enter browser name(s)."
+           title="Enter the name of one or more browsers
+or press space to see all choices."
+           multiple
+           data-multiple
+           data-list="#browsersList"
+           data-minchars="1"
+           data-maxitems="100"
+           data-autofirst
+           aria-expanded="false"
+           aria-owns="awesomplete_list_2"
+           role="combobox" />
+    <ul id="browsersList" hidden>
+      <li>Zebra</li>
+      <li>Safari</li>
+      <li>Opera</li>
+      <li>Microsoft Internet Explorer</li>
+      <li>Microsoft Edge</li>
+      <li>Google Chrome</li>
+      <li>Firefox</li>
+    </ul>
+    <ul id="awesomplete_list_2" hidden
+        role="listbox"
+        aria-label="Results List">
+    </ul>
+    <span class="visually-hidden"
+          role="status"
+          aria-live="assertive"
+          aria-atomic="true">
+      Type one or more characters for results.
+    </span>
+    <script>
+      // Show label and insert label into the input:
+
+      // ***** The error occurs when the next line executes ***** //
+
+      new Awesomplete( 'input[data-multiple]',
+                       {
+                         filter:  function( text, input ) {
+                                    return Awesomplete.FILTER_CONTAINS(
+                                             text, input.match( /[^,]*$/ )[ 0 ] );
+                                  },
+
+                         item:    function( text, input ) {
+                                    return Awesomplete.ITEM(
+                                             text, input.match( /[^,]*$/ )[ 0 ] );
+                                  },
+
+                         replace: function( suggestion ) {
+                                    var before = this.input.value
+                                                 .match( /^.+,\s*|/ )[ 0 ];
+
+                                    this.input.value = before + suggestion.label + ", ";
+                                  }
+                       } );
+    </script>
+  </body>
+</html>
+
+

I downloaded the files needed for the <script src="awesomplete.js" async></script> and <link rel="stylesheet" href="awesomplete.css" /> lines to my computer before trying to run my web-page. You may do the same using this link to show the top section of the Awesomplete web-page and then clicking on the Download button.

+

In my initial test web-page using this widget, I used class="awesomplete" setting in the input element as suggested near the top of the Awesomplete web-page, and it worked, but it only let me enter one value. However, I need to enter multiple matches, but simply adding the multiple and data-multiple attributes to the input element isn't enough to make it work. I then added the script that crates the Awesomplete object and took the class out of the input element, but that's when I started getting the error I showed, above. +Incidentally, having the class in the element didn't work.

+

After the above works, I'm wondering if the Awesomplete settings in the input element will be used when the Awesomplete object is created in the script or do I need to take then out of the input element and instead explicitly put them in the Awesomplete new call.

+

Thanks

","

While putting the above web-page content into codepen.io I found that the javascript file can be found using the codepen's setting js search tool, but the corresponding css file can't when using the css search tool. However, using the URL for the js file, I was able to find the css file. When both of these URLs are added to codepen, my test version worked and did allow multiple choices to be selected in the input element. Finally, was able to copy the script and link statements into my local version of the test web-page, and it also worked. Note, the script statement uses the min.js version, not the full version. I don't know if this is a factor, but for my production site, I want the min.js version anyway.

+

Here are to two lines needed to make the code I posted here work:

+
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.5/awesomplete.min.js"></script>
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.5/awesomplete.css">
+
+

Hope this helps others, too.

",html +"jQuery validation not working separately on each class. It is working on all element at the same time

I have this code which was working on a single class perfectly. I changed this to each class because I added multiple-element with the same class and want to set the same validation error on both fields.

+

html

+
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
+    <label>Serial number start with 1 or 2</label>
+    <span>
+        <input type="text" name="serienummer" value="" maxlength="12" minlength="12" class="serialnumber"
+            placeholder="00-000000-00">
+    </span>
+    <span class="errmsgserienum"></span>
+</div>
+<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
+    <label>Serial number start with 1 or 2</label>
+    <span>
+        <input type="text" name="serienummer1" value="" maxlength="12" minlength="12" class="serialnumber"
+            placeholder="00-000000-00">
+    </span>
+    <span class="errmsgserienum"></span>
+</div>
+
+

JS

+
jQuery(function ($) {
+    $('.serialnumber').keyup(function (ev) {
+        $('.serialnumber').each(function (ev) {
+            var x = $(this).val();
+            // Allow Backspace and Delete
+            if (ev.keyCode == 8 || ev.keyCode == 46) {
+                return true;
+            }
+            if (!x.match(/^1|2+/)) {
+                $(".errmsgserienum").html("Serial number should start with 1 or 2");
+                $(this).val(x.substr(0, -1));
+            } else if (x.match(/^1|2+/) && x.length == 12) {
+                $(".errmsgserienum").html("");
+            }
+        });
+    });
+});
+
+

After adding each class it is working on all elements at the same time. How can this be work on each class element separately?

","

You don't need to use each loop here . Simply , use $(this).closest(".outer").find(".errmsgserienum").. to add error message next to input box where user has typed.

+

Demo Code :

+

+
+
jQuery(function($) {
+  $('.serialnumber').keyup(function(ev) {
+    var x = $(this).val();
+    // Allow Backspace and Delete
+    if (ev.keyCode == 8 || ev.keyCode == 46) {
+      return true;
+    }
+    if (!x.match(/^1|2+/)) {
+ //get closest outer div and then find span tag to show error 
+ $(this).closest("".outer"").find("".errmsgserienum"").html(""Serial number should start with 1 or 2"");
+      $(this).val(x.substr(0, -1));
+    } else if (x.match(/^1|2+/) && x.length == 12) {
+      $(this).closest("".outer"").find("".errmsgserienum"").html("""");
+    }
+  });
+
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<!--aded outer class-->
+<div class=""col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 outer"">
+  <label>Serial number start with 1 or 2</label>
+  <span>
+  <input type=""text"" name=""serienummer"" value="""" maxlength=""12"" minlength=""12"" class=""serialnumber"" placeholder=""00-000000-00"">
+  </span>
+  <span class=""errmsgserienum""></span>
+</div>
+<div class=""col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 outer"">
+  <label>Serial number start with 1 or 2</label>
+  <span>
+  <input type=""text"" name=""serienummer1"" value="""" maxlength=""12"" minlength=""12"" class=""serialnumber"" placeholder=""00-000000-00"">
+  </span>
+  <span class=""errmsgserienum""></span>
+</div>
+
+
+

",html +"How do i get img-fluid to work in Bootstrap Carousel?

I've been trying to make my images within my carousel responsive by adding the img-fluid tag to them but nothing is working. I've tried using !important. I've tried using block. I am not sure what is preventing the change. Any suggestions?

+
.container{
+        
+        font-size: 32px;
+        font-family: 'Inter', sans-serif;
+        position:relative;
+        top: 150px;
+        right:-15px;
+        font-weight: 300;
+        width: 1440px;
+        letter-spacing: 2px;
+        
+      
+  }
+  
+ 
+  
+  .item{
+      
+      
+        float:right;
+      
+     
+      
+  }
+  
+
+
+<div class="container">
+ 
+
+ + + + + + + +
<div class="carousel-inner">
+  <div class="item active">
+    <img class="image img-fluid" src="images/image-tanya.jpg" alt="Tanya" style="height:648px; width:648px;" ><div class="carousel-caption">  
+  </div>
+    </div>      
+
+  <div class="item ">
+    <img class="image img-fluid" src="images/image-john.jpg" alt="John" style="height:648px; width:648px;">
+  </div>
+
","

style="height:648px; width:648px;" is the culprit

+

The styles defined by the img-fluid class are being overwritten by the inline styles on the img tags in the the HTML. Inline styles always take precedence over those defined in style sheets. Try removing those inline styles and see what happens :)

",html +"Iframe doesn't work in kolkov angular editor

Kolkov angular editor doesn't support Iframe.

+

Package: https://www.npmjs.com/package/@kolkov/angular-editor

+

In the editor, it looks like it's working but the front panel is not showing anything +

+

Expected result is : +

","

For this you need to make changes in angular editor config : +You need to set sanitize: false.

+
config: AngularEditorConfig = {
+    sanitize: false,
+  .........................
+  };
+
+

Due to senetize:false chrome gives you an error in the front end like this :

+
+

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

+
+

You can fix this error by creating custom pipe for sanitizing HTML :

+

sanitize-html.pipe.ts

+
import { Pipe, PipeTransform } from '@angular/core';
+import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
+
+@Pipe({
+  name: 'sanitizeHtml'
+})
+export class SanitizeHtmlPipe implements PipeTransform {
+
+  constructor(private _sanitizer: DomSanitizer) {
+  }
+
+  transform(v: string): SafeHtml {
+    return this._sanitizer.bypassSecurityTrustHtml(v);
+  }
+}
+
+

In HTML

+
<p *ngIf="appMessageData" [innerHTML]="appMessage | sanitizeHtml"></p>
+
+

This will help you :)

",html +"Add multiple table rows when button clicked

I am trying to load html file containing same table elements like my default table when I click on add more button. +When I click Add more button it loads the file one time but don't work when I click the button second time. +Here is my table section of default page :

+
<div class="form_container">
+    <form method="POST" action="actionPage.php">
+        <div class="table_container">
+            <table border="2">
+                <tr>
+                    <tr>
+                        <td><label>Sr.No :</label></td>
+                        <td><input type = "number" class="SrNo" name="SrNo" value="1" readonly></td>
+                        <td><label>Design number :</label></td>
+                        <td><input type="text" class="designNo" name="designNumber"></td>
+                    </tr>
+                    <tr>                
+                        <td><label>Fabric quality :</label></td>
+                        <td><select name="fabricSelect">
+                            <option value="Fabric1" name="fabric1">Fabric1</option>
+                            <option value="Fabric2" name="fabric2">Fabric2</option>
+                            <option value="Fabric3" name="fabric3">Fabric3</option>
+                            <option value="Fabric4" name="fabric4">Fabric4</option>
+                            </select>           
+                        <td><label>Color matching :</label></td>
+                        <td><input type="select" class="colorMatch" name="colorMatch"></td>
+                    </tr>
+                    <tr>
+                        <td><label>Quantity :</label></td>
+                        <td><input type="number" class="quantity" name="quantity"></td>
+                        <td><label>Printing type :</label></td>
+                        <td><select name="printSelect">
+                            <option value="Print1">Print1</option>
+                            <option value="Print2">Print2</option>
+                            <option value="Print3">Print3</option>
+                            <option value="Print4">Print4</option>
+                            </select>
+                        </td>           
+                    </tr>
+                    <tr>
+                        <td ><label>Rate :</label></td>
+                        <td colspan="2"><input type="number" name="rate"></td>
+                    </tr>
+                    <tr class="newForm">
+                    </tr>
+                </tr>
+            </table>
+            <input type="submit" id="submit_btn" class="class_btn">
+        </div>
+    </form>
+    <button class="addButton">Add more tab</button>
+</div>
+
+

This is my script :

+
<script>
+    $(document).ready(function() {
+        var flag = 0;
+        $(".addButton").click(function(e) {
+            if(flag != 5) {
+                flag += 1;
+                $(".newForm").load("addedForm.php");
+            }
+            else {
+                e.preventDefault();
+            }
+        });
+    })
+</script>
+
+

And here is my other file that I want to load :

+
<tr>
+<td><label>Sr.No :</label></td>
+<td><input type = "number" class="SrNo" value="" readonly></td>
+
+<td><label>Design Number:</label></td>
+<td><input type="text" class="designNo"></td>
+
","

Is there any reason to load the file instead of cloning the element you need, especially since it already appears in your DOM? This is, in my opinion, cleaner and easier to manage.

+

I think this code below should do the same thing without having to load another file (which I had Cross origin issues with)

+

EDIT +Now clones entire table instead of just one row. Be careful with the names of inputs, since they are cloned too.

+
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
+
+<div class="form_container">
+    <form method="POST" action="actionPage.php">
+        <div class="table_container">
+            <table id="clone" border="2">
+                <tr>
+                    <tr >
+                        <td><label>Sr.No :</label></td>
+                        <td><input type = "number" class="SrNo" name="SrNo" value="1" readonly></td>
+                        <td><label>Design number :</label></td>
+                        <td><input type="text" class="designNo" name="designNumber"></td>
+                    </tr>
+                    <tr>                
+                        <td><label>Fabric quality :</label></td>
+                        <td><select name="fabricSelect">
+                            <option value="Fabric1" name="fabric1">Fabric1</option>
+                            <option value="Fabric2" name="fabric2">Fabric2</option>
+                            <option value="Fabric3" name="fabric3">Fabric3</option>
+                            <option value="Fabric4" name="fabric4">Fabric4</option>
+                            </select>           
+                        <td><label>Color matching :</label></td>
+                        <td><input type="select" class="colorMatch" name="colorMatch"></td>
+                    </tr>
+                    <tr>
+                        <td><label>Quantity :</label></td>
+                        <td><input type="number" class="quantity" name="quantity"></td>
+                        <td><label>Printing type :</label></td>
+                        <td><select name="printSelect">
+                            <option value="Print1">Print1</option>
+                            <option value="Print2">Print2</option>
+                            <option value="Print3">Print3</option>
+                            <option value="Print4">Print4</option>
+                            </select>
+                        </td>           
+                    </tr>
+                    <tr>
+                        <td ><label>Rate :</label></td>
+                        <td colspan="2"><input type="number" name="rate"></td>
+                    </tr>
+                    <tr class="newForm">
+                    </tr>
+                </tr>
+            </table>
+            
+        </div>
+        <input type="submit" id="submit_btn" class="class_btn">
+    </form>
+    <button class="addButton">Add more tab</button>
+</div>
+
+<script>
+    $(document).ready(function() {
+        var flag = 0;
+        $(".addButton").click(function(e) {
+            if(flag != 5) {
+                flag += 1;
+                var clone = $("#clone").clone();
+                clone.find("input[name=SrNo]").val(flag+1);
+                clone.appendTo($(".table_container"));
+            }
+            else {
+                e.preventDefault();
+            }
+        });
+    })
+</script>
+
",html +"Coloring each word in inner HTML with a separate color using a JavaScript function

I am working on a small project to color each syllable in a separate color.

+

We take input from a text area and then pass it to a JavaScript function that does the syllable splitting and finally we need to output each syllable in a different color.

+

At first I wanted to output the result in another text area, but then I found out that there is no way to style each syllable inside a text area.

+

So for now I will be outputting it in a div using inner HTML.

+

This is a sample code that I am using to test what works and what doesn't:

+

I tried changing the inner HTML style before outputting each result but it is not working. I am getting both words in blue

+
<!DOCTYPE html>
+<html>
+
+<head>
+  <meta charset="utf-8">
+  <title>Username Password Generator</title>
+</head>
+
+<body style="text-align: center;">
+
+
+
+<form id="myForm">
+  First name:<br> <input type="text" name="fname" value="Donald"/><br>
+  Last name:<br> <input type="text" name="lname" value="Duck"/><br>
+ 
+</form> 
+<br>
+<button onclick="color()">color</button> 
+
+<h1 id="firstNameLastName"></h1>
+
+<script>
+
+  function color() {
+  var firstName = document.getElementById("myForm").elements[0].value;
+  var lastName = document.getElementById("myForm").elements[1].value;
+
+ //var password = randomstring();
+  document.getElementById("firstNameLastName").style.color = "red";
+  document.getElementById("firstNameLastName").innerHTML = firstName;
+  document.getElementById("firstNameLastName").style.color = "blue";
+  document.getElementById("firstNameLastName").innerHTML += ' ' + lastName;
+}
+
+
+</script>
+</body>
+</html>
+
+

I updated my function and now it works:

+
  function color() {
+  var firstName = document.getElementById("myForm").elements[0].value;
+  var lastName = document.getElementById("myForm").elements[1].value;
+
+ //var password = randomstring();
+  var x = document.createElement("SPAN");
+  x.style.color="red";
+  var t = document.createTextNode(firstName);
+  x.appendChild(t);
+  document.getElementById("firstNameLastName").appendChild(x);
+  x = document.createElement("SPAN");
+  x.style.color="blue";
+  t = document.createTextNode(lastName);
+  x.appendChild(t);
+  document.getElementById("firstNameLastName").appendChild(x);
+}
+
","

Your approach will not work. You will need separate html elements for each word. I think a span would be a good choice.

+

The reason is that when you do document.getElementById("firstNameLastName").style.color you set the text color for the whole h1 element.

+

You initially make it all red, and then all blue, so you end up with 2 blue words.

+

You can check my approach on this fiddle.

",html +"CSS expand transition when child element sizes increase

I am using Vuetify and have a v-list-item with a title and a subtitle. But the title length is limited to only show one line. If the title is longer it will be cut off and show "...". +If I click the list item i want the subtitle to disappear and show the full title instead. This might result in a new height of the whole v-list-item. The expansion of the height should be a transition so that the height is not hopping when I am clicking the list item. I have trouble to solve this problem so maybe you have some ideas. This is my code so far:

+
<v-list-item three-line :class="{ activeListItem: currentPostId === post.id }">
+   <v-list-item-content>
+      <v-list-item-title :class="{'full-text': currentPostId === post.id}">
+         Title
+      </v-list-item-title>
+      <v-list-item-subtitle :class="{ 'post-subtitle-hidden': currentPostId === post.id }">
+         Subtitle
+      </v-list-item-subtitle>
+   </v-list-item-content>
+</v-list-item>
+
+

CSS:

+
.activeListItem {
+   background-color: #c4e0ff !important;
+}
+.full-text {
+   white-space: normal;
+}
+.post-subtitle-hidden {
+   display: none;
+}
+.v-list-item__subtitle, .v-list-item__title {
+   -webkit-box-flex: 1;
+   -ms-flex: 1 1 100%;
+   flex: 1 1 100%;
+   overflow: hidden;
+   text-overflow: ellipsis;
+   white-space: nowrap;
+}
+
","

Instead of display: none use max-height: 0 then on the active class give it a max-height of like 100px (the maximum height you think it will ever use) than add a transition on max-height

+

that way it will have a sliding effect

+

--- edit --- +snippet for what is discussed in the comments

+

+
+
$('.title').click(function() {
+    $('.subtitle').toggleClass(""subtitle-show"");
+});
+
.subtitle {
+  max-height: 0;
+  overflow: hidden;
+  transition: max-height .3s;
+}
+
+.subtitle-show {
+  max-height: 100px;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""wrapper"">
+<div class=""title"">
+  Title
+</div>
+  <div class=""subtitle"">
+      The subtitle
+  </div>
+</div>
+
+
+

+

When I click on the title the subtitle appears/disappears the only problem with this implementation is that when you close it you have a little delay because it is transitioning on the max-height 100px to 0

+

As far as I know there is no better way to do this in css.

",html +"AudioBuffer - get data only from a particular sample of a particular length without decoding the entire sound

I'm working on a DAW in JavaScript and I need to be able to load many (up to 30) long audio files (up to 15 minutes each) and I don't want them to flood the memory. I just want to be able to cut little pieces, process them and mix in ScriptProcessorNode, but I encountered a couple of problems:

+
    +
  • AudioBuffer will load the entire audio file into memory uncompressed
  • +
  • AudioBuffer.getChannelData() will extract the entire buffer - not possible just to extract one little chunk (for example, from sample 1024 to sample 2048)
  • +
  • MediaElementAudioSourceNode, which is made to handle large files - it won't let me extract any data from it, neither it will let me load the file dynamically from URL - it only allows me to connect to other nodes in AudioContext, but I don't want to connect it anywhere
  • +
+

Is there a way to load big audio files, for example, in MP3 format, keep them compressed in MP3 format in memory, but extract little chunks of audio data to the AudioBuffer?

+

Like, for example:

+
var request = new XMLHttpRequest();
+request.open('GET', 'my_15min_audioFile.ogg', true);
+request.responseType = 'arraybuffer';
+request.onload = function() {
+    var longCompressed = new LongAudioNode(request.response);// something similar to fs.open
+    var channel=1, fromSample=1024, length=2048;
+    var block/**Float32Array*/ = longCompressed.extractBlock(channel, fromSample, length);/// similar to fs.read
+    /// do something with this block and then request another from any random index I want
+}
+request.send();
+
","

There is no API in the browser which does exactly what you want. But there might be one in the future. Web Codecs will probably support reading decoded data as a stream.

+

But there is a workaround which works under certain conditions. You can scan the ArrayBuffer with the encoded data of an MP3 for frame headers and then cut it accordingly. The pieces should still be valid MP3s which can then be decoded with decodeAudioData(). However there are some gotchas. The decoded pieces might not fit together without any post-processing. The phonograph library is built using this technique.

",html +"Need help scraping a web-page

I started a mini project where I want to retrieve coin name, price, coin market-cap, circulating supply and volume for the first 100 coins on the first page. Until now, (after asking several questions and getting good inputs) I am able to retrieve all the coin names on the first page. However, with prices I only get the first 11 names, and coin-market cap I get nothing. I really want to be collect the data so I can start doing some data analysis, but I always hit a wall. Can someone point me further in the right direction?? I am aware there is an api, but I want to expand my knowledge.

+
import requests
+from lxml import html
+from selenium import webdriver
+
+url = "https://coinmarketcap.com/"
+
+driver = webdriver.Chrome()
+
+driver.get(url)
+
+coin_name = [name.text for name in driver.find_elements_by_xpath('//td[3]/a[@class="cmc-link" and starts-with(@href, "/currencies/")]')]
+print(coin_name)
+print(len(coin_name))
+price = [p.text for p in driver.find_elements_by_xpath('//td[4]/div/a[@class = "cmc-link" and contains(@href, "/markets/")]')]
+print(price)
+print(len(price))
+
+market_cap = [m.text for m in driver.find_elements_by_xpath('//p[@class = "cmc-link" and contains(@style, "white-space:nowrap")]//p[@color="text"]')]
+
+print(len(market_cap))
+
","

You need to scroll the elements into the view. Just keep sending a page down.

+
import time
+
+import requests
+from lxml import html
+from selenium import webdriver
+from selenium.webdriver.common.keys import Keys
+
+url = "https://coinmarketcap.com/"
+
+driver = webdriver.Chrome(executable_path='C:/chromedriver.exe')
+
+driver.get(url)
+driver.maximize_window()
+for i in range(22):
+    coin_name = driver.find_elements_by_xpath('//td[3]/a[@class="cmc-link" and starts-with(@href, "/currencies/")]')
+
+    prices = driver.find_elements_by_xpath('//td[4]/div/a[@class = "cmc-link" and contains(@href, "/markets/")]')
+
+    market_caps = driver.find_elements_by_xpath('//p[@class="sc-1eb5slv-0 kDEzev"]')
+    
+    html = driver.find_element_by_tag_name('html')
+    html.send_keys(Keys.PAGE_DOWN)
+    for coin, price, cap in zip(coin_name, prices, market_caps):
+        print("Coin :", coin.text, "Price :", price.text, "Market_caps:", cap.text)
+
+

Output:-

+
CETH Price : $648.10 Market cap : $435,982,385,626
+Coin : XRP
+XRP Price : $0.573805 Market cap : $73,825,115,056
+Coin : Tether
+USDT Price : $1.00 Market cap : $26,053,047,457
+Coin : Litecoin
+LTC Price : $117.47 Market cap : $20,302,149,320
+Coin : Bitcoin Cash
+BCH Price : $350.85 Market cap : $7,768,463,654
+Coin : Chainlink
+LINK Price : $13.34 Market cap : $6,526,170,500
+Coin : Cardano
+ADA Price : $0.163470 Market cap : $5,300,831,845
+Coin : Binance Coin
+BNB Price : $34.82 Market cap : $5,085,969,556
+Coin : Polkadot
+DOT Price : $5.25 Market cap : $5,027,979,819
+Coin : Stellar
+XLM Price : $0.178429 Market cap : $4,683,566,948
+
",html +"Can anyone modify this code so that it can be used for classes because if I write getElementsByClassName the code doesn't work so plese help me
<script>
+function copyClipboard() {
+  var elm = document.getElementById("divClipboard");
+  // for Internet Explorer
+
+  if(document.body.createTextRange) {
+    var range = document.body.createTextRange();
+    range.moveToElementText(elm);
+    range.select();
+    document.execCommand("Copy");
+    alert("Copied div content to clipboard");
+  }
+  else if(window.getSelection) {
+    // other browsers
+
+    var selection = window.getSelection();
+    var range = document.createRange();
+    range.selectNodeContents(elm);
+    selection.removeAllRanges();
+    selection.addRange(range);
+    document.execCommand("Copy");
+    alert("Copied div content to clipboard");
+  }
+}
+</script>
+
+

Plese modify this code so that it can be used for classes rather then for id. If I change "getElementById" to "getElementsByClassName" the code doesn't work. So please help .

","

document.getElementsByClassName returns an array of elements where all the elements have the same class. So if there's only one element of class "divClipboard", you can change that line to,

+
var elm = document.getElementsByClassName("divClipboard")[0];
+
",html +"querySelector is unable to access passed id
<div id="page1">
+               block1
+        </div>
+        <div id="page2">
+             block2
+        </div>
+        <div id="page3">
+            block3
+        </div>
+
+

I am trying to access the id of the div by using following function, but it does not work.

+
           function  aa(page)
+              {
+                  document.querySelector('#${page}').style.display='block';
+              }
+
+

I am getting the following error: +'querySelector' on 'Document': '#${page}' is not a valid selector.

","

You need to use template literals enclosed by backticks instead of single quotes which delimit a normal string.

+
document.querySelector(`#${page}`)
+
",html +"AJAX is sending all null data to the Spring Controller using POST mapping?

I am trying to send data from HTML Form with POST mapping using ajax to the spring controller. But it's sending all null data. Tried lots of variation for ajax. It's sending the school object but all fields are null. The console shows the fields are saving but all becomes null in the AJAX.

+

Here is the createSchoolForm.html

+
<!DOCTYPE html>
+<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
+<head>
+    <title>Create School || EDUBD</title>
+    <meta charset="utf-8">
+    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
+    <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
+</head>
+<body>
+    <h1>EDUBD - Manage School Portal</h1>
+
+    <h3>Create New School</h3> <br>
+
+    <form id="createSchool">
+        <br>
+        <label>School Name:
+        <input type="text" id="schoolName"  value="" />
+        </label>
+        <br>
+        <label>School Email:
+        <input type="text" id="schoolEmail" value="" />
+        </label>
+        <br>
+        <label>School Phone Number:
+        <input type="tel" id="schoolPhone" value="" />
+        </label>
+        <br>
+        <input id="btn" type="submit" value="Submit" />
+    </form>
+
+    <div id="feedback"></div>
+
+
+
+    <script>
+        $(document).ready( function() {
+            $("#createSchool").submit(function(e){
+                e.preventDefault();
+                var schoolData = {
+                    schoolName: $("#schoolName").val(),
+                    schoolEmail: $("#schoolEmail").val(),
+                    schoolPhone: $("#schoolPhone").val(),
+                    status: null,
+                    schoolStreet: null,
+                    schoolHouse: null,
+                    schoolZip: null,
+                    schoolCity: null,
+                    schoolState: null,
+                    schoolCountry: null,
+                    image: null,
+                    createBy: null,
+                    updatedBy: null,
+                    createdDate: null,
+                    updatedDate: null,
+                    id: null
+                };
+               // let j = JSON.stringify(schoolData);
+                console.log(JSON.stringify(schoolData));
+
+                $.ajax({
+                    header:{
+                        contentType : 'application/x-www-form-urlencoded; charset=UTF-8'
+                    },
+                    type : "post",
+                    url : "Create",
+                    data : JSON.stringify(schoolData),
+                    dataType : "json",
+                    success: function (data) {
+                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
+                            + JSON.stringify(data, null, 4) + "&lt;/pre&gt;";
+                        $('#feedback').html(json);
+                        console.log("SUCCESS : ", data);
+                    },
+                    error: function (e) {
+                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
+                            + e.responseText + "&lt;/pre&gt;";
+                        $('#feedback').html(json);
+                        console.log("ERROR : ", e);
+                    }
+                });
+            });
+        });
+
+    </script>
+
+</body>
+</html>
+
+

Here is the controller:

+
    @ApiOperation(value = "Create School")
+    //@PostMapping(BASE_SCHOOL_PATH+"/Create")
+    @PostMapping(value = BASE_SCHOOL_PATH+"/Create", produces = {"application/json"},
+            consumes = {"application/x-www-form-urlencoded"})
+    public  String create (School school, @ApiIgnore HttpServletResponse response) throws IOException {
+        // components tests are expecting this assertion and exception handling, and will fail if removed
+        try {
+            Assert.isNull(school.getId(), "School ID field must be null");
+            Assert.notNull(school.getSchoolEmail(),"School email cannot be null.");
+            Assert.notNull(school.getSchoolPhone(),"School Phone number cannot be null. ");
+            Assert.isNull(schoolDao.readByEmail(school.getSchoolEmail()),"School already exists in the system.");
+            schoolDao.create(school, null);
+            return "createSchoolForm";
+        } catch (IllegalArgumentException e) {
+            logger.error(e.getMessage(), e);
+            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
+            return null;
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+            return null;
+        }
+    }
+
+
","

The Solution that worked for me.

+

I have tried different ways to solve the problem. It actually helped me to understand how HTTP request works. Here is the solution that worked for me. +I used XMLHttpRequest() to send the data from the HTML form. After sending, I had to capture the data with @RequestBody. This is important for the POST to work. +I also had 2 different produces and consumes in my controller. Had to match those. Lastly, used <button> in place of <input> for the submission.

+

The Solution

+

New HTML looks like this:

+
 <h3>Create New School</h3> <br>
+    <form id="createSchool" method="post">
+        <br>
+        <label>School Name:
+        <input type="text" id="schoolName"  value="" required/>
+        </label>
+        <br>
+        <label>School Email:
+        <input type="email" id="schoolEmail" value="" required/>
+        </label>
+        <br>
+        <label>School Phone Number:
+        <input type="tel" id="schoolPhone" value="" required/>
+        </label>
+        <br>
+        <button type="button" id="submit">Submit Form</button>
+    </form>
+
+    <div id="feedback"></div>
+
+    <script>
+        $(document).ready( function() {
+            $("#submit").click(function(e) {
+                e.preventDefault();
+                var school=new Object(); //creating object to add values. 
+                school.schoolName = $("#schoolName").val();
+                school.schoolEmail= $("#schoolEmail").val();
+                school.schoolPhone = $("#schoolPhone").val();
+                school.status= null;
+                school.schoolStreet= null;
+                school.schoolHouse= null;
+                school.schoolZip= null;
+                school.schoolCity= null;
+                school.schoolState= null;
+                school.schoolCountry= null;
+                school.image= null;
+                school.createBy= null;
+                school.updatedBy= null;
+                school.createdDate= null;
+                school.updatedDate= null;
+                school.id= null;
+
+                var s2=JSON.stringify(school);
+                console.log(s2);
+
+                var xhr = new XMLHttpRequest();
+                xhr.open("POST", "SchoolCreate",true);
+                xhr.setRequestHeader("Content-Type", "application/json");
+                xhr.onreadystatechange = function() { // Call a function when the state changes.
+                    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
+                        // Request finished. Do processing here.
+                        console.log("success");
+                        $('#feedback').html("Success");
+                    }
+                    else {
+                        console.log(xhr.responseText);
+                        $('#feedback').html(xhr.responseText);
+                    }
+                }
+                xhr.send(s2);
+
+                //This will empty the fields after submission.
+                document.getElementById('schoolName').value='';
+                document.getElementById('schoolEmail').value='';
+                document.getElementById('schoolPhone').value='';
+
+
+            });
+        });
+    </script>
+
+</body>
+
+

The Controller:

+
    @ApiOperation(value = "Create School")
+    @PostMapping(value = "/ManageSchool"+BASE_SCHOOL_PATH+"/SchoolCreate", produces = {"application/json"},
+            consumes = {"application/json"})
+    public String create (@RequestBody School school, @ApiIgnore HttpServletResponse response) throws IOException {
+        // components tests are expecting this assertion and exception handling, and will fail if removed
+        try {
+            Assert.isNull(school.getId(), "School ID field must be null");
+            Assert.notNull(school.getSchoolEmail(),"School email cannot be null.");
+            Assert.notNull(school.getSchoolPhone(),"School Phone number cannot be null. ");
+            Assert.isNull(schoolDao.readByEmail(school.getSchoolEmail()),"School already exists in the system.");
+            schoolDao.create(school, null);
+            return "createSchoolForm";
+        } catch (IllegalArgumentException e) {
+            logger.error(e.getMessage(), e);
+            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
+            return null;
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+            return null;
+        }
+    }
+
+

These answers helped me to find some ground in the end.

+

How to transfer data from HTML to controller Spring

+

XMLHttpRequest not sending POST data

",html +"Background img blur - css

Hello dear developers,

+

I want to blur the background image on hovering.but it does not work. Can anybody help me? i tried many ways. +This is a box and i wand to blur backgournd and show the text with hover-over-effect. +currently when the mouse is over the boxes, the following happens: +Either: +the Background becomes blur but the text does not appear +or: +The texts appear but background will not blur

+

+

HTML

+
<div class="kursContainer">
+        <div class="BodyKurs">
+                <h1>Body</h1>
+                <picture>
+                    <img src="../Kurse/img/body.webp" alt="zumba">
+                </picture>
+            <div class="overlay">
+                <h2>Body</h2>
+                <h3>Abnehmen - 6 Wochen</h3>
+                <h4>Lorem ipsum dolor sit amet, consectetur adipiscing     elit</h4>
+            </div>
+        </div>
+
+

CSS

+
.kursContainer {
+  display: grid;
+  justify-content: space-evenly;
+  grid-template-columns: repeat(3, 1fr);
+  grid-gap: 1em;
+  justify-items: center;
+  width: 122vmin;
+  margin: 2vmin auto;
+  align-items: center;
+
+  grid-template-areas:
+    "body body fatburn"
+    "body body zumba"
+    "yoga sixpack sixpack"
+    "step sixpack sixpack"
+    "backwork backwork tourde"
+    "backwork backwork booty";
+ }
+ .BodyKurs{
+   position: relative;
+   width: 80vmin;
+   height: 80vmin;
+   border-radius: 10px;
+   background-color: var(--schwarz);
+   transition: transform 0.2s;
+ }
+
+.BodyKurs img{
+   width: 80vmin;
+   border-radius: 10px;
+}
+ .BodyKurs h1 {
+   position: absolute;
+   text-align: start;
+   padding-left: 3vmin;
+   bottom: 1vmin;
+   color: var(--hellGrau);
+   font-size: 8vmin;
+ }
+
+ .BodyKurs:hover {
+    box-shadow: 0 0px 4.6px rgba(0, 0, 0, 0.278),
+     0 0px 15.4px rgba(0, 0, 0, 0.411), 0 0px 69px rgba(0, 0, 0, 0.69);
+   transform: scale(1.05);
+   z-index: 2;
+   cursor: pointer;
+ }
+
+  .overlay {
+  width: 80vmin;
+  height: 80vmin;
+  position: absolute;
+  text-align: center;
+  bottom: 0;
+  border-radius: 10px;
+  color: var(--hellGrau);
+  transition: 0.3s all;
+  /* background: rgba(0, 0, 0, 0.2); */
+  visibility: hidden;
+   cursor: pointer;
+  z-index: 5;
+}
+ .overlay:hover {
+  visibility: visible;
+}
+
+picture:hover {
+  filter: blur(5px);
+}
+
","

You can use :not(:hover) style

+

Example 1:

+

+
+
.wrap:hover img,
+.wrap:hover img:not(:hover) {
+    filter: blur(3px);
+}
+
+.wrap {
+    width: 300px;
+}
+
+span {
+    position: absolute;
+    color: #ffffff;
+    z-index: 1;
+    text-align: center;
+    width: 300px;
+    display: none;
+}
+
+.wrap:hover span {
+    display: block;
+}
+
<div class='wrap'>
+    <span>
+        <h1>Lorem</h1>
+        <p>Text</p>
+    </span>
+    <img src=""https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRK7bvAryKdY7JSlepTHatE1A4nAVU5lJXkdw&usqp=CAU""
+        width=""300px"">
+</div>
+
+
+

+
+

This example is a little more CSS but I think it's easier to understand. Used again :not(:hover) but this time on the span element.

+

Example 2:

+

+
+
.wrap:hover img,
+.wrap:hover span:not(:hover) {
+    filter: blur(3px);
+}
+
+.wrap {
+    position: relative;
+    width: 300px;
+    overflow: hidden;
+}
+
+span {
+    position: absolute;
+    top: 0px;
+    right: 0px;
+    bottom: 0px;
+    left: 0px;
+    color: #ffffff;
+    z-index: 1;
+    text-align: center;
+    display: none;
+}
+
+.wrap:hover span {
+    display: block;
+}
+
<div class='wrap'>
+    <span>
+        <h1>Lorem</h1>
+        <p>Text</p>
+    </span>
+    <img src=""https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRK7bvAryKdY7JSlepTHatE1A4nAVU5lJXkdw&usqp=CAU""
+        width=""300px"">
+</div>
+
+
+

",html +"traffic light sequence, html, javascript and css

I am trying to make a program that displays a traffic light sequence. I have made a mistake in the code so it doesn't get past showing the red light when the "starts sequence" button is clicked. if you can see where I went wrong please help me get it working.

+

I have used functions to change the display of the different lights. when the start sequence button is clicked the change function should call each function (stop,ready,go) which change the brightness of the lights in order from red to amber to green and back.

+

+
+
function change() {
+
+  setTimeout(stop, 2000);
+  setTimeout(ready, 2000);
+  setTimeout(go, 2000);
+  setTimeout(ready, 2000);
+  setTimeout(stop, 2000);
+
+}
+
+function stop() {
+  aimg = document.getElementById(""a"");
+  bimg = document.getElementById(""b"");
+  cimg = document.getElementById(""c"");
+  aimg.style.filter = ""brightness(2)"";
+  bimg.style.filter = ""brightness(0)"";
+  cimg.style.filter = ""brightness(0)"";
+}
+
+function go() {
+  aimg = document.getElementById(""a"");
+  bimg = document.getElementById(""b"");
+  cimg = document.getElementById(""c"");
+  aimg.style.filter = ""brightness(0)"";
+  bimg.style.filter = ""brightness(0)"";
+  cimg.style.filter = ""brightness(2)"";
+}
+
+
+function ready() {
+  aimg = document.getElementById(""a"");
+  bimg = document.getElementById(""b"");
+  cimg = document.getElementById(""c"");
+  aimg.style.filter = ""brightness(0)"";
+  bimg.style.filter = ""brightness(2)"";
+  cimg.style.filter = ""brightness(0)"";
+}
+
.container {
+  height: 450px;
+  width: 200px;
+  border: 5px solid;
+  ;
+}
+
+.top {
+  position: absolute;
+  top: 30px;
+  left: 35px;
+}
+
+.middle {
+  position: absolute;
+  top: 175px;
+  left: 35px;
+}
+
+.bottom {
+  position: absolute;
+  top: 320px;
+  left: 35px;
+}
+
<html>
+
+<body>
+  <div class=""container""></div>
+  <button id=""traffic"" onClick=""change()"">start sequence</button><br>
+  <div class=""top"">
+    <img src=""aRed.png"" alt=""Red"" id=""a""><br>
+  </div>
+  <div class=""middle"">
+    <img src=""bAmber.png"" alt=""Amber"" id=""b""><br>
+  </div>
+  <div class=""bottom"">
+    <img src=""cGreen.png"" alt=""Green"" id=""c""><br>
+  </div>
+</body>
+
+</html>
+
+
+

","

You're calling all setTimeout at the same time, so they all trigger after 2 seconds. You could solve it by calling each timeout after the previous one has finished. Also, you don't need to find the elements again in each function call.

+
let aimg = document.getElementById("a");
+let bimg = document.getElementById("b");
+let cimg = document.getElementById("c");
+
+function change() {
+  setTimeout(stop, 2000);
+}
+
+function stop() {
+  aimg.style.filter = "brightness(2)";
+  bimg.style.filter = "brightness(0)";
+  cimg.style.filter = "brightness(0)";
+  setTimeout(ready, 2000);
+} 
+
+function ready() {
+  aimg.style.filter = "brightness(0)";
+  bimg.style.filter = "brightness(2)";
+  cimg.style.filter = "brightness(0)";
+  setTimeout(go, 2000);
+}
+
+function go() {
+  aimg.style.filter = "brightness(0)";
+  bimg.style.filter = "brightness(0)";
+  cimg.style.filter = "brightness(2)";
+  setTimeout(stop, 2000);
+}
+
+

Bear in mind that if you call change() more than once, you'll start multiple sequences. You could prevent that by storing a interval id for each of the three timeouts

+
readyTimeout = setTimeout(ready, 2000);
+
+

And then canceling them all when the button is pressed:

+
clearTimeout(readyTimeout);
+
",html +"How to load the next page of the API's data using button click ""Load More""?

my goal is to render some user data from API https://reqres.in/api/users?page=( this can be 1,2 or more if pages are available) and output it to a html table using JS / Promises. So initially I have managed to get the first page's data to the table and now I need it to be modified when I click "Load More" button it should delete the current data on the table and shows the page 2's data. This is my code so far

+
let userDataTable = document.getElementById("userData");
+
+var tot_pages;
+let pagesCount = 1;
+
+console.log(tot_pages);
+let getUSerInfo = function () {
+  fetch(`https://reqres.in/api/users?page=${pagesCount}`)
+    .then((response) => response.json())
+    .then((people) => {
+      let users = people.data;
+      tot_pages = people.total_pages;
+      console.log(users);
+      console.log(tot_pages);
+      for (let i = 0; i < users.length; i++) {
+        let htmlContent = `<tr><td>${users[i].id}</td><td><img src="${users[i].avatar}"/></td><td>${users[i].first_name}</td><td>${users[i].last_name}</td><td>${users[i].email}</td></tr>`;
+        userDataTable.insertAdjacentHTML("beforeend", htmlContent);
+      }
+    })
+    .catch(function (error) {
+      console.log(error);
+    });
+};
+getUSerInfo();
+console.log(tot_pages);
+
+document
+  .getElementById("load_btn")
+  .addEventListener("click", () => getUSerInfo());
+
+

also when there are no pages left to load (ex: when the last page's data is showing in the table then the "Load More" button should not be visible)

+

I'll explain what my idea was achieving this task : I was trying to create a global variable(tot_pages) initializing it to 1. Then inside the promise I was trying to assign the total pages from the object which I render via reqres.in and return it to the button as a counter or something. So as an ex : When I click the button the counter will increase(in this case the tot_pages variable will increase). Anyway after hours of trying on my own could not get this done yet. I do really appreciate if someone can help me out. Thank you for you time and consideration!

","

I think your code will work fine with you updating pagesCount variable on each successful API fetch, check this updated code. I've changed some variable names

+
let totalPages,
+    currentPage = 0,
+    loadMoreBtn = document.getElementById("load_btn");
+
+// bind load more button
+loadMoreBtn.addEventListener("click",getUSerInfo);
+
+// fetch people
+ function getUSerInfo() {
+    // ignore if all data has been loaded
+    if(currentPage >= totalPages) return
+    
+    const nextPage = currentPage + 1;
+    fetch(`https://reqres.in/api/users?page=${nextPage}`)
+        .then((response) => response.json())
+        .then((people) => {
+             const users = people.data,
+             userDataTable = document.getElementById("userData");
+
+             totalPages = people.total_pages;
+
+             // hide load more button
+             if(totalPages == nextPage) loadMoreBtn.style.visibility = 'hidden';
+
+             // udate table data
+             for (let i = 0; i < users.length; i++) {
+                 let htmlContent = `<tr><td>${users[i].id}</td><td><img src="${users[i].avatar}"/></td><td>${users[i].first_name}</td><td>${users[i].last_name}<  /td><td>${users[i].email}</td></tr>`;
+                  userDataTable.insertAdjacentHTML("beforeend", htmlContent);
+             }
+
+             currentPage = nextPage;
+        })
+        .catch(function (error) {
+             console.log(error);
+        });
+    };
+
+ // fetch initial page
+ getUSerInfo();
+
",html +"Is there a faster way of creating and iterating over a 200x200 grid in Javascript?

I am new into Javascript and for the purposes of a simple game, I need to display a 200x200 grid on a page, with each cell containing a boolean value. My current approach looks like this: I create an HTML table dynamically, assign IDs and add a checkbox on each cell.

+

Here is how I go about creating my table:

+
    const a = 200;
+    var resultTable = '<table name = "mytab" id = "abc">';
+    for (var i = 0; i < a; i++) {
+        resultTable += '<tr>';
+        for (var j = 0; j < a; j++) {
+            var uid = i + '.' + j;
+            resultTable += '<td class="container"><input type="checkbox" id="' 
+            + uid + '" class="regular-checkbox"><\/td>';
+        }
+    }
+
+

and this is how I am collecting values:

+
    for (var i = 0; i < a; i++) {
+            for (var j = 0; j < a; j++) {
+                var yy = i + '.' + j;
+               /* if (document.getElementById(yy).checked) do something */
+            }
+    }
+
+

It works but there are some serious performance issues. Is there a different approach of doing this faster? Any help is appreciated.

","

A performance enhancement would be selecting the elements. Currently you create the entire table from a string and later select each input with document.getElementById(). You could improve this by creating a reference to each input when you create the elements, so you don't have to find it later on.

+

With document.createElement() you can create instances of elements in JavaScript. The function returns a reference to the created element which you can store to use later on.

+

For example, you could create an input element with it.

+
const input = document.createElement('input');
+input.type = 'checkbox';
+input.checked = true;
+
+

Now you have an input element already saved in the input constant. Now you don't have the find the element later on as you already have a reference to it, making the loop having to do 1 less task per input, resulting in 200 x 200 less tasks.

+

The example below uses the aforementioned createElement method to create a <table> element. In the second loop the <input> element is created and a reference to the element is stored in an array. Looping through this array is now n(0) which allows you to loop through each input in a single loop.

+
const amount = 200;
+const inputCollection = [];
+
+const table = document.createElement('table');
+table.name = 'mytab';
+table.id = 'abc';
+
+for (let i = 0; i < amount.length; i++) {
+  const row = table.insertRow();
+
+  for (let j = 0; j < amount.length; j++) {
+    const input = document.createElement('input');
+    input.classList.add('regular-checkbox');
+    input.type = 'checkbox';
+
+    // Add the input reference to the collection.
+    inputCollection.push(input);
+
+    const cell = row.insertCell();
+    cell.append(input);
+  }
+}
+
+document.body.append(table);
+
+inputCollection.forEach(input => {
+  if (input.checked) {
+    // Do something.
+  }
+});
+
",html +"How to Send Lead Form Data to swaggerhub Api using php?

I have a Swagger API on which, I had to send Lead Form Data From my Web Page. I Can't Get much data From internet. Form is Already Created on Swagger HUB on Which ,I can manually insert data and it's Working But I had to send data From my Webpage , I am Already sending Data From my Webpage to Google Sheets But I Can't insert same data into Swagger HUB API Dynamically Can Anyone Help me With it Thanks!

","

As per documentation you have to use formdata to send infomration:

+

+

First you have to authenticate using authenticate endpoint and then use that token for authenticating the post endpoint.

+

",html +"Box that expand in a gallery

I'm trying to figure out how to expand a box by the size some boxes inside a "gallery". +I need it the way it doesn't messy the other boxes neither the other page elements. It should expand and collapse. +There are eight boxes and when I click at one of them it should take the space of all the eight boxes, when I clik it again, it should collapse down to its original one-box-size. It should also show a different content for each box when expanded. +

+

+

I tried to use css target properties and anchor tags. +What solution would you guys use?

+

here's my code trial:

+
<a href="#odontopediatria">
+    <div class="trat-card">
+        <div class="trat-icone"><i class="fas fa-tooth"></i></div>
+        <div class="trat-titulo">Odontopediatria</div>
+    </div>
+    <a href="#_" class="lightbox" id="odontopediatria">
+        <div class="lightbox-conteudo">
+            <div class="trat-texto">
+                <i class="fas fa-tooth fa-3x"></i>
+                <p>Odontopediatria é a especialidade que tem como objetivo o diagnóstico, a prevenção, o tratamento e o controle dos problemas de saúde bucal do bebê, da criança e do adolescente.
+                </p>
+            </div>
+        </div>
+    </a>
+</a>
+
+
+    
+.lightbox {
+  text-align: center;
+  color: white;
+  font-size: 22px;
+  display: none;
+}
+
+.lightbox:target {
+  display: block;
+  top: 0;
+}
+
+.lightbox div:nth-child(n) {
+  position: absolute;
+    left: 0;
+  display: flex;
+    flex-direction: column;
+    width: 100%;
+    height: 306px;
+    border-radius: 4px;
+    align-items: center;
+    justify-content: space-around;
+  padding: 30px;
+  margin: 0 auto;
+}
+
","

I hope you are doing well, this is a demo of what you want, I use a small jquery code for manage a togglable class which help to make CSS to expand small box to large.

+

+
+
$(document).ready(function() {
+  $("".expandable_box"").click(function() {
+    $(this).parent("".main_col"").toggleClass(""expanded"");
+  });
+});
+
body {
+  margin: 0px;
+}
+
+* {
+  box-sizing: border-box;
+}
+
+.main_container {
+  padding: 0px 5px;
+}
+
+.main_row {
+  display: flex;
+  flex-wrap: wrap;
+  margin: 0px -5px;
+  position: relative;
+}
+
+.main_col {
+  -ms-flex: 0 0 25%;
+  flex: 0 0 25%;
+  max-width: 25%;
+  padding: 0px 5px;
+  margin: 5px 0px;
+  text-align: center;
+}
+
+.main_col.expanded {
+  position: absolute;
+  -ms-flex: 0 0 100%;
+  flex: 0 0 100%;
+  max-width: 100%;
+  left: 0;
+  top: 0;
+  bottom: 0;
+  right: 0;
+}
+
+.expandable_box {
+  padding: 30px;
+  background-color: #3ca6b6;
+  color: #fff;
+  border-radius: 5px;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+  text-decoration: none;
+}
+
+.expanded .expandable_box {
+  min-height: 100%;
+  background-color: #0c798a;
+}
+
+.expandable_box h4 {
+  margin: 20px 0px 0px;
+}
+
+.expandable_box p {
+  display: none;
+  margin: 0px;
+  padding: 15px 0px 0px;
+  visibility: hidden;
+  opacity: 0;
+}
+
+.expanded .expandable_box p {
+  display: block;
+  visibility: visible;
+  opacity: 1;
+}
+
+@media(max-width: 991px) {
+  .main_col {
+    -ms-flex: 0 0 50%;
+    flex: 0 0 50%;
+    max-width: 50%;
+  }
+}
+
<!DOCTYPE html>
+<html>
+
+<head>
+  <title>Same Place Expander</title>
+  <meta charset=""utf-8"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1"">
+</head>
+
+<body>
+  <div class=""main_container"">
+    <div class=""main_row"">
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+      <div class=""main_col"">
+        <a href=""javascript:void(0);"" class=""expandable_box"">
+          <i class=""fas fa-tooth fa-lg""></i>
+          <h4>Lorem Ipsum</h4>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fringilla dapibus est, et cursus justo. Aenean lobortis porta nunc, nec ultricies lectus molestie id. Nulla sollicitudin elementum consectetur. Pellentesque gravida nunc eget efficitur vestibulum.
+            In lorem lacus, maximus eu bibendum quis, fringilla at lectus. Vestibulum fringilla quam sed diam mattis, non congue arcu efficitur.
+          </p>
+        </a>
+      </div>
+    </div>
+  </div>
+  <script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js""></script>
+  <script src=""https://kit.fontawesome.com/a35ed2bddb.js"" crossorigin=""anonymous""></script>
+</body>
+
+</html>
+
+
+

+

I hope this will works fine for you.

+

Thank you...

",html +"Tree graph in HTML

How to get this:

+
<ul>
+  <input type="text" placeholder="A" />
+  <ul>
+    <input type="text" placeholder="B" />
+    <ul>
+      <input type="text" placeholder="D" />
+    </ul>
+    <ul>
+      <input type="text" placeholder="E" />
+    </ul>
+  </ul>
+  <ul>
+    <input type="text" placeholder="C" />
+    <ul>
+      <input type="text" placeholder="F" />
+    </ul>
+    <ul>
+      <input type="text" placeholder="G" />
+    </ul>
+  </ul>
+</ul>
+
+

out of it:

+
const graph = {
+  A: ['B', 'C'],
+  B: ['D', 'E'],
+  C: ['F', 'G'],
+  D: [],
+  E: [],
+  F: [],
+  G: [],
+ }
+
+

const graph means:

+
        A
+      /   \
+     B     C
+    / \   / \
+   D   E F   G
+
+

Without using oop graph. +You can remove input from lists, then just insert the name of the vertex.

","

You need to draw dom via binary tree algorithm i.e. depth first.

+

Algorithm is:

+
    +
  1. Draw root element, find its children

    +
  2. +
  3. Start from first child, draw it, find its children

    +
  4. +
  5. Keep on repeating step 2 until you you reach bottom of the tree.

    +
  6. +
  7. Then go to next child from step 2 and perform same steps as for the first child.

    +
  8. +
+

By following above steps I think you can easily draw DOM using depth first binary tree algorithm.

+

Take a look at sample below

+
<body>
+<div id="root"></div>
+</body>
+const graph = {
+  A: ['B', 'C'],
+  B: ['D', 'E'],
+  C: ['F', 'G'],
+  D: [],
+  E: [],
+  F: [],
+  G: [],
+  
+ }
+ 
+ const root = document.getElementById("root"); 
+ 
+ const findchildren = (node) => graph[node]
+ 
+ const drawNode = (node) => {
+    const input = document.createElement("input"); 
+  input.setAttribute("type", "text");
+  input.setAttribute("placeholder", node);
+  root.appendChild(input); 
+  const children = findchildren(node)
+  if (children.length > 0) {
+    children.forEach(item => drawNode(item))    
+  }
+ }
+ 
+ drawNode("A")
+
",html +"Disable HTML autofix in Chrome

I am creating NODE.js app that use Nunjucks as view engine. I added tests to verify if the html created is valid (for now I just wanted to check if all tags are properly closed). In order to do this i spin up application, go to the site using headless chrome, making a snapshot and running validation code on output files.

+

The problem is that browsers try to fix HTML code automatically. They close tags by themself in order to create more or less valid HTML. Is there a way to disable this feature?

+

I would like to be sure that i created valid HTML document using nunjucks rather then counting that browser will fix it itself.

","

If you validate the source directly, Chrome will not change the HTML. Try this in your browser: view-source:https://stackoverflow.com/questions/65091531/disable-html-autofix-in-chrome +If you use the developer panel to inspect the DOM, Chrome tries to correct poor html.

+

You could maybe just do a GET request to the application, and validate the result, instead of using Chrome.

",html +"Does canvas context2d.drawImage( webglCanvas, 0, 0 ) block until a webgl is finished rendering?

I assume the answer is "no" from my testing but I thought I'd make sure.

+

I'm trying to draw / copy the contents from a WebGL canvas to a 2d canvas every frame and I want to know if I should wait until the WebGL context is finished drawing (which I can use gl.fenceSync to check) before calling it or if I can call drawImage immediately without worrying about a performance hit. Here's how I would plan to use it using three.js as a stand in renderer:

+
const renderer = new THREE.WebGLRendeer();
+const canvas = document.createElement( 'canvas' );
+const ctx = canvas.getContext( '2d' );
+
+// ...
+
+function renderLoop() {
+
+    renderer.render( camera, scene1 );
+    ctx.drawImage( renderer.domElement, 0, 0 );
+
+    renderer.render( camera, scene2 );
+    ctx.drawImage( renderer.domElement, 0, 0 );
+
+}
+
+

Is there a pitfall here I'm missing?

+

Thank you!

+
+

Edit

+

Per gman's request here's an example demonstrating that the function seems to not block by performing a lot of GPU work (50000 instanced cubes with no depth write) before calling drawImage. The drawImage functions takes the same amount of time whether there is one cube or 50000 cubes and whether it's called before or after render() which leads me to believe drawImage does not block. Tested on a 2017 Mac laptop with latest Chrome:

+

https://jsfiddle.net/sL9npto6/

","
+

Does canvas context2d.drawImage( webglCanvas, 0, 0 ) block until a webgl is finished rendering?

+
+

Yes, it effectively blocks

+

The last example on this page does exactly what your render loop shows.

+

If you have some example that you think shows otherwise make a minimal repo and post it a snippet

",html +"Angular Multiple layouts routing is not working

I have the follwing multi-layout structure without lazy loading. When navigating to +https://localhost:44327/admin or /student it doesn't show anything. If I use an empty path instead of admin and student then navigate to it's child (/manageConcern) route it loads the first (AdminLayoutComponent) Layout specified in routing. The second LayoutCompnent (/trainings) doesn't load. looks like the router-outlet in app.component can't read the paths. Any idea what I am missing here? This is what I want to achieve https://stackblitz.com/edit/angular-multi-layout-example

+

Routing-module.ts

+
RouterModule.forRoot([
+  {
+    path: 'admin',
+    component: AdminLayoutComponent,
+    children: [
+      {path: '', redirectTo: 'manageConcern', pathMatch: 'full'},
+      {path: 'manageConcern', component: MasterConcernComponent},
+      {path: 'createTraining', component: AdminComponent},
+    ]
+  },
+  {
+    path: 'student',
+    component: StudentLayoutComponent,
+    children: [
+      {path: '', redirectTo: 'trainings', pathMatch: 'full'},
+      {path: 'trainings', component: TrainingsComponent},
+    ]
+  }
+]),
+
+

AdminLayoutComponent.html

+
<app-header></app-header>
+    <app-menu [menuItems]="menuItems"></app-menu>
+    <div class="app-body-content m-5 p-4">
+       <router-outlet></router-outlet>
+    </div>
+
+

StudentLayoutComponent.html

+
    <app-menu [menuItems]="menuItems"></app-menu>
+    <div class="app-body-content m-5 p-4">
+       <router-outlet></router-outlet>
+    </div>
+
+

app.component.html

+
 <router-outlet></router-outlet>
+
",

As app.component.ts is not a routed component it doesn't know anything about the active route. If you want to use your main router-outlet in app.component.ts then you have to add <base href="/"> in your index.html.

,html +"h1 ""hello world"" text hiding behind of navigation bar how can i fix this

I have a problem with bootstrap.

+

this is my navbar.html code

+
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
+        <a class="navbar-brand" href="#">Fixed navbar</a>
+        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
+        <span class="navbar-toggler-icon"></span>
+        </button>
+        <div class="collapse navbar-collapse" id="navbarCollapse">
+        <ul class="navbar-nav mr-auto">
+            <li class="nav-item active">
+            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
+            </li>
+            <li class="nav-item">
+            <a class="nav-link" href="#">Link</a>
+            </li>
+            <li class="nav-item">
+            <a class="nav-link disabled" href="#">Disabled</a>
+            </li>
+        </ul>
+        <form class="form-inline mt-2 mt-md-0">
+            <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
+            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
+        </form>
+        </div>
+</nav>
+
+

and this is my layout.html code:

+
<!DOCTYPE html>
+<html lang="tr">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>{% block title %}
+    {% endblock %}</title>
+    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
+</head>
+<body>
+    {% include "includes/navbar.html" %}
+    <h1>Hello World</h1>
+    {% block context %}
+    {% endblock %}
+    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
+    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
+</body>
+</html>
+
+

h1 "hello world" text hiding behind of navigation bar how can i fix this +note: navbar must be static in web site +THANKS

",

i fixed this problem i added after the body tag 3 times

,html +"HTML Button Alignment to be made in right of row

I want to take both the buttons to right side of the row. As you can see in the screenshot (both are left)

+

I tried different ways including float-right but it wasn't properly styling it.

+
<div class="row">
+        <div class="col-2" style='text-align: right;'>
+          <button style='width: 100% !important;' 
+            class='btn btn-theme'>VAT Details</button>
+        </div>
+        <div class="col-2">
+          <button style='width: 100% !important;' 
+            class='btn btn-theme'>NCIIC</button>
+        </div>
+    </div>
+
+

","

Try this -

+
<div class="row justify-content-end">
+        <div class="col-2" style='text-align: right;'>
+          <button style='width: 100% !important;' 
+            class='btn btn-theme'>VAT Details</button>
+        </div>
+        <div class="col-2">
+          <button style='width: 100% !important;' 
+            class='btn btn-theme'>NCIIC</button>
+        </div>
+    </div>
+
+

Since row is display flex by default you just need to add justify-content-end to the row.

",html +"Two elements absolutely positioned at the same place but not showing at the same place

So, I have these two things. One is a transparent button and the other one is an image behind it.

+

I did that because adding a background didn't work. Here's what I tried:

+
.top-container > button {
+    background-image: url(path-to-image); /* I also tried image() */
+    background-repeat: no-repeat
+    width: 100px;
+    height: 33px;
+    color: white;
+    border: none;
+    font-family: 'CapitalisTypOasis', 'CapitalisTypOasisMedium';
+    text-align: center;
+    z-index: 2;
+    position: absolute;
+    top: 1.7em;
+    padding: 0;
+}
+
+

I did all of the tiny variations I could think of, and since my deadline is soon, I put an image behind the button. Works perfectly.

+
.boutonsim { 
+    display: block;
+    height: 33px;
+    width: 100px;
+    position: absolute;
+    top: 1.7em;
+    z-index: 1;
+}
+
+.top-container > button {
+    display: block;
+    width: 100px;
+    height: 33px;
+    background-repeat: no-repeat;
+    background-color: rgba(255, 255, 255, 0);
+    color: white;
+    border: none;
+    font-family: 'CapitalisTypOasis', 'CapitalisTypOasisMedium';
+    text-align: center;
+    z-index: 2;
+    position: absolute;
+    top: 1.7em;
+    padding: 0;
+}
+
+

HTML:

+
<div class="top-container">
+            <img id="img2" src="images/haut.png" />
+            <img id="title" src="images/nom.png" />
+            <img id="logo" src="images/LOGO.png" />
+            <div class="boutonsim" style="right: 80px;"><img src="images/clipart/boutonORIGINAL.png" /></div>
+            <button style="right: 80px;">Culture</button>
+
+        </div>
+
+

They're supposed to be at the same place but when I open my file in Chrome, they're not. +Could anyone help? Thanks.

+

This is a GIF of the result in a snippet if it can help:

+

+
+
<a href=""https://gyazo.com/c849e62e7893453a2b442f2060bce1e4""><img src=""https://i.gyazo.com/c849e62e7893453a2b442f2060bce1e4.gif"" alt=""Image from Gyazo"" width=""166""/></a>
+
+
+

","

TL;DR; position them with anything but em.

+

The button must have a different font-size than the rest of the dom (which is also default behaviour), which means that the div and the button have different font-sizes. So because you are positioning them with em, they will be positioned differently (div: 27.2px and button: 22.667px), since the CSS compiler looks at the elements font-size to determine the top value in px.

",html +"Show Google Maps & YouTube videos after Cookies got accepted

I am using this plugin on my WordPress website: https://wordpress.org/plugins/cookie-notice/ and I am pretty satisfied with it because it's easy to use and lightweight.

+ +

With the latest GDPR rulings it is now needed to hide Google Maps and YouTube videos or replace them with a placeholder image as long as the visitor doesn't accept the cookie consent. Unfortunately the plugin doesn't have such a functionality.

+ +

Has anyone a sample code or an idea on how to embedd Google Maps and YouTube videos like that? All plugins that have this functionality cost around 99 $ a year, which is a bit too much for only one map and one YouTube video on my homepage...

","

Im not sure how farmiliar you are with Jquery but you could do something like this.

+ +
var cookiesAccepted = false;
+
+ +

Add 'media-blocks' class to all media you want to hide. +Set jquery to watch Cookies bar for accept click. When its clicked add a class that shows all your embedded media that you wanted to hide, eg:

+ +
$('#cookie-btn').on('click',function(){
+  var cookiesAccepted = true;
+  $('.media-blocks').addClass('show');
+
+})
+
+ +

Just a guideline of how I'd do it.

",html +"Populate list in Django using view

I have the following function to read news headlines into a Python list:

+ +
import requests
+
+
+def us_news_articles():
+    url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=###
+    source = requests.get(url)
+    data = source.json()
+    us_news_articles_list = []
+    for article in data['articles']:
+        us_news_articles_list.append(article)
+    return us_news_articles_list
+
+ +

This function works, and I've verified it.

+ +

Now I want to be able to use this to populate HTML li items

+ +

I have the following views built:

+ +
def viz(request):
+    return render(request, 'resume/viz.html')
+
+class USNewsArticles(TemplateView):
+    template_name = 'viz'
+
+    def get_context_data(self, *args, **kwargs):
+        context = {
+            'articles': us_news_articles(),
+        }
+        return context
+
+ +

My URL looks like this

+ +
path('viz/', views.viz, name='viz')
+
+ +

And in my HTML file, I have the following:

+ +
            <ul>
+            {% for article in articles %}
+              <li>{{ article.title }}</li>
+                <ul>
+                  <li>{{ article.description }}</li>
+                </ul>
+            {% endfor %}
+            </ul>
+
+ +

However, when I deploy the website, I get no list. I believe it's an issue with the view, but I am not well-versed enough in understand views and functions to understand why it will not populate the li items

","

Your URLs are routed to your viz view, which just renders an empty template (viz.html). I think what you meant to do is this:

+ +
class USNewsArticles(TemplateView):
+    template_name = 'resume/viz.html'
+
+    def get_context_data(self, *args, **kwargs):
+        context = {
+            'articles': us_news_articles(),
+        }
+        return context
+
+ +

And your URL:

+ +
path('viz/', USNewsArticles.as_view())
+
+ +

TemplateView is a helper where you specify the template file directly, and it supplies the appropriate GET handler. - no need for an intermediate def myview function. In fact, the beauty of Class-Based Views is it writes a lot of the boilerplate for you. Unless you are customizing the behavior, you generally don't have to write methods that return Responses by hand.

",html +"HTML DOM: remove specific div based on data attribute value using php

I am new in codeigniter.I get the html string form database as shown below

+ +
<div class=""rockfm-form-container uiform-wrap"">
+<div class=""rockfm-alert-container""></div>
+<form class=""rockfm-form"" action="""" name="""" method=""post"" data-zgfm-type=""1"" enctype=""multipart/form-data"" id=""rockfm_form_7"">
+<input type=""hidden"" value=""7"" class=""_rockfm_form_id"" name=""_rockfm_form_id""> 
+<input type=""hidden"" value=""0"" class=""_rockfm_wizard_st"" > 
+<input type=""hidden"" value=""PGRpdiBjbGFzcz0icm9ja2ZtLWFsZXJ0IHJvY2tmbS1hbGVydC1zdWNjZXNzIj5TdWNjZXNzISBGb3JtIHdhcyBzZW50IHN1Y2Nlc3NmdWxseS48L2Rpdj4="" name=""_rockfm_onsubm_smsg"" class=""_rockfm_onsubm_smsg"" > <!--- ajax or post ---> 
+<input type=""hidden"" value=""1"" class=""_rockfm_type_submit"" name=""_rockfm_type_submit""> 
+<input type=""hidden"" value=""rocket_front_submitajaxmode"" name=""action""> 
+<div class=""uiform-main-form"">
+ <div class=""uiform-step-content"" >
+    <div id=""rockfm_uiibpy0eewu"" data-idfield=""uiibpy0eewu"" data-typefield=""33"" class=""rockfm-heading rockfm-field "" ></div>
+    <div id=""rockfm_uiya0wevyae"" data-idfield=""uiya0wevyae"" data-typefield=""28"" class=""rockfm-preptext rockfm-field rockfm-required "" data-val-type=""4""></div>
+    <div id=""rockfm_ui04fxilqp6"" data-idfield=""ui04fxilqp6"" data-typefield=""7"" class=""rockfm-textarea rockfm-field "" ></div>
+    <div id=""rockfm_uiwdtl19w05"" data-idfield=""uiwdtl19w05"" data-typefield=""10"" class=""rockfm-select rockfm-field "" ></div>
+    <div id=""rockfm_uiksx46ggj9"" data-idfield=""uiksx46ggj9"" data-typefield=""12"" class=""rockfm-fileupload rockfm-field "" ></div>
+    <div id=""rockfm_ui2jrdo8mcp"" data-idfield=""ui2jrdo8mcp"" data-typefield=""20"" class=""rockfm-submitbtn rockfm-field "" ></div>
+ </div>
+</div>
+</form>
+</div>
+
+ +

I have another table of typefields as shown in image

+ +

+ +

html string is convert into DOM and add check condition of if typefieldid = 10 is flag_status = 0 then remove this div only <div id=""rockfm_uiwdtl19w05"" data-idfield=""uiwdtl19w05"" data-typefield=""10"" class=""rockfm-select rockfm-field "" ></div> but this gave me code like this

+ +
<div id=""rockfm_uiibpy0eewu"" data-idfield=""uiibpy0eewu"" data-typefield=""33"" class=""rockfm-heading rockfm-field ""></div>
+<div id=""rockfm_uiya0wevyae"" data-idfield=""uiya0wevyae"" data-typefield=""28"" class=""rockfm-preptext rockfm-field rockfm-required ""></div>
+<div id=""rockfm_ui04fxilqp6"" data-idfield=""ui04fxilqp6"" data-typefield=""7"" class=""rockfm-textarea rockfm-field ""></div>
+<div id=""rockfm_uiksx46ggj9"" data-idfield=""uiksx46ggj9"" data-typefield=""12"" class=""rockfm-fileupload rockfm-field ""></div>
+<div id=""rockfm_ui2jrdo8mcp"" data-idfield=""ui2jrdo8mcp"" data-typefield=""20"" class=""rockfm-submitbtn rockfm-field ""></div>
+
+ +

Issue is that when typefield = 10 is flag_status = 0 its remove <div id=""rockfm_uiwdtl19w05"" data-idfield=""uiwdtl19w05"" data-typefield=""10"" class=""rockfm-select rockfm-field "" ></div> but other information in html string is also remove. I show code of controller function where I html string converted into DOM documents, get the record of fby_id and flag_status form typefields table and making an array of this record. Then make a foreach loop of data-typefield using DOM query for getting attribute value of data-typefield then add check condition for if 0 = 1 then remove specific div

+ +

One more issue is that how to pass and show final data in view file after removing specific div based on condition. Here is code of controller function

+ +
public function getform() {
+
+$form_id = ($this->input->post('id')) ? Uiform_Form_Helper::sanitizeInput($this->input->post('id')) : 0;
+
+$data = array();
+
+if (intval($form_id) === 0) {
+    return;
+} else {
+
+
+    $rdata = $this->model_forms->getFormById($form_id);
+}
+
+
+$response = array();
+if (!empty($rdata)) {
+    $response['html_content'] = Uiform_Form_Helper::encodeHex($rdata->fmb_html);
+}
+
+$html = $rdata->fmb_html;
+$doc = new DOMDocument();
+$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
+$xpath = new DOMXPath($doc);
+
+$fields = $this->model_fields->getAllFieldsType();
+
+$field_array =array();
+ foreach ($fields as $value) {
+
+    $field_array[$value->fby_id] = $value->flag_status;
+
+}
+
+foreach ($xpath->query(""//div[@data-typefield]"") as $item) 
+{
+
+    $typefield = $item->getAttribute('data-typefield');
+
+    if($field_array[$typefield] == 1)
+    {
+        $item->outertext = '';
+
+        $doc->saveHTML($item);
+    }
+
+
+}
+
+$data = array();
+
+$json = $response;
+$data['json'] = $response;
+
+$this->load->view('html_view', $data);
+}
+
+ +

and please guide me is there any option to remove only specific div from HTML DOM. I want my code output like this way

+ +
<div class=""rockfm-form-container uiform-wrap"">
+<div class=""rockfm-alert-container""></div>
+<form class=""rockfm-form"" action="""" name="""" method=""post"" data-zgfm-type=""1"" enctype=""multipart/form-data"" id=""rockfm_form_7"">
+<input type=""hidden"" value=""7"" class=""_rockfm_form_id"" name=""_rockfm_form_id""> 
+<input type=""hidden"" value=""0"" class=""_rockfm_wizard_st"" > 
+<input type=""hidden"" value=""PGRpdiBjbGFzcz0icm9ja2ZtLWFsZXJ0IHJvY2tmbS1hbGVydC1zdWNjZXNzIj5TdWNjZXNzISBGb3JtIHdhcyBzZW50IHN1Y2Nlc3NmdWxseS48L2Rpdj4="" name=""_rockfm_onsubm_smsg"" class=""_rockfm_onsubm_smsg"" > <!--- ajax or post ---> 
+<input type=""hidden"" value=""1"" class=""_rockfm_type_submit"" name=""_rockfm_type_submit""> 
+<input type=""hidden"" value=""rocket_front_submitajaxmode"" name=""action""> 
+<div class=""uiform-main-form"">
+  <div class=""uiform-step-content"" >
+     <div id=""rockfm_uiibpy0eewu"" data-idfield=""uiibpy0eewu"" data-typefield=""33"" class=""rockfm-heading rockfm-field "" ></div>
+     <div id=""rockfm_uiya0wevyae"" data-idfield=""uiya0wevyae"" data-typefield=""28"" class=""rockfm-preptext rockfm-field rockfm-required "" data-val-type=""4""></div>
+     <div id=""rockfm_ui04fxilqp6"" data-idfield=""ui04fxilqp6"" data-typefield=""7"" class=""rockfm-textarea rockfm-field "" ></div>
+     <div id=""rockfm_uiksx46ggj9"" data-idfield=""uiksx46ggj9"" data-typefield=""12"" class=""rockfm-fileupload rockfm-field "" ></div>
+     <div id=""rockfm_ui2jrdo8mcp"" data-idfield=""ui2jrdo8mcp"" data-typefield=""20"" class=""rockfm-submitbtn rockfm-field "" ></div>
+   </div>
+ </div>
+ </form>
+</div>
+
","

Your code is mostly there, but the main part is removing the node, I've changed the test to say if the status = 0, then use removeChild() to get rid of the element. Then the document should only contain the <div> elements you want at the end...

+ +
foreach ($xpath->query(""//div[@data-typefield]"") as $item)
+{
+    $typefield = $item->getAttribute('data-typefield');
+    if($field_array[$typefield] == 0)
+    {
+        $item->parentNode->removeChild($item);
+    }
+}
+
+echo $doc->saveHTML();
+
",html +"Prevent from closing on keydown Esc in Chrome

Google Chrome closes <dialog> elements when Esc is pressed. Seems to be reacting to keydown.

+ +

Firefox does not. This is the expected behavior, as closing on any key press is easy to implement.

+ +

How to make Google Chrome leave dialogs open on Esc?

+ +

Please see fiddle https://jsfiddle.net/zeqo7kaf/1/

+ +

I have implemented window's, document's, body's, dialog's key events (up, down and pressed) to prevent propagation, however it seems to me that this is above dom events.

+ +

(in order to see dialogs in Firefox, go to about:config and set property dom.dialog_element.enabled to true).

","

You can try to use cancel event: MDN

+ +
dialog.addEventListener('cancel', (event) => {
+    event.preventDefault();
+});
+
+ +

Modified JSFiddle: https://jsfiddle.net/7et3hf8p/

",html +"Adding previously saved getImageData of canvas on top of other image

I'm trying to cover the whole canvas with an image while letting a transparent hole in it.

+ +

Basically I have a game with a player on it. I want to cover the whole game with an image except for the position of the player. This works fine when I consider a fill option with color but I want to do it with an image. Below is my (failing) code :

+ +
var img = new Image();
+
+img.onload = function() {
+
+  ctx.clearRect(0, 0, width, height);
+
+  drawMap(); // draws my ""hidden game""
+
+  ctx.beginPath();
+  ctx.fillStyle = visionRadial(game.p1.px, game.p1.py);
+  ctx.rect(game.p1.px - 50, game.p1.py - 50, 100, 100);
+  ctx.fill(); // this gives me a transparent circle around the position of the player.
+
+  // Trying to save the image around my player
+  var p1 = ctx.getImageData(game.p1.px - 50, game.p1.py - 50, 100, 100);
+
+  // Image to cover the board game
+  ctx.drawImage(img, 0, 0);
+
+  // Adding back the player position (transparent lens)
+  ctx.putImageData(p1, game.p1.px - 50, game.p1.py - 50);
+
+};
+
+img.src = 'example.jpg';
+
+ +

But this does not work. It seems like when I'm saving the part of previous image in p1, the image does not display anymore...

+ +

What am I missing here ?

+ +

Thanks a lot !

","

Canvas, a drawable image

+

The functionsgetImageData and putImageData are just for manipulating pixels. Using pixel data to render is VERY slow as pixel data is not rendered by the GPU, does not do transparency, filters, composites, scaling, etc. Almost useless as a rendering source

+

Rather than store the image as pixel data create a second canvas, draw what you need on it and use it as an image with full hardware support and all the other stuff you can do with images.

+

Example

+

Modifying your code to use a canvas to hold the overlay.

+
// creates a canvas, size w, h , and copies canvasToCopy onto it at x, y 
+function createOverlay(canvasToCopy, x, y, w, h) {
+    const overlay = document.createElement("canvas");
+    overlay.width = w;
+    overlay.height = h;
+    const ctx = overlay.getContext("2d");
+    ctx.drawImage(canvasToCopy, -x, -y);  // copies canvas to overlay
+    return overlay;
+}
+var overlay; // to hold overlay image (a canvas)
+var img = new Image();
+img.src = "example.jpg";
+img.onload = () => {
+  ctx.clearRect(0, 0, width, height);
+  drawMap(); 
+  ctx.beginPath();
+  ctx.fillStyle = visionRadial(game.p1.px, game.p1.py);
+  ctx.rect(game.p1.px - 50, game.p1.py - 50, 100, 100);
+  ctx.fill(); 
+
+  // copy current canvas content to overlay
+  overlay = createOverlay(ctx.canvas, game.p1.px - 50, game.p1.py - 50, 100, 100);
+
+  ctx.drawImage(img, 0, 0);
+
+  // draw overlay over canvas content
+  ctx.drawImage(overlay, game.p1.px - 50, game.p1.py - 50);
+
+  img.onload = undefined; // never leave an onload (any unused event) set once done
+                          // De-reference so resources closed over can be set free
+
+};
+
",html +"How to force an input html element to show only the last inputted character

I want to create an input:

+ +
<input type='text' id='in'></input>
+
+ +

When the user types a character the input will hold that character. +But when the user types a different character, the input will hold the new character. How can I do this?

","

Follows an example:

+ +

+
+
<input type='text' id='in' onkeydown=""this.value = ''""></input>
+
+
+

",html +"Nested table with data tables

I have the following nested HTML table. I am using the Datatables API to make my tables searchable. One problem I have faced is with the nested tables I'm not sure how to make the nested tables searchable? I have tried adding additional ID tags to the nested tables HTML code and adding that into the dataTables JS code call but that did not work. Any idea how to make the sub-tables searchable?

+ +

+
+
<link href=""https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"" rel=""stylesheet"" />
+<script src=""https://code.jquery.com/jquery-3.3.1.js""></script>
+<script src=""https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js""></script>
+
+
+<script>
+  $(document).ready(function() {
+    $('#example').DataTable();
+} );
+</script>
+
+
+<div class=""container"">
+    <table id=""example"" class=""table table-striped"">
+        <thead>
+            <tr>
+                <th>Image</th>
+                <th>Date</th>
+                <th>TC NAME</th>
+                <th>NS FLOW</th>
+                <th>SN FLOW</th>
+                <th>NS FLOW</th>
+                <th>SN FLOW</th>
+                <th>NS FLOW</th>
+                <th>SN FLOW</th>
+            </tr>
+        </thead>
+        <tbody>
+
+            <tr>
+                <td>721</td>
+                <td>3/15/20</td>
+
+                <td>
+                    <table id=""example1"" class=""table table-nostriped"">
+                        <tr>
+                            <td>TC1</td>
+                        </tr>
+                        <tr>
+                            <td>TC2</td>
+                        </tr>
+                        <tr>
+                            <td>TC3</td>
+                        </tr>
+                    </table>
+
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>600</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>800</td>
+                        </tr>
+                        <tr>
+                            <td>400</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+            </tr>
+
+
+
+
+
+        <tr>
+                <td>722</td>
+                <td>3/16/20</td>
+
+                <td>
+                    <table class=""table table-nostriped"">
+                        <tr>
+                            <td>TC1</td>
+                        </tr>
+                        <tr>
+                            <td>TC2</td>
+                        </tr>
+                        <tr>
+                            <td>TC3</td>
+                        </tr>
+                    </table>
+
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>600</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>800</td>
+                        </tr>
+                        <tr>
+                            <td>400</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+            </tr>
+
+
+
+
+        <tr>
+                <td>633</td>
+                <td>3/17/20</td>
+
+                <td>
+                    <table class=""table table-nostriped"">
+                        <tr>
+                            <td>TC1</td>
+                        </tr>
+                        <tr>
+                            <td>TC2</td>
+                        </tr>
+                        <tr>
+                            <td>TC3</td>
+                        </tr>
+                    </table>
+
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>600</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>800</td>
+                        </tr>
+                        <tr>
+                            <td>400</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                    </table>
+                </td>
+
+                <td>
+                 <table class=""table table-nostriped"">
+                        <tr>
+                            <td>100</td>
+                        </tr>
+                        <tr>
+                            <td>200</td>
+                        </tr>
+                        <tr>
+                            <td>300</td>
+                        </tr>
+                    </table>
+                </td>
+
+            </tr>
+
+        </tbody>
+    </table>
+</div>
+
+
+

","

If you by ""searchable"" mean DataTables inside DataTables you can use the createdRow callback to initialize tables inside a <tr>'s columns.

+ +

You must have a columns section in order to compensate for the missing <thead> in the nested tables (avoiding the TypeError: col is undefined error) :

+ +
const columns = [
+  { title: '' },
+]
+
+ +

Init the nested tables in the createdRow callback:

+ +
let table = $('#example').DataTable({
+  createdRow: function(row) {
+    $(row).find('td table')
+      .DataTable({
+        columns: columns,
+        dom: 'tf'
+      })
+  }
+})
+
+ +

Notice the dom section. Here only showing the table itself and the filter box. You +can remove the header with

+ +
table.dataTable td table thead {
+  display: none;
+}
+
+ +

Dont add this CSS if you want sortable columns in the nested tables.

+ +

demo using the markup in question -> http://jsfiddle.net/davidkonrad/8pzkr6yn/

+ +
+ +

Update. If your concern just is to be able to search within the content of the nested tables (e.g the HTML markup scraped away) just define the relevant columns type as 'html' (https://datatables.net/reference/option/columns.type) :

+ +
let table = $('#example').DataTable({
+  columnDefs: [
+    { targets: [2,3,4,5,6,7], type: 'html' },
+  ],
+  ...
+})
+
",html +"How to create html rows and cols

How to make only three rows with three elements in each from array with coordinates. So far I'm making duplicated rows whit elements

+ +
let container = document.querySelector('.container');
+let arr = [{i: 0, j: 0}, {i: 0, j: 1}, {i: 0, j: 2}, {i: 1, j: 0}, {i: 1, j: 1}, {i: 1, j: 2}, {i: 2, j: 0}, {i: 2, j: 1}, {i: 2, j: 2}];
+function drawHtml(){    
+    arr.forEach(cell => {       
+        container.innerHTML += `
+            <div class=""row row-${cell.i}"">
+                <div class=""cell-row cell-${cell.j}"">
+                    <img src=""https://via.placeholder.com/100"" alt="""">
+                </div>
+            </div>`
+    }); 
+}
+drawHtml()
+
+ +

the end result should be like this

+ +
    <div class=""container"">
+            <div class=""row row-0"">
+                <div class=""cell-row cell-0"">
+                    <img src=""https://via.placeholder.com/100"" alt="""">
+                </div>
+                <div class=""cell-row cell-1"">
+                    <img src=""https://via.placeholder.com/100"" alt="""">
+                </div>
+                ...
+            </div>
+            <div class=""row row-1"">
+                <div class=""cell-row cell-0"">
+                    <img src=""https://via.placeholder.com/100"" alt="""">
+                </div>
+                <div class=""cell-row cell-1"">
+                    <img src=""https://via.placeholder.com/100"" alt="""">
+                </div>
+                ....
+            </div>
+            ....
+            </div>
+    </div>
+
+
","

Can you try the below code

+ +

+
+
<div id=""pContainer"" class=""container""></div>    
+<script>
+
+    let container = document.querySelector('.container');
+    let arr = [{i: 0, j: 0}, {i: 0, j: 1}, {i: 0, j: 2}, {i: 1, j: 0}, {i: 1, j: 1}, {i: 1, j: 2}, {i: 2, j: 0}, {i: 2, j: 1}, {i: 2, j: 2}];
+    function drawHtml(){    
+    var innerHTML='';
+    var i=0,tmp=0;
+    innerHTML+='<div class=""row row-0"">';
+    arr.forEach(cell => {       
+        i = parseInt(cell.i);
+        if(tmp != i)
+            innerHTML+='</div><div class=""row row-'+cell.i+'"">';
+        innerHTML+='<div class=""cell-row cell-'+cell.j+'"">';
+        innerHTML+='<img src=""https://via.placeholder.com/100"" alt="""">';
+        innerHTML+='</div>';
+        
+        tmp = i;
+    }); 
+    innerHTML+='</div>';
+    container.innerHTML = innerHTML;
+    }
+    drawHtml()    
+</script>
+
+
+

",html +"center cards but with a left justify?

I have an unknown number of fixed-size cards displayed in a fluid container. I want the rows centered but the problem comes in when there's an uneven number of cards to fill a row. It'll center two cards underneath a row display 5 cards. I'd like for those 2 cards to justify to the left so everything remains vertically inline. If I align everything to the left, then I can end up with an uneven margin on the left and right side of the outer columns. For instance, the screen width might only have room to display 4 cards in a row, but the spacing to the right left to fill could be anywhere from 0 to 300px (the size of a card). Hopefully that makes sense. If not I'll draw pictures to illustrate what I mean.

+ +

https://www.codeply.com/p/pOnFgE1lTs

+ +
<div class='container-fluid'>
+    <div class='row'>
+        <div class='col-md-10 offset-md-1'>
+            <div class='card-deck'>
+
+                <!-- repeat this block for X-number of cards -->
+                <div class=""card mb-4 game-card mx-auto"">
+                    <img class=""card-img-top"" src=""#"">
+                    <div class=""card-body text-center"">
+                        <h4 class=""card-title text-center"">Game Title</h4>
+                        <p class=""card-text"" style=""text-align:justify"">title here</p>
+                        <a href="""" class=""btn btn-sm btn-primary"">View</a>
+                    </div>
+                </div>
+
+            </div>
+        </div>
+    </div>
+</div>
+
+.game-card{max-width:300px;width:300px;min-width:300px}
+
","

I found this example which I think will meet my needs. I'm not really sure what its doing yet, I've never dealt with scss before.

+ +
// Bootstrap 4 breakpoints & gutter
+$grid-breakpoints: (
+    xs: 0,
+    sm: 576px,
+    md: 768px,
+    lg: 992px,
+    xl: 1200px
+) !default;
+
+$grid-gutter-width: 30px !default;
+
+// number of cards per line for each breakpoint
+$cards-per-line: (
+    xs: 1,
+    sm: 2,
+    md: 3,
+    lg: 4,
+    xl: 5
+);
+
+@each $name, $breakpoint in $grid-breakpoints {
+    @media (min-width: $breakpoint) {
+        .card-deck .card {
+            flex: 0 0 calc(#{100/map-get($cards-per-line, $name)}% - #{$grid-gutter-width});
+        }
+    }
+}
+
+ +

https://codepen.io/migli/pen/OQVRMw

",html +"Control multiple range sliders Django form

What I want: +Multiple Range sliders (the number changes based on user selections) on one page, moving the sliders should update the value and display this in a span element as well as update the model.

+ +

The problem: +Unfortunately I don't know how to change the values of sliders when there are multiple sliders that are created with a forloop. The span element does not get update and the value element of the slider also does not change when I move the slider handle of a slider.

+ +

Html:

+ +
<form method=""post"">
+formset1.management_form }}
+for form in formset1 %}
+    <div class=""custom-slider-container"">
+        <label>{{ form.name.value }}</label>
+        <span id=""demo-{{ forloop.counter0 }}"" class=""range-val"">0</span>
+        {{ form.weight }}
+    <div>
+{% endfor %}
+</form>
+
+ +

Views.py:

+ +
initial = Driver.objects.filter(simulation=chosenSim, type='KEY_OUTPUT')
+formset = sliders_formset(request.POST or None, queryset=initial)
+    if 'sliders_confirm' in request.POST:
+        if formset.is_valid():
+            instances = formset.save(commit=False)
+            for form in instances:
+                form.save()
+        return HttpResponseRedirect(request.path_info)
+
+ +

Forms.py

+ +
sliders_formset = modelformset_factory(Driver, fields=['name', 'weight'], extra=0,
+                                   widgets={'weight': RangeInput(attrs={'class': 'custom-slider', 'max': 20})})
+
+ +

If any other information is needed, please let me know and I'll add it!

","

Using ""each"" solved my problem!

+ +
<script>
+    var rangeSlider = function(){
+        var slider = $('.custom-slider-container'),
+        range = $('.custom-slider'),
+        value = $('.range-val-label');
+
+        range.each(function(){
+            var range_val = $(this).attr('value');
+            var range_val = Math.trunc(range_val);
+            $(this).prev().html(range_val);
+        });
+
+        slider.each(function(){
+
+            value.each(function(){
+                var value = $(this).next().attr('value');
+                $(this).html(value);
+            });
+
+            range.on('input', function(){
+                $(this).prev(value).html(this.value);
+            });
+        });
+    };
+rangeSlider();
+</script>
+
",html +"USGA - GHIN 2nd Page Information - Get The Info from a 2nd web page after an XML log in

I got excellent help from ""asmitu"" who helped me log-in to the USGA GHIN site with the following code. However, my real end problem was to log-In and then maneuver to this 2nd URL (“https://www.ghin.com/golfer-lookup/following“) to extract my data that is stored on the 2nd URL page. Is there a way to modify the code below so that I land on the 2nd page after login?

+ +
Sub GHIN_Login()
+
+Const Url = ""https://api2.ghin.com/api/v1/public/login.json?""
+Dim Http As New XMLHTTP60, ghinNum$, lastName$
+
+ghinNum = """"            'put your ghinNum here
+lastName = """"           'put your lastName here
+
+With Http
+  .Open ""GET"", Url & ""ghinNumber="" & ghinNum & ""&lastName="" & lastName & ""&remember_me=false"", False
+  .setRequestHeader ""User-Agent"", ""Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36""
+  .setRequestHeader ""Referer"", ""https://www.ghin.com/login""
+  .send
+End With
+
+MsgBox Http.responseText
+End Sub
+
","

The content of that target page generates dynamically, so you can't parse the required fields using xhr. However, the following attempt should lead you grab the json response having required fields within it.

+ +
Sub GetInformation()
+    Const Url = ""https://api2.ghin.com/api/v1/public/login.json?""
+    Const Link = ""https://api2.ghin.com/api/v1/followed_golfers/""
+    Dim Http As New XMLHTTP60, ghinNum$, lastName$
+
+    ghinNum = """"
+    lastName = """"
+
+    With Http
+        .Open ""GET"", Url & ""ghinNumber="" & ghinNum & ""&lastName="" & lastName & ""&remember_me=false"", False
+        .setRequestHeader ""User-Agent"", ""Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36""
+        .setRequestHeader ""Referer"", ""https://www.ghin.com/login""
+        .send
+        .Open ""GET"", Link & ghinNum & "".json"", False
+        .send
+    End With
+
+    MsgBox Http.responseText
+End Sub
+
",html +"how can i convert table row and columns a scroll table at ie8?

i want to convert row and column(it's a x-scrollable table) +my solution works at ie11 and chrome +but this one doesn't work at ie8 +i have to make this work at ie8 +but i have no idea how to make it work...

+ +

i think i have to replace flex to something.. +i googled about it but i couldn't find it...

+ +

please teach me how to fix it...:(

+ +

+
+
table{
+display: -webkit-box;
+display: -ms-flexbox;
+overflow-x: auto;
+overflow-y: hidden;
+}
+
+tbody
+{display:flex}
+
+th,td{display:block}
+
<html lang=""en"">
+  <head>
+    <meta charset=""utf-8"">
+    <title>HTML</title>
+    <style>
+      table {
+        width: 100%;
+      }
+      table, th, td {
+        border: 1px solid #bcbcbc;
+      }
+    </style>
+  </head>
+  <body>
+    <table>
+      <thead>
+        <tr>
+          <th>col</th>
+          <th>col</th>
+          <th>col</th>
+          <th>col</th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr>
+          <th>row</th>
+          <td>Dolor</td>
+          <td>Dolor</td>
+          <td>Dolor</td>
+        </tr>
+        <tr>
+          <th>row</th>
+          <td>Dolor</td>
+          <td>Dolor</td>
+          <td>Dolor</td>
+        </tr>
+        <tr>
+          <th>row</th>
+          <td>Dolor</td>
+          <td>Dolor</td>
+          <td>Dolor</td>
+        </tr>
+      </tbody>
+    </table>
+  </body>
+</html>
+
+
+

","

I tried to search and found that CSS only examples use Flex and Grid which is not supported in IE 8 browser.

+ +

As a workaround, you can try to use the Javascript code to convert table row to column.

+ +

Example:

+ +

+
+
<!doctype html>
+<html>
+<head>
+<style>
+#btn, #tbl2container {margin-top: 10px;}
+td {
+    padding: 5px;
+    border: 1px dotted gray;
+}
+</style>
+
+</head>
+<body>
+<div id=""table_container"">
+    <table id=""tbl1"">
+        <tr>
+            <td>A1</td>
+            <td>A2</td>
+            <td>A3</td>
+            <td>A4</td>
+            <td>A5</td>
+        </tr>
+        <tr>
+            <td>B1</td>
+            <td>B2</td>
+            <td>B3</td>
+            <td>B4</td>
+            <td>B5</td>
+        </tr>
+        <tr>
+            <td>C1</td>
+            <td>C2</td>
+            <td>C3</td>
+            <td>C4</td>
+            <td>C5</td>
+        </tr>
+    </table>
+</div>
+<button id=""btn"" onclick=""clk()"">Convert Table</button>
+<div id=""tbl2container""></div>
+<script>
+function convertTable(tbl) {
+    var rows = tbl.rows.length;
+    var cols = tbl.rows[0].cells.length;
+    var tbl2 = document.createElement('table');
+
+    for (var i = 0; i < cols; i++) {
+        var tr = document.createElement('tr');
+        for (var j = 0; j < rows; j++) {
+            var td = document.createElement('td');
+            var tdih = tbl.rows[j].cells[i].innerHTML;
+            td.innerHTML = tdih;
+            tr.appendChild(td);
+        }
+        tbl2.appendChild(tr);
+    }
+    return tbl2;
+}
+
+//test
+var btn = document.getElementById('btn');
+
+function clk() {
+    this.disabled = true;
+    var t1 = document.getElementById('tbl1');
+    var t2 = convertTable(t1);
+    document.getElementById('tbl2container').appendChild(t2);
+}
+</script>
+</body>
+</html>
+
+
+

+ +

Output in IE 11 with (IE 8) document mode:

+ +

+ +

Reference:

+ +

JSFiddle example

+ +

The IE 8 is too old and out of support scope of Microsoft. If possible then try to use the latest Microsoft browsers. If you have to use the IE browser then at least move to the IE 11 browser.

",html +"How to display a typescript string variable containing html content on the template as an element, and not string?

I have an angular application, I have the following in component typescript:

+ +
field: string;
+  constructor() { 
+    this.field = ""Hello, I am <b>happy</b><br><br><input type='text' value='hello' />""
+  }
+
+ +

and in my html template for the component I have this:

+ +
<div [innerHTML]=""field""></div>
+
+ +

I am expecting an output:

+ +
Hello, I am happy(happy in bold)
+
+[Text input field here]
+
+
+ +

Instead the entire input tag is omitted. Any idea how to render html content like this onto a template in angular?

","

You will have to trust the HTML first before injecting it. You have to use the DomSanitizer for such a thing. An h3 or p or div element is considered safe. An input element is not.

+ +

You can create a pipe and use it where ever you need it.

+ +
import { Pipe, PipeTransform } from '@angular/core';
+import { DomSanitizer } from '@angular/platform-browser';
+
+@Pipe({
+    name: 'sanitizeHtml'
+})
+export class SanitizeHtml implements PipeTransform  {
+
+   constructor(private _sanitizer: DomSanitizer){}  
+
+   transform(v: string) : SafeHtml {
+      return this._sanitizer.bypassSecurityTrustHtml(v); 
+   } 
+} 
+
+ +

Now in you html you can call the pipe in this way :

+ +
<div [innerHTML]=""field | sanitizeHtml""></div>
+
",html +"Show Loading indicator on Bootstrap 4 (Modal) dialog

I have a simple question about Bootstrap 4 with simple trick +I want to show a Loading indicator such as Twitter in Every time the user opens the modal. +I make some codes and it works well but I lost some pieces ....

+ +

Button HTML Codes :

+ +
<a href=""#example_Modal"" role=""button"" data-toggle=""modal"" data-target=""#example_Modal"">Click here</a>
+
+ +

Modal HTML Codes

+ +
<div class=""modal fade"" id=""example_Modal"" tabindex=""-1"" role=""dialog"" aria-labelledby=""example_ModalLabel"" aria-hidden=""true""data-backdrop=""static"" data-keyboard=""false"">
+<div class=""modal-dialog"" role=""document"">
+<div class=""modal-content"">
+
+<!-- Preloader -->
+<div id=""modal-preloader"">
+    <div class=""modal-preloader_status"">
+        <div class=""modal-preloader_spinner"">
+            <div class=""d-flex justify-content-center"">
+                <div class=""spinner-border"" role=""status""></div>
+            </div>
+        </div>
+    </div>
+</div>
+<!-- End Preloader -->
+
+<div class=""modal-body""></div>
+<div class=""modal-footer""></div>
+
+</div>
+</div>
+</div>
+
+ +

Jquery Codes

+ +
$('#example_Modal').on('shown.bs.modal', function () {
+    $(""#modal-preloader"").delay(5000).fadeOut(100);
+});
+
+ +

as you can see here it work well but I want the Loading indicator spinner show eveytime when the user close the modal and open it again I think I explain well what I Want... thank you

","

You can achieve that by defining handler when modal closes. Please run the working code snippet below.

+ +

+
+
$('#example_Modal').on('shown.bs.modal', function () {
+    $(""#modal-preloader"").delay(5000).fadeOut(100);
+});
+
+// reset loading display when modal is closed
+$('#example_Modal').on('hidden.bs.modal', function (e) {
+   $(""#modal-preloader"").show();
+})
+
<html>
+  <head>
+    <script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+    <link rel=""stylesheet"" href=""https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"" integrity=""sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"" crossorigin=""anonymous"">
+    <script src=""https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"" integrity=""sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"" crossorigin=""anonymous""></script>
+    <script src=""https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"" integrity=""sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"" crossorigin=""anonymous""></script>
+  </head>
+
+  <body>
+    <a href=""#example_Modal"" role=""button"" data-toggle=""modal"" data-target=""#example_Modal"">Click here</a>
+    <div class=""modal fade"" id=""example_Modal"" tabindex=""-1"" role=""dialog"" aria-labelledby=""example_ModalLabel"" aria-hidden=""true"" data-backdrop=""static"" data-keyboard=""false"">
+      <div class=""modal-dialog"" role=""document"">
+        <div class=""modal-content"">
+
+          <!-- Preloader -->
+          <div id=""modal-preloader"">
+            <div class=""modal-preloader_status"">
+              <div class=""modal-preloader_spinner"">
+                <div class=""d-flex justify-content-center"">
+                  <div class=""spinner-border"" role=""status""></div>
+                </div>
+              </div>
+            </div>
+          </div>
+          <!-- End Preloader -->
+
+          <div class=""modal-body""></div>
+          <div class=""modal-footer"">
+            <button type=""button"" class=""btn btn-secondary"" data-dismiss=""modal"">Close</button>
+          </div>
+        </div>
+      </div>
+    </div>
+  </body>
+
+</html>
+
+
+

+ +

There is also other way to achieve that by simply modifying the shown.bs.modal handle like this:

+ +
$('#example_Modal').on('shown.bs.modal', function () {
+  $(""#modal-preloader"").show().delay(5000).fadeOut(100);
+});
+
+ +

but it appears glitchy when you re-open the modal. So i recommend using hidden.bs.modal to reset the loading section display inside the modal.

+ +

I hope this answers your question.

",html +"how to make div in one box with side by side for currency input

how to make box like above ? in pure css without boostrap

+ +

why i asked this because i don't use bootstrap 4 and can't find any way to use it with boostrap 3, i was trying to make one but it was the box become like a column down

+ +

here is my css:

+ +
.currency {
+  white-space: nowrap;
+  max-width: 150px;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  float:left;
+  border: 2px solid;
+}
+
+ +

and my htlm

+ +
<div>
+  <label class=""currency""></label>
+  <input type=""text""> 1000
+</div>
+
","

The wrapper could be a label element, the currency sign can be the ::before pseudoelement which can read a data-* attribute on the label itself.

+ +

+
+
label {
+   border: 2px #ccc solid;
+   border-radius: .5em;
+   display: inline-flex;
+   color: #666;
+   overflow: hidden;
+   font: 2rem Verdana;
+}
+
+label:before {
+   content: attr(data-currency);
+   width: 2.5em;
+   padding: .5em 0;
+   background: #e6e6e8;
+   text-align: center;
+   font: inherit;
+   border-right: inherit;
+}
+
+input {
+   border: 0;
+   padding: .25em .75em;
+   font: inherit;
+   color: inherit;
+}
+
<label aria-label=""Enter the amount in €"" data-currency=""€"">
+   <input type=""text"" />
+</label>
+
+
+

",html +"Save html table data locally with electron

I'm new to coding and its a lot of try and error. Now I'm struggling with html tables.

+

For explanation: I am building an Electron Desktop application for stocks. I am able to input the value via GUI in an html table, and also export this as Excel file. But, every time I reload the app, all data from the table are gone. It would be great to save this data permanently, and simply add new data to the existing table after an application restart.

+

What's the best way to achieve this?

+

In my mind, it would the best way to overwrite the existing Excel file with the new work (old and new data from the table), because it would be easy to install the tool on a new PC and simply import the Excel file to have all data there. I don't have access to a web server, so I think a local Excel file would be better than a php solution.

+

Thank you.

+
<table class="table" id="tblData"  >
+    <tr>
+            <th>Teilenummer</th>
+            <th>Hersteller</th>
+            <th>Beschreibung</th>
+
+        </tr>
+
+</table>
+
+

This is the actual table markup.

","

Your question has two parts, it seems to me.

+ +
    +
  1. data representation and manipulation
  2. +
  3. data persistence
  4. +
+ +

For #1, I'd suggest taking a look at Tabulator, in particular its methods of importing and exporting data. In my projects, I use the JSON format with Tabulator and save the data locally so it persists between sessions.

+ +

So for #2, how and where to save the data? Electron has built-in methods for getting the paths to common user directories. See app.getPath(name). Since it sounds like you have just one file to save, which does not need to be directly accessible to the user, appData is probably a good place to store it.

+ +

As for the ""how"" to store it – you can just write a file to that path using Node fs, though I like fs-jetpack too. Tabulator can save data as well.

+ +

Another way to store data is with electron-store. It works very well, though I've only used it with small amounts of data.

+ +

So the gist is that when your app starts, it loads the data and when the app quits, it saves the data, along with any changes which have been made, though I'd suggest saving after every change.

+ +

So, there are lots of options depending on your needs.

",html +"JS code to pull Youtube Livestream Video ID

I'm looking to create a webpage that features my channel's livestream, but also displays the livestream chat. Using an iframe code src targetting the channels livestream I was able to get the site to display whatever video is being livestreamed at that moment:

+ +
+

src=""https://www.youtube.com/embed/live_stream?channel=MY_CHANNEL_ID""

+
+ +

However using Youtube Chat iFrame code, I can only target a specific video's chat.

+ +
+

src=""https://www.youtube.com/live_chat?v=VIDEO_ID&embed_domain=MY_DOMAIN

+
+ +

As such, I am trying to use JS code to pull the livestream video ID from the livestream iFrame for use in the live-chat iframe. Using the developers console, I have determined that the following code works to pull the Video ID, however I have run into an error due to trying to access a cross-origin iframe.

+ +

Code: +(Developed using code from get youtube video id from iframe video & get element from within an iframe)

+ +
var iframe = document.getElementById('live-video');
+var livevid = iframe.contentWindow.document.querySelector(""link[href^='https://www.youtube.com/watch?v=']"").href,
+    regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/,
+    videoId = livevid.match(regExp);
+
+if (videoId && videoId[1].length === 11) {
+    console.log(videoId[1]);
+}
+
+ +

This code returns the correct video ID & URL if I use developer tools to manually edit the contained within Youtube's iFrame. When I do not manually edit the code, it returns the following error

+ +

Error:

+ +
+

Uncaught DOMException: Blocked a frame with origin ""MY_DOMAIN"" from accessing a cross-origin frame.

+
+ +

From my research, you can use document.postmessge to bypass cross-origin errors on Youtube, but I am at a loss on how to implement that into my code, or if it would even work to resolve the issue I am facing.

+ +

Any help you can offer would be greatly appreciated!

","

Realized after some further thought that the nature of iFrames would block any attempts I made to access their DOM content; so I worked with the Youtube API to create a workaround:

+ +
/*Access Youtube iframe API*/
+<script src=""https://www.youtube.com/iframe_api""></script>
+
+/*Insert Livestream Video*/
+<iframe id=""live-video"" src=""https://www.youtube.com/embed/live_stream?channel=[MY_CHANNEL_ID]&enablejsapi=1&version=3&origin=[MY_DOMAIN_HERE]"" width=""560"" height=""315"" frameborder=""0"" allow=""accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"" allowfullscreen enablejsapi=""1""></iframe>
+
+/*Basic API code for Youtube videos*/
+<script>
+  var player;
+function onYouTubeIframeAPIReady() {
+  player = new YT.Player('live-video', {
+    events: {
+      'onReady': onPlayerReady,
+      'onStateChange': onPlayerStateChange
+    }
+  });
+}
+function onPlayerReady() {
+  var url = player.getVideoUrl(); /*Use Youtube API to pull Video URL*/
+  var match = url.match(/[?&]v=([^&]+)/); 
+  var videoId = match[1]; /*Use regex to determine exact Video URL*/
+/*Insert a new iFrame for the livestream chat after a specific div named chatframe*/
+  var livevid = document.createElement(""iframe"");
+  livevid.src = 'https://www.youtube.com/live_chat?v=' + videoId + '&embed_domain=[MY_DOMAIN_HERE]'
+  livevid.width = '100%';
+  livevid.height= '400px';
+  document.getElementById(""chatframe"").appendChild(livevid);
+}
+    function onPlayerStateChange() {
+    }
+</script>
+
",html +"Auto click button on page load is not working

I'm completely newbie to code, and I'm making a website on Webflow and trying to adapt some functions with custom code. I read a bunch of topics here that mentions the possibility of auto clicks a button on load of the page. So I tried adding the snippet to the body of the page and publishing the website to check if it would work, but the auto click didn't happen. The page is only a button with an auto click. Could someone help me to understand why it's not working? Thanks in advance.

+ +
<body>
+  <div><a id=""redirect"" ms-member-page=""default"" href=""#"" class=""w-button"">Button Text</a></div>
+  <script src=""https://d3e54v103j8qbb.cloudfront.net/js/jquery-3.4.1.min.220afd743d.js?site=5e79526aa1d3ba459f1ebac2"" type=""text/javascript"" integrity=""sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="" crossorigin=""anonymous""></script>
+  <script src=""js/webflow.js"" type=""text/javascript""></script>
+  <!-- [if lte IE 9]><script src=""https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js""></script><![endif] -->
+  <script type=""text/javascript"">
+document.getElementById(""redirect"").click();
+</script>
+</body>
+
","

The autoclick is working, but it's just the fact that your anchor tag (a) is not leading the user anywhere. You probably were trying to do something like this:

+ +
<body>
+  <div><a id=""redirect"" ms-member-page=""default"" href=""/mypage.html"" class=""w-button"">Button Text</a></div>
+  <script src=""https://d3e54v103j8qbb.cloudfront.net/js/jquery-3.4.1.min.220afd743d.js?site=5e79526aa1d3ba459f1ebac2"" type=""text/javascript"" integrity=""sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="" crossorigin=""anonymous""></script>
+  <script src=""js/webflow.js"" type=""text/javascript""></script>
+  <!-- [if lte IE 9]><script src=""https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js""></script><![endif] -->
+  <script type=""text/javascript"">
+document.getElementById(""redirect"").click();
+</script>
+</body>
+
+ +

Read more about anchor tags here.

+ +

a tags are for links, to send your user to a page. Buttons are made with the <button> tag.

",html +"can I have a button next to the select option? if can't, can I put the button outside and connect with the option in the select?

What I want is when you select and there are multiple options showing with two buttons. When the button is clicked, I want to take the option value,( which might be id) and do some functions. +Is it possible? +If I put buttons outside next to each option, how can I connect with the option in the multiple select?

+ +

","

This is an example using jQuery

+ +
<select id=""choice"" multiple=""multiple"">
+  <option value=""one"">one</option>
+  <option value=""two"">two</option>
+  <option value=""three"">three</option>
+</select>
+
+<button type=""button"">one</button>
+<button type=""button"">two</button>
+<button type=""button"">three</button>
+
+<script>
+$('button').click(function() {
+  var val = $(this).text(); // one, two, three
+  $(""#choice option[value='"" + val + ""']"").prop(""selected"", true);
+});
+</script>
+
+
+ +

Online Verification

",html +"separate styles for check box CSS

independent styles

+ +

I have this problem, at the moment of applying the styles they are applied in all the checboxes that are found, I only think that the styles of each checkbox are applied independently and that only 1 can be selected

+ +

+
+
  <style media=""screen"">
+  /* Hide the checkbox */
+  form p {
+   position: relative; /* allows to position the checkbox */
+  }
+
+  [type=""checkbox""]:not(:checked),
+  [type=""checkbox""]:checked {
+   /* Hide the checkbox without
+      making it hidden for the
+      screen readers */
+   position: absolute;
+   left: 0;
+   opacity: 0.01;
+  }
+
+  /* Preparing the label */
+  [type=""checkbox""]:not(:checked) + label,
+  [type=""checkbox""]:checked + label {
+   position: relative; /* allows to position the custom boxes */
+   padding-left: 2.3em; /* space for upcoming boxes */
+   font-size: 1.05em;
+   line-height: 1.7;
+   cursor: pointer;
+  }
+  /* Box aspect */
+[type=""checkbox""]:not(:checked) + label:before,
+[type=""checkbox""]:checked + label:before {
+ content: '';
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 1.4em;
+ height: 1.4em;
+ border: 1px solid #aaa;
+ background: #FFF;
+ border-radius: .2em;
+ box-shadow: inset 0 1px 3px rgba(0,0,0, .1), 0 0 0 rgba(203, 34, 237, .2);
+ transition: all .275s;
+}
+
+/* Check aspect */
+[type=""checkbox""]:not(:checked) + label:after,
+[type=""checkbox""]:checked + label:after {
+ content: 'X';
+ position: absolute;
+ top: .38em;
+ left: .18em;
+ font-size: 1.6em;
+ color: #CB22ED;
+ line-height: 0;
+ transition: all .2s; /* Little transition */
+}
+
+/* Unchecked aspect */
+[type=""checkbox""]:not(:checked) + label:after {
+ opacity: 0;
+ transform: scale(0) rotate(45deg);
+}
+
+/* Checked aspect */
+[type=""checkbox""]:checked + label:after {
+ opacity: 1;
+ transform: scale(1) rotate(0);
+}
+  </style>
+
<p>
+ <input type=""checkbox"" class=""check"" id=""test1"" />
+ <label for=""test1"" aria-describedby=""label"">YES</label>
+</p>
+<p>
+ <input type=""checkbox"" id=""test2"" />
+ <label for=""test2"" aria-describedby=""label"">NO</label>
+</p>
+
+
+

+ +

As shown in the example, the styles appear for everyone but I only wish that each one had its content. I expect answers and thank you for your attention.

","

What you are doing is targeting the HTML attribute <input> with the type of type=""checkbox"". Therefore, any of those you have on the page will be targeted. However, you can override input[type=""checkbox""] with an ID. To define an ID, simply put, on your HTML page. On each HTML tag like <input> or <p> or even <textarea> you can add an ID like this <input id=""thisIsWhateverYouWant"" type=""checkbox""> same goes for the others. To write it in CSS, inside the <style> tags you can write something like this #thisIsWhateverYouWant {height: 100%; width: 100%} Those styles will override what you have.

+ +

Here is a reference to what overrides what. Check this out

",html +"Prevent enter from writing new line in content edititable div

How can I prevent the user from writing a new line with the enter key in a contenteditable div?

+ +

So far I have tried (the id of my editable div is editable:

+ +
$('#editable').on('keyup', function(e) {
+    if (e.which == 13) {
+        event.preventDefault();
+    }
+});
+
+ +

However this does not work.

+ +

Is this possible using JS and jQuery?

+ +
+

Edit

+
+ +

I have been informed that pressing enter does not insert a new line so I have put a picture showing when happens when I press enter inside the editable div.

+ +

I would like code to remain on one line basically, even if the user presses enter.

+ +

","

Instead of keyup, use keydown.

+ +
const ediatble = document.querySelector('#editable');
+ediatble.addEventListener('keydown', e => {
+  if (e.key === 'Enter') {
+    e.preventDefault();
+
+  }
+});
+
+ +

See example on JSFiddle

",html +"how to use onchage event instead of setInterval in this script

in my laravel project i have colorpicker input field where I want to autosave the value in database. In this section I have pasted the script which is running properly. But the problem is this is continue saving the value after the interval. But what I want? +When I click the input field then the event will fire without clicking it would not goes on. +so plz can anyone help me out how can I use the onchange event for this. I have pasted the code below plz check it out and let me know

+ +
<script>  
+$(document).ready(function(){  
+     function autoSave()  
+     {  
+            var id =$(""#hid"").val();
+            var statscolor = $('#statscolor').val();  
+
+
+               $.ajax({  
+                    headers: {
+                         'X-CSRF-TOKEN': $('meta[name=""csrf-token""]').attr('content')
+                     },
+                    method:""put"",  
+                    // url:""{{ route('companyStats.update', $auto->id) }}"",   
+                    url:""colorstats/""+id,   
+                    data:{backgroundcolor:statscolor},  
+                    dataType:""text"",  
+                    success:function(data)  
+                    {  
+
+                         console.log(data);  
+                         // $('#autoSave').fadeIn().text(""color successfully updated"");
+                         // $('#autoSave').fadeOut(3000);
+                         $('#autoSave').text('updatedsuccessfully');
+                         // setInterval(function(){
+
+                         //      $('#autoSave').fadeOut();
+
+
+                         // }, 5000); 
+                         /*setTimeout(function() {
+                            // $('#autoSave').fadeOut(""slow"");
+                            $('#autoSave').fadeIn().text(""color successfully updated"");
+                        }, 5000 ); */
+
+
+                    }  
+               });  
+
+     }
+     setInterval(function(){   
+          autoSave();   
+          }, 5000);  
+});  
+</script>
+
+ +

this is blade input field

+ +
     <div class=""form-group"">
+                               <label for=""statscolor"">Background Color</label>
+
+                               <input type=""hidden"" id=""hid"" value=""{{$auto->id}}"" name=""hid"">
+
+                               <input class=""jscolor float-right"" name=""backgroundcolor"" id=""statscolor"" value=""{{$auto->backgroundcolor}}"" autocomplete=""off"" style=""background-image: none; background-color: rgb(0, 142, 255); color: rgb(255, 255, 255);"" onChange=""autoSave()"">
+
+                               <small id=""autoSave""></small>
+
+                           </div>
+
","

This answer is based on JQuery, but if you use jscolor.js (I guess) there may be a specific event. In this case, every time your color changes, your function is called. You should probably save the data when the colorpicker is closed.

+ +

+
+
$(document).ready(function() {
+  $('.jscolor').on('change', function() {
+    var statscolor = $('#statscolor').val();
+
+    alert('Your new Color:' + statscolor);
+    //Replace the alert with the ajax call
+
+  });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.js""></script>
+<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""form-group"">
+    <label for=""statscolor"">Background Color</label>
+
+    <input type=""hidden"" id=""hid"" value=""{{$auto->id}}"" name=""hid"">
+
+    <input class=""jscolor float-right"" name=""backgroundcolor"" id=""statscolor"" value=""{{$auto->backgroundcolor}}"" autocomplete=""off"" style=""background-image: none; background-color: rgb(0, 142, 255); color: rgb(255, 255, 255);"" >
+
+    <small id=""autoSave""></small>
+
+  </div>
+
+
+

+ +
+ +

Second solution

+ +

If my guess is correct, this is the solution with jscolor.

+ +

+
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.js""></script>
+<div class=""form-group"">
+  <label for=""statscolor"">Background Color</label>
+
+  <input type=""hidden"" id=""hid"" value=""{{$auto->id}}"" name=""hid"">
+
+  <input class=""jscolor float-right"" name=""backgroundcolor"" id=""statscolor"" value=""{{$auto->backgroundcolor}}"" autocomplete=""off"" style=""background-image: none; background-color: rgb(0, 142, 255); color: rgb(255, 255, 255);"" onChange=""autoSave(this.jscolor)"">
+
+  <small id=""autoSave""></small>
+
+</div>
+
+<script>
+  function autoSave(jscolor) {
+    // 'jscolor' instance can be used as a string
+    alert('#' + jscolor);
+  }
+</script>
+
+
+

",html +"Dynamically Changing and Saving Content in Text Box

I am trying to create a web page that has something akin to a blog editor functionality. I want the user to be able to define their font style (basic categories like header 1, 2, 3, default text, etc.). I was planning on just using a HTML text box tag with a drop down menu that the user can use to toggle their text style.

+ +

I am not sure, however, how to change the style of the text that the user puts in the text box and then save the user's post (with styling preferences) in a MySQL database.

","

You can use tools below that designed specially for your need.

+ +",html +"How do i execute code when i select an option in blazor

I am trying to execute a method when i select a option but i can't figure out how to do this.

+ +

this is what i am trying right now the <InputSelect/> is in an <EditForm/> object:

+ +
<tr>
+   <th>
+      <label for=""layouts"">Layout *</label><br />
+      <InputSelect @bind-Value=""label.Layout"">
+            <option value="""">Selecteer</option>
+            <option value=""@availableLayouts.GetValue(0)"" @onselect=""OnSelectFinalCheck"">Eindcontrole</option>
+            <option value=""@availableLayouts.GetValue(1)"" @onselect=""OnSelectStock"">Voorraad</option>
+            <option value=""@availableLayouts.GetValue(2)"">Uitbesteed werk</option>
+            <option value=""@availableLayouts.GetValue(3)"">Geleidebon label</option>
+        </InputSelect>
+      <br />
+   </th>
+<th>
+
+ +

So this is my selection and when i click ""voorraad"" i want to execute a method.

","

Note: The onselect event fires after some text has been selected in an element. It has nothing to do with the select element or selection of options... +As far as I remember, the InputSelect had some issues, but these may have already been dealt with by the Blazor team.

+ +

The following code snippet describes how you can use the select element in Blazor, and how to implement a two-way data binding; that is, from a variable to an element, and from an element to a variable. You can do that in various ways: my code employs the most efficient way to achieve this goal, according to maestro Steve Anderson.

+ +

Here's the code snippet that bind the SelectedAuthorID variable to the select element employing two-way data binding.

+ +
 <select @bind=""@SelectedAuthorID"">
+    <option value=@(0)></option>
+    @foreach (var author in authors)
+    {
+        <option value=""@author.ID"">@author.Name</option>
+    }
+</select>
+
+ +

Note: The SelectedAuthorID is a property which defines a backing private variable:

+ +
    int _selectedAuthorID;
+    private int SelectedAuthorID
+    {
+        get => _selectedAuthorID;
+        set
+        {
+            if (_selectedAuthorID != value)
+            {
+                _selectedAuthorID = value;
+            }
+        }
+     }
+
+ +

Well, this code is quite self-explanatory, but if you're not completely understand what I did, don't hesitate to ask.

+ +

The authors object in the foreach loop above is a list of authors you can create as follows:

+ +
 @code {
+     List<Author> authors= Enumerable.Range(1, 10).Select(i => new Author { ID 
+                            = i, Name = $""Author {i.ToString()}"" }).ToList();
+
+ public class Author
+ {
+    public int ID { get; set; }
+    public string Name { get; set; }
+ }  
+
+ +

}

+ +

Now, let's try to model my options after the value=""@availableLayouts.GetValue(1)"" expression . This expression is evaluated to a string literal, right ? And when the user select this option, the OnSelectStock is called to do something.

+ +

Let's say that we want to call an OnSelectStock method and pass it the author id when an author is selected, and his id is even. Thus we can do something like this:

+ +
    if (_selectedAuthorID != value)
+        {
+            _selectedAuthorID = value;
+            if(value % 2 == 0)
+            {
+                OnSelectStock( value );
+            }
+
+        }
+
+ +

This is it.

+ +

Hope this helps...

+ +

Complete working code:

+ +

Index.razor

+ +
@page ""/""
+
+<select @bind=""@SelectedAuthorID"">
+    <option value=@(0)></option>
+    @foreach (var author in authors)
+    {
+        <option value=""@author.ID"">@author.Name</option>
+    }
+</select>
+
+<p>Selected Author ID: @authorID</p>
+
+@code{
+
+string authorID;
+
+int _selectedAuthorID;
+private int SelectedAuthorID
+{
+    get => _selectedAuthorID;
+    set
+    {
+        if (_selectedAuthorID != value)
+        {
+            _selectedAuthorID = value;
+      // Call OnSelectStock only if the author ID is an even number
+            if (value % 2 == 0)
+            {
+                OnSelectStock(value);
+            }
+        }
+    }
+ }
+
+ List<Author> authors = Enumerable.Range(1, 10).Select(i => new Author 
+                { ID = i, Name = $""Author {i.ToString()}"" }).ToList();
+
+ private void OnSelectStock(int value)
+ {
+    authorID = value.ToString();
+ }
+
+ public class Author
+ {
+    public int ID { get; set; }
+    public string Name { get; set; }
+ }
+}
+
",html +"How to change HTML button onclick with Javascript?

I am trying to change the onclick function of an HTML button using Javascript. Currently, when I try to re-click the button (with the new function) the console returns this error:

+ +
index.js:25 Uncaught TypeError: document.getelementbyId is not a function
+    at lightmode (index.js:25)
+    at HTMLInputElement.onclick (index.html:1)
+
+ +

Here is the code for the index.html file (HTML):

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <title>Javascript</title>
+    <link rel=""stylesheet"" type=""text/css"" href=""main.css"">
+    <script type=""text/javascript"" src=""index.js""></script>
+</head>
+<body id=""mainbody"">
+    <header id=""hdr"">
+        <h1>JAVASCRIPT</h1>
+    </header>
+    <input type=""button"" value=""Dark Mode"" onclick=""darkmode();"" id=""modebutton""/>
+
+</body>
+</html>
+
+ +

and here is the code for the index.js file (Javascript):

+ +
function darkmode(){
+    var hdr = document.getElementById(""hdr"");
+    var body = document.getElementById(""mainbody"");
+    var btn = document.getElementById(""modebutton"");
+    body.style.background = ""grey"";
+    hdr.style.background = ""black"";
+    hdr.style.color = ""white"";
+    btn.value = ""Light Mode"";
+    btn.setAttribute(""onClick"", ""javascript: lightmode();"");
+}
+
+function lightmode(){
+    var hdr = document.getElementById(""hdr"");
+    var body = document.getElementById(""mainbody"");
+    var btn = document.getelementbyId(""modebutton"");
+    body.style.background = 'white';
+    hdr.style.background = ""grey"";
+    hdr.style.color = ""black"";
+    btn.value = ""Dark Mode"";
+    btn.setAttribute(""onClick"", ""javascript: darkmode();"");
+}
+
+ +

If anyone needs me to add the css file I'd be happy to do it.

","
var btn = document.getelementbyId(""modebutton"");
+
+ +

It is getElementById not getelementbyId . Notice the captialisation. Correct it and you'll not get that error. Yes, javascript is case-sensitive!

",html +"HTML title attribute making css :hover not work

I have some code to make an arrow and im trying to add a title attribute to it. Here is the arrow code:

+ +

+
+
#arrow-right {
+  width: 0;
+  height: 0;
+  border-top: 10px solid transparent;
+  border-bottom: 10px solid transparent;
+  border-left: 10px solid white;
+}
+
+#arrow-right:hover {
+  border-left: 10px solid gray;
+}
+
<div id=""arrow-right"" title=""text here""></div>
+
+
+

+ +

Before I added the 'title' attribute, it worked fine, changing to color to grey on hover, but after I added the 'title' attribute, the css color changing stopped working but the title started working. Is there any way to have both of these work at the same time?

","

replace

+ +
<div id=""arrow-right"" ; title=""text here""></div>
+
+ +

with

+ +
<div id=""arrow-right"" title=""text here""></div>
+
",html +"JS files doesn't work correctly in wordpress

As I've mentioned in the title, I'm having some problems with my js files.
+I've tested the scripts in the HTML template and works fine, but when I put them into the functions.php file there are some scripts that doesn't work as they should.

+ +

Here the functions.php file:

+ +
<?php
+function load_stylesheets(){
+ /************/
+}
+
+function add_js(){
+    wp_register_script('jquery-min', get_template_directory_uri().'/js/jquery.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('jquery-min');
+    wp_register_script('jquery-migrate', get_template_directory_uri().'/js/jquery/jquery-migrate.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('jquery-migrate');
+    wp_register_script('popper', get_template_directory_uri().'/js/popper/popper.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('popper');
+    wp_register_script('bootstrap', get_template_directory_uri().'/js/bootstrap/js/bootstrap.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('bootstrap');
+    wp_register_script('easing', get_template_directory_uri().'/js/easing/easing.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('easing');
+    wp_register_script('jquery.waypoints', get_template_directory_uri().'/js/counterup/jquery.waypoints.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('jquery.waypoints');
+    wp_register_script('jquery.counterup', get_template_directory_uri().'/js/counterup/jquery.counterup.js', array('jquery'), 2, true);
+    wp_enqueue_script('jquery.counterup');
+    wp_register_script('carousel', get_template_directory_uri().'/js/owlcarousel/owl.carousel.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('carousel');
+    wp_register_script('lightbox', get_template_directory_uri().'/js/lightbox/js/lightbox.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('lightbox');
+    wp_register_script('typed', get_template_directory_uri().'/js/typed/typed.min.js', array('jquery'), 2, true);
+    wp_enqueue_script('typed');
+    wp_register_script('contactform', get_template_directory_uri().'/js/contactform.js', array('jquery'), 3, true);
+    wp_enqueue_script('contactform');
+    wp_register_script('main', get_template_directory_uri().'/js/main.js', array('jquery'), 3, true);
+    wp_enqueue_script('main');
+}
+add_action(""wp_enqueue_scripts"", ""load_stylesheets"", ""add_js"", 999);
+?>
+
+ +

Thanks in advance!

","

You cannot hook into wp_enqueue_scripts and call multiple functions like that:

+ +
add_action(""wp_enqueue_scripts"", ""load_stylesheets"", ""add_js"", 999);
+
+ +

add_action() accepts these four parameters:

+ +
+
    +
  • $tag (string) (Required) The name of the action to which the $function_to_add is hooked.
  • +
  • $function_to_add (callable) (Required) The name of the function you wish to be called.
  • +
  • $priority (int) (Optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
    + Default value: 10
  • +
  • $accepted_args (int) (Optional) The number of arguments the function accepts. + Default value: 1
  • +
+
+ +

So, to add both your stylesheets and scripts you'll have to do:

+ +
add_action( 'wp_enqueue_scripts', 'load_stylesheets', 999 );
+add_action( 'wp_enqueue_scripts', 'add_js', 999 );
+
",html +"Img appearing out of order when placed in between links

I'm trying to create a paginator which inserts an ellipsis in the middle. My issue is the ellipsis ends up at the end of the row instead of in the middle like I'm placing it in the code. What am I doing wrong?

+ +
<div>
+    <div class=""pagination"">
+        <a href=""?page=1"">1</a>
+        <a href=""?page=2"">2</a>
+        <a href=""?page=3"">3</a>
+        <img src=""/static/svg/ellipsis-h-solid.svg"" style=""width: 15px"">
+        <a href=""?page=13"">13</a>
+        <a href=""?page=14"">14</a>
+        <a href=""?page=15"" class=""active"">15</a>
+    </div>
+    <p style=""margin-left: 10px;"">30 trades</p>
+</div>
+
+ +

+ +

EDIT: +I also tried setting display: inline and display: inline-block but it still appears at the end

+ +
<div class=""pagination"">
+    <a href=""?page=1"" >1</a>
+    <a href=""?page=2"" >2</a>
+    <a href=""?page=3"" class=""active"">3</a>
+    <img src=""/static/svg/ellipsis-h-solid.svg"" style=""width: 15px; display: inline;"">
+    <a href=""?page=13"" >13</a>
+    <a href=""?page=14"" >14</a>
+    <a href=""?page=15"" >15</a>
+</div>
+
","

in my computer the img appears in 4th place, I strongly believe your anchor has good previous styling which disturbs the img placement, I beleive your anchor is sorted using either javascript or CSS style

+ +

please check that you have any CSS style like this, add the img tag also for that CSS

+ +
{
+      display: flex;
+      flex-direction: row;
+}
+
+ +

may be try to manually give order like this example (optional)

+ +
:nth-child(1) { order: 2; }
+
",html +"Using localstorage to store login info

I have been working on a project where we can store login info so that once a user registers, the data gets saved in the localStorage object. I have mentioned some javascript code to show that:

+ +
var user = document.getElementById(""user"");
+var pass = document.getElementById(""pass"");
+var email = document.getElementById(""email"");
+var user2 = document.getElementById(""user2"");
+var pass2 = document.getElementById(""pass2"");
+
+function register() {
+    localStorage.setItem(""username"", user.value);
+    localStorage.setItem(""password"", pass.value);
+    localStorage.setItem(""email"", email.value);
+    document.getElementById(""id01"").innerHTML = ""Registration successful"";
+}
+
+function login() {
+    var checkuser = localStorage.getItem(""username"");
+    var checkpass = localStorage.getItem(""password"");
+    if (checkuser === user2.value && checkpass === pass2.value) {
+        document.getElementById(""demo"").innerHTML = ""You are now logged in."";
+    } else {
+        document.getElementById(""demo"").innerHTML = ""Incorrect username and password"";
+    }
+}
+
+ +

In the javascript code mentioned above, i have used the localStorage object to store the values. I have stored the username in a user property, the password in a pass property and the email in an email property.

+ +

My question is: Is there any way where we can store the username, password and the email in one property(user property)?

","

Yes, you can do this by putting all the features you want in one object.

+ +

Example here

+ +
var user = document.getElementById(""user"");
+var pass = document.getElementById(""pass"");
+var email = document.getElementById(""email"");
+var user2 = document.getElementById(""user2"");
+var pass2 = document.getElementById(""pass2"");
+var user = {
+email:email,
+pass:pass,
+//.. other properties 
+}
+
+ +

then you can set like this

+ +
localStorage.setItam(""USEROBJ"",JSON.stringify(user));
+
+ +

When you want to call this you should use like

+ +
var user = JSON.parse(localStorage.getItam(""USEROBJ""));
+
+ +

By the way you can read this

+ +

Storing Objects in HTML5 localStorage more detail about you question

",html +"Button on navbar causes navbar height to increase

I refer to the following example on navbar using Bootstrap:

+ +

https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_navbar_form&stacked=h

+ +

Copying the HTML, I put it in my JSP page. The following is the eventual HTML:

+ +
<html>
+
+<head>
+<!-- Required meta tags -->
+<meta charset=""utf-8"">
+<meta name=""viewport"" content=""width=device-width, initial-scale=1, shrink-to-fit=no"">
+
+<link href=""/webjars/bootstrap/css/bootstrap.min.css"" rel=""stylesheet"">
+<script type=""text/javascript"" src=""/webjars/jquery/jquery.min.js""></script>
+<script type=""text/javascript"" src=""/webjars/bootstrap/js/bootstrap.bundle.min.js""></script>
+
+<title>2</title>
+</head>
+
+<body>
+
+<nav class=""navbar navbar-expand-sm bg-dark navbar-dark"">
+  <form class=""form-inline"" action=""/action_page.php"">
+    <input class=""form-control mr-sm-2"" type=""text"" placeholder=""Search"">
+    <button class=""btn btn-success"" type=""submit"">Search</button>
+  </form>
+</nav>
+<br>
+
+<div class=""container"">
+  <h3>Navbar Forms</h3>
+  <p>Use the .form-inline class to align form elements side by side inside the navbar.</p>
+</div>
+
+</body>
+</html>
+
+ +

On both IE and Google Chrome, the navbar's height is bigger than the one in the example, with the extra spaces below the controls, as shown below. I found that this is due to the button. If the button is removed, the navbar's height would be the same as in the example. What could be the root cause and how can I resolve it? I am using Bootstrap 4.4.

+ +

","

this is because of the browser default CSS which also known as User Agent Style Sheet.

+ +

+I found that if you use <!DOCTYPE html> this space was removed because the bottom margin of the form element in HTML5's User agent style sheet is 0px;

+ +

If i don't use <!DOCTYPE html> it consider the HTML4's User agent style sheet, and the bottom margin of the form element in it is 1em.

+ +

so now choice is yours that if you have to use <!DOCTYPE html> or not.

+ +

Otherwise the another solution is that use class=""mb-0"" in form element it is the bootstrap-4 class to set margin-bottom: 0px; for any element.

",html +"Google play icon not appearing (fontawsome)

I want to add google play and apple icons with the download button +the apple icon works fine but the google play doesn't show and i don' know why

+

+
+
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"">
+<h1>Meet new and interesting dogs nearby.</h1>
+<button type=""button"" class=""btn btn-dark btn-lg""><i class=""fa fa-apple""></i>Download</button>
+<button type=""button"" class=""btn btn-outline-light btn-lg""><i class=""fab fa-google-play""></i>Download 2</button>
+
+
+

","

Cause you're using fontawsome version 4.7.0 and the google play icon is version 5.0.0. Here is the correct code you must use instead.

+

You must also change the class of the apple icon to fab fa-apple cause it's for version 5.8.0 of fontawsome.

+

+
+
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"">
+<h1>Meet new and interesting dogs nearby.</h1>
+<!-- <button type=""button"" class=""btn btn-dark btn-lg""><i class=""fa fa-apple""></i>Download</button> -->
+<button type=""button"" class=""btn btn-dark btn-lg""><i class=""fab fa-apple""></i>Download</button>
+<button type=""button"" class=""btn btn-outline-light btn-lg""><i class=""fab fa-google-play""></i>Download 2</button>
+
+
+

",html +"Repeated errors with Firebase Authentication

I've been trying to set up FirebaseUI email and password authentication for the first time on a really basic website, but am experiencing multiple errors, and nothing shows up where the sign in/sign up UI should be. It's just empty, with only the loader showing. First, I have made sure that Firebase has properly been implemented, and hosting and deploys are working fine as well. I have also enabled email and password authentication in the console, and have followed the documentation to set things up. Here's what I've done so far:

+
<head>
+    <script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js"></script>
+    <script src="https://www.gstatic.com/firebasejs/ui/4.8.1/firebase-ui-auth.js"></script>
+    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.8.1/firebase-ui-auth.css" />
+</head>
+
+<body>
+    <h2>Testing</h2>
+     <h1>firebase auth practice</h1>
+     <div id="firebaseui-auth-container"></div>
+     <div id="loader">Loading...</div>
+
+    <script>
+        var firebaseConfig = {
+            // I've omitted this part for the purposes of the question.
+        };
+        firebase.initializeApp(firebaseConfig);
+        
+        import * as firebase from 'firebase';
+        import * as firebase from 'firebase/auth';
+
+        var ui = new firebaseui.auth.AuthUI(firebase.auth());
+
+        ui.start('#firebaseui-auth-container', {
+            signInOptions: [
+                firebase.auth.EmailAuthProvider.PROVIDER_ID
+            ]
+            });
+
+        var uiConfig = {
+            callbacks: {
+                signInSuccessWithAuthResult: function(authResult, redirectUrl) {
+                return true;
+                },
+                uiShown: function() {
+                document.getElementById('loader').style.display = 'none';
+                }
+            },
+            signInFlow: 'popup',
+            signInSuccessUrl: 'loggedin.html',
+            signInOptions: [
+                firebase.auth.EmailAuthProvider.PROVIDER_ID
+            ],
+            tosUrl: 'tos.html',
+            privacyPolicyUrl: 'privacy.html'
+            };
+
+         ui.start('#firebaseui-auth-container', uiConfig);
+    </script>
+
+</body>
+
+

loggedin.html, tos.html, and privacy.html are all pretty much empty. All of this has been taken from the documentation, but I got errors saying that firebase.auth() is not a function, and then I tried the import part, and got errors saying that the import statement cannot be used outside of a module. I have attempted to try what others with these errors did on SO, such as using type="module", but to no avail. I suspect that the issue might have to do with the import bit, but cannot find any fixes yet, in either SO or the documentation.

+

Any help with this would be greatly appreciated!

","

You're not importing the Firebase Authentication SDK yet, which FirebaseUI depends on.

+

You'll want to add this line to your script section:

+
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-auth.js"></script>
+
+

Note that there may be many more problems, but this change should fix the firebase.auth() is not a function that you mentioned.

+

If you have more problems after this, please post a separate question for each, with its own MCVE (read the link please, as it's quite useful).

",html +"CSS: absolute element nested sticky element

I have table with last sticky column, this column have a absolute menu, but the absolute menu backward the sticky column. I want the menu forward the column. I tried z-index but not working. Please help me! (Sorry my bad English)

+My codepen: codepen

+
.sticky {
+  position: sticky;
+  right: 0;
+  background-color: yellow;
+}
+.menu {
+  position: absolute;
+  left: 0;
+  background-color: red;
+  z-index: 1;
+}
+
+
+

+
+
body {
+  margin: 0;
+}
+
+.wrapper {
+  overflow-x: auto;
+  position: relative;
+  white-space: nowrap;
+  max-width: 600px;
+}
+th,
+td {
+  min-width: 300px;
+  text-align: center;
+}
+th:last-child,
+td:last-child {
+  min-width: 50px !important;
+}
+
+.sticky {
+  position: sticky;
+  right: 0;
+  background-color: yellow;
+}
+.menu {
+  position: absolute;
+  left: 0;
+  background-color: red;
+  z-index: 1;
+}
+
<body>
+    <div class=""wrapper"">
+      <table>
+        <thead>
+          <tr>
+            <th>Col</th>
+            <th>Col</th>
+            <th>Col</th>
+            <th class=""sticky"">Action</th>
+          </tr>
+        </thead>
+        <tbody>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky"">
+              . . .
+              <div class=""menu"">
+                <div>item</div>
+                <div>item</div>
+                <div>item</div>
+              </div>
+            </td>
+          </tr>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky"">. . .</td>
+          </tr>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky"">. . .</td>
+          </tr>
+        </tbody>
+      </table>
+    </div>
+  </body>
+
+
+

","

you need to add z-index to the sticky element parent of your absolute element:

+

+
+
body {
+  margin: 0;
+}
+
+.wrapper {
+  overflow-x: auto;
+  position: relative;
+  white-space: nowrap;
+  max-width: 600px;
+}
+th,
+td {
+  min-width: 300px;
+  text-align: center;
+}
+th:last-child,
+td:last-child {
+  min-width: 50px !important;
+}
+
+.sticky {
+  position: sticky;
+  right: 0;
+  background-color: yellow;
+}
+.menu {
+  position: absolute;
+  left: 0;
+  background-color: red;
+}
+.z-index {
+  z-index: 1;
+}
+
<body>
+    <div class=""wrapper"">
+      <table>
+        <thead>
+          <tr>
+            <th>Col</th>
+            <th>Col</th>
+            <th>Col</th>
+            <th class=""sticky"">Action</th>
+          </tr>
+        </thead>
+        <tbody>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky z-index"">
+              . . .
+              <div class=""menu"">
+                <div>item</div>
+                <div>item</div>
+                <div>item</div>
+              </div>
+            </td>
+          </tr>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky"">. . .</td>
+          </tr>
+          <tr>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td>-----------------------------------</td>
+            <td class=""sticky"">. . .</td>
+          </tr>
+        </tbody>
+      </table>
+    </div>
+  </body>
+
+
+

",html +"Hide div element conditionally in ReactJS

I'm new ReactJS, there is a code where I am supposed to hide the below div until the data is returned from the backend. So there is an input where the ID is searched upon clicking the submit button. Once the info is retrieved, only then the

+

Name "XYZ"

+

Address "123,abc"

+

should be displayed. +As of now it diplays,( blank space in front of it) so I just want the Name and Address titles to be hidden until the data is retrieved.

+

Name

+

Address

+

Below is the code:

+
 <div className="info">
+    <div className="info-block">
+        <div className="info-title"><TranslatedString stringId="name" /></div>
+        <div className="info-cell">{returnObj?.data?.name}</div>
+        <div className="info-title"><TranslatedString stringId="address" /></div>
+        <div className="info-cell">{returnObj?.data?.address}</div>                 
+    </div>
+ </div>
+
+

returnObj is where the data from the backend is stored. I tried adding condition on the info-title and info-cell like stringId={returnObj?.status == "Success"?"name":null} but that didn't work.

","

To prevent rendering the div before the data has been fetched, you could do:

+
{returnObj?.data && (
+    <div className="info">
+      <div className="info-block">
+        <div className="info-title"><TranslatedString stringId="name" /></div>
+        <div className="info-cell">{returnObj.data.name}</div>
+        <div className="info-title"><TranslatedString stringId="address" /></div>
+        <div className="info-cell">{returnObj.data.address}</div>                 
+      </div>
+    </div>
+)};
+
",html +"make menu scrollable on button click

I have a problem with my code, I'm trying to make my menu that contains list of items scrollable on button click (left and right buttons). The thing is after i click on right button, it works but it does not let me click it again....if i do it does nothing.So it goes once right and once left only. I want to be able to keep pressing it untill i reach the last item in the menu and vice versa.

+

My html code for the menu:

+
<div class="menu-wrapper">
+    <ul class="menu">
+        <li class="item active">Hair</li>
+    <li class="item">Massage</li>
+    <li class="item">Nails</li>
+    <li class="item">Facial</li>
+    <li class="item">Tattoo</li>
+    <li class="item">Institue</li>
+    <li class="item">Masking</li>
+    <li class="item">Doudou</li>
+    <li class="item">Facial</li>
+    <li class="item">Tattoo</li>
+    <li class="item">Institue</li>
+    <li class="item">Masking</li>
+    <li class="item">Doudou</li>
+    </ul>
+
+    <div class="paddles">
+        <button class="left-paddle paddle hidden">
+            <
+        </button>
+        <button class="right-paddle paddle">
+            >
+        </button>
+</div>
+  </div> 
+
+

My Css code is:

+
.menu-wrapper {
+    position: relative;
+    border-radius: 10px;
+    height: 50px; 
+    margin: 1em auto;
+
+    overflow-x: hidden;
+    overflow-y: hidden;
+}
+
+.menu   {
+    height: 50px; 
+    background: white;
+    box-sizing: border-box;
+    padding-left: 0;
+    white-space: nowrap;
+    overflow-x: hidden;
+    overflow-y: hidden;
+    -webkit-overflow-scrolling: touch;
+    
+    
+}
+.item {
+    display: inline-block;
+    width: 155px;
+    height: auto;
+    text-align: center;
+    box-sizing: border-box;
+    padding: 10px;}
+    .item.active{color: white; background-color: #6f51ed;}
+.item:hover{
+    cursor: pointer;
+}
+.paddle {
+    position: absolute;
+    top: 0;
+    bottom: 0;
+    width: 2em;
+}
+.left-paddle {
+    left: 0;
+    color:#6f51ed;
+    background-color: transparent;
+    border-color: transparent;
+ outline: none;
+ font-size: x-large;
+ padding-bottom: 5px;
+}
+.right-paddle {
+    right: 0;
+    color:#6f51ed;
+    background-color: transparent;
+    border-color: transparent;
+    outline: none;
+    font-size: x-large;
+    padding-bottom: 5px;
+}
+.hidden {
+    display: none;
+}
+
+

My Jquery/Js code is:

+
 <script>
+ var scrollDuration = 450;
+// paddles
+var leftPaddle = document.getElementsByClassName('left-paddle');
+var rightPaddle = document.getElementsByClassName('right-paddle');
+// get items dimensions
+var itemsLength = $('.item').length;
+var itemSize = $('.item').outerWidth(true);
+// get some relevant size for the paddle triggering point
+var paddleMargin = 5;
+
+// get wrapper width
+var getMenuWrapperSize = function() {
+    return $('.menu-wrapper').outerWidth();
+}
+var menuWrapperSize = getMenuWrapperSize();
+// the wrapper is responsive
+$(window).on('resize', function() {
+    menuWrapperSize = getMenuWrapperSize();
+});
+// size of the visible part of the menu is equal as the wrapper size 
+var menuVisibleSize = menuWrapperSize;
+
+// get total width of all menu items
+var getMenuSize = function() {
+    return itemsLength * itemSize;
+};
+var menuSize = getMenuSize();
+// get how much of menu is invisible
+var menuInvisibleSize = menuSize - menuWrapperSize;
+
+// get how much have we scrolled to the left
+var getMenuPosition = function() {
+    return $('.menu').scrollLeft();
+};
+
+// finally, what happens when we are actually scrolling the menu
+$('.menu').on('scroll', function() {
+
+    // get how much of menu is invisible
+    menuInvisibleSize = menuSize - menuWrapperSize;
+    // get how much have we scrolled so far
+    var menuPosition = getMenuPosition();
+
+    var menuEndOffset = menuInvisibleSize - paddleMargin;
+
+    // show & hide the paddles 
+    // depending on scroll position
+    if (menuPosition <= paddleMargin) {
+        $(leftPaddle).addClass('hidden');
+        $(rightPaddle).removeClass('hidden');
+    } else if (menuPosition < menuEndOffset) {
+        // show both paddles in the middle
+        $(leftPaddle).removeClass('hidden');
+        $(rightPaddle).removeClass('hidden');
+    } else if (menuPosition >= menuEndOffset) {
+        $(leftPaddle).removeClass('hidden');
+        $(rightPaddle).addClass('hidden');
+}
+
+
+
+});
+
+// scroll to left
+$(rightPaddle).on('click', function() {
+    $('.menu').animate( { scrollLeft: itemSize}, scrollDuration);
+});
+
+// scroll to right
+$(leftPaddle).on('click', function() {
+    $('.menu').animate( { scrollLeft: -itemSize }, scrollDuration);
+});
+</script>
+
","

Because you are scrolling to the same position, you need to add or subtract the itemSize to the current scroll position of .menu.

+
// scroll to left
+$(rightPaddle).on('click', function() {
+   $('.menu').animate({
+     scrollLeft: $('.menu').scrollLeft() + itemSize
+   }, scrollDuration);
+});
+
+// scroll to right
+$(leftPaddle).on('click', function() {
+   $('.menu').animate({
+     scrollLeft: $('.menu').scrollLeft() - itemSize
+   }, scrollDuration);
+});
+
",html +"Remove underline from href attribute that reference a Django template

At the top of one of my website pages, I have some text representing the name of my company. When the user clicks the text (a link in this case), they are redirected to the index route via the Django template.

+

Currently, the text is decorating. It's always the traditional blue color of a hyperlink and it's underlined when the user hovers over it. I'm trying to turn off this text decoration. Here is my attempt (which doesn't work):

+

layout.html

+
{% load static %}
+
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta name="viewport" content="width=device-width, initial-scale=1.0">
+        <link href="{% static 'my_app/styles.css' %}" rel="stylesheet">
+        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Pacifico">
+    </head>
+    <body>
+        <div id="logo">
+            <a href="{% url 'index' %}">ABC Company</a>
+        </div>
+    </body>
+
+

CSS

+
#logo {
+
+    font-family: 'Pacifico', serif;
+    text-align: center;
+    font-size: 60px;
+    font: 400 100px/1.5;
+    color: #2b2b2b;
+    text-decoration: none;
+
+}
+
+#logo:hover {
+    text-decoration: none;
+}
+
+

If I remove the href, the text goes back to the color specified in the #logo id in the CSS.

+

Any ideas why the text-decoration isn't being turned off?

+

Thanks in advance!

","

set the decoration of the hyperlink to the anchor tag of the div logo

+
   #logo a {
+        color: #FFFFFF;
+        text-decoration: none;
+        and your other decorations
+    }
+
",html +"Bootstrap 4 collapse, close all other collapsible items

Using Bootstrap 4 Collapse component.

+

When I click on Categories, the corresponding collapsible section should display. If I then click on Brands, I want the Categories section to collapse before the Brands one shows (or vice-versa).

+

Here the collapse works but multiple collapsible elements can be seen at the same time:

+

+
+
.view-custom-filters {
+  display: flex;
+}
+
+.view-collapse-button {
+  background: lightgrey;
+  width: 150px;
+  height: 50px;
+  display: table-cell;
+  text-align: center;
+  vertical-align: middle;
+}
+
<div id=""#viewCustomFilters"" class=""view-custom-filters"">
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#categories-collapsed"" aria-expanded=""true"" aria-controls=""categories-collapsed"">
+      Categories
+    </div>
+    <div class=""view-collapse-content collapse"" id=""categories-collapsed"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 1</a>
+        </li>
+        <li>
+          <a href=""#"">Link 2</a>
+        </li>
+        <li>
+          <a href=""#"">Link 3</a>
+        </li>
+        <li>
+          <a href=""#"">Link 4</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#brands-collapsed"" aria-expanded=""true"" aria-controls=""brands-collapsed"">
+      Brands
+    </div>
+    <div class=""view-collapse-content collapse"" id=""brands-collapsed"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 5</a>
+        </li>
+        <li>
+          <a href=""#"">Link 6</a>
+        </li>
+        <li>
+          <a href=""#"">Link 7</a>
+        </li>
+        <li>
+          <a href=""#"">Link 8</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+</div>
+
+<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"" integrity=""sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"" crossorigin=""anonymous"">
+<script src=""https://code.jquery.com/jquery-3.5.1.slim.min.js"" integrity=""sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"" integrity=""sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"" integrity=""sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"" crossorigin=""anonymous""></script>
+
+
+

+

I read that to achieve what I want, I need a wrapper element and use data-parent on the .collapse elements but when doing so, I get an error Uncaught TypeError: Cannot read property 'querySelectorAll' of null.

+

+
+
.view-custom-filters {
+  display: flex;
+}
+
+.view-collapse-button {
+  background: lightgrey;
+  width: 150px;
+  height: 50px;
+  display: table-cell;
+  text-align: center;
+  vertical-align: middle;
+}
+
<div id=""#viewCustomFilters"" class=""view-custom-filters"">
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#categories-collapsed"" aria-expanded=""true"" aria-controls=""categories-collapsed"">
+      Categories
+    </div>
+    <div class=""view-collapse-content collapse"" id=""categories-collapsed"" data-parent=""#viewCustomFilters"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 1</a>
+        </li>
+        <li>
+          <a href=""#"">Link 2</a>
+        </li>
+        <li>
+          <a href=""#"">Link 3</a>
+        </li>
+        <li>
+          <a href=""#"">Link 4</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#brands-collapsed"" aria-expanded=""true"" aria-controls=""brands-collapsed"">
+      Brands
+    </div>
+    <div class=""view-collapse-content collapse"" id=""brands-collapsed"" data-parent=""#viewCustomFilters"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 5</a>
+        </li>
+        <li>
+          <a href=""#"">Link 6</a>
+        </li>
+        <li>
+          <a href=""#"">Link 7</a>
+        </li>
+        <li>
+          <a href=""#"">Link 8</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+</div>
+
+<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"" integrity=""sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"" crossorigin=""anonymous"">
+<script src=""https://code.jquery.com/jquery-3.5.1.slim.min.js"" integrity=""sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"" integrity=""sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"" integrity=""sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"" crossorigin=""anonymous""></script>
+
+
+

+

How can I achieve to have only 1 collapsible element shown at a time?

","

You were almost there.

+

You own error is you add a # into id of viewCustomFilters so <div id="#viewCustomFilters" class="view-custom-filters"> instead was <div id="viewCustomFilters" class="view-custom-filters">

+

+
+
.view-custom-filters {
+  display: flex;
+}
+
+.view-collapse-button {
+  background: lightgrey;
+  width: 150px;
+  height: 50px;
+  display: table-cell;
+  text-align: center;
+  vertical-align: middle;
+}
+
<div id=""viewCustomFilters"" class=""view-custom-filters"">
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#categories-collapsed"" aria-expanded=""true"" aria-controls=""categories-collapsed"">
+      Categories
+    </div>
+    <div class=""view-collapse-content collapse"" id=""categories-collapsed"" data-parent=""#viewCustomFilters"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 1</a>
+        </li>
+        <li>
+          <a href=""#"">Link 2</a>
+        </li>
+        <li>
+          <a href=""#"">Link 3</a>
+        </li>
+        <li>
+          <a href=""#"">Link 4</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+  <div class=""view-collapse-wrap"">
+    <div class=""view-collapse-button"" role=""button"" data-toggle=""collapse"" data-target=""#brands-collapsed"" aria-expanded=""true"" aria-controls=""brands-collapsed"">
+      Brands
+    </div>
+    <div class=""view-collapse-content collapse"" id=""brands-collapsed"" data-parent=""#viewCustomFilters"">
+      <ul>
+        <li>
+          <strong>All</strong>
+        </li>
+        <li>
+          <a href=""#"">Link 5</a>
+        </li>
+        <li>
+          <a href=""#"">Link 6</a>
+        </li>
+        <li>
+          <a href=""#"">Link 7</a>
+        </li>
+        <li>
+          <a href=""#"">Link 8</a>
+        </li>
+      </ul>
+    </div>
+  </div>
+</div>
+
+<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"" integrity=""sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"" crossorigin=""anonymous"">
+<script src=""https://code.jquery.com/jquery-3.5.1.slim.min.js"" integrity=""sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"" integrity=""sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"" crossorigin=""anonymous""></script>
+<script src=""https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"" integrity=""sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"" crossorigin=""anonymous""></script>
+
+
+

",html +"select2 single select boxes multiple not working

here i use select option in one function is it possible? here I don't just use 4 select options but it can be 10 or unlimited, what's the best way?

+

my code :

+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet">
+
+<select id="selectss" style="width: 100%;">
+    <option value="1">01</option>
+    <option value="2">02</option>
+    <option value="3">03</option>
+</select>
+<br><br><br>
+<select id="selectss" style="width: 100%;">
+    <option value="1">04</option>
+    <option value="2">05</option>
+    <option value="3">06</option>
+</select>
+<br><br><br>
+<select id="selectss" style="width: 100%;">
+    <option value="1">07</option>
+    <option value="2">08</option>
+    <option value="3">09</option>
+</select>
+<br><br><br>
+<select id="selectss" style="width: 100%;">
+    <option value="1">Test</option>
+    <option value="2">Test</option>
+    <option value="3">Test</option>
+</select>
+
+<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
+<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
+
+<script>
+    $(document).ready(function() {
+       $("#selectss").select2();
+    });
+</script>
+
+

Previously I used the code below, but this is not the best way because it has to change all the ids in the select option :

+
<script>
+    $(document).ready(function() {
+        $("#selectss1, #selectss2, #selectss3, #selectss3, #selectss4").select2();
+    });
+</script>
+
","

Please use this method.

+
$(".selectss").select2();
+
+

Please change id to class. +This adds select2 to all elements with class containing "selectss". +You should not have duplicate IDs

",html +"How to move a text input to the top in a input field?

I've recently started learning Html and Css and I'm trying to move the word "Your Comment" to the top in the input field.

+
https://prnt.sc/1k74619
+
+
<div class="comment">
+<input placeholder="Your Comment" type="text" />
+</div>
+
+
.comment input {
+    width: 680px;
+    height: 169;
+    border: 0;
+    padding-left: 20px;
+    font-family: 'Montserrat';
+    outline-color: #b5b5b5;
+    margin-top: 30px;
+    margin-left: -115px;       
+}
+
","

<INPUT> tag is for single line text but <TEXTAREA></TEXTAREA> tag is for multi line text.

+Useful link: https://www.w3schools.com/html/html_form_elements.asp +

+
+
*{
+    box-sizing: border-box;
+}
+.comment input,
+.comment textarea{
+    font-family: 'Montserrat', Arial;
+    width: 100%;
+    max-width: 680px;
+    padding: 20px;
+    border: 1px solid #b5b5b5;
+    outline: none;
+    border-radius: 8px;
+    margin-bottom: 10px;
+}
+.comment textarea{
+    height: 169px;
+}
+.comment input:focus,
+.comment textarea:focus{
+    border: 1px solid #32babe;
+    box-shadow: 0 0 0 2px #32babe;
+}
+
<div class=""comment"">
+    <input type=""text"" placeholder=""Your Commnet - in single line"">
+    <textarea placeholder=""Your Comment - in multi lines""></textarea>
+</div>
+
+
+

",html +"a json telegram bot response always showing up after i submit the form , i want to just alert it using js

I wanted to send photo from this HTML to a group in telegram using a bot, then I found this code in this forum it works fine but after I submit the form, the browser opening a new tab then showing up a JSON response

+

what I want after I submit the form is just alert('photo has been sent!')

+

what should I do?

+
<form method="POST" target="_blank"
+action="https://api.telegram.org/bot{{ config('app.token') }}/sendPhoto" enctype="multipart/form-data">
+<input type="text" name="chat_id" value="{{ config('app.idgroup') }}" hidden />
+<input type="text" name="reply_to_message_id" value="{{ $rp->msg_id }}" hidden />
+<input type="text" name="allow_sending_without_reply" value="true" hidden />
+<br />
+<label for="caption"> Caption</label>
+<input type="text" name="caption" placeholder="caption" />
+<br />
+<input type="file" name="photo" />
+<br />
+<input type="submit" value="sendPhoto" />
+</form>
+
+

","
<script type="text/javascript">
+$(document).on("submit", "form", function (event) {
+    event.preventDefault();
+    $.ajax({
+        url: $(this).attr("action"),
+        type: $(this).attr("method"),
+        dataType: "JSON",
+        data: new FormData(this),
+        processData: false,
+        contentType: false,
+        success: function (data, status) {
+            alert('Success');
+        },
+        error: function (xhr, desc, err) {
+            alert('Error');
+        }
+    });
+});
+
",html +"Animating with Javascript

In this code, I was trying to move the yellow box (the small box) to the right, bottom, left, and top respectively in the red box (the big box) and I have wanted to move the yellow box unendly. I have moved the yellow box to the right and bottom but couldn't move to the left and top. I couldn't understand what the problem is. How should I write this code in Javascript? Could you help me, please? I have used Visual Studio Code.

+

+
+
 window.onload = function(){
+                var posX = 0,posY =0, posZ=0;
+                var smallbox = document.getElementById(""smallbox"");
+                var time = setInterval(move,10);
+    
+                function move(){
+                    if(posX>=150){
+                       if(posY>=150){
+                            if(posZ>=150){
+                                clearInterval(time);
+                            }
+                            else{
+                                posZ++;
+                                smallbox.style.right = posZ + ""px"";
+                            }
+                        }
+                        else{
+                            posY++;
+                            smallbox.style.top = posY + ""px"";
+                        }
+                    }
+                    else{
+                        posX = posX+1;
+                        smallbox.style.left = posX + ""px""; 
+                    }
+                }
+            }
+
        #bigbox{
+            height: 200px;
+            width: 200px;
+            background-color: red;
+            position: relative;
+        }
+        #smallbox{
+            height: 50px;
+            width: 50px;
+            background-color: yellow;
+            position: absolute;
+        }
+
<div id=""bigbox"">
+   <div id=""smallbox"">
+    
+   </div>
+</div>
+
+
+

","

The reason that your animation is not working is that CSS alignments for objects must use "top" or "bottom" and "left" or "right" to align themselves. What you are doing is aligning horizontally using "left" and then trying to align horizontally using "right", or the same thing but around the other way.

+

What I would instead suggest is using code that essentially reads:

+
if at top-left, move right.
+if at top-right, move down.
+if at bottom-right, move left.
+if at bottom-left, move up.
+
+

An example of this in action:

+

+
+
window.onload = function() {
+  var posX = 0,
+    posY = 0,
+    boxW = 200,
+    boxH = 200,
+    smallboxW = 50,
+    smallboxH = 50;
+  var smallbox = document.getElementById(""smallbox"");
+  var time = setInterval(move, 10);
+
+  function move() {
+    if (posY <= 0 && posX < boxW) {
+      // go right
+      posX++;
+      smallbox.style.left = posX + ""px"";
+    }
+    if (posX >= boxW - smallboxW && posY < boxH) {
+      // go down
+      posY++;
+      smallbox.style.top = posY + ""px"";
+    }
+    if (posY >= boxH - smallboxH && posX > 0) {
+      // go left
+      posX--;
+      smallbox.style.left = posX + ""px"";
+    }
+    if (posX <= 0 && posY > 0) {
+      // go up
+      posY--;
+      smallbox.style.top = posY + ""px"";
+    }
+  }
+}
+
#bigbox {
+  height: 200px;
+  width: 200px;
+  background-color: red;
+  position: relative;
+}
+
+#smallbox {
+  height: 50px;
+  width: 50px;
+  background-color: yellow;
+  position: absolute;
+}
+
<body>
+  <div id=""bigbox"">
+    <div id=""smallbox"">
+
+    </div>
+  </div>
+</body>
+
+
+

",html +"Styling a specific sentence in a paragraph with CSS

I want to only target this specific sentence (Starting at $2.00 / frame.) in a paragraph to apply CSS and it has to remain in the same line but when using other elements it skips one line.

+
<p>Assorted frames made of different material, including MDF, birchwood, and PDE. Select frames can be sanded and painted according to your needs. Starting at $2.00 / frame.</p>
+
+

Any help would be appreciated.

","

Just wrap your targeted element in span tag and apply style.

+

+
+
p .highlight {
+  color: red;
+  font-weight: bold;
+}
+
<p>Assorted frames made of different material, including MDF, birchwood, and PDE. Select frames can be sanded and painted according to your needs. Starting at <span class=""highlight""> $2.00 / frame. </span> </p>
+
+
+

+

[Note] Change style according to your need.

",html +"How create a printable report using html and css with ASP.NET Core?

I want to design a report with HTML and CSS, but I do not know how these forms are designed. Forms such as pay slips that can also be printed. See the pictures I posted below. Please help me. Thank you

+

+

","

You can try to use colspan and rowspan.Here is a simple demo:

+
    <table width="100%">
+    <tr>
+        <td colspan="9">first line</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td rowspan="2">
+            4
+        </td>
+        <td rowspan="2">
+            5
+        </td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td rowspan="2">
+            4
+        </td>
+        <td rowspan="2">
+            5
+        </td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td rowspan="2">
+            4
+        </td>
+        <td rowspan="2">
+            5
+        </td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td>6</td>
+        <td>7</td>
+        <td>8</td>
+        <td>9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td rowspan="2">
+            4
+        </td>
+        <td rowspan="2">
+            5
+        </td>
+        <td>6</td>
+        <td>7</td>
+        <td rowspan="2">8</td>
+        <td rowspan="2">9</td>
+    </tr>
+    <tr>
+        <td>1</td>
+        <td>2</td>
+        <td>3</td>
+        <td>6</td>
+        <td>7</td>
+
+    </tr>
+</table>
+   
+
+     <style>
+            table, th, td {
+                border: 1px solid black;
+                text-align:center;
+            }
+        </style>
+
+

result: +

+

You can also change width,height,text-align or background for each tr/td.

",html +"Save a canvas image to disk

Using js I was able to create a small script that is able to create random canvas images.
+To transform them to png I do the following:

+
var dataURL = canvas.toDataURL("image/png");
+window.open(canvas.toDataURL('image/png'));
+
+

This is fine for seeing the images in a separate browser tab, but I'd like it to save it to disk whenever I run the program. Is this possible?

+

Thanks.

","

I finally found a solution! Node apparently supports canvas and allows for saving the image to filesystem via fs.
+See here: https://www.youtube.com/watch?v=3c2EFpCr_vY

",html +"Call js function and send some data when click an option from dropdown in Datatable row

I'm looking for call a js function after click on my dropdown list. The code works, when I click it, it call myFunction. My problem is I need to add the datatable row into myFunction as a parameter.

+

My error: ReferenceError: Can't find variable: meta

+

I'm noob with javascript and html languages.

+
<script>
+function myFunction(selectObject, row) {
+    var value = selectObject.value; 
+    alert("Actualización Status: " + value + row);
+}
+</script>
+
+<script>
+    var json={{ posts_list | safe }};
+    $(document).ready(function() {
+        var table = $('#posts_table').DataTable( {
+            dom: 'Bfrtip',
+            buttons: [
+                'copy', 'csv', 'excel', 'print'
+            ],
+            "scrollX": true,
+            data: json.data,
+            columns:[
+                {defaultContent: ""},
+                {data: "_id"},
+                {
+                    "data": "status",
+                    "render": function(data, type, row, meta){
+                        if (data == 'no_denunciado') {
+                            data = '<select id="status" onchange="myFunction(this, meta.row)">' +
+                            '<option value="no_denunciado">' + data + '</option>' +
+                            '<option value="nuevo">Nuevo</option>' +
+                            '<option value="en_gestion">En Gestion</option>' +
+                            '<option value="baja_edenor">Baja</option>' +
+                            '</select>';
+                        }
+
","

meta.row is being used out of scope of the function you need to put in the data not the variable meta.data as that will fall out of scope like so.

+

change

+
data = '<select id="status" onchange="myFunction(this, meta.row)>'
+
+

to

+
data = '<select id="status" onchange="myFunction(this, \''+meta.row+'\')">'
+
+

EDIT from the chat I see that you want to string an object I wrote a quick function

+
function ObjectToString(myObject){
+var keys = Object.keys(myObject);
+var returnedString="";
+keys.forEach(key=>{returnedString+="["+key+":"+myObject[key]+"]";});
+return returnedString;
+}
+
",html +"Add page to PDF using Node WKHTMLTOPDF

I have a HTML template created using Handlebar. +Let us say I want to create 10 HTML file from that. +Now I want to print the 10 pages to the single pdf. +How can I do so in wkhtmltopdf? +How can I add pages in wkhtmltopdf? +Any help will be highly appreciated.

",

In order to add multiple pages to the pdf we have to take help of css page break.

,html +"Text position in table-style DIV when there's a picture?

I have this table-style DIV code for a used vehicle sales platform:

+

+
+
.mainwrapper {
+    border: 2px solid;
+    display: table;
+}
+
+.itemwrapper {
+    display: table-row;
+    width: 706px;
+}
+.mainwrapper {
+margin-bottom: 20px;
+}
+.item {
+width: 700px;
+border: 1px solid;
+padding: 1em;
+background-color: blue;
+color: white;
+}
+.item:nth-child(2) {
+float: left;
+margin: -2px;
+}
+.item1 {
+display: table-cell;
+text-align: left;
+margin-left: -30px;
+}
+.item1 p {
+margin-top: -30px;
+}
+.item-price {
+width: 300px;
+background-color: blue;
+padding: 1em;
+color: white;
+text-align: center;
+}
+.picture, .item {
+    display: table-cell;
+    border: 1px solid;
+}
+.picture {
+width: 90px;
+margin: 1px;
+border: 2px solid;
+}
+.picture img {
+height: 185px;
+}
+
  <div class=""mainwrapper"">
+    <div class=""itemwrapper"">
+        <div class=""item"">1992 ELDDIS PAMPEROS XLi</div>
+        <div class=""item-price"">£1,000</div>
+    </div>
+        <div class=""itemwrapper"">
+        <div class=""picture""><img src=""https://complianz.io/wp-content/uploads/2019/03/placeholder-300x202.jpg.webp""></div>
+        <div class=""item1""><p>2 berth, good condition</p></div>
+    </div>
+</div>
+  <div class=""mainwrapper"">
+    <div class=""itemwrapper"">
+        <div class=""item"">2008 SWIFT CHALLENGER 540</div>
+        <div class=""item-price"">£13,000</div>
+    </div>
+        <div class=""itemwrapper"">
+        <div class=""picture""><img src=""https://complianz.io/wp-content/uploads/2019/03/placeholder-300x202.jpg.webp""></div>
+        <div class=""item1""><p>4 berth end bedroom</p></div>
+    </div>
+</div>
+
+
+

+

What I am trying to do is ensure the class item1 is opposite the image, with the text like this if you didn't have the £ per month div and list as table: +

+

Basically, what I am trying to fix is the text that's in class item1 opposite the image (not with all the description or colored DIV there); see the image below.

+

I tried margin-left and margin-top, but it won't quite put the image opposite.

+

This is the result of my code: +

+

I can't quite get it to work as I'd expected, text opposite image and size of DIV in the CSS; if anyone can help, I'd much welcome this.

+

It works OK - no major coding errors, but isn't quite esthetically working out, and that's the basic problem.

+

I'm trying this as basic HTML first before attempting anything with Javascript, just to ensure it works as a standalone design.

+

Edit: I tried vertical-align for text, that worked, but it's fixing the gap between image div and text that's the issue. There's a large amount of space I don't know how to fix.

","

As the answer for the text is solved. You can change the column width by changing the css property of item. you can do it as follows. The width was 700px in your code you can reduce to get a smaller width. I changed it to 400px.

+
.item {
+width: 400px;
+border: 1px solid;
+padding: 1em;
+background-color: blue;
+color: white;
+}
+
",html +"PHP / HTML: Optionally add further filter options to search a database

Currently, I have a dropdown menu to select a specific column of a table in my database with a text field to search through column for matches. Nothing special so far, it just looks something like this:

+
<select name="option" id="option">
+   <option value="option1">Option 1</option>
+   <option value="option2">Option 2</option>
+   <option value="option3">Option 3</option>
+   <option value="option4">Option 4</option>
+</select>
+
+<input type="text" id="option1" name="option1"><br>
+
+

Now I would like to add more filter options, where I don't want to just write this code excerpt repeatedly one below the other. What I would like most is to be able to press something like a plus button and thus select another filter option.

+

+

I have no idea what to call this function or how to implement this. Anyone here who could help me please?

","

I think you want to clone your box (textbox and dropdown) - Here you can use the clone component to clone your elements

+
    <style>
+    .d-none{
+      display:none;
+    }
+    </style>
+    <div class="clone_component_1">
+    <select name="option" id="option">
+       <option value="option1">Option 1</option>
+       <option value="option2">Option 2</option>
+       <option value="option3">Option 3</option>
+       <option value="option4">Option 4</option>
+    </select>
+    
+    <input type="text" id="option1" name="option1">
+    <div class="">
+           <a href="javascript:;" onclick="remove_component(this, '1')" class="btn btn-danger btn-xs btn-bold remove_component_button_1 remove-button d-none"><i class="fa fa-minus-circle"></i></a>
+            <a href="javascript:;" onclick="clone_component(this, '1')" class="btn btn-primary btn-xs btn-bold clone_component_button_1 add-button"/><i class="fa fa-plus-circle"></i></a>
+    </div>
+ </div>
+    
+    <script>
+    //clone component
+    window.clone_component = function (t, n) {
+        var tr = $(t).closest('.clone_component_' + n);
+        var clone = tr.clone();
+        clone.find('input,textarea').val('');
+        tr.after(clone);
+        clone.find('.remove_component_button_' + n).removeClass("d-none");
+        if ($('.clone_component_' + n).length > 1) {
+            $('.remove_component_button_' + n).removeClass("d-none");
+        }
+    }
+    
+    //remove component
+    window.remove_component = function (t, n) {
+        if ($('.clone_component_' + n).length !== 1) {
+            $(t).closest('.clone_component_' + n).remove();
+            console.log('.clone_component_' + n);
+            console.log($('.clone_component_' + n).length);
+            if ($('.clone_component_' + n).length === 1) {
+                $('.remove_component_button_' + n).addClass("d-none");
+            } else {
+                $('.remove_component_button_' + n).eq(($('.clone_component_' + n).length - 1)).removeClass("d-none");
+            }
+        } else {
+            $('.remove_component_button_' + n).addClass("d-none");
+        }
+        $('.clone_component_button_' + n).eq(($('.clone_component_' + n).length - 1)).removeClass("d-none");
+    }
+    
+    </script>
+
+

try to use css and elements accordingly but this is and idea how you can clone the elements

",html +"undefined data in response

I have a fetch which returns a JSON when clicked on a Button.

+
$("#search").click(function(event){
+    var e = document.getElementById("lineDesc");
+    var line = e.options[e.selectedIndex].text;
+    var month = document.getElementById("descMonth").value;
+    var desc = $("#lineDescAr").val();
+    var search = document.getElementById("searchtab");
+    let fd = new FormData();
+        fd.set('line', line);
+        fd.set('month', month);
+        fd.set('desc', desc);
+
+    fetch('search.php',{method:'POST',body: fd})
+        .then( r=> {r.json(); console.log(r);})
+        .then( json=>{ //undefined even though response is json
+            search.innerHTML="";
+            Object.keys( json ).forEach( key=>{
+            let obj=json[ key ];
+            //search.innerHTML +='<div class="cell">'+/*line*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*scanner*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*fault*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*duration*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*date*/+'</div>';
+            })
+        })
+    event.preventDefault();
+});
+
+

When i run it, the .then(json=> is empty.

+

In the networkanalysis the response looks like this.

+
[{"line":"L411A","scanner":"Gesamt","fault":"elektrisch","description":"L411A-Test","duration":"100","date":"2021-08-17 07:09:27"}]
+
+

So it is not empty but the json is?

+

Appreciate any help.

+

Would also appreciate it if anyone could tell me how to properly access the returned data.

","

the first then did not returned any thing so the second get undefined as argument

+
$("#search").click(function(event){
+    var e = document.getElementById("lineDesc");
+    var line = e.options[e.selectedIndex].text;
+    var month = document.getElementById("descMonth").value;
+    var desc = $("#lineDescAr").val();
+    var search = document.getElementById("searchtab");
+    let fd = new FormData();
+        fd.set('line', line);
+        fd.set('month', month);
+        fd.set('desc', desc);
+
+    fetch('search.php',{method:'POST',body: fd})
+        .then( r=> r.json() )
+        .then( json=>{ //undefined even though response is json
+            search.innerHTML="";
+            Object.keys( json ).forEach( key=>{
+            let obj=json[ key ];
+            //search.innerHTML +='<div class="cell">'+/*line*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*scanner*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*fault*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*duration*/+'</div>';
+            //search.innerHTML +='<div class="cell">'+/*date*/+'</div>';
+            })
+        })
+    event.preventDefault();
+});
+
+
",html +"How to change clicked image in JavaScript?

I have two types of images and I named them xxxxx.jpg(1st) and xxxxxNoWall.jpg(2nd).
+I would like to make my page in a way that the 1st version is displayed normally, but when you click on it, the modal will show the 2nd version.
+However, so far I'm only able to make the modal display the same image as I clicked on. I guess the problem is somewhere in JavaScript where I can add "NoWall.jpg" behind the name of the original element?
+Can somebody help me with it, please?
+HTML: + +

+
    <div id="modal01" class="modal" onclick="this.style.display='none'">
+      <div class="modal-content">
+        <img id="img01" style="max-width:100%">
+      </div>
+    </div>
+
+

JavaScript:

+
   <script>
+    
+    if(window.innerWidth > 768){
+    function onClick(element) {
+      document.getElementById("img01").src = element.src;
+      document.getElementById("modal01").style.display = "block";
+    }} else {
+    function onClick(element) {
+      document.getElementById("modal01").style.display = "none";
+    }}
+    
+    </script>
+
+
+
+thanks very much!","

Well none of your code is changing xxxxx.jpg to xxxxxNoWall.jpg.
+Is this all the code you have?

+

You can use .replace(), for example:

+
  document.getElementById("img01").src = element.src.replace(/([^/]+)\.([^.]+)$/, '$1NoWall.$2');
+
+

This adds "NoWall" before the file extension.
+The first parameter of .replace() is a regular expression. In this case it works like this:
+https://regex101.com/r/0u9WUe/1

",html +"How can I insert CSS styles inside independent of specific elements?

Traditionally, you can add CSS in three ways:

+
    +
  1. External CSS via <link rel="stylesheet" href="foo.css">
  2. +
  3. Internal CSS via <style> h1 { ... } in the <head> element
  4. +
  5. Inline CSS via the style="..." attribute on specific elements
  6. +
+

Inline CSS has the drawback that I can't use CSS classes, which is something I need to do. Is there a way to define internal CSS (e.g. a <style></style> fragment in the <body> element?

+

This would be much easier for me because I could create a self-contained HTML snippet with a method in my server code. This kind of method is necessary because I don't control the <head> section. It is owned by a commercial product. I can only insert content inside the <body>.

+

Example:

+
<div>
+ <style>
+  .myclass {...}
+ </style>
+ <div class="myclass">...</div>
+</div>
+
+

Related: https://htmx.org/essays/locality-of-behaviour/

+

I have seen other websites (like https://amazon.com) where they appear to have several style tags inside the <body>.

+

There is a huge gap between theory and practice. Many sites use <style> in the body.

+

The editors decided against it. But maybe there will be a change in the future: https://github.com/whatwg/html/issues/1605

","

Under the premise, you don't care about invalid HTML in relation of <style> inside <body> (which is not that uncommon), you can assign unique identifier i.e.:

+

+
+
<style>
+  .my-class-1 {
+    color: gold;
+  }
+</style>
+<div class=""my-class-1"">Fragment Content</div>
+
+<style>
+  .my-class-2 {
+    color: tomato;
+  }
+</style>
+<div class=""my-class-2"">Fragment Content</div>
+
+<div class=""my-fragment-1"">
+  <style>
+    .my-fragment-1 .my-class {
+      color: teal;
+    }
+  </style>
+  <div class=""my-class"">Fragment Content</div>
+</div>
+
+<div class=""my-fragment-2"">
+  <style>
+    .my-fragment-2 .my-class {
+      color: hotpink;
+    }
+  </style>
+  <div class=""my-class"">Fragment Content</div>
+</div>
+
+<style id=""my-style-1"">
+  #my-style-1 + div {
+    color: orangered;
+  }
+</style>
+<div>Fragment Content</div>
+
+<style id=""my-style-2"">
+  #my-style-2 + div {
+    color: indigo;
+  }
+</style>
+<div>Fragment Content</div>
+
+
+

",html +"How to reinitialize a function in jQuery after having modified the DOM

Using a jQuery Plugin (Link to Plugin Code) I try to achieve a multi-select drop-down menu. Then I want to dynamically (depending on user input) change the menu-entries. The first part works fine, but changing menu-entries doesn't so far. Therefor I wanted to ask for help.

+

Here is the HTML part:

+
<select id="Fruits" name="Fruits" multiple="" style="display: none;">
+    <option value="1">Number1</option>
+    <option value="2">Number2</option>
+    <option value="3">Number3</option>
+</select>
+
+

Then I use that code to initialise the menu:

+
$(function(){
+   $('#Fruits').multiSelect({'noneText':'Select Fruits'});
+});
+
+

The result is precisely what I want:

+

+

Next I try to dynamically add a menu-entry. I do that by the following code:

+
   var option = document.createElement("option");
+   option.text = "Number4";
+   option.value = "4";
+   var select = document.getElementById("Fruits");
+   select.appendChild(option);
+
+

This is what I hope to achieve: +

+

However the result looks precisely like the first picture. Also running

+
$(function(){
+   $('#Fruits').multiSelect({'noneText':'Select Fruits'});
+});
+
+

again doesn't help.

","

Get the MultiSelect instance (.data("plugin_multiSelect")) from the <select> and call .updateMenuItems() after you've added the new elements:

+
$("select").data("plugin_multiSelect")
+           .updateMenuItems();
+
+

--
+The answer is based on the source code and a test on their demo page.

",html +"Filtering a table in javascript

I'm trying to filter a table using a JavaScript function, but I'm not sure what the issue is...When clicking the filter link, nothing happens, but it should be filtering the second column ("Platform" column) and only displaying rows with "TEST" in it.

+

I'm trying to debug it here:

+

https://jsfiddle.net/7vh5wmsx/

+
function filterTable(input) {
+        var filter = input.value.toUpperCase();
+        var table = document.getElementById("myTable");
+        var tr = table.getElementsByTagName("tr");
+        var tds = tr.getElementsByTagName('td');
+
+        for (var i = 0; i < tr.length; i++) {
+            if (tds[1].textContent.toUpperCase().indexOf(filter) > -1) {
+                tr[i].style.display = "";
+            } else {
+                tr[i].style.display = "none";
+            }
+        }
+    }
+
","

Use this code

+
function myFunction() {
+  // Declare variables
+  var input, filter, table, tr, td, i, txtValue;
+  input = document.getElementById("myInput");
+  filter = input.value.toUpperCase();
+  table = document.getElementById("myTable");
+  tr = table.getElementsByTagName("tr");
+
+  // Loop through all table rows, and hide those who don't match the search query
+  for (i = 0; i < tr.length; i++) {
+    td = tr[i].getElementsByTagName("td")[0];
+    if (td) {
+      txtValue = td.textContent || td.innerText;
+      if (txtValue.toUpperCase().indexOf(filter) > -1) {
+        tr[i].style.display = "";
+      } else {
+        tr[i].style.display = "none";
+      }
+    }
+  }
+}
+
+
",html +"TailwindCC: no-underline class does not work for my tag?

I'm trying to avoid having underlines under my <a> tags. I have added the class "no-underline" as per the docs but I'm still getting the underlines under my links? I have added the code im using below:

+
<div
+  class="
+    my-3
+    flex flex-wrap
+    -m-1
+    text-center
+    justify-center
+    items-center
+    no-underline
+  "
+>
+  <div class="m-auto">
+    {% for tag in tags %}
+    <a
+      href="{% routablepageurl blog_page 'post_by_tag' tag.slug %}"
+      class="no-underline"
+    >
+      <span
+        class="
+          font-mono
+          m-1
+          bg-gray-200
+          hover:bg-gray-300
+          rounded-full
+          px-2
+          py-1
+          font-bold
+          text-sm
+          leading-loose
+          cursor-pointer
+          shadow-lg
+          no-underline
+        "
+        >{{ tag }}</span
+      >
+    </a>
+    {% empty %} No tags yet {% endfor %}
+  </div>
+</div>
+
+Thanks for the help!
+
+
","

Add no-underline in to

+
<div class="m-auto">
+
+

And make sure that there are no underline class in the parent divs.

+

You can also try to add

+
style="text-decoration: none !important;"
+
+

into the divs tag if those doesn't work.

",html +"window onload function issue
window.onload = prepareButton;
+
+function prepareButton() {
+  document.getElementById('slist').onclick = function() {
+    window.location = "students";
+  }
+}
+
+

Once I click on a slist element which happens to be a <p> tag structured like this

+
<p type="button" id="slist" class="active">Student List</p>
+
+

It keeps the page reloading forever, I don't know why.

","

You should assign a whole URL or path to window.location, not just a word:

+

+
+
window.onload = prepareButton;
+
+function prepareButton() {
+  document.getElementById('slist1').onclick = function() {
+    window.location = ""stackoverflow.com/questions"";
+  }
+  document.getElementById('slist2').onclick = function() {
+    window.location = ""/questions"";
+  }
+  document.getElementById('slist3').onclick = function() {
+    window.location = ""../.."";
+  }
+}
+
All these buttons will take you to the StackOverflow questions overview.
+<p type=""button"" id=""slist1"">Using the whole URL</p>
+<p type=""button"" id=""slist2"">Using an absolute path</p>
+<p type=""button"" id=""slist3"">Using a relative path</p>
+
+
+

+

(Sorry - for some reason it doesn't work inside a StackSnippet …)

",html +"How to add a transparent Bootstrap Navbar to a Fullpage.js site?

I want to add a transparent Bootstrap Navbar to a page which use fullpage.js. I want to achieve something like this, so that the navbar stays on top of the page but doesn't push the website contents down. How can I do this? I tried the code below but it doesn't work. I tried looking for solutions online but I couldn't find one. Here is some sample code. As you can see the navbar is not even displaying.

+

+<html>
+
+<head>
+    <meta charset="UTF-8">
+
+    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/3.1.2/fullpage.css" integrity="sha512-TD/aL30dNLN0VaHVoh9voFlNi7ZuWQYtV4bkIJv2ulZ8mEEkZJ7IyGvDthMKvIUwzLmPONnjQlAi55HTERVXpw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
+
+    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/3.1.2/fullpage.min.js"></script>
+
+    <link href="css/master.css" type="text/css" rel="stylesheet" />
+
+    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
+        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
+
+    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+
+</head>
+
+<body>
+    
+    <div id="fullpage">
+        <nav class="navbar navbar-light bg-transparent" id="myMenu">
+            <!-- Brand -->
+            <a class="navbar-brand" href="#">Logo</a>
+    
+            <!-- Toggler/collapsibe Button -->
+            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"
+                style="border: none;">
+                <span class="navbar-toggler-icon"></span>
+            </button>
+    
+            <!-- Navbar links -->
+            <div class="collapse navbar-collapse" id="collapsibleNavbar">
+                <ul class="navbar-nav">
+                    <li class="nav-item">
+                        <a class="nav-link" href="index.html">Home</a>
+                    </li>
+                    <li class="nav-item">
+                        <a class="nav-link" href="about-us.html">About us</a>
+                    </li>
+                </ul>
+            </div>
+        </nav>
+
+        <div class="section">
+            <div class="container-fluid">
+                <h2>Lorem ipsum</h2>
+            </div>
+
+        </div>
+
+        <div class="section">
+            <div class="container-fluid">
+
+            </div>
+        </div>
+
+        </div>
+
+    <script>
+        new fullpage('#fullpage', {
+            //options here
+            menu: '#myMenu',
+            autoScrolling: true,
+            scrollHorizontally: true,
+            navigation: true,
+        });
+
+        //methods
+        fullpage_api.setAllowScrolling(true);
+    </script>
+
+    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
+        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
+    </script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
+        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
+    </script>
+    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
+        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
+    </script>
+</body>
+
+</html>
+
",

I managed to find a fix myself. I edited the css of the "navbar" class so instead of a relative position its position is fixed and now it works just as i wanted it to!

,html +"Regex to find comments in HTML JavaScript tag

If anyone who is better at regex could assist it would be greatly appreciated. I am trying to get the following regex (see URL) to find all HTML JavaScript comments within the script tag. This will run using Windows PowerShell for the task needed.

+

The below example is what I have so far. However, it still doesn't:

+
(?s)(?(?=\A).*?<script[^>]*>).*?(?:\K\/\/|<\/script>.*?(?:<script[^>]*>|\z)(*SKIP)(*FAIL))
+
+
    +
  • should highlight all the text to the right of the "//" until line-break
  • +
  • should not include URLs inside of the script tag
  • +
  • should not be case sensitive for the script tag
  • +
+

Example URL also including seven test scenarios: +https://regex101.com/r/YpCJXM/1

+

Goal: +If each of the scenarios could have the comment text highlighted while not including any of the extra areas outside of the script tag. As long as it works on regex101 I can make it work with PS!

+

Edit: I am fully aware you should not parse this with regex! However, I'm sure someone more skilled in regex could easily handle just completing the few scenarios needed for this task.

+

Edit_2: +The below is another example. However, it still doesn't:

+
(\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*)
+
+
    +
  • should only include text inside the script tag
  • +
+

Answer: +The below is a slight change of MikeM's answer to allow both http or https

+
(?si)(?<!http:|https:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)
+
","

The following is not foolproof but it passes your tests:

+
(?si)(?<!https:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)
+
+

The positive lookahead ensures the closing script tag comes before the opening script tag, ahead in the string.

+

Example usage:

+
$pattern = '(?si)(?<!https?:)\/\/[^\r\n]*(?=(?:(?!<script[^>]*>).)*<\/script>)'
+$results = $data | Select-String $pattern -AllMatches
+$results.Matches.Value
+
+// find this comment here
+//find this comment here
+//find this comment here
+// find this comment here
+// find this comment here
+//find this comment here
+// find this comment here
+//find this comment here
+//find this comment here with this included also!
+
",html +"Confused About the Arguments for Canvas Method putImageData()

+

I have two canvases, shown in the attached image. +Each canvas has a width and height of 100 pixels. +Assume I have used the canvas method getImageData() +to create an image data object:

+
var c1 = getElementById("canvas1");
+var ctx1 = c1.getContext("2D");
+var imageData = ctx1.getImageData(0,0,c1.width,c1.height);
+
+

I would like to copy the lower left quadrant of canvas1 +to the upper right quadrant of canvas2. After reading +documentation on the 7-argument version of putImageData() +I thought the following would result in "C" appearing +in the upper right quadrant of canvas2:

+
ctx2.putImageData(imageData,50,0,0,50,50,50);
+
+

This didn't work. Instead the "C" appeared in the lower right +quadrant of canvas2.

+

I assumed the first two numbers (50,0) specified the x,y coords +of the upper left corner of the destination area. I also thought +the next two numbers (0,50) specified the upper left corner +of the rectangular area inside imageData that is to be copied. +The last two numbers (50,50) are the width and height of the +rectangular area to be copied.

+

I hope someone can show me the correct parameters to use.

+

Thank you.

","

The meaning of the additional parameters of the putImageData method are indeed a bit confusing.

+

If you determine 0,50,50,50 for those it does not mean that it just copies the data of the lower half of your 100x100 imageData. In fact, it just masks the upper half (effecively making it invisible) - the data to be drawn is still the whole 100 x 100 area.

+

If you want the lower-left quadrant copied to the upper-right, you have to shift it up by 50 pixels vertically.

+

+
+
let canvas = document.getElementById(""canvas"");
+let ctx1 = canvas.getContext(""2d"");
+let ctx2 = document.getElementById(""canvas2"").getContext(""2d"");
+
+ctx1.font = '16px sans-serif';
+ctx1.fillText('A', canvas.width * .25, canvas.height * .25);
+ctx1.fillText('B', canvas.width * .75, canvas.height * .25);
+ctx1.fillText('C', canvas.width * .25, canvas.height * .75);
+ctx1.fillText('D', canvas.width * .75, canvas.height * .75);
+
+let imageData = ctx1.getImageData(0, 0, canvas.width, canvas.height);
+ctx2.putImageData(imageData, 50, -50, 0, 50, 50, 50);
+
canvas {
+  background: PaleTurquoise;
+}
+
<canvas id=""canvas"" width=""100"" height=""100""></canvas>
+<canvas id=""canvas2"" width=""100"" height=""100""></canvas>
+
+
+

",html +"Using form labels for multiple elements

My page has many js-generated form elements which can exist simultaneously but need to be created from the same block of code (jsx, react). My problem is that I need to give labels to all these form elements for semantics and seo, but I can't give them all the same id (becuase html ids are unique). Is the only option to dynamically generate unique html ids? Is there any way to do this with html classes?

+

My code would look something like this:

+
function cardEditor() {
+    return (
+        <form>
+            <label for="card-title">Title: </label>
+            <input type="text" id="card-title">
+            <button type="submit">Save</button>
+        </form>
+    );
+}
+
","

You can pass id as props to your component

+
const Input = ({ id }) => {
+    return <>
+       <label for={id}>Title: </label>
+       <input type="text" id={id}>
+    </>
+}
+function cardEditor() {
+    return (
+        <form>
+            <Input id="card-title-1" />
+            <Input id="card-title-2" />
+            <Input id="card-title-3" />
+            <button type="submit">Save</button>
+        </form>
+    );
+}
+
+

or generate unique ids for your form elements

+
const uuid = () => Math.random().toString(36).slice(-6);
+
+const Input = () => {
+    const id = uuid();
+    return <>
+       <label for={id}>Title: </label>
+       <input type="text" id={id}>
+    </>
+}
+
+function cardEditor() {
+    return (
+        <form>
+            <Input/>
+            <Input/>
+            <Input/>
+            <button type="submit">Save</button>
+        </form>
+    );
+}
+
",html +"Hibernate and Jackson manyToMany relation with extra fields

Recently I've been trying to link a Module table and an Activity table by a Many to Many relationship. +This relation welcomes an additional field as below.

+
-------------------------------------------------------------
+| Module        |   ModuleHasActivities |     Activities    |
+-------------------------------------------------------------
+| id            |  Module_idModule      |   id              |   
+| Name          |  Activity_idActivity  |   Name            |
+| Observations  |  Day                  |   Price           |
+-------------------------------------------------------------
+
+

I use JsonManagedReference and JsonBackReference to avoid infinite loops. Unfortunately the result is not the expected one since I don't get the list of modules from the activities and vice versa. The only information returned are the entity fields.

+
@Entity
+@Table(name = "Module")
+public class Module implements Serializable {
+
+    @Id
+    @GeneratedValue
+    @Column(name = "idModule")
+    private int id;
+    
+    // Other fields plus getter and setter
+
+    @OneToMany(mappedBy = "module", cascade = CascadeType.ALL)
+    @JsonBackReference
+    private Set<ModuleHasActivities> moduleHasActivities = new HashSet<>();
+}
+
+
@Entity
+@Table(name = "Activite")
+public class Activite implements Serializable {
+
+    @Id
+    @GeneratedValue
+    @Column(name = "idActivite")
+    private int id;
+
+    // Other fields
+
+    @OneToMany(mappedBy = "activite", cascade = CascadeType.ALL)
+    @JsonBackReference
+    private Set<ModuleHasActivities> moduleHasActivities = new HashSet<>();
+}
+
+
@Entity
+@Table(name = "Module_has_Activite")
+public class ModuleHasActivities implements Serializable {
+
+    @Id
+    @ManyToOne
+    @JoinColumn(name = "Module_idModule")
+    @JsonManagedReference
+    private Module module;
+
+    @Id
+    @ManyToOne
+    @JoinColumn(name = "Activite_idActivite")
+    @JsonManagedReference
+    private Activite activite;
+
+    @Column(name = "IdJour")
+    private int jour;
+
+}
+
+

Query modules response:

+
[
+    {
+        "id": 1,
+        "code": "TT1",
+        "title": "Test 1",
+        "description": "Nothing",
+        "observations": "Nothing",
+    }
+]
+
+

What I expect (something like this) :

+
[
+    {
+        "id": 1,
+        "code": "TT1",
+        "title": "Test 1",
+        "description": "Nothing",
+        "observations": "Nothing",
+        "activities": [
+          "day1": 
+          {
+           //fields of activities
+          },
+          "day2": 
+          {
+           //fields of activities
+          },
+    ]
+    }
+]
+
+

When I debug hibernate's SQL queries, we see that the join is never done. And that's what interests me! Joints to the module table are missing. +

+

A little help would be appreciated,

+

Thank you

+

Already visited links : +Extra fields for many to many relations

","

Finally, I solved my problem. Instead of using a composite key, I changed my database model to use a primary id key and 2 references to my concerned tables. Mapping is easier and I get my information.

",r +"Java Spring Unsupported StringMatcher REGEX

There is an issue when attempting to use StringMatcher.REGEX with java spring. There is no compiler error or anything, but when you attempt to call the item using the above string matcher, you receive the following error:

+
2020-10-09 15:07:30.543 ERROR 29584 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Unsupported StringMatcher REGEX; nested exception is java.lang.IllegalArgumentException: Unsupported StringMatcher REGEX] with root cause
+
+java.lang.IllegalArgumentException: Unsupported StringMatcher REGEX
+    at org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder.getPredicates(QueryByExamplePredicateBuilder.java:210) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
+    at org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder.getPredicate(QueryByExamplePredicateBuilder.java:102) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
+    at org.springframework.data.jpa.repository.support.SimpleJpaRepository$ExampleSpecification.toPredicate(SimpleJpaRepository.java:886) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
+    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.applySpecificationToCriteria(SimpleJpaRepository.java:762) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
+
+

The error can be seen when executing something along the lines of:

+
ExampleMatcher matcher = ExampleMatcher
+                                .matchingAll()
+                                .withStringMatcher(
+                                        ExampleMatcher.StringMatcher.REGEX
+                                 );
+
+

Note that the above code compiles just fine, the error happens when it is executed.

","

First, StringMatcher.REGEX is an entirely valid value. As you can see inside the ExampleMatcher.class file, you have 6 valid StringMatcher options:

+
    public static enum StringMatcher {
+        DEFAULT,
+        EXACT,
+        STARTING,
+        ENDING,
+        CONTAINING,
+        REGEX;
+
+        private StringMatcher() {
+        }
+    }
+
+

Because it is a valid entry, the code will compile just fine and see no issue. +The problem is that the regex option only works in Java, not Java Spring. The spring documentation for query by example states:

+
+

Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.

+
+

However, this is not the case. According to a jira ticket for Spring, there is no support for StringMatcher.REGEX and there never will be, because not all database systems support it. Basically, you only have access to DEFAULT, EXACT, STARTING, ENDING, and CONTAINING string matcher items and REGEX will never work. I hope this answer saves someone a lot of time. I wasted too much trying to figure it out.

",r +"problem upload image with 'rn-fetch-blob' in 'IOS'

I use rn-fetch-blob to upload an image. This works correctly in Android but does not work in iOS. +I use data parameter in response to create image link , and when I check response from iOS I found data is null in iOS response . I don't know why why data parameter is null when status is 200.

+

I tried all answers for same issues but they did not work for me!

+

code for Upload Image:

+
export const UploadImageService2 = async (
+  file: any,
+): AxiosRequestConfig => {
+  console.log("UploadImageService2");
+  console.log("file: " + file);
+  let seps = `${file.path}`.split('/');
+  let filename = seps[seps.length - 1];
+  var fp = file.path + "";
+  const realPath = Platform.OS === 'ios' ? fp.replace('file://', '') : fp;
+  console.log("fb: " + fp);
+  console.log("filePath: " + realPath);
+
+  const data = [
+    {
+      name: 'Files',
+      filename,
+      type: file.mime,
+      // binary field data from a file path, use `wrap` method to wrap the path
+      data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
+      // binary field data encoded in BASE64
+      // data: RNFetchBlob.base64.encode(file),
+    },
+  ];
+  console.log("dataObj: " + JSON.stringify(data));
+  const response = await RNFetchBlob.fetch(
+    'POST',
+    `${BaseUrl}api/image`,
+
+    {
+      Authorization: 'Bearer ',
+      'Content-Type': 'multipart/form-data',
+    },
+    data,
+  );
+
+  return {
+    ...(response ? response : {}),
+    ...file,
+  };
+
+};
+
+
+

That's function called by this:

+
 _uploadSingleImage = async (file: any, sendCheckupForm) => {
+    console.log("_uploadSingleImage");
+    console.log("_file: " + JSON.stringify(file));
+    let response = await UploadImageService2(file);
+    // let response = await UploadImageService(file);
+    console.log('resp=>>>', response)
+    if (get(response, ['respInfo', 'status']) === 200) {
+      console.log("okkk");
+      const responseData = get(response, ['data'], file.name);
+      console.log("responseData: " + JSON.stringify(responseData));
+      const fileUrl = responseData.replace(/^"(.+(?="$))"$/, '$1');
+      // const fileUrl = 'myTestImage';
+      const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'success', FileName: fileUrl } : i);
+      console.log("attachedFiles: " + JSON.stringify(attachedFiles));
+      this.setState({ attachedFiles });
+      console.log('fileUrl', fileUrl)
+      this.setState({ receptionImage: fileUrl });
+      if (sendCheckupForm) {
+        // this.setState({showCheckupForm: false});
+        this.props.sendCheckupForms(
+          this.props.token,
+          this.props.orderDetails.Id,
+          {
+            fileList: [fileUrl],
+          },
+        );
+        this.props.getOrder(this.props.token, this.props.orderId);
+      }
+    } else {
+      console.log("Erorrr");
+      const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'error' } : i);
+      this.setState({ attachedFiles });
+    }
+  };
+
+

This is example Json response for rn-fetch-blob in iOS:

+
{ taskId: 'jgd8phv6w98zryggebvvkg',
+  type: 'utf8',
+  respInfo: 
+   { redirects: [ 'https://cp.azmayeshonline.com/api/image' ],
+     status: 200,
+     timeout: false,
+     taskId: 'jgd8phv6w98zryggebvvkg',
+     headers: 
+      { 'x-aspnet-version': '4.0.30319',
+        'Content-Length': '42',
+        'x-frame-options': 'AllowAll',
+        Date: 'Tue, 27 Oct 2020 19:34:43 GMT',
+        Expires: '-1',
+        Server: 'Microsoft-IIS/10.0',
+        'Content-Type': 'application/json; charset=utf-8',
+        'Cache-Control': 'no-cache',
+        'x-powered-by': 'ASP.NET',
+        Pragma: 'no-cache' },
+     respType: 'json',
+     state: '2',
+     rnfbEncode: 'utf8' },
+  info: [Function],
+  array: [Function],
+  blob: [Function],
+  text: [Function],
+  json: [Function],
+  base64: [Function],
+  flush: [Function],
+  session: [Function],
+  readStream: [Function],
+  readFile: [Function],
+  exif: null,
+  filename: 'IMG_0002.JPG',
+  path: '/Users/mesimac/Library/Developer/CoreSimulator/Devices/52589261-2055-4237-9DED-E4F8D71FD25B/data/Containers/Data/Application/5FC9EEDF-5710-4935-9380-F03114B291CF/tmp/react-native-image-crop-picker/7EF8432F-53A3-4A41-8068-159A5990623C.jpg',
+  height: 1024,
+  width: 1541,
+  data: null,
+  modificationDate: '1441224147',
+  localIdentifier: 'B84E8479-475C-4727-A4A4-B77AA9980897/L0/001',
+  size: 304799,
+  sourceURL: null,
+  mime: 'image/jpeg',
+  cropRect: null,
+  creationDate: '1255122560',
+  status: 'loading' }
+
+

Anyone suggestions for how I can handle this?

","

Try using:

+
data:RNFetchBlob.wrap(realPath)
+
+

instead of:

+
data:RNFetchBlob.wrap(decodeURIComponent(realPath))
+
+

The rest of your code looks fine. Anyway, you are replacing the fp.replace('file://', ''), which is needed for iOS.

+

This is how I did it in my code:

+
data:RNFetchBlob.wrap(this.state.file.uri.replace("file://", ""))
+
",r +"Cannot access updated data from useReducer hook in function defined in setTimeout

In my application, I'm using a dispatch from useReducer hook on click of a button and in the same function I'm using a setTimeout of 2 seconds. But when I store the data using dispatch of usereducer then I'm not getting updated value in setTimeout function.

+

I cannot share original code, but sharing a snippet of another demo app where this issue occurs.

+
const initialData = { data: "ABC" };
+
+function reducer(state = initialData, action) {
+  switch (action.type) {
+    case "STORE":
+      return {
+        ...state,
+        data: action.payload
+      };
+    default:
+      return state;
+      break;
+  }
+}
+function Demo() {
+  const [state, dispatch] = React.useReducer(reducer, initialData);
+  console.log("Render : ",state.data);  //Will be executed on each rendering
+  const handleClick = () => {
+    dispatch({
+      type: "STORE",
+      payload: state.data + parseInt(Math.random() * 10)
+    });
+    setTimeout(() => {
+      console.log("ButtonClick : ",state.data); //Will be executed after 2 seconds of dispatching.
+    }, 2000);
+  };
+  return <button onClick={handleClick}>{state.data}</button>;
+}
+ReactDOM.render(<Demo />, document.getElementById("app"));
+
+
+
+

In above example I'm storing data in reducer using dispatch, and I'm calling console.log("ButtonClick") on Button Click after 2 seconds but even after 2 seconds, I'm not getting updated data in console. But in console.log("Render") I'm getting updated data.

+

Live example on : https://codepen.io/aadi-git/pen/yLJLmNa

","

When you call

+
const handleClick = () => {
+  dispatch({
+    type: "STORE",
+    payload: state.data + parseInt(Math.random() * 10)
+  });
+  setTimeout(() => {
+    console.log("ButtonClick : ",state.data); //Will be executed after 2 seconds of dispatching.
+  }, 2000);
+};
+
+

this is what happens:

+
    +
  1. Run dispatch with an object to store some data. This function is executed asynchronically, so the result is not available immediately.

    +
  2. +
  3. Register a timeout handler, which logs the current value of state.data to the console. Since the preceding dispatch is still working in progress, the value of state.data is still the old one.

    +

    This means you can not log a new dispatched value by running console.log after your dispatch call because you can not see into the future. You can only log the new data after a re-render of your component due to changing state. Then you can and should use

    +
    React.useEffect(() => {
    +  console.log(state.data);
    +}, [state.data]);
    +
    +
  4. +
+

Some more explanations about setTimeout and why console.log logs old values within it

+

You use

+
setTimeout(() => {
+  console.log("ButtonClick : ", state.data);
+}, 2000);
+
+

and this is equivalent to

+
const callback = () => console.log("ButtonClick : ", state.data);
+setTimeout(callback, 2000);
+
+

In the first line you create a function (named callback here), which prints some text. This text consists of a simple string and the value of state.data. Therefore this function has a reference to the variable state.data. The function in combination with the reference to the outer state is called closure and this closure ensures, that the value state.data is kept alive as long as the function lives (is not binned by the garbage collector).

+

In the second line setTimeout is called with this function. Simplified this means a task is stored somewhere which states, that exactly this function has to be executed after the given timeout. So as long as this task is not done, the function stays alive and with it the variable state.data.

+

In the meantime long before the task is handled, the new action is dispatched, new state calculated and Demo re-rendered. With that a new state.data and a new handleClick is created. With the new creation of handleClick also a new function is created which is passed to setTimeout. This whole handleClick function is then passed as onClick handler for the button element.

+

The re-render is now over, but the task from before is still pending. Now when the timeout duration ends (long after re-rendering the component) the task is taken from the task queue and executed. The task still has reference to the function from the render before and this function still has reference to the value state.data from the render before. So the value logged to the console is still the old value from the render before.

",r +"airflow - use an operator inside a function

Im planning to use an airflow operator inside a function and then call it from a different task. For me, the task ran successfully, but it didn't trigger the operator inside the function.

+
def func():
+    t1 = BashOperator(
+            task_id='print_date',
+            bash_command='touch /tmp/aaaaaaaaaaaaa'
+        )
+    t1
+
+main_dag = DAG(
+    'bhuvitest',
+    default_args=args,
+    description='A simple tutorial DAG',
+    schedule_interval=timedelta(days=1),
+    catchup=False
+)
+
+bhuvitest = PythonOperator(
+        task_id='python_task', 
+        python_callable=func,
+        dag = main_dag)
+
","

The following should work instead of t1:

+
t1.execute(dict())
+
+

The airflow.operators documentation can give more details.

",r +"React-native-gifted-chat with cloud firestore pagination

I'm using Firestore to store messages. In order to optimize the mobile application performances, I would like to set a limit(50) in the firestore query. +It works well and implemented the onLoadEarlier React-native-gifted-chat available in the props.

+

All is working fine.

+

But, when I send a new message in the chat, after scrolled up to see the earliers messages, only the 50 last messages with the new one, off course, are available.

+

So, each time I'm adding a message in the Firestore database, the onSnapshot (in the useeffect) is executed and apply the limit query.

+

Is there a way to avoid this ?

+

Thanks.

+

Here my useEffect :

+
useEffect(() => {
+    const messagesListener = firestore()
+    .collection('groups')
+    .doc(group._id)
+    .collection('messages')
+    .orderBy('createdAt', 'desc')
+    .limit(50)
+    .onSnapshot(querySnapshot => {
+        const newMessages = querySnapshot.docs.map(doc => {
+            const firebaseData = doc.data();
+
+            const data = {
+                _id: doc.id,
+                text: '',
+                createdAt: new Date().getTime(),
+                ...firebaseData
+            };
+
+            return data;
+        });
+
+        setMessages(previousMessages => {
+            return GiftedChat.append(previousMessages, newMessages);
+        });
+    });
+
+    return () => messagesListener();
+}, []);
+
","

I am using FlatList in react-native to render chats and I had to paginate the chats list. Since Firestore query cursor is not supported in live listener, I created two list, recentChats & oldChats.

+

I populate recentChats using live listener query.onSnapshot & oldChats using cursor startAfter. FlatList data is combination of both list and I take care of merging logic.

+
const MESSAGE_LIMIT = 15;
+
+const ChatWindow = props => {
+  const { sessionId, postMessage, onSendTemplateButtonPress } = props;
+
+  // Firestore cursor is not supported in query.onSnapshot so maintaining two chat list
+  // oldChats -> chat list via cursor, recentChats -> chat list via live listener
+  const [oldChats, setOldChats] = useState([]);
+  const [recentChats, setRecentChats] = useState([]);
+
+  // if true, show a loader at the top of chat list
+  const [moreChatsAvailable, setMoreChatsAvailable] = useState(true);
+
+  const [inputMessage, setInputMessage] = useState('');
+
+  useEffect(() => {
+    const query = getGuestChatMessagesQuery(sessionId)
+      .limit(MESSAGE_LIMIT);
+    const listener = query.onSnapshot(querySnapshot => {
+      let chats = [];
+      querySnapshot.forEach(snapshot => {
+        chats.push(snapshot.data());
+      });
+      // merge recentChats & chats
+      if (recentChats.length > 0) {
+        const newRecentChats = [];
+        for (let i = 0; i < chats.length; i++) {
+          if (chats[i].sessionId === recentChats[0].sessionId) {
+            break;
+          }
+          newRecentChats.push(chats[i]);
+        }
+        setRecentChats([...newRecentChats, ...recentChats]);
+      } else {
+        setRecentChats(chats);
+        if (chats.length < MESSAGE_LIMIT) {
+          setMoreChatsAvailable(false);
+        }
+      }
+    });
+
+    return () => {
+      // unsubscribe listener
+      listener();
+    };
+  }, []);
+
+  const onMessageInputChange = text => {
+    setInputMessage(text);
+  };
+
+  const onMessageSubmit = () => {
+    postMessage(inputMessage);
+    setInputMessage('');
+  };
+
+  const renderFlatListItem = ({ item }) => {
+    return (<ChatBubble chat={item} />);
+  };
+
+  const onChatListEndReached = () => {
+    if (!moreChatsAvailable) {
+      return;
+    }
+    let startAfterTime;
+    if (oldChats.length > 0) {
+      startAfterTime = oldChats[oldChats.length - 1].time;
+    } else if (recentChats.length > 0) {
+      startAfterTime = recentChats[recentChats.length - 1].time;
+    } else {
+      setMoreChatsAvailable(false);
+      return;
+    }
+    // query data using cursor
+    getGuestChatMessagesQuery(sessionId)
+      .startAfter(startAfterTime)
+      .limit(MESSAGE_LIMIT)
+      .get()
+      .then(querySnapshot => {
+        let chats = [];
+        querySnapshot.forEach(snapshot => {
+          chats.push(snapshot.data());
+        });
+        if (chats.length === 0) {
+          setMoreChatsAvailable(false);
+        } else {
+          setOldChats([...oldChats, ...chats]);
+        }
+      });
+  };
+
+  return (
+    <View style={[GenericStyles.fill, GenericStyles.p16]}>
+      <FlatList
+        inverted
+        data={[...recentChats, ...oldChats]}
+        renderItem={renderFlatListItem}
+        keyExtractor={item => item.messageId}
+        onEndReached={onChatListEndReached}
+        onEndReachedThreshold={0.2}
+        ListFooterComponent={moreChatsAvailable ? <ActivityIndicator /> : null}
+      />
+      {
+        Singleton.isStaff ?
+          null:
+          <ChatInput
+            onMessageInputChange={onMessageInputChange}
+            onMessageSubmit={onMessageSubmit}
+            inputMessage={inputMessage}
+            style={GenericStyles.selfEnd}
+            onSendTemplateButtonPress={onSendTemplateButtonPress}
+          />
+      }
+    </View>
+  );
+};
+
",r +"How to get a Truncated text value in React Native?

Is there exist some way to get the Truncated text in RN when we use numberOfLines?

+For example:

+

Component

+
 <Text style={{width: 50}} numberOfLines={3}>
+    Some very long text with tons of useful info
+ </Text>
+
+

Output

+
 Some
+ very
+ long...
+
+

I want to know what exactly the text is visible to the end-user. Is it possible somehow?

+

Thanks for any help!

+

P.S. I tried to use Ref features to get the content but it contains props with the whole text so it didn't help

","

You can use the onTextLayout prop like this.

+

The e.nativeEvent.lines has each line in the text, if you have the text and the number of lines then you can use this array like below and view the texts in each line. This works in Android not sure about web.

+
export default function App() {
+  
+  const text =
+    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
+
+  const lines = 3;
+
+  return (
+    <View style={{ flex: 1 }}>
+      <Text
+        onTextLayout={(e) => {
+          const shownText = e.nativeEvent.lines.slice(0, lines).map((line) => line.text).join('');
+          alert(shownText);
+          const hidenText = text.substring(shownText.length);
+          alert(hidenText);
+        }}
+        numberOfLines={lines}
+        onPress={this.toggleUser}>
+        {text}
+      </Text>
+    </View>
+  );
+}
+
",r +"""runreadytoruncompiler"" error with .net core 3.1 when publishing a single file probject

I have an F# project that I build this way:

+
+

dotnet publish --nologo -r osx-x64 -c Release --self-contained true /p:PublishSingleFile=true /p:PublishTrimmed=true /p:PublishReadyToRun=true

+
+

and I get pages of this:

+
RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Resources.IResourceWriter' from assembly 'System.Text.RegularExpressions, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. while resolving 0x10000ce - System.Resources.IResourceWriter. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.JavaScriptEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0x2000045 - System.Text.Json.JsonWriterOptions. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.JavaScriptEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0x2000046 - System.Text.Json.Utf8JsonWriter. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.JavaScriptEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0x1000011 - System.Text.Encodings.Web.JavaScriptEncoder. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.TextEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0x10000ad - System.Text.Encodings.Web.TextEncoder. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.TextEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0xa00023c - System.Text.Encodings.Web.TextEncoder.FindFirstCharacterToEncodeUtf8. [/Users/thomas/Projects/test/test.fsproj]
+RUNREADYTORUNCOMPILER : warning : Could not load type 'System.Text.Encodings.Web.TextEncoder' from assembly 'System.Memory, Version=4.2.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. while resolving 0xa00023f - System.Text.Encodings.Web.TextEncoder.FindFirstCharacterToEncode. [/Users/thomas/Projects/test/test.fsproj]
+
+

What does this error mean?

+

I have another project I build with the exact same command line without any problem.

+

If I remove the single file attribute, then it will build properly.

+

How to troubleshoot this? the error message doesn't really explain me what's going on.

","

Adding this to the project file to fix JavaScriptEncoder:

+
<TrimmerRootAssembly Include="System.Text.Encodings.Web" />
+
+

And this for IResourceWriter:

+
<TrimmerRootAssembly Include="System.Resources.Writer" />
+
+

ReadyToRun sometimes needs help (or its just buggy) on what to include, you can read more here

",r +"ConsoleLogger writing logs out of order in aws lambda with 3.1

We have an AWS lambda with .net core 3.1, we use dependency injection to add some services, one of those services is a ConsoleLogger, we inject the logger like this:

+
private void ConfigureServices(IServiceCollection services)
+{
+    this.Configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();
+    services.AddOptions();
+    services.AddLogging(builder =>
+    {
+        builder.AddConsole((x) =>
+        {
+            x.DisableColors = true;
+            x.Format = Microsoft.Extensions.Logging.Console.ConsoleLoggerFormat.Systemd;
+        });
+    });
+    
+    // more services
+}
+
+

Then in the function we use the logger like this:

+
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
+public async Task Handle(ILambdaContext lambdaContext)
+{
+    var logger = this.ServiceProvider.GetService<ILogger<MyClass>>();
+
+    string startTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
+    logger.LogInformation($"Start Time stamp:{startTime}|AwsRequestId:{lambdaContext.AwsRequestId}");
+    
+    // more work
+    logger.LogInformation("processing x");
+    // more work
+    string endTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
+    logger.LogInformation($"End Time stamp:{endTime}|AwsRequestId:{lambdaContext.AwsRequestId}");
+}
+
+

The problem is that in cloudwatch the logs are out of order +

+

Even the report of the cost is before my entry.

+

Is there a way to avoid this?

+

Thanks

","

ConsoleLogger buffers messages in an internal queue, so they're probably getting delayed there, and it's nothing to do with CloudWatch. Amazon's own CloudWatch logging library does the same thing, and they note in their own documentation that it can be a problem for Lambdas: https://github.com/aws/aws-logging-dotnet/#aws-lambda

+

Their recommended solution is to use Amazon.Lambda.Logging.AspNetCore which doesn't do any buffering.

",r +"Custom size material-ui button

I am usimng material-ui with NextJs and would like a button about 4x the width of a large button. +The width property does not seem to have any effect

+

The Component

+
export function ShiButton(props) {
+const classes = useStyles();
+
+const {
+    path,
+    text,
+    colour = "primary",
+    variant = "contained",
+    size = "large",
+} = props;
+return (
+    <Link href={path} passHref>
+        <Button size={size} variant={variant} color={colour} width={900}>
+            {text}
+        </Button>
+    </Link>
+);
+
+

} +Calling page

+
    <ShiButton path="\" text="Sign-up" size="large" />
+
","

You can use Material-UI's styling solution in your app :

+

This is the CSS for the large button

+

+

So just increase padding and/or font-size by X to achieve greater width

+

+
+
const useStyles = makeStyles({
+  FourTimesLargeBtn: {
+    padding: ""32px 88px"",
+    fontSize: ""3.75rem""
+  }
+});
+
+function ShiButton(props) {
+  const classes = useStyles();
+
+  const {
+    path,
+    text,
+    colour = ""primary"",
+    variant = ""contained"",
+    size = ""large""
+  } = props;
+  return (
+    <Link href={path}>
+      <Button
+        classes={{ root: classes.FourTimesLargeBtn }}
+        size={size}
+        variant={variant}
+        color={colour}
+        width={900}
+      >
+        {text}
+      </Button>
+    </Link>
+  );
+}
+
+function App() {
+  return <ShiButton text=""Hello"" />;
+}
+
+
+ReactDOM.render(<App/>, document.getElementById(""root""));
+
<div id=""root""></div>
+
+<script src=""https://unpkg.com/react@16/umd/react.development.js""></script>
+<script src=""https://unpkg.com/react-dom@16/umd/react-dom.development.js""></script>
+<script src=""https://unpkg.com/babel-standalone@6/babel.min.js""></script>
+<script src=""https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js""></script>
+
+<script type=""text/babel"">
+  const { Button, makeStyles, Link } = MaterialUI;
+</script>
+
+
+

",r +"EventSource dynamic binding variable

I try to update and display message from variable updated into EventSource function:

+
ngOnInit(): void {
+     const EventSource: any = window['EventSource'];
+     const fx = new EventSource('/weather/update/');
+     fx.onmessage = function (evt) {
+          this.newMessage  = evt.data;
+          console.log(this.newMessage);
+     }
+}
+
+

in template:

+
<p>{{newMessage}}</p>
+
+

The received message always is empty, but in console i can see the new message.

","

You're loosing context this. Try using arrow function in order to preserve this:

+
               like this     
+                  \/
+fx.onmessage = evt => {
+   this.newMessage  = evt.data;
+   console.log(this.newMessage);
+}
+
",r +"Changing the information before serialization

I have a database model like:-

+
class Script(db.Model):
+   path = db.Column(db.String(50))
+
+

and a serializer like:-

+
class ScriptSchema(ma.Schema):
+   class Meta:
+      fields = (
+          'path'
+   )
+
+

My question is that when I dump the data after querying:-

+
all_scripts_orm = Script.query.all()
+all_scripts = ScriptSchema(many=True).dump(all_scripts_orm)
+
+

I get data in the form of

+
[
+   {"path": "Sample_folder/Sample_Script_1.txt"},
+   {"path": "Sample_folder/Sample_script_2.txt"}
+]
+
+

But I want to be able to do extract only the name of the script and serialize it

+
[
+    {"path": "Sample_script_1.txt"},
+    ...
+]
+
+

How do I approach this problem as I don't want to make another column just for name in the Script Model ?

","

Use a Function field, documentation example here and documented here. For example:

+
from os import path as op
+
+class ScriptSchema(ma.Schema):
+   class Meta:
+      fields = (
+          'path'
+   )
+
+   path = fields.Function(lambda obj: op.basename(obj.path))
+
",r +"How to overwrite a file of nodemobules on Heroku?

I want to overwrite a file of nodemobules on Heroku using the following npm script. +
What should I do to find the location of the file?

+

replaceScript.js

+
const data = "fixedcode";
+fs.writeFile('LOCATION_PATH_OF_A_FILE_OF_HEROKU_NODE_MODULE', data, (err) => 
+{console.log("soxError",err);
+});
+
+

package.json

+
"scripts": {
+"postinstall": "node replaceScript.js"
+},
+
","

You can use __dirname to get the location of the replaceScript, and from there, navigate around to node_modules and to the nested file. For example, if replaceScript is in the same directory as node_modules:

+
// replaceScript.js
+
+// The following test will pass when on Heroku:
+if (process.env._ && process.env._.includes('heroku')) {
+    const path = `${__dirname}/node_modules/some-package/index.js`;
+    require('fs').writeFileSync(path, data);
+}
+
",r +"Override Field Option on Inherited Model in Django

I've found similar questions and answers, but none seems exactly right. I've got an abstract base model like so:

+
class BaseModel(models.Model):
+    timestamp = models.DateTimeField(auto_now_add=True)
+    modified = models.DateTimeField(auto_now=True)
+    description = models.CharField(max_length=512, blank=True, null=True, help_text='Help')
+
+    class Meta:
+        abstract = True
+
+

And then I'm inheriting from it:

+
class AnotherModel(BaseModel):
+    field1 = models.CharField(max_length=512)
+
+

But I want this model's help_text on the description field to be something else, like help_text='Some other help text'

+

What's the best way to do this? Can I override options on fields from inherited models?

","

If this is really about the help text, I suggest to just override the ModelForm. However, you can use a factory and return the inner class:

+
def base_factory(description_help: str = "Standard text"):
+    class BaseModel(models.Model):
+        timestamp = models.DateTimeField(auto_now_add=True)
+        modified = models.DateTimeField(auto_now=True)
+        description = models.CharField(
+            max_length=512, blank=True, null=True, help_text=description_help
+        )
+
+        class Meta:
+            abstract = True
+
+    return BaseModel
+
+
+class ConcreteModel(base_factory("Concrete help")):
+    field1 = ...
+
",r +"Total value of warehouse active record

I have the object Tool and I need to calculate the cost of all the Tools in the warehouse. +I can sum the column price Tool.sum(:price) but i need to sum (quantity * price) of all the table Tools. +Thanks in advance.

+
create_table "tools", force: :cascade do |t|
+    t.integer "quantity"
+    t.string "name"
+    t.integer "price"
+    t.boolean "avilable"
+    t.string "store"
+    t.string "comments"
+    t.datetime "created_at", precision: 6, null: false
+    t.datetime "updated_at", precision: 6, null: false
+  end
+
","

Check out the example listed for ActiveRecord::Calculations#calculate.

+

You can do the following:

+
  Tool.sum("quantity * price")
+
",r +"Libraries cannot be found on Dataflow/Apache-beam job launched from CircleCI

I am having serious issues running a python Apache Beam pipeline using a GCP Dataflow runner, launched from CircleCI. I would really appreciate if someone could give any hint on how to tackle this, I've tried it all but nothing seems to work.

+

Basically, I'm running this python Apache Beam pipeline which runs in Dataflow and uses google-api-python-client-1.12.3. If I run the job in my machine (python3 main.py --runner dataflow --setup_file /path/to/my/file/setup.py), it works fine. If I run this same job from within CircleCI, the Dataflow job is created, but it fails with a message ImportError: No module named 'apiclient'.

+

By looking at this documentation, I think I should probably use explicitely a requirements.txt file. If I run that same pipeline from CircleCI, but adding the --requirements_file argument to a requirements file containing a single line (google-api-python-client==1.12.3), the dataflow job fails because the workers fail too. In the logs, there's a info message first ERROR: Could not find a version that satisfies the requirement wheel (from versions: none)" which results in a later error message "Error syncing pod somePodIdHere (\"dataflow-myjob-harness-rl84_default(somePodIdHere)\"), skipping: failed to \"StartContainer\" for \"python\" with CrashLoopBackOff: \"back-off 40s restarting failed container=python pod=dataflow-myjob-harness-rl84_default(somePodIdHere)\". I found this thread but the solution didn't seem to work in my case.

+

Any help would be really, really appreciated. Thanks a lot in advance!

","

This question looks very similar to yours. The solution seemed to be to explicitly include the dependencies of your requirements in your requirements.txt

+

apache beam 2.19.0 not running on cloud dataflow anymore due to Could not find a version that satisfies the requirement setuptools>=40.8

",r +"What MySQL collation to select when storing MD5 CHAR(32)?

I am storing MD5 hashes as indexes of some records, I understand a good data type for this is CHAR(32), but what should I select for collation ?

+

I assume it is relevant that MD5 only support these characters: abcdef0123456789 so I need a collation that supports very few characters and no special ones ?

+

Eider way, which one is best collation ? Many other data rows use utf8_general_ci in my db.

","

Will you need to have "A" == "a"? If so, you need a case-folding COLLATION.

+

But first, I suspect your question is really about CHARACTER SET. This is the encoding of the characters. Almost any character set can handle hex characters. ascii is fine; latin1 is fine. I would not use any character sets other than those for MD5, UUID, country_code, postal_code, etc. And, since each of those is constant length, CHAR(..) is useful. Virtually everywhere else, VARCHAR(..) is 'better'.

+

"Collation" has to do with sorting and comparing. Once you have decided on CHARACTER SET ascii (or latin1), then you need to decide whether you will ever need to compare a1b2 = A1B2. If so, use ascii_general_ci (or latin1_general_ci). The "ci" means "case insensitive".

+

If you will never mix capitalization, ascii_bin (latin1_bin) is fine and is a trivial amount faster. "bin" means "just compare the bits"; that is, no case folding, accent stripping. etc.

+

Even better might be to convert from CHAR(32) to BINARY(16) via UNHEX() and go the other way via HEX(). This has no collation and cuts the space used in half. (But it makes the string unprintable.)

+

For other columns, ... The character set utf8mb4, not utf8, is needed for Chinese and Emoji (like your picture). I can't judge whether the _general_ci collation is appropriate without understanding more about your application.

",r +"How do I make a delay when using a .mcfunction file? closed

I'm trying to make a map like the new Among Us game pooping about but I'm running into a problem.

+

I cant make a delay between commands.

+

I tried on my own, but changed to looking up tutorials but their only for Minecraft Java Edition. +I tried many things like using the scoreboard command but it uses repeating commands which you cant do in a mcfunction files. +I have also tried making a command that sets a delay but I cant use it in a .mcfunction file due to it being a 'custom' command +Secondly I don't understand how to code commands anyway.

+

Can I have some help please?

","

Use schedule.

+

To create one:

+
schedule function <function> <time> [append|replace]
+
+

To clear one:

+
schedule clear <function>
+
",r +"ASP .NET - JSON Serializer not working on class instances

Anonymous objects are automatically serialized as expected when returned from controller action. +When returning class instance, http response contains only empty json body, why? Where is this documented?

","

Ok, I forgot to add default { get; set; } to the properties, this seems to be compulsory for the json serializer.

",r +"my pytesseract is not working(i need help)

my plan is to make a bot that will answer a bot on messenger

+

the messenger bot messages are randomized number or a math questionaire bot

+

so i want to make a bot that will answer the messenger bots qustions

+

i made a code like this:

+
import pyautogui
+import pytesseract
+from PIL import Image
+
+

i want to take screenshot every 10 seconds

+
pyautogui.sleep(2)
+
+

sleep for two seconds to give me time to switch from pycharm to messenger

+
pyautogui.screenshot('x_value.png', confidence=0.8)
+img = Image.open('x_value.png')
+img = pytesseract.image_to_string(img)
+print(img)
+
+

here is the taken screenshot by my bot

+

here is the result:

+
Tee oxHj
+
+

i tried resizing the image using tuple but I still get the wrong result....i hope ypu guys help me so i can improve my skills....thank you

","

It worked when I inverted the image. But I wasn't able to use .png format so I tried in .jpg format and it worked. You can try this.

+
import pytesseract
+from PIL import Image, ImageOps
+
+img = Image.open('f1.jpg')
+img = ImageOps.invert(img)
+img = pytesseract.image_to_string(img)
+print(img)
+
+

Hope I helped.

",r +"Graph API - Create Application with authorization_code token

I'm trying to register an application in Azure AD using Graph API with an oauth token obtained with the Authorization Code grant type. I can do it with Client Credentials, but not with Authorization Code. With the latter I can list applications, but not create them. +Here's the permissions I've set in the application: +

+

And here's what I set in postman to get the token: +

+

I get the token just fine and I can list the applications, but when I try to create a new one through the endpoint 'POST https://graph.microsoft.com/v1.0/applications' I get the following response: +

+

Anyone knows why this is happening? Thanks!

","

According to the last screenshot you provided, it seems the process stopped at login page(the response body is the html of login page) when do authorization code flow.

+

I test it in my side(also in postman) but it works fine, below is my configuration in postman for your reference:

+

+

+

Although I didn't reproduce your problem in my test, but I can provide you some information about authorization code backend request to know what does the response in your postman mean.

+

When we do authorization code flow(not in postman) to get access token, there are two steps. First we need to request the url https://login.microsoftonline.com/{tenantId or commone}/oauth2/authorize?resource=https://graph.microsoft.com&client_id={clientId}&response_type=code&redirect_uri=https://hurytest&response_mode=query in your browser like below screenshot. +

+

We can find the content in the red box in screenshot above is same to the response you get in postman. So I think the process stopped here(which is the first step of authorization code flow).

+

Second step, we need to input username and password into the login page. It will redirect to another page like below screenshot. +

+

Copy the code after code= in the above screenshot and then use the code in below request to get access token.

+

+

In a word, I didn't reproduce your problem in my postman. But the backend request in your postman may stopped in the first step(login page) of authorization code flow which I mentioned above. So please check if you configured correct in postman. If still doesn't work, you can do authorization code flow by the two steps I provided to get the access token.

",r +"Why am I getting syntax error on the return line?

Why am I getting syntax error on the return line?

+
def with_argument_dump(function, *args, **kwargs):
+    
+def function_with_argument_dump(*args, **kwargs):
+    argStr = ', '.join(map(str, args))
+    kwargsStr = ','.join(f'{k}={v}' for k,v in kwargs.items()
+
+
+    return (f"fct w/args:{function.__name__}({','.join([argStr,kwargsStr])})")
+
","

You are missing a ) in the kwargsStr line:

+
kwargsStr = ','.join(f'{k}={v}' for k,v in kwargs.items()
+
+

Should be:

+
kwargsStr = ','.join(f'{k}={v}' for k,v in kwargs.items())
+
",r +"Authenticating a Vuejs frontend with an Express Backend

I am looking for some advice on implementing authentication when the client and the server live in separate projects.

+

The Server

+

This API was built as an Express Server. It has routes for CRUD operations with a MySQL database. It also has a user model that utilize bcrypt to encrypt passwords. There is no Frontend, in this project.

+

The Client

+

This is a Vue project made with the vue-cli and hits the above API to get the data to display.

+

The Issue

+

I need to add authentication. I was thinking I would do this with express-session, but I am a little confused with how exactly it works. All of the tutorials I have seen use express-session in combination with passport. This seems fine, but in all the examples passport forwards to a login page that lives on the server. This is usually written in handlebars or some other templating framework. I am not sure the best way of implementing since the login page lives in the client project.

+

How I thought it worked (Am I missing something?)

+

I was originally of the impression that for a new user express-session would create a token that I would save in the users table (maybe generated at login and stored temporarily). Once the user logs in with the correct password this token is passed to the client to be stored as a cookie. When the client wants access to restricted data, it would pass the token as a Authentication header to the server to get permission.

+

The Questions

+
    +
  1. Since my projects are separated is passport still useful for my use case?
  2. +
  3. Is it secure to create the session cookie on the server and send the token to the client as a response to the client's login POST?
  4. +
  5. Do I need to store the session token in the database?
  6. +
  7. Is there a better option?
  8. +
","

In my project I have almost the same setup, and I ended up with JWT to generate an access token.

+

The cycle begins with the user sending his/her email and password to my login endpoint.

+

In this stage I hash the password using some secret string, fetch the user from database and check if authentication succeed.

+

After that I generate an access token with an expiring time set, and I expected this access token in all protected routes.

+

With this approach you can easily implements refresh token to exchange at time to time, saving the refresh token in your database.

+

This is very simple and Is good to you understand how the process of authentication is done.

+

jsonwebtoken

",r +"After updating from Eclipse 2020-06 to 2020-09, Java support is gone

I was developing in Java on Eclipse for Java Developers 2020-06 on Windows 10 and decided to run updates, which installed Eclipse 2020-09. When Eclipse restarted, I created a new workspace. When I opened Preferences, there was no longer a Java section. The only Java search result was in Oomph:

+

+

The Java New Project wizard was also gone. (I checked under Other.)

+

The installation details still show Eclipse IDE for Java Developers and Eclipse Java Development Tools:

+

+

How do I reenable Java support?

+

Update

+

Here is the eclipse.ini file:

+
-startup
+plugins/org.eclipse.equinox.launcher_1.5.800.v20200727-1323.jar
+--launcher.library
+plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.1300.v20200819-0940
+-product
+org.eclipse.epp.package.java.product
+-showsplash
+org.eclipse.epp.package.common
+--launcher.defaultAction
+openFile
+--launcher.defaultAction
+openFile
+--launcher.appendVmargs
+-vmargs
+-Dosgi.requiredJavaVersion=11
+-Dosgi.instance.area.default=@user.home/eclipse-workspace
+-XX:+UseG1GC
+-XX:+UseStringDeduplication
+--add-modules=ALL-SYSTEM
+-Dosgi.requiredJavaVersion=11
+-Dosgi.dataAreaRequiresExplicitInit=true
+-Xms256m
+-Xmx2048m
+--add-modules=ALL-SYSTEM
+
","

Just to be clear, I assume you have specified a Java 11 JDK (or newer) in the "-vm" arguments in your "eclipse.ini" file? 2020-09 requires at least Java 11 to run.

+

I would create a new workspace.

",r +"Assign combinations of conditions to a new column in a dataframe through dictionaries

I am trying to use a combinations of dictionaries to generate a conditional column in a dataframe.

+

The first dictionary contains a list of all possible conditions which results in a bool True or False.

+

The second dictionary assigns combinations of conditions to business rules I want to call in order to generate a conditional column in my dataframe.

+
# testing df
+d = {'col1': [1, 2, 3, 4, 5], 'col2': ['apple', 'pear', 'banana', 'apple', 'cookie']}
+
+# making the df
+df = pd.DataFrame(d)
+
+# all possible testing conditions
+df_conds = {
+    1: eval("df['col1'] == 3"),
+    2: eval("df['col1'] >= 3"),
+    3: eval("df['col2'] == 'apple'")
+}
+
+# assigning combinations of conditions to business rules
+df_cond_assignments = {
+    'br1' : [1, 2],
+    'br2' : [1, 2, 3],
+    'br3' : [3],
+    'br4' : [2, 3]
+}
+
+

I want to call br4 for instance, and generate my conditional column by applying conditions 2 and 3.

+
result_df['result'] = df_conds[df_cond_assignments.get('br4')]
+
+

That code results in TypeError: unhashable type: 'list' and I understand why. However, I'm not sure how to do what I'm trying to do.

+

Another way I tried was

+
result_df = df_conds.get(key for key in [df_cond_assignments.get('br4')])
+
+

Which returns None

+

For example, if I apply br4 the correct result would look like:

+
result:
+false
+false
+false
+true
+false
+
","

Does this work for you:

+
np.logical_and.reduce([df_conds[i] for i in df_cond_assignments['br4']])
+
+

Output:

+
array([False, False, False,  True, False])
+
",r +"Resize UIImage to fit UIImageView in Swift

I am trying to change the image of a imageview programmatically after it has been downloaded.

+

It works fine - it downloads the image but I have 1 problem.

+

When I change the image of the uiimageview, it changes its dimensions and becomes huge, basically taking up the entire screen. I don't understand it, since I have set the uiimageview to only be 175 x 175 points in size. I know that the image I am downloading is much bigger, but I want the image to be scaled down so it just fills the available space in the imageView, but it seems my imageView is stretching to accommodate the entire image.

+

Is there any way around this issue?

+

So far I have:

+
cell.backgroundImage.image = item.image
+
+

simply setting it - I have also tried to change the frames both before and after, but nothing works:

+
cell.backgroundImage.frame = CGRect(x: 8, y: 15, width: 175, height: 175)
+
+

Hope you can help me out, I am really lost here.

+

Thanks all! Stay safe <3

","

You have to change the contentMode of the imageView

+
cell.backgroundImage.contentMode = .scaleAspectFill
+
+

this will fill and you can clip the extra parts of the image. by clipping them:

+
cell.backgroundImage.clipsToBounds = true
+
+

You can also use .scaleAspectFit if you prefer

",r +"How to change backgroud color when in focus, not in focus or the field is empty in flutter

I want to make a text form field so that the color of the field changes when I press the text form field, Changes color when text form field is empty and changes color when the content is there. Same as to the border of the text form field. how can I do this? Kindly refer me to an example if possible.

","

You can use the onTap parameter of the TextFormField by calling setState to update the colors, before this assign the Form Field color and border configuration to variables and use set State to update the color and configuration once the TextFormField is tapped

",r +"get total from recursion

I have an array of object which have reference to its collection

+
const data = [{
+    id: 1,
+    name: 'A',
+    referer_id: null,
+    point: 4
+  },
+  {
+    id: 2,
+    name: 'B',
+    referer_id: 1,
+    point: 100
+  },
+  {
+    id: 3,
+    name: 'C',
+    referer_id: null,
+    point: 4
+  },
+  {
+    id: 4,
+    name: 'D',
+    referer_id: 1,
+    point: 2
+  },
+  {
+    id: 5,
+    name: 'E',
+    referer_id: null,
+    point: 4
+  },
+  {
+    id: 6,
+    name: 'F',
+    referer_id: null,
+    point: 4
+  },
+  {
+    id: 7,
+    name: 'G',
+    referer_id: 2,
+    point: 4
+  },
+];
+
+

the referer id will refer to the id. And I have another array of number used to calculate the point

+
const pointsByLevel = [0.5, 0.3, 0.2]; // this would be dynamic from database
+
+

as of now, I can get the sum of all total like this

+
function getPoint(user_id) {
+  const mainUserPoint = data.find((u) => u.id === user_id).point;
+  let sum = 0;
+  
+  for (let subdep of data.filter((d) => d.referer_id === user_id)) {
+    sum += getPoint(subdep.id);
+  }
+  return mainUserPoint + sum;
+}
+
+

but the real challenge is the first level should return the point only but afterward the point will be multiplied to pointsByLevel based on the index

+

so the output will be like this

+
console.log(getPoint(1));
+/**
+A - 4
+B D - [100 * 0.5], [2 * 0.5]
+G - [4 * 0.3]
+**/
+
+// 4 + 50 + 1 + 1.2 = 56.2
+
+

So the end result I'm gonna get 56.2

+

What is the most efficient way to do this

","

You'll have to keep track of how many levels deep you are as an additional argument to getPoint. Set the default to 0, and the increment it each time you recurse. You can then find the corresponding points by level for it. (I inserted a 1.0 coefficient for level 0). I also added a comment to show the partial results at each level.

+

+
+
const data = [
+  { id: 1, name: 'A', referer_id: null, point: 4 },
+  { id: 2, name: 'B', referer_id: 1, point: 100 },
+  { id: 3, name: 'C', referer_id: null, point: 4 },
+  { id: 4, name: 'D', referer_id: 1, point: 2 },
+  { id: 5, name: 'E', referer_id: null, point: 4 },
+  { id: 6, name: 'F', referer_id: null, point: 4 },
+  { id: 7, name: 'G', referer_id: 2, point: 4 }
+];
+
+const pointsByLevel = [1, 0.5, 0.3, 0.2]; //  NOTE: I added a 1.0 for level 0
+
+function getPoint(user_id, level = 0) {
+  const user = data.find((u) => u.id === user_id);
+  const mainUserPoint = user.point;
+  let sum = 0;
+
+  for (let subdep of data.filter((d) => d.referer_id === user_id)) {
+    let val = getPoint(subdep.id, level + 1);
+    sum += val;
+  }
+  let result = (mainUserPoint * pointsByLevel[level]) + sum;
+  console.log(`getPoint for ${user_id} ""${user.name}"" is ${level} levels deep and has the value ${result}`)
+  return result;
+}
+
+console.log(getPoint(1));
+
+
+

",r +"Groupby date and process by a given time interval using pandas

I have a large dataframe containing several months' data and I need to process data between [09:00:00-11:59:59] for each of the 31 days.

+

The structure of the dataframe (df) looks as below:

+
id,date,value
+5,2012-03-01 00:00:00,0
+2,2012-03-01 00:00:00,0
+3,2012-03-01 00:00:00,0
+1,2012-03-01 00:00:00,0
+4,2012-03-01 00:00:00,0
+
+

I can easily filter the dataframe for times between [09:00:00 - 11:59:59] using:

+
indx = pd.DatetimeIndex(df['date'])
+df1 = df.iloc[indx.indexer_between_time('09:00:00','11:59:59')]
+
+

And I can also group each day's dataframe using:

+
df['date'] = pd.to_datetime(df['date'])
+df_grouped = df.groupby([df['date'].dt.date])
+df_list = []
+for idx, data in df_grouped:
+    df_list.append(data)
+
+

How can I tie this together to get a list of dataframes containing only data between [09:00:00-11:59:59]. The intention is to loop through the dataframes with data for [09:00:00-11:59:59] and pass each of them into some function for further processing:

","

You already have df1, now groupby on that:

+
df_grouped = df1.groupby(pd.to_datetime(df1['date']).dt.date) )
+df_list = [d for _,d in df_grouped]
+
",r +"Why response type is different?

I am building a simple gallery management app with React Native. +In gallery page, I called "FetchGallery" function and in there, I got some response.

+
+

This is constructor part.

+
+
this.state = {
+  mainGalleryData: [
+    {
+      bg_url: '',
+      country_id: 0
+    }
+  ],
+};
+
+
+

That is the code for response.

+
+
  _onFetchGalleryBySite = (e) => {
+    fetch(config.api.getGalleryInfo + '/' + e, {
+      method: 'GET',
+      headers: this.state.myHeaders
+    })
+      .then((response) => response.json())
+      .then((responseJSON) => {
+        console.log('resJSON=>', responseJSON['gallery_list']);  // => log is in the below.
+        responseJSON['gallery_list'].map(item => {
+          if (item != "") {
+            let obj = {}
+            obj.bg_url = item.bg_url
+            obj.country_id = item.country_id
+            this.state.mainGalleryData.push(obj)
+          }
+        })
+      })
+      .catch(err => console.log('_onFetchGalleryInfoErr=>', err))
+  }
+
+
+

This is the log of fetched data

+
+
resJSON => [{ "bg_url": "staff_upload/bgremoval_20201008030228.png", "country_id": "3" },  
+            { "bg_url":"Guest/1/image/bgremoval_20201004222851.png", "country_id": "3" }]
+
+

And in the render() , I used this data in the flatList

+
+

That is the code for FlatList

+
+
    <FlatList
+      data={mainGalleryData}
+      renderItem={this.renderGallery}
+      keyExtractor={(item, index) => index.toString()}
+    />
+
+
+

This is the renderGallery.

+
+
  renderGallery = (item) => (
+    <TouchableOpacity onPress={() => console.log('itemClicked=>', item)} style={styles.overlay}>
+      <Image source={newImg} style={styles.newImg} />
+      {
+        this.state.gallery_id == item.location_id ?
+          <Text style={{ fontWeight: '700' }} numberOfLines={1}>{item.item.title}</Text>
+          :
+          <Text style={{ fontSize: 12 }} numberOfLines={1}>{item.item.title}</Text>
+      }
+    </TouchableOpacity>
+  )
+
+

When I click one of those data, I want to get this data. But the result is different that I expect.

+
I want:  { "bg_url": "staff_upload/bgremoval_20201008030228.png", "country_id": "3" } 
+result:  { "index": 2, "item": {"Guest/1/image/bgremoval_20201004222851.png", "country_id": "3"}}  
+
+

So I had to get country_id with "item.item.country_id".

+

I want to get country_id with "item.country_id".

+

What is this <"index": 2> ?

","
+

Before pushing response in state, please clear "mainGalleryData[]" +because default it has 1 item in state which makes index +inappropriate.

+
+

Do this

+
console.log('resJSON=>', responseJSON['gallery_list']);
+const responseData = responseJSON['gallery_list'];
+const data = this.state.mainGalleryData.concat(responseData); <-- add this line -->
+this.state({ mainGalleryData: data });
+
",r +"How do I format my GET request to the Spotify Web API in Python?

I'm new to working with APIs. I'm trying to create a script that will output the tracks of a public playlist from Spotify. I have hit a roadblock at an early stage: I'm unsure how exactly to format my GET request to retrieve the tracks of the playlist in question and where I put the OAuth access token. My current attempt returns a 401 status code.

+

What I've done so far:

+
    +
  • I have created an App on the Spotify Developers website dashboard.
  • +
  • I have saved client_id and client_secret from the dashboard into a script ("spotifysecrets.py").
  • +
  • I have run the following code in my main script:
  • +
+
import requests
+
+from spotifysecrets import client_id as cid, client_secret as cs
+
+AUTH_URL = "https://accounts.spotify.com/api/token"
+
+token_req = requests.post(AUTH_URL, {
+    "grant_type": "client_credentials",
+    "client_id": cid,
+    "client_secret": cs
+    })
+
+access_token = token_req.json()["access_token"]
+
+

Everything appears to have worked fine so far. The problem occurs in the next step.

+
    +
  • Having obtained the token, I am getting a 401 error when trying to make my tracks request. The code I have written is as follows:
  • +
+
pl_id = "…"  # I have elided the actual playlist ID for the purposes of this question
+tracks = "https://api.spotify.com/v1/playlists/{}/tracks".format(pl_id)
+songs_req = requests.get(tracks, {
+    "Authorization": "Basic {}".format(access_token)
+    })
+
+

Edit

+

I have tried using

+
songs_req = requests.get(tracks, headers={
+    "Authorization": "Basic {}".format(access_token)
+    })
+
+

instead but this gives a 400 error.

","

I looked into the api and I believe you have a syntax error:

+
songs_req = requests.get(tracks, {
+    "Authorization": "Basic {}".format(access_token)
+    })
+
+

should be:

+
songs_req = requests.get(tracks, {
+    "Authorization": "Bearer {}".format(access_token)
+    })
+
",r +"Disabling single button

I am having a problem of disabling single button

+

When I click to order for $10 it disables all buttons, and I only want the one which I have clicked to be disabled

+

+
+
$(document).ready(function() {
+  $('.btn-checkout').click(function(e) {
+    $('.btn-checkout').html('proccesing order');
+    $('.btn-checkout').attr(""disabled"", true);
+  });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+<form method=""POST"">
+  <button type='button' class='btn-checkout'> order for $10</button>
+  <button type='button' class='btn-checkout'> order for $20</button>
+  <button type='button' class='btn-checkout'> order for $30</button>
+</form>
+
+
+

","

Use $(this) which is the actual clicked item accessed by the selector

+

+
+
$(function() {
+  $('.btn-checkout').on('click',function(e) {
+    $(this).html('proccesing order');
+    $(this).attr(""disabled"", true);
+  });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+<form method=""POST"">
+  <button type='button' class='btn-checkout'> order for $10</button>
+  <button type='button' class='btn-checkout'> order for $20</button>
+  <button type='button' class='btn-checkout'> order for $30</button>
+</form>
+
+
+

+

I would also delegate so you could add more buttons later

+

+
+
$(function() {
+  $('#container').on('click','.btn-checkout',function(e) {
+    $(this).html('proccesing order');
+    $(this).attr(""disabled"", true);
+  });
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+<form method=""POST"">
+<div id=""container"">
+  <button type='button' class='btn-checkout'> order for $10</button>
+  <button type='button' class='btn-checkout'> order for $20</button>
+  <button type='button' class='btn-checkout'> order for $30</button>
+</div>  
+</form>
+
+
+

",r +"Can I assign a variable as value to an object's key?

Is this allowed?

+
export class H{
+passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
+...
+
+validatePassword(control: FormControl) {
+...
+    return (REG_EXP.test(password)) ? null : {
+      validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
+        valid: false,
+        message:  this.passwordErrorMessage //can I do this?
+      } 
+    };
+  }
+}
+
+

For one of my test cases, I am getting the following error

+
TypeError: Cannot read property 'passwordErrorMessage' of undefined
+Error object: Property name: ngDebugContext, value: [object Object]
+Error object: Property name: ngErrorLogger, value: function () { [native code] }
+TypeError: Cannot read property 'passwordErrorMessage' of undefined
+    at HelperService.validatePassword (webpack:///./src/app/helper.service.ts?:224:31)
+
+

It seems this is undefined. I am still in early stages of debugging but my first doubt is if the usage of this is correct? Things work fine if I change the usage to message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'

","

yes you can, but you'll need to either bind validatePassword to the class or use an arrow function to pass this context into the function. this should work:

+
export class H{
+    passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
+    ...
+
+    validatePassword = (control: FormControl) => {
+        ...
+        return (REG_EXP.test(password)) ? null : {
+          validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
+            valid: false,
+            message:  this.passwordErrorMessage
+          } 
+    };
+  }
+}
+
",r +"Is it possible to program a WebApp where u can import an .csv and export as pdf?

So i am currently working on a project for my company. The target is to make an automated pdf genarator for our products. I want to programm an WebApp for this and constantly implement new functions. We have a prepared Indesign file with a guidline that needs to be met. My question is, is this even possible, to feed the programm with the .csv file and at the end i will receive a finished .pdf(with the design guidline).

+

It is my first time on StackOverflow, so please excuse if i was not precise enough :)

+

PS: I know about the Data-Merge function in Indesign, yet this doesn't work for us.

+

Thanks :)

","

Yes, this is possible, however when you use it in an actual publicly accessible web app (as opposed to an in-house tool that you use manually), then you will need an InDesign server license for that.

+

But technically, it is definitively possible to write a script to read .csv files to generate a certain layout with certain contents.

",r +"Avoid error ""call to a member function get_cart()…"" in WooCommerce function

Receiving an error on a code that did work previously but now it is stopping me editing a page in wordpress (As when I attempt to edit a page, it states there's been a critical error).

+

The code below basically changes text for add to cart button depending if the related product is in the cart.

+

Code below and error exception below that:

+
function woocommerce_custom_add_to_cart_text($add_to_cart_text, $product ) {
+    global $woocommerce;
+    // Get cart
+    $cart_items = $woocommerce->cart->get_cart();
+
+    foreach ( $cart_items as $cart_item_key => $cart_item ) {
+        // Get product id in cart
+        $_product_id = $cart_item['product_id'];
+ 
+        if ( $product->get_id() == $_product_id ) {
+            $add_to_cart_text = 'Already in cart';
+        }
+    }
+
+    return $add_to_cart_text;
+  
+}
+add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );
+
+

Error exception:

+
An error of type E_ERROR was caused in line 3 of the file /home4/metisonl/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code. Error message: Uncaught Error: Call to a member function get_cart() on null in /home4/metisonl/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:3
+Stack trace:
+#0 /home4/metisonl/public_html/staging/4326/wp-includes/class-wp-hook.php(287): woocommerce_custom_add_to_cart_text('Add to cart', Object(WC_Product_Simple))
+#1 /home4/metisonl/public_html/staging/4326/wp-includes/plugin.php(206): WP_Hook->apply_filters('Add to cart', Array)
+#2 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woocommerce/includes/class-wc-product-simple.php(62): apply_filters('woocommerce_pro...', 'Add to cart', Object(WC_Product_Simple))
+#3 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woo-gutenberg-products-block/src/BlockTypes/AbstractProductGrid.php(473): WC_Product_Simple->add_to_cart_text()
+#4 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woo-gutenberg-products-block/src/BlockTypes/AbstractProductGrid.php(446): Automattic\WooCommerce\Blocks\BlockTypes\Abstra
+
","

Updated … You need to check that cart object exist and that cart is not empty, so try the following to avoid this kind of error:

+
add_filter( 'woocommerce_product_add_to_cart_text', 'filter_product_add_to_cart_text', 10, 2 );
+function filter_product_add_to_cart_text( $add_to_cart_text, $product ) {
+    if ( ! WC()->cart && WC()->cart->is_empty() ) 
+        return $add_to_cart_text;
+
+    // Loop through cart items
+    foreach ( WC()->cart->get_cart() as $cart_item ) {
+        // Get product id in cart
+        $_product_id = $cart_item['product_id'];
+ 
+        if ( $product->get_id() == $_product_id ) {
+            return __('Already in cart');
+        }
+    }
+    return $add_to_cart_text;
+}
+
+

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

",r +"How can I add individual data points to my bar plot using ggbarplot? (add jitter does not work, neither does dotplot)

I am having a hard time adding individual data points on my barplots using ggbarplot. I seem to have an issue particularly on multi-grouped data (using fill or color). I've tried a couple different ways to add dots, but they've either resulted in an error (adding jitter) or the dots are not properly aligned to the correct bar (adding dotplot). Any help would be greatly appreciated.

+

Example data:

+
library(ggpubr)
+
+
+#dataframe
+ER <- read.table(header=TRUE, text="
+  Sex  Group ER
+  M    V     1046
+  M    V     1290
+  M    Z     1202
+  M    Z     1056
+  F    V     8000
+  F    V     7859
+  F    Z     4000
+  F    Z     3409
+")
+
+

I can get it to work if I use "add = c(point)" but when I try to use "add = c(jitter)" it results in an error ("position_jitterdodge()' requires at least one aesthetic to dodge by. I've seen similar questions asked here, but were usually resolved by adding the grouping factor to "Fill" instead of "color." I tried both and neither worked.

+
e <- ggbarplot(ER, x = "Sex", y = "ER", title = "Arcuate Nucleus",
+                 ylab= "ER Labeling", xlab = "Group", color = "Group",
+                 add = c("mean_se", "jitter"), add.params = list(color = "black"), palette = "jco",
+                 position = position_dodge(.8)) 
+print(e) 
+
+

Trying to use "add = c("dotplot)" results in the dots being mixed between my second group and shown in between the two side-by-side groups.

+
e2 <- ggbarplot(ER, x = "Sex", y = "ER", title = "Arcuate Nucleus",
+                 ylab= "ER Labeling", xlab = "Group", color = "Group",
+                 add = c("mean_se", "dotplot"), add.params = list(color = "black"), palette = "jco",
+                 position = position_dodge(.8)) 
+print(e2) 
+
+

This seems to work... but I would really like to use different colors, shapes, and add jitter. Example below.

+
e3 <- ggbarplot(ER, x = "Sex", y = "ER", title = "Arcuate Nucleus",
+                 ylab= "ER Labeling", xlab = "Group", color = "Group",
+                 add = c("mean_se", "point"), add.params = list(color = "black"), palette = "jco",
+                 position = position_dodge(.8)) + theme(axis.line = element_line(size = 0.9), axis.ticks = element_line(size = 0.9)) 
+
+print(e3)
+
+

","

The issue is that with add.params(color = "black") you are overwriting the grouping (color = "Group") needed for dodging the points. Hence, dropping add.params(color = "black") will make your code work. If you want black points and error bars you can do that via e.g. scale_color_manual by setting the colors for all groups to "black":

+ +
library(ggpubr)
+#> Loading required package: ggplot2
+
+ER <- read.table(header=TRUE, text="
+  Sex  Group ER
+  M    V     1046
+  M    V     1290
+  M    Z     1202
+  M    Z     1056
+  F    V     8000
+  F    V     7859
+  F    Z     4000
+  F    Z     3409
+")
+
+ggbarplot(ER, x = "Sex", y = "ER", title = "Arcuate Nucleus",
+               ylab= "ER Labeling", xlab = "Group", color = "Group", fill = "Group",
+               add = c("mean_se", "jitter"), palette = "jco",
+               position = position_dodge(.8)) +
+  scale_color_manual(values = c(V = "black", Z = "black"))
+
+

+

EDIT

+

The issue is that packages like ggpubr offer a lot out of the box. The "price" one pays for that is that out-of-the-box solutions have their limits. If you want have more control about the appearence of your plot you have to do it (at least partially) using ggplot2, e.g. to color the points you can the jittered points using geom_jitter. Here I change the shape of the points so that I can add a black outline. Unfortunately it is not possibleto change the fill color as well as jitterdodge requires the fill aes:

+
ggbarplot(ER, x = "Sex", y = "ER", title = "Arcuate Nucleus",
+          ylab= "ER Labeling", xlab = "Group", color = "Group", fill = "Group",
+          add = c("mean_se"), palette = "jco",
+          position = position_dodge(.8)) +
+  scale_color_manual(values = c(V = "black", Z = "black")) +
+  geom_jitter(aes(Sex, ER, fill = Group), shape = 21, color = "black",  position = position_jitterdodge(jitter.height = .1, jitter.width = .2))
+
+

Another option would be to use e.g.

+
geom_jitter(aes(Sex, ER, fill = Group), color = "grey",  position = position_jitterdodge(jitter.height = .1, jitter.width = .2))
+
+

which gives you "filled" e.g. "grey" points but with no outline.

",r +"Operate with a table in R

I want to get a tuple from a table in R.

+

For example, if i have this table named batch_task:

+
arrival_time, departure_time, jod_id, task_id
+11792, 11999, 18, 88
+11792, 14331, 18, 82
+11792, 12112, 18, 91
+16281, 16552, 27, 147
+16281, 16396, 27, 139
+16281, 16529, 27, 137
+
+

So, for each job_id i need a tuple {arrival_time, service_time}; for example, for the job_id = 18, i want to get the tuple {11792, (11999-11792)+(14331-11792)+(12112-11792)} = {11792, 3066}.

+

Anyone could help me? Thanks in advance, +Jesús

","

Assuming that batch_task is actually a data frame rather than a table (which is a specific type of R structure dealing with count data), here's a solution using the dplyr package:

+
library(dplyr)
+
+batch_task %>% 
+  group_by(arrival_time) %>%
+  summarise(service_time = sum(departure_time - arrival_time), .groups = "drop")
+#> # A tibble: 2 x 2
+#>   arrival_time service_time
+#>          <int>        <int>
+#> 1        11792         3066
+#> 2        16281          634
+
+

Note that there is no data structure called a tuple in R. There are various ways to represent tuples, but the most sensible way in this case would be to keep the result in a data frame format.

+
+

Data

+
batch_task <- structure(list(arrival_time = c(11792L, 11792L, 11792L, 16281L, 
+16281L, 16281L), departure_time = c(11999L, 14331L, 12112L, 16552L, 
+16396L, 16529L), jod_id = c(18L, 18L, 18L, 27L, 27L, 27L), task_id = c(88L, 
+82L, 91L, 147L, 139L, 137L)), class = "data.frame", row.names = c(NA, 
+-6L))
+
",r +"sort by name in api

I want to sort this image gallery by name, but I really don’t know how to do that?

+

gallery html

+
<div>
+  <div id="result"></div>
+</div>
+
+

gallery js

+
const container = document.getElementById('result');
+
+function getData() {
+  fetch('https://randomuser.me/api/?results=30')
+    .then((response) => response.json())
+    .then((results) => output(results));
+}
+
+function output(results) {
+  const htmlData = results.results
+    .map((result) =>
+      `
+    <div>
+        <img src="${result.picture.large}">
+        <div>${result.name.first}</div>
+    </div>
+    `
+    ).join('');
+
+  container.innerHTML += htmlData;
+}
+
+getData();
+
","

So use sort on your array

+
results.results
+  .sort((a, b) => a.name.first.localeCompare(b.name.first))
+  .map(...)
+
+

+
+
const container = document.getElementById('result');
+
+function getData() {
+  fetch('https://randomuser.me/api/?results=30')
+    .then((response) => response.json())
+    .then((results) => output(results));
+}
+
+function output(results) {
+  const htmlData = results.results
+    .sort((a, b) => a.name.first.localeCompare(b.name.first))
+    .map((result) =>
+      `
+    <div>
+        <img src=""${result.picture.large}"">
+        <div>${result.name.first}</div>
+    </div>
+    `
+    ).join('');
+
+  container.innerHTML += htmlData;
+}
+
+getData();
+
<div>
+  <div id=""result""></div>
+</div>
+
+
+

",r +"Node mysql ER_PARSE_ERROR 1064

I am inserting a row into table like this but its not working i searched on internet and tried all solutions for no luck for me i don't know what i am doing wrong here

+
var b = req.body;
+mysqlConnection.query(
+  'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES ?',
+   [[
+     b.nid,
+     b.name,
+     b.dob,
+     b.gender
+    ]],
+  (error, results) => {
+    if(!error)
+    res.status(201).send(result.insertId);
+    else
+    res.send(error)
+  }
+
+

);

+

Error

+
   "code": "ER_PARSE_ERROR",
+    "errno": 1064,
+    "sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123, 'Alex', '2020-10-30', 'male' at line 1",
+    "sqlState": "42000",
+    "index": 0,
+    "sql": "INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES 123, 'Alex', '2020-10-30', 'male'"
+}
+
","

There is a missing parenthesis just after VALUES, try this

+
mysqlConnection.query(
+  'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES (?)',
+   [[
+     b.nid,
+     b.name,
+     b.dob,
+     b.gender
+    ]],
+  (error, results) => {
+    if(!error)
+    res.status(201).send(result.insertId);
+    else
+    res.send(error)
+  }
+);
+
",r +"How to change visualstate values and reuse the control with different properties values?

I've realized a custom textbox that changes BorderBrush on MouseOver event (in this case it changes the BorderBrush, but I can change other properties).

+

Now if I want to customize the color of BorderBrush on MouseOver and create different textboxes with different "BorderBrush on MouseOver" colors, how to do it using visualstates? +Is there a way without define a different style for every textbox?

+
<ResourceDictionary>
+
+    <Style TargetType="{x:Type local:IconTextBox}">
+        <Setter Property="BorderThickness" Value="1"/>
+        <Setter Property="BorderBrush" Value="Black"/>
+
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="{x:Type local:IconTextBox}">
+                    <Border x:Name="Border"
+                    BorderThickness="{TemplateBinding BorderThickness}"
+                    BorderBrush="{TemplateBinding BorderBrush}"
+                    Background="{TemplateBinding Background}">
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualStateGroup.Transitions>
+                                    <VisualTransition GeneratedDuration="0:0:0.5" />
+                                </VisualStateGroup.Transitions>
+                                <VisualState x:Name="Normal" />
+                                <VisualState x:Name="MouseOver">
+                                    <Storyboard>
+                                        <ColorAnimationUsingKeyFrames
+                                            Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"
+                                            Storyboard.TargetName="Border">
+                                            <EasingColorKeyFrame KeyTime="0"
+                                                Value="Green" />
+                                                <!-- I want to change that Green -->
+
+                                        </ColorAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+
+                        <ScrollViewer x:Name="PART_ContentHost"
+                                    Focusable="False"
+                                    HorizontalScrollBarVisibility="Hidden"
+                                    VerticalScrollBarVisibility="Hidden" />
+                    </Border>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+</ResourceDictionary>
+
","

You don't need to have a separate style for changing the color. You can add a dependency property to your IconTextBox and change the color based on the property.

+

Declare a dependency property in IconTextBox.cs:

+
public Color MouseOverBorderBrushColor
+{
+    get { return (Color)GetValue(MouseOverBorderBrushColorProperty); }
+    set { SetValue(MouseOverBorderBrushColorProperty, value); }
+}
+
+public static readonly DependencyProperty MouseOverBorderBrushColorProperty =
+    DependencyProperty.Register("MouseOverBorderBrushColor", typeof(Color), 
+    typeof(IconTextBox), new PropertyMetadata(null));
+
+

Bind to the property in your style:

+
<ControlTemplate TargetType="{x:Type local:IconTextBox}">
+    <Border x:Name="Border"
+        BorderThickness="{TemplateBinding BorderThickness}"
+        BorderBrush="{TemplateBinding BorderBrush}"
+        Background="{TemplateBinding Background}">
+        <Border.Resources>
+            <ResourceDictionary>
+                <Storyboard x:Key="ColorStoryboard">
+                    <ColorAnimationUsingKeyFrames
+                    Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"
+                    Storyboard.TargetName="Border">
+                        <EasingColorKeyFrame KeyTime="0"
+                        Value="{Binding MouseOverBorderBrushColor, RelativeSource={RelativeSource TemplatedParent}}" />
+                    </ColorAnimationUsingKeyFrames>
+                </Storyboard>
+            </ResourceDictionary>
+        </Border.Resources>
+        <VisualStateManager.VisualStateGroups>
+            <VisualStateGroup x:Name="CommonStates">
+                <VisualStateGroup.Transitions>
+                    <VisualTransition GeneratedDuration="0:0:0.5" />
+                </VisualStateGroup.Transitions>
+                <VisualState x:Name="Normal" />
+                <VisualState x:Name="MouseOver" Storyboard="{StaticResource ColorStoryboard}" />
+
+            </VisualStateGroup>
+        </VisualStateManager.VisualStateGroups>
+
+        <ScrollViewer x:Name="PART_ContentHost"
+            Focusable="False"
+            HorizontalScrollBarVisibility="Hidden"
+            VerticalScrollBarVisibility="Hidden" />
+    </Border>
+</ControlTemplate>
+
+

Note that you can't use TemplatedParent in VisualStateManager hence I added the storyboard as a static resource to the resources of the border and used that in VisualStateManager. This trick is explained here.

+

Then you can have IconTextBoxes with different mouse over border brush colors:

+
<local:IconTextBox MouseOverBorderBrushColor="Green" />
+<local:IconTextBox MouseOverBorderBrushColor="Red" />
+
",r +"string replace do not replace character in string

I have the following string

+
var str = "this---is--- a --- test d ---";
+
+

I want to remove all the - and replace by nothing.

+

I tried using

+
var str = "this---is--- a --- test d ---";
+var res = str.replace("-", "");
+
+

but res do not change...

+

if I do

+
var str = "this---is--- a --- test d ---";
+var res = str.split('-').filter(e => !!e).join();
+
+

it does work.

+

Why the replace is not ?

","

Because replace will only replace one occurrence.

+
"aabc".replace("a", ""); // Outputs "abc"
+"aabc".replaceAll("a", ""); // Outputs "bc"
+
+

Use replaceAll to replace all occurrences

+
var str = "this---is--- a --- test d ---";
+var res = str.replaceAll("-", "");
+
",r +"When running gradle task inside map loop the task is running only after the script

I am using a docker plugin to build my docker images, +I have a project with multiply services but it is a monolete so I have a single build.gradle file. +What I'm trying to do is build all the images using a map loop, +but when building the project only the last element in the map is being built.

+

These is the relevant parts of the build.gradle file:

+
plugins {
+    id 'java'
+    id 'application'
+    id 'maven'
+    id 'distribution'
+    id 'maven-publish'
+    //docker-plugin
+    id 'com.palantir.docker' version '0.25.0'
+}
+
+group = 'com.company.scheduler'
+version '4.0.0-SNAPSHOT'
+
+
+//Handle release version scenario 
+def PublishedVersion
+def buildNumber
+if (version ==~ /(?s).*SNAPSHOT.*/) {  //Check if SNAPSHOT/Release version
+    if ("$System.env.BUILD_NUMBER" == null) {buildNumber = '0'} else {buildNumber = "$System.env.BUILD_NUMBER"}
+    PublishedVersion = version
+} else {
+    if ("$System.env.BUILD_NUMBER" == null) {buildNumber = '0'} else {buildNumber = "$System.env.BUILD_NUMBER"}
+    PublishedVersion = version + '-' + buildNumber
+}
+
+mainClassName = 'com.company.scheduler'
+
+dependencies {
+    compile group: 'com.coralogix.sdk', name: 'coralogix-sdk', version: '2.0.3'
+}
+
+def serviceOptionMap =   [ "utility-meters": "utility_meters_import_plugins",
+                           "weather":        "weather_importer"
+]
+
+serviceOptionMap.each { k, v ->
+    docker {
+            def service_id="${k}"
+            def artifact_start_script="${v}"
+            println 'artifact_start_script: ' + artifact_start_script
+            println 'service_id: ' + service_id
+            name "47957039666.dkr.ecr.us-east-1.amazonaws.com/panpwr/service-gradle/${service_id}:$PublishedVersion"
+            //if (version ==~ /(?s).*SNAPSHOT.*/) {tag "$version", "47957039666.dkr.ecr.us-east-1.amazonaws.com/panpwr/ev/${project.name}:latest"}
+            copySpec.from("build/distributions").into(".")
+            dockerfile file("${rootProject.projectDir}/Dockerfile")
+            buildArgs([ARTIFACT_ID: "${service_id}", PANPWR_VERSION: "$PublishedVersion", ARTIFACT_START_SCRIPT: "$artifact_start_script"])
+            labels(["service-name": "${service_id}", "service-version": "$PublishedVersion"])
+            pull false //TODO: change to true
+            noCache false
+            println 'built docker image: ' + service_id
+        }
+}
+
+

This is the build output:

+
> Configure project :scheduled-tasks
+artifact_start_script: utility_meters_import_plugins
+service_id: utility-meters
+built docker image: utility-meters
+artifact_start_script: weather_importer
+service_id: weather
+built docker image: weather
+
+> Task :scheduled-tasks:dockerClean
+> Task :scheduled-tasks:dockerPrepare
+> Task :scheduled-tasks:docker
+
+BUILD SUCCESSFUL in 5s
+3 actionable tasks: 3 executed
+10:16:39 AM: Task execution finished 'docker'.
+
+

And when I check my local images I can see only the second image:

+
$ docker images | grep gradle
+47957039666.dkr.ecr.us-east-1.amazonaws.com/panpwr/service-gradle/weather           4.0.0-SNAPSHOT      729a926206ed        20 hours ago        1.11GB
+
","

It turns out that this plugin doesn't support building multiple images, +So I ended up creating a sub-module to each service that only creates docker images using this plugin. +So this is pretty much the structure:

+
├── Dockerfile
+├── app1
+│   └── build.gradle
+├── app2
+│   └── build.gradle
+├── gradle
+│   └── wrapper
+│       ├── gradle-wrapper.jar
+│       └── gradle-wrapper.properties
+├── gradle-user-home
+├── gradlew
+├── build.gradle
+
+

And this is the simple gradle.build for the submodules:

+
plugins {
+    //docker-plugin
+    id 'com.palantir.docker' version '0.25.0'
+}
+
+version '4.0.0-SNAPSHOT'
+
+
+//Handle release version scenario 
+def PublishedVersion
+def buildNumber
+if (version ==~ /(?s).*SNAPSHOT.*/) {  //Check if SNAPSHOT/Release version
+    if ("$System.env.BUILD_NUMBER" == null) {buildNumber = '0'} else {buildNumber = "$System.env.BUILD_NUMBER"}
+    PublishedVersion = version
+} else {
+    if ("$System.env.BUILD_NUMBER" == null) {buildNumber = '0'} else {buildNumber = "$System.env.BUILD_NUMBER"}
+    PublishedVersion = version + '-' + buildNumber
+}
+
+docker {
+    name "47957039666.dkr.ecr.us-east-1.amazonaws.com/panpwr/service-gradle/${project.name}:$PublishedVersion"
+    copySpec.from("${rootProject.projectDir}/scheduled-tasks/build/distributions").into(".")
+    dockerfile file("${rootProject.projectDir}/Dockerfile")
+    buildArgs([ARTIFACT_ID: "${project.name}", PANPWR_VERSION: "$PublishedVersion", ARTIFACT_START_SCRIPT: "${project.name}"])
+    labels(["service-name": "${project.name}", "service-version": "$PublishedVersion"])
+    pull true
+    noCache false
+    println 'built docker image: ' + project.name
+}
+
+
+publishing {
+    publications {
+        dockerPublication(MavenPublication) {
+            from components.docker
+            artifactId project.name + "-docker"
+        }
+    }
+}
+
+

And running the docker task on the root project creates all the docker images:

+
./gradlew clean build docker -g gradle-user-home
+
",r +"Starting a singleTask activity causes it to spawn on top of the caller task

I have an activity that has singleTask launch mode. This activity can receive shared content from other apps, using these filters:

+
            <intent-filter>
+                <action android:name="android.intent.action.SEND" />
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="text/*" />
+                <data android:mimeType="image/*" />
+                <data android:mimeType="video/*" />
+                <data android:mimeType="audio/*" />
+                <data android:mimeType="application/*" />
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.intent.action.SEND_MULTIPLE" />
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="image/*" />
+                <data android:mimeType="video/*" />
+                <data android:mimeType="audio/*" />
+                <data android:mimeType="application/*" />
+            </intent-filter>
+
+

When I share an URL from Google Chrome for instance, my activity is created correctly, but instead of getting created on its own task, is created on top of the Chrome task. Isn't the singleTask launch mode meant to prevent this? Both my activity and my application has affinity explicitly defined on the manifest. Is there something else needed in this case?

+

Manifest:

+

+    <application
+        android:name=".MainApplication"
+        android:allowBackup="false"
+        android:icon="@mipmap/ic_launcher"
+        android:label="@string/app_name"
+        android:largeHeap="true"
+        android:theme="@style/AppTheme.Launcher"
+        android:usesCleartextTraffic="true"
+        android:taskAffinity="my.example.app"
+        tools:replace="android:allowBackup">
+        <activity
+            android:name=".MainActivity"
+            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode|layoutDirection|locale"
+            android:label="@string/app_name"
+            android:launchMode="singleTask"
+            android:taskAffinity="my.example.app"
+            android:windowSoftInputMode="adjustResize">
+
",

The only solution I could figure out was to create a new activity for the sole purpose of handling ACTION_SEND intents and pass them to the main activity. This new activity should have an entire blank UI.

,r +"Detect social account existence flow using custom policies on Azure AD B2C

I am struggling to get my head around how to implement a custom policy for the following flow:

+
User lands on the login page and that login page only contains an email input.
+User enters email address and clicks continue
+    if user has already registered
+        Redirected to their selected login provider (Google, Microsoft Account or Local Account)
+    if user has not registered before
+        Check google provider if a user account exists for that email address
+        if Google account exists
+            Redirect to Google login
+        Check Microsoft provider if a user account exists for that email address
+        if Microsoft account exists
+            Redirect to Microsoft login
+        else
+            Redirect to registration screen
+            User completes registration screen
+            User is automatically logged in
+            
+The user
+
+

I've investigated whether this can in fact be done and I've found a "digital workspace for visual collaboration" (a.k.a Mural.co) that does in fact implement a similar flow, so this has to be possible. See the pictures below.

+

+

+

I'm, however, unable to find information on

+
    +
  1. how to query the social providers for account existence
  2. +
  3. how to go about creating this complex type of flow in Azure AD B2C custom policies.
  4. +
+

Any pointers in the right direction would be greatly appreciated

","
    +
  1. Not possible. Nobody would allow you to probe a social IdP for an email. Data protection etc.

    +
  2. +
  3. Reference our samples and wiki

    +
  4. +
+

Your sign up would be from our default sign up journey.

+

Your sign in flow could work like this:

+
    +
  1. Request for email
  2. +
  3. Read the directory to see if an email exists
  4. +
  5. If email exists, send the user to the IdP they used to sign up. You can do that by looking at the “issuers” registered on the userIdentity object,
  6. +
  7. If email doesn’t exist, send the user to the combined sign in and sign up page (technical profile) where they can sign in with social or sign up with a local account. Hide the sign in elements with CSS.
  8. +
",r +"std::atomic lock-free inconsistency on ARM (raspberry pi 3)

I had a problem with a static assert. The static assert was exactly like this:

+
static_assert(std::atomic<bool>::is_always_lock_free);
+
+

and the code failed on Raspberry Pi 3 (Linux raspberrypi 4.19.118-v7+ #1311 SMP Mon Apr 27 14:21:24 BST 2020 armv7l GNU/Linux).

+

On the cppreference.com atomic::is_always_lock_free reference site it is stated that:

+
+

Equals true if this atomic type is always lock-free and false if it is never or sometimes lock-free. +The value of this constant is consistent with both the macro ATOMIC_xxx_LOCK_FREE, where defined, with the member function is_lock_free and non-member function std::atomic_is_lock_free.

+
+

The first strange thing for me is "sometimes lock-free". What does it depend on? But questions later, back to the problem.

+

I made a little test. Wrote this code:

+
#include <iostream>
+#include <atomic>
+
+int main()
+{
+    std::atomic<bool> dummy {};
+    std::cout << std::boolalpha
+            << "ATOMIC_BOOL_LOCK_FREE --> " << ATOMIC_BOOL_LOCK_FREE << std::endl
+            << "dummy.is_lock_free() --> " << dummy.is_lock_free() << std::endl
+            << "std::atomic_is_lock_free(&dummy) --> " << std::atomic_is_lock_free(&dummy) << std::endl
+            << "std::atomic<bool>::is_always_lock_free --> " << std::atomic<bool>::is_always_lock_free << std::endl;
+    return 0;
+}
+
+

compiled and ran it on raspberry using g++ -std=c++17 atomic_test.cpp && ./a.out (g++ 7.3.0 and 8.3.0, but that shouldn't matter) and got:

+
ATOMIC_BOOL_LOCK_FREE --> 1
+dummy.is_lock_free() --> true
+std::atomic_is_lock_free(&dummy) --> true
+std::atomic<bool>::is_always_lock_free --> false
+
+

As you can see it is not as consistent as stated on the cppreference site... For comparison I ran it on my laptop (Ubuntu 18.04.5) with g++ 7.5.0 and got:

+
ATOMIC_BOOL_LOCK_FREE --> 2
+dummy.is_lock_free() --> true
+std::atomic_is_lock_free(&dummy) --> true
+std::atomic<bool>::is_always_lock_free --> true
+
+

So there is a difference in ATOMIC_BOOL_LOCK_FREE's value and of course the is_always_lock_free constant. Looking for the definition of ATOMIC_BOOL_LOCK_FREE all I could find is

+
c++/8/bits/atomic_lockfree_defines.h: #define ATOMIC_BOOL_LOCK_FREE  __GCC_ATOMIC_BOOL_LOCK_FREE
+c++/8/atomic: static constexpr bool is_always_lock_free = ATOMIC_BOOL_LOCK_FREE == 2;
+
+

What is the difference between ATOMIC_BOOL_LOCK_FREE (or __GCC_ATOMIC_BOOL_LOCK_FREE) being equal to 1 or 2? Is it a case where if 1 then it may or may not be lock-free and if 2 it is 100% lock-free? Are there any other values apart from 0? Is this an error on the cppreference site where it is stated that all those return values should be consistent? Which of the results for the raspberry pi output is really true?

","

1 means "sometimes lock free" in the standard. But really that means "not known to be lock free at compile time".

+

Without compiler options, GCC's default baseline includes ARM chips so old that they don't support the necessary instructions for atomic RMWs, so it has to make code that could run on ancient CPUs, always calling libatomic functions instead of inlining atomic operations.

+

The runtime query function returns true when you run it on an RPi with its ARMv7 or ARMv8 CPU.

+

With -march=native or -mcpu=cortex-a53 you'd get is_always_lock_free being true, because it's known at compile time that the target machine definitely supports the required instructions. (Those options tell GCC to make a binary that might not run on other / older CPUs.) This was confirmed by the OP in comments.

+

Without that compile option, std::atomic operations have to call libatomic functions, so there's extra overhead even on a modern CPU.

+

The way GCC (and all sane compilers) implement std::atomic<T>, it's either lock free for all instances or none, not checking alignment or whatever at runtime per object.

+

alignof( std::atomic<int64_t> ) is 8 even if alignof( int64_t ) was only 4 on a 32-bit machine, so it's undefined behaviour if you have a misaligned atomic object. (The practical symptoms of that UB could include tearing, i.e. non-atomicity, for pure-load and pure-store.) If you follow C++ rules, all your atomic objects will be aligned; you'd only have a problem if you cast a misaligned pointer to atomic<int64_t> * and tried to use it.

",r +"The underlying provider failed on Rollback. Test Performance JMeter

i have problem when my method is accessed by more than 10 users at a time.

+

Here's some example of how I implemented my classes' methods:

+
BeginDbTransaction();
+
+ IdentityResult result = new IdentityResult();
+ try
+{
+    result = await AddAspNetUsers(user, model.Password);
+   if (result.Succeeded)
+   {
+      running method1 //(insert db)
+      running method2 //(insert db)
+   }
+   else{ IsTransRollbacked = true;}
+
+}
+catch (Exception ex)
+{
+   throw ex;
+}
+
+

The error is "The underlying provider failed on Rollback.".

+

Anybody can improve my code, please.. Thanks a lot.

","

Your code is not clear but I recommend to rewrite your code something like this :

+
using (var tran=new  BeginDbTransaction())
+{
+    try
+    {
+      // open your connection
+      // call AddAspNetUsers in order to add new user
+     // if you get any error while creating new user throw excetion
+     //call another methods
+    }
+    catch (Exception ex)
+    {
+      tran.RollBack();
+    }
+}
+   
+
+

transaction should be created in your logic layer not in UI layer. +And also new your IdentityResult() in constructor

",r +"How to get a random multiple of a given number within a range

I'm making a program in which a JPanel is created with a random RGB value and the user has to use buttons to match the color in another JPanel.

+

I want the random R, G, and B values to be multiples of 15, though, so the user can match the color more easily.

+

Right now my code looks like this:

+
int randRed = rand.nextInt(255);
+
+

and the same for green and blue. I could use a modulus to repeat the code until it happens to be a multiple of 15 but that would be terribly inefficient.

+

What is the best method to achieve a random multiple of 15 less than 255?

","

RIght after posting I figured it out...

+
int randRed = (rand.nextInt(17)+1)*15;
+
+

15 goes into 255 17 times, so just multiple a random int between 0 and 17, add 1, and multiply by 15.

",r +"Django Error: Ensure this value has at most 5 characters (it has 6)
class User(AbstractBaseUser, TimeStampedModel):
+    objects = UserManager()
+
+    GENDER_MALE = "male"
+    GENDER_FEMALE = "female"
+    GENDER_OTHER = "other"
+
+    GENDER_CHOICES = (
+        (GENDER_MALE, "Male"),
+        (GENDER_FEMALE, "Female"),
+        (GENDER_OTHER, "Other"),
+    )
+
+    email = models.EmailField(unique=True)
+    username = models.CharField(max_length=20, unique=True)
+    gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
+
+

It has the same code as above.

+

The service is being distributed using EB of AWS and an error "Ensure this value has at most 5 characters (it has 6)." occurred when the user set the gender to female.

+

The original code confirmed that the error occurred because the maximum_length of the gender was set to 5, and the code corrected to 6 is the code shown above.

+

However, the same error occurs in the service even after the makemigrations - migrate - eb deploy. "Ensure this value has at most 5 characters (it has 6)." But if you run the server in local, it works normally without errors.

+

I thought that postgresql connected to eb did not apply to migration, which led to an error i thought. However, after looking at the migration process through eb logs, we were able to confirm that it was applied normally without error.

+

What am I missing, what should I look at? Please give me a lot of advice.

+

+

+

There is one other change now. The same distribution was properly applied at the service server. No errors are generated. However, the development server generates an error even though it is the same distribution. Should we check the connection between aws eb and rds? What should I check?

","

Resolved. The server specified by config.yml in .elasticbeanstalk was a service server. In short, my distribution was applied to the actual service server, not to the development server, and the development server was not deployed, so errors continued. It is my mistake to enter the wrong folder. I thank many people who read the questions.

",r +"How is App Installs calculated in the Dynamic links panel

What is the relationship of Clicks, App-installs, Redirect, First-open, Re-open?

","

APP_INSTALL is only logged when users installs the app from a Firebase Dynamic Link. This is only supported by the Play Store as mentioned in the official doc. This means installs from other platforms (mainly iOS App Store) won't get logged.

+

Having smaller APP_INSTALL count than CLICK makes sense since not all users who clicks on the Dynamic Link needs to install the app.

+

Edit: Added more details below.

+

CLICK is recorded when a user clicks the FDL and sends a request to the FDL server

+

REDIRECT is recorded when a successful response was given by the FDL server. The event may send the user to the App Store, fallback URL, or to the app receiving the link.

+

Here's how the flow looks

+

+

However, it's a bit tricky on iOS when the app is installed and Universal Links is triggered. In this instance, no requests to FDL server will be made, therefore no FDL events CLICK and REDIRECT will be logged before APP_RE_OPEN.

",r +"from django.db import models in models.py but in command prompt i got NameError: name 'model' is not defined

i got an this error: +File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 15, in +class Product(models.Model): +File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 16, in Product +name = model.CharField(max_length=200, null=True) +NameError: name 'model' is not defined

+

But in my "models.py" in the first line i have imported the model:

+
from django.db import models
+from django.contrib.auth.models import User
+
+# Create your models here.
+
+class Customer(models.Model):
+    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
+    name = models.CharField(max_length=200, null=True)
+    email = models.CharField(max_length=200, null=True)
+
+    def __str__(self):
+        return self.name
+
+

Any clue what i should look for please?

+

Thank you

","

You haven't shown the rest of the models.py file but it seems to be a typo in your Product model class definition. In the line name = model.CharField(max_length=200, null=True) change from model to models.

",r +"Filtering data with more than n repetitions by taking a mean of those repetitions

I have time-series data at one-minute interval (data frame name is pn.nano). I wish to convert it into 5-minute averaged data. But before averaging, it should be ensured that each 5-minute interval has at least 3 values (i.e. each 5-min interval should have at least 3 minutes of data). Then only averaging should be done otherwise the data should be filtered out.

+

The data looks as follows. The column names (11.5, 15.4, etc.) are the pollutants whose variation with time is being monitored.

+
nano.pn <- structure(list(datetime = structure(c(1491887640, 1491887700, 
+           1491887760, 1491887820, 1491887880, 1491887940, 1491888000, 1491888060, 
+           1491888120, 1491888180), tzone = "Asia/Calcutta", class = c("POSIXct", 
+           "POSIXt")), `11.5` = c(5938.99, 5530.35, 4825.41, 4439.71, 4357.98, 
+           4467.01, 3956.29, 3880.23, 3469.57, 3356.23), `15.4` = c(9594.94, 
+           9124.55, 8382.42, 8223.1, 8216.26, 8454.1, 8112.84, 7519.49, 
+           7060.94, 7337.3), `20.5` = c(5126.89, 4965.06, 4749.27, 4941.16, 
+           5081.44, 5254.23, 5424.79, 4855.33, 4790.21, 5149.6), `27.4` = c(2936.92, 
+           2882.55, 2704.88, 2856.22, 2868.12, 2909.07, 3106.77, 2887.35, 
+           2802.64, 2853.24), `36.5` = c(1768.23, 1770.75, 1584.26, 1619.82, 
+           1558.73, 1610.95, 1587.24, 1557.97, 1481.79, 1323.94)), row.names = c(NA, 
+           -10L), class = c("tbl_df", "tbl", "data.frame"))
+
+

My approach is to use the following code:

+
x <- nano.pn %>% mutate(datetime= floor_date(datetime, unit = "5 mins"))
+n <- x %>% group_by(datetime) %>% summarise(countt= n())
+n.pn.5min <- x %>% mutate(countt= rep(n$countt,n$countt)) %>% filter(countt>2) %>% 
+                   group_by(datetime) %>% summarise_all(mean, na.rm= TRUE)
+
+

Although this works fine, is there any better approach?

","

Does this work:

+
> nano.pn %>% mutate(cuttime = cut(datetime, '5 mins')) %>% group_by(cuttime) %>% filter(n() > 3) %>% summarise(across(is.numeric, mean, na.rm = 1))
+`summarise()` ungrouping output (override with `.groups` argument)
+# A tibble: 2 x 6
+  cuttime             `11.5` `15.4` `20.5` `27.4` `36.5`
+  <fct>                <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
+1 2017-04-11 10:44:00  5018.  8708.  4973.  2850.  1660.
+2 2017-04-11 10:49:00  3826.  7697.  5095.  2912.  1512.
+> 
+
+

The difference between my result and Thomas's is that when he used flood_date, the first row in the data frame that had time "10:44:00.000" changed to "10:40:00.000" and wasn't included in the mean calculation as it was the only observation in that group and second group had 4 rows. Mine has 5 in both groups. So please use which ever code would work for you.

",r +"Lists within Lists, Loops within loops Automate the Boring Stuff

So i am trying to work my way though the Automate the Boring Stuff book and class but I am having a terrible time trying to figure out the second practice question at the end of chapter 4.

+

The problem asks to copy this

+

grid =
[['.','.','.','.','.','.'],
+['.','0','0','.','.','.'],
+['0','0','0','0','.','.'],
+['0','0','0','0','0','.'],
+['.','0','0','0','0','0'],
+['0','0','0','0','0','.'],
+['0','0','0','0','.','.'],
+['.','0','0','.','.','.'],
+['.','.','.','.','.','.']]

+

And write a code that prints it out like this

+

..OO.OO..
+.OOOOOOO.
+.OOOOOOO.
+..OOOOO..
+...OOO...
+....O....

+

So I was able to figure out how to call the list within a list values and print the heart sideways using this code:

+
grid = [['.','.','.','.','.','.'],
+    ['.','0','0','.','.','.'],
+    ['0','0','0','0','.','.'],
+    ['0','0','0','0','0','.'],
+    ['.','0','0','0','0','0'],
+    ['0','0','0','0','0','.'],
+    ['0','0','0','0','.','.'],
+    ['.','0','0','.','.','.'],
+    ['.','.','.','.','.','.']]
+    
+
+for x in grid:
+    for y in x:
+        print(y,end='')
+    print('\n')
+
+

Now I am trying to figure out how to print it the right way. I understand that I need to call the values at the 0 index within each list in the whole list first, then the 1 index and so on.

+

I looked at other answers and adjusted my code to this:

+
for x in range(len(grid[0])):
+    for y in range(len(grid)):
+        print(grid[x][y],end='')
+    print('\n')
+
+

Initially I had it without range(len()) but it gave me an error saying indices must be integers(which is fixed using the len function i assume because the len function returns an actual integer, right?). Now I am getting an error that my list is out of range. I have been trying to figure this out on my own for a few hours now and I am just not understanding at all and trying to quell my frustration. Can anyone help me out? Ive seen some other answers with some more advanced methods used to complete the practice but I am really trying to grasp these concepts I am learning now and just the basics in general so I am only looking for suggestions that involve really the simplest methods of lists, and loops. Thank you guys and I can add more information if necessary.

","

You should swap the looping variables during printing (effectively rotating the print).

+
for x in range(len(grid[0])):
+    for y in range(len(grid)):
+        print(grid[y][x],end='')
+    print() # Removed '\n' here because it printed two lines (end='\n' by default)
+
+

This works because the outer loop (x) is through each column, and the inner loop (y) is through each row. So by printing in that order you effectively rotate the image.

",r +"How check radio buttons checked or not?

I have tried simple java programme using if statements.
+for that, I'm using radio buttons to check whether is check or not?
+please check my code below is not working properly someone please help me on this?
+Project link below
+https://drive.google.com/file/d/1xhNbKyXYJh2k5i7a6nVl1VkTY7dTNzSg/view?usp=sharing

+
private void BTN_submitActionPerformed(java.awt.event.ActionEvent evt) {                                           
+        String finalResult;
+        int age = Integer.parseInt(TXT_age.getText());
+        RBTN_male.setActionCommand("male");
+        RBTN_female.setActionCommand("female");
+        String radio_Result = BTNgrp_gender.getSelection().getActionCommand();
+
+
+        if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
+            if (TXT_age.getText() == null || TXT_age.getText().trim().isEmpty()) {
+
+                JOptionPane optionPane = new JOptionPane("Please fill your age", JOptionPane.ERROR_MESSAGE);
+                JDialog dialog = optionPane.createDialog("Age missing");
+                dialog.setAlwaysOnTop(true);
+                dialog.setVisible(true);
+
+            } else {
+                if (age == 0) {
+                    JOptionPane optionPane = new JOptionPane("Please enter valid age", JOptionPane.ERROR_MESSAGE);
+                    JDialog dialog = optionPane.createDialog("Wrong age");
+                    dialog.setAlwaysOnTop(true);
+                    dialog.setVisible(true);
+                } else {
+                    if (age > 0 && age <= 5) {
+                        finalResult = "Rhymes";
+                        LBL_result.setText(finalResult);
+                    } else if (age > 15) {
+                        finalResult = "Poetry";
+                        LBL_result.setText(finalResult);
+                    }
+                }
+            }
+
+        } else {
+            JOptionPane optionPane = new JOptionPane("Please Select Your Gender", JOptionPane.ERROR_MESSAGE);
+            JDialog dialog = optionPane.createDialog("Gender Missing");
+            dialog.setAlwaysOnTop(true);
+            dialog.setVisible(true);
+        }
+
+
+    }                                          
+
","

The main problem with your code is in the second line of your method BTN_submitActionPerformed

+
int age = Integer.parseInt(TXT_age.getText()); 
+
+

Here the value for TXT_age is “Enter your age”. Now this cannot be parsed to an integer therefore a NumberFormatException is thrown which prevents the program from continuing its expected course of execution. The program also removes the placeholder text from this field on click leaving it empty i.e “” therefore submitting it will also result in an error.

+

To solve the issues above you can rewrite this method as follows:

+
    private void BTN_submitActionPerformed(java.awt.event.ActionEvent evt) {
+        int age;
+        String finalResult;
+        JOptionPane optionPane;
+        JDialog dialog;
+        RBTN_male.setActionCommand("male");
+        RBTN_female.setActionCommand("female");
+        try {
+            age = Integer.parseInt(TXT_age.getText());
+            if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
+
+                if (age == 0  || age < 0 ) {
+                    optionPane = new JOptionPane("Please enter valid age", JOptionPane.ERROR_MESSAGE);
+                    dialog = optionPane.createDialog("Wrong age");
+                    dialog.setAlwaysOnTop(true);
+                    dialog.setVisible(true);
+                } else {
+                    if (age > 0 && age <= 5) {
+                        finalResult = "Rhymes";
+                        LBL_result.setText(finalResult);
+                    } else if (age > 15) {
+                        finalResult = "Poetry";
+                        LBL_result.setText(finalResult);
+                    }
+                }
+
+            } else {
+                optionPane = new JOptionPane("Please Select Your Gender", JOptionPane.ERROR_MESSAGE);
+                dialog = optionPane.createDialog("Gender Missing");
+                dialog.setAlwaysOnTop(true);
+                dialog.setVisible(true);
+            }
+        } catch (NumberFormatException e) {
+            optionPane = new JOptionPane("Please fill your age", JOptionPane.ERROR_MESSAGE);
+            dialog = optionPane.createDialog("Age missing");
+            dialog.setAlwaysOnTop(true);
+            dialog.setVisible(true);
+        }
+
+    }
+
+

On a sidenote you can also think of other problems that may arise. For example, as user can enter anything in the textfield that means a user can enter a number that may not fit in an int. So if that happens then your program will again break. However, if you make above mentioned changes to your method then the problems that you are facing currently will be resolved.

",r +"How to check that last test is failed?

I test my code via Test2::V0

+
is $result, 'value', 'Test OK';
+
+

Can I check that last test is failed?

+

In mojolicious, for example, there is ->or(sub{ ... })

+

Does Test2::V0 have something similar?

","

Test functions have return values -- a true value or a false value depending on the outcome of the test -- which can be captured or checked.

+
if (! is $result, 'value', 'Test Ok') {
+    warn "Test 42 failed. Skip test 43\n";
+}
+
+is $result, 'value', 'Test Ok'
+    or warn "Test 42 failed. Skip test 43\n";
+
+$z1 = is $result1, 'value1';
+$z2 = is $result2, 'value2';
+$z3 = is $result3, 'value3';
+if (!!$z1 + !!$z2 + !!$z3 >= 2) {
+    print "At least two of the previous three tests passed!\n";
+}
+
",r +"Wrong colors when rendering SKTexture

I'm have an SKTexture generated by a GKNoiseMap. When I look at the texture in a swift playground, it has the expected colours. When I apply the texture to a material and render it in a SCNView, the colours are different (see images below). What am I doing wrong?

+

+

+

Full code:

+
import GameKit
+import SpriteKit
+import PlaygroundSupport
+
+let source = GKPerlinNoiseSource()
+let noise = GKNoise(source)
+noise.gradientColors = [-1: #colorLiteral(red: 0.7537418008, green: 0.4404714704, blue: 0.2776784003, alpha: 1) , 1: #colorLiteral(red: 0.2008953691, green: 0.186568588, blue: 0.2595013976, alpha: 1)]
+let map = GKNoiseMap(noise, size: vector2(1.0, 1.0), origin: vector2(0.0, 0.0), sampleCount: vector2(Int32(256), Int32(256)), seamless: false)
+let texture = SKTexture(noiseMap: map )
+
+
+let ball = SCNSphere(radius: 1)
+let materials = SCNMaterial()
+materials.diffuse.contents = texture
+ball.materials = [materials]
+var node = SCNNode(geometry: ball)
+
+
+var sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
+var scene = SCNScene()
+sceneView.scene = scene
+PlaygroundPage.current.liveView = sceneView
+
+var cameraNode = SCNNode()
+cameraNode.camera = SCNCamera()
+cameraNode.position = SCNVector3(x: 0, y: 0, z: 3)
+scene.rootNode.addChildNode(cameraNode)
+scene.rootNode.addChildNode(node)
+
","

I don't understand why this works (I suspect this has something to do with gamma correction), but here is a workaround:

+

Convert the SKTexture to an UIImage, then assign the UIimage to the material's diffuse contents. This shows correct colours.

",r +"replacing NA with next available number within a group

I have a relatively large dataset and I want to replace NA value for the price in a specific year and for a specific ID number with an available value in next year within a group for the same ID number. Here is a reproducible example:

+
ID <- c(1,2,3,2,2,3,1,4,5,5,1,2,2)
+year <- c(2000,2001,2002,2002,2003,2007,2001,2000,2005,2006,2002,2004,2005)
+value <- c(1000,20000,30000,NA,40000,NA,6000,4000,NA,20000,7000,50000,60000)
+data <- data.frame(ID, year, value)
+
+   ID year value
+1   1 2000  1000
+2   2 2001 20000
+3   3 2002 30000
+4   2 2002    NA
+5   2 2003 40000
+6   3 2007    NA
+7   1 2001  6000
+8   4 2000  4000
+9   5 2005    NA
+10  5 2006 20000
+11  1 2002  7000
+12  2 2004 50000
+13  2 2005 60000
+
+

So, for example for ID=2 we have following value and years:

+
   ID year value
+   2 2001  20000
+   2 2002  NA
+   2 2003  40000
+   2 2004  50000
+   2 2005  60000
+
+

So in the above case, NA should be replaced with 40000 (Values in next year). And the same story for other IDs. +the final result should be in this form:

+
   ID year value
+   1 2000  1000
+   1 2001  6000
+   1 2002  7000
+   2 2001  20000
+   2 2002  40000
+   2 2003  40000
+   2 2004  50000
+   2 2005  60000
+   3 2007    NA
+   4 2000  4000
+   5 2005  20000
+   5 2006  20000
+
+

Please note that for ID=3 since there is no next year available, we want to leave it as is. That's why it's in the form of NA

+

I appreciate if you can suggest a solution
+Thanks

","

dplyr solution

+
library(tidyverse)
+
+data2 <- data %>%
+  dplyr::group_by(ID) %>%
+  dplyr::arrange(year) %>% 
+  dplyr::mutate(replaced_value = ifelse(is.na(value), lead(value), value))
+
+
print(data2)
+# A tibble: 13 x 4
+# Groups:   ID [5]
+      ID  year value replaced_value
+   <dbl> <dbl> <dbl>          <dbl>
+ 1     1  2000  1000           1000
+ 2     4  2000  4000           4000
+ 3     2  2001 20000          20000
+ 4     1  2001  6000           6000
+ 5     3  2002 30000          30000
+ 6     2  2002    NA          40000
+ 7     1  2002  7000           7000
+ 8     2  2003 40000          40000
+ 9     2  2004 50000          50000
+10     5  2005    NA          20000
+11     2  2005 60000          60000
+12     5  2006 20000          20000
+13     3  2007    NA             NA
+
",r +"Access API Linkedin with B2C user

I have created a B2C tenant with an user flow that contain a linkedin way for connect. +In my ASP.NET website, i want to display linkedin's informations of the user connected.

+

In my research, i have seen different way to make this but it is possible only with custom policy and i need to know if in 2020, there is a solution or not, to get user info by linkedin.

+

Thank you in advance.

","

Sounds like passing an access token through a user flow to your application can be useful. With the access token the application will be able to call the LinkedIn API directly.

",r +"How can I click a drawable svg in TextinputEdittext?

I have an svg on an textinputedittext. It is on the right side of the edittext. I want to click and get an action from it.

+

This is xml of edittexxt:

+
<com.google.android.material.textfield.TextInputLayout
+                android:id="@+id/textinputlayout_login"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                app:endIconMode="custom"
+                app:errorIconDrawable="@drawable/ic_icon_show_hide_svg"
+                app:layout_constraintStart_toStartOf="@id/constraintlayout_login_editable_areas"
+                app:layout_constraintEnd_toEndOf="@id/constraintlayout_login_editable_areas"
+                app:layout_constraintTop_toBottomOf="@id/edittext_login_username"
+                android:layout_marginTop="16dp">
+
+                <com.example.android.custombutton.CustomEdittext
+                    android:id="@+id/edittext_login_password"
+                    android:layout_width="match_parent"
+                    android:layout_height="54dp"
+                    app:layout_constraintStart_toStartOf="parent"
+                    app:layout_constraintEnd_toEndOf="parent"
+                    android:inputType="textPassword"
+                    android:layout_marginTop="16dp"
+                    android:layout_marginStart="16dp"
+                    android:layout_marginEnd="16dp"
+                    android:paddingEnd="8dp"
+                    android:hint="Password"/>
+
+            </com.google.android.material.textfield.TextInputLayout>
+
+

How can I click this: @drawable/ic_icon_show_hide_svg

","

Use:

+
<com.google.android.material.textfield.TextInputLayout
+       android:id="@+id/textinputlayout_login"
+       app:endIconMode="custom"
+       app:endIconDrawable="@drawable/ic_icon_show_hide_svg"
+       ..>
+
+

Then you can define a clickListener with:

+
textinputlayout_login.setEndIconOnClickListener { 
+    //do something 
+}
+
+

For a password textfield you can also use the built-in feature endIconMode="password_toggle":

+
    <com.google.android.material.textfield.TextInputLayout
+        app:endIconMode="password_toggle"
+        app:endIconDrawable="@drawable/..."
+
",r +"NodeJS require for async tasks

I am trying to use NodeJS require syntax with an asynchronous database query. I would like the program to wait for the query to complete before it moves on to the next require as some information returned from the database is passed as a parameter to the next require.

+

Here is my code:

+
const dealership = require('../models/getDealershipById.js')(id);
+const dealershipLeads = require('../models/getLeadsByDealershipId.js')(dealership.id);
+const dealershipStaff = require('../models/getStaffByDealershipId.js')(dealership.id);
+
+return [dealership, dealershipLeads, dealershipStaff];
+
+

I have tried wrapping this in an anonymous async function but this did not work. Does anyone know how to do this?

+

Here is my module code:

+
module.exports = function(id) {
+const pool = require('../loaders/pool.js')();
+
+  pool.query('SELECT * FROM dealerships WHERE id = \'' + id + '\';', (err, 
+res) 
+  => {
+    if(err) console.error(err.stack);
+
+    return res.rows[0];
+  });
+};
+
","

As I understand you have wrapped your exported function with async and await:

+
module.exports = function(id) {
+    return new Promise((resolve, reject) => {
+        const pool = require('../loaders/pool.js')();
+
+        pool.query(
+            "SELECT * FROM dealerships WHERE id = '" + id + "';",
+            (err, res) => {
+                if (err) {
+                    console.error(err.stack);
+                    reject(err);
+                }
+                else {
+                    resolve(res.rows[0]);
+                }
+            }
+        );
+    });
+};
+
+

So now just use the async and await in the calling code:

+
async function getData() {
+     const dealership = await require('../models/getDealershipById.js')(id);
+     const dealershipLeads = await require('../models/getLeadsByDealershipId.js')(dealership.id);
+     const dealershipStaff = await require('../models/getStaffByDealershipId.js')(dealership.id);
+}
+
+getData()
+
+

Important: as a side note, avoid "SELECT * FROM dealerships WHERE id = '" + id + "';" as this is a real bad security antipattern, if the id is not sanitized correctly it could very easily allow SQL code injection. Use something like pool.query("SELECT * FROM dealerships WHERE id = ?", [id], ...) if your driver allows it, or replace it with a driver or wrapper that does.

",r +"Ensure at-most-once semantic with SendGrid Mail API

I have an [Azure Storage] queue where I put e-mail messages to be sent. Then, there is a separate service which monitors that queue and send e-mails using some service. In this particular case I'm using SendGrid.

+

So, theoretically, if the sender crashes right after a successful call to SendGrid Mail Send API (https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html), the message will be returned to the queue and retried later. This may result in the same e-mail being delivered more than once, which could be really annoying for some type of e-mail.

+

The normal way to avoid this situation would be to provide some sort of idempotency key to Send API. Then the side being called can make sure the operation is performed at most once.

+

After careful reading of SendGrid documentation and googling, I could not find any way to achieve what I'm looking for here (at most once semantic). Any ideas?

","

Without support for an idempotency key in the API itself your options are limited I think.

+

You could modify your email sending service to dequeue and commit before calling the Send API. That way if the service fails to send the message will not be retried as it has already been removed from the queue, it will be sent at most once.

+

Additionally, you could implement some limited retries on particular http responses (e.g. 429 & 5xx) from SendGrid where you are certain the message was not sent and retrying might be useful - this would maintain "at most once" whilst lowering the failure rate. Probably this should include some backoff time between each attempt.

",r +"Is eliminating construction of unused object allowed in standard even if constructor has observable side-effects?

Consider the following code:

+
#include <iostream>
+
+struct M {
+    M() { std::cout << "M\n"; }
+};
+
+template <class T>
+struct Test {
+    Test() { std::cout << "Test\n"; }
+    inline static auto m = M{};
+};
+int main() {
+    Test<int> t1;
+    //Test t;
+    //(void)&t1.m;
+}
+
+

Using the latest GCC or Clang the only "Test" is printed out. But if we use an address of m object (uncomment the last line (void)&t1.m;) or transform Test class template into the regular (non-templated) class then the M constructor was called.

+

Is this behaviour allowed by the C++ standard? Any quotes?

","

Yes, it's spelled out in the standard.

+
+

[temp.inst] (emphasis mine)

+

4 Unless a member of a class template or a member template is a +declared specialization, the specialization of the member is +implicitly instantiated when the specialization is referenced in a +context that requires the member definition to exist or if the +existence of the definition of the member affects the semantics of the +program; in particular, the initialization (and any associated side +effects) of a static data member does not occur unless the static data +member is itself used in a way that requires the definition of the +static data member to exist.

+
+

Since your example doesn't use the static data member at all, its definition is never fully instantiated.

",r +"ocaml Str.full_split does not returns the original string instead of the expected substring

I am trying to write a program that will read diff files and return the filenames, just the filenames. So I wrote the following code

+
open Printf
+open Str
+let syname: string = "diff --git a/drivers/usc/filex.c b/drivers/usc/filex"
+
+let fileb = 
+  let pat_filename = Str.regexp "a\/(.+)b" in
+  let s = Str.full_split pat_filename syname in
+  s
+
+let print_split_res (elem: Str.split_result) =
+  match elem with
+  | Text t -> print_string t
+  | Delim d -> print_string d
+
+let rec print_list (l: Str.split_result list) =
+  match l with
+  | [] -> ()
+  | hd :: tl -> print_split_res hd ; print_string "\n" ; print_list tl
+;;
+
+() = print_list fileb
+
+

upon running this I get the original sting diff --git a/drivers/usc/filex.c b/drivers/usc/filex back as the output.

+

Whereas if I use the same regex pattern with the python standard library I get the desired result

+
import re
+p=re.compile('a\/(.+)b')
+p.findall("diff --git a/drivers/usc/filex.c b/drivers/usc/filex")
+
+

Output: ['drivers/usc/filex.c ']

+

What am I doing wrong?

","

Not to be snide, but the way to understand OCaml regular expressions is to read the documentation, not compare to things in another language :-) Sadly, there is no real standard for regular expressions across languages.

+

The main problem appears to be that parentheses in OCaml regular expressions match themselves. To get grouping behavior they need to be escaped with '\\'. In other words, your pattern is looking for actual parentheses in the filename. Your code works for me if you change your regular expression to this:

+
Str.regexp "a/\\(.+\\)b"
+
+

Note that the backslashes must themselves be escaped so that Str.regexp sees them.

+

You also have the problem that your pattern doesn't match the slash after b. So the resulting text will start with a slash.

+

As a side comment, I also removed the backslash before /, which is technically not allowed in an OCaml string.

",r +"How to find two common coulmn in R

I have three diferent dataset named mus, dom and cas. They have same colnames including CRA, CHROM, POS, REF and ALT. I need to find the same REF and ALT values based on CHROM in each dataset. In another words I want to have REF and ALT values which is same in each one. for instance REF: A and ALT: T is found in all dataset and It may be in different CHROM, furthermore I need to keep other columns. How can I do that in R? please see below the format of samples. each sample named "cas", "dom" and "mus" has a different CRA and same CHROM, with different POS and REF and ALT. now I'd like to find same values of REF and ALT between these three samples based on CHROM ?

+ +
CRA CHROM   POS REF ALT
+dom_76  chr1    3365296 T   A
+dom_76  chr1    3540134 T   C
+dom_76  chr1    3665288 A   G
+dom_76  chr1    7110674 T   C
+dom_76  chr1    8920460 A   G
+
+

thanks.

","

We can bind the datasets into a single data with bind_rows, while creating an id column (.id), then grouped by 'REF', 'ALT', 'CHROM', filter the rows where the number of distinct elements of 'grp' are 3 i.e. those are the ones having the common values in all the three datasets

+
library(dplyr)
+bind_rows(cas, dom, mus, .id = 'grp') %>%
+         group_by(REF, ALT, CHROM) %>%
+         filter(n_distinct(grp) == 3)
+
",r +"ggplot2 — any way to automatically plot the different transformed-y on the same scatter plot, for you?

Q: Given a typical x,y scatter plot using ggplot(), can ggplot2 automagically plot the transformed y’s as well?

+

Example: simple x,y scatter

+

• In this ex, using stat_smooth(..) feature in ggplot2 to have multiple lm-fits:

+
ggplot(df, aes(x=myX, y=myY)) +
+geom_point(color=‘darkgray’) + 
+   stat_smooth(method=‘lm’, se=F, aes(color=‘black’), formula=“y ~ x”) +
+   stat_smooth(method=‘lm’, se=F, aes(color=‘blue’), formula=“log(y) ~ x”) +
+   stat_smooth(method=‘lm’, se=F, aes(color=‘green’), formula=“sqrt(y) ~ x”) +
+
+   # log-scale it so transforms show up:
+   scale_y_continuous(trans=‘log10’)
+
+

• But I want to plot the scatters for the transformed y’s as well: sqrt(y) andlog(y)

+
    +
  1. Does ggplot2 have such an automagic feature to also plot these into the same plot?

    +
  2. +
  3. If not, what is the simplest recommended approach? Is it to compute manually then unstack (base-R) or melt (reshaper2) them into a long-format?

    +
  4. +
","

I would suggest next approach. You can create the transformations in new variables. Then, reshape data to long and then plot using one visualization for all variables or facets. Here the facet approach:

+
library(tidyverse)
+#Code1
+iris %>% mutate(x=Petal.Length,y=Sepal.Length,logy=log(Sepal.Length),sqrty=sqrt(Sepal.Length)) %>%
+  select(c(x,y,logy,sqrty)) %>%
+  pivot_longer(-x) %>%
+  ggplot(aes(x=x,y=value,color=name,group=name))+
+  geom_point()+
+  geom_smooth(method = lm,se=F)+
+  facet_wrap(.~name,scales = 'free_y')
+
+

Output:

+

+

Or the individual plot approach:

+
#Code2
+iris %>% mutate(x=Petal.Length,y=Sepal.Length,logy=log(Sepal.Length),sqrty=sqrt(Sepal.Length)) %>%
+  select(c(x,y,logy,sqrty)) %>%
+  pivot_longer(-x) %>%
+  ggplot(aes(x=x,y=value,color=name,group=name))+
+  geom_point()+
+  geom_smooth(method = lm,se=F)
+
+

Output:

+

+

I have used iris dataset and tidyverse functions.

",r +"discord.py BS4 can't get info out of href element

I have the following HTML:

+
<a href="//site.com/user/123/Username1"><img height="56px" src="//s.site.com/user/123/avatar" width="56px"/>Username</a>
+
+

How can I get "Username1" before the </a> tag?

","

You can use .text property:

+
from bs4 import BeautifulSoup
+
+html_doc = '''<a href="//site.com/user/123/Username1"><img height="56px" src="//s.site.com/user/123/avatar" width="56px"/>Username</a>'''
+soup = BeautifulSoup(html_doc, 'html.parser')
+
+print(soup.a.text)
+
+

Prints:

+
Username
+
+
+

If you want to parse the username from href="..." attribute:

+
print(soup.a['href'].split('/')[-1])
+
+

Prints:

+
Username1
+
",r +"Combining Multiple Quarters in Tableau

I'm looking to combine the same quarters from each year, based on each region. I'm looking for 'seasonality'. So there would be 4 bars per region, combing the data from the 3 years. Any ideas on how to do this?

+

I've attached a picture of what it looks like now without combined quarters. +Screenshot of Current Look +

","

Dates in tableau always appear in Dimension section of data pane. This however, does not always mean that they are discrete. They can be either discreet or continuous.

+

To understand the difference, let’s first talk about date parts and date values. Discrete dates use date parts. Date parts are literally the parts that make up a date. Let’s take the date of March 6, 2016. The “month” date part is March (or 03). The “day” date part is 6 and the “year” date part is 2016. If I used any of these on their own, such as month, then I would be looking at every March aggregated together in my view and so on.

+

Date values are used for continuous dates. They follow the same structure of date parts (i.e. year, quarter, month, week, day and so on). The difference between date values and date parts is that date values imply a level of detail in a timeline. Remember continuous fields do not create headers, they create an axis. In the case of a continuous date, it creates a timeline. Date values determine how the timeline is organized.

+

After understanding this, you can use dates as either continuous or discreet with either date part or date value.

+

To understand this difference further let's take example of superstore (sample) data. Add [order date] on columns and sum([sales]) on rows. Change mark type to bars, to understand this difference.

+

case-1 Date part as Discreet. +If date part is selected as quarters +Only four bars will be displayed irrespective of the number of years available in [order date]

+

case-2 date part as continuous +There may not be apparent change in view. However if you notice subtle change, the axis of date field has now converted into an continuous axis. (Note: More suitable chart for continuous date is line chart)

+

case-3 date value as continuous +Now there will as many bars as there are number of years in data multiplied by 4. Axis will still be continuous. (Note: More suitable chart for continuous date is line chart)

+

case-4 date value as discreet +There will be as many bars as there are number of years in data multiple by four. Axis will be changed to an discreet axis. (separate bars)

+

*Therefore, you need to select date-part as discreet (see screenshot) for your desired view.

+

",r +"Mathjax breaking with \mathcal and subscript

I am using MathJax3 on a Jekyll website. I have an issue when \mathcal is subscripted inside an equation environment.

+

For example, the following code doesn't work (it is rendered as pure text)

+
\begin{equation}
+    f(x) = \mathcal{L}_{\theta}(x)\sum_{i=1}^N x^2
+\end{equation}
+
+

but the same in the $$ environment works correctly:

+
$$
+    f(x) = \mathcal{L}_{\theta}(x)\sum_{i=1}^N x^2
+$$
+
+

The issue appears to be in having \mathcal with a subscript followed by \sum with a subscript. If I remove the subscript from \mathcal or \sum everything works also in the equation environment. However, \sum doesn't give this issue with any other component, therefore I assume the problem is with \mathcal.

+

My MathJax configuration is the following:

+
<!-- MathJax --> 
+<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
+<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
+<script async src="https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_CHTML"></script>
+
+<script>
+    MathJax = {
+      tex: {
+        inlineMath: [['$', '$'], ['\\(', '\\)']],
+        tags: 'ams'
+      }
+    };
+</script>
+
+<script type="text/javascript"
+    src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
+</script>
+
","

First of all, you are loading MathJax three times, which is never a good idea. Plus you are loading three different versions (your first script loads MathJax v3, your second loads the latest v2 (2.7.9), and the final script loads MathJax v2.7.1). Because the first two scripts have the async attribute, these will not block the rest of the page from being processed, and so the final script (without async) probably will be run before either of the first two are loaded, so you are probably getting version 2.7.1, which is quite old. But it may be that if one of the other versions is in your browser cache, it may be run immediately, and you will get that, and thus it is not clear what version you will actually get. So the first thing you should do is clean up your loading of MathJax (decide on what version you want to use and only load that one).

+

Your script with the MathJax configuration variable contains a v3 configuration, so you may want to retain the first MathJax loading script and remove the others. But the configuration script should come before the script that loads MathJax (so it is in place when MathJax loads).

+

But none of those are the cause of the issue you are having. That is a bad interaction between Jekyll's Markdown and the LaTeX in your page. Markdown uses underscores to delimit italic text, so when you have subscripts for two items, Markdown will insert <emph>...</emph> (or something similar), and since MathJax doesn't process math containing HTML tags, that will prevent your equation from being typeset.

+

Apparently, Jekyll knows about $$...$$ delimiters and prevents the underscores being processed by Markdown, but doesn't know about \begin{equation}...\end{equation}, and so underscores are processed there. I don't use Jekyll myself, so I can't test it, but that's what it looks like to me.

+

See the MathJax documentation for information about such interactions with content-management systems, and potential work-arounds.

",r +"How to overwrite a rewrite_tag in fluent-bit

In my scenario, I'm using a fluent-bit (version 1.6.1) filter to identify a particular log pattern and tag (from.solr.out) it.

+
[FILTER]
+    Name          rewrite_tag
+    Match         test_tag
+    Rule          $msg "^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.*$"  from.solr.out false
+    Emitter_Name  re_emitted
+
+

Then I modify the record to add a field like below

+
[FILTER]
+    Name record_modifier
+    Match from.solr.out
+    Record aid 53
+
+

Now I need to give a new tag (format.logging) to that modified record which I tried with below code snippet and it doesn't work.

+
[FILTER]
+    Name          rewrite_tag
+    Match         from.solr.out
+    Rule          $from.solr.out "^.*$"  format.logging false
+    Emitter_Name  re_emitted_indexing
+
+
    +
  • What is wrong with that approach?

    +
  • +
  • Is there any better approach/filter to achieve this task?

    +
  • +
","

Figure out how to get the result that I expected.

+
...
+[2020/10/22 12:49:07] [ info] [sp] stream processor started
+[0] format.logging: [1603351147.631883694, {"msg"=>"2020-10-16 09:29:03.968 WARN  ...
+
+

I thought the original message that comes with the tag $msg is disappearing after adding the new tag (from.solr.out). Because in my second filter, I'm adding a record to the second tag (from.solr.out) not the initial tag ($msg).

+

Then in the last filter, I was trying to create a new tag (format.logging) by using the second tag (from.solr.out). That's where things have gone wrong. Instead of using the second tag, I tried to use the first tag ($msg) here. Then I got all the changes I needed as the output.

+

Changes I was expecting were;

+
    +
  • Filter the input message to identify some logs
  • +
  • Add a field to the identified messages
  • +
  • Tag the modified message
  • +
+

The final change I've done is

+
[FILTER]
+    Name          rewrite_tag
+    Match         from.solr.out
+    Rule          $msg "^.*$"  format.logging false
+    Emitter_Name  re_emitted_indexing
+
",r +"How to change the auto rounding of floats in a numpy array after the array has been divided by a constant?

Using Python 2.7, and numpy 1.16.5

+

I want to convert array elements from inch to foot

+
FootToInch = 12.0
+a = [.5, 1, 1.5, 2]
+a = np.array(a)
+new_a = a/FootToInch
+
+

I get:

+
[0.04166667 0.08333333 0.125      0.16666667]
+
+

I don't want the first element rounded to that value. I wanted it rounded to the same value +as simply dividing, I.e, .5/12 = 0.041666666666666664

+

Is there a way to change the rounding in the array to get the same value as .5/12?

","

There is a configuration in numpy that sets the level of precision when values are printed to the screen.

+

To set that precision, you use the .set_printoptions() method.

+

To show what effect the printoption has on the visual outputs, I ran this through a range of print settings from 6 digits of precision up to by not including 20 digits in steps of 2 and calculated the value

+
FootToInch = 12.0
+a = [.5, 1, 1.5, 2]
+a = np.array(a)
+
+for prec in range(6, 20, 2):
+    np.set_printoptions(prec)
+    print(prec, ':', a/FootToInch)
+
+

This results in the following outputs:

+
6 : [0.041667 0.083333 0.125 0.166667]
+8 : [0.04166667 0.08333333 0.125 0.16666667]
+10 : [0.0416666667 0.0833333333 0.125 0.1666666667]
+12 : [0.041666666667 0.083333333333 0.125 0.166666666667]
+14 : [0.04166666666667 0.08333333333333 0.125 0.16666666666667]
+16 : [0.0416666666666667 0.0833333333333333 0.125 0.1666666666666667]
+18 : [0.041666666666666664 0.08333333333333333 0.125 0.16666666666666666]
+
",r +"Get User Data from Entry in View Page in Xamarin

In my Xamarin App, I was able to get the data from user through Entry and bind it in ViewModel.cs.

+

But, now I want to get this user data from Entry in ViewPage.

+

Below is code for Entry in .xml page and also of the Data Biding I was using ViewModel (it was working perfectly).

+

How could I get the user data through Entry in PageView.xml.cs too.

+

PageView.xml

+
<Entry
+    Text="{Binding Email}"
+    Keyboard="Email"
+    ReturnType="Done"
+    FontSize="15"
+    Placeholder="Enter Email" >
+</Entry>
+
+<Entry
+    Text="{Binding Password}"
+    Keyboard="Numberic"
+    ReturnType="Done"
+    FontSize="15"
+    IsPassword="true"
+    MaxLenght="8"
+    Placeholder="Enter Password" >
+</Entry>
+
+<Button
+    x:Name="SubmitButton"
+    Text="Submit" />
+
+

PageView.xml.cs

+
FormDataButton.Clicked += async (sender, args) =>
+{
+    if (Email != null && Password != null && Password.Lenght == 8)
+    {
+        // sample code
+        var email = Email;
+        var password = Password;
+    }
+    else{
+        Console.WriteLine("Error");
+    }
+}
+
+

Data Binding I was using in ViewModel.cs

+
private string _Email;
+public string Email
+{
+    get => _Email;
+    set => this.RaiseAndSetIfChanged(ref _Email, value);
+}
+
+private string _Password;
+public string Password
+{
+    get => _Password;
+    set => this.RaiseAndSetIfChanged(ref _Password, value);
+}
+
","

if you mean the code-behind, you just assign the control a name

+
<Entry x:Name="MyEntry"
+    Text="{Binding Email}"
+    Keyboard="Email"
+    ReturnType="Done"
+    FontSize="15"
+    Placeholder="Enter Email" >
+</Entry>
+
+

then in the code behind,

+
if (myEntry.Text == "blah") ...
+
+

however, if you are already using data binding, then you can just access the value via your VM

+
if (VM.Email == "blah") ...
+
",r +"Groupby multiindex columns using dictionary

On a DataFrame with single levels, group the data on columns using a dictionary:

+
df1 = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=['a','b','c','d','e','f','g','h'])
+dict_col= {'a':'ab','b':'ab','c':'c','d':'d','e':'efgh','f':'efgh','g':'efgh','h':'efgh'}
+df1.groupby(dict_col, axis=1).sum()
+    ab          c           d           efgh
+A   1.014831    1.274621    -1.490353   -0.954438
+B   1.484857    -0.968642   0.700881    -3.281607
+C   0.898556    1.444362    0.680974    -2.985182
+
+

On a MultiIndexed DataFrame:

+
MultiIndex = pd.MultiIndex.from_product([['bar', 'baz', 'foo', 'qux'], ['a','b','c','d','e','f','g','h']])
+df2 = pd.DataFrame(np.random.randn(3, 32), index=['A', 'B', 'C'], columns=MultiIndex)
+df2.groupby(dict_col, axis=1, level=1).sum()
+    ab          c           d           efgh
+A   6.583721    -1.554734   1.922187    1.100208
+B   6.138441    0.653721    -0.204472   1.890755
+C   0.951489    2.695940    -1.494028   0.907464
+
+

How to get something like this (All elements on level 0)?

+
    bar                                            baz                                              foo
+    ab          c           d           efgh       ab           c           d           efgh        ......    
+A   6.583721    -1.554734   1.922187    1.100208   4.944954     -1.343831   0.939265    -3.614612   ......
+B   6.138441    0.653721    -0.204472   1.890755   -0.347505    1.633708    0.392096    0.414880    ......
+C   0.951489    2.695940    -1.494028   0.907464   1.905409     -1.021097   -2.399670   0.799798    ......
+
","

One way is to pass a function to groupby, and then convert the tuples back to MultiIndex

+
out = df2.groupby(lambda x: (x[0], dict_col[x[1]]), axis=1).sum()
+out.columns = pd.MultiIndex.from_tuples(out.columns)
+
+

Another way is flatten the column levels by stack then unstack back after groupby:

+
df2.stack(level=0).groupby(dict_col, axis=1).sum().unstack(level=-1)
+
",r +"Javascript regex for specific name validation

I have a university assignment to write a JS regex for name validation: name can include spaces at the beginning and the end (don't ask anything, it's our teacher demand), also it can include such chars like: -, ' and space (" "). At the moment, my regex looks like that:

+
var Nameregex = /^( ?)*[A-Z]+((['-])?[a-z]+)*(([ ]?[a-z]*)*)*$/g;
+
+

It works almost perfect, but except for one case: one word (words separated from each other with spaces and - symbols) can contain only one ' symbol.

+

For example, names like John-andrew'andrew'john shouldn't work. But John-andrew'john-andrew'john should work.

","

Add a (?!.*'[A-Za-z]+') negative lookahead after ^:

+
/^(?!.*'[A-Za-z]+')\s*[A-Z]+(?:['-]?[a-z]+)*(?:\s*[a-z]*)*$/
+
+

See proof

+

Explanation

+
--------------------------------------------------------------------------------
+  ^                        the beginning of the string
+--------------------------------------------------------------------------------
+  (?!                      look ahead to see if there is not:
+--------------------------------------------------------------------------------
+    .*                       any character except \n (0 or more times
+                             (matching the most amount possible))
+--------------------------------------------------------------------------------
+    '                        '\''
+--------------------------------------------------------------------------------
+    [A-Za-z]+                any character of: 'A' to 'Z', 'a' to 'z'
+                             (1 or more times (matching the most
+                             amount possible))
+--------------------------------------------------------------------------------
+    '                        '\''
+--------------------------------------------------------------------------------
+  )                        end of look-ahead
+--------------------------------------------------------------------------------
+  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
+                           more times (matching the most amount
+                           possible))
+--------------------------------------------------------------------------------
+  [A-Z]+                   any character of: 'A' to 'Z' (1 or more
+                           times (matching the most amount possible))
+--------------------------------------------------------------------------------
+  (?:                      group, but do not capture (0 or more times
+                           (matching the most amount possible)):
+--------------------------------------------------------------------------------
+    ['-]?                    any character of: ''', '-' (optional
+                             (matching the most amount possible))
+--------------------------------------------------------------------------------
+    [a-z]+                   any character of: 'a' to 'z' (1 or more
+                             times (matching the most amount
+                             possible))
+--------------------------------------------------------------------------------
+  )*                       end of grouping
+--------------------------------------------------------------------------------
+  (?:                      group, but do not capture (0 or more times
+                           (matching the most amount possible)):
+--------------------------------------------------------------------------------
+    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
+                             or more times (matching the most amount
+                             possible))
+--------------------------------------------------------------------------------
+    [a-z]*                   any character of: 'a' to 'z' (0 or more
+                             times (matching the most amount
+                             possible))
+--------------------------------------------------------------------------------
+  )*                       end of grouping
+--------------------------------------------------------------------------------
+  $                        before an optional \n, and the end of the
+                           string
+
",r +"aws cloudformation - Encountered unsupported property RequestValidatorId

I was trying to create a requestValidator and use it in my request by
+"RequestValidatorId": { +"Ref": "PostRequestValidator" +} +.
+It should return the id of the requestValidator according to the doc.
+https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html

+

But below error occurs.

+

Logical ID: postBannerMethod

+
Encountered unsupported property RequestValidatorId
+
+

resources.json

+
{
+    "AWSTemplateFormatVersion": "2010-09-09",
+    
+    "Parameters": {
+      "RolesStack": {
+        "Type": "String",
+        "Default": "admin-iam-roles"
+      },
+      "HandlerCodeS3Bucket": {
+        "Type": "String",
+        "Default": "admin-lambda-sourcecode"
+      },
+      "HandlerCodeS3BucketLayer": {
+        "Type": "String",
+        "Default": "admin-lambda-sourcecode/layers"
+      },
+      "HandlerCodeS3Key": {
+        "Type": "String",
+        "Default": "helloWorld.zip"
+      }
+    },
+    "Resources": {
+     
+      "MyLayer": {
+        "Type": "AWS::Lambda::LayerVersion",
+        "Properties": {
+            "CompatibleRuntimes": [
+                "nodejs12.x"
+            ],
+            "Content": {
+                "S3Bucket": {
+                  "Ref": "HandlerCodeS3Bucket"
+                },
+                "S3Key": "imageUploadLayer.zip"
+            },
+            "Description": "My layer",
+            "LayerName": "imageLayer",
+            "LicenseInfo": "MIT"
+        }
+    },
+      "createBannerHandler": {
+        "Type": "AWS::Lambda::Function",
+        "Properties": {
+          "FunctionName": "createBanner",
+          "Handler": "createBanner.handler",
+          "Role": {
+            "Fn::ImportValue": {
+              "Fn::Sub": "${RolesStack}-LambdaRoleArn"
+            }
+          },
+          "Code": {
+            "S3Bucket": {
+              "Ref": "HandlerCodeS3Bucket"
+            },
+            "S3Key":"createBanner.zip"
+          },
+          "Layers": [
+            {
+              "Ref": "MyLayer"
+            }
+          ],
+          "Runtime": "nodejs12.x"
+        }
+      },
+      "HelloWorldApi": {
+        "Type": "AWS::ApiGateway::RestApi",
+        "Properties": {
+          "Name": "hello-api",
+          "Description": "API used for practice",
+          "FailOnWarnings": true
+        }
+      },
+      "PostRequestValidator": {
+        "Type" : "AWS::ApiGateway::RequestValidator",
+        "Properties" : {
+            "Name" : "PostRequestValidator",
+            "RestApiId" : {
+                "Ref": "HelloWorldApi"
+            },
+            "ValidateRequestBody" : true,
+            "ValidateRequestParameters" : false
+        }
+      },
+      "BannerResource": {
+        "Type": "AWS::ApiGateway::Resource",
+        "Properties": {
+            "RestApiId": {
+                "Ref": "HelloWorldApi"
+            },
+            "ParentId": {
+                "Fn::GetAtt": [
+                    "HelloWorldApi",
+                    "RootResourceId"
+                ]
+            },
+            "PathPart": "banner"
+        }
+      },
+      "postBannerMethod": {
+        "Type": "AWS::ApiGateway::Method",
+        "DependsOn": ["HelloWorldApi"],
+        "Properties": {
+          "RestApiId": {
+            "Ref": "HelloWorldApi"
+          },
+          "ResourceId": {
+            "Ref": "BannerResource"
+          },
+          "HttpMethod": "POST",
+          "AuthorizationType": "NONE",
+          "Integration": {
+            "Credentials": {
+              "Fn::ImportValue": {
+                "Fn::Sub": "${RolesStack}-ApiGatewayRoleArn"
+              }
+            },
+            "IntegrationHttpMethod": "POST",
+            "Type": "AWS_PROXY",
+            "RequestValidatorId": {
+              "Ref": "PostRequestValidator"
+            },
+            "Uri": {
+              "Fn::Join": ["",
+                [
+                  "arn:aws:apigateway:",
+                  {
+                    "Ref": "AWS::Region"
+                  },
+                  ":lambda:path/2015-03-31/functions/",
+                  {
+                    "Fn::GetAtt": ["createBannerHandler", "Arn"]
+                  },
+                  "/invocations"
+                ]
+              ]
+            }
+          }
+        }
+      }
+    }
+  }
+
+
","

Your RequestValidatorId is one level to deep. It should be in AWS::ApiGateway::Method, not in Integration:

+
{
+  "AWSTemplateFormatVersion": "2010-09-09",
+  "Parameters": {
+    "RolesStack": {
+      "Type": "String",
+      "Default": "admin-iam-roles"
+    },
+    "HandlerCodeS3Bucket": {
+      "Type": "String",
+      "Default": "admin-lambda-sourcecode"
+    },
+    "HandlerCodeS3BucketLayer": {
+      "Type": "String",
+      "Default": "admin-lambda-sourcecode/layers"
+    },
+    "HandlerCodeS3Key": {
+      "Type": "String",
+      "Default": "helloWorld.zip"
+    }
+  },
+  "Resources": {
+    "MyLayer": {
+      "Type": "AWS::Lambda::LayerVersion",
+      "Properties": {
+        "CompatibleRuntimes": [
+          "nodejs12.x"
+        ],
+        "Content": {
+          "S3Bucket": {
+            "Ref": "HandlerCodeS3Bucket"
+          },
+          "S3Key": "imageUploadLayer.zip"
+        },
+        "Description": "My layer",
+        "LayerName": "imageLayer",
+        "LicenseInfo": "MIT"
+      }
+    },
+    "createBannerHandler": {
+      "Type": "AWS::Lambda::Function",
+      "Properties": {
+        "FunctionName": "createBanner",
+        "Handler": "createBanner.handler",
+        "Role": {
+          "Fn::ImportValue": {
+            "Fn::Sub": "${RolesStack}-LambdaRoleArn"
+          }
+        },
+        "Code": {
+          "S3Bucket": {
+            "Ref": "HandlerCodeS3Bucket"
+          },
+          "S3Key": "createBanner.zip"
+        },
+        "Layers": [
+          {
+            "Ref": "MyLayer"
+          }
+        ],
+        "Runtime": "nodejs12.x"
+      }
+    },
+    "HelloWorldApi": {
+      "Type": "AWS::ApiGateway::RestApi",
+      "Properties": {
+        "Name": "hello-api",
+        "Description": "API used for practice",
+        "FailOnWarnings": true
+      }
+    },
+    "PostRequestValidator": {
+      "Type": "AWS::ApiGateway::RequestValidator",
+      "Properties": {
+        "Name": "PostRequestValidator",
+        "RestApiId": {
+          "Ref": "HelloWorldApi"
+        },
+        "ValidateRequestBody": true,
+        "ValidateRequestParameters": false
+      }
+    },
+    "BannerResource": {
+      "Type": "AWS::ApiGateway::Resource",
+      "Properties": {
+        "RestApiId": {
+          "Ref": "HelloWorldApi"
+        },
+        "ParentId": {
+          "Fn::GetAtt": [
+            "HelloWorldApi",
+            "RootResourceId"
+          ]
+        },
+        "PathPart": "banner"
+      }
+    },
+    "postBannerMethod": {
+      "Type": "AWS::ApiGateway::Method",
+      "DependsOn": [
+        "HelloWorldApi"
+      ],
+      "Properties": {
+        "RestApiId": {
+          "Ref": "HelloWorldApi"
+        },
+        "ResourceId": {
+          "Ref": "BannerResource"
+        },
+        "HttpMethod": "POST",
+        "AuthorizationType": "NONE",
+        "RequestValidatorId": {
+          "Ref": "PostRequestValidator"
+        },
+        "Integration": {
+          "Credentials": {
+            "Fn::ImportValue": {
+              "Fn::Sub": "${RolesStack}-ApiGatewayRoleArn"
+            }
+          },
+          "IntegrationHttpMethod": "POST",
+          "Type": "AWS_PROXY",
+          "Uri": {
+            "Fn::Join": [
+              "",
+              [
+                "arn:aws:apigateway:",
+                {
+                  "Ref": "AWS::Region"
+                },
+                ":lambda:path/2015-03-31/functions/",
+                {
+                  "Fn::GetAtt": [
+                    "createBannerHandler",
+                    "Arn"
+                  ]
+                },
+                "/invocations"
+              ]
+            ]
+          }
+        }
+      }
+    }
+  }
+}
+
",r +"matching very long and complex version numbers with regular expressions in python

I have lots of lines like this.

+
some text some more text v3.1.0-beta.4 more & more text
+some text some v2 build.3 some more text more & more text
+some text some v21.1.23456.551436a4 alpha.4 some more text v16.1.2 more & more text
+
+

version numbers are:

+
v3.1.0-beta.4
+v2 build 3
+v21.1.23456.551436a4 alpha.4 and v16.1.2
+
+

The problem is I can have have words beta or build or neither in my version numbers. variable length of version numbers.

+

Here's what I have now and this can only match numbers.

+
\d+(?:\.\d+)+
+
+

How do I search for the existence of one or more version numbers in a give line like shown in above lines like above?

","

You may try this regex:

+
\bv[\d+]+[\w.]*(?:[-\s]+(?:alpha|beta|build)[\w.]*)?
+
+

RegEx Demo

+

Pattern Details:

+
    +
  • \bv: Match v after a word boundary
  • +
  • [\d+]+: Match 1+ digit or dot characters
  • +
  • [\w.]*: Match 0 or more word or dot characters
  • +
  • (?:[-\s]+(?:alpha|beta|build)[\w.]*)?: starting with whitespace or hyphen, optionally match alpha|beta|build part followed by 0 or more word or dot characters
  • +
",r +"What is a REST way to ""publish"" an offer?

I have a rest interface where buy and sell offers are made.
+An offer is first created, then potentially edited and finally, published.

+

Now for my question. Since additional verbs are prohibited in rest, how can I describe publishing of an offer?

","

Here's a potential restful workflow

+

Create

+
    +
  • POST /offers/buys/unpublished { your buy offer resource }
  • +
+

Edit

+
    +
  • PUT /offers/buys/unpublished/123 { your complete replacement buy offer resource } +or
  • +
  • PATCH /offers/buys/unpublished/123 { a patch document for the fields being edited }
  • +
+

Publish

+
    +
  • POST /offers/buys/published { your unpublished resource with ID 123 }
  • +
+

Delete

+

You could delete the offer before or after it was published. In that case you'd have one of these.

+
    +
  • DELETE /offers/buys/unpublished/123
  • +
  • DELETE /offers/buys/published/123
  • +
+

The paths can be a bit debatable, but generally nouns are acceptable.

+

I prefer paths like the above (that also have adjectives), but you could do something like /published-buy-offers or you could do away with the adjectives and assume the resource's representation has fields to represent the kinds and states of offers. Then the path can be something simple like /offers.

",r +"Can you pass a shipping address to Stripe Checkout

I am using Stripe Checkout API to direct a website user to make payment.

+

Is there a way to pass a shipping address to the hosted checkout page so it's gathered from the referrer rather then Stripe themselves?

+
function createSession()
+{
+    require 'vendor/autoload.php';
+    \Stripe\Stripe::setApiKey('[API_KEY_REDACTED]');
+    
+    $YOUR_DOMAIN = '[SITE_URL_REDACTED]';
+    
+    // Calculate price
+    $price = 50;
+    
+    $checkout_session = \Stripe\Checkout\Session::create([
+        'billing_address_collection' => 'required',
+        'payment_method_types' => ['card'],
+        'line_items' => [[
+            'price_data' => [
+                'currency' => 'gbp',
+                'unit_amount' => $price,
+                'product_data' => [
+                    'name' => 'Product'
+                ],
+            ],
+            'quantity' => 1,
+        ]],
+        'mode' => 'payment',
+        'success_url' => $YOUR_DOMAIN . '/success',
+        'cancel_url' => $YOUR_DOMAIN . '/cancel',
+    ]);
+    
+    return json_encode(['id' => $checkout_session->id]);
+}
+
+

You can add the following line to make Stripe ask for a shipping address, but I want to pass this from the referrer instead.

+
'shipping_address_collection' => [
+    'allowed_countries' => ['US', 'CA'],
+],
+
","

To do this you would create a Customer and provide their shipping address, then provide that existing Customer when creating the Checkout session:

+
$checkout_session = \Stripe\Checkout\Session::create([
+    'customer' => 'cus_123',
+    ...
+]);
+
",r +GCP: How can I find Instances running for a specific time?

I try to identify all instances running in my Google Cloud Plattform environment for longer than a certain time period specified by me. How can I achieve this?

,"

Try:

+
 gcloud compute instances list --filter="creationTimestamp.date('%s', Z)< $(date -d'5 hours ago' +%s)" --format="csv[no-heading](NAME)" 
+
+

This should list you all instances running for e.g. more than 5 hours.

",r +"Skip Email Verifications On Adding O365 Guest User

We would like to skip the email verification step in the process of adding a guest user in an O365 tenant. There is an api that allows one to create an invitation through which we can disable 'email notification' but if the newly added user does not have an account on any of the O365 tenants then email verification seems to be mandatory.

+

Our application uses microsoft graph apis along with custom UI's for integrating with microsoft teams. For our application, email verification needs to be skipped since the user is already authenticated and authorized before he reaches the microsoft teams UI.

+

Is there anyway through which the email verification could be skipped?

+

Thanks.

","

@Andy Dufresne:

+

Firstly, we can't skip the email verification process, it's a mandatory. +For your requirement, could you please have a look on this document.

",r +"Calculator with radio button and if statement

I am beginner in JavaScript and I am trying to write a code, but I can't. I want to write a calculator which includes radio button (with three choices)and when user chooses one of them it calculates different things, for example calculateing bmi or area of different shapes.

+

In the other words, I want to take 5 different numbers which user writes in fields. Then with this numbers and radio button selection, write a calculator. Then I want to show the result to user. +Is it possible to help me?

","

Maybe try and get an idea on how JavaScript works before moving onto something like this. I can't say it's advanced but considering you're a beginner, I think you should start off small, and understand the syntax of JavaScript better. There's tons of videos on YouTube on how to make a button calculator in JavaScript, and while I don't understand what exactly you're wanting, if you're really committed to this project you have in mind, maybe follow a YouTube tutorial on how to make a basic button calculator. You can then understand how radio buttons work and maybe experiment around with them in a way you want them to function.

+

Then, if you stumble upon some confusion or errors, you can paste your code snippet here and ask. Because right now, we can't write your code for you. This site is meant for asking programming questions while showing your code so people here and see where you're wrong and help you fix that error and then you can continue off with that new solution, while also learning something.

",r +"How to autowire datasource from dependent spring boot app in another spring boot jar project?

I have Spring boot web app let's name it A and jar spring boot project let's name it B. There is dependency to jar B in pom file of Spring boot app A. DataSource is defined in app A. The question now is as follows: Is there possibility to autowire DataSource from app A in jar B? +When I try to autowire there is warning: "Could not autowire. No beans of "DataSource" type found". Is there possibility to point spring boot in jar B, to autowire DataSource from dependent app? Any suggestions will be very helpful. Thank's a lot!

","

You can do that just add the @ComponentScan annotation and include package of the first app to be scanned by Spring in the second app.

+

Here is something that you should do in the second app:

+
@ComponentScan("foo.bar")
+@SpringBootApplication
+
",r +"Three.js and Django?

somebody knows if can i upload a Three.js project to Django? +i did a project to upload jpg and png images in Django, but i have another project in three.js to use .OBJ images, but now i neet to include my Three.js project to my Django project but i don't know how and if its posible to do it... Thank u so much! +enter image description here

+
+

files to Django project

+
+

files to Three.js project

","

Yes, you can use both Django and Three.js together. +Three.js is a library run on the client-side and so needs to be included with the static files for Django.

+

From the directory structures, you have included in your question the index.html file would become a Django template. It's not clear what elements of your Three.js project you want to make dynamic or vice versa. +The rest of the Three.js folder structure could then be moved to a static folder. +You will probably need to update the path structure of the imports in the Three.js scripts to include /static/original_folder/file.type

",r +"second AsyncResult in Celery returns None[Python]

When I create the second AsyncResult, I get nothing when I try to get the task result (the PENDING status). How can this be avoided?

+
        res = AsyncResult(task_id)
+        print(task_id)
+        result = res.get()
+        print(result)
+        res = AsyncResult(task_id)
+        result = res.get()
+        print(result)
+
",

You need to cache the result if you may need it again. Calling get() and forget() frees resources created to store that AsyncResult object data.

,r +"Dynamic appending of the textarea elements with jQuery

I have a drop-down list with some options. Multiple options can be selected at once. When some options are selected the corresponding hidden divs are shown.

+

Now I need to dynamically add a textarea to the shown divs - not to all of them. If an option is deselected the corresponding div is hidden and the added textarea input must be removed from it. How can I do that?

+

+
+
$(""#dist"").change(function() {
+  var optionValue = $(this).val();
+  if (optionValue) {
+    $("".dist-box"").hide();
+    for (var k in optionValue) {
+      $('div.' + optionValue[k]).show();
+    }
+  } else {
+    $("".dist-box"").hide();
+  }
+}).change();
+
.dist-box {
+  color: #fff;
+  padding-top: 10px;
+  display: none;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js""></script>
+<select name=""dist[]"" id=""dist"" class=""dist"" multiple="""">
+  <option value=""dih"">dih</option>
+  <option value=""vii"">vii</option>
+  <option value=""des"">des</option>
+</select>
+
+<div id=""dih"" name=""dih"" class=""dih dist-box"" style=""color: initial; display: none;"">
+  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
+</div>
+
+<div id=""vii"" name=""vii"" class=""vii dist-box"" style=""color: initial; display: none;"">
+  Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.
+</div>
+
+<div id=""des"" name=""des"" class=""des dist-box"" style=""color: initial; display: none;"">
+  Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.
+</div>
+
+
+

+

https://jsfiddle.net/u3tm7b0r/1/

","

To achieve what you need you can hide all the .dist-box elements when a change is made, then use the selected values from the select to build a selector string to target the required ones, before appending the textarea to them and displaying them:

+

+
+
$(""#dist"").change(function() {
+  $('.dist-box').hide().find('textarea').remove();
+  if (!this.value)
+    return;
+    
+  let idSelector = $(this).val().map(v => `#${v}`).join(',');
+  $(idSelector).append(function() {
+    return `<textarea name=""${this.id}""></textarea>`
+  }).show();
+}).change();
+
.dist-box {
+  color: #fff;
+  padding-top: 10px;
+  display: none;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js""></script>
+<select name=""dist[]"" id=""dist"" class=""dist"" multiple="""">
+  <option value=""dih"">dih</option>
+  <option value=""vii"">vii</option>
+  <option value=""des"">des</option>
+</select>
+
+<div id=""dih"" class=""dih dist-box"" style=""color: initial; display: none;"">
+  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
+</div>
+
+<div id=""vii"" class=""vii dist-box"" style=""color: initial; display: none;"">
+  Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.
+</div>
+
+<div id=""des"" class=""des dist-box"" style=""color: initial; display: none;"">
+  Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.
+</div>
+
+
+

+

That being said, the dynamic appending of the textarea elements seems almost entirely redundant, as the textarea are always present when the parent .dist-box is visible, so you could just leave them present in the DOM but hidden along with the parent.

",r +"Multiple material-ui tooltips open on click

I'm trying to use 2 Material-UI tooltips in the same parent component. Also, I need a custom control for the open and close action of the tooltips. So, I used the open and setOpen states using the UseState hook.

+

How can I maintain separate states for the 2 tooltips that I use, so that I can differentiate between the respective tooltip's open and close action?

+

Please help. Hope I made the problem statement clear.

","

Create two separate state variables

+
const MyComponent = () => {
+  const [open1, open1Set] = useState(false);
+  const [open2, open2Set] = useState(false);
+};
+
",r +"Whats the difference between ForwardRefExoticComponent and ForwardRefRenderFunction in react?

I'm writing a React component which can forward ref to its chilren

+

I found out that for the return type of the function components, I can use ForwardRefExoticComponent and ForwardRefRenderFunction. But I'm not sure whats the difference between them.

+

So far, When using ForwardRefExoticComponent, I can extend it while the ForwardRefRenderFunction cannot? I posted a question related to my case here : How to export forwardRef with ForwardRefRenderFunction

+

If anyone know whats the difference between them and what they do please help me. Because it seems that React team has no document about them (but they are inside react package)

","

ForwardRefExoticComponent

+

The definition taken from here is

+
interface ExoticComponent<P = {}> {
+    /**
+     * **NOTE**: Exotic components are not callable.
+     */
+    (props: P): (ReactElement|null);
+    readonly $$typeof: symbol;
+}
+
+interface NamedExoticComponent<P = {}> extends ExoticComponent<P> {
+    displayName?: string;
+}
+
+interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> {
+    defaultProps?: Partial<P>;
+    propTypes?: WeakValidationMap<P>;
+}
+
+

If you write it out you get

+
interface ForwardRefExoticComponent<P> {
+    /**
+     * **NOTE**: Exotic components are not callable.
+     */
+    (props: P): (ReactElement|null);
+    readonly $$typeof: symbol;
+    displayName?: string;
+    defaultProps?: Partial<P>;
+    propTypes?: WeakValidationMap<P>;
+}
+
+

ForwardRefRenderFunction

+

The definition taken from here is

+
interface ForwardRefRenderFunction<T, P = {}> {
+    (props: PropsWithChildren<P>, ref: ((instance: T | null) => void) | MutableRefObject<T | null> | null): ReactElement | null;
+    displayName?: string;
+    // explicit rejected with `never` required due to
+    // https://github.com/microsoft/TypeScript/issues/36826
+    /**
+     * defaultProps are not supported on render functions
+     */
+    defaultProps?: never;
+    /**
+     * propTypes are not supported on render functions
+     */
+    propTypes?: never;
+}
+
+

Differences

+
    +
  • ForwardRefRenderFunction does not support propTypes and defaultProps, whereas ForwardRefExoticComponent does.
  • +
  • ForwardRefExoticComponent has an additional member $$typeof of type symbol
  • +
  • The call signature of ForwardRefRenderFunction takes a props object, which must include a member children and a ref object as parameters, whereas the call signature of ForwardRefExoticComponent only takes a props object of arbitrary shape as parameter.
  • +
+

Some more thoughts

+

The interplay of those two definitions is best seen in the definition of the forwardRef function:

+
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
+
+

Also, a big difference between the two definitions seems to be, that ForwardRefExoticComponent (like all exotic components) are no function components, but actually just objects, which are treated specially when rendering them. Therefore the comment

+
+

NOTE: Exotic components are not callable.

+
+

And for some reason, those exotic components are necessary in some places.

",r +"MySQL access string like an array

I'm was trying to make function that will return random character. What I have is a string that contains alphanumerics. In Postgresql I can set text as array, but I don't know how MySQL do same. for example:

+

in postgresql

+
DECLARE chars TEXT[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
+
+

So when I want get chars[10] it will return A. How to do this in MySQL?

","

I think the questoin is not about arrays, it is about get random char, right? In this case You can use next approach in MySQL:

+
SELECT SUBSTRING(
+        '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 
+        ROUND(RAND()*61)+1,
+         1
+    ) as random_char;
+
+

The SUBSTRING function returns one char from random position.

+

Try it on SQLize.online

",r +"Can dynamic method in outer block be accessed in child block? - Ruby Meta Programming

I have a DSL that allows me to write ruby code dynamically.

+

The Outer class takes a custom block of code to be processed.

+

There is also a well-known DSL method called settings which can take its own block of code for configuration purposes.

+

I want to be able to create reusable methods in the other block and have them available from within the inner block.

+

While writing the sample code for this post, I stumbled upon a usage that works by assigning self to a variable in the outer scope and calling the method on the variable in the child scope.

+

I would prefer to NOT need to assign self to a variable and I noticed that if I tried to do something similar in RSPEC, then I don't need to use variable = self, I can define methods in parent blocks and they are available in child blocks, see the last example.

+

Classes

+
class Settings
+  attr_accessor :a
+  attr_accessor :b
+  attr_accessor :c
+
+  def initialize(&block)
+    instance_eval(&block)
+  end
+end
+
+class Outer
+  def initialize(&block)
+    instance_eval(&block)
+  end
+
+  def build_settings(&block)
+    Settings.new(&block)
+  end
+end
+
+

Run the code

+
Outer.new do
+
+  # Create a method dynamically in the main block
+  def useful_method
+    '** result of the useful_method **'
+  end
+
+  x = self
+
+  settings = build_settings do
+    self.a = 'aaaa'
+    self.b = useful_method()    # Throws exception
+    self.c = x.useful_method()  # Works
+  end
+
+end
+
+

Run the code (with detailed logging)

+
# Helper to colourize the console log
+class String
+  def error;          "\033[31m#{self}\033[0m" end
+  def success;        "\033[32m#{self}\033[0m" end
+end
+
+# Run code with detailed logging
+Outer.new do
+
+  # Create a method dynamically in the main block
+  def useful_method
+    '** result of the useful_method **'
+  end
+
+  puts "respond?: #{respond_to?(:useful_method).to_s.success}"
+
+  x = self
+
+  settings = build_settings do
+    puts "respond?: #{respond_to?(:useful_method).to_s.error}"
+    self.a = 'aaaa'
+    begin
+      self.b = useful_method().success
+    rescue
+      self.b = 'bbbb'.error
+    end
+    begin
+      self.c = x.useful_method().success
+    rescue
+      self.c = 'cccc'.error
+    end
+  end
+
+  puts "a: #{settings.a}"
+  puts "b: #{settings.b}"
+  puts "c: #{settings.c}"
+
+end
+
+

Console Log from the running code

+
    +
  • Assignment to b throws an exception
  • +
  • Assignment to c works fine
  • +
+

+

Sample in RSpec where you don't need to assign self

+

Why can I access the usefull_method in the RSpec DSL, but not in my own.

+
RSpec.describe 'SomeTestSuite' do
+  context 'create method in this outer block' do
+    def useful_method
+      'david'
+    end
+
+    it 'use outer method in this inner block' do
+      expect(useful_method).to eq('david')
+    end
+  end
+end
+
","

You could pass the Outer instance to Settings.new:

+
class Outer
+  def initialize(&block)
+    instance_eval(&block)
+  end
+
+  def build_settings(&block)
+    Settings.new(self, &block)
+    #            ^^^^
+  end
+end
+
+

and from within Settings use method_missing to delegate undefined method calls to outer:

+
class Settings
+  attr_accessor :a
+  attr_accessor :b
+  attr_accessor :c
+
+  def initialize(outer, &block)
+    @outer = outer
+    instance_eval(&block)
+  end
+
+  private
+
+  def method_missing(name, *args, &block)
+    return super unless @outer.respond_to?(name)
+
+    @outer.public_send(name, *args, &block)
+  end
+
+  def respond_to_missing?(name, include_all = false)
+    @outer.respond_to?(name, include_all) or super
+  end
+end
+
+

This way, useful_method can be called without an explicit receiver.

",r +"A problem comes when I add chinese,simplified to localization

I want to add chinese, simplified to localization file and a message shows: +“Localizable.strings” couldn’t be copied to “zh-Hans.lproj” because an item with the same name already exists. To save the file, either provide a different name, or move aside or delete the existing file, and try again.

+

There is not chinese, simplified in the list and I just can't add it. By the way, other languages works fine when I try to add them.Anyone know how to deal with it?

+

+

+

","

I find the reason at last. Maybe my colleague add the chinese, simplified before and he didn't delete the file in the project but just delete the cell in the list. After I delete the chinese, simplified file in the project, it works fine.

",r +"Pandas: Sort a Multiindex Dataframe's multi-level column with mixed datatypes

Below is my dataframe:

+
In [2804]: df = pd.DataFrame({'A':[1,2,3,4,5,6], 'D':[{"value": '126', "perc": None, "unit": None}, {"value": 324, "perc": None, "unit": None}, {"value": 'N/A', "perc": None, "unit": None}, {}, {"value": '100', "perc": None, "unit": None}, np.nan]})
+
+In [2794]: df.columns = pd.MultiIndex.from_product([df.columns, ['E']])
+
+In [2807]: df
+Out[2807]: 
+   A                                             D
+   E                                             E
+0  1  {'value': '126', 'perc': None, 'unit': None}
+1  2    {'value': 324, 'perc': None, 'unit': None}
+2  3  {'value': 'N/A', 'perc': None, 'unit': None}
+3  4                                            {}
+4  5  {'value': '100', 'perc': None, 'unit': None}
+5  6                                           NaN
+
+

I need to sort the multi-level column with index (D,E) in descending order based on value key from dict.

+

As you can see value key can have values in mixed datatypes like int, string or empty like {}, or NaN.

+

N/A and Nan values should always appear at last after sorting(both asc and desc).

+

Expected output:

+
In [2814]: df1 = pd.DataFrame({'A':[2,1,5,3,4,6], 'D':[{"value": 324, "perc": None, "unit": None}, {"value": '126', "perc": None, "unit": None}, {"value": '100', "perc": None, "unit": None}, {"value": 'N/A', "perc": None, "unit": None}, {},np.nan]})
+
+In [2799]: df1.columns = pd.MultiIndex.from_product([df1.columns, ['E']])
+
+In [2811]: df1
+Out[2811]: 
+   A                                             D
+   E                                             E
+0  2    {'value': 324, 'perc': None, 'unit': None}
+1  1  {'value': '126', 'perc': None, 'unit': None}
+2  5  {'value': '100', 'perc': None, 'unit': None}
+3  3  {'value': 'N/A', 'perc': None, 'unit': None}
+4  4                                            {}
+5  6                                           NaN
+
","

Create helper column filled by numeric and sorting by this column:

+
df['tmp'] = pd.to_numeric(df[('D','E')].str.get('value'), errors='coerce')
+df1 = df.sort_values('tmp', ascending=False).drop('tmp', axis=1)
+print (df1)
+   A                                             D
+   E                                             E
+1  2    {'value': 324, 'perc': None, 'unit': None}
+0  1  {'value': '126', 'perc': None, 'unit': None}
+4  5  {'value': '100', 'perc': None, 'unit': None}
+2  3  {'value': 'N/A', 'perc': None, 'unit': None}
+3  4                                            {}
+5  6                                           NaN
+
+
+
df1 = df.sort_values('tmp').drop('tmp', axis=1)
+print (df1)
+   A                                             D
+   E                                             E
+4  5  {'value': '100', 'perc': None, 'unit': None}
+0  1  {'value': '126', 'perc': None, 'unit': None}
+1  2    {'value': 324, 'perc': None, 'unit': None}
+2  3  {'value': 'N/A', 'perc': None, 'unit': None}
+3  4                                            {}
+5  6                                           NaN
+    
+
",r +"Repeat binary number to be the same length as another number in python

Say I have a binary number message of 0100110101100101 and a binary key of 001.

+

How can I repeat the key to be the same length as the message? As in take the length of the message and then repeat the pattern of the key till the length of the message is reached?

+

In the example the output should be 0010010010010010

+

Thanks.

","

You can use python's list slicing:

+
In [1599]: a = '0100110101100101'
+In [1602]: key = '001'
+
+In [1608]: factor = len(a) // len(key)
+In [1606]: remainder = len(a) % len(key)
+
+In [1625]: if factor == 0:
+      ...:     print("pattern greater than the string")
+      ...: else:
+      ...:     answer = (key * factor) + key[:remainder]
+      ...: 
+
+In [1614]: answer
+Out[1614]: '0010010010010010'
+
",r +"How to display array in String as table rows with Javascript/jquery

In my script I'm getting a String as a result from PHP database request through an ajax call. The result string looks like this:

+
array(4) {
+  [0]=>
+  array(3) {
+    ["id"]=>
+    string(3) "181"
+    ["number"]=>
+    string(2) "37"
+    ["livingid"]=>
+    string(1) "1"
+  }
+  [1]=>
+  array(3) {
+    ["id"]=>
+    string(3) "181"
+    ["number"]=>
+    string(2) "37"
+    ["livingid"]=>
+    string(1) "2"
+  }
+  [2]=>
+  array(3) {
+    ["id"]=>
+    string(3) "185"
+    ["number"]=>
+    string(2) "37"
+    ["livingid"]=>
+    string(1) "1"
+  }
+  [3]=>
+  array(3) {
+    ["id"]=>
+    string(3) "185"
+    ["number"]=>
+    string(2) "37"
+    ["livingid"]=>
+    string(1) "2"
+  }}
+
+

I dont know why it is returned like this. I want to display the result in a table. For that I would use jquery:

+
   $("#deActWh").append(result); //#deActWh is the id of table 
+
+

But this is only working, if I'm having the html table syntx in the string like <tr> <td> and so on. Im looking for a good way to convert this string back to an array and inserting the html syntax in each row. I also need to get rid of all the unnecessary stuff like "array(4)... string(3) ..etc." I thougt about using the split() method, but I dont know how I could use this method usefully here. I'm open for suggestions or other approaches.

","

Instead of returning it as a php array, you can return it as a json_encoded string.

+

I am assuming that you are using pdo to fetch the result out from mysql and you return that straight away to to the ajax.

+

$result = whatever your pdo call is.

+

return json_encode($result);

+

Since jquery is javascript, it can interpret JSON easily. However, you still have to loop through and build the table yourself.

",r +"Extract number with percentage

I have several texts from which I need to extract the number with a percentage, e.g., 1.4%, 2.5% and so on.

+

It is always one line within the whole text with the words 'management fee'. Issue is that sometimes it is 'management fee per year 3.5%' or 'management fee up to 2 years 2,5%' (the number can be with a dot or a comma).

+

So far I have

+
(?<=management fee\s)\d+([\,\.]\d+)?%
+
+

but this only works for the 'management fee 3.5%' and not for cases in which there are more words after management fee.

+

How can achieve this?

","

You can match `management free and repeat optional words after it, as least as possible. Use a capturing group to get the value with the percentage sign.

+

You don't have to escape the . and the , in the character class.

+

If the whitespace char should be present before the number, you could use \s+ to match 1+ more times.

+
\bmanagement fee(?:\s+\w+)*?\s*(-?\d+(?:[.,]\d+)?%)
+
+

Regex demo

+
import re
+ 
+regex = r"\bmanagement fee(?:\s+\w+)*?\s*(-?\d+(?:[.,]\d+)?%)"
+s = "management fee per year 3.5% or management fee up to 2 years 2,5%"
+print(re.findall(regex, s))
+ 
+# ['3.5%', '2,5%']
+
",r +"Transferring and Deleting Data in Google Spreadsheets

I am trying to use Google Apps Script to create a function that will search for word Yes in a specific column in my Google Spreadsheet.

+

If it finds Yes, it will then continue to copy those entire rows onto a different spreadsheet saved to my google drive and then delete it from the original spreadsheet.

+

I have little to none experience with this language, but I have made some code.

+

I am looking for a correct way to execute this and how to complete my code. What would you do?

+

Newest code edit:

+
function moveDelete() {
+  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
+  var dsh=SpreadsheetApp.getActive().getSheetByName('Sheet2');
+
+  var data = sh.getRange(1, 1, sh.getLastRow()-1).getValues();
+  var range = sh.getRange(1, 1, data.length);
+
+
+  var rowsDeleted = 0;
+  for (var i = 0; i <= data.length - 1; i++) {3
+    var array = data[i]
+    if (array[4] == 'Yes') {
+      dsh.appendRow(array);
+      sh.deleteRow((parseInt(i)+1) - rowsDeleted);
+      rowsDeleted++;
+    }
+  }
+};
+
+function onOpen() {
+  var sheet = SpreadsheetApp.getActiveSpreadsheet();
+  var entries = [{
+    name : "Send to Record",
+    functionName : "moveDelete"
+  }];
+  sheet.addMenu("Custom Menu", entries);
+};
+
","

Solution 1 - transfer to the same document:

+
function moveDelete() {
+  
+  var ss = SpreadsheetApp.getActive()
+  var sh = ss.getSheetByName('Sheet1');
+  var dsh= ss.getSheetByName('Sheet2');  
+  var data = sh.getDataRange().getValues();
+
+  var rowsDeleted = 0;
+  for (var i = 0; i <= data.length - 1; i++) {
+    var array = data[i]
+    if (data[i][4] == 'Yes') {
+      dsh.appendRow(array);
+      sh.deleteRow((parseInt(i)+1) - rowsDeleted);
+      rowsDeleted++;
+    }
+  }
+};
+
+

Solution 2 (based on comment) - transfer to another spreadsheet file:

+
function moveDelete() {
+  
+  var ss = SpreadsheetApp.getActive();
+  var ts = SpreadsheetApp.openById("id of the target spreadsheet here"); // example: 31d6k7iXh20rjLn22m0axvscR6-BcyOy_fxhdk-ResXU
+  var sh = ss.getSheetByName('Sheet1'); // Sheet1 of the source spreadsheet
+  var dsh= ts.getSheetByName('Sheet2'); // Sheet2 of the target spreadsheet
+  var data = sh.getDataRange().getValues();
+
+  var rowsDeleted = 0;
+  for (var i = 0; i <= data.length - 1; i++) {
+    var array = data[i]
+    if (data[i][4] == 'Yes') {
+      dsh.appendRow(array);
+      sh.deleteRow((parseInt(i)+1) - rowsDeleted);
+      rowsDeleted++;
+    }
+  }
+};
+
+

Note that 1. uses 4 as an index which checks for the 5th column which is column E. Make sure to get the index number right to pick the desired column.

",r +"F# If-statement type mismatch errors

Im a relatively new F# programmer, and it seems everytime i fix one problem in my code another arises, so my issue is inside the transpose recursive function, i want to run an if-else statement inside it to check if the input is actually valid or not, however this errors and im not sure why or how to fix it.

+

I already have a question with quite a similar issue and title, however i was told to make a new question instead of editing the old one because of various reasons.

+
type Result<'T,'TError> =
+    | Ok of 'T
+    | Error of 'TError
+
+
+let isValidTBL list =
+    match List.map List.length list |> List.distinct |> List.length with
+    | 1 -> true
+    | _ -> false
+
+
+
+let Column_1 list =
+    if List.exists List.isEmpty list then [] // return empty list
+    else
+    list |> List.map List.head
+
+let Column_2 list =
+    if List.exists List.isEmpty list then
+        Error "empty value"
+    else
+        list |> List.map List.tail |> Ok
+
+let rec transpose list = [
+  if (isValidTBL list = false) then Error "Invalid Table"
+  else
+  match list with
+  | []::list -> () 
+  | list -> 
+
+        yield Column_1 list 
+        yield! transpose (Column_2 list) ]
+
+
+

warning FS0020: The result of this expression has type 'Result<'a,string>' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'.

+

error FS0001: This expression was expected to have type +''a list list'
+but here has type +'Result<'b list list,string>'

+

thanks in advance

","

The key issue is that you are trying to mix Result with an ordinary F# list. When you are inside a list comprehension, you can only return values using yield, so when you write:

+
let rec transpose list = [
+  if (isValidTBL list = false) then Error "Invalid Table"
+  else 
+    yield // (...)
+]
+
+

The part with Error "Invalid table" is not a return value, but just a value you create and then ignore. This bit you could solve by rearranging the code to start the list comprehension only in the Ok case:

+
let rec transpose list =
+  if (isValidTBL list = false) then Error "Invalid Table"
+  else Ok [
+    yield // (...)
+  ]
+
+

However, this is also not solving all your problems because you want to have a recursive call to transpose and if this is also inside a comprehension, then it's "too late" to return an error.

+

You can write this without comprehensions, but to be honest, I think this gets a lot easier if you just handle the error using exceptions:

+
exception InvalidTable
+exception EmptyValue 
+
+let Column_2 list =
+  if List.exists List.isEmpty list then raise EmptyValue
+  else list |> List.map List.tail 
+
+let rec transpose list = [
+  if (isValidTBL list = false) then raise InvalidTable
+  else
+    match list with
+    | []::list -> ()
+    | list -> 
+        yield Column_1 list 
+        yield! transpose (Column_2 list) ]
+
+

You have to make sure to handle the exceptions and you may want to convert them to Error values if you are using Result throughout your project, but the code becomes simpler this way.

",r +"Why is #regex used in task.json in Azure DevOps extension? What does it check for?

I came across this and was wondering what this means and how it works? +What's the significance of using #regex here and how does it expand?

+

https://github.com/microsoft/azure-pipelines-tasks/blob/master/Tasks/DownloadPackageV0/task.json

+
 "endpointUrl": "{{endpoint.url}}/{{ **#regex ([a-fA-F0-9\\-]+/)[a-fA-F0-9\\-]+ feed }}_apis**/Packaging/Feeds/{{ **#regex [a-fA-F0-9\\-]*/([a-fA-F0-9\\-]+) feed** }}{{#if view}}@{{{view}}}{{/if}}/Packages?includeUrls=false"
+
+

Also I would like to know how many packages will it return and display in the Task input UI dropdown if there are thousands of packages in the feed. Is there a known limit like first 100 or something?

","

#regex doesn't appear to actually be documented anywhere, but it takes two space-delimited arguments. The first is a regular expression and the second is a "path expression" identifying what value to match against, in this case the value of the feed input parameter. If the regex matches the value, it returns the first capturing subexpression, otherwise it returns the empty string.

+

In this particular context, the feed parameter is formatted as 'projectId/feedId', where projectId and feedId are GUIDs, and projectId and the / are eliminated for organization-scoped feeds (i.e. feeds that are not inside a project). The first regex therefore extracts the project ID and inserts it into the URL, and the second regex extracts the feed ID and inserts it into the URL.

+

As of this writing, the default limit on the API it's calling is 1000.

",r +"Invalid face detection type=0 error throws on certain devices - Xamarin.Android

I have xamarin.forms android project app with a custom camera view. I am using Camera.IFaceDetectionListener for detecting faces in the camera preview. It works fine on most of the devices. But in certain devices it throws exception which says invalid face detection type=0 after calling

+
Control.Preview.SetFaceDetectionListener(this);
+Control.Preview.StartFaceDetection();
+
+

After some googling saw some SO post says some devices does not support face detection.

+

From this post Face detection not working , there is a way to check a device whether it support face detection or not by using Camera.getMaxNumDetectedFaces(). How exactly can I use this in xamarin? Or is there any other way to solve this issue? Because my app gets crashed when starting the Face detection. Any help is appreciated.

","

Determine if the device supports facial recognition.

+

You could try to use this before you StartFaceDetection();

+
CameraManager cManager = (CameraManager)GetSystemService(Context.CameraService);
+string cId = (int)CameraFacing.Front + "";
+CameraCharacteristics cameraCharacteristics = cManager.GetCameraCharacteristics(cId);
+int maxCount = (int)cameraCharacteristics.Get(CameraCharacteristics.StatisticsInfoMaxFaceCount);
+
+

If maxCount = 0 then we can be sure that our device does not support face detection

",r +"Confusing UnboundLocalError in Python 3.8

I am just starting to learn how to code so I hope I'm asking this correctly. For practice, I wanted to create a program that will print out classes since the form doesn't really change. It would take inputs, modify them, then put them in the correct order.

+

I'm having trouble taking the words from a list and remove spaces, adding underscores, and modifying values. In a function above the following code, I get the inputs and put them into a global list called required. I have messed with putting global required under def modify(): but that doesn't change anything. The commented out lines are the ones that keep flagging the error "UnboundLocalError: local variable 'i' referenced before assignment". I want to replace the original word and add a modified word. I've tried moving the indentation around without success.

+

It doesn't make sense to me as earlier in the code it has no problem printing 'i' and later in the code it has no trouble doing what I'm looking for either. Why is it having trouble with 'i' in the section in-between where it works just fine?

+

For reference, I am using the values of 'first name', 'last name', 'city', 'company name', 'town'. It prints the results for the strings with spaces correctly and modifies the single word strings and places them correctly into the list.

+
def modify():
+    
+    for i in range(0,len(required)+1):
+        print()
+        print(i)
+        print()
+        if chr(32) in str(required[i]):
+            
+            no_space = ""
+            underscore = ""
+            
+            for l in str(required[i]):
+            
+                if ord(l) !=32:
+                    
+                    no_space += l
+                    underscore += l
+                
+                elif ord(l) == 32:
+                    
+                    del i
+                    underscore += "_"
+                    
+            
+            print()
+            print(no_space)
+            print(underscore)
+            # required.index[c] = no_space
+            # required.append(underscore)
+        
+            # required.insert(i+1,underscore)
+            # required[i] = no_space  
+                      
+                            
+        elif chr(32) not in str(required[i]):
+            
+            if chr(95) in str(required[i]):
+                continue
+            
+            elif chr(95) not in str(required[i]):
+            
+                additional = "the_" + str(required[i])
+            
+                required.insert(i+1,additional)
+            
+    print()
+    for t in range(len(required)):
+        print(str(t+1)+". "+required[t])
+
+

Thank you! I hope this isn't too confusing!

","

I think the error is cause by this line:

+
del i
+
+

You're deleting the value assigned to i in that specific moment, that's why at the beginning you can print it but after that it throws the exception.

",r +"issue with XLPagerTabStrip while implementing in my app

i am creating using Swift in my app i am implementing XLPagerTabStrip and i have referred below blog to implement here is the link

+

This is the reference link

+

all thing works perfect although when i navigate to my Home screen then XLPagerTabStrip showing over status bar here is the screenshot what type of output i am getting

+

This is the screen shot of output which i am getting

+

This is expected output i want something like this

+

This is storyboard screenshot

+

here is my Controller code

+
import UIKit
+import XLPagerTabStrip
+
+class HomeViewController: ButtonBarPagerTabStripViewController {
+
+    //MARK: - VARIABLEs
+    
+    //MARK: - OUTLETs
+    
+    //MARK: - VOID METHODs
+    
+    override func viewDidLoad() {
+        configureButtonBar()
+        super.viewDidLoad()
+        // Do any additional setup after loading the view.
+    }
+    
+    //MARK: - CLICKED EVENTs
+    
+    //MARK: - FUNCTIONs
+    func configureButtonBar() {
+        settings.style.buttonBarBackgroundColor = .white
+        settings.style.buttonBarItemBackgroundColor = .white
+
+        settings.style.buttonBarItemFont = UIFont(name: "Roboto-Medium", size: 14.0)!
+        settings.style.buttonBarItemTitleColor = UIColor(red: 84/255, green: 84/255, blue: 84/255, alpha: 1)
+        
+        settings.style.buttonBarMinimumLineSpacing = 0
+        settings.style.buttonBarItemsShouldFillAvailableWidth = true
+        settings.style.buttonBarLeftContentInset = 0
+        settings.style.buttonBarRightContentInset = 0
+
+        settings.style.selectedBarHeight = 3.0
+        settings.style.selectedBarBackgroundColor = UIColor(red: 112/255, green: 112/255, blue: 112/255, alpha: 1)
+        
+        // Changing item text color on swipe
+        changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
+            guard changeCurrentIndex == true else { return }
+            oldCell?.label.textColor = UIColor(red: 84/255, green: 84/255, blue: 84/255, alpha: 1)
+            newCell?.label.textColor = UIColor(red: 112/255, green: 112/255, blue: 112/255, alpha: 1)
+        }
+    }
+    
+    override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
+        let child1 = UIStoryboard.init(name: "Functional", bundle: nil).instantiateViewController(withIdentifier: "FeedViewController") as! FeedViewController
+        
+        let child2 = UIStoryboard.init(name: "Functional", bundle: nil).instantiateViewController(withIdentifier: "ArticlesViewController") as! ArticlesViewController
+        
+        return [child1, child2]
+    }
+}
+
+

i did everything same as provided in demo app but still XLPagerTabStrip covers status bar and view which contain notification and menu icon i can't get it why this is happing i did everything as in demo can anyone have idea about this

+

as you can see in storyboard screenshot i have added menu and notification icon but XLPagerTabStrip covers that whole view when run the app

+

can anyone have idea why this is happing then please suggest me

","

Please read the blog from the official team. +XLPagerTabStrip tutorial

",r +"How to check if my bot can add a role in discord.js v12?

I've made a warn command that gives the mentioned user a warned role, but I ran into a problem. Sometimes server owners might forget about moving the role of the bot above the warned role, and that would cause the bot to not be able to give the role to the user. I've tried using role.editable, but it returns false even if the role is below the bot's role. The user to warn has also lower roles than the bot. Here is my code:

+
const { DiscordAPIError } = require("discord.js");
+const Discord = require('discord.js');
+const fs = require("fs");
+const ms = require("ms")
+//let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
+var mongoPath = '../../mongo.js' //path.join(__dirname, '..', 'mongo.js');
+const mongo = require(mongoPath)
+const setWarnedSchema = require('../../schemas/setwarned-schema.js')
+const mongoose = require('mongoose');
+const cache = {}
+const setup = require('../../util/setup')
+const moderation = require('../../util/moderation')
+const index = require('../../index.js')
+//const commands = require("./commands");
+
+module.exports = {
+    commands: ['warn'],
+    expectedArgs: ['{user ping/user ID} [reason]'],
+    permissionError: ['you are missing the manage messages permissions'],
+    minArgs: 1,
+    maxArgs: null,
+    permissions: ['MANAGE_MESSAGES'],
+    requiredRoles: [],
+    description: "The bot will warn the mentioned user",
+    callback: async (message, args, text) => {
+        const guild = message.guild
+        let guildID = message.guild.id;
+        var warnedRoleID = null
+        warnedRoleID = await setup.getWarnedRoles(guildID)
+
+        warnedRoleID = warnedRoleID.toString()
+        var UserID = args[0]
+        var member = index.getMention(args[0], message)
+
+        var warnReason = args
+        warnReason.shift()
+        warnReason = warnReason.toString()
+        warnReason = warnReason.replace(/,/g, ' ')
+        if(!member) {
+            return message.reply('please specify the user that should be warned')
+        };
+
+        if (!warnReason) {
+            warnReason = 'no reason given'
+        };
+        var warnedRole = message.guild.roles.cache.get(warnedRoleID);
+        var warnedOneHighestRoleID = member.roles.highest.id;
+        var warningOneHighestRoleID = message.member.roles.highest.id;
+
+        if(!warnedRole) {
+            return message.reply('there is not a role set as the warned role, set it by doing &setwarnedrole (that requires manage server permissions)')
+        };
+
+        //let warnReason = args.join(" ").slice(18);
+        if(member.id === message.author.id) {
+            return message.reply('can not allow self-harm')
+        }
+        if (message.member.roles.highest.comparePositionTo(member.roles.highest) <= 0) { //warnedOneHighestRoleID === warningOneHighestRoleID
+            return message.reply('you can not warn a user with the same (or higher) permissions as you')
+        }
+        if(!message.member.permissions.has('MANAGE_MESSAGES')){
+            return message.reply(`you don't have manage messages permissions that are required to execute this command.`);
+        }
+
+        if (member.roles.cache.has(`${warnedRoleID}`)) {
+            const logEmbed = new Discord.MessageEmbed()
+            .setColor('#FF0000')
+            .setTitle(`An attempt to warn an already warned member happened`)
+            //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
+            .setDescription(`**Warned member:** <@${member.user.id}>\n**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
+            .setTimestamp()
+    
+            index.modLog(guildID, logEmbed)
+            message.reply('this user is already warned!')
+            return
+        };
+        console.log(warnedRole.editable)
+        if(!warnedRole.editable) {
+            message.reply(`failed to warn <@${member.id}> as the warned role is above my highest role. Try moving at least one of my roles above other ones`)
+            return
+        };
+        member.roles.add(warnedRoleID)
+        .then(memberAdded => {
+         message.reply(`you have succesfully warned <@${member.id}> with the reason **${warnReason}**`);
+        })
+        .catch(error => {
+        //console.log(error);
+            if(message.member.permissions.has('ADMINISTRATOR')){
+                message.reply('there is no role set as the warned role. Set it by doing `&setwarnedrole add {role ID}`')
+            } else message.reply('there is no role set as the warned role. Ask an admin to set it by doing `&setwarnedrole add {role ID}`')
+        });
+        const embed = new Discord.MessageEmbed()
+
+        .setColor('#FF0000')
+        .setTitle(`You hev been warned in ${message.guild.name}`)
+        //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
+        .setDescription(`**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
+        .setTimestamp()
+
+        member.user.send(embed).catch(error => {
+            message.channel.send(`Failed to DM <@${member.id}> the info about this action`)
+            console.log(error)
+        })
+
+        const logEmbed = new Discord.MessageEmbed()
+        .setColor('#FF0000')
+        .setTitle(`A member has been warned`)
+        //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
+        .setDescription(`**Warned member:** <@${member.user.id}>\n**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
+        .setTimestamp()
+
+        index.modLog(guildID, logEmbed)
+    }
+}
+
+

Is there a way to check if the role can be added to the user by a bot? Thanks in advance.

","

Role hiearchy isn't the sole factor in determining if a role is editable. For example, if your bot doesn't have the MANAGE_ROLES permission, then no matter how high your bot's highest role is, Role#editable will still return false.

+

What you want to do is first check if the GuildMember is manageable (via GuildMember#manageable). If they aren't, you can't really expect to be able to add roles to them. +Then, you want to check if your bot has the MANAGE_ROLES permission. +Lastly, you want to check if the position of the said "warn role" is higher than that of the bot's highest role.

+

The last 2 steps should be done internally by Role#editable (See https://github.com/discordjs/discord.js/blob/master/src/structures/Role.js#L128)

+

So what you could do is

+
if(!member.manageable || !warnedRole.editable) return console.log("Nope, cannot add role to that member")
+
",r +"How to compile/link ratfor code by gfortran compiler?

I've installed gfortran on my ubuntu 20x (amd-64) to learn programming from a very famous book, Software Tools by Kernighan & Plauger, and the language they used was ratfor so could you please tell me if it's possible to compile the example code (written in ratfor) on gfortran. If it's possible, what are the essential parameter/flags/switches for compiling and linking? +I've got a moderate knowledge on C but I never used fortran. I don't know how to build fortran code.

+

Thank you.

+

P.S Any reference to books/links will be appreciated.

","

You cannot compile Ratfor using gfortran. Ratfor is a different language, it is not Fortran. You have to find a preprocessor that translates Ratfor into Fortran or into some other language.

+

A quick google finds http://sepwww.stanford.edu/doku.php?id=sep:software:ratfor90 but there may be better things around and this site is not for software recommendations.

",r +"How to handle useState asynchronous in React hooks (in my case)

Here products state is null when I try to display the product. I know to handle this we can use useEffect again for displaying the product but still product state is null. Here is the part of the code that I tried to attempt.

+
function Product() {
+  const [products, setProducts] = useState(null);
+
+  useEffect(() => {
+    axios
+      .get("http://localhost:4000/products")
+      .then((res) => setProducts(res.data));
+  }, []);
+
+  useEffect(() => {
+   console.log(products); // Here still products is null
+    products.map((product) => (
+      <tr key={product.id}>
+        <td>{product.productName}</td>
+        <td>{product.productDesc}</td>
+        <td>{product.manufacturer}</td>
+        <td>{product.price}</td>
+        <td>{product.quantity}</td>
+      </tr>
+    ));
+  }, [products]);
+
+  return <></>;
+}
+
+

If I remove products.map then it is showing as two values first one is null and the second is an array of the object (i.e my data).

","

This is a typical example of lifting the state up to the higher-order component in React.js. +All states and API calls need to be written in your top-level-component.

+
import ProductItem from "./ProductItem";
+
+function Product(){
+  const [products, setProducts] = useState(null);
+
+  useEffect(() => {
+    axios
+      .get("http://localhost:4000/products")
+      .then((res) => setProducts(res.data));
+  }, []);
+
+return(
+     <table>
+       <thead>
+          <th>Name</th>
+          <th>Description</th>
+          <th>Manufacturer</th>
+          <th>Price</th>
+          <th>Qunatity</th>
+       </thead>
+       <tbody>
+          <ProductItem products={products} />
+       </thead>
+     </table>
+ );
+}
+
+

Here, the products state is passed as a prop to ProductItem. Now the ProductItem component will have the list of the product's item which can be accessed as a prop.

+
function ProductItem({products}) {
+
+  useEffect(() => {
+   console.log(products); // getting the list of the product in the developer console,
+  }, [products]);
+
+  return (
+    <>
+     {products.map((product) => (
+      <tr key={product.id}>
+        <td>{product.productName}</td>
+        <td>{product.productDesc}</td>
+        <td>{product.manufacturer}</td>
+        <td>{product.price}</td>
+        <td>{product.quantity}</td>
+      </tr>
+      ))}
+   </>;
+ );
+}
+export default ProductItem;
+
",r +"Entity Framework Core DbContext OnConfiguring does not exist anymore

It was a while ago i used Entity Framework Core so I don't know if they have simply deleted the virtual OnConfiguraing method in the DbContext class or assembly or what you call it. But I have search everywhere and their are no answer. +I have tried changing from V17 and V19 but its the same on both.

+

What I am trying to do: +Using Entity Framwork, i am trying the Code First Approach.
+The code below used to work.

+

(Taken from docs.microsoft) +using Microsoft.EntityFrameworkCore;

+
public class BloggingContext : DbContext
+{
+    public DbSet<Blog> Blogs { get; set; }
+    public DbSet<Post> Posts { get; set; }
+
+    protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder)
+    {
+        optionsBuilder.UseSqlServer(
+            @"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
+    }
+}
+
+public class Blog
+{
+    public int BlogId { get; set; }
+    public string Url { get; set; }
+    public int Rating { get; set; }
+    public List<Post> Posts { get; set; }
+}
+
+public class Post
+{
+    public int PostId { get; set; }
+    public string Title { get; set; }
+    public string Content { get; set; }
+
+    public int BlogId { get; set; }
+    public Blog Blog { get; set; }
+}
+
+

What I get +disappearance of onconfig

+

As you can see on the image, the OnConfiguring should be after Model property but its not there anymore.

+

Question: Does anybody know why OnConfiguring has disappeared from DbContext?

","

In the image you provide you are trying to override with the "public" modifier. The override for OnConfiguring is "protected".

+

Try writing "protected override" and intellisense should pick it up for you.

",r +"Can I use the same RecyclerView adapter for two different activities for two different data classes?

I have created a RecyclerView. I want to add another RecyclerView to another activity in my app which displays different layout and different data (uses different data class). can I do it with same adapter that I created? if yes, then please tell how? if by getItemViewType() then how to differentiate between two activities to set the respective view holder and how to add two data classes? please help. I am working in Kotlin, please give a kotlin example.

","

I would suggest you not to do so. From the maintance perspective, it would just make you code harder to understand and update later. Even if that means you need more code.

+

If you really want to do so, you could provide additional parameter to the adapter class - a Boolean for example, that will tell you which activity are you in right now and for which data it has to be prepared.
+And having that, you can just add an if condition in every place you need sth different depending on a data class youre using. And thats it.

",r +"Autodesk forge Webhook API, Error 400 400, VALIDATION_ERROR

using autodesk forge API, I am trying to create a webhook over folder using the following information; unfortunately, I am receiving the following response:

+
{
+   "id":"xxxx-xxxx-xxx-xxxxx",
+   "status":400,
+   "code":"VALIDATION_ERROR",
+   "detail":["Payload is not valid for serialization"]
+}
+
+

URL: +https://developer.api.autodesk.com/webhooks/v1/systems/data/events/dm.folder.added/hooks (for specific folder added event) or: https://developer.api.autodesk.com/webhooks/v1/systems/data/hooks (for all events). Both are returning the same error

+

Header:

+
{
+"Content-Type":"application/json",
+   "Authorization":"<MY_TOKEN>",
+   "x-ads-region":"US"
+}
+
+

Data:

+
{
+   "callbackUrl":"<MY_DOMAIN>:<MY_PORT>/callback",
+   "scope":{
+      "folder":"urn:adsk.wipprod:fs.folder:co.xxxxxxxxxxxx-xxxxx"
+   }
+}
+
+

Troubleshooting:

+
    +
  • I've tried different folders, root and non-root. I can access all the folders i tried using the api
  • +
  • I am sure that my account is US region
  • +
  • I've tried to add hubId and/or projectId, but I received the same error
  • +
  • <MY_DOMAIN>:<MY_PORT>/callback is configured and working fine
  • +
  • Headers and Data are serializing and de-serializing normally using json loads & dumps
  • +
+

Any suggestion/help?

","

Answering myself :)

+

I've discovered that my issue is not related to Forge API, it's a general one related to python Requests. The payload (data) of Requests cannot be nested dictionary, only 1 level dictionary is accepted, nested ones will fail. the solution is to stringify the dict (json.dumps) and use that string as request payload.

",r +"Prevent running an spring boot task which implements CommandLineRunner

I am writing a spring boot integration test using cucumber for a task (non web application) which implements CommandLineRunner. Due to default behavior of commandLineRunner, even after running the cucumber feature as junit, it runs the task first and then come backs to cucumber feature file. Instead I expect it not to run the task and control should come to feature file once the configuration is done.

+

How can I prevent CommandLineRunner from running its run method?

",

Add @Profile(“!profile_name”) annotation to the bean declaration and then set that profile when you need to exclude it

,r +Is there any Autocad mobile SDK to show and edit dwg files?

I'd like to show and edit dwg files in my iOS and Android app. Is there any Autocad mobile SDK to use? I didn't find in autocad website.

,"

From the Forge perspective, there is no native mobile component for manipulating DWG files. You could however achieve a "kind-of editing experience" by collecting a set of updates your user wants to apply to their DWGs, and then apply the updates in the cloud, leveraging the Forge Design Automation service for AutoCAD.

",r +"Struggling with Material UI styling solution

I want to be able to inject my own CSS into Material UI's components addition to their other built-in rules, but I'm not sure how I would set these parameters using the styled-components API. Is it even possible?

+

snippet

+
const Wrap = styled(Container)({
+    margin: 0,
+    padding: 0,
+    maxWidth: 'xl',
+});
+
","

You can use styled-components and material-ui together. But since you're using Material-UI, you can use its own styled API instead to better integrate with the Material-UI framework like injecting Material-UI customized theme easily when needed for example.

+
import { styled } from "@material-ui/core/styles";
+import { styled as muiStyled } from "@material-ui/core/styles";
+
+const MyButton1 = styled(Button)({
+  background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
+  border: 0,
+  borderRadius: 3,
+  boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
+  color: "white",
+  height: 48,
+  padding: "0 30px"
+});
+const MyButton2 = muiStyled(Button)((props) => ({
+  background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
+  border: 0,
+  borderRadius: 3,
+  boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
+  color: "white",
+  height: 48,
+  padding: props.theme.spacing(5)
+}));
+
+

Usage

+
<MyButton1>Styled with styled-components API</MyButton1>
+<MyButton2>Styled with MUI styled API</MyButton2>
+
+

Live Demo

+

",r +"Latency debug for websocket communication

I'm working on a debug latency problem of websocket.

+

I am trying to receive some price information from crypto-currency exchange with its websocket interface. The data packets we receive include the timestamp generatee on the exchange server. I log the time when we receive the tick information on our computer (the "client box") and compare the latency between the arrival time and the server generation time. Most of the ticks show a few tens of milliseconds which is more or less fine. But everyday we see a few times the latency becomes several seconds or even more then ten seconds and I would like to figure out where are these large latency come from.

+

The system is using Python programming language and the websocket module I'm using is websocket-client (https://pypi.org/project/websocket_client/, https://github.com/websocket-client/websocket-client), I tried to add logs inside the module and see if it is due to module processing time but still no luck.

+

One idea currently in my mind is to use tcpdump to capture the net traffic and record the time the tcp packet arrives my network card. If this time still presents the latency, I will have no way other than move the program to a co-located server. However, I encounters difficult here as the websocket connection is SSL-encrypted. Thus I cannot see the tick generation time packed inside the message.

+

Does anyone have some solution here ? In particular:

+
    +
  • Is there any way to retrieve the private key of SSL from the websocket-client python package from client-end? (I assume the key should be available somewhere local side, otherwise the websocket-client cannot decrypt the data itself. And WireShark should be able to decrypt the message for TSL1.2 protocol) +
      +
    • if it is not easy to do this with websocket-client package, I'm happy to try other websocket lib written by python, C/C++.
    • +
    +
  • +
  • Can tcpdump get the timestamp when the TCP data packet sent from server (even in server time)?
  • +
+

Any other advices are highly appreciated as well.

+

Thanks a lot!

+
+

Thanks @Eugène Adell +My tcpdump opened in WireShark is mostly like below + +and I can see the TSval in TCP Option - Timestamps + +Can these indicate something? +Sorry for probably basic questions, really lack of experience in this area & Thanks again.

","

EDIT

+
+

Can tcpdump get the timestamp when the TCP data packet sent from +server (even in server time)?

+
+

Open your capture and see if the packets have the TCP timestamps option (as defined in RFC 1323 but better explained in RFC 7323). If so, the very first SYN packet should already mention it.

+

Unluckily the meaning of the TSval (Timestamp value in milliseconds) given in these packets is not the real clock and is not always changing like a real clock (it depends on the implementation used by your computers). If the conversation with your server lasts for 60s for example, check if this TSval also moves from 60s, if so maybe can you use this field to track when the packets were sent.

",r +"copy input into buffer for CNN with tensorflow lite micro ESP32

When using tensorflow lite one a esp32, I use

+
loat input_data[3] = {value1, value2, value3};
+
+// Copy value to input buffer (tensor)
+for (size_t i = 0; i < 3; i++){
+    model_input->data.f[i] = input_data[i];
+    }
+
+

to copy the "feature values" to the input buffer. For applications with only 3 features per sample(like the setosa example), this is pretty straight forward.

+

How do pass the values for a CNN? My model input is

+
[1,80,3,1]
+
+

with

+

[noOfTimeSeries, noOfMeasurementsPerSensorPerTimeSeries, noOfSensors, anotherDimensionForTensorflow]

+

My features are so far stored in a struct, but I could put them into an array if necessary.

+

How would I pass values for CNN with images?

","

Although the tflite model has multidimensional input, you can fill your input buffer as if it were a 1D dimensional array in tflite for microcontrollers.

+

In your case,

+
size_t input_size = 1*80*3*1;
+
+for (size_t i = 0; i < input_size; i++){
+    model_input->data.f[i] = input_data[i];
+}
+
+

In your case, the flattened 1D array would look like

+
[Measurement1Sensor1, Measurement1Sensor2, Measurement1Sensor3, Measurement2Sensor1, ...]
+
+

Hopefully, you get the idea.

+

As side advice and for other readers, consider quantizing the model to int8 parameters or even int8 input and outputs. It will reduce the size and improve inference time considerably.

",r +"Problems with the ggcorr function to perform square correlation matrix

I am trying to make a square matrix in which the upper triangular part contains the numerical values of the correlation and the lower triangular part the corresponding colors using Pearson's method.

+
library(ggcorrplot)
+library(corrplot)
+dadosp=head(iris)[1:4]
+matcor <- round(cor(dadosp), 2)# matcor
+ggcorr(matcor,palette = "Greys", 
+       name = expression(rho),method=c("pairwise","pearson"),
+      max_size = 10,legend.position = " ",
+       min_size = 2,position="triangsuperior",
+       size = 3,
+       hjust = 0.75,
+       nbreaks = 6,
+       angle = -45)
+
+
+
+

However, the following error appears:

+
Erro: Can't find `position` called 'triangsuperior'
+Run `rlang::last_error()` to see where the error occurred.
+
+

The example in which I intend to reproduce would be in structural terms similar to the one below:

+

","

Try

+
corrplot.mixed(matcor)
+
+

Are you looking for this?

+

",r +"HTML-How to submit a form with sweetalert

somebody knows how to submit a form in html with sweetalert?

+

I have this checkbox and I want that onchange "direct" me to the sweetalert js with 2 Buttons. One with "No" and one with "Yes". The "Yes" button should now be the new "onchange" and with the "No" button the submit should be canceled.

+
<form method='post' action='....'>    
+<input type="checkbox" name="checkbox_admin" onchange="submit();" checked>
+</form>
+
+

Hope you know what I mean. :D

","

This is how I would normally do

+
$(document).ready(function() {
+    $('[data-click="swal-danger"]').click(function(e) {
+                e.preventDefault();
+                var form = $(this).parents('form');
+                swal({
+                  title: "Are You Sure?",
+                  text: "Are You Sure You Want To Delete.",
+                  icon: "error",
+                  buttons: true,
+                  dangerMode: true,
+                })
+                    .then((willDelete) => {
+                      if (willDelete) {                         
+                        swal(form.submit(), {
+                          icon: "success",
+                        });
+                      } else {
+                        
+                      }
+            });
+      });
+});
+
+

Use this while submitting the form via swal/Sweetalert

+
swal(form.submit()
+
+

Then create a form submit button but without the type submit as bellow

+
<form method='post' action='....'>    
+    <button class="btn btn-danger" data-click="swal-danger">DELETE USER</button>
+</form>
+
+

Make sure your button have this on your button data-click="swal-danger"

",r +".NET 5 Blazor Server App ObjectResult ""Accept"" header not being respected

I'm creating a controller in a .NET 5 Blazor Server App, and the OkObjectResult I'm returning from my controller is always returning JSON, even when I set Accepts: application/xml.

+

Due to getting the correct result inside my custom InvalidModelStateResponseFactory, I tend to think this might be a bug.

+

Startup.cs:

+
services
+    .AddControllers(options =>
+    {
+        options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
+    })
+    .ConfigureApiBehaviorOptions(options =>
+    {
+        options.InvalidModelStateResponseFactory = actionContext =>
+        {
+            KeyValuePair<string, ModelStateEntry> firstModelErrorPropertyName = actionContext.ModelState.First(s => s.Value.Errors.Count > 0);
+            ModelError firstError = firstModelErrorPropertyName.Value.Errors.First();
+            ObjectResult toReturn = new ObjectResult(new ErrorResponse
+            {
+                Status = RequestStatus.Fail,
+                ErrorCode = ErrorCode.MissingParameter,
+                ErrorDescription = $"Missing POST parameter: {firstModelErrorPropertyName.Key}: {"Description here"}"
+            });
+
+            toReturn.StatusCode = 200;
+
+            return toReturn;
+        };
+    })
+    .AddXmlSerializerFormatters()
+    .AddXmlDataContractSerializerFormatters()
+    .AddXmlOptions(options =>
+    {
+    })
+    .AddJsonOptions(options =>
+    {
+        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
+    });
+
+

Controller:

+
/// <summary>
+/// Enroll a member in IDCS services.
+/// </summary>
+/// <returns></returns>
+[HttpPost("enroll")]
+[Consumes("application/x-www-form-urlencoded")]
+[FormatFilter]
+public async Task<IActionResult> EnrollAsync(
+     [FromForm] EnrollRequest req)
+{
+    return Ok(new
+    {
+        content = "Enroll"
+    });
+}
+
","

I figured out the issue right after posting. If I return a defined object:

+
return Ok(new EnrollmentSuccessResponse
+    {
+        Content = "Enroll"
+    });
+
+

instead of an anonymous object

+
return Ok(new
+    {
+        content = "Enroll"
+    });
+
+

Everything works as expected.

",r +"Microsoft.TeamFoundation.Build.WebApi associate an artifact with a build before queuing it

I have two pipelines in Azure Devops. One generates an artifact and the other one runs tests on it. The pipeline that generates the artifact gets triggered whenever a PR is created. The pipeline that runs the tests is only triggered if certain checks are true.

+

I am trying to programmatically associate the artifact ID from the first pipeline with the second one but don't seem to find a way to do this. the SDK offers BuildHttpClientBase.CreateArtifactAsync() method but you must already have a build ID to do so. I am not sure how to get the ID, since queuing a build with BuildHttpClient.QueueBuildAsync() will fail without this artifact set first.

","

First of all, I think you have a misunderstanding about the BuildHttpClientBase.CreateArtifactAsync() method. This method should be used to create an artifact for a build, rather than assigning artifacts to another build. The method provided by the SDK can only trigger the pipeline, and cannot associate the artifact generated by one build pipeline with another build pipeline.

+

So to achieve this, we need to set the second build pipeline definition and add download pipeline artifact task to the second pipeline to download the artifact generated in the first pipeline.

+

For example:

+

1.Publishing artifacts in the first pipeline:

+
steps:
+- task: PublishPipelineArtifact@1
+  inputs:
+    targetPath: $(System.DefaultWorkingDirectory)/bin/WebApp
+    artifactName: WebApp
+
+

2.Downloading artifacts in the second pipeline:

+
steps:
+- task: DownloadPipelineArtifact@2
+  inputs:
+    artifact: WebApp
+
+

For details, please refer to this official document.

",r +"How I can POST an id to ASP.Net controller from view using AJAX?

I'm trying to POST an ID to the controller, but nothing is being sent. This I am doing from an Alert using Sweet Alert.

+

This is the code for the view:

+
@foreach (var item in Model)
+{
+   <div>
+       <a class="btn btn-danger py-2 my-1" onclick="Clickfn(@item.CertificadosID)" data-id="@item.CertificadosID">Eliminar</a>
+   </div>
+}
+
+<script>
+function Clickfn(id) {
+    swal({
+        title: "¿Estas seguro de que quieres eliminar esto?",
+        text: "La información se perdera hasta que vuelva a editarla",
+        icon: 'warning',
+        dangerMode: true,
+        buttons: [
+            { text: "Cancelar", visible: true, value: null, closeModal: true },
+            { text: "Eliminar", visible: true, value: true, closeModal: true }
+        ]
+    }).then((value) => {
+        if (value == true) {
+            $.ajax({
+                url: '/Certificados/Delete',
+                type: 'POST',
+                data: { "id": id }
+            });
+        }
+    });
+}
+</script>
+
+

And this is the code of the controller action:

+
    [HttpPost, ActionName("Delete")]
+    [ValidateAntiForgeryToken]
+    public async Task<IActionResult> DeleteConfirmed(int id)
+    {
+        var certificados = await _context.Certificados.FindAsync(id);
+        _context.Certificados.Remove(certificados);
+        await _context.SaveChangesAsync();
+        TempData["Mensaje"] = "Su certificado ha sido eliminado";
+        return RedirectToAction(nameof(Index));
+    }
+
","

Here is a demo to use ajax to post data to action with [ValidateAntiForgeryToken]:

+

View(You need to use <form method="post"></form> in view,so that you can have $('input[name="__RequestVerificationToken"]')):

+
<form method="post"></form>
+    <a class="btn btn-danger py-2 my-1" onclick="Clickfn(1)" data-id="1">Eliminar</a>
+@section scripts{ 
+
+<script>
+    function Clickfn(id) {
+        var token = $('input[name="__RequestVerificationToken"]').val();
+        $.ajax({
+            url: '/Certificados/Delete',
+            type: 'POST',
+            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
+            data: { "id": id }
+        });
+    }
+</script>
+}
+
+

Controller:

+
[HttpPost, ActionName("Delete")]
+        [ValidateAntiForgeryToken]
+        public async Task<IActionResult> DeleteConfirmed(int id)
+        {
+            return Ok();
+        }
+
+

result: +

",r +"How to read from the screen in flutter?

I am developing a flutter app that uses the camera to scan a barcode and shows it on the screen.

+

I added barcode_scan: ^1.0.0 to my dependencies and it works perfectly but I have a few questions:

+
    +
  1. Does flutter support reading from the screen? (like reading the barcode digits that I got on the screen)
  2. +
  3. do I need firebase to store a database of products to match the scanned barcodes with it or can I store the barcodes in the application? +I ultimately aim to read a barcode, look for the product and display some info about it This is the result I get after scanning a barcode
  4. +
","

For 1. The package you are using barcode_scan: ^1.0.0, provides a way to read barcode using your camera, To read barcode from camera, an example on how you can read the barcode

+
import 'package:barcode_scan/barcode_scan.dart';
+
+void main() async {
+  var result = await BarcodeScanner.scan();
+  
+  print(result.type); // The result type (barcode, cancelled, failed)
+  print(result.rawContent); // The barcode content
+  print(result.format); // The barcode format (as enum)
+  print(result.formatNote); // If a unknown format was scanned this field contains a note
+}
+
+

if you wants to read from images in your images folder/gallery, you have to create the code to load those image qr_code_tools package can help you to read those, an example

+
String _data = '';
+
+  void _getQrByGallery() {
+    Observable<File>.fromFuture(
+            ImagePicker.pickImage(source: ImageSource.gallery))
+        .flatMap((File file) {
+      return Observable<String>.fromFuture(
+        QrCodeToolsPlugin.decodeFrom(file.path),
+      );
+    }).listen((String data) {
+      setState(() {
+        _data = data;
+      });
+    }).onError((dynamic error, dynamic stackTrace) {
+      setState(() {
+        _data = '';
+      });
+    });
+  }
+
+

For 2. You can save anywhere, but if you are calling from an API and are updating products info than store database remotely.

",r +"How do I add a smooth slide from left to right effect with CSS and Javascript on my side nav?

I am trying to make a CSS and JavaScript side-nav. Here is the code I have so far:

+

+
+
var nav = document.getElementById('nav');
+function show(){
+nav.style.display = ""block"";
+}
+
.side-nav{
+background-color:black;
+height:100%;
+width:250px;
+position: absolute;
+display:none;
+}
+#myLink{
+
+color:gray;
+text-decoration: none;
+display:block;
+margin-left:15px;
+margin-bottom:10px;
+font-size:25px;
+transition: .5s;
+font-family: 'Marck Script', cursive;
+margin-top:10px;
+
+}
+#myLink:hover{
+  color:white;
+}
+
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset=""utf-8"">
+    <meta name=""viewport"" content=""width=device-width"">
+    <title>repl.it</title>
+    <link href=""style.css"" rel=""stylesheet"" type=""text/css"" />
+    <link href=""https://fonts.googleapis.com/css2?family=Marck+Script&display=swap"" rel=""stylesheet"">
+  </head>
+  <body>
+    <div class = ""side-nav"" id = ""nav"">
+<div id = ""myLinks"">
+
+<a href = ""#"" id = ""myLink"">Home</a>
+<a href = ""#"" id = ""myLink"">Contact</a>
+<a href = ""#"" id = ""myLink"">Blog</a>
+<a href = ""#"" id = ""myLink"">Products</a>
+
+</div>
+
+
+
+    </div>
+    <a href = ""#"" onclick = ""show();"">Show nav</a>
+    <script src=""script.js""></script>
+    
+  </body>
+</html>
+
+
+

+

How do I achieve a smooth slide from left to right with the side nav? Do I still need to use JavaScript? Or is there some way to do that with just CSS? Thanks in advance!!!

","

If you want to use jQuery you would need something like this. I've also added the close button.

+

+
+
$( '.show-nav' ).click( function() {
+  $( '#nav' ).animate( {width: 'toggle'} );
+} );
+
.side-nav{
+  background-color:black;
+  height:100%;
+  width:250px;
+  position: absolute;
+  display: none;
+}
+
+#myLink{
+  color:gray;
+  text-decoration: none;
+  display:block;
+  margin-left:15px;
+  margin-bottom:10px;
+  font-size:25px;
+  transition: .5s;
+  font-family: 'Marck Script', cursive;
+  margin-top:10px;
+}
+
+#myLink:hover{
+  color:white;
+}
+
+#nav .show-nav {
+  position: absolute;
+  top: 0;
+  right: 0;
+  padding: 10px;
+  color: white;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset=""utf-8"">
+    <meta name=""viewport"" content=""width=device-width"">
+    <title>repl.it</title>
+    <link href=""style.css"" rel=""stylesheet"" type=""text/css"" />
+    <link href=""https://fonts.googleapis.com/css2?family=Marck+Script&display=swap"" rel=""stylesheet"">
+  </head>
+  <body>
+    <div class = ""side-nav"" id = ""nav"">
+      <div id = ""myLinks"">
+
+      <a href = ""#"" id = ""myLink"">Home</a>
+      <a href = ""#"" id = ""myLink"">Contact</a>
+      <a href = ""#"" id = ""myLink"">Blog</a>
+      <a href = ""#"" id = ""myLink"">Products</a>
+      <a class=""show-nav"" href = ""#"">Close</a>
+      </div>
+    </div>
+    
+    <a class=""show-nav"" href = ""#"">Show nav</a>
+    <script src=""script.js""></script>
+    
+  </body>
+</html>
+
+
+

",r +"Mat tab last child - only affect one group and not all other groups in component?

I ran into this example when looking to solve an issue with making the last tab move to the right of the group - which is what I need.

+

Here's an example: StackBlitz

+

I've tried adding a class and trying the following... but I can't get the style to change for only one group.

+
.my-class .mat-tab-label:last-child {
+  margin-left: auto;
+}
+
+

How can I only make the css effect a specific of my groups?

","

You could do the selecting of the correct group/row with adding the .mat-tab-group class to your selector and combine it with a :nth-child, :first-child, etc. It depends on which group/row you want to select. Here are two examples:

+

This will only adjust the styling of the first group:

+
.mat-tab-group:first-child .mat-tab-label:last-child {
+  margin-left: auto;
+}
+
+

The example below will target only the last label within the second group/row. To target a specific group/row you could change the nth-child number to anything you want:

+
.mat-tab-group:nth-child(2) .mat-tab-label:last-child {
+  margin-left: auto;
+}
+
",r +"Athena Query JSON Fields Stored as String

I have an Athena table which has a field

+
fields (string)
+
+

The data looks like

+
{"field_1":"value_1","field_2":"value_2"}
+{"field_1":"value_3","field_2":"value_4"}
+...
+
+

I would like to query such as:

+
select "fields"."field_1" as field_1 from table_name where field_1 = "something"
+
+

I have tried many methods and only either gotten an error or only empty values for field_1. Any help would be greatly appreciated.

","

Based on the sample data it looks like fields is a JSON. So the first thing I would do is to use json_parse to convert it.

+

The syntax "fields"."field_1" would work for a row column - however, it looks like it's not possible to cast a json to a row in Athena (which is based on Presto 0.172) - see Cast from JSON in the 0.172 Presto Release Documentation.

+

You may convert it to a map<varchar,varchar> and then access it via Subscript Operator: []

+

Example:

+
with example as
+(
+    SELECT * FROM (
+    VALUES
+        ('{"field_1":"value_1","field_2":"value_2"}'),
+        ('{"field_1":"value_3","field_2":"value_4"}')
+    ) AS t (fields)
+)
+,example_cast as
+(
+    select *
+    ,cast(json_parse(fields) AS map<varchar,varchar>) fields_parsed
+    from example 
+)
+select *
+,fields_parsed['field_1'] fields_field_1
+from example_cast;
+
",r +"How to add empty space between the elements when I use $('body').text()?

if I create for example a page with the following content:

+
<body>
+<p>
+ABC DEF<p>GHI</p>
+JKL<br>MNO
+</p>
+</body>
+
+

Then I get in the browser:

+
ABC DEF
+
+GHI
+
+JKL
+MNO
+
+

But when I now use $('body').text() then I get back:

+
ABC DEFGHI
+JKLMNO
+
+

Is it possible to add an empty space between the elements? So that 'DEFGHI' and 'JKLMNO' are actually two words instead of one?

+

Here the link to a jsfiddle example.

","

Use html() instead of text() and then replace br and p tags with spaces.

+
var text = $('body').html();
+var str = text.replace( /<br\s*[\/]?>/gi, '\r\n'); // <br> to newline
+var str2 = str.replace(/<\/?p[^>]*>/g, '\r\n'); // <p> to newline
+var str3 = str2.replace(/  +/g, ' '); // multiple spaces to one
+
+console.log(str3)
+
+

Resulting exactly the same structure as the HTML, but in text

+
ABC DEF
+
+GHI
+
+JKL
+MNO
+
+

if you'll replace to empty space ' ' instead of '\r\n' you'll get:

+
ABC DEF GHI 
+JKL MNO
+
+",r +"Combinations to match FX trades
   Buy Currency Sell Currency Buy Amount Sell Amount
+1. CHF          USD           50000      61000
+2. USD          CHF           20999      20000     
+3. USD          CHF           34000      30000
+4. CHF          AUD           400        356
+5. AUD          CHF           378        400
+6. USD          CHF           34000      30000
+
+

Hi, I am trying to solve a problem of matching FX trades. As seen above, the first line buy CHF 50000, can be reconciled by combining 2nd and 3rd, or 2nd and 6th trade. Trade 4 can be reconciled with trade 5. Hope you guys get the idea.

+

What I've worked out so far:

+
    +
  • try to take the unique currencies in buy column and check if they are present in sell column. [i for i in df['Buy Currency'].unique() if i in df['Sell Currency'].unique()]
  • +
  • check if Buy only has 1 type of currency. if true, continue to next loop. assert len(set(df['Buy Currency'])) != 1
  • +
  • check for exact match in Buy Amt and Sell Amt. In this case, 400 appears in both columns thus can be easily found. +[amt for amt in df['Buy Amount'].astype(int).tolist() if amt in df['Sell Amount'].astype(int).tolist()]
  • +
+

The part where I'm stuck is matching 1 buy trade with more than 1 sell trade. In addition, there can be more than 1 way of doing so, as illustrated in the first trade. Also tried using itertools.combinations as seen in +Find all combinations of a list of numbers with a given sum, but I won't be able to verify if the combinations are same FX pairs.

+

Any help is greatly appreciated!

","

you can groupby and merge the dataframe with itself on Buy ccy with the Sell ccy.

+

If you want exact match (i.e. and not greater) you can use the following snippet:

+
from itertools import chain, combinations
+
+
+def match(row):
+    res1 = []
+    res2 = []
+    def all_subsets(ss):
+        return chain(*map(lambda x: combinations(ss, x), range(0, len(ss) + 1)))
+    for subset in all_subsets(row[0]):
+        res1.append(sum(subset))
+    for subset in all_subsets(row[1]):
+        res2.append(sum(subset))
+    common = set(res1) & set(res2)
+    return common
+    
+
+df_buy = df.groupby('Buy Currency')['Buy Amount'].unique().reset_index()
+df_sell = df.groupby('Sell Currency')['Sell Amount'].unique().reset_index()
+results = df_buy.merge(df_sell, left_on='Buy Currency', right_on='Sell Currency', how='outer')
+results['match'] = results[[u'Buy Amount', u'Sell Amount']].apply(match, axis=1)
+
+

The output will be:

+
Buy Currency      Buy Amount Sell Currency          Sell Amount  \
+0          AUD           [378]           AUD                [356]   
+1          CHF    [50000, 400]           CHF  [20000, 30000, 400]   
+2          USD  [20999, 34000]           USD              [61000]   
+                    match  
+0                     {0}  
+1  {0, 50000, 400, 50400}  
+2                     {0} 
+
+

Where match column will give you the possible exact matches, 0 means there is no exact match.

",r +"Two adapters for one recycler view

I have a bit of a dilemma. I'll try to explain it as simply as I can.

+

My app has a page where I show a feed of posts through a recycler view (represented by the blue rectangles):

+

+

This is simple enough, as I've created a PostAdapter class for the recycler view where I handle all the child view logic.

+

Now I have another requirement where I need a page that shows a post (blue rectangle) at the top of the recycler view, and then the replies to that post below it (represented by the red rectangles):

+

+

Please remember that the blue and red rectangles are simplifications. Each of these views has dozens of child views and hundreds of lines of code of logic each.

+

I've created another class, ReplyAdapter, for the recycler view on this page, which handles all the logic for the replies.

+

My problem now becomes: how can I also show the post (blue rectangle) at the top of the recycler view?

+

I know that I can modify ReplyAdapter to allow for multiple types (as explained here), but because these are already two separate classes, each with their own complex logic, that's not really a possibility for me.

+

So my question is: is there a way to keep the logic of the two adapters separate while still being able to use both under the same recycler view? If so, how? If no, what should I do?

","

If your use case is exactly this - data from PostAdapter on top, data from ReplyAdapter below - then androidx.recyclerview.widget.ConcatAdapter may help. As its name implies, it concatenates adapters.

",r +"How to remove Dynamics 365 finance & operation metadata from odata call?

I try to get data from OData. +The link is as below.

+
https://*********.cloudax.dynamics.com/data/PurchaseOrderHeadersV2?$select=PurchaseOrderNumber,RequestedDeliveryDate,DeliveryAddressDescription&$filter=OrderVendorAccountNumber%20eq%20%27100001%27
+
+

I only add 3 fields to the select clause. But the "@odata.etag" field has added to the response. The response is as below.

+
{
+  "@odata.context":"https://****.cloudax.dynamics.com/data/$metadata#PurchaseOrderHeadersV2(PurchaseOrderNumber,RequestedDeliveryDate,DeliveryAddressDescription)","value":[
+    {
+      "@odata.etag":"W/\"JzE5MDYyOTE2NzcsNTYzNzMwMzU3NjswLDA7MSw1NjM3MTYzMzI2OzAsMDswLDAn\"","PurchaseOrderNumber":"PO00003871","RequestedDeliveryDate":"2020-10-07T12:00:00Z","DeliveryAddressDescription":"******"
+    },{
+      "@odata.etag":"W/\"JzE5NjkzNDMzOTUsNTYzNzMwMzU3NzswLDA7MSw1NjM3MTYzMzI2OzAsMDswLDAn\"","PurchaseOrderNumber":"PO00003872","RequestedDeliveryDate":"2020-09-16T12:00:00Z","DeliveryAddressDescription":"*******"
+    },{
+      "@odata.etag":"W/\"JzIwNzgyNTg4OSw1NjM3MzAzNTc4OzAsMDsxLDU2MzcxNjMzMjY7MCwwOzAsMCc=\"","PurchaseOrderNumber":"PO00003873","RequestedDeliveryDate":"2020-10-08T12:00:00Z","DeliveryAddressDescription":"*****"
+    },{
+      "@odata.etag":"W/\"JzE3MjYzMjQ0NzUsNTYzNzMwMzU3OTswLDA7MSw1NjM3MTYzMzI2OzAsMDswLDAn\"","PurchaseOrderNumber":"PO00003874","RequestedDeliveryDate":"2020-10-08T12:00:00Z","DeliveryAddressDescription":"**********"
+    },{
+      "@odata.etag":"W/\"JzEsNTYzNzMwNDMyNjswLDA7MSw1NjM3MTYzMzI2OzAsMDswLDAn\"","PurchaseOrderNumber":"PO00003881","RequestedDeliveryDate":"2020-10-09T12:00:00Z","DeliveryAddressDescription":"*********"
+    }
+  ]
+} 
+
+

How can I remove this metadata information from response?

","

You can try these headers, which will eliminate metadata from response.

+
Content-Type: application/json; odata.metadata=minimal
+
+

In fact you can mention odata.metadata=none for further

+
apiurl?$format=application/json;odata.metadata=none
+
",r +"Remapping dataframe values with dictionary key/value

I have a dictionary of simulated team scores:

+
{'t1': 83,
+ 't2': 82,
+ 't3': 66,
+ 't4': 74}
+
+

And a dataframe of matchups:

+
team_home  score_home  team_away  score_away
+t1         0           t2         0
+t3         0           t4         0
+
+

I want to remap the scores in the dataframe with the corresponding team's score in the dictionary. The final output should look like this:

+
team_home  score_home  team_away  score_away
+t1         83           t2        82
+t3         66           t4        74
+
","

Let's filter the team like columns then stack to reshape and map the values from dct then use unstack and assign the result to the corresponding score like columns:

+
c = df.filter(like='team').columns
+df['score' + c.str.lstrip('team')] = df[c].stack().map(dct).unstack()
+
+
+
  team_home  score_home team_away  score_away
+0        t1          83        t2          82
+1        t3          66        t4          74
+
",r +"Move each bigram from a list format to a new row in Pandas or Pyspark dataframes

I have pandas and pyspark dataframes with lists of bigrams per row per day basis. I want to break the lists and move each bigram to a single row with counts in descending order.

+

As shown below is the dataframe I have. I have sorted by the event_dt. In the column 'merged', the list of bigrams are shown. For example, 'nice meet' and 'meet postpaid' are two bigrams. The list of bigrams continues for each day...

+

+

Now I want to move each biagram to a new row for the same date. For example, 'nice meet' will be in a row and 'meet postpaid' will go on another row, while the event_dt columns shows the same date. I also want the counts of bigrams in descending order, and also want to get top 10 or top 20 counts bigrams for each date. +Here I want it to look like,

+

+

As you can see each bigram comes in a row with counts with the same date. The first row shows the bigram 'customer care' because this bigram is happening down the line 20 times which the pyspark/pandas is calculating (which I need help!) +Appreciate the help in advance!

","

I think you need something like this:

+
from pyspark.sql.functions import explode
+
+df_res = (df
+         .select('event_dt', explode('merged').alias('bigram'))
+         .groupBy('event_dt', 'bigram')
+         .count()
+         )
+df_res.show()
+
+

Notice that with this code if you have, let's say, "customer care" in 2 different days, my version will count them separately and you'll find a row for each day it appeared.

+

UPDATE

+

If you want to see the top n from each group, you should do as follows:

+
from pyspark.sql.functions as f
+from pyspark.sql.window import Window
+
+n = 10
+win = Window.partitionBy('event_dt').orderBy(f.desc('count'))
+
+(df_res
+ .withColumn('rank', f.row_number().over(win))
+ .filter('rank<=' + str(n))
+ .show()
+)
+
",r +"Machine Learning Classifier use past predictions as features

I want to built a binary classifier machine learning model. +I want to use the model's previous predictions as features for the future predictions, to take into account that my training samples are not independent.

+

Is there a framework to achieve this with scikit-learn, or any other python ML library?

+

I know this problem could be solved with memory-based Neural Networks architectures, like RNNs, LSTMs, ..., but I would want to consider non deep learning approaches first (typically with gradient boosting models, tree based models, ...)

","

There are several statistical models which you can use for predicting the future based on the past without using deep learning; in other words, for time series forecasting.

+

For example, you could use ARIMA/SARIMA/SARIMAX or VAR, which are statistical models which can be used for prediction.

+

You can consult the following links as starting points:

+
    +
  1. https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/
  2. +
  3. https://www.machinelearningplus.com/time-series/vector-autoregression-examples-python/
  4. +
+

Also, do not forget to delve deep into the statsmodel python library.

",r +"Why return null in while loop R

I wanted to store the result in a vector if it satisfy the if statement, but the return value is always null. How can I make it to return the value of the loop?

+
url <- "http://stat.ethz.ch/Teaching/Datasets/WBL/legierung.dat" 
+data <- read.table(url, header = TRUE)
+breaking = data[,4]
+c = mean(breaking)
+b  = 1
+p = data
+oo <- c()
+var = function(){
+  if(a > c){
+    oo<-c(oo,"High")
+  }else{
+    oo = c(oo,"Low")
+  }
+  return(oo)
+} 
+
+count = 0
+while(count <=length(p[,4])){
+  a = p[(b),4]
+  b = b+1
+  var()
+  count = count+1 
+}
+
","

You are doing this in a very complicated way.

+

As far as I could read your code I think you want 'High' for values which are greater than mean of Breaking column and 'Low' otherwise. You can do this with ifelse statement.

+
mean_breaking <- mean(p$breaking)
+p$new_col <- ifelse(p$breaking > mean_breaking, 'High', 'Low')
+
+

The same can be done without ifelse as well :

+
p$new_col <- c('Low', 'High')[(p$breaking > c) + 1]
+
",r +"UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function

I am using Socket.io for real time image upload process but I got this error mentioned below. I'm writing socket and app.js logics in different files by referring this answer now i want to emit that socket events in controller files but got the error

+
UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
+
+

below is my code

+

app.js

+
 // modules =================================================
+ var express = require('express');
+ var app = express();
+ const logger = require('morgan');
+ var bodyParser = require('body-parser');
+ const indexRouter = require("./routes/index");
+ const cors = require('cors');
+ const path = require("path");
+ const config = require("./environments/index");
+ var http = require('http').Server(app);
+ var sockets = require('./apis/socket.io');
+ // configuration ===========================================
+ var port = config.PORT || 8081; // set our port
+
+ sockets.getSocketIo(http);
+
+ app.use(bodyParser.json({ limit: '50mb' }));
+
+ app.use(bodyParser.urlencoded({
+    limit: '50mb',
+    extended: true,
+    parameterLimit: 50000
+ }));
+ app.use(cors());
+ app.use(logger('dev'))
+ app.use("/api", indexRouter);
+
+ app.use(express.static(path.join(__dirname, "/build")));
+
+ app.get('/', function (req, res) {
+    res.sendFile(__dirname + '/index.html');
+ });
+
+  http.listen(port, () => {
+      console.log('Magic happens on port ' + port); // shoutout to the user
+  });
+
+ exports = module.exports = app;
+
+

This is socket.io.js file code

+
 var socketio = require('socket.io');
+ var io = {};
+
+ module.exports = {
+
+getSocketIo: function (app) {
+
+    let userId = 1
+
+    io = socketio.listen(app);
+    io.sockets.on('connection', function (socket) {
+        console.log("new connection: " + socket.id);
+
+        console.log(socket)
+
+
+        console.log('socket connected')
+
+        // let rooms = socket.id
+
+
+        io.sockets.adapter.rooms
+        if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + 
+  userId].length > 0) userId++;
+        socket.join("room-" + userId);
+
+        //Send this event to everyone in the room.
+        io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
+        io.sockets.in(userId).emit('Image_upload', "Image uploading is started");
+        console.log(socket.room)
+        console.log(socket)
+    });
+}
+};
+
+

This is controller code of api controller

+
 report_data: async (req, res) => {
+    if (!req.body.id) {
+        logger.warn(error.MANDATORY_FIELDS);
+        return res.status(500).send(error.MANDATORY_FIELDS)
+    }
+    io.emit('progress', "Image is Uploading started Please Wait A minute");
+    io.emit('error', "clients connected!");
+
+    let Id = req.body.id;
+    let path = `tmp/daily_gasoline_report/${Id}`;
+
+    req.body.data_url = path
+    sequelize.sequelize.transaction(async (t1) => {
+        let result = error.OK
+        result.data = data
+
+        logger.info(result);
+        return res.status(200).send(result)
+    }).catch(function (err) {
+        logger.warn(err);
+        console.log(err)
+        return res.status(500).send(error.SERVER_ERROR)
+    })
+},
+
","

You can Make changes like below in your file

+

app.js

+
// modules =================================================
+var express = require('express');
+var app = express();
+const logger = require('morgan');
+var bodyParser = require('body-parser');
+const cors = require('cors');
+const path = require("path");
+const config = require("./environments/index");
+var http = require('http').Server(app);
+var io = require('socket.io').listen(http);
+const indexRouter = require("./routes/index");
+
+// configuration ===========================================
+var port = config.PORT || 8081; // set our port
+
+app.use(bodyParser.json({ limit: '50mb' }));
+
+app.use(bodyParser.urlencoded({
+    limit: '50mb',
+    extended: true,
+    parameterLimit: 50000
+}));
+app.use(cors());
+app.use(logger('dev'))
+app.use("/api", indexRouter);
+
+app.use(express.static(path.join(__dirname, "/build")));
+
+app.get('/', function (req, res) {
+    res.sendFile(__dirname + '/index.html');
+});
+
+http.listen(port, () => {
+    console.log('Magic happens on port ' + port); // shoutout to the user
+});
+
+app.locals.io = io
+
+exports = module.exports = app;
+
+

socket.io.js

+
let io;
+
+const getSocketIo = (http) => {
+    let userId = 1
+
+    io = require('socket.io')(http);
+    io.sockets.on('connection', function (socket) {
+
+        io.sockets.adapter.rooms
+        if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
+        socket.join("room-" + userId);
+
+        //Send this event to everyone in the room.
+        io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
+        console.log("new connection: " + socket.id);
+        console.log('socket connected')
+    });
+}
+
+module.exports = {
+    getSocketIo,
+    io
+};
+
+

in your controllers add this code in api you have mentioned whenever you want to use socket add this code before using it

+

const io = req.app.locals.io;

",r +"EMFILE: Too many files open

I'm trying to set up an api on azure's web app service using bottle + anaconda packages.

+

I can't simply use a copy of the site-packages folder because numpy is involved. Instead, in addition to the site-packages folder I must also give numpy access to the mkl binaries. So I copy the Anaconda\envs\{ENV_NAME}\Library\bin folder into the app and add it to %PATH%. That folder has less than 200 files in it, so I'm surprised seeing the following error during the deployment:

+
 2020-10-29T04:34:21.3218237Z ##[error]Error: EMFILE: too many open files, open 'D:\a\_temp\temp_web_package_058969368946595324\site-packages\statsmodels\tsa\arima\datasets\__init__.py'
+
+

Everything builds and runs as long as I don't include the bin folder to %PATH%

+

No, I'm not close to my file size limit on the azure web app service. Has anyone run into this before?

","

This error happens because of the XDT Transform.

+

During an XDT Transform, all contents of the original package are transformed and then zipped up. This error is thrown if the deployment is significantly large.

",r +"typescript express failed to export and show undefined when running by nodeJS through required require('./main.ts')

My problem is difficult to explain, so i simply the code. let me post the code first

+

main.ts

+
import express from 'express';
+let a = 1 
+console.log ('a in main.ts', a)
+export let b = a 
+const app = express()
+let PORT = 8080
+import {c} from "./efg"
+console.log("export from efg.ts", c)
+app.listen(PORT, () => {
+    console.log(`Server runs at ${PORT}`);
+  });
+
+

efg.ts

+
import {b} from './main'
+console.log('export from main.ts', b) 
+export let c = 'efg'
+
+

main.js

+
require('ts-node/register')
+require('./main.ts')
+
+

when i run the code with ts-node main.ts, everything is fine, it prints out

+
a in main.ts 1
+export from main.ts 1
+export from efg.ts efg
+Server runs at 8080
+
+

but when i run the code with node main.js , strange things happen

+
a in main.ts 1
+export from main.ts undefined <---- main.ts export become undefined
+export from efg.ts efg
+Server runs at 8080
+
+

the strange thing is if I rename main.js to other names like run.js, it works normally +Can anyone tell me why this happens? I don't understand why when i use the name main.js the export from main.ts become undefined

","

You should not have a main.js importing your main.ts file but instead have a tsconfig.json file at the root of your project and then compile using tsc, you will then be able to enter the following command node main.js.

",r +"How to restructure the output tensor of a cnn layer for use by a linear layer in a simple pytorch model

Given a pytorch input dataset with dimensions:

+
dat.shape = torch.Size([128, 3, 64, 64])
+
+

+

This is a supervised learning problem: we have a separate labels.txt file containing one of C classes for each input observation. The value of C is calculated by the number of distinct values in the labeles file and is presently in the single digits.

+

I could use assistance on how to mesh the layers of a simple mix of convolutional and linear layers network that is performing multiclass classification. The intent is to pass through:

+
    +
  • two cnn layers with maxpooling after each
  • +
  • a linear "readout" layer
  • +
  • softmax activation before the output/labels
  • +
+

Here is the core of my (faulty/broken) network. I am unable to determine the proper size/shape required of:

+
 Output of Convolutional layer -> Input of Linear [Readout] layer
+
+
class CNNClassifier(torch.nn.Module):
+
+    def __init__(self):
+        super().__init__()
+        self.conv1 = nn.Conv2d(3, 16, 3)
+        self.maxpool = nn.MaxPool2d(kernel_size=3,padding=1)
+        self.conv2 = nn.Conv2d(16, 32, 3)
+        self.linear1 = nn.Linear(32*16*16, C)
+        self.softmax1 = nn.LogSoftmax(dim=1)
+
+    def forward(self, x):
+        x = self.conv1(x)
+        x = self.maxpool(F.leaky_relu(x))
+        x = self.conv2(x)
+        x = self.maxpool(F.leaky_relu(x))
+        x = self.linear1(x)  # Size mismatch error HERE 
+        x = self.softmax1(x)
+        return x
+
+

Training of the model is started by :

+
        Xout = model(dat)
+
+

This results in :

+
+

RuntimeError: size mismatch, m1: [128 x 1568], m2: [8192 x 6]

+
+

at the linear1 input. What is needed here ? Note I have seen uses of wildcard input sizes e.g via a view:

+
    ..
+    x = x.view(x.size(0), -1)
+    x = self.linear1(x)  # Size mismatch error HERE 
+
+

If that is included then the error changes to

+
+

RuntimeError: size mismatch, m1: [28672 x 7], m2: [8192 x 6]

+
+

Some pointers on how to think about and calculate the cnn layer / linear layer input/output sizes would be much appreciated.

","

The error

+

You have miscalculated the output size from convolutional stack. It is actually [batch, 32, 7, 7] instead of [batch, 32, 16, 16].

+

You have to use reshape (or view) as output from Conv2d has 4 dimensions ([batch, channels, width, height]), while input to nn.Linear is required to have 2 dimensions ([batch, features]).

+

Use this for nn.Linear:

+
self.linear1 = nn.Linear(32 * 7 * 7, C)
+
+

And this in forward:

+
x = self.linear1(x.view(x.shape[0], -1))
+
+

Other possibilities

+

Current new architectures use pooling across channels (usually called global pooling). In PyTorch there is an torch.nn.AdaptiveAvgPool2d (or Max pooling). Using this approach allows you to have variable size of height and width of your input image as only one value per channel is used as input to nn.Linear. This is how it looks:

+
class CNNClassifier(torch.nn.Module):
+    def __init__(self, C=10):
+        super().__init__()
+        self.conv1 = nn.Conv2d(3, 16, 3)
+        self.maxpool = nn.MaxPool2d(kernel_size=3, padding=1)
+        self.conv2 = nn.Conv2d(16, 32, 3)
+        self.pooling = torch.nn.AdaptiveAvgPool2d(output_size=1)
+        self.linear1 = nn.Linear(32, C)
+        self.softmax1 = nn.LogSoftmax(dim=1)
+
+    def forward(self, x):
+        x = self.conv1(x)
+        x = self.maxpool(F.leaky_relu(x))
+        x = self.conv2(x)
+        x = self.maxpool(F.leaky_relu(x))
+        x = self.linear1(self.pooling(x).view(x.shape[0], -1))
+        x = self.softmax1(x)
+        return x
+
+

So now images of torch.Size([128, 3, 64, 64]) and torch.Size([128, 3, 128, 128]) can be passed to the network.

",r +"Add redirection with regular expression on WordPress Site from .htaccess file

I want to add redirection on the WordPress site from the .htaccess file

+

Current URL:

+
example.com/papaya-exfoliator/?uf
+
+

It will be redirected to

+
example.com/produit/papaya-exfoliator/
+
+

Currently, the "All In One Redirection" plugin is installed and it's working fine without regular expression.

+

Like if I hit example.com/papaya-exfoliator then it will redirect to example.com/produit/papaya-exfoliator/ but if there are any extra data in the URL like /?uf then the redirection is not working.

","

You could do something like the following at the top of your .htaccess file to redirect from /papaya-exfoliator/?uf to /produit/papaya-exfoliator/

+
RewriteEngine On
+
+RewriteCond %{QUERY_STRING} ^uf$
+RewriteRule ^(papaya-exfoliator)/?$ /produit/$1/ [QSD,R=302,L]
+
+

Note that the RewriteRule pattern (ie. ^(papaya-exfoliator)/?$) matches against the URL-path only. You need to use an additional condition (ie. RewriteCond directive) to match against the query string (ie. uf).

+

I've made the trailing slash on the source URL optional since you used both versions (with and without the trailing slash) in your question.

+

The QSD flag is necessary in order to remove the query string from the target URL (otherwise it is copied by default). The QSD flag requires Apache 2.4. If you are still on Apache 2.2 then you will need to append a ? to the end of the substitution string instead (to essentially append an empty query string). eg. /produit/$1/?.

+

The $1 backreference simply saves repetition by capturing papaya-exfoliator from the requested URL.

+
+

If you wish to redirect regardless of whether the query string is present or not then simply remove the RewriteCond directive. This then makes the rule in the WP plugin superfluous.

+
+

If you wish to redirect only when a query string is present (any query string) then change the RewriteCond directive to read:

+
RewriteCond %{QUERY_STRING} .
+
+

ie. It matches 1 character in the query string, so there is a query string on the requested URL.

",r +"Django: How to filter model objects after passing through functions?

I have a model called Service, which has a field url of type str. I have a function f that returns the hostname of an url:

+
def f(url):
+    return urllib.parse.urlparse(url).hostname
+
+

I want to get all the objects whose f(url) equals a value target.

+

One way to achieve this would be by doing the following:

+
[x for x in Service.objects.all() if(f(x.url) == target)]
+
+

But in that case, I'll get a list, not a QuerySet.

+

Is there a way to filter the objects and get a QuerySet satisfying the above criteria?

","

Can you try sthg like this instead of looping through, we are changing target:

+
from django.db.models import Q
+
+target_not_safe = 'http://'+target
+target_safe = 'https://'+target
+queryset = Service.objects.filter(Q(url=target_not_safe) | Q(url=target_safe))
+
+

Q objects

+

EDIT

+

How about using _istartwith:

+
queryset = Service.objects.filter(Q(url__istartswith=target_not_safe) | Q(url__istartswith=target_safe))
+
+

Edit 2

+

Another trick could be to check inside the list using __in. So:

+
query_list = [x.id for x in Service.objects.all() if(f(x.url) == target)]
+queryset = Service.objects.filter(id__in=query_list)
",r +"replace value of array if value exists in other array of object

I am trying to do array manipulation +Basically I have two arrays that is generated dynamically and can be of any length.

+
let arr1 =['test', 'XDDD', 'test new']
+let arr2 = [{value: 'test', error : 'error'}, {value: 'test new', error: 'invalid'}]
+
+

I have check if arr2 object property value exists in arr1 , if yes then replace the arr1 value at index. for eg test is at index 0 then replace it like test [error] i.e arr2.value + arr2.error. similarly "test new" should get replaced at same index with "test new [invalid]"

+

Final output ['test [error]', 'XDDD', 'test new [invalid]']

","

You could do it using forEach (modifing the arr1) or map (if you want a new array).

+
arr2.forEach(item => { 
+    const idx = arr1.findIndex(e => e === item.value);
+    if (idx >= 0) {
+        arr1[idx] = `${arr1[idx]} [${item.error}]`;
+    }
+})
+
+

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/forEach

+
const newArr = arr1.map(item => {
+    const err = arr2.find(a => a.value === item);
+    return err ? `${item} [${err.error}]` : item;
+});
+
+

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map

",r +"Firebase function: Error: unable to open for write

so I was trying to implement a firebase function. I went to firebase functions repository example and copied it. Everything is working properly "Deploy complete!" with no signs of an error. However, when I'm trying to upload image to the firebase store, firebase functions can't open it?

+

There is a code that I used:

+
const functions = require('firebase-functions');
+const admin = require('firebase-admin');
+admin.initializeApp()
+const {Storage} = require("@google-cloud/storage");
+const gcs = new Storage();
+const path = require('path');
+const os = require('os');
+const fs = require('fs');
+const sharp = require("sharp");
+
+exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
+
+  const fileBucket = object.bucket; // The Storage bucket that contains the file.
+  const filePath = object.name; // File path in the bucket.
+  const contentType = object.contentType; // File content type.
+  const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
+
+  if (!contentType.startsWith('image/')) {
+    return console.log('This is not an image.');
+  }
+
+  const fileName = path.basename(filePath);
+
+  if (fileName.startsWith('thumb_')) {
+    return console.log('Already a Thumbnail.');
+  }
+
+  const bucket = admin.storage().bucket(fileBucket);
+  const tempFilePath = path.join(os.tmpdir(), fileName);
+  console.log('Created temporary path',tempFilePath);
+  const metadata = {
+    contentType: contentType,
+  };
+  await bucket.file(filePath).download({destination: tempFilePath});
+  console.log('Image downloaded locally to', tempFilePath);
+
+  const thumbFileName = `thumb_${fileName}`;
+  const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
+  console.log('Created thumb path',tempFilePath);
+  const size = 200;
+
+  /*await*/ sharp(tempFilePath).resize(size,size).toFile(thumbFilePath);
+
+  await bucket.upload(tempFilePath, {
+    destination: filePath,
+    metadata: metadata,
+  });
+  
+  return fs.unlinkSync(tempFilePath);
+});
+
+

Error:

+

","

Cloud Functions has a read-only filesystem except for the /tmp directory. You have to make sure you are writing your data to a path /tmp/your-file

+
+

The only writeable part of the filesystem is the /tmp directory, which +you can use to store temporary files in a function instance. This is a +local disk mount point known as a "tmpfs" volume in which data written +to the volume is stored in memory. Note that it will consume memory +resources provisioned for the function.

+
+

Cloud Functions Execution Environment

",r +"Aframe 1.0.4 - setting scene.environment does not update materials

So I saw an old post here:

+

https://discourse.threejs.org/t/is-there-a-way-to-increase-scene-environment-map-exposure-without-affecting-unlit-materials/13458/4

+

That says... "If you apply the env map to Scene.environment, it is automatically used as the environment map for all physical materials in the scene (assumed the material’s envmap is not set)."

+

So tried this using an Aframe component on the scene:

+
AFRAME.registerComponent('setenvironment', {
+  init: function () {
+    var sceneEl = this.el;
+    var loader = new THREE.CubeTextureLoader();
+    loader.setPath('./');
+
+    var textureCube = loader.load([
+      './images/py.png', './images/pz.png',
+      './images/nx.png', './images/ny.png',
+      './images/px.png', './images/nz.png'
+    ]);
+    textureCube.encoding = THREE.sRGBEncoding;
+    sceneEl.object3D.environment = textureCube;
+  }
+});
+
+

The environment attribute is successfully set, but the other objects materials still have envMap set to null and the environment lighting does not take effect on the materials.

+

Any ideas?

","

aframe 1.0.4 uses three.js revision 111dev. The scene's environment property was introduced in revision 112 (source).

+

If you use the aframe master build - it seems to be working properly (as its based on three.js r119).

+

Otherwise, you'll have to iterate through the meshes, and set the material.envMap property manually.

",r +"Using map and grep to find file names with underscores

My Perl script searches a directory for file names using the map and grep expressions. The script works, but I want to also specify in the map and grep expressions that ALL outputted file names must also include underscores in their names. Sounds simple enough, but I can't figure out how to do this. Please advise. Thanks.

+

Here's my original script that fails to limit outputted file names to only those with underscores in their names:

+
#!/usr/bin/perl
+use strict;
+use warnings;
+
+my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
+opendir(my $DIR, $dir);
+my @files =
+   map s/1//rg,
+      grep /^[^2-9]*\.png\z/i,
+        readdir($DIR);
+
+foreach my$file (@files) {
+   print "$file\n";
+}
+
+

Here's the output. Notice how file names without underscores such as "Asarumcanadense.png" are unwantingly outputted:

+
Ilex_verticillata.png
+Asarum_canadense.png
+Ageratina_altissima.png
+Lonicera_maackii.png
+Chelone_obliqua.png
+Asarumcanadense.png
+
+

Modifying the map/grep expression as below to include only file names with underscores in the middle of their names created a syntax error:

+
my @files =
+ map s/*_*1//rg,
+    grep /^_*[^2-9]*\.png\z/i,
+      readdir($DIR); # outputted files must also include an underscore
+
+

Again, please advise how to specify in the map and grep expressions that ALL outputted file names must also include underscores in their names. Thanks.

","

Add the needed condition to grep:

+
my @files =
+   map { s/1//rg }
+      grep { /^[^2-9]*\.png\z/i && /_/ } 
+        readdir($DIR);
+
",r +"Only sum up unique values in column
   |       A                B           
+---|----------------------------------------- 
+1  |    Total              1.600
+---|-----------------------------------------
+2  |    Product_A_x1         700        
+3  |    Product_A_x5         700  
+---|-----------------------------------------      
+4  |    Product_B_x3         300        
+---|-----------------------------------------
+5  |    Product_C_x4         200      
+6  |    Product_C_x8         200      
+---|------------------------------------------
+7  |    Product_D_x9         400         
+8  |    Product_D_x11        400      
+9  |    Prodcut_D_x8         400  
+10 |
+
+
+

In Cell B1 I want to sum the unique values from Column B.

+
B1 = 700 + 300 + 200 + 400
+
+

In case a value appears two times it should only be included one time in the sum function.

+
+

Is there somehting like a SUMIF formula for unique values?

","

In Microsoft365 you can use: +=SUM(UNIQUE(B2:B9))

",r +"Could not start GlassFish Server4.1 HTTP or HTTPS Listener port is occupied while server is not running ON A MAC

Could anyone shed some light on this? I have watched a few YouTube videos with the same problem but all solutions are based on Windows. How could I fix this on a Mac? I'm pretty sure I have no other servers running.

+

Thanks +see error image from netbeans

","

This means that there is another application using the ports the Glassfish requires. Use the command

+

lsof -nP -iTCP:$PORT | grep LISTEN

+

to list the what ports are in use along with the process ID of the process using the port. Glassfish requires ports 4848, 8080 and 8081 to be free. One app that sometimes causes port issues is vnc, so check if you have screen sharing turned on and try disable it if that is the case.

",r +"parse year and month from a string SQL BigQuery

I have a column Time in the BigQuery table. The data type is STRING. The data looks like this: 2020-10-15-03:15:40. I need to parse year and month. The desired output is: 2020-10. I have tried:

+
SELECT
+    date(parse_datetime('%Y-%m-%T', Time)) as Date
+FROM `bigquery_table`
+
+

Error message: failed to parse a string "2020-10-15-03:15:40"

","

How about using string operations?

+
select substring(time, 1, 4) as year,
+       substring(time, 6, 2) as month
+
+

If this were any sort of date/time data type, you can use extract():

+
select extract(year from time) as year,
+       extract(month from time) as month
+
+

I strongly encourage you to use the correct data types for your values. But if you or your DBA has chosen not to follow this simple best practice, then you can just use string operations.

",r +"Chisel/FIRRTL DefnameDifferentPortsException

I recently updated the Chisel version of a big project of mine from 3.1.1 to 3.4.0; however, I am getting a bunch of firrtl.passes.CheckHighFormLike$DefnameDifferentPortsException:

+
firrtl.passes.CheckHighFormLike$DefnameDifferentPortsException: : ports of extmodule XilinxSimpleDualPortNoChangeBRAM with defname XilinxSimpleDualPortNoChangeBRAM are different for an extmodule with the same defname
+firrtl.passes.CheckHighFormLike$DefnameDifferentPortsException: : ports of extmodule XilinxSimpleDualPortNoChangeBRAM_1 with defname XilinxSimpleDualPortNoChangeBRAM are different for an extmodule with the same defname
+// and so on 241 times
+
+

Here is the definition of XilinxSimpleDualPortNoChangeBRAM, together with its dependencies:

+
class XilinxSimpleDualPortNoChangeBRAM(width: Int,
+                                       depth: Int,
+                                       performance: String="HIGH_PERFORMANCE",
+                                       initFile: String="",
+                                       ramStyle: String="block",
+                                       val useReset: Boolean=false)
+                                       extends BlackBox(Map("RAM_WIDTH" -> width,
+                                                            "RAM_DEPTH" -> depth,
+                                                            "RAM_PERFORMANCE" -> performance,
+                                                            "INIT_FILE" -> initFile,
+                                                            "RAM_STYLE" -> ramStyle))
+                                       with HasBlackBoxResource with Memory {
+    val io = IO(new XilinxSimpleDualPortBRAMBlackBoxIO(log2Ceil(depth), width))
+    val acceptedRamStyles = Seq("block", "distributed", "registers", "ultra")
+    require(acceptedRamStyles contains ramStyle)
+    def write(wrAddr: UInt, wrData: UInt, wrEn: Bool): Unit = {
+      io.wea := wrEn
+      io.addra := wrAddr
+      io.dina := wrData
+    }
+
+    def read(rdAddr: UInt, rdEn: Bool): UInt = {
+      io.addrb := rdAddr
+      io.regceb := rdEn
+      io.enb := rdEn
+      io.doutb
+    }
+
+    def defaultBindings(clock: Clock, reset: core.Reset): Unit = {
+      io.clock := clock
+      if(useReset)
+        io.reset := reset
+      else
+        io.reset := false.B
+    }
+    setResource("/XilinxSimpleDualPortNoChangeBRAM.v")
+}
+
+trait Memory extends BaseModule {
+  def read(rdAddr: UInt, rdEn: Bool): UInt
+  def write(wrAddr: UInt, wrData: UInt, wrEn: Bool): Unit
+  val latency: Int = 2
+}
+
+class XilinxSimpleDualPortBRAMIO(addrWidth: Int, dataWidth: Int) extends Bundle {
+    val addra  = Input(UInt(addrWidth.W))
+    val addrb  = Input(UInt(addrWidth.W))
+    val dina   = Input(UInt(dataWidth.W))
+    val wea    = Input(Bool())
+    val enb    = Input(Bool())
+    val regceb = Input(Bool())
+    val doutb  = Output(UInt(dataWidth.W))
+
+    override def cloneType = (new XilinxSimpleDualPortBRAMIO(addrWidth, dataWidth)).asInstanceOf[this.type]
+}
+class XilinxSimpleDualPortBRAMBlackBoxIO(addrWidth: Int, dataWidth: Int) extends XilinxSimpleDualPortBRAMIO(addrWidth, dataWidth) {
+    val clock  = Input(Clock())
+    val reset  = Input(Reset())
+
+    override def cloneType = (new XilinxSimpleDualPortBRAMBlackBoxIO(addrWidth, dataWidth)).asInstanceOf[this.type]
+}
+
+

The Verilog resource XilinxSimpleDualPortNoChangeBRAM.v is one of the BRAM instantiation templates available in Vivado:

+
module XilinxSimpleDualPortNoChangeBRAM #(
+  parameter RAM_WIDTH = 64,                       // Specify RAM data width
+  parameter RAM_DEPTH = 512,                      // Specify RAM depth (number of entries)
+  parameter RAM_PERFORMANCE = "HIGH_PERFORMANCE", // Select "HIGH_PERFORMANCE" or "LOW_LATENCY"
+  parameter INIT_FILE = "",                       // Specify name/location of RAM initialization file if using one (leave blank if not)
+  parameter RAM_STYLE = "block"                   // Target memory type. Accepted values: block, distributed, registers, ultra (UltraScale+ only)
+) (
+  input [clogb2(RAM_DEPTH-1)-1:0] addra, // Write address bus, width determined from RAM_DEPTH
+  input [clogb2(RAM_DEPTH-1)-1:0] addrb, // Read address bus, width determined from RAM_DEPTH
+  input [RAM_WIDTH-1:0] dina,          // RAM input data
+  input wea,                           // Write enable
+  input enb,                           // Read Enable, for additional power savings, disable when not in use
+  input regceb,                        // Output register enable
+  output [RAM_WIDTH-1:0] doutb,         // RAM output data
+  input clock,                          // Clock
+  input reset                          // Output reset (does not affect memory contents)
+);
+
+  (* ram_style = RAM_STYLE *) reg [RAM_WIDTH-1:0] BRAM [RAM_DEPTH-1:0];
+  reg [RAM_WIDTH-1:0] ram_data = {RAM_WIDTH{1'b0}};
+
+  // The following code either initializes the memory values to a specified file or to all zeros to match hardware
+  generate
+    if (INIT_FILE != "") begin: use_init_file
+      initial
+        $readmemh(INIT_FILE, BRAM, 0, RAM_DEPTH-1);
+    end else begin: init_bram_to_zero
+      integer ram_index;
+      initial
+        for (ram_index = 0; ram_index < RAM_DEPTH; ram_index = ram_index + 1)
+          BRAM[ram_index] = {RAM_WIDTH{1'b0}};
+    end
+  endgenerate
+
+  always @(posedge clock) begin
+    if (wea)
+      BRAM[addra] <= dina;
+    if (enb)
+      ram_data <= BRAM[addrb];
+  end
+
+  //  The following code generates HIGH_PERFORMANCE (use output register) or LOW_LATENCY (no output register)
+  generate
+    if (RAM_PERFORMANCE == "LOW_LATENCY") begin: no_output_register
+
+      // The following is a 1 clock cycle read latency at the cost of a longer clock-to-out timing
+       assign doutb = ram_data;
+
+    end else begin: output_register
+
+      // The following is a 2 clock cycle read latency with improve clock-to-out timing
+
+      reg [RAM_WIDTH-1:0] doutb_reg = {RAM_WIDTH{1'b0}};
+
+      always @(posedge clock)
+        if (reset)
+          doutb_reg <= {RAM_WIDTH{1'b0}};
+        else if (regceb)
+          doutb_reg <= ram_data;
+
+      assign doutb = doutb_reg;
+
+    end
+  endgenerate
+
+  //  The following function calculates the address width based on specified RAM depth
+  function integer clogb2;
+    input integer depth;
+      for (clogb2=0; depth>0; clogb2=clogb2+1)
+        depth = depth >> 1;
+  endfunction
+
+endmodule
+
+

I tried to have a look at the file where this exception is thrown, CheckHighForm.scala, but I quickly got lost as I have no idea of what I should be looking for.

+

What I understood from the tests in CheckSpec.scala is that it should throw an exception if ExtModules have matching port names and widths, but a different order, so I tried to make the order of the inputs in the Chisel BlackBox the same as the ones in the Verilog module but I still get an exception.

+

The test throw an exception if parameterless ExtModules have the same ports, but different widths made me think that having multiple instantiations with different port widths could be the reason for the exception, but then there is another test that says that it should NOT throw an exception if ExtModules have parameters, matching port names, but different widths, which is the case here as the port widths are controlled by parameters.

+

What could be the reason for this exception?

+

Update: As requested, here is the FIRRTL IR of two instantiations of the black box:

+
  extmodule XilinxSimpleDualPortNoChangeBRAM : 
+    input addra : UInt<14>
+    input addrb : UInt<14>
+    input dina : UInt<1>
+    input wea : UInt<1>
+    input enb : UInt<1>
+    input regceb : UInt<1>
+    output doutb : UInt<1>
+    input clock : Clock
+    input reset : Reset
+    
+    defname = XilinxSimpleDualPortNoChangeBRAM
+    parameter RAM_STYLE = "block"
+    parameter RAM_WIDTH = 1
+    parameter RAM_DEPTH = 16384
+    parameter RAM_PERFORMANCE = "HIGH_PERFORMANCE"
+    parameter INIT_FILE = ""
+
+  extmodule XilinxSimpleDualPortNoChangeBRAM_1 : 
+    input addra : UInt<6>
+    input addrb : UInt<6>
+    input dina : UInt<518>
+    input wea : UInt<1>
+    input enb : UInt<1>
+    input regceb : UInt<1>
+    output doutb : UInt<518>
+    input clock : Clock
+    input reset : Reset
+    
+    defname = XilinxSimpleDualPortNoChangeBRAM
+    parameter RAM_STYLE = "distributed"
+    parameter RAM_WIDTH = 518
+    parameter RAM_DEPTH = 64
+    parameter RAM_PERFORMANCE = "HIGH_PERFORMANCE"
+    parameter INIT_FILE = ""
+
+

Update 2: Apparently, some XilinxSimpleDualPortNoChangeBRAM were picking up an older version of XilinxSimpleDualPortBRAMBlackBoxIO where the reset was still of type Bool instead of Reset. Changing that solved the issue.

","

This check is supposed to disallow impossible situations when referring to a specific BlackBox. Namely, the following must be true:

+
    +
  • If the BlackBox has no parameters, then all ports must have the same name, same width, and be in the same order
  • +
  • If the BlackBox has parameters, then all ports must have the same name and be in the same order (but may have different widths)
  • +
+

It sounds like either your example is producing BlackBoxes that violate the latter condition (since your BlackBoxes have parameters) or this has exposed a bug in that FIRRTL compiler check.

+

The actual Verilog module is never checked and can't cause any problems here.

+

Could you update your question to provide the FIRRTL IR that is producing these errors? Specifically, what does the FIRRTL IR for XilinxSimpleDualPortNoChangeBRAM and XilinxSimpleDualPortNoChangeBRAM_1 look like? This should be in a file like "Foo.fir". Alternatively, you can do something like:

+
import chisel3.stage.ChiselStage
+
+/* Note: this is emitChirrtl ("chirrtl") as you want the FIRRTL emitted from Chisel. */
+println(ChiselStage.emitChirrtl(new MyTopModule))
+
",r +"I am getting an error ->.can someone help me plz

Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at com.example.pcetsnmiet.Fragments.DashBoardFragment.onCreateView(DashBoardFragment.java:34)

+

dashboardFragment.xml

+
<?xml version="1.0" encoding="utf-8"?>
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+xmlns:tools="http://schemas.android.com/tools"
+android:layout_width="match_parent"
+android:layout_height="match_parent"
+xmlns:app="http://schemas.android.com/apk/res-auto"
+tools:context=".Fragments.DashBoardFragment"
+android:background="#ECB1B1">
+
+<com.denzcoskun.imageslider.ImageSlider
+    android:id="@+id/image_slider"
+    android:layout_width="match_parent"
+    android:layout_height="200dp"
+    app:iss_auto_cycle="true"
+    app:iss_period="1000"
+    app:iss_delay="0"
+    android:background="#fff"
+
+    />
+
+ +

DashboardFragment.java

+
public class DashBoardFragment extends Fragment {
+
+ImageSlider imageSlider;
+@Override
+public View onCreateView(LayoutInflater inflater, ViewGroup container,
+                         Bundle savedInstanceState) {
+
+
+
+    imageSlider = (ImageSlider) getView().findViewById(R.id.image_slider); //this is the line error pointing at
+
+    final List<SlideModel> remoteimages = new ArrayList<>();
+
+    FirebaseDatabase.getInstance().getReference().child("Slider")
+            .addListenerForSingleValueEvent(new ValueEventListener() {
+                @Override
+                public void onDataChange(@NonNull DataSnapshot snapshot) {
+                    for(DataSnapshot data:snapshot.getChildren())
+                    {
+                        remoteimages.add(new SlideModel(data.child("url").getValue().toString(),data.child("title").getValue().toString(), ScaleTypes.FIT));
+
+                    }
+                    imageSlider.setImageList(remoteimages,ScaleTypes.FIT);
+                }
+
+                @Override
+                public void onCancelled(@NonNull DatabaseError error) {
+
+                }
+            });
+
+
+
+
+
+    // Inflate the layout for this fragment
+    return inflater.inflate(R.layout.fragment_dash_board, container, false);
+
+}
+
+

}

","

You are using wrong approach. You need to define your layout at first , then get views from it as below -

+
View view = inflater.inflate(R.layout.fragment_dash_board, container, false);
+imageSlider = (ImageSlider) view.findViewById(R.id.image_slider); 
+
+//let other code remain same
+
+
+return view;
+
",r +"BackButton and BottomNavigationBar

I want to navigate between my pages, when I'm on the settings page I want a back button that takes me to the home page and the same for the favorites, from my pages there is also a bottom navigation bar that allows you to navigate between them. I have already tried with the Navigator() but it forces me to put another button on the home page. I don't know if I made myself clear, but I hope you can help me.

+

Thank you!

+

Update : I have used getX 's package.

","

If the settings page doesn't include the bottom app bar, then you can use Navigator.of(context).pop() or you can use a top app bar and set automaticallyImplyLeading = true to display a back button which also pops.

+

Here is a example of one of my bottom app bars which allows smooth navigation across multiple pages:

+
class _MainScreenState extends State<MainScreen> {
+ 
+
+  int _currentIndex = 0;
+  final List<Widget> _children = [
+    Home(),
+    InboxMain(),
+    DashboardMain(),
+    ProfileMain(),
+    FriendsMain()
+  ];
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      body: _children[_currentIndex],
+      bottomNavigationBar: new Theme(
+        data: Theme.of(context).copyWith(
+          canvasColor: Color.fromRGBO(41, 34, 78, 1),
+        ), //
+        child: BottomNavigationBar(
+          //selectedItemColor: Colors.red,
+          //selectedIconTheme: IconThemeData(color: Colors.red),
+          type: BottomNavigationBarType.fixed,  
+          showSelectedLabels: false,
+          showUnselectedLabels: false,
+          backgroundColor: Color.fromRGBO(41, 34, 78, 1),
+          onTap: onTabTapped,
+          currentIndex: _currentIndex,
+          items: [
+            BottomNavigationBarItem(
+                icon: _currentIndex == 0
+                    ?  Icon(Icons.home_outlined, color: Colors.white)
+                    : Icon(
+                        Icons.home_outlined,
+                        color: Colors.grey[600],
+                      ),
+                title: Container(
+                  height: 0,
+                )),
+            BottomNavigationBarItem(
+                icon: _currentIndex == 1
+                    ? Icon(
+                        Icons.email_outlined,
+                        color: Colors.white,
+                      )
+                    : Icon(
+                        Icons.email_outlined,
+                        color: Colors.grey[600],
+                      ),
+                title: Container(
+                  height: 0,
+                )),
+            BottomNavigationBarItem(
+                icon: _currentIndex == 2
+                    ? Icon(Icons.dashboard, color: Colors.white)
+                    : Icon(Icons.dashboard, color: Colors.grey[600]),
+                title: Container(
+                  height: 0,
+                )),
+            BottomNavigationBarItem(
+                icon: _currentIndex == 3
+                    ? Icon(
+                        Icons.person,
+                        color: Colors.white,
+                      )
+                    : Icon(Icons.person, color: Colors.grey[600]),
+                title: Container(
+                  height: 0,
+                )),
+            BottomNavigationBarItem(
+                icon: _currentIndex == 4
+                    ? Icon(
+                        Icons.people_alt,
+                        color: Colors.white,
+                      )
+                    : Icon(Icons.people_alt, color: Colors.grey[600]),
+                title: Container(
+                  height: 0,
+                )),
+          ],
+        ),
+      ),
+    );
+  }
+
+  void onTabTapped(int index) {
+    setState(() {
+      _currentIndex = index;
+    });
+  }
+}
+
+

My app (once logged in) navigates to this, and all navigation is controlled here, other than extended screens which I use a back button and pop().

",r +"HDFS File Encoding Converter

I'm trying to convert an HDFS file from UTF-8 to ISO-8859-1.

+

I've written a small Java program :

+
String theInputFileName="my-utf8-input-file.csv";
+String theOutputFileName="my-iso8859-output-file.csv";
+Charset inputCharset = StandardCharsets.UTF_8;
+Charset outputCharset = StandardCharsets.ISO_8859_1;
+
+try (
+    final FSDataInputStream in = theFileSystem.open(new Path(theInputFileName)) ;
+    final FSDataOutputStream out = theFileSystem.create(new Path(theOutputFileName))
+)        
+{
+    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in, inputCharset)))
+    {
+        String line;
+        while ((line = reader.readLine()) != null)
+        {
+            out.write(line.getBytes(this.outputCharset));
+            out.write(this.lineSeparator.getBytes(this.outputCharset));
+        }
+    }
+} catch (IllegalArgumentException | IOException e)
+{
+    RddFileWriter.LOGGER.error(e, "Exception on file '%s'", theFileNameOutput);
+}
+
+

This code is executed through a Hadoop Cluster using Spark (the output data is usually provided by a RDD)

+

To simplify my issue I have removed RDD/Datasets parts to work direcly on HDFS File.

+

When I execute the code :

+
    +
  • Localy on my DEV computer : It Works !, local output file is encoded in ISO-8859-1
  • +
  • on EDGE server : via spark-submit command using HDFS Files It Works ! HDFS output file is encoded in ISO-8859-1
  • +
  • on Datanode via oozie : It doesn't work :-( : HDFS outfile is encoded in UTF-8 instead of ISO-8859-1
  • +
+

I don't understand what properties (or something else) may be causing the change in behavior

+

Versions :

+
    +
  • Hadoop : v2.7.3
  • +
  • Spark : v2.2.0
  • +
  • Java : 1.8
  • +
+

Looking forward to your help. +Thanks in advance

","

Finally, I found the source of my problem.

+

The input file on the cluster was corrupted, the whole file did not have a constant and consistent encoding.

+

External data are aggregated daily and recently the encoding has been changed from ISO to UTF8 without notification...

+

To put it more simply:

+
    +
  • the start contained bad conversion « é ê è » instead of « é ê è »
  • +
  • the end was correctly encoded
  • +
+

We have split, fixed the encoding and merged the data to repair the input.

+

The final code works fine.

+
private void changeEncoding(
+            final Path thePathInputFileName,final Path thePathOutputFileName,
+            final Charset theInputCharset,  final Charset theOutputCharset,
+            final String theLineSeparator
+        ) {
+    try (
+        final FSDataInputStream in = this.fileSystem.open(thePathInputFileName);
+        final FSDataOutputStream out = this.fileSystem.create(thePathOutputFileName);
+        final BufferedReader reader = new BufferedReader(new InputStreamReader(in, theInputCharset));
+        final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, theOutputCharset));) {
+        
+        String line;
+        while ((line = reader.readLine()) != null) {
+            writer.write(line);
+            writer.write(theLineSeparator);
+        }
+        
+    } catch (IllegalArgumentException | IOException e) {
+        LOGGER.error(e, "Exception on file '%s'", theOutputFileName);
+    }
+}
+
+

Stop your research ! +;-)

",r +"Add a column name to a panda dataframe (multi index)

I concatenate series objects, with existing column names together to a DataFrame in Pandas. The result looks like this:

+
pd.concat([x, y, z], axis=1)
+
+
+   X   |  Y   |   Z
+  -------------------
+  data | data | data
+
+

Now I want to insert another column name A above the column names X, Y, Z, for the whole DataFrame. This should look like this at the end:

+
   A                  # New Column Name
+  ------------------- 
+   X   |  Y   |   Z   # Old Column Names
+  -------------------
+  data | data | data 
+
+

So far I did not find a solution how to insert a column name A above the existing columns names X, Y, Z for the complete DataFrame. I would be grateful for any help. :)

","

Let's try with MultiIndex.from_product to create MultiIndex columns:

+
df = pd.concat([x, y, z], axis=1)
+df.columns = pd.MultiIndex.from_product([['A'], df.columns])
+
+
+
A            
+X     Y     Z
+data  data  data
+
",r +"OSMnx- why is the 'walk' network larger than 'all' network?

I export and compare the km length of the total network and then the pedestrian network via OSMnx. The strange thing is that for some cities the walk network is larger than the total network. How can this be explained? I checked the queries in the custom filter of the OSMnx code and I still can't explain it, since network='walk' is a stricter definition, thus should be contained in the all network...

+

Try out this code and let me know if you have any explanations.

+
place = 'Empire state building, New York, NY 10001, USA'
+
+# import graph all
+G_a = ox.graph_from_address(place, retain_all=True, network_type='all', simplify=True, clean_periphery=False)
+
+# import graph walk 
+G_w = ox.graph_from_address(place, retain_all=True, network_type='walk', simplify=True, clean_periphery=False) 
+
+
+print('all: ', G_a.size(weight='length'), 'walk: ', G_w.size(weight='length'))
+
","

The walk network type is fully bidirectional, meaning that each pair of adjacent nodes has at least two edges between them (there could be more than two if the nodes are directly linked by multiple street segments, as this is a MultiDiGraph), one pointing from node u to v and the other pointing from node v to u. Pedestrians can walk either direction on any street, so all edges must be bidirectional in a walking network.

+

The all network type is not fully bidirectional as it makes no presumptions about who or what may flow through it. Hence, all of its edges obey one-way directionality constraints when present, meaning that some of its nodes may only be linked by a single one-way edge.

+

This is why you may see more edges in a walk network's model than in an all network's model. However, your all network will always have at least as many nodes as your walk network, as you can see here:

+
import osmnx as ox
+ox.config(use_cache=True, log_console=True)
+
+place = 'Empire state building, New York, NY 10001, USA'
+G_a = ox.graph_from_address(place, retain_all=True, network_type='all', 
+                            simplify=True, clean_periphery=False)
+G_w = ox.graph_from_address(place, retain_all=True, network_type='walk', 
+                            simplify=True, clean_periphery=False)
+assert len(G_a) >= len(G_w)
+
+

You can also see and set which network_type arguments are treating as bidirectional with the bidirectional_network_types setting:

+
print(ox.settings.bidirectional_network_types)
+
+

The bidirectional_network_types setting will be exposed via ox.config() in the next release of OSMnx.

",r +"Dataflow SQL - Unsupported type Geography

I'm trying to create a Dataflow SQL on Google Big Query and I got this error

+
Unsupported type for column centroid.centroid: GEOGRAPHY
+
+

I couldnt find any evidence that Dataflow SQL actually does not support Geography data and in the documentation geography data is not mentioned at all. Is this the case, why is that and is there any workaround?

","

No unfortunately Dataflow SQL does not support Geography types. It supports a subset of BigQuery Standard SQL. Only the data types listed explicitly in the page you linked are supported, it should probably be more clear about that.

+

Dataflow SQL relies on ZetaSQL to parse and analyze queries, and ZetaSQL does not yet support Geography (you can see the current status here).

+

Unfortunately for now the only workaround is to convert any GEOGRAPHY fields to a supported type.

",r +"Reading a file from a position in R

I have a large plain text file to be read in R, where all data is contained at the same line with no spaces (DNA sequence with no header). I found the next function:

+
readChar("filename",nchar=n)
+
+

which allows to read just the "n" first elements of the file saving a lot of time. Is there another function in R that goes further by reading just from START position to STOP one, avoiding to upload the whole file?

","

Basically no, from what i know, you need to read the whole file and then discard the characters that you don't want. For example, if you want only the first 10 letters for every line:

+
strsub(readChar("filename",nchar=n),1,10)
+
+

But, this post (How to efficiently read the first character from each line of a text file?) shows some ways of improving the efficiency of that.

",r +"How to omit na in aggregate to calculate SD in R

I have a dataframe that looks like this:

+
dat <- structure(list(cohort = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
+1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
+1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
+1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "ADC8_AA", class = "factor"), 
+    status = c(1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 
+    1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, -9L, 1L, 1L, 2L, 
+    2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 
+    2L, 2L, 1L, 2L, -9L, 2L, 1L, -9L, 2L), age_onset = c(NA, 
+    NA, NA, NA, 63, NA, 79, NA, 67, 71, 81, NA, NA, NA, NA, 73, 
+    NA, 66, 77, 68, 75, NA, NA, NA, NA, 76, 79, NA, NA, NA, NA, 
+    NA, 70, NA, 77, 84, 78, 76, NA, 92, 64, 60, 72, NA, 81, NA, 
+    62, NA, 82, 74)), row.names = c(NA, 50L), class = "data.frame")
+
+

I am trying to get mean and sd like this, but it gets me NA for SD for status ==-9. What could be the reason and how do I do this correctly?

+
> aggregate(age_onset~cohort+status, data = dat, mean, na.action = na.omit)
+   cohort status age_onset
+1 ADC8_AA     -9  82.00000
+2 ADC8_AA      2  73.54167
+> aggregate(age_onset~cohort+status, data = dat, sd)
+   cohort status age_onset
+1 ADC8_AA     -9        NA
+2 ADC8_AA      2  7.661191
+
","

Try this:

+
aggregate(age_onset~cohort+status, data = dat, sd, na.rm = TRUE)
+#    cohort status age_onset
+# 1 ADC8_AA     -9        NA
+# 2 ADC8_AA      2  7.661191
+
+

You can use the ... argument of aggregate to pass na.rm = TRUE through to sd.

+

You will still get NA for any groups that only have a single non-missing value. This is because standard deviation isn't defined for a single value.

+
subset(dat, status == -9)
+#     cohort status age_onset
+# 23 ADC8_AA     -9        NA
+# 46 ADC8_AA     -9        NA
+# 49 ADC8_AA     -9        82
+
+sd(82)
+# [1] NA
+
",r +"Combining values from multiple tables using join clause with multiple ON

I want to combine all the related data using LEFT JOIN clause but if one of tables has no matched record from other table it will not show up. Can you check my queries it seems that there is missing or totally messed up. Here's my query.

+
SELECT*
+FROM
+MASTER_TBL 
+LEFT JOIN
+(
+SELECT*
+FROM
+TBLA A
+LEFT JOIN
+TBLB B
+ON
+A.ID=B.ID AND A.DESC=B.DESC
+LEFT JOIN
+TBLC C
+ON
+B.ID=C.ID AND B.DESC=C.DESC
+LEFT JOIN
+TBLD D
+ON
+C.ID=D.ID AND C.DESC=D.DESC
+) E
+ON 
+MASTER_TBL.ID=E.ID
+
+

","

This approach uses UNION ALL to combine the letter named tables (tbla, tblb, tblc, tbld) into a CTE, common table expression. The combined table is then summarized by id, [desc] and crosstabulated (or pivoted) across the login columns. The pivoted result is then LEFT JOIN'ed to the master_tbl. Something like this.

+
with
+tbl_cte(tbl, id, [login], [desc]) as (
+    select 'A', * from tbla
+    union all
+    select 'B', * from tblb
+    union all
+    select 'C', * from tblc
+    union all
+    select 'D', * from tblc),
+pvt_cte(id, tbla_login, tblb_login, tblc_login, tbld_login, [desc]) as (
+    select id, 
+           max(case when tbl='A' then [login] else null end) as tbla_login,
+           max(case when tbl='B' then [login] else null end) as tblb_login,
+           max(case when tbl='C' then [login] else null end) as tblc_login,
+           max(case when tbl='D' then [login] else null end) as tbld_login,
+           [desc] 
+    from tbl_cte
+    group by id, [desc])
+select mt.id, [name], country, [status], pc.tbla_login, 
+       pc.tblb_login, pc.tblc_login, pc.tbld_login, pc.[desc]
+from master_tbl mt
+     left join pvt_cte pc on mt.id=pc.id;
+
",r +"Align many short sequences from two lists and find complementary

So I have two list objects in R and I want to know which of the sequences can bind to each other through DNA complementarity.

+

The first object rs is reverse complement microRNA seed regions and the second is 3'UTRs motifs. +Any lead on how to solve this problem?
+I found a package called microRNAs (https://www.bioconductor.org/packages/release/bioc/manuals/microRNA/man/microRNA.pdf) with a function called matchSeeds(seed, seq). I did this but this function is actually looking for exact matches, which is not exactly what I need. Any lead on how to solve this in R will be very much appreciated. +Thanks!

+
> typeof(rs)
+[1] "list"
+> typeof(u)
+[1] "list"
+
+head(rs)
+$`miR-92|34108_3p `
+[1] "TGCAAT"
+
+$`miR-92|34106_3p `
+[1] "TGCAAT"
+
+$`miR-92|34110_3p `
+[1] "TGCAAT"
+
+$`miR-184|1952_3p `
+[1] "CCGTCC"
+
+$`miR-184|1954_3p `
+[1] "CCGTCC"
+
+$`miR-1795_3p `
+[1] "CCGTCC"
+
+head(u)
+$upper_1
+[1] "gccgtt"
+
+$upper_2
+[1] "ccgagc"
+
+$upper_3
+[1] "gacatt"
+
+$upper_4
+[1] "gcttat"
+
+$upper_5
+[1] "taccta"
+
+$upper_6
+[1] "tcgtct"
+
","

If you want to find if any substrings in rs list are complementary to the strings in u list, and you want it to be performant you can use package Biostrings function matchPDict.

+

Example:

+
library(Biostrings)
+library(IRanges)
+
+lis <- list(`miR-92|34108_3p ` = "TGCAAT",
+            `miR-92|34106_3p ` = "TGCAAT",
+            `miR-92|34110_3p ` = "TGCAAT")
+
+u <- list(upper_1 ="gccgtt",
+          upper_2 = "ccgagc",
+          upper_3 = "gacatt",
+          upper_4 = "gcttat",
+          upper_5 = "taccta")
+
+

Convert first list to DNAStringSet:

+
lis <- DNAStringSetList(lis)
+lis <- unlist(lis)
+
+

Convert second list to DNAStringSet:

+
u <- DNAStringSetList(u)
+u <- unlist(u)
+
+

Get the complement of lis

+
lis_rc <- complement(lis)
+
+

create a PDict so you can match it fast vs the other list

+
pdict0 <- PDict(lis_rc)
+
+

iterate over list u running matchPDict

+
lapply(u, function(x) matchPDict(pdict0, x))
+
+

EDIT: if you want to check any orientation you can create them using accesory functions such as complement, reverse and reverseComplement and provide that to PDict:

+
lis_rc <- c(lis,
+            complement(lis),
+            reverse(lis),
+            reverseComplement(lis))
+
+names(lis_rc) <- paste(trimws(names(lis_rc)), rep(c("",
+                                            "c",
+                                            "r",
+                                            "rc"),
+                                          each = length(lis)),
+                                            sep = "_")
+
+pdict0 <- PDict(lis_rc)
+
+res <- lapply(u, function(x) matchPDict(pdict0, x))
+
+

res is a list of IRanges objects

+

you can check where the hits are with

+
lapply(res, width)
+lapply(res, start)
+lapply(res, end)
+
+

EDIT2:

+

if you just want to count the matches without the match coordinates you can simply use:

+
vcountPDict(pdict0, u)
+      [,1] [,2] [,3] [,4] [,5]
+ [1,]    0    0    0    0    0
+ [2,]    0    0    0    0    0
+ [3,]    0    0    0    0    0
+ [4,]    0    0    0    0    0
+ [5,]    0    0    0    0    0
+ [6,]    0    0    0    0    0
+ [7,]    0    0    0    0    0
+ [8,]    0    0    0    0    0
+ [9,]    0    0    0    0    0
+[10,]    0    0    0    0    0
+[11,]    0    0    0    0    0
+[12,]    0    0    0    0    0
+
+

rows correspond to sequences in pdict0, while columns correspond to sequences in u:

+
mat <- vcountPDict(pdict0, u)
+rownames(mat) <- names(lis_rc)
+colnames(mat) <- names(u)
+
+                   upper_1 upper_2 upper_3 upper_4 upper_5
+miR-92|34108_3p_         0       0       0       0       0
+miR-92|34106_3p_         0       0       0       0       0
+miR-92|34110_3p_         0       0       0       0       0
+miR-92|34108_3p_c        0       0       0       0       0
+miR-92|34106_3p_c        0       0       0       0       0
+miR-92|34110_3p_c        0       0       0       0       0
+miR-92|34108_3p_r        0       0       0       0       0
+miR-92|34106_3p_r        0       0       0       0       0
+miR-92|34110_3p_r        0       0       0       0       0
+miR-92|34108_3p_rc       0       0       0       0       0
+miR-92|34106_3p_rc       0       0       0       0       0
+miR-92|34110_3p_rc       0       0       0       0       0
+
",r +"Disable shipping methods having a specific word and based on a shipping class in WooCommerce

I've used a Business Bloomer snippet and tweaked it a bit to unset some shipping methods depending on a shipping class of items in the cart.

+

It works fine with the 4 shipping methods I have tested with but in order to fully work on my website, I have to list all shipping methods values manually and I have A LOT ( 86 to unset in if and 60 in else.)

+

Therefore, I would like to edit the snipped so I could unset all shipping methods that contains the same term all at once rather than look for each value individually, but don't really know how to.

+

I have prints for sale and so I’ve set some shipping methods for orders including prints and some for orders whitout. Therefore all my shipping methods for prints have a value ending with “_print” when the others have a value ending with “_classique”, as you can see in the code bellow.

+

My goal is to disable all shipping methods ending with “_classique” when a product with the “print” shipping class in the cart and vice versa.

+

So far my code looks like this :

+
add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_regular_shipping_method', 10, 2 );
+
+function businessbloomer_hide_regular_shipping_method( $rates, $package ) {
+    $shipping_class_target = 35; // shipping class ID
+    $in_cart = false;
+    foreach( WC()->cart->get_cart_contents() as $key => $values ) {
+        if( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
+        $in_cart = true;
+        break;
+        }
+    }
+    if( $in_cart ) { // shipping method with value
+        unset( $rates['wbs:2:d6f790a0_colissimo_sans_signature_classique'] ); 
+        unset( $rates['wbs:2:d748dcd4_lettre_suivie_classique'] ); 
+        unset( $rates['wbs:2:f1058bc8_colissimo_avec_signature_classique'] ); 
+
+    }
+    else{
+        unset( $rates['wbs:2:1cdf4913_colissimo_sans_signature_print'] );
+        unset( $rates['wbs:2:fghla482_lettre_suivie_print'] );
+        unset( $rates['wbs:2:g27a1f56_colissimo_avec_signature_print'] );
+
+
+    }
+    return $rates;
+}
+
+

Any help on how to achieve this would be very appreciated. +Thank you to anyone who'll take time to read this !

","

Updated

+

Using PHP strpos() will allow you to check if a word is contained in a string. Then you will need to make some changes in your code to make it work:

+
add_filter( 'woocommerce_package_rates', 'show_hide_shipping_methods', 10, 2 );
+function show_hide_shipping_methods( $rates, $package ) {
+    $shipping_class_id = 35; // Targeted shipping class ID
+    $found = false;
+    
+    // Loop through cart items for the current package
+    foreach ( $package['contents'] as $cart_item ) {
+        if( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ) {
+            $found = true;
+            break;
+        }
+    }
+    
+    // Loop through shipping rates
+    foreach ( $rates as $rate_key => $rate ) {
+        if ( $found && strpos($rate_key, '_classique') !== false ) {
+            unset($rates[$rate_key]); 
+        } 
+        elseif (! $found && strpos($rate_key, '_print') !== false ) {
+            unset($rates[$rate_key]);
+        }
+    }
+    return $rates;
+}
+
+

Code goes in functions.php file of the active child theme (or active theme). It should works.

+
+

Clearing shipping caches:

+
    +
  • You will need to empty your cart, to clear cached shipping data
  • +
  • Or In shipping settings, you can disable / save any shipping method, then enable back / save.
  • +
+
+

Related:

+",r +"How to run Git commands in Azure DevOps Server release pipeline using PowerShell tasks (git clone)

I am trying to execute git commands through PowerShell task in an Azure DevOps Server and I am facing authentication issues. More specific the task keep exiting with error code 1, as it asks for username and password. The git commands I am trying to executre are:

+
$wikiUrl = 'https://azure-devops-server/tfs/Common/MainProject/_git/MainProject.wiki'
+git clone $wikiUrl $tmpDirName --depth 1
+
+# Editing files content
+
+git -C $tmpDirName add $statusPageRepoPath
+git -C $tmpDirName commit -m 'update status page'
+git -C $tmpDirName push
+
+

I don't want to add the username and the password as parameters for security reasons. I am interested in making it work with the user credential being retrieved from the execution and not explicitly defined.

+

The recommended from Microsoft solution is to enable in the Agent the option to allow scripts to access the OAuth token. I have enabled this option as it is shown in the picture below, but still, I am getting the same error.

+

+

It looks like that the git clone command cannot access the token and it keeps asking for credentials. I tested also the git checkout and it looks to work ok. The problem is mainly appears to be with the clone command.

","

After a lot of tries and trying different solutions I managed to make it work. As first step, as I mentioned in my question, I enabled the option in the Agent to allow scripts retrieve the OAuth token.

+

+

This doesn't look to be sufficient as it needs also to pass the token in the requests. In order to do this, I applied the following changes:

+
    +
  1. I changed the URL of the repository prior to git clone. The initial URL was this one: +
    $wikiRawUrl = 'https://azure-devops-server/tfs/Common/MainProject/_git/MainProject.wiki'
    +
    +and the new is this one: +
    $wikiRawUrl = 'https://azure-devops-server/tfs/Common/MainProject/_git/MainProject.wiki'
    +$url = "$($wikiRawUrl)".Replace("https://", "")
    +$wikiUrl = "https://$($env:SYSTEM_ACCESSTOKEN)@$url"
    +
    +which adds the access token env:SYSTEM_ACCESSTOKEN in front of the URL of the repository.
  2. +
+
+
    +
  1. I added in extra parameters on my git commands in order to pass the access token again as extra header in them. Furthermore, to ensure that I am not going to have any issues with our local provided certificate, I also explicitly applied the https.sslbackend to schannel (this part was taken from reverse engineering native tasks of Azure DevOps release pipelines). As that, the initial commands were these ones:

    +
    git clone $wikiUrl $tmpDirName --depth 1
    +
    +# Editing files content
    +
    +git -C $tmpDirName add $statusPageRepoPath
    +git -C $tmpDirName commit -m 'update status page'
    +git -C $tmpDirName push 
    +
    +

    and the new ones are these:

    +
    git -c http.extraheader="AUTHORIZATION: bearer $($env:SYSTEM_ACCESSTOKEN)" -c http.sslbackend="schannel" clone $wikiUrl $tmpDirName --depth 1
    +
    +# Editing files content
    +
    +git -C $tmpDirName -c http.extraheader="AUTHORIZATION: bearer $($env:SYSTEM_ACCESSTOKEN)" -c http.sslbackend="schannel" add $statusPageRepoPath
    +git -C $tmpDirName -c http.extraheader="AUTHORIZATION: bearer $($env:SYSTEM_ACCESSTOKEN)" -c http.sslbackend="schannel" commit -m 'update status page'
    +git -C $tmpDirName -c http.extraheader="AUTHORIZATION: bearer $($env:SYSTEM_ACCESSTOKEN)" -c http.sslbackend="schannel" push 
    +
    +
  2. +
+

All the above changes worked well and finally I was able to use git commands without any problem in PowerShell.

",r +"Is the reason I am getting 'NoneType' errors because I don't have a GPU on my laptop when doing opencv / maskrcnn using my webcam?

Running the code below - trying to implement the maskrcnn with opencv and my webcam.

+

When I set PROCESS_IMG = False, the output is fine, shows webcam input as well as FPS (if I set it to false).

+

I tried to comment out the line s = masked_image and below and every 4-5 seconds I would get a refresh of the webcam as well as a proper maskrcnn output overlaid on top (which is what I want).

+

Not assuming I'm going to get 60fps by any means, 0.2fps would be fine.

+
import os
+import sys
+import cv2
+import time
+import imutils
+import numpy as np
+import mrcnn.model as modellib
+from mrcnn import utils, visualize
+from imutils.video import WebcamVideoStream
+import random
+
+# Root directory of the project
+from samples.coco.coco import CocoConfig
+
+ROOT_DIR = os.path.abspath("./")
+
+sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
+
+# Directory to save logs and trained model
+MODEL_DIR = os.path.join(ROOT_DIR, "logs")
+
+# Local path to trained weights file
+COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
+# Download COCO trained weights from Releases if needed
+if not os.path.exists(COCO_MODEL_PATH):
+    utils.download_trained_weights(COCO_MODEL_PATH)
+
+class InferenceConfig(CocoConfig):
+    # Set batch size to 1 since we'll be running inference on
+    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
+    GPU_COUNT = 1
+    IMAGES_PER_GPU = 1
+
+config = InferenceConfig()
+config.display()
+
+# Create model object in inference mode.
+model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
+
+# Load weights trained on MS-COCO
+model.load_weights(COCO_MODEL_PATH, by_name=True)
+
+# COCO Class names
+# Index of the class in the list is its ID. For example, to get ID of
+# the teddy bear class, use: class_names.index('teddy bear')
+class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
+               'bus', 'train', 'truck', 'boat', 'traffic light',
+               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
+               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
+               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
+               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
+               'kite', 'baseball bat', 'baseball glove', 'skateboard',
+               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
+               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
+               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
+               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
+               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
+               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
+               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
+               'teddy bear', 'hair drier', 'toothbrush']
+
+colors = visualize.random_colors(len(class_names))
+
+gentle_grey = (45, 65, 79)
+white = (255, 255, 255)
+
+OPTIMIZE_CAM = True
+SHOW_FPS = False
+SHOW_FPS_WO_COUNTER = False  # faster
+PROCESS_IMG = True
+
+
+if OPTIMIZE_CAM:
+    vs = WebcamVideoStream(src=0).start()
+else:
+    vs = cv2.VideoCapture(0)
+
+if SHOW_FPS:
+    fps_caption = "FPS: 0"
+    fps_counter = 0
+    start_time = time.time()
+
+SCREEN_NAME = 'Mask RCNN LIVE'
+cv2.namedWindow(SCREEN_NAME, cv2.WINDOW_NORMAL)
+cv2.setWindowProperty(SCREEN_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
+
+while True:
+    # Capture frame-by-frame
+    if OPTIMIZE_CAM:
+        frame = vs.read()
+    else:
+        grabbed, frame = vs.read()
+        if not grabbed:
+            break
+    
+    if SHOW_FPS_WO_COUNTER:
+        start_time = time.time() # start time of the loop
+
+    if PROCESS_IMG:    
+        results = model.detect([frame])
+        r = results[0]
+
+        # Run detection
+        masked_image = visualize.display_instances(frame, r['rois'], r['masks'], 
+            r['class_ids'], class_names, r['scores'], colors=colors)
+        
+    if PROCESS_IMG:
+        s = masked_image
+    else:
+        s = frame
+    print("Image shape: {1}x{0}".format(s.shape[0], s.shape[1]))
+
+    width = s.shape[1]
+    height = s.shape[0]
+    top_left_corner = (width-120, height-20)
+    bott_right_corner = (width, height)
+    top_left_corner_cvtext = (width-80, height-5)
+
+    if SHOW_FPS:
+        fps_counter+=1
+        if (time.time() - start_time) > 5 : # every 5 second
+            fps_caption = "FPS: {:.0f}".format(fps_counter / (time.time() - start_time))
+            # print(fps_caption)
+            fps_counter = 0
+            start_time = time.time()
+        ret, baseline = cv2.getTextSize(fps_caption, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
+        cv2.rectangle(s, (width - ret[0], height - ret[1] - baseline), bott_right_corner, gentle_grey, -1)
+        cv2.putText(s,fps_caption, (width - ret[0], height - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.5, white, lineType=cv2.LINE_AA)
+
+    if SHOW_FPS_WO_COUNTER:
+        # Display the resulting frame
+        fps_caption = "FPS: {:.0f}".format(1.0 / (time.time() - start_time))
+        # print("FPS: ", 1.0 / (time.time() - start_time))
+        
+        # Put the rectangle and text on the bottom left corner
+        ret, baseline = cv2.getTextSize(fps_caption, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
+        cv2.rectangle(s, (width - ret[0], height - ret[1] - baseline), bott_right_corner, gentle_grey, -1)
+        cv2.putText(s, fps_caption, (width - ret[0], height - baseline),
+                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, white, 1, lineType=cv2.LINE_AA)
+
+    
+    s = cv2.resize(s,(1920,1080))
+    cv2.imshow(SCREEN_NAME, s)
+    cv2.waitKey(1)
+    if cv2.waitKey(1) & 0xFF == ord('q'): break
+    
+# When everything done, release the capture
+if OPTIMIZE_CAM:
+    vs.stop()
+else:
+    vs.release()
+cv2.destroyAllWindows()
+
+

Error:

+
AttributeError                            Traceback (most recent call last)
+<ipython-input-1-d3debbeb3ebd> in <module>
+    109     else:
+    110         s = frame
+--> 111     print("Image shape: {1}x{0}".format(s.shape[0], s.shape[1]))
+    112 
+    113     width = s.shape[1]
+
+AttributeError: 'NoneType' object has no attribute 'shape'
+
+

If I add this code in, I get an image with the correct mask:

+
file_names = next(os.walk(IMAGE_DIR))[2]
+image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
+
+start = time.time()
+# Run detection
+results = model.detect([image], verbose=1)
+end = time.time()
+print("Time:",end-start,"seconds")
+
+# Visualize results
+r = results[0]
+visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
+                            class_names, r['scores'])
+
","

I made a function that solves my problem:

+
def save_image(image, image_name, boxes, masks, class_ids, scores, class_names, filter_classs_names=None,
+               scores_thresh=0.1, save_dir=None, mode=0):
+    """
+        image: image array
+        image_name: image name
+        boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
+        masks: [num_instances, height, width]
+        class_ids: [num_instances]
+        scores: confidence scores for each box
+        class_names: list of class names of the dataset
+        filter_classs_names: (optional) list of class names we want to draw
+        scores_thresh: (optional) threshold of confidence scores
+        save_dir: (optional) the path to store image
+        mode: (optional) select the result which you want
+                mode = 0 , save image with bbox,class_name,score and mask;
+                mode = 1 , save image with bbox,class_name and score;
+                mode = 2 , save image with class_name,score and mask;
+                mode = 3 , save mask with black background;
+    """
+    mode_list = [0, 1, 2, 3]
+    assert mode in mode_list, "mode's value should in mode_list %s" % str(mode_list)
+
+    if save_dir is None:
+        save_dir = os.path.join(os.getcwd(), "output")
+        if not os.path.exists(save_dir):
+            os.makedirs(save_dir)
+
+    useful_mask_indices = []
+
+    N = boxes.shape[0]
+    if not N:
+        print("\n*** No instances in image %s to draw *** \n" % (image_name))
+        return
+    else:
+        assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]
+
+    for i in range(N):
+        # filter
+        class_id = class_ids[i]
+        score = scores[i] if scores is not None else None
+        if score is None or score < scores_thresh:
+            continue
+
+        label = class_names[class_id]
+        if (filter_classs_names is not None) and (label not in filter_classs_names):
+            continue
+
+        if not np.any(boxes[i]):
+            # Skip this instance. Has no bbox. Likely lost in image cropping.
+            continue
+
+        useful_mask_indices.append(i)
+
+    if len(useful_mask_indices) == 0:
+        print("\n*** No instances in image %s to draw *** \n" % (image_name))
+        return
+
+    colors = random_colors(len(useful_mask_indices))
+
+    if mode != 3:
+        masked_image = image.astype(np.uint8).copy()
+    else:
+        masked_image = np.zeros(image.shape).astype(np.uint8)
+
+    if mode != 1:
+        for index, value in enumerate(useful_mask_indices):
+            masked_image = visualize.apply_mask(masked_image, masks[:, :, value], colors[index])
+
+    masked_image = Image.fromarray(masked_image)
+
+    if mode == 3:
+        masked_image.save(os.path.join(save_dir, '%s.jpg' % (image_name)))
+        return
+
+    draw = ImageDraw.Draw(masked_image)
+    colors = np.array(colors).astype(int) * 255
+
+    for index, value in enumerate(useful_mask_indices):
+        class_id = class_ids[value]
+        score = scores[value]
+        label = class_names[class_id]
+
+        y1, x1, y2, x2 = boxes[value]
+        if mode != 2:
+            color = tuple(colors[index])
+            draw.rectangle((x1, y1, x2, y2), outline=color)
+
+        # Label
+        #font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15)
+        draw.text((x1, y1), "%s %f" % (label, score), (255, 255, 255))
+
+    masked_image.save(os.path.join(save_dir, '%s.jpg' % (image_name)))
+
",r +"R markdown adds # link behind HTML headers

I've been trying to solve some HTML knitting issues. My HTML does not currently allow me to use HTML in the code, and thus I am unable to create tabsets.

+

However, while trying to solve that issue a new issue occured: My HTML output adds a clickable # behind each # Header.

+

I use the basic Rmarkdown format:

+
---
+title: "Try"
+output: html_document
+---
+
+/```{r setup, include=FALSE}
+knitr::opts_chunk$set(echo = TRUE)
+/```
+
+## R Markdown
+
+This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
+
+When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
+
+## Including Plots
+
+
+

And then the output shows me this:

+

+

Anyway have any idea how to solve this?

","

This is a new feature introduced in the current development version of rmarkdown. See the NEWS file for more info. To disable this feature, you may use:

+
output:
+  html_document:
+    anchor_sections: false
+
",r +"Html input field not registring on first click

I am having issues with begin date field. the first time that the page loads, if you click on the begin date field the calender is not poping up, however if I click on any other field/label and than click back on begin date field, it works just fine. I have tried the following with no success:

+

1- I have tried using onclick and onchange to invoke the js function +2- I have tird adding a listener on page load to the beginDate element. +3- Tried moving focuse to another element on page load.

+

+
+
var tripsByCategory = {
+    1: [""3"", ""5""],
+    2: [""2"", ""3"", ""4""],
+    3: [""5"", ""7""]
+}
+
+function changecat(value) {
+    if (value.length == 0) document.getElementById(""duration"").innerHTML = ""<option></option>"";
+    else {
+        var catOptions = """";
+        for (categoryId in tripsByCategory[value]) {
+            catOptions += ""<option>"" + tripsByCategory[value][categoryId] + ""</option>"";
+        }
+        document.getElementById(""duration"").innerHTML = catOptions;
+    }
+}
+
+function datePicker() {
+
+    $('#beginDate').datepicker({dateFormat: ""yy-mm-dd""}); 
+
+}
+
+
+function clearPage() {
+     var form = document.getElementById(""costForm"");
+     form.onsubmit = form.reset(); 
+     document.addEventListener(""click"", function() {
+         datePicker();
+        //alert(""yay"");
+        }, true);
+
+        document.getElementById(""beginDate"").addEventListener(""click"", function() {
+            datePicker();
+        }, false);
+}
+
body{
+background-color: #7fc7d6;
+}
+
+.sectionTitle{
+    text-align: center;
+}
+.column3 {
+  float: left;
+  width: 100%;
+  padding: 2px;
+}
+    
+.row::after {
+  display: table;
+}
+
<!DOCTYPE html>
+<html>
+<head>
+<meta http-equiv=""Content-Type"" content=""text/html"" charset=""utf-8"">
+<title>test</title>
+<link href=""style.css"" rel=""stylesheet"" type=""text/css"" />
+<script src=""index.js""></script>
+<link href= 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css'  rel='stylesheet'> 
+<script src= ""https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"">  </script> 
+<script src=  ""https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"">  </script> 
+</head>
+<body onLoad=""clearPage()"">
+
+    <div class=""row"">
+        <h2 class=""column3"">!Testing</h2>
+        <form action=""http://localhost:8080//places"" method=GET id=""costForm"">
+            <div class=""column3"">
+                <label for=""numberOfPeople"">Number of Travelers:</label>
+                <input type=""number"" id=""numberOfPeople"" name=""numberOfPeople"" min=""1"" max=""10"" required />
+            </div>
+            
+            <div class=""column3"">
+                <label for=""beginDate"">Begin Date:</label>
+                <input type=""text"" name=""beginDate"" id=""beginDate"" value=""YYYY-MM-DD"" required />
+            </div>      
+            <div class=""column3"">
+                <label for=""hikeOption"">Choose a Destenation:</label>
+                <select name=""hikeOption"" id=""hikeOption"" onclick=""changecat(this.value);"" required >
+                    <option value="""" disabled selected>Select</option>
+                    <option value=""1"">1</option>
+                    <option value=""2"">2</option>
+                    <option value=""3"">3</option>
+                </select>
+            </div>
+                <div class=""column3"">
+                <label for=""duration"">Choose a Duration:</label>
+                <select name=""duration"" id=""duration"" required>
+                    <option value="""" disabled selected>Select</option>
+                </select>
+            </div>
+            <div class=""column3"">
+                <input type=""SUBMIT"" value=""Get Total Cost"">
+            </div>
+        </form>
+    </div>
+
+</body>
+</html>
+
+
+

","

Use the Event mousedown instead, that solve the issue. This is a common issue not related to jquery. But it might not work flawlessly on mobiles, you will have to add touch events as well, see https://developer.mozilla.org/en-US/docs/Web/API/Touch_events.

+

+
+
var tripsByCategory = {
+    1: [""3"", ""5""],
+    2: [""2"", ""3"", ""4""],
+    3: [""5"", ""7""]
+}
+
+function changecat(value) {
+    if (value.length == 0) document.getElementById(""duration"").innerHTML = ""<option></option>"";
+    else {
+        var catOptions = """";
+        for (categoryId in tripsByCategory[value]) {
+            catOptions += ""<option>"" + tripsByCategory[value][categoryId] + ""</option>"";
+        }
+        document.getElementById(""duration"").innerHTML = catOptions;
+    }
+}
+
+function datePicker() {
+
+    $('#beginDate').datepicker({dateFormat: ""yy-mm-dd""}); 
+
+}
+
+
+function clearPage() {
+     var form = document.getElementById(""costForm"");
+     form.onsubmit = form.reset();
+       document.getElementById(""beginDate"").addEventListener(""mousedown"", function() {
+            datePicker();
+        }, false);
+}
+
body{
+background-color: #7fc7d6;
+}
+
+.sectionTitle{
+    text-align: center;
+}
+.column3 {
+  float: left;
+  width: 100%;
+  padding: 2px;
+}
+    
+.row::after {
+  display: table;
+}
+
<!DOCTYPE html>
+<html>
+<head>
+<meta http-equiv=""Content-Type"" content=""text/html"" charset=""utf-8"">
+<title>test</title>
+<link href=""style.css"" rel=""stylesheet"" type=""text/css"" />
+<script src=""index.js""></script>
+<link href= 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css'  rel='stylesheet'> 
+<script src= ""https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"">  </script> 
+<script src=  ""https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"">  </script> 
+</head>
+<body onLoad=""clearPage()"">
+
+    <div class=""row"">
+        <h2 class=""column3"">!Testing</h2>
+        <form action=""http://localhost:8080//places"" method=GET id=""costForm"">
+            <div class=""column3"">
+                <label for=""numberOfPeople"">Number of Travelers:</label>
+                <input type=""number"" id=""numberOfPeople"" name=""numberOfPeople"" min=""1"" max=""10"" required />
+            </div>
+            
+            <div class=""column3"">
+                <label for=""beginDate"">Begin Date:</label>
+                <input type=""text"" name=""beginDate"" id=""beginDate"" value=""YYYY-MM-DD"" required />
+            </div>      
+            <div class=""column3"">
+                <label for=""hikeOption"">Choose a Destenation:</label>
+                <select name=""hikeOption"" id=""hikeOption"" onclick=""changecat(this.value);"" required >
+                    <option value="""" disabled selected>Select</option>
+                    <option value=""1"">1</option>
+                    <option value=""2"">2</option>
+                    <option value=""3"">3</option>
+                </select>
+            </div>
+                <div class=""column3"">
+                <label for=""duration"">Choose a Duration:</label>
+                <select name=""duration"" id=""duration"" required>
+                    <option value="""" disabled selected>Select</option>
+                </select>
+            </div>
+            <div class=""column3"">
+                <input type=""SUBMIT"" value=""Get Total Cost"">
+            </div>
+        </form>
+    </div>
+
+</body>
+</html>
+
+
+

",r +"How do I get the Name of Keyboard sending key events?
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
+val enabledInputMethodList = imm.enabledInputMethodList
+
+

In the above snippet, I'm able to get the enabled Keyboards in my device. But I would like to know specifically which keyboard( Gboard or Microsoft SwiftKey) is sending the event

","

See this answer: https://stackoverflow.com/a/14371088/6591585

+

It tells you the default keyboard app. While it doesn't say which keyboard is being used to input the text, chances are it's the same as the default.

",r +"Beautiful Soup - urllib.error.HTTPError: HTTP Error 403: Forbidden

I am trying to download a GIF file with urrlib, but it is throwing this error:

+
urllib.error.HTTPError: HTTP Error 403: Forbidden
+
+

This does not happen when I download from other blog sites. This is my code:

+
import requests
+import urllib.request
+
+url_1 = 'https://goodlogo.com/images/logos/small/nike_classic_logo_2355.gif'
+
+source_code = requests.get(url_1,headers = {'User-Agent': 'Mozilla/5.0'})    
+
+path = 'C:/Users/roysu/Desktop/src_code/Python_projects/python/web_scrap/myPath/'
+
+full_name = path + ".gif"    
+urllib.request.urlretrieve(url_1,full_name)
+
","

Don't use urllib.request.urlretrieve. Instead, use the requests library like this:

+
import requests
+
+url = 'https://goodlogo.com/images/logos/small/nike_classic_logo_2355.gif'
+
+path = "D:\\Test.gif"
+
+response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
+
+file = open(path, "wb")
+
+file.write(response.content)
+
+file.close()
+
+

Output:

+

+

Hope that this helps!

",r +"Passing a string to navigation.navigate

I'm trying to set a menu and I'm trying to pass the path to navigation.navigate as navigation.navigate(menu.path) but it doesn't allow me to pass the route in that way.

+

So I create the item here with the path as selections.name

+
    export default function Menu_1({ navigation }) {
+      const [selections, setSelections] = useState([
+        { title: 'Normas de utilización de la App', key:'1' , name:'Normas'},
+        { title: 'Zonas maritimas', key:'2'}
+      ]) 
+
+
+

When I try to pass that path to navigation.navigate it doesn't allow to me unless I use Navigation.navigate('Normas')

+
     return (
+            <View style={globalStyles.container}>
+              <FlatList
+                data={selections}
+                renderItem={({ item })=>(
+                  <TouchableOpacity onPress={() => navigation.navigate()}>
+                    <Card>
+                      <Image
+                      style={{ 
+                        width: 100, 
+                        height: 50,
+                      }} 
+                      source={images.images_menu[item.key]} />
+                      <Text style={globalStyles.titleCard}> {item.title} </Text>
+                    </Card>
+                  </TouchableOpacity>
+                  
+                )}
+              />
+            </View>     
+        )   
+    }
+
+
+

is there a way to pass the string from selections.name to navigation.navigate?

","

If I understood this correctly, you can access the selections.name in the item param of your renderItem prop, like this:

+
 return (
+        <View style={globalStyles.container}>
+          <FlatList
+            data={selections}
+            renderItem={({ item })=>(
+              <TouchableOpacity onPress={() => navigation.navigate(item.name)}> // item.name
+                <Card>
+                  <Image
+                  style={{ 
+                    width: 100, 
+                    height: 50,
+                  }} 
+                  source={images.images_menu[item.key]} />
+                  <Text style={globalStyles.titleCard}> {item.title} </Text>
+                </Card>
+              </TouchableOpacity>
+              
+            )}
+          />
+        </View>     
+    )
+
+

You can also switch this to whatever you want, navigate(item.key), navigate(item.foo). Just make sure you are keeping the values here

+
const [selections, setSelections] = useState([
+        { title: 'Normas de utilización de la App', key:'1' , name:'Normas'},
+        { title: 'Zonas maritimas', key:'2', name: 'Foo'} // missing name
+      ]) 
+
",r +"MySQL turns itself off after discord bot left on for about 12 hours

I'm hosting a discord.js bot on an ubuntu VPS, and the bot uses MySQL as its database. I turn on the bot, and leave it, and it works fine, but after about 12 hours (it tends to vary), the bot goes offline, because of an error, saying MySQL server disconnected. But, if I restart the bot, MySQL turns back on, and bits of the bot that require the database use the database perfectly fine. I'm not sure if this is an error with MySQL, Node.JS or Ubuntu, but I don't know how to fix it. Thanks!

","

I had a similar issue when I started using MySQL. The problem is that your bot crashes when it encounters a connection timeout. The MySQL server doesn't go offline, just your connection to it does. Meaning that when you restart your bot it reconnects and everything works.

+

I encountered two ways of getting around the issue of having to restart the bot manually.

+
    +
  • Set up your bot so that it restarts automatically when it encounters a critical error. (Not really the best option but if you want to do it that way it works)

    +
  • +
  • Create a connection pool.

    +
  • +
+

This is by far the better option. It will create a pool of connections ready to go. When you need a connection it will provide you with one and release it after you are done. That way your connection won't time out.

+

It works like this:

+
const mysql = require('mysql');
+
+var db_config = {
+ user: 'root',
+ password: 'Your password',
+ database: 'Your database',
+ // etc
+};
+
+var con = mysql.createPool(db_config);
+
+con.getConnection(function(err, con) {
+ if (err) {
+  connection.release();
+  console.log(' Error getting mysql_pool connection: ' + err);
+  throw err;
+ }
+ console.log('Connected to Database');
+});
+
",r +"How to make changes in the react webpage in github pages?

I had deployed me react webpage successfully in the main branch. There are my main source files, take a look Main branch. And after deployment, branch gh-pages has all necessary files containing like a static folder and all... take a look here gh-pages branch.

+

But whenever I change in the main branch, it does not reflect the webpage. Is there any way to push all my changes??

+

I am unable to push changes to the gh-pages branch as I am afraid because it is having totally different files.

+

How can I do these changes??

+

I had followed these git commands, but it didn't work

+
$ git add .
+$ git status // to see what changes are going to be commited
+$ git commit -m 'Some descriptive commit message'
+$ git push origin master
+
+$ git checkout gh-pages // go to the gh-pages branch
+$ git rebase master // bring gh-pages up to date with master
+$ git push origin gh-pages // commit the changes
+$ git checkout master // return to the master branch
+
+

Referred from here

+

Thanks in advance...

","

Make sure you have these scripts in your package.json file, then you can just run npm run deploy

+
"scripts": {
+//...
+"predeploy": "npm run build",
+"deploy": "gh-pages -d build"
+}
+
",r +"Amazon cognito basic functionality questions

I am making an app and I have a few questions about Amazon Cognito:

+
    +
  1. I read that when you sign in to Cognito it returns a JWT token consisting of: ID token, access token, and refresh token. My first question is, where do I save these tokens in my app so the user can continue to be logged in and doesn't have to log in ever time? Do I save it in a state or in a cookie etc or somewhere else? I don't understand this.

    +
  2. +
  3. How do I use the JWT to make authenticated api requests?

    +
  4. +
  5. How do I refresh a JWT behind the scenes so a user can stay signed in? This isn't clear to me in the documentation. Once the JWT expires, how does can the user remain logged in without having to sign in every time?

    +
  6. +
+

Thanks!

","

My understanding is as follows. The choice of storage is important because you want to prevent cross-site scripting (XSS) and cross-site request forgery (CSRF). Always use HTTPS, naturally.

+
    +
  1. Store in memory, or in an HttpOnly cookie, or in a session cookie (in descending order of preference), but not in HTML5 web storage
  2. +
  3. Send the JWT in the HTTP Authorization header using the Bearer schema (see below)
  4. +
  5. See JWT refresh token flow
  6. +
+

The content of the header looks like:

+
Authorization: Bearer <token>
+
+

A few recommended sites:

+",r +"how to merge small dataframes into a large without copy

I have a large pandas dataframe, and want to merge a couple smaller dataframes into it, thus adding more columns. However, it seems there is an implicit of copy of the large dataframe after each merge, which I want to avoid. What's the most efficient way to do this? (Note the resulting dataframe will have the same rows, as it is growing with more columns.) map seems better, as it keeps the original dataframe, but there is overhead to create dictionary. Also not sure it works with merging multiple col into the main one. Or maybe the merge may not be deep copying everything internally?

+

Base case:

+
id(df)  # before merge
+
+df = df.merge(df1[["sid", "col1"]], how="left", on=["sid"])
+id(df)  # will be different  <-- trying to avoid copying df every time a smaller one merged into it
+
+df = df.merge(df2[["sid", "col2"]], how="left", on=["sid", "key2"])
+id(df)  # will be different   
+...
+
+

Using map():

+
d_col1 = {d["sid"]:d["col1"] for d in df1[["sid", "col1"]].to_dict("records")}
+df["col1"] = df["sid"].map(d_col1)
+id(df) # this is the same object
+
+

Some post referred dask, haven't tested that yet.

","

here is another way. First map can be done with a Series and as df1 is already built, I don't know if it is less efficient than using a dictionary though.

+
df["col1"] = df["sid"].map(df1.set_index('sid')['col1']) 
+
+

Now with two or more columns, you can play with index

+
df['col2'] = (
+    df2.set_index(['sid','key2'])['col2']
+       .reindex(pd.MultiIndex.from_frame(df[['sid','key2']]))
+       .to_numpy()
+)
+
",r +"Cannot find conda info. Please verify your conda installation on EMR

I am trying to install conda on EMR and below is my bootstrap script, it looks like conda is getting installed but it is not getting added to environment variable. When I manually update the $PATH variable on EMR master node, it can identify conda. I want to use conda on Zeppelin.

+

I also tried adding condig into configuration like below while launching my EMR instance however I still get the below mentioned error.

+
    "classification": "spark-env",
+    "properties": {
+        "conda": "/home/hadoop/conda/bin"
+    }
+
+
[hadoop@ip-172-30-5-150 ~]$ PATH=/home/hadoop/conda/bin:$PATH
+[hadoop@ip-172-30-5-150 ~]$ conda
+usage: conda [-h] [-V] command ...
+
+conda is a tool for managing and deploying applications, environments and packages.
+
+
#!/usr/bin/env bash
+
+
+# Install conda
+wget https://repo.continuum.io/miniconda/Miniconda3-4.2.12-Linux-x86_64.sh -O /home/hadoop/miniconda.sh \
+    && /bin/bash ~/miniconda.sh -b -p $HOME/conda
+
+
+conda config --set always_yes yes --set changeps1 no
+conda install conda=4.2.13
+conda config -f --add channels conda-forge
+rm ~/miniconda.sh
+echo bootstrap_conda.sh completed. PATH now: $PATH
+export PYSPARK_PYTHON="/home/hadoop/conda/bin/python3.5"
+
+echo -e '\nexport PATH=$HOME/conda/bin:$PATH' >> $HOME/.bashrc && source $HOME/.bashrc
+
+
+conda create -n zoo python=3.7 # "zoo" is conda environment name, you can use any name you like.
+conda activate zoo
+sudo pip3 install tensorflow
+sudo pip3 install boto3
+sudo pip3 install botocore
+sudo pip3 install numpy
+sudo pip3 install pandas
+sudo pip3 install scipy
+sudo pip3 install s3fs
+sudo pip3 install matplotlib
+sudo pip3 install -U tqdm
+sudo pip3 install -U scikit-learn
+sudo pip3 install -U scikit-multilearn
+sudo pip3 install xlutils
+sudo pip3 install natsort
+sudo pip3 install pydot
+sudo pip3 install python-pydot
+sudo pip3 install python-pydot-ng
+sudo pip3 install pydotplus
+sudo pip3 install h5py
+sudo pip3 install graphviz
+sudo pip3 install recmetrics
+sudo pip3 install openpyxl
+sudo pip3 install xlrd
+sudo pip3 install xlwt
+sudo pip3 install tensorflow.io
+sudo pip3 install Cython
+sudo pip3 install ray
+sudo pip3 install zoo
+sudo pip3 install analytics-zoo
+sudo pip3 install analytics-zoo[ray]
+#sudo /usr/bin/pip-3.6 install -U imbalanced-learn
+
+
+
+

","

I got the conda working by modifying the script as below, emr python versions were colliding with the conda version.:

+
wget https://repo.anaconda.com/miniconda/Miniconda3-py37_4.9.2-Linux-x86_64.sh  -O /home/hadoop/miniconda.sh \
+    && /bin/bash ~/miniconda.sh -b -p $HOME/conda
+
+echo -e '\n export PATH=$HOME/conda/bin:$PATH' >> $HOME/.bashrc && source $HOME/.bashrc
+
+
+conda config --set always_yes yes --set changeps1 no
+conda config -f --add channels conda-forge
+
+
+conda create -n zoo python=3.7 # "zoo" is conda environment name
+conda init bash
+source activate zoo
+conda install python 3.7.0 -c conda-forge orca 
+sudo /home/hadoop/conda/envs/zoo/bin/python3.7 -m pip install virtualenv
+
+

and setting zeppelin python and pyspark parameters to:

+
“spark.pyspark.python": "/home/hadoop/conda/envs/zoo/bin/python3",
+"spark.pyspark.virtualenv.enabled": "true",
+"spark.pyspark.virtualenv.type":"native",
+"spark.pyspark.virtualenv.bin.path":"/home/hadoop/conda/envs/zoo/bin/,
+"zeppelin.pyspark.python" : "/home/hadoop/conda/bin/python",
+"zeppelin.python": "/home/hadoop/conda/bin/python"
+
+

Orca only support TF upto 1.5 hence it was not working as I am using TF2.

",r +"Use tsc without npm install -g

I'm working on a project that I have to give to some guys. +The project is in typescript and so they have to run the command tsc to compile.

+

The problem is when I run this command after doing npm install typescript it seem that the command doesn't exist but if I install with the -g option then it works.

+

But I really would like the possibility to the futur owner of the project to just have to run npm install without installing dependencies on his computer.

+

But is it even possible ?

+

btw I'm on ubuntu 20

+

Thanks !

","

npm install typescript installs it locally to the project. I would go further and add --save-dev so it only gets listed under devDependencies, not dependencies.

+

You can still run TypeScript in that situation. Your best bet is to add entries to the "scripts" key in package.json, like this:

+
{
+    "name": "blah",
+    "version": "1.0.0",
+    "description": "...",
+    "scripts": {
+        "build": "tsc command arguments go here"
+    },
+    "keywords": [],
+    "author": "...",
+    "license": "...",
+    "devDependencies": {
+        "typescript": "^4.5.5"
+    }
+}
+
+

Then you run that command via:

+
+npm run build
+
+

Node.js will find tsc in node_modules and run it.

",r +"Snowflake scripting set variable in if statment

In Snowflake I trying to set a variable to different values depend on input to the procedure.

+

When I read about the if statment here: +https://docs.snowflake.com/en/developer-guide/snowflake-scripting/branch.html

+

I can't figure out how to use the input type_name to set a new variable or overwrite the query variable if type_name have a specific value, any ideas?

+
create or replace procedure test_sp_dynamic(table_name varchar,type_name varchar)
+returns table(X varchar)
+language sql
+as
+$$
+  declare
+    tn varchar default :type_name;
+    tn_2 varchar;
+    res RESULTSET;
+    query varchar default 'SELECT Y ' || :table_name || ' ORDER BY Y';
+  begin
+   
+    res := (execute immediate :query);
+    return table (res);
+  end;
+$$
+;
+
+
","

The question is vague. It is possible to overwrite the query defined in DECLARE block.

+

Test table:

+
CREATE OR REPLACE TABLE t(Y VARCHAR, Z VARCHAR)
+AS SELECT 1, 2 UNION ALL SELECT 10,20;
+
+

Procedure:

+
create or replace procedure test_sp_dynamic(table_name varchar,type_name varchar)
+returns table(X varchar)
+language sql
+as
+$$
+declare
+    res RESULTSET;
+    query VARCHAR;
+begin
+    if (:type_name = 'some_value') then
+        query := 'SELECT Z FROM ' || :table_name || ' ORDER BY Z';
+    else
+        query := 'SELECT Y FROM ' || :table_name || ' ORDER BY Y';
+    end if;
+   
+    res := (execute immediate :query);
+    return table(res);
+end;
+$$
+;
+
+CALL test_sp_dynamic('t', 'some_value');
+-- X
+-- 2
+-- 20
+
+CALL test_sp_dynamic('t', 'else');
+-- X
+-- 1
+-- 10
+
",r +"Difference between .resumeWith(Result.failure(...)) and .resumeWithException

I might be missing some fundamental understanding of coroutines and continuations in Kotlin, but I couldn't find any information on the difference between

+
Continuation<T>.resumeWith(Result.failure(/* some exception */))
+// and
+Continuation<T>.resumeWithException(/* some exception */)
+
+

and the same for

+
Continuation<T>.resumeWith(Result.success(/* some value */))
+// and
+Continuation<T>.resume(/* some value */)
+
+

When should which one be used and why?

","

It requires just a quick look at the source: +

+

And yeah you are right it's exactly the same. The only difference is the amount of code you have to write

",r +"unable to initialize snowflake data source

I am trying to access the snowflake datasource using "great_expectations" library.

+

The following is what I tried so far:

+
from ruamel import yaml
+
+import great_expectations as ge
+from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest
+
+context = ge.get_context()
+
+
+
+datasource_config = {
+    "name": "my_snowflake_datasource",
+    "class_name": "Datasource",
+    "execution_engine": {
+        "class_name": "SqlAlchemyExecutionEngine",
+        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
+    },
+    "data_connectors": {
+        "default_runtime_data_connector_name": {
+            "class_name": "RuntimeDataConnector",
+            "batch_identifiers": ["default_identifier_name"],
+        },
+        "default_inferred_data_connector_name": {
+            "class_name": "InferredAssetSqlDataConnector",
+            "include_schema_name": True,
+        },
+    },
+}
+
+print(context.test_yaml_config(yaml.dump(datasource_config)))
+
+
+

I initiated great_expectation before executing above code:

+
great_expectations init
+
+

but I am getting the error below:

+
great_expectations.exceptions.exceptions.DatasourceInitializationError: Cannot initialize datasource my_snowflake_datasource, error: 'NoneType' object has no attribute 'create_engine'
+
+
+

What am I doing wrong?

","

Your configuration seems to be ok, corresponding to the example here.

+

If you look at the traceback you should notice that the error propagates starting at the file great_expectations/execution_engine/sqlalchemy_execution_engine.py in your virtual environment.

+

The actual line where the error occurs is:

+
            self.engine = sa.create_engine(connection_string, **kwargs)
+
+

And if you search for that sa at the top of that file:

+
import sqlalchemy as sa
+
+make_url = import_make_url()
+except ImportError:
+        sa = None
+
+

So sqlalchemy is not installed, which you +don't get automatically in your environement if you install greate_expectiations. The thing to do is to +install snowflake-sqlalchemy, since you want to use sqlalchemy's snowflake +plugin (assumption based on your connection_string).

+
/your/virtualenv/bin/python -m pip install snowflake-sqlalchemy
+
+

After that you should no longer get an error, it looks like test_yaml_config is waiting for the connection +to time out.

+

What worries me greatly is the documented use of a deprecated API of ruamel.yaml. +The function ruamel.yaml.dump is going to be removed in the near future, and you +should use the .dump() method of a ruamel.yaml.YAML() instance.

+

You should use the following code instead:

+
import sys
+from ruamel.yaml import YAML
+
+import great_expectations as ge
+context = ge.get_context()
+
+datasource_config = {
+    "name": "my_snowflake_datasource",
+    "class_name": "Datasource",
+    "execution_engine": {
+        "class_name": "SqlAlchemyExecutionEngine",
+        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
+    },
+    "data_connectors": {
+        "default_runtime_data_connector_name": {
+            "class_name": "RuntimeDataConnector",
+            "batch_identifiers": ["default_identifier_name"],
+        },
+        "default_inferred_data_connector_name": {
+            "class_name": "InferredAssetSqlDataConnector",
+            "include_schema_name": True,
+        },
+    },
+}
+
+yaml = YAML()
+
+yaml.dump(datasource_config, sys.stdout, transform=context.test_yaml_config)
+
+

I'll make a PR for great-excpectations to update their documentation/use of ruamel.yaml.

",r +"Change Plotly scatter plot color

I am trying to visualize a 4-class dataset via plotly.

+

For the following code : +fig = px.scatter_3d(df_pca, x='pca1', y='pca2', z='pca3', color = 'emotion')

+

I get the below graph which is not convenient to understand because the "blue" and "purple" colors are "indiscernible".

+

So I would like to change the "purple" color to "yellow". Could you please advise how to do it in plotly? The documentation does not seem very helpful.

+

","

I found this color_discrete_sequence parameter in the documentation, perhaps it can help you https://plotly.com/python/discrete-color/#explicitly-constructing-a-color-sequence

+
import plotly.express as px
+df = px.data.gapminder().query("year == 2007")
+fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
+             color_discrete_sequence=["red", "green", "blue", "goldenrod", "magenta"],
+             title="Explicit color sequence"
+            )
+
+fig.show()
+
+

",r +"HTML Unescape is not unescaping special characters

My program does not unescape the HTML special characters for quotes and I can't figure out why. It still displays the special characters in the Terminal.

+

For example: 'In the comic book &quot;Archie&quot;

+
import requests
+import html
+
+API_URL = "https://opentdb.com/api.php"
+
+parameters = {
+    "amount": 10,
+    "type": "boolean"
+}
+
+response = requests.get(API_URL, params=parameters)
+data = html.unescape(response.json())
+unescaped_data = data["results"]
+print(f"UNESCAPED DATA: {unescaped_data}") # THIS IS NOT WORKING
+
","

The result isn't unescaped because response.json() returns a JSON object (i.e. a dict) and not a string. If you wanted to, you could unescape the response string using html.unescape(response.text) but this will leave you with invalid JSON, e.g.: "question":""Windows NT" is a monolithic kernel.", (note the additional quotes). So the escaping is there for a reason and you will have to unescape only those parts that you really need, that is, the string components of your JSON object.

",r +"How to implement JWT authorization header in swagger docs in Express/JavaScript

I am trying to add the following configuration to my swagger.config.ts:

+
const swaggerUiOptions = {
+  explorer: true,
+  swaggerOptions: {
+    authAction: {
+      JWT: {
+        name: 'JWT',
+        schema: {
+          type: 'apiKey',
+          in: 'header',
+          name: 'Authorization',
+          description: ''
+        },
+        value: 'Bearer <JWT token here>'
+      }
+    }
+  }
+};
+
+

Then below this, I have:

+
app.use('/api-docs', swaggerUi.serve, swaggerUI.setup(swaggerSpec, swaggerUiOptions));
+
+

However, the Authorize button that I am expecting to see does not appear in the UI. I am not sure if there is something in the whole configuration file that may be clobbering what I added, since I did not write the whole thing, here it is:

+
import express from 'express';
+import { Model } from "mongoose";
+import swaggerJsdoc from "swagger-jsdoc";
+import swaggerUi from "swagger-ui-express";
+import m2s from 'mongoose-to-swagger';
+import { readFileSync } from 'fs';
+
+class SwaggerEndPointInformationDto {
+readonly httpMethod: string
+readonly httpPath: string
+
+constructor(httpMethod: string, httpPath: string) {
+this.httpMethod = httpMethod;
+this.httpPath = httpPath
+}
+}
+
+class SwaggerConfig {
+// private readonly app: express.Application;
+private built = false;
+private static instance: SwaggerConfig;
+private models = Array<Model<any>>();
+
+public static getInstance() {
+if (!this.instance) {
+this.instance = new SwaggerConfig();
+}
+return this.instance;
+}
+
+registerModel(model: Model<any>) {
+this.checkIsNotBuilt();
+this.models.push(model);
+}
+
+// addPathAndMethod()
+
+registerSwaggerPage(app: express.Application, listeners: [(entry: SwaggerEndPointInformationDto) => void]) {
+// registerSwaggerPage(app: express.Application) {
+this.built = true;
+
+const packageJson = JSON.parse(readFileSync('./package.json').toString());
+const swaggerOptions = {
+definition: {
+openapi: '3.0.0',
+info: {
+title: packageJson.name,
+version: packageJson.version,
+}
+},
+apis: [
+'./dist/**/*.js',
+],
+};
+// const swaggerSpec: {paths: never;} = swaggerJsdoc(swaggerOptions);
+// @ts-ignore
+const swaggerSpec: { paths: string; } = swaggerJsdoc(swaggerOptions);
+
+const swaggerUiOptions = {
+explorer: true,
+swaggerOptions: {
+authActions: {
+JWT: {
+name: 'JWT',
+schema: {
+type: 'apiKey',
+in: 'header',
+name: 'Authorization',
+description: ''
+},
+value: 'Bearer <JWT Token here>'
+}
+}
+}
+};
+
+// add to components.schemas
+this.models.forEach(model => {
+const swaggerModel = m2s(model)
+// @ts-ignore
+swaggerSpec.components.schemas.push(swaggerModel);
+});
+
+// add routes
+app._router.stack.filter((e: { route: never; }) => e.route).forEach((element: any) => {
+console.log(element)
+// if (element?.route?.path?.startsWith('/')) {
+//   const httpPath: string = element.route.path
+//   // @ts-ignore
+//   if (!swaggerSpec.paths[httpPath]) {
+//     // @ts-ignore
+//     swaggerSpec.paths[httpPath] = {}
+//   }
+//   // @ts-ignore
+//   const pathInfo = swaggerSpec.paths[httpPath];
+//   for (const e in Object.keys(element.route.methods)) {
+//     const httpMethod = Object.keys(element.route.methods)[e]
+//     // console.log(element.route.methods[httpMethod])
+//     if (element.route.methods[httpMethod]) {
+//       if(!pathInfo[httpMethod]) {
+//         // @ts-ignore
+//         pathInfo[httpMethod] = {
+//           description: "This is a description",
+//           content: {
+//             // "application/json": {
+//             //     "schema":
+//             // }
+//           }
+//         }
+//       }
+
+//       // const eventDto = new SwaggerEndPointInformationDto(httpMethod, httpPath)
+//       // listeners.forEach((fn: (entry: SwaggerEndPointInformationDto) => void) => fn(eventDto))
+//     }
+//   }
+// }
+});
+
+app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, swaggerUiOptions));
+console.log(JSON.stringify(swaggerSpec, null, 2))
+
+//app._router.stack.filter(e => e.route)
+}
+
+private checkIsNotBuilt() {
+if (this.built) {
+throw new Error('Swagger Configuration is already built.')
+}
+}
+
+public static swaggerMethod2 = (description: string) => (target: Object, propertyKey: string) => {
+// Object.defineProperty(target, propertyKey, { description });
+console.log(description);
+console.log(Object);
+console.log(propertyKey);
+};
+}
+
+
+// const swaggerMethod = (description: string) => (target: Object, propertyKey: string) => {
+// console.log(description);
+// console.log(Object);
+// console.log(propertyKey);
+// };
+/*
+const swaggerMethod22 = (description: string) => (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
+// console.log(key);
+// Object.defineProperty(target, propertyKey, { description });
+console.log("*********************************");
+console.log(description);
+console.log(Object);
+console.log(propertyKey);
+return descriptor;
+};
+*/
+function swaggerMethod(description: string) {
+return function (
+target: Object,
+key: string | symbol,
+descriptor: PropertyDescriptor
+) {
+return descriptor;
+};
+}
+
+export { SwaggerConfig, swaggerMethod, SwaggerEndPointInformationDto };
+
+

When I attempt to refactor to:

+
const swaggerSpec = {
+  swaggerDefinition: {}
+}
+
+

I get the following complaint from TypeScript:

+
+

A class member cannot have the 'const' keyword

+
+

Also, when applying:

+
* security
+*   - Authorization: []
+
+

Where would that go in this yaml file:

+
/**
+* @openapi
+* /api/v2/patients:
+*   post:
+*     tags: [Patients]
+*     description: to create a new patient.
+*     requestBody:
+*       required: true
+*       content:
+*         application/json:
+*           schema:
+*             type: object
+*             $ref: '#/components/schemas/NewPatientDto'
+*     responses:
+*       201:
+*         description: Creates a new patient.
+*         content:
+*           application/json:
+*             schema:
+*             $ref: '#/components/schemas/NewUserDto'
+*       415:
+*         description: Only 'application/json'. incoming content is supported..
+*         content:
+*           application/json:
+*             schema:
+*             $ref: '#/components/schemas/BaseError415Dto'
+*       500:
+*         description: A server error. The returned object contains the exact nature of the error.
+*         content:
+*           application/json:
+*             schema:
+*             $ref: '#/components/schemas/BaseError500Dto'
+*/
+this.app.post(p().api.v2.patients.$url, [
+authMiddleware.verifyJWT,
+patientsMiddleware.createPatientContext,
+patientsMiddleware.validateAndBuildNewPatientDto,
+patientsMiddleware.validateSamePatientDoesNotExist,
+patientsController.createPatient
+])
+
","

I am not sure in your implementation, but as per openapi and my implementation this is working for me,

+

You can add authorization in definition > components in securitySchemes,

+
const swaggerSpec = {
+    definition: {
+        openapi: '3.0.3',
+        info: {
+            title: packageJson.name,
+            version: packageJson.version
+        },
+        components: {
+            securitySchemes: {
+                Authorization: {
+                    type: "http",
+                    scheme: "bearer",
+                    bearerFormat: "JWT",
+                    value: "Bearer <JWT token here>"
+                }
+            }
+        }
+    },
+    apis: [
+        './dist/**/*.js'
+    ]
+};
+
+

As per your implementation use,

+
const swaggerUiOptions = {
+  explorer: true
+};
+
+app.use('/api-docs', swaggerUi.serve, swaggerUI.setup(swaggerSpec, swaggerUiOptions));
+
+

One more thing, in particular api's annotation pass, security key with authorization,

+
/**
+* @openapi
+* /api/v2/patients:
+*   post:
+*     security:
+*       - Authorization: []
+*     tags: [Patients]
+*     description: to create a new patient.
+....
+
+

It looks:

+

+

Per api there is lock icon:

+

+

After Click:

+

+
+

Try to update openapi version at least 3.0.3!

+
",r +"why is the location string not showing in the window. tkinter python?

im trying to write a code that will tell you if the location is a file or directory. if its a file, then it will read the file. here is my code (ik its very bad, im sorry)

+
import os
+import tkinter as tk
+
+screen = tk.Tk()
+screen.title("files and directories")
+screen.geometry("300x100")
+
+def FileDir():
+    path = location.get(1.0, "end-1c")
+    location.delete(1.0, tk.END)
+
+    if os.path.exists(path):
+        print("✔ - this location exists")
+
+        info_location = tk.Label(screen, text=f"location: {location}")
+        info_location.pack()
+
+        if os.path.isfile(path):
+            print("\tthis is a file")
+            type = 'file'
+
+            info_type = tk.Label(screen, text=f"type: {type}")
+            info_type.pack()
+
+            while True:
+                open_file = input("\nDo you want to read this file? ")
+
+                if open_file.lower() == 'yes':
+                    with open(path) as file:
+                        contents = file.read()
+                    print(contents)
+                    break
+
+                elif open_file.lower() == 'no':
+                    print("goodbye!")
+                    break
+
+                else:
+                    print("invalid input")
+                    continue
+
+        elif os.path.isdir(path):
+            print("\tthis is a directory")
+            type = 'directory'
+
+            info_type = tk.Label(screen, text=f"type: {type}")
+            info_type.pack()
+
+    else:
+        print("✘ - this location doesn't exist")
+
+text = tk.Label(screen, text="Enter file/directory location: ")
+text.pack()
+
+location = tk.Text(screen, height = 1, width = 25)
+location.pack()
+
+enter_btn = tk.Button(screen, text="Enter", command=FileDir)
+enter_btn.pack()
+
+screen.mainloop()
+
+

so when putting the location of a string, everything works fine except that the location doesnt show and instead it shows ".!text". anyone know why?

","

location is a widget rather than a string. The string representation of a tkinter widget is its internal name. Thus, when you do text=f"location: {location}" you are creating a string that contains the name of the widget rather than the contents.

+

To display the contents you must fetch them from the widget. You're already doing that when you define path, so you just need to use {path} rather than {location}

+
text=f"location: {path}"
+
",r +"How do I make separate hover functions work in javascript?

I'm trying to make an image {image 7} appear when hovering over {image 5} while also making {image 8} appear when hovering over {image 6}. It seems to work fine when using the hovering only once, but when I try to do it twice (make different images appear when hovering on different images), it doesn't work. I think that it is because i don't know how to call each set of images on script properly. I'm pretty new at this so any help would be super appreciated. Thank you in advaced!

+

p.s. +I will use the hover event for diferent elements several times in my webpage, not just twice.

+

here is my html:

+
<div class="row1">
+
+<div>
+<div class="hover-title">
+
+<a rel="history" href="enlightened-type" class="image-link" id="what" onmouseover="showImg()" onmouseout="hideImg()">{image 5 scale="19"}</a>
+
+</div>
+
+<div class="hover-image">
+<div id="what1" style="visibility: hidden;"> {image 7 scale="27"} </div>
+</div>
+
+</div>
+
+<div>
+
+<div class="hover-title">
+<a rel="history" href="enlightened-type" class="image-link" id="young" onmouseover="showImg()" onmouseout="hideImg()">{image 6 scale="16"}</a>
+</div>
+
+<div class="hover-image">
+<div id="young1" style="visibility: hidden;">{image 8 scale="12"} </div>
+</div>
+
+</div>
+
+

& this is my script:

+
<script>
+
+    var hoverImg = 
+        document.getElementById("what1");
+        document.getElementById("young1");
+
+    function showImg(x) {
+      hoverImg.style.visibility = "visible";
+    }
+
+    function hideImg(x) {
+      hoverImg.style.visibility = "hidden";
+    }
+  
+ 
+</script>
+
","

I think you should add the sender to the event handler and edit the related element

+

In html you should do this

+
<a rel="history" href="enlightened-type" class="image-link" id="what" onmouseover="showImg(this)" onmouseout="hideImg(this)">{image 5 scale="19"}</a>
+
+

And in Js

+
function showImg(x) {
+  document.getElementById(x.id + "1").style.visibility = "visible";
+}
+
+function hideImg(x) {
+  document.getElementById(x.id + "1").style.visibility = "hidden";
+}
+
",r +"Using if then statements R to changing existing values of variable

I have a data frame with a variable AGE_YR. I want to convert any ages less than 1 to 1.

+

I am unsure how to write this using an if then/else statement in R and seem to be stuck on using my SAS knowledge which is obviously not helping.

+

Logically I want to write something like this If df$AGE_YR < 1 THEN df$AGE_YR == 1 but the syntax is obviously wrong.

","

You were not far off

+
df$AGE_YR <- ifelse(df$AGE_YR < 1, 1, df$AGE_YR)
+
+

Might yield better run time

+
df$AGE_YR <- pmax(df$AGE_YR, 1)
+
",r +"How to make POSTGRESQL query based on first 2 parameters and latest third parameter

I have DB:

+
**client_id  |  Version |  Date(year, month, day)**
+
+

I need to make query request for last year(or last 12 months) group by Client_id, Version and latest date(!) for them. +For example:

+
client_id  |  Version |    **LATEST** Date
+   23           v2           2022-1-25
+   23           v1           2021-3-23
+   25           v0           2021-6-23
+ 
+
+

This is what I have right now:

+
SELECT client_id, Version, Date 
+FROM db_table
+WHERE date >= '2022-01-01' AND date < NOW()::DATE
+GROUP BY client_id, Version, Date 
+
+

And I'm getting result for EVERY DAY. If I'm removing DATE from group by, its complaining that Date should be in Group by.

+

I hope I did describe everything properly. I'm new here, so please let me know if I provide not full info.

+

Thank you for your time.

","

To get the most recent full year (i.e. not including the partial current day),

+
SELECT current_date - interval '1 year'; --this returns 2021-02-07 when run today
+
+

To consider today as part of the 12 month period, then:

+
SELECT current_date - interval '1 year - 1 day'; --this returns 2021-02-08 when run today
+
+

So, assuming that you want the former option (you can switch it if you like):

+
SELECT client_id, "Version", MAX("Date") AS latest_date 
+FROM db_table
+WHERE "Date" BETWEEN current_date - interval '1 year' AND current_date
+GROUP BY client_id, "Version";
+
+

p.s. recommend you don't use "Date" as a column name since it's a reserved word, and avoid using upper case letters in column names :)

",r +"Hide Row if groupname included fixed Text angular

I have a table which show all names from json. But Some name should be hidden, if they include groupnam4. +For example: +How can I hide row "name2" in HTML, if group.name = groupname4.

+

My Json looks like:

+
{
+   name: "name1"
+   groups:
+         [
+           { id: "1",
+             name: "groupname1"},
+           { id: "2",
+             name: "groupname2"},
+         ]
+ },
+
+{
+    name: "name2"
+    groups:
+        [
+         { id: "1",
+           name: "groupname1"},
+         { id: "2",
+           name: "groupname4"},
+        ]
+}
+
","
<tr *ngFor="let item of groups">
+  <td *ngIf="item.name != 'groupname4' ">{{ item.name }}</td>
+</tr>
+
+

write an ngIf condition and render when the name groupname4

",r +"Unhandled Rejection (TypeError) on callback passed to react component

I'm stuck with a problem passing callback function to a component. +This is a small piece of my App.js file

+
loginCompleted = (status) => {
+        if (status == "1") {
+            this.setState({ currentUser: "xxxx" });
+        }
+    }
+
+    render() {
+        return (
+            <BrowserRouter>
+                <MainTemplate authStatus={ this.state.currentUser }>
+                    <Switch>
+                        <Route exact path='/' component={Home} />
+                        <Route exact path='/login' component={Login} loginCompleted={this.loginCompleted}  />
+                    </Switch>
+                </MainTemplate>
+            </BrowserRouter>
+        );
+    }
+
+

As you can see I want to pass the loginCompleted callback to the Login component.

+

In the Login component there is this function that handle the submit form

+

handleSubmit = async e => { +e.preventDefault(); +const token = await this.LoginService.loginUser(this.state.username, this.state.password); +if (token) { +console.log(token); +this.props.loginCompleted(token); +this.props.history.push("/home"); +} +else { +console.log("NULL"); +} +}

+

I recevice the error

+
Unhandled Rejection (TypeError): this.props.loginCompleted is not a function
+
+

Despite the research I still don't understand why. Can you help me? +Thanks!

","

Seems, that you are passing prop to the route, not to the component itself. Try this approach.

+
+
loginCompleted = (status) => {
+        if (status == "1") {
+            this.setState({ currentUser: "xxxx" });
+        }
+    }
+
+    render() {
+        return (
+            <BrowserRouter>
+                <MainTemplate authStatus={ this.state.currentUser }>
+                    <Switch>
+                        <Route exact path='/' component={Home} />
+                        <Route exact path='/login'> 
+                          <Login loginCompleted={this.loginCompleted}  />
+                       </Route>
+                    </Switch>
+                </MainTemplate>
+            </BrowserRouter>
+        );
+    }
+
+
+

We wrap the Component inside of Route and pass the prop to component, not to route.

",r +"Replace ""%"" with ""\%"" in string

I need to make a character vector suitable for use in LaTeX, so I need to escape all the percent signs with a single backslash. So far, all I've been able to do is to get two backslash:

+
> text <- c("This is 60%", "This is 30%")
+> gsub("%", "\\%", text, fixed=TRUE)
+[1] "This is 60\\%" "This is 30\\%"
+> gsub("%", "\\\\%", text, fixed=TRUE)
+[1] "This is 60\\\\%" "This is 30\\\\%"
+
+

As expected, if fixed=FALSE I get no backslash using "\\%" as a substitution or two backslash using `"\\%"' as a substitution. How can I get "This is 60\%" as a result?

","

In fact, the first version is already working:

+
text <- c("This is 60%", "This is 30%")
+gsub("%", "\\%", text, fixed=TRUE)
+[1] "This is 60\\%" "This is 30\\%"
+
+

When you see \\% in the printed string, the first backslash is just an escape character for the second backslash, which is literal. Your output string is really this:

+
This is 60\%
+
",r +"Mongoose not saving elements in Object Array?

I'm trying to make a RPG Discord Bot, where you can level skills, sell items, etc. +Recently, a friend of mine refactored all the code. Everything is working, besides the start command:

+

Before the refactor, it'd save everything correctly. +Afterwards, it didn't save the maxLevel property for any skill and began saving ObjectID properties.

+

Skills/start.js

+

+    await new client.database.user({
+      userID: interaction.user.id,
+      inventory: [],
+      coins: 250,
+      skills: [
+        {
+          name: 'Strength',
+          level: 1,
+          exp: 0,
+          maxLevel: 50,
+        },
+        {
+          name: 'Agility',
+          level: 1,
+          exp: 0,
+          maxLevel: 50,
+        },
+        {
+          name: 'Knowledge',
+          level: 1,
+          exp: 0,
+          maxLevel: 50,
+        },
+        {
+          name: 'Trading',
+          level: 1,
+          exp: 0,
+          maxLevel: 50,
+        },
+        {
+          name: 'Challenge',
+          level: 1,
+          exp: 0,
+          maxLevel: 5,
+        },
+        {
+          name: 'Hunting',
+          level: 1,
+          exp: 0,
+          maxLevel: 50,
+        }
+      ],
+      mobsKilled: 0,
+      bossesKilled: 0,
+      created: moment().format('DD/MM/YYYY'),
+      heavenDifficulty: Math.floor(Math.random() * 9 + 1),
+    }).save();
+
+

Schemas/User.js

+
import mongoose from 'mongoose';
+
+const userSchema = mongoose.Schema({
+  userID: String,
+  guild: {
+    guildID: String,
+    guildName: String,
+    position: String
+  },
+  inventory: [{ name: String, amount: Number }],
+  coins: Number,
+  skills: [{ name: String, level: Number, exp: Number }],
+  mobsKilled: Number,
+  bossesKilled: Number,
+  created: String,
+  heavenDifficulty: Number,
+  isPremium: Boolean,
+  premium: {
+    since: String,
+    sinceTS: String, //TS = Timestamp
+    tier: String
+  }
+});
+
+const UserSchema = mongoose.model('users', userSchema);
+
+

Also, I do know, that the premium properties are empty. This is because I want to add them to the database, when someone becomes a premium member and not when they start their journey.

+

Edit: This is what it's returning (all undefined properties should be the maxLevel property) +:

","

"Afterwards, it didn't save the maxLevel property..."

+

Is the issue occurring because you need to add a maxLevel property to your database schema?

+

",r +"Powershell how to search the file and then open then tail the file based on the first search

How do open tail the first text file I search in descending order?

+
Get-Content -Tail
+
+
Get-ChildItem -Force -Recurse -File -Path "C:\*.txt" -ErrorAction SilentlyContinue | Where-Object { $_.CreationTime.Date -lt (Get-Date).Date } | Sort CreationTime -Descending
+
","

Use Select-Object -First 1 to discard everything after the first input object:

+
Get-ChildItem ... |Where-Object {...} | Sort ... |Select-Object -First 1 |Get-Content -Tail
+
",r +"show div onclick, add class to the div and get the similar process for the other divs

I have a block of div i wanted to add .active class to the div .verified-account when clicking .title-box.has-value it should also add class to .screen-answer.

+

So if the next div is clicked, the previous clicked and active div needs to get his class removed (so deactive) and his row beneath hidden. The next selected div needs to get the same process as the previous.

+
<div class="screen-start">
+<div class="screenbox">
+<div class="btn-screen box-start">
+<div class="title-box has-value blue-bg">YES</div>
+<div class="verified-account"></div>
+</div>
+<div class="btn-screen box-start">
+<div class="title-box has-value green-bg">AMAZING!!!</div>
+<div class="verified-account"></div>
+</div>
+<div class="btn-screen box-start">
+<div class="title-box has-value green-bg">MAYBE YES.</div>
+<div class="verified-account"></div>
+</div>
+</div>
+<div class="screen-answerbox">
+<div class="screen-answer blue">This was a active
+</div>
+<div class="screen-answer green">This was a active
+</div>
+<div class="screen-answer green">This was a active
+</div>
+</div>
+</div>
+
+

My Jquery code

+
jQuery(document).ready(function($) {
+
+var selector = '.title-box.has-value';
+
+$(selector).on('click', function(){
+$(selector).closest('.btn-review').find('.icons8-verified-account').removeClass('active');
+$(this).closest('.btn-review').find('.icons8-verified-account').addClass('active');
+$(selector).parents('.rating-start').find('.range-answer').removeClass('active');
+$(this).parents('.rating-start').find('.range-answer').addClass('active');
+});
+});
+
","

You can just use:

+
$('.verified-account').removeClass("active");
+$(this).next('.verified-account').addClass("active");
+
+

The first line removed .active from all elements with the class verified-account; +
The second line adds the class active to the verified-account element related to the click element.

+

Demo

+

+
+
jQuery(document).ready(function($) {
+
+  var selector = '.title-box.has-value';
+
+  $(selector).on('click', function() {
+    var inx = $(selector).index(this);
+    $(selector).closest('.btn-review').find('.icons8-verified-account').removeClass('active');
+    $(this).closest('.btn-review').find('.icons8-verified-account').addClass('active');
+    $(selector).parents('.rating-start').find('.range-answer').removeClass('active');
+    $(this).parents('.rating-start').find('.range-answer').addClass('active');
+    $('.verified-account').removeClass(""active"");
+    $(this).next('.verified-account').addClass(""active"");
+    $('.screen-answer').removeClass(""active"");
+    $('.screen-answer').eq(inx).addClass(""active"")
+  });
+});
+
.active {
+  color: yellow;
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<div class=""screen-start"">
+  <div class=""screenbox"">
+    <div class=""btn-screen box-start"">
+      <div class=""title-box has-value blue-bg"">YES</div>
+      <div class=""verified-account"">Verify</div>
+    </div>
+    <div class=""btn-screen box-start"">
+      <div class=""title-box has-value green-bg"">AMAZING!!!</div>
+      <div class=""verified-account"">Verify</div>
+    </div>
+    <div class=""btn-screen box-start"">
+      <div class=""title-box has-value green-bg"">MAYBE YES.</div>
+      <div class=""verified-account"">Verify</div>
+    </div>
+  </div>
+  <div class=""screen-answerbox"">
+    <div class=""screen-answer blue"">This was a active
+    </div>
+    <div class=""screen-answer green"">This was a active
+    </div>
+    <div class=""screen-answer green"">This was a active
+    </div>
+  </div>
+</div>
+
+
+

",r +"MongoDB retrieve data with highest value

I have this collection in MongoDB:

+
[
+  { _id: "...", "project": 244, "scanner": "powershell", "version": 2 },
+  { _id: "...", "project": 244, "scanner": "powershell", "version": 3 },
+  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
+  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
+]
+
+

I need to retrieve all the document with the highest version, in this case:

+
  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
+  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
+
+

I can find the highest version, sorting with -1 and taking the first one.

+

How do I apply the result found to the filter?

+

Many thanks

","

playground

+
db.collection.aggregate([
+  {
+    "$group": { //Find max value
+      "_id": "null",
+      "maxV": {
+        "$max": "$version"
+      },
+      data: { // add all records to this array
+        $push: "$$ROOT"
+      }
+    }
+  },
+  {
+    $project: {
+      "output": {
+        $filter: {//Filter the matching record from the array in stage 1
+          input: "$data",
+          as: "d",
+          cond: {
+            $eq: [
+              "$$d.version",
+              "$maxV"
+            ]
+          }
+        }
+      },
+      "_id": 0
+    }
+  }
+])
+
+

If you want to get rid of key output, you can two more stages as in this play

+
  {
+    "$unwind": "$output"
+  },
+  {
+    "$replaceRoot": {
+      "newRoot": "$output"
+    }
+  }
+
",r +"Laravel OneToMany query

I'm new to Laravel and the Eloquent model and I find it difficult to understand the simplest queries even after reading the documentation.

+

I have two models Measure and MeasureType, and I want to select all measures of a certain type. What in sql would be like:

+
select * from measures m
+      join measure_types mt on mt.id=m.measure_type_id
+      join measure_type_trans t on t.measure_type_id=mt.id
+      where t.name='xyz';
+
+

In Measure I have:

+
public function type()
+    {
+        return $this->belongsTo(MeasureType::class, 'measure_type_id');
+    }
+
+

And in MeasureType:

+
public function measures()
+    {
+        return $this->hasMany(Measure::class);
+    }
+
+

Name column is in the translatable table measure_type_trans +How do I do such simple query?

","

If you want the type and nested in it the measures that belong to it

+
$measureType = MeasureTypeTrans::where('name', 'xyz')->with('type.measures')->first();
+
+//you can access the measures with the attribute having the same name as the relation
+$measures = $measureType->type->measures;
+
+

If you want to have only the measures as a collection (almost the same as the query you posted)

+
$name = 'xyz';
+$measures = Measure::whereHas('type', function ($typeQueryBuilder) use($name) {
+    $typeQueryBuilder->whereHas('typeTrans', function($typeTransQB) use($name) {
+        $typeTransQB->where('name', $name);
+    });
+})->get();
+
",r +"PL/SQL function is ""stuck""

I have the following simple PL/SQL function, which compiles without any errors if I execute the script. However, when I call the function it gives no output or error and doesn't end.

+

Function:

+
CREATE OR REPLACE FUNCTION columns_of_table(table_name_given in varchar) 
+    return varchar 
+    is
+    
+    to_return varchar(999) := '';
+    CURSOR col_cursor IS SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM user_tab_columns WHERE TABLE_NAME = table_name_given;
+    tab_name user_tab_columns.table_name%TYPE;
+    col_name user_tab_columns.COLUMN_NAME%TYPE;
+    data_type user_tab_columns.data_type%TYPE;      
+        
+    BEGIN
+        OPEN col_cursor;
+
+        LOOP
+        FETCH col_cursor into tab_name, col_name, data_type;
+        to_return := col_name || ' ' || data_type || ', ';
+        END LOOP;
+        to_return := SUBSTR(to_return, 1, LENGTH(to_return) - 2);
+        CLOSE col_cursor;
+        return to_return;
+    END;
+/
+
+

Adding the function and executing it in PLUS SQL:

+
SQL> @H:\DBI\05\Script.sql
+
+Funktion wurde erstellt.
+
+SQL> select columns_of_table('rezl') from user_tables;
+
+

Afterwards nothing happens and no new imput prompt shows up.

","

You've coded an infinite loop.

+

Using an explicit cursor to do row-by-row processing is almost always a poor design decision. An implicit cursor has far fewer steps (so far fewer sources of bugs) and is generally much easier to read.

+
CREATE OR REPLACE FUNCTION columns_of_table(table_name_given in varchar) 
+    return varchar 
+is
+    to_return varchar(999) := '';
+BEGIN
+    FOR col IN (SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE 
+                  FROM user_tab_columns 
+                 WHERE TABLE_NAME = table_name_given)
+    LOOP
+      to_return := col.column_name || ' ' || col.data_type || ', ';
+    END LOOP;
+    to_return := SUBSTR(to_return, 1, LENGTH(to_return) - 2);
+    return to_return;
+END;
+
+

If you really need to use an explicit cursor for some reason, you'd need to have an explicit exit statement

+
    LOOP
+      FETCH col_cursor into tab_name, col_name, data_type;
+      EXIT WHEN col_cursor%NOTFOUND;
+      to_return := col_name || ' ' || data_type || ', ';
+    END LOOP;
+
+

Of course, you could also replace your manual looping with a simpler listagg statement

+
select listagg( column_name || ' ' || data_type, ', ' )  
+  from user_tab_columns 
+ where table_name = table_name_given;
+
",r +"Convert grouped data in dataframe to documents in preparation for word2vec

I'm trying to replicate what the author of this paper has achieved with the publicly available Medicare dataset.

+

In summary, the author groups medical provider claims by the providers ID, their taxonomy and the HCPCS (codes of the procedures they performed) by most frequent to least frequent, see below image:

+

+

Using the code below I have been able to recreate the top left hand table and also the bottom left table (I don't think it's necessary) but I don't know how to group each providers HCPCS codes by highest frequency to lowest frequency in preparation for feeding it into word2vec to train an embedding model.

+

If I could get some help preparing the data ready for word2vec training I would be very grateful.

+
library(httr)
+library(jsonlite)
+library(tidyverse)
+
+# CONNECT TO CMS DATA
+res <- GET("https://data.cms.gov/data-api/v1/dataset/5fccd951-9538-48a7-9075-6f02b9867868/data?size=5000")
+
+# CONVERT TO DATA FRAME
+data = fromJSON(rawToChar(res$content))
+
+# GROUPING AND COUNTING OCCURANCES OF HCPCS PER PROVIDER ID
+providerHCPCS <- data %>% 
+  group_by(Rndrng_NPI,Rndrng_Prvdr_Type,HCPCS_Cd) %>% 
+  count(HCPCS_Cd, name = "Line_Srvc_Cnt") %>% 
+  group_by(Rndrng_NPI) %>% 
+  arrange(desc(Line_Srvc_Cnt), .by_group = TRUE)
+
","

Is this what you want as a result?

+
table2 <- providerHCPCS %>% group_by(Rndrng_NPI, Rndrng_Prvdr_Type) %>% summarise(HCPCS_sequence = (paste(HCPCS_Cd, collapse=", ")))
+
+
",r +"Is there any way of having customised button for different users based on the information in the firebase

I am trying to implement a request button that if click on it should turn into a request send the way Facebook works

+

I tried to implement this But I am having issues

+

Below is the approach I used

+
class _TherapistRequestState extends State<TherapistRequest> {
+  final Stream<QuerySnapshot> therapists = FirebaseFirestore
+      .instance.collection('users')
+      .where('role', isEqualTo: 'Therapist')
+      .snapshots();
+  final _auth = FirebaseAuth.instance;
+  String ? therapist;
+
+  @override
+  Widget build(BuildContext context) {
+    Size size = MediaQuery.of(context).size;
+    return Scaffold(
+      appBar: AppBar(
+        title:Row(
+          mainAxisAlignment: MainAxisAlignment.start,
+          children: [
+            Text(
+              'MAISHA BORA',
+              style: GoogleFonts.aclonica(
+                textStyle:const TextStyle(
+                  fontWeight: FontWeight.bold,
+                  color: Colors.white,
+                  fontSize: 20,
+                ),
+              ),
+            ),
+          ],
+        ),
+        backgroundColor: kPrimaryColor.withOpacity(0.9),
+      ),
+      body: Column(
+        children: [
+          const SizedBox(
+            height: 20,
+          ),
+          Row(
+            mainAxisAlignment: MainAxisAlignment.center,
+            children: [
+              Text(
+                'Available Therapist',
+                style: GoogleFonts.aclonica(
+                    color: kPrimaryColor,
+                    fontSize: 25,
+                    fontWeight: FontWeight.bold
+                ),
+              ),
+            ],
+          ),
+          const Divider(
+            color: kPrimaryColor,
+            height: 20,
+          ),
+          StreamBuilder(
+            stream: therapists,
+              builder: (context, AsyncSnapshot snapshot){
+                if(snapshot.hasData){
+                  final data = snapshot.requireData;
+                  return ConstrainedBox(
+                      constraints: BoxConstraints.tightFor(
+                        height: size.height * 0.7,
+                        width: size.width
+                      ),
+                    child: ListView.builder(
+                        scrollDirection: Axis.vertical,
+                        shrinkWrap: true,
+                        itemCount: data.size,
+                        itemBuilder: (context, i){
+                          therapist = data.docs[i]['uid'];
+                          return Column(
+                            children: [
+                              Card(
+                                shadowColor: Colors.grey,
+                                elevation: 10.0,
+                                shape: RoundedRectangleBorder(
+                                  borderRadius: BorderRadius.circular(10),
+                                ),
+                                child: Padding(
+                                  padding: const EdgeInsets.all(20.0),
+                                  child: Column(
+                                    children: [
+                                      Row(
+                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
+                                        children: [
+                                          Text(
+                                            'Dr ${data.docs[i]['username']}',
+                                            style: GoogleFonts.acme(
+                                              textStyle:const TextStyle(
+                                                color: Colors.black,
+                                                fontSize: 20,
+                                              ),
+                                            ),
+                                          ),
+                                          Text(
+                                            'Patients ${data.docs[i]['patients']}/4',
+                                            style: GoogleFonts.aladin(
+                                              textStyle: const TextStyle(
+                                                color: Colors.grey,
+                                                fontSize: 20,
+                                              ),
+                                            ),
+                                          ),
+                                        ],
+                                      ),
+                                      Row(
+                                        mainAxisAlignment: MainAxisAlignment.end,
+                                        children: [
+                                          buildButton(context),
+                                        ],
+                                      ),
+                                    ],
+                                  ),
+                                ),
+                              ),
+                            ],
+                          );
+                        }
+                    ),
+                  );
+                }
+                else{
+                  return Container();
+                }
+              },
+          ),
+        ],
+      ),
+    );
+  }
+  Widget buildButton(context){
+    return StreamBuilder(
+        stream: FirebaseFirestore.instance.collection('users').doc(therapist).collection('request').doc(_auth.currentUser!.uid).snapshots(),
+        builder: (context, AsyncSnapshot snapshot){
+          if(snapshot.data.exists){
+            return SquareButton(
+                label: 'Request Sent',
+                color: Colors.grey,
+                onPressed: (){
+                  null;
+                }
+            );
+          }
+          return SquareButton(
+            label: 'Request',
+            color: Colors.green,
+            onPressed: () async{
+              FirebaseFirestore.instance.collection('users')
+                  .doc(therapist)
+                  .collection('request')
+                  .doc(_auth.currentUser!.uid)
+                  .set({
+                'userId' : _auth.currentUser!.uid,
+              }).then((value) {
+                showToast(
+                  message: 'Request sent successfully',
+                  color: Colors.green,
+                );
+              });
+            },
+          );
+        }
+    );
+  }
+}
+
+

But when I use this, if I go to the page I get this error

+

The following NoSuchMethodError was thrown building StreamBuilder flutter

+

which I suppose is when I try to check the state of the button

+

How can tackle this using a different method.

+

Please do assist me on this

","

I would suggest that instead of using a stream, you can fetch the data from firebase once. To do that, you can define a future on top of your state and assign it a value in your initState +In your build method you can use a FutureBuilder around the button you want to customize

+

EDIT +You can do something like this:

+
class _TherapistRequestState extends State<TherapistRequest> {
+    Future required_document;
+    initHelper()async{     //using this function because we need to use async await    
+        required_document = await FirebaseCollection.......doc();
+    }
+    initState(){
+        initHelper();
+    }
+    Widget build(BuildContext context){
+            return Container(); 
+        // enclose your button that needs to be customized in a FutureBuilder like so:
+            // FutureBuilder(
+            // future: required_document,
+            // builder:(a,b){return ElevatedButton()} 
+            //)
+            
+    }
+}
+
+
",r +"Unable to write text field after adding onChange (that have setState) ReactJS

I want to create poll/exercise form that update the value by useState. So, I created handleChange() to handle update from input form and that work perfeclt fine for the most of my input field except the one that is store state as object (I have state field that called answers to keep multiple answer choices from my poll/excercise as answer1 ... answer4) like this

+
const [pollValues, setpollValues] = useState({
+    name: "",
+    question: "",
+    type: "",
+    answers: {
+      answer1: "",
+      answer2: "",
+      answer3: "",
+      answer4: "",
+    },
+  }); 
+
+

and handleChange() use by passing event form input form:

+
 function handleChange(e) {
+    const { name, value } = e.target;
+    console.log(name, value);
+
+    setpollValues((prev) => ({
+      ...prev,
+      [name]: value,
+    }));
+  }
+
+

and use it for handle input with name (that locate in main return() ), question, type work perfectly fine. but the poll answers choice, I make a sub-component in the same file and passing name as props to identify the choice

+
     <ChoiceAnswer type="required" name="answer1" choiceNumber="1" />
+     <ChoiceAnswer type="required" name="answer2" choiceNumber="2" />
+     <ChoiceAnswer type="optional" name="answer3" choiceNumber="3" />
+     <ChoiceAnswer type="optional" name="answer4" choiceNumber="4" />
+
+ const ChoiceAnswer = (props) => {
+    const { type, choiceNumber, name } = props;
+    if (type == "required") {
+      return (
+        <div
+          className="d-flex flex-column "
+          style={{
+            rowGap: "0.5rem",
+            margin: "0px",
+            padding: "0px",
+            width: "100%",
+          }}
+        >
+          <div
+            className="d-flex align-items-center"
+            style={{
+              padding: "1rem",
+              border: "1.5px #ccc solid",
+              borderRadius: "1rem",
+              columnGap: "1rem",
+            }}
+          >
+            <div style={{ width: "7rem" }}>
+              <h5>ตัวเลือกที่ {choiceNumber}</h5>
+              <p style={{ color: "red" }}>* จำเป็น</p>
+            </div>
+
+            <input
+              type="text"
+              style={{ width: "100%" }}
+     
+              id={name}
+              name={name}
+              placeholder="ใส่คำตอบ"
+              onChange={handleChange}
+              required
+            ></input>
+          </div>
+        </div>
+      ); else if (type == "optional") {...}
+
+

the problem that occurs with the answers only, cannot typing text in text field (try to console log and found that it can only update only 1 character at once cannot type in string) but If I delete the setState It will normally typable. So, I don't know what happend that make my answers field cannot typing and using handleChang() to update their values.

","

There is a mistake in your handleChange function. answers are nested one more level.

+

Try like below.

+
function handleChange(e) {
+    const { name, value } = e.target;
+    console.log(name, value);
+
+    setpollValues(prev => ({
+        ...prev,
+        answers: {
+            ...prev.answers,
+            [name]: value
+        }
+    }));
+}
+
+

",r +"modal doesn't show when placed inside a div that has a show/hide function

I have a straightforward multi-image modal set up which works perfectly. However, the page I am trying to integrate it on is set up as follows: I have a header, a set of links to the left, and a main section next to the links. When a link is clicked it changes the content of the main section through a hide/show function. In this manner all of the site is on one page. The problem is that when I place the modal inside the hidden div of choice, the images show up when the main contents is changed, but the modal does not open when the image is clicked. Here is the code for the main div and the hidden div where the modal will be (the user needs to click on where the image would be that says "fall bill" to open the div where the modal is. You will see that I placed some images in as holders. The images fade when hovered as they are supposed to. I cannot figure out any reason why the modal will not show up in such an instance but works if it is not inside a div that can be hidden.

+

Here is a the code:

+

+
+
var modal = document.getElementById('myModal');
+var images = document.getElementsByClassName('img');
+var modalImg = document.getElementById(""img01"");
+
+for (var i = 0; i < images.length; i++) {
+  var img = images[i];
+  img.onclick = function(evt) {
+    console.log(evt);
+    modal.style.display = ""block"";
+    modalImg.src = this.src;
+  }
+}
+
+var span = document.getElementsByClassName(""close"")[0];
+
+span.onclick = function() {
+  modal.style.display = ""none"";
+}
+
+
+function show(param_div_id) {
+  document.getElementById('main').innerHTML = document.getElementById(param_div_id).innerHTML;
+}
+
.img {
+  border-radius: 5px;
+  cursor: pointer;
+  transition: 0.3s;
+}
+
+.img:hover {
+  opacity: 0.8;
+}
+
+.modal {
+  display: none;
+  /* Hidden by default */
+  position: fixed;
+  /* Stay in place */
+  z-index: 10;
+  /* Sit on top */
+  padding-top: 100px;
+  /* Location of the box */
+  left: 0;
+  top: 0;
+  width: 100%;
+  /* Full width */
+  height: 100%;
+  /* Full height */
+  overflow: auto;
+  /* Enable scroll if needed */
+  background-color: rgb(0, 0, 0);
+  /* Fallback color */
+  background-color: rgba(0, 0, 0, 0.9);
+  /* Black w/ opacity */
+}
+
+.modal-content {
+  margin: auto;
+  display: block;
+  width: 80%;
+  max-width: 700px;
+}
+
+.modal-content,
+#caption {
+  animation-name: zoom;
+  animation-duration: 0.6s;
+}
+
+@keyframes zoom {
+  from {
+    transform: scale(0)
+  }
+  to {
+    transform: scale(1)
+  }
+}
+
+.close {
+  position: absolute;
+  top: 15px;
+  right: 35px;
+  color: #f1f1f1;
+  font-size: 40px;
+  font-weight: bold;
+  transition: 0.3s;
+}
+
+.close:hover,
+.close:focus {
+  color: #bbb;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+@media only screen and (max-width: 700px) {
+  .modal-content {
+    width: 100%;
+  }
+}
+
+#main {
+  background-image: url('bkgd.jpg');
+  display: block;
+  width: 690px;
+  font-family: ""Book Antiqua"";
+  color: #004B97;
+  font-size: 16pt;
+  padding: 2%;
+  margin: 5px;
+  border-radius: 15px;
+  border: medium #9999FF solid;
+}
+
+.mainContents {
+  display: flex;
+  flex-wrap: wrap;
+  margin: 0 auto;
+  position: relative;
+  width: 690px;
+  flex-wrap: wrap;
+  justify-content: center;
+}
+
+#home,
+#bills,
+#munTax,
+#schoolTax,
+#interimTax,
+#taxCert,
+#dupsReceipts,
+#directions,
+#FAQ {
+  display: none;
+  width: 300px;
+  font-family: ""Book Antiqua"";
+  color: #004B97;
+}
+
+.head {
+  width: 100%;
+  text-align: center;
+  font-family: inherit;
+  font-size: 16pt;
+  color: #004B97;
+  padding-bottom: 10px;
+}
+
+.head2 {
+  position: relative;
+  width: 100%;
+  text-align: center;
+  font-family: inherit;
+  font-size: 14pt;
+  color: #835BF9;
+  padding-bottom: 15px;
+}
+
+.lower {
+  width: 100%;
+  display: flex;
+  margin: 0 auto auto 10;
+  flex-wrap: wrap;
+  justify-content: space-around;
+  padding: 10px;
+  align-items: center;
+}
+
+.pay {
+  text-align: center;
+  background-image: url('background.jpg');
+  color: #0D095E;
+  font-size: 14pt;
+  border: medium #9999FF solid;
+  border-radius: 15px;
+  padding: 5px;
+  margin: 5px;
+}
+
<div id=""main"">
+  <div class=""mainContents"">
+    <div class=""head"">Outside Receiving Hours:<br/> Please use secure drop box outside building
+    </div>
+    <div class=""head2"">
+      <strong>2022 Millage Rates</strong><br/> County - 3.2273; Township - .62; PVSD (School + Library) = 23.8117
+    </div>
+    <div class=""lower"">
+      <div class=""pay"">
+        Pay Tax Bill Online<br/>
+        <img alt=""Pay Online"" height=""80"" src=""payonline.png"" width=""144"">
+      </div>
+
+      <div class=""pay"">
+        Understanding Your Tax Bill<br/>
+
+        <button onclick=""show('bills')"" class=""link""><img alt=""Fall Bill"" height=""129"" src=""FallTaxBill-psd.png"" width=""300""></button>
+      </div>
+    </div>
+  </div>
+</div>
+
+<div id=""bills"">
+  <div class=""mainContents"">
+    <div class=""head"">Understanding Your Tax Bill</div><br/>
+    <div class=""lower"">
+      <div class=""pay"">
+        Spring Tax Bill<br/>
+        <img class=""img"" src=""http://onebigphoto.com/uploads/2012/10/midnight-sun-in-lofoten-norway.jpg"" alt=""Midnight sun in Lofoten, Norway"" width=""300"" height=""200"">
+      </div>
+      <div class=""pay"">
+        Fall Tax Bill<br/>
+        <img class=""img"" src=""http://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/1490029386/fisherman-cabin-hamnoy-lofoten-islands-norway-NORWAY0320.jpg?itok=cpPuUjh1"" alt=""Fishermen's cabins in Lofoten, Norway"" width=""300"" height=""200"">
+      </div>
+      <div class=""pay"">
+        Fall Tax Bill Stubs<br/>
+        <img class=""img"" src=""http://fjordtours.blob.core.windows.net/fjordtours-umbraco/1199/gerirangerfjord-per-ottar-walderhaug-fjordnorway.jpg"" alt=""Gerirangerfjord, Norway"" width=""300"" height=""200"">
+      </div>
+    </div>
+  </div>
+</div>
+
+<div id=""myModal"" class=""modal"">
+  <span class=""close"">&times;</span>
+  <img class=""modal-content"" id=""img01"">
+  <div id=""caption""></div>
+</div>
+
+
+

","

the listeners are removed when content is swapped, add image listeners there instead:

+

+
+
var modal = document.getElementById('myModal');
+var images = document.getElementsByClassName('img');
+var modalImg = document.getElementById(""img01"");
+
+
+var span = document.getElementsByClassName(""close"")[0];
+
+span.onclick = function() {
+  modal.style.display = ""none"";
+}
+
+
+function show(param_div_id) {
+  document.getElementById('main').innerHTML = document.getElementById(param_div_id).innerHTML;
+
+    for (var i = 0; i < images.length; i++) {
+      var img = images[i];
+      img.onclick = function(evt) {
+        console.log(evt);
+        modal.style.display = ""block"";
+        modalImg.src = this.src;
+      }
+    }
+
+}
+
.img {
+  border-radius: 5px;
+  cursor: pointer;
+  transition: 0.3s;
+}
+
+.img:hover {
+  opacity: 0.8;
+}
+
+.modal {
+  display: none;
+  /* Hidden by default */
+  position: fixed;
+  /* Stay in place */
+  z-index: 10;
+  /* Sit on top */
+  padding-top: 100px;
+  /* Location of the box */
+  left: 0;
+  top: 0;
+  width: 100%;
+  /* Full width */
+  height: 100%;
+  /* Full height */
+  overflow: auto;
+  /* Enable scroll if needed */
+  background-color: rgb(0, 0, 0);
+  /* Fallback color */
+  background-color: rgba(0, 0, 0, 0.9);
+  /* Black w/ opacity */
+}
+
+.modal-content {
+  margin: auto;
+  display: block;
+  width: 80%;
+  max-width: 700px;
+}
+
+.modal-content,
+#caption {
+  animation-name: zoom;
+  animation-duration: 0.6s;
+}
+
+@keyframes zoom {
+  from {
+    transform: scale(0)
+  }
+  to {
+    transform: scale(1)
+  }
+}
+
+.close {
+  position: absolute;
+  top: 15px;
+  right: 35px;
+  color: #f1f1f1;
+  font-size: 40px;
+  font-weight: bold;
+  transition: 0.3s;
+}
+
+.close:hover,
+.close:focus {
+  color: #bbb;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+@media only screen and (max-width: 700px) {
+  .modal-content {
+    width: 100%;
+  }
+}
+
+#main {
+  background-image: url('bkgd.jpg');
+  display: block;
+  width: 690px;
+  font-family: ""Book Antiqua"";
+  color: #004B97;
+  font-size: 16pt;
+  padding: 2%;
+  margin: 5px;
+  border-radius: 15px;
+  border: medium #9999FF solid;
+}
+
+.mainContents {
+  display: flex;
+  flex-wrap: wrap;
+  margin: 0 auto;
+  position: relative;
+  width: 690px;
+  flex-wrap: wrap;
+  justify-content: center;
+}
+
+#home,
+#bills,
+#munTax,
+#schoolTax,
+#interimTax,
+#taxCert,
+#dupsReceipts,
+#directions,
+#FAQ {
+  display: none;
+  width: 300px;
+  font-family: ""Book Antiqua"";
+  color: #004B97;
+}
+
+.head {
+  width: 100%;
+  text-align: center;
+  font-family: inherit;
+  font-size: 16pt;
+  color: #004B97;
+  padding-bottom: 10px;
+}
+
+.head2 {
+  position: relative;
+  width: 100%;
+  text-align: center;
+  font-family: inherit;
+  font-size: 14pt;
+  color: #835BF9;
+  padding-bottom: 15px;
+}
+
+.lower {
+  width: 100%;
+  display: flex;
+  margin: 0 auto auto 10;
+  flex-wrap: wrap;
+  justify-content: space-around;
+  padding: 10px;
+  align-items: center;
+}
+
+.pay {
+  text-align: center;
+  background-image: url('background.jpg');
+  color: #0D095E;
+  font-size: 14pt;
+  border: medium #9999FF solid;
+  border-radius: 15px;
+  padding: 5px;
+  margin: 5px;
+}
+
<div id=""main"">
+  <div class=""mainContents"">
+    <div class=""head"">Outside Receiving Hours:<br/> Please use secure drop box outside building
+    </div>
+    <div class=""head2"">
+      <strong>2022 Millage Rates</strong><br/> County - 3.2273; Township - .62; PVSD (School + Library) = 23.8117
+    </div>
+    <div class=""lower"">
+      <div class=""pay"">
+        Pay Tax Bill Online<br/>
+        <img alt=""Pay Online"" height=""80"" src=""payonline.png"" width=""144"">
+      </div>
+
+      <div class=""pay"">
+        Understanding Your Tax Bill<br/>
+
+        <button onclick=""show('bills')"" class=""link""><img alt=""Fall Bill"" height=""129"" src=""FallTaxBill-psd.png"" width=""300""></button>
+      </div>
+    </div>
+  </div>
+</div>
+
+<div id=""bills"">
+  <div class=""mainContents"">
+    <div class=""head"">Understanding Your Tax Bill</div><br/>
+    <div class=""lower"">
+      <div class=""pay"">
+        Spring Tax Bill<br/>
+        <img class=""img"" src=""http://onebigphoto.com/uploads/2012/10/midnight-sun-in-lofoten-norway.jpg"" alt=""Midnight sun in Lofoten, Norway"" width=""300"" height=""200"">
+      </div>
+      <div class=""pay"">
+        Fall Tax Bill<br/>
+        <img class=""img"" src=""http://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/1490029386/fisherman-cabin-hamnoy-lofoten-islands-norway-NORWAY0320.jpg?itok=cpPuUjh1"" alt=""Fishermen's cabins in Lofoten, Norway"" width=""300"" height=""200"">
+      </div>
+      <div class=""pay"">
+        Fall Tax Bill Stubs<br/>
+        <img class=""img"" src=""http://fjordtours.blob.core.windows.net/fjordtours-umbraco/1199/gerirangerfjord-per-ottar-walderhaug-fjordnorway.jpg"" alt=""Gerirangerfjord, Norway"" width=""300"" height=""200"">
+      </div>
+    </div>
+  </div>
+</div>
+
+<div id=""myModal"" class=""modal"">
+  <span class=""close"">&times;</span>
+  <img class=""modal-content"" id=""img01"">
+  <div id=""caption""></div>
+</div>
+
+
+

",r +"how to calculate error part in of fitted line of polyfit to data?

I am confused about the error part of polyfit. I have the following code:

+
def polyfit(df,columns, degree):
+    coef=[]
+    error=[]
+    x = np.array(list(range(0,df.shape[0])))
+    for skill in columns:
+        y=df[skill]
+        y=pd.to_numeric(y)
+        coeffs = numpy.polyfit(x, y, degree)
+
+        # Polynomial Coefficients
+        coef.append(coeffs.tolist()[0])
+
+        # r-squared
+        p = numpy.poly1d(coeffs)
+        # fit values, and mean
+        yhat = p(x)                         # or [p(z) for z in x]
+        ybar = numpy.sum(y)/len(y)          # or sum(y)/len(y)
+        ssreg = numpy.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
+        sstot = numpy.sum((y - yhat)**2)    # or sum([ (yi - ybar)**2 for yi in y])
+        error.append(ssreg / sstot)
+        
+    results = pd.DataFrame({'skills':columns, 'coef': coef, 'error':error, 'error2':sstot})
+    return results
+
+

where a sample of df is:

+
new_list    administrative coordination administrative law  administrative support
+0   0.0465116   0.0232558   0.0581395
+1   0.0714286   0   0.0285714
+2   0.0210526   0   0.0421053
+3   0.0288462   0.00961538  0.0961538
+4   0.0714286   0.0238095   0.107143
+5   0.00952381  0   0.0666667
+6   0.0285714   0.00952381  0.0666667
+7   0.0428571   0   0.0428571
+8   0.111111    0.0277778   0.138889
+9   0   0.0136986   0.0273973
+
+

the result is as below:

+
polyfit(df,['administrative coordination',  'administrative law',   'administrative support'], 1)
+
+skills  coef    error   error2
+0   administrative coordination -0.000573   0.002681    0.011538
+1   administrative law  0.000511    0.020165    0.011538
+2   administrative support  0.002245    0.036025    0.011538
+
+

But why error2 is the same for all columns? where i am making mistake about calculating error part? I wanna find columns with minimum errors. +By error I mean minimum distances of fitted line to data points.

","

Your variable sstot is a scalar and will be reset for each iteration of your loop. This means that when you run the following line:

+
results = pd.DataFrame({'skills':columns, 'coef': coef, 'error':error, 'error2':sstot}) 
+
+

The column error2 will be set to scalar value of sstot in the most recent iteration of your for loop, which is why error2 has all the same value.

+

I am guessing that you meant to keep track of sstot for each skill, so you can create a list called error2, then set the column error2equal to this list (like the lists you created forcoefanderror`). For example:

+
def polyfit(df,columns, degree):
+    coef=[]
+    error=[]
+    error2=[]
+    x = np.array(list(range(0,df.shape[0])))
+    for skill in columns:
+        y=df[skill]
+        y=pd.to_numeric(y)
+        coeffs = np.polyfit(x, y, degree)
+
+        # Polynomial Coefficients
+        coef.append(coeffs.tolist()[0])
+
+        # r-squared
+        p = np.poly1d(coeffs)
+
+        # fit values, and mean
+        yhat = p(x)                         # or [p(z) for z in x]
+        ybar = np.sum(y)/len(y)          # or sum(y)/len(y)
+        ssreg = np.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
+        sstot = np.sum((y - yhat)**2)    # or sum([ (yi - ybar)**2 for yi in y])
+        error.append(ssreg / sstot)
+        error2.append(sstot)
+
+    results = pd.DataFrame({'skills':columns, 'coef': coef, 'error':error, 'error2':error2})
+    return results
+
+

Result using your sample df:

+
>>> polyfit(df,['administrative coordination',  'administrative law',   'administrative support'], 1)
+                        skills      coef     error    error2
+0  administrative coordination -0.000573  0.002681  0.010100
+1           administrative law  0.000511  0.020165  0.001069
+2       administrative support  0.002245  0.036025  0.011538
+
",r +"How does it work when executing the $regex query in Mongodb?

I have a question about Mongodb Index.

+

As far as I know, when the query is executed, it is found in the data sorted by the selected Index

+
db.HASH_TAG.find({"hashtag" : { $regex : "^Test"}}).sort({htseq:1}).hint("hashtag_1_htseq_1").explain("executionStats");
+
+

========================= explain===============================

+
executionStages  :{
+  "stage" : "SORT", 
+  "inputStage" : {
+     "stage" : "SORT_KEY_GENERATOR",
+     "inputStage" : {
+             "stage" : "FETCH",
+              "inputStage" : {
+                        "stage" : "IXSCAN",
+                        "indexName" : "hashtag_1_htseq_1", 
+                         "keyPattern" : {
+                            "hashtag" : 1.0, 
+                            "htseq" : 1.0
+                        }, 
+                  }
+          }
+     }
+}
+
+

Please explain why SORT_KEY_GENERATOR occurs in the input stage.

","

Your regular expression is not an equality match, therefore the query planner cannot guarantee ahead of time that the index will return the documents in sorted order.

+

The values in the index will be sorted by hashtag and then by htseq, the regex would match hashtags "Test", "Tester", "Tested", "Testing", etc., so the matched documents will still need to be sorted to be returned in order of htseq values.

+

You might be able to get index-supported sorting by anchoring both end of the regex like { $regex : "^Test$"}, but at that point you may as well just use equality match.

",r +"I need to write a trigger in oracle before insert statement using 2 tables

Table 1 +RPA_DUTY_BUDGET

+
column : material
+column : duty_budget
+
+

Table 2 +RPA_IMPORTS

+
column : material
+column : grn
+column : amount
+column : duty_actuals
+column : duty_budget
+
+

When I need to insert the data into RPA_IMPORTS then I need to search for the material and its corresponding duty_budget from RPA_DUTY_BUDGET and insert those values.

+

I could easily achieve this by using a join, however the since the duty changes periodically it will take the latest duty, that is the reason, I need to store in RPA_IMPORTS for further calcualtion.

","

This doesn't even require a join.

+
create or replace trigger trg_biu_imp
+  before insert or update on rpa_imports
+  for each row
+begin
+  select d.duty_budget
+    into :new.duty_budget
+    from rpa_imports i
+    where i.material = :new.material;
+end;
+/    
+
",r +".Net cors policy issue

I have a web project: .Net core API as a backend and React app as a frontend and everything is working fine with every browser except Mozilla private tab. When I run my react app in Mozilla private window this error occurs:

+

Cross-Origin Request Blocked: ... Reason: CORS request did not succeed

+

but if my cors policy is not correct how can other browsers connect my backend without any problem? (p.s Mozilla normal tab works fine as well)

+

Question: what is the problem and how can I fix it?

","

Here's a lot of same question :) +I'm facing same problem now.

+

After hundreds attempts i have semi-solition:

+

Startup.cs:

+
public void ConfigureServices(IServiceCollection services)
+{
+  services.AddCors();
+  //some other code here...
+}
+
+public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+{
+  //some code...
+  app.UseRouting();
+
+  app.UseCors(x => x
+              .SetIsOriginAllowed(origin => true)
+              .AllowAnyMethod()
+              .AllowAnyHeader()
+              .AllowCredentials()
+              .Build());   
+
+ app.UseAuthorization();
+ //other code
+}
+
+

In react application:

+
export const loginUser = createAsyncThunk(
+  'user/loginUser',
+   async function(loginCredentials, {rejectWithValue}) {      
+   try {                
+       const response = await fetch(`https://localhost:5001/usr/loginuser`, {                
+             method: 'POST',                
+             headers: {                                                                          
+                 'Content-Type': 'text/plain',
+                 'Accept': 'text/plain',
+             },
+             body: JSON.stringify({loginCredentials})
+         });
+           
+         if (!response.ok) {
+              throw new Error('Server Error!');
+        }
+
+//other code
+
+

With this code i have situation when most of request are failed (seems like 'fetch canceled' in browser) but about 30% request are successfully. That's why i called it "semi"-solution.

+

Have no idea what's happening, because failed and normal requests are identical (headers and body).

",r +"React.js what is the best technique to show to the user different pages according to there role

there a sec or two that the wrong page appears on the screen until the request get me the user's role so i can show him the right page. +how can i show them the right page since the first moment

","

The best way is to handle the role is App.js File because all your route are there and then you can specifiy which route should be avalible according to thier roles.like this example:

+
// App.js 
+function App() {
+const [addUserManagment, setAddUserManagment] = useState({
+   render: false,
+   type: "",
+});
+useEffect(() => {
+   const space = localStorage.getItem("space");
+   if (space === "c" || space === "a") {
+   setAddUserManagment({
+      render: true,
+      type: space,
+   });
+  }
+}, []);
+  return (
+<div className="App">
+  <Routes>
+    <Route path="/">
+      <Route index element={<Login />} />
+      <Route path="forget-password" element={<ForgetPassword />} />
+      <Route path="reset-password/:token" element={<RestPassword />} />
+      <Route
+        path="register/:campanyName/:companyId"
+        element={<InviteRegister />}
+      />
+    </Route>
+          <Route path="profile" element={<Profile />} />
+      {addUserManagment.render && (
+        <Route path="setting" element={<Setting />} />
+      )}
+      {addUserManagment.render && (
+        <Route
+          path="user-management"
+          element={
+            addUserManagment.type === "c" ? <UserList /> : <UserListAdmin />
+          }
+        />
+      )}
+    </Route>
+   </Routes>
+  )
+}
+
+

Now settign and user-managment are rendered if type of user equal to c or a.

",r +"R: Set next row to NA in group_by

I want to set the next row i+1 in the same column to NA if there is already an NA in row i and then do this by groups. Here is my attempt:

+
dfeg <- tibble(id = c(rep("A", 5), rep("B", 5)),
+               x = c(1, 2, NA, NA, 3, 5, 6, NA, NA, 7))
+
+setNextrowtoNA <- function(x){
+  
+  for (j in 1:length(x)){
+    
+    if(is.na(x[j])){x[j+1] <- NA}
+    
+  }
+}
+
+dfeg <- dfeg %>% group_by(id) %>% mutate(y = setNextrowtoNA(x))
+
+

However my attempt doesn't create the column y that am looking for. Can anyone help with this? Thanks!

+

EDIT: In my actual data I have multiple values in a row that need to be set to NA, for example my data is more like this:

+
dfeg <- tibble(id = c(rep("A", 6), rep("B", 6)),
+                   x = c(1, 2, NA, NA, 3, 4, 15, 16, NA, NA, 17, 18))
+
+

And need to create a column like this:

+
y = c(1, 2, NA, NA, NA, NA, 15, 16, NA, NA, NA, NA)
+
+

Any ideas? Thanks!

+

EDIT 2:

+

I figured it out on my own, this seems to work:

+
dfeg <- tibble(id = c(rep("A", 6), rep("B", 6)),
+               x = c(1, 2, NA, NA, 3, 4,  15, 16, NA, NA, 17, 18))
+
+setNextrowtoNA <- function(x){
+  
+  for (j in 1:(length(x))){
+    
+    if(is.na(x[j]))
+    {
+      x[j+1] <- NA
+      }
+    lengthofx <- length(x)
+    x <- x[-lengthofx]
+    print(x[j])
+  }
+  return(x)
+}
+
+dfeg <- dfeg %>% group_by(id) %>% mutate(y = NA,
+                                         y = setNextrowtoNA(x))
+
","

Use cumany:

+
library(dplyr)
+dfeg %>% 
+  group_by(id) %>% 
+  mutate(y = ifelse(cumany(is.na(x)), NA, x))
+
+   id        x     y
+   <chr> <dbl> <dbl>
+ 1 A         1     1
+ 2 A         2     2
+ 3 A        NA    NA
+ 4 A        NA    NA
+ 5 A         3    NA
+ 6 A         4    NA
+ 7 B        15    15
+ 8 B        16    16
+ 9 B        NA    NA
+10 B        NA    NA
+11 B        17    NA
+12 B        18    NA
+
+
+

Previous answer:

+

Use an ifelse statement with lag:

+
library(dplyr)
+dfeg %>% 
+  group_by(id) %>% 
+  mutate(y = ifelse(is.na(lag(x, default = 0)), NA, x))
+
",r +"How to replace the text with the previous text in the label?

I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.

+
from tkinter import *
+
+root = Tk()
+root.geometry("400x400")
+
+my_label = Label(text="Hello").pack()
+
+def test():
+    my_label = Label(text="Bye").pack()
+
+my_button = Button(root, text="Open a file", command=test).pack()
+
+root.mainloop()
+
+

I saw that people using config to do that. But I don't understand what is the problem with my code.

+
from tkinter import *
+
+root = Tk()
+root.geometry("400x400")
+
+global my_label
+my_label = Label(text="Hello").pack()
+
+def test():
+    my_label.config(text="Bye")
+
+
+my_button = Button(root, text="Open a file", command=test).pack()
+
+root.mainloop()
+
+

It gives me this error:

+
AttributeError: 'NoneType' object has no attribute 'config'
+
","

You don't use global at the global level. You should remove that.

+

The PROBLEM is that the .pack() method returns None. Tkinter is a hopelessly antiquated relic of software days gone by, and does not use good object practices. You need

+
my_label = Label(text="hello")
+my_label.pack()
+
",r +"Programming Languages where a keyword is needed to specify that the method is extended from its parent class

Forgive me for my ignorance, but does anyone know any languages that strictly enforce the condition I've given on the title? For example, using Python syntax, we can extend a class with a new method like this

+
class A:
+    pass
+
+class B(A):
+    def foo(self):
+        pass
+
+

But is there a language that needs an additional keyword, let's say new, to specify that this method is unique to the child class and is not an override of the methods of its parent class/es? For example:

+
class A:
+    pass
+
+class B(A):
+    def new foo(self):
+        pass
+
+

I am asking this because, when I am working on a project that requires multiple inheritance such as class B(A, C, D), and I saw a method defined in B, I need to check if the given method is from one of its parent class or its own method, and I find it extremely tedious.

","

The closest I can think of is the @Override annotation in Java, which can be applied to a method declaration in order for the compiler to check that it overrides an inherited method (or implements an interface method).

+

When used in conjunction with a linter which checks that all method overrides are annotated with @Override, then your IDE will give you a linter warning when you omit the annotation. IntellIJ IDEA and SonarSource both have linter rules for this, for example.

+

So long as you are strict about obeying the linter warning, then it's "strict" in that sense, but of course linter warnings don't actually prevent your code from being compiled or executed. Nonetheless, I don't know of a closer example from a real programming language. Unfortunately Java doesn't have multiple inheritance so it's not directly applicable to your problem.

",r +"Pandas: Get list of shared values of column B that two different values from column B have in common

I have a table like this:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
imageuser
11
21
31
12
32
23
33
......
+
+

Now I want to find shared images between two users. For example, when I ask for the images shared between user 1 and user 2, I want [1, 3] as a result.

+

How could I achieve this?

","

Expanding on @BrendanA's answer, you can use itertools.combinations to get all 2-combinations, find their shared images and cast the result to a DataFrame:

+
from itertools import combinations
+users_to_images = df.groupby('user')['image'].agg(set)
+data = {(i,j): [list(users_to_images[i].intersection(users_to_images[j]))] for i,j in combinations(users_to_images.index, 2)}
+out = pd.DataFrame.from_records(data, index=['shared_images']).T
+
+

Output:

+
       shared_images
+(1, 2)        [1, 3]
+(1, 3)        [2, 3]
+(2, 3)           [3]
+
+

Then users 1,2 share images 1,3; users 1,3 share 2,3, etc.

",r +"How to refetch apollo query after i redirect to page with Vue Router?

I delete some resource in a page via apollo mutation:

+
async delete () {
+  await this.$apollo.mutate({
+    mutation: orderDelete,
+    variables: {
+      id: this.order.id
+    }
+  })
+
+  this.$emit('success')
+}
+
+

This is the method triggered by success emitter:

+
onOrderDeleted () {
+  this.closeModal('modalOrderDelete')
+
+  this.$nextTick(() => {
+    this.redirectToClient()
+  })
+},
+redirectToClient () {
+  this.$router.push({
+    name: 'clients.show',
+    params: { clientKey: this.clientKey }
+  })
+}
+
+

Here is what happen: when the page is redirected to clients.show the order is still being show even if i deleted it, it only updates if i refresh the whole page.

+

So i would like to know how i trigger a query refresh when i redirect to this page? Apollo is probably keeping data in cache and not updating it, i don't know how to update the cache only of this specific query, but all programatically because the user will be redirect via Vue Router.

+

Note: clients.show shows a list of orders, so it should update the orders removing that one i just deleted, but it just doesn't change.

","

this.$apollo.mutate() has more features than you used:

+

The object looks like this:

+
this.$apollo.mutate({
+  mutation: someGql,
+  variables: {
+    label: param1,
+  },
+  update: function(store, response) => {
+    // how to update the store
+  },
+  optimisticResponse: theResponseYouExpect,
+})
+
+

So, you sent the gql, but did not handle the response from that query (neither the real response from the server or the optimistic response (that you expect on success))

+

More on Vue Apollo mutation here.

",r +"Is there a way to always stay at the searched-for Symbol location when using vscode and pressing `esc` key?

Let's say I use Go to Symbol in Editor. Let's further say I have a function def run(): (this is Python) that I want to jump to.

+

If I type @run in the Symbol search dropbox, the viewport will shift to def run in the source code.

+

So far, so I good. I have found what I want!

+

At that point, if I press esc I jump back to my starting location, rather than staying at def run() in the source. I have to remember to press Enter to get out of Go to Symbol in Editor... and stay at my location.

+

How can I make it so esc, by itself, always leaves me where I have found the symbol in the text?

+

I.e. I want to get more the behavior I get from using Edit, Find where esc leaves at the pattern location. And pressing Enter when in Find mode jumps me to the next pattern hit, if any.

+

environment: macos, vscode 1.63.2 (latest as of now)

+

p.s. You also get the same behavior from a Go to Line/Column... dialog, esc will yank you back to your starting point, Enter will leave you at the new location.

","

I'm afraid it's not currently possible. I've tried to unbind every single keyboard shortcut bound to Escape key so it should basically become a dead key, yet even with this setting symbol suggest highlight were cancelled by pressing the Escape, so no luck.

+

Unbinding the primary action is normally prerequisite for changing default behaviour -- in your case for mapping it to "accept highlighted symbol" action (which I haven't found either) -- so it seems that Enter/Escape behaviour of symbol palette is not exposed for remapping.

",r +"Does the event `invalid` only fire once?

I tried to hook into the invalid event for numeric input (which is required), and while the invalid event fires right on loading the page (as all the cells are empty), it does not refire if one fills an input field and removes its content or inputs a letter instead of a number. But I could not find anything indicating that this would be its behaviour. But at the same time I can also not find an issue with my code. So I guess I am first asking what the desired behaviour is before I continue hunting for bugs.

","

Apparently rubber ducking is quite helpful:

+

The invalid event only fires on form submission, while the css :invalid styling is applied live on input events rather than only after submission events.

+
+

If a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire

+
+

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event

",r +"How to fill in gaps of duplicate indices in dataframe?

I have a dataframe like as shown below

+
tdf = pd.DataFrame({'grade': np.random.choice(list('AAAD'),size=(5)),
+                   'dash': np.random.choice(list('PPPS'),size=(5)),
+                   'dumeel': np.random.choice(list('QWRR'),size=(5)),
+                   'dumma': np.random.choice((1234),size=(5)),
+                   'target': np.random.choice([0,1],size=(5))
+})
+
+

I am trying to create a multi-index dataframe using some of the input columns

+

So, I tried the below

+
tdf.set_index(['grade','dumeel'],inplace=True)
+
+

However, this results in missing/gap for duplicate entries (in red highlight)

+

+

How can I avoid that and show my dataframe with all indices (whether it is duplicate or not)

+

I would like to my output to have all rows with corresponding indices based on original dataframe

","

It is only display issue:

+
tdf.set_index(['grade','dumeel'],inplace=True)
+
+print (tdf)
+             dash  dumma  target
+grade dumeel                    
+A     W         S    855       1
+      R         P    498       1
+      R         P    378       0
+      W         P    211       0
+      W         P     12       0
+      
+with pd.option_context("display.multi_sparse", False):
+    print (tdf)
+             dash  dumma  target
+grade dumeel                    
+A     W         S    855       1
+A     R         P    498       1
+A     R         P    378       0
+A     W         P    211       0
+A     W         P     12       0
+
",r +"No tidy method for objects of class formula using friedman.test in R

here the datasets with repeated measure

+
alt=structure(list(groupter = c(1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 
+1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
+2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L), screen = c(12.2, 
+24.4, 13.5, 18.5, 13.9, 16.6, 12, 16.6, 13.5, 15.9, 11.5, 9.6, 
+44, 22.2, 17.1, 31.2, 13.7, 39.9, 11.5, 20, 27.5, 18.5, 22.2, 
+21.9, 18.3, 42.1, 16.4, 16.6, 12, 28.7, 10.3, 33.6, 10.1, 22.7, 
+7.2, 28, 16.4, 13.2), vizit.1.day.2 = c(16.1, 9.8, 9.3, 21, 11.3, 
+9.8, 11.3, 16.6, 15.4, 14.9, 11, 10.3, 22.7, 15.4, 33.3, 15.2, 
+9.3, 32.1, 10.3, 13.9, 32.1, 14.4, 23.2, 17.1, 17.8, 27, 15.4, 
+29.9, 12.2, 16.8, 9.6, 18.1, 10.5, 15.4, 13.2, 11.5, 20, 9.6), 
+    vizit.2.day.9 = c(10.1, 16.4, 11.5, 21.9, 20, 12.5, 12.5, 
+    13.5, 14.9, 17.1, 10.8, 11, 21.7, 14.4, 16.4, 34.5, 9.3, 
+    23.6, 12, 12.5, 32.6, 11.3, 19.3, 16.4, 12.2, 30.7, 12, 28, 
+    14.4, 17.1, 9.8, 22.7, 11.5, 13.2, 11.5, 10.5, 13.9, 14.9
+    ), vizit.3.day.16 = c(22.7, 12.7, 22.4, 16.4, 12.2, 11, 10.8, 
+    13, 13, 12.5, 9.6, 8.6, 17.8, 12.2, 13.5, 22.4, 8.4, 26.8, 
+    14.4, 11.8, 72.9, 8.6, 19.5, 16.4, 14.2, 32.8, 12, 27.5, 
+    9.1, 13, 9.3, 18.1, 11, 10.8, 12.7, 24.6, 13, 13.5), vizit.4.day.23 = c(23.9, 
+    14, 11.2, 13.7, 21.1, 10.5, 15.6, 18.6, 13.7, 14.2, 12.4, 
+    7.5, 20.9, 15.6, 13.7, 20.7, 8.2, 44, 10.7, 10.3, 32.2, 7, 
+    20.2, 11.7, 29, 23.2, 10.7, 23.9, 9.8, 11.4, 9.1, 19.5, 8.7, 
+    11.9, 11.7, 11.4, 20, 10.7), vizit.5.day.29 = c(13.5, 16.7, 
+    15.4, 14.9, 44, 11, 14.4, 15.6, 11, 12.6, 11.4, 9.4, 26.2, 
+    14, 17.4, 18.8, 10.3, 41.2, 12.6, 11.9, 28.5, 8.4, 20.7, 
+    12.8, 24.1, 30.6, 13.7, 26.9, 13.5, 11.9, 10, 8.4, 10, 13, 
+    12.4, 11.7, 16.3, 11.2)), class = "data.frame", row.names = c(NA, 
+-38L))
+
+

i want do test for dependent samples, in this case the Friedman test, but for each study group separately(groupter). +i can simple perform friedman.test for example so friedman.test(alt) and will be glad the result. But the main problem that in my datasets there is grouping variable groupter, and I need to do it not for the entire dataset, but for each group separately for groupter = 1 separately and groupter = 2 separately.

+
 ?friedman.test
+
+

does not allow to be divided into groups .

+

How for each category of groupter perform friedman.test by all metric vars.

+

from screen to vizit 5 day 29

+

to get needed output

+
alt                         
+groupter    screen  vizit 1 day 2   vizit 2 day 9   vizit 3 day 16  vizit 4 day 23  vizit 5 day 29  
+1                           0,05
+2                           0,05
+
+

I use group_map but i get error

+
> if (requireNamespace("broom", quietly = TRUE)) {
++   # a list of tibbles
++   alt %>%
++     group_by(groupter) %>%
++     group_map(~ broom::tidy(friedman.test~., data = .x))}
+ Error: No tidy method for objects of class formula 
+
+

Please help. As usual any help is greatly appreciated.

","
 alt %>% 
+  group_by(groupter) %>% 
+  mutate(id_row = row_number()) %>% 
+  pivot_longer(-c(id_row, groupter)) %>% 
+  nest() %>% 
+  mutate(result = map(data, ~friedman.test(value ~ name | id_row, data = .x))) %>% 
+  mutate(out = map(result, broom::tidy)) %>% 
+  select(-c(data, result)) %>% 
+  ungroup() %>% 
+  unnest(out)
+
+  groupter statistic p.value parameter method                
+     <int>     <dbl>   <dbl>     <dbl> <chr>                 
+1        1      14.5  0.0129         5 Friedman rank sum test
+2        2      11.7  0.0389         5 Friedman rank sum test
+
",r +"Form validation with js if one of the entries in the table rows is filled in, the other must also be filled in before submitting the form

Here's an example of the form. Note: in each TR(Line) the user, when filling in an input, has to fill in the other input as well.

+

+
+
document.addEventListener(""DOMContentLoaded"", function(){
+   
+   document.getElementById(""form"").onsubmit = function(e){
+      
+      var tr = document.querySelectorAll(""#tabcli1 tr"");
+      
+      for(var x = 0; x < tr.length; x++){
+         
+         var inps = tr[x].querySelectorAll(""input"");
+         
+         for(var i = 0; i < inps.length; i++){
+            if(inps[i].value.trim()) break;
+         }
+
+         if(i == inps.length){
+            e.preventDefault();
+            alert(""Tem de preencher os dois campos das linhas que tem um valor!"");
+            break;
+         }else{
+           
+         }
+         
+      }
+   
+   }
+   
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+
+<form id=""form"">
+<table class=""table table-bordered table-striped"" style=""width:100%;"" id=""tabcli1"">
+  <thead>
+  </thead>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+</table>
+<div style=""float: right; width:  100%;"">
+  <button class=""btn btn-raised btn-success ripple-effect"" style=""float: right;"" >Gravar <i class=""fa fa-paper-plane""></i></button> 
+  </div>
+</form>
+
+
+

+

The way my code is running forces me to fill in at least one input on each line.

+

What I want is that if you fill in one of the inputs on the line, it forces you to fill in the other input on the same line.

","

You can do this with below code.

+

+
+
document.addEventListener(""DOMContentLoaded"", function(){
+   
+document.getElementById(""form"").onsubmit = function(e){
+  
+    var tr = document.querySelectorAll(""#tabcli1 tr"");
+    var flag = false;
+  
+    for(var x = 0; x < tr.length; x++){
+     
+        var inps = tr[x].querySelectorAll(""input"");
+        var selcts = tr[x].querySelectorAll(""select"");
+     
+        for(var i = 0; i < inps.length && i < selcts.length; i++){
+            if((inps[i].value.trim() != '' && selcts[i].value.trim() == '') || (inps[i].value.trim() == '' && selcts[i].value.trim() != '')) {
+                flag = true;
+            }
+    
+        }
+    }
+    if(flag == true) {
+        e.preventDefault();
+        alert(""Tem de preencher os dois campos das linhas que tem um valor!"");
+        flag = false;
+    }
+}
+   
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
+<form id=""form"">
+<table class=""table table-bordered table-striped"" style=""width:100%;"" id=""tabcli1"">
+  <thead>
+  </thead>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+  <tbody>
+    <tr class=""table__row"">
+      <td class=""table__content"" data-heading=""Quantidade""><input min='0' oninput='this.value = Math.abs(this.value)' type=""number"" class=""form-control"" name=""Quantid[]"" ></td>
+      <td class=""table__content"" data-heading=""Tamanho""><select class=""form-control"" name=""taman[]""><option></option><option value=""S""> S</option><option value=""M""> M</option><option value=""L""> L</option></select></td>
+    </tr>
+  </tbody>
+</table>
+<div style=""float: right; width:  100%;"">
+  <button class=""btn btn-raised btn-success ripple-effect"" style=""float: right;"" >Gravar <i class=""fa fa-paper-plane""></i></button> 
+  </div>
+</form>
+
+
+

",r +"How to use virtual environment installed on Ubuntu which is installed on Windows?

Recently, I've installed airflow on Windows 10 by installing it on Ubuntu from MS Store. And I can see Airflow web-server from a browser from Windows. However, now I want to create a DAG using Pycharm on Windows, and I have to select python interpreter with airflow installed in its venv.

+

Where can I find this virtual environment from Windows?

","

I solved this problem myself. WSL is the feature of Pycharm professional edition, and there is no way to use it in the community edition.

+

https://www.jetbrains.com/help/pycharm/using-wsl-as-a-remote-interpreter.html#configure-wsl

",r +"How to query based on a hierarchy level?

I have table that contains 3 main attributes: STAGING_ID, DEVELOPMENT_ID & PRODUCTION_ID for each NUMBER_ID. I want to query a table based on this table that says:

+
IF there are NO null values in any of the three columns, select STAGING_ID in 'MAIN_ID' column and 'LEVEL_DESCRIPTION' to be STAGING
+IF there is a NULL value in only STAGING_ID (not DEVELOPMENT_ID or PRODUCTION_ID), then select the next level, which would be DEVELOPMENT_ID in 'MAIN_ID' column, and 'LEVEL_DESCRIPTION' to be DEVELOPMENT
+IF there is a NULL value in STAGING & DEVELOPMENT (not PRODUCT_ID), then select the next level, which would be PRODUCT_ID in 'MAIN_ID' column, and 'LEVEL_DESCRIPTION' to be PRODUCTION
+
+

So the levels always follow this hierarchy, STAGING > DEVELOPMENT > PRODUCTION.

+
So in the picture,
+FIRST ROW, should be: LEVEL_DESCRIPTION: STAGING, MAIN_ID: 3532
+SECOND ROW, should be: LEVEL_DESCRIPTION: DEVELOPMENT, MAIN_ID: 3532
+THIRD ROW, should be: LEVEL_DESCRIPTION: PRODUCTION, MAIN_ID: 1081
+
+

+

So when I query based on this table, I would need 3 columns:

+
+

NUMBER_ID, MAIN_ID, LEVEL_DESCRIPTION

+
+

Is there I can do that? I'm thinking of a case statement, but I'm having trouble formulating this.

+
DROP TABLE TBL_1;
+CREATE TABLE TBL_1
+(
+    number_id int, 
+      production_id int,
+      develpoment_id int, 
+    staging_id int
+);
+
+INSERT INTO TBL_1
+values 
+(11111,2331, 1233, 3532),
+(11122,9080, 1291, null),
+(11144,1082, null, null)
+
","

Using COALESCE and CASE:

+
SELECT *, 
+  COALESCE(staging_id, development_id, production_id, 'Not found') AS main_id,
+  CASE WHEN staging_id IS NOT NULL THEN 'Staging'
+       WHEN development_id IS NOT NULL THEN 'Development'
+       WHEN production_id IS NOT NULL THEN 'Production'
+       ELSE 'Not found'
+  END AS Level_description
+FROM TBL_1;
+
+

db<>fiddle demo

",r +"Confused by docker networking / connections

OK so I am trying to deploy a Rails app to a docker container (host machine is a mac). I was thinking to deploy in development first to check everything is working.

+

I have setup a phpmyadmin service and I can connect to the server by typing in server name moviedb_mariamovie_1 with user root and corresponding PW. +But whatever I put into my database.yml for Rails doesn't work: I tried localhost, I tried 127.0.0.1, I tried "mariamovie" and I tried "moviedb_mariamovie_1", and it always says "host not found" when I tried rails db:create (or anything actually that involves the DB). +I am totally confused by this. I read the database section of the docker manuals and I seem to be too stupid for that.

+

(I have other problems with this but one after the other :)

+

docker-compose.yml:

+
version: "3.7"
+services:
+  moviedb:
+    image: tkhobbes/moviedb
+    restart: unless-stopped
+    ports:
+      - 3001:3000
+    depends_on:
+      - mariamovie
+    environment:
+      MYSQL_ROOT_PASSWORD: redacted
+      RAILS_ENV: development
+    volumes:
+      - /Users/thomas/Documents/Production/moviedb/storage:/opt/activestorage
+  mariamovie:
+    image: mariadb
+    restart: unless-stopped
+    ports:
+      - 3333:3306
+    environment:
+      MYSQL_ROOT_PASSWORD: redacted
+  phpmymaria:
+    image: phpmyadmin
+    restart: unless-stopped
+    ports:
+      - 8021:80
+    depends_on:
+      - mariamovie
+    environment:
+      PMA_PORT: 3333
+      PMA_ARBITRARY: 1
+    image: nginx:1.21-alpine
+    volumes:
+      - /Users/thomas/Documents/Production/moviedb/vendor/nginx:/etc/nginx/user.conf.d:ro
+    ports:
+      - 8020:8020
+    depends_on:
+      - moviedb
+    restart: unless-stopped
+
+

database.yml:

+
default: &default
+  adapter: mysql2
+  encoding: utf8mb4
+  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
+  host: 127.0.0.1
+  port: 3333
+  username: redacted
+  password: redacted
+
+development:
+  <<: *default
+  database: newmovie_development
+...
+
",

You're inside your docker "network". Your database should be accessible from your Rails app (which is inside too) via mariamovie:3306.

,r +"Why do I get ""ValueError: need more than 1 value to unpack"" when using spaCy convert on my conllu data?

I am trying to convert my training data for spaCy train using spaCy convert. My data looks (after some preprocessing with pandas) like this:

+
1   Hii hii PRON    _   NounClass=9|Num=Sing    _   _   _   _
+2   si  si  VERB    _   _   _   _   _   _
+3   mara    mara    NOUN    _   NounClass=10|Num=Plur   _   _   _   _
+4   ya_kwanza   ya_kwanza   NUM _   _   _   _   _   _
+5   kwa kwa ADP _   _   _   _   _   _
+6   uongozi uongozi NOUN    _   NounClass=11|Num=Sing   _   _   _   _
+
+

I used the following command in the Terminal:

+
PS C:\Users\...\pythonProject1> python -m spacy convert C:\Users\...\pythonProject1\my_dataframe_ready.conllu C:\Users\...\pythonProject1\train
+
+

and get the following output:

+
ℹ Grouping every 1 sentences into a document.
+⚠ To generate better training data, you may want to group sentences into
+documents with `-n 10`.
+Traceback (most recent call last):
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\runpy.py", line 193, in _run_module_as_main
+    "__main__", mod_spec)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\runpy.py", line 85, in _run_code
+    exec(code, run_globals)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\__main__.py", line 4, in <module>
+    setup_cli()
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\cli\_util.py", line 71, in setup_cli
+    command(prog_name=COMMAND)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\click\core.py", line 829, in __call__
+    return self.main(*args, **kwargs)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\click\core.py", line 782, in main
+    rv = self.invoke(ctx)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\click\core.py", line 1259, in invoke
+    return _process_result(sub_ctx.command.invoke(sub_ctx))
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\click\core.py", line 1066, in invoke
+    return ctx.invoke(self.callback, **ctx.params)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\click\core.py", line 610, in invoke
+    return callback(*args, **kwargs)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\typer\main.py", line 500, in wrapper
+    return callback(**use_params)  # type: ignore
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\cli\convert.py", line 89, in convert_cli
+    msg=msg,
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\cli\convert.py", line 140, in convert
+    db = DocBin(docs=docs, store_user_data=True)
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\tokens\_serialize.py", line 86, in __init__
+    for doc in docs:
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\training\converters\conllu_to_docs.py", line 38, i
+n conllu_to_docs
+    for sent_doc in sent_docs:
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\training\converters\conllu_to_docs.py", line 85, i
+n read_conllx
+    ner_map=ner_map,
+  File "C:\Users\...\miniconda3\envs\pythonProject1\lib\site-packages\spacy\training\converters\conllu_to_docs.py", line 209,
+in conllu_sentence_to_doc
+    heads=heads,
+  File "spacy\tokens\doc.pyx", line 366, in spacy.tokens.doc.Doc.__init__
+  File "spacy\morphology.pyx", line 49, in spacy.morphology.Morphology.add
+  File "spacy\morphology.pyx", line 153, in spacy.morphology.Morphology.feats_to_dict
+ValueError: need more than 1 value to unpack
+
+

Is there something still wrong with my Data? I actually have no idea what this Error should be telling me.

","

Based on the line your error is occurring on, it looks like you have a malformed feature list somewhere. A feature list looks like alpha=yes|beta=no. It seems like you might have something that looks like alpha=yes|beta, which is invalid.

+

I think the underscore by itself is a special case and should be valid, but maybe you have some other kind of filler?

+

You can debug this by modifying the conllu_sentence_to_doc function in conllu_to_docs.py to print the morphs value before calling doc = Doc(...).

",r +"Logical solutions, FALSE, TRUE export wrongly to moodle

I've solutions of a cloze question, sol4=FALSE and sol5=TRUE but when I export the exercise to moodle with exsolution: r mchoice2moodle(sol4)|r mchoice2moodle(sol5), both solutions equal TRUE (corresponding to c and d)! Do you know this is some kind of Moodle bug or what am I doing wrong? +

+

","

You cannot represent logical questions/answers by multiple-choice questions of length 1 in Moodle. In R/exams, mchoice questions are allowed to have this format and hence no error is generated. But in Moodle, the corresponding MULTIRESPONSE type needs to have at least two choice and at least one of these needs to be true.

+

Therefore, instead of using a multiple-choice question of length 1, I would use a single-choice question of length 2 like this:

+
Question
+========
+The p-value is: ##ANSWER1##
+
+The null hypothesis is: ##ANSWER2##
+
+Answerlist
+----------
+* 
+* not rejected
+* rejected
+
+Meta-information
+================
+exname: Hypothesis test
+extype: cloze
+exclozetype: num|schoice
+exsolution: 0.123|10
+
+

Then you get a simple drop-down menu with both choices rather than just a single check box. This also has the advantage that you can clearly distinguish between not answering and not true.

+

",r +"Could not find the correct Provider above this TasksScreenNew Widget

I have a problem using Flutter Provider... every time when im clicking at the widget that brings me to the Tasksscreen i'm getting this error. Im really new to Provider... got that code from a tutorial. I'm just stuck with this error for 1 hour now and i haven't found anything suitable for my problem.

+

If you need more code, just say it

+

Error:

+
ProviderNotFoundException (Error: Could not find the correct Provider<TaskData> above this TasksScreenNew Widget
+
+
+
+

Code:

+
import 'package:flutter/cupertino.dart';
+import 'package:flutter/material.dart';
+import 'package:learnon/widgets/tasks_list.dart';
+import 'package:learnon/screens/addtasksscreen.dart';
+import 'package:learnon/models/tasks_data.dart';
+import 'package:provider/provider.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+
+bool theme = false;
+FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
+    FlutterLocalNotificationsPlugin();
+
+class TasksScreenNew extends StatelessWidget {
+  static const routeName = "/tasksnewwidget";
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      backgroundColor: Colors.blueAccent,
+      floatingActionButton: FloatingActionButton(
+        heroTag: null,
+        child: Icon(Icons.add),
+        backgroundColor: Colors.lightBlue,
+        onPressed: () {
+          showModalBottomSheet(
+              isScrollControlled: true,
+              context: context,
+              builder: (BuildContext context) => AddTaskScreen());
+        },
+      ),
+      body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+        Container(
+          padding: EdgeInsets.only(top: 60, left: 30, right: 30, bottom: 30),
+          child: Column(
+            crossAxisAlignment: CrossAxisAlignment.start,
+            children: [
+              SizedBox(
+                height: 10,
+              ),
+              Text(
+                'Todo',
+                style: TextStyle(
+                    color: Colors.white,
+                    fontSize: 50,
+                    fontWeight: FontWeight.bold),
+              ),
+              Text(
+                '${Provider.of<TaskData>(context).taskCount} Tasks',
+                style: TextStyle(fontSize: 18, color: Colors.white),
+              ),
+            ],
+          ),
+        ),
+        Expanded(
+          child: Container(
+            padding: EdgeInsets.symmetric(horizontal: 20),
+            child: TasksList(),
+            decoration: BoxDecoration(
+              borderRadius: BorderRadius.only(
+                topLeft: Radius.circular(20),
+                topRight: Radius.circular(20),
+              ),
+            ),
+          ),
+        )
+      ]),
+    );
+  }
+}
+// CircleAvatar(
+// radius: 30,
+// backgroundColor: Colors.white,
+// child: Icon(
+// Icons.list,
+// color: Colors.blueAccent,
+// size: 30,
+// ),
+// )
+
+
","

To access providers from context, you need to wrap any widget higher up the tree in Provider or ChangeNotifierProvider.

+

You can try doing the following on the current page.

+
Widget build(BuildContext context) {
+  return ChangeNotifierProvider<TaskData>(
+    create: (_) => TaskData(),
+    builder: (context, __) => Scaffold(
+
+

You can also see examples, e.g. here https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

",r +"Get statistical measures of a varchar field in snowflake

I have a field called MER_DATA in a snowflake table having a value as shown below:

+
+

[43,44.25,44.5,42.75,44,44.25,42.75,43,42.5,42.5,36.75,42.25,42.75,43.25,43.25,43.25,42.75,43.5,42,43,43.75,43.75,43.25,41.75,43.25,42.5,43.25,42.75,43.25,43.5,43.25,43.25,43.75,...]

+
+

Each row has approximately 4k(This varies from row to row)numbers in them and the data type of the field is varchar(30000). The data is around 700k rows

+

Now I want to calculate the standard deviation of each row using the numbers present in the list shown above.

+

I have tried doing this in MySQL using the following query:

+
select mac, `timestamp`, std(res), min(res), max(res) 
+from 
+    (select mac, `timestamp`, r.res from table cmr ,
+    json_table(mer_data, '$[*]' columns (res float path '$'))r)T 
+group by mac, `timestamp`;
+
+

which gives me the right result but takes a lot of time for 700k rows.

+

I want to do the same in snowflake. Is there an optimal way to do this?

+

Also the query needs to run within 10 mins in snowflake. The mysql query can take upto 1 hours.

","

Without the table definition and example source data it's difficult to produce a complete solution for your problem, but here is an example of how to do this using the STRTOK_SPLIT_TO_TABLE table function which first splits your varchar numbers to rows, so we can then re-aggregate the Value's to get the standard deviations per row.

+

First generate some test data at the right scale:

+
Create or Replace Table cmr (mer_data varchar) as
+With gen as (
+select 
+   uniform(1,700000, random()) row_num,
+   normal(50, 1, random(0))::decimal(4,2) num
+from table(generator(rowcount => 2800000000)) v 
+)
+Select listagg(num, ',') listNums from gen group by row_num
+;
+
+

Check we have 700k rows and varying count of numbers per row.

+
Select 
+  count(*) row_count, 
+  min(REGEXP_COUNT( mer_data , '[,]' ))+1 min_num_count, 
+  max(REGEXP_COUNT( mer_data , '[,]' ))+1 max_num_count 
+from cmr limit 10;
+
+

Split the varchar number lists to rows with STRTOK_SPLIT_TO_TABLE and group by the generated SEQ column to calculate the stddev of the VALUE.

+
Select 
+  seq row_num, 
+  stddev(value) stdListNums, 
+  min(value) minNum, max(value) maxNum, 
+  count(value) countListNums
+from cmr, table(STRTOK_SPLIT_TO_TABLE(mer_data ,',')) 
+Group By 1
+;
+
+

For my data the query takes just over 3 minutes on and XSMALL Virtual Warehouse, and +a little over 30 seconds on LARGE Virtual Warehouse.

+

You can read about the STRTOK_SPLIT_TO_TABLE function here.

",r +"How to add an obejct from RecyclerView to database MVVM

I want to add an object from my RecyclerView to database by clicking on its icon. I use MVVM pattern, so I should add a object in Fragment. I have 2 callbacks and second one should add an object to database when by clicking. How can I get object so as to use it in viewModel.saveWord() method in adapter callback. Or I should do it anywhere else?

+

RecyclerView Adapter:

+
class SearchDefAdapter(
+    private var infoListener: OnItemClickListener,
+    private var addListener: OnItemClickListener
+):
+    ListAdapter<Def, SearchDefViewHolder>(differCallback) {
+    interface OnItemClickListener {
+        fun onItemClick(position: Int)
+    }
+
+    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchDefViewHolder {
+        return SearchDefViewHolder(
+            SearchWordCardBinding.inflate(
+                LayoutInflater.from(parent.context),
+                parent,
+                false
+            ),
+            addListener,
+            infoListener
+        )
+    }
+
+    override fun onBindViewHolder(holder: SearchDefViewHolder, position: Int) {
+        holder.bind(getItem(position))
+    }
+}
+
+

RecyclerView ViewHolder:

+
class SearchDefViewHolder(
+    private val binding: SearchWordCardBinding,
+    addListener: SearchDefAdapter.OnItemClickListener,
+    infoListener: SearchDefAdapter.OnItemClickListener
+): RecyclerView.ViewHolder(binding.root) {
+    fun bind(data: Def) {
+        with (binding) {
+            searchCardTv.text = "${data.text} - ${data.tr[0].text}"
+        }
+    }
+
+    init {
+        binding.addSearchCard.setOnClickListener {
+            addListener.onItemClick(adapterPosition)
+
+        }
+
+        binding.infoSearchCard.setOnClickListener {
+            infoListener.onItemClick(adapterPosition)
+        }
+    }
+}
+
+

RecyclerView differ callback:

+
val differCallback = object : DiffUtil.ItemCallback<Def>() {
+    override fun areItemsTheSame(oldItem: Def, newItem: Def): Boolean {
+        return oldItem.text == newItem.text
+    }
+
+    override fun areContentsTheSame(oldItem: Def, newItem: Def): Boolean {
+        return oldItem == newItem
+    }
+}
+
+

Adapter initialization in fragment:

+
searchDefAdapter = SearchDefAdapter(
+            object : SearchDefAdapter.OnItemClickListener {
+                override fun onItemClick(position: Int) {
+                    if (!translationsList.isNullOrEmpty()){
+                        val bundle = Bundle()
+                        bundle.putStringArray(INFO_BUNDLE_ID, translationsList[position])
+                        val wordFragment = WordFragment()
+                        wordFragment.arguments = bundle
+                        parentFragmentManager.beginTransaction().apply {
+                            replace(R.id.searchFragment, wordFragment)
+                            commit()
+                        }
+                    }
+                }
+            },
+            object : SearchDefAdapter.OnItemClickListener {
+                override fun onItemClick(position: Int) {
+                    //viewModel.saveWord()
+                }
+            }
+        )
+
","

Change your callback parameter from position to your item type.

+
interface OnItemClickListener {
+    fun onItemClick(def: Def)
+}
+
+//...
+
+class SearchDefViewHolder(
+    private val binding: SearchWordCardBinding,
+    addListener: SearchDefAdapter.OnItemClickListener,
+    infoListener: SearchDefAdapter.OnItemClickListener
+): RecyclerView.ViewHolder(binding.root) {
+
+    private lateinit var def: Def
+
+    fun bind(data: Def) {
+        with (binding) {
+            searchCardTv.text = "${data.text} - ${data.tr[0].text}"
+        }
+        def = data
+    }
+
+    init {
+        binding.addSearchCard.setOnClickListener {
+            addListener.onItemClick(def)
+        }
+
+        binding.infoSearchCard.setOnClickListener {
+            infoListener.onItemClick(def)
+        }
+    }
+}
+
+

Then in your Fragment, your listeners are easier to define and directly give you the item to write to database.

",r +"Multiple TypeScript discriminations based on different properties

I'm trying to build a complex REACT component which supports different use-cases. In order to simplify its use, I want to implement TypeScript discriminations types to better infer the props.

+

It's not useful to post the full example, but I can show you a simpler one, which is the following one:

+
interface ICategoryDiscriminationGame {
+    category: 'game';
+    gameType: 'AAA' | 'AA' | 'A';
+}
+
+interface ICategoryDiscriminationProgram {
+    category: 'program';
+    programType: 'software' | 'freeware';
+}
+
+type TCategoryDiscrimination = (ICategoryDiscriminationGame | ICategoryDiscriminationProgram);
+
+
+interface ISaleDiscriminationPresale {
+    saleType: 'pre-sale',
+    preSaleCost: number;
+}
+
+interface ISaleDiscriminationRetailSale {
+    saleType: 'retail',
+    retailSaleCost: number;
+}
+
+type TSaleDiscrimination = (ISaleDiscriminationPresale | ISaleDiscriminationRetailSale);
+
+
+type TExampleCompProps = TCategoryDiscrimination & TSaleDiscrimination;
+
+export const ExampleComp = (props: TExampleCompProps) => {
+    if (props.category === 'game') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
+        console.log(props.gameType); // In here, intellisense infer also 'props.gameType' -> NICE
+    }
+
+    if (props.saleType === 'pre-sale') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
+        console.log(props.preSaleCost); // In here, intellisense infer also 'props.preSaleCost' -> NICE
+    }
+
+    if (props.category === 'game' && props.saleType === 'retail') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
+        console.log(props.retailSaleCost); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
+        console.log(props.gameType); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
+    }
+
+    return <p>In example comp</p>
+}
+
+

As you can see, inside the ExampleComp, the intellisense is brilliant, and works great. The problem is when I try to use the ExampleComp.
+What I would expect is that, when I write <ExampleComp, the intellisense allows me only the props category and saleType, since the other ones cannot exist without first defining those two. BUT, instead, it just suggests everything:

+

+

So, the question here is: what am I missing that does not make the intellisense works correctly ALSO in the props?

+

TS Playground link

","

That's just the nature of IntelliSense. Once you start to supply some of the combinations of the required props, the suggested ones will be narrowed to only the ones which are applicable to the current possible combination:

+

Before adding some props: +

+

After adding some props: +

",r +"Trying to reverse my stream in ascending order - Java 8

This idea behind this code is that it reads the data from three .csv files w/ keys organized by year, and retrieves the sum of the data by year, as well as the minimum and maximum number for each year.

+

The problem is, when print it returns the yearly results in descending order.

+

I need help figuring out a way to reverse the stream, so that yearly data from each file is in ascending order.

+
public class SalesGenerator {
+    
+    //This class will print out the Maximum and minimum Sales data from the .getSales() in TeslaImport.
+    public static void teslaReport(
+        Set<Entry<String, List<TeslaImport>>> entrySet, 
+        List<TeslaImport> teslaModel, String modelName) 
+    throws IOException {        
+        //This comparator will sort the sales array values.
+        Comparator<TeslaImport> comparativeOperator = Comparator.comparing(tesla -> tesla.getSales());
+
+        entrySet.stream().forEach(entry -> System.out.println(
+            "Month: " + entry.getKey() + " -> " 
+            + entry.getValue().stream()
+                .mapToInt(tesla -> tesla.getSales().intValue())
+                .sum()
+        ));
+        
+        TeslaImport maximumSales = teslaModel.stream()
+            .max(comparativeOperator)
+            .orElseThrow(NoSuchElementException::new);
+        TeslaImport minimumSales = teslaModel.stream()
+            .min(comparativeOperator)
+            .orElseThrow(NoSuchElementException::new);
+            
+        //Print out the maximum and minimum results from TeslaReport.
+        System.out.println(modelName + " Yearly Sales Report");
+        System.out.println("The BEST month for " + modelName + " was: " + maximumSales.getDate());
+        System.out.println("The WORST month for " + modelName + " was: " + minimumSales.getDate());                                                                                 
+    } 
+    
+    public static void main(String[] args) throws IOException {
+        
+        /* To produce the sales values from TeslaData, we need to instantiate the TeslaData variable to import
+        all the EntrySet models */
+        TeslaData analysedData = new TeslaData();
+        
+        /*The FileReader from our FileGenerator class needs to be instantiated to model3. We can use to when
+        when reporting our data in TeslaReport */
+        List<TeslaImport> model3 = FileGenerator.teslaFileRead("model3.csv");
+        Set<Entry<String, List<TeslaImport>>> entrySetModel3 = analysedData.entryByYear(model3);
+        teslaReport(entrySetModel3, model3, "Model 3");
+        
+        /*The FileReader from our FileGenerator class needs to be instantiated to modelS. We can use to when
+        when reporting our data in TeslaReport */
+        List<TeslaImport> modelS = FileGenerator.teslaFileRead("modelS.csv");
+        Set<Entry<String, List<TeslaImport>>> entrySetModelS = analysedData.entryByYear(modelS);
+        teslaReport(entrySetModelS, modelS, "Model S");
+        
+        /*The FileReader from our FileGenerator class needs to be instantiated to modelX. We can use to when
+        when reporting our data in TeslaReport */
+        List<TeslaImport> modelX = FileGenerator.teslaFileRead("modelX.csv");   
+        Set<Entry<String, List<TeslaImport>>> entrySetModelX = analysedData.entryByYear(modelX);        
+        teslaReport(entrySetModelX, modelX, "Model X");
+    }
+}
+
+

Note: TeslaImport is the class where I placed my JavaBean's (get/set, toString, date, and sales)

","

As the report data are printed for the entry set retrieved from the method entryByYear in TeslaModel class, it is very likely that this method returns the entry set for a tree map sorted in the descending order. Thus, to change the order, the stream should be re-sorted by key:

+
entrySet.stream()
+    .sorted(Map.Entry.comparingByKey())
+    .forEach(entry -> System.out.println(
+            "Month: " + entry.getKey() + " -> " 
+            + entry.getValue().stream()
+                .mapToInt(tesla -> tesla.getSales().intValue())
+                .sum()
+        ));
+
",r +"Capture matching text format in a string

I am trying to write a regex to extract the items in the text below that start with the # and ends with )

+

const bodyOfText = "#[DataStructures](topic_DataStructures) is one #[Algorithms](topic_Algorithms) branch that could #[Make or Mar](topic_Make or Mar)";

+

So basically, will want an array that looks like:

+

["#[DataStructures](topic_DataStructures)", "#[Algorithms](topic_Algorithms)", "#[Make or Mar](topic_Make or Mar)"]

","

Using string match() we can try:

+

+
+
var bodyOfText = ""#[DataStructures](topic_DataStructures) is one #[Algorithms](topic_Algorithms) branch that could #[Make or Mar](topic_Make or Mar)"";
+var matches = bodyOfText.match(/#\[.*?\]\(.*?\)/g);
+console.log(matches);
+
+
+

",r +"How to use multiple Full Calendar sources with different coloring based on description?

I have been building a Google Apps Script web app to display my Google Calendar events. The calendar service won't allow an editable calendar to be used so I have been using Full Calendar to complete this task. When I use the google calendar api to import events, they all come in but they all have the same color. The coloring is essential and depends on the event description (e.g. if "specified string" is in the event description the color is yellow, otherwise grey). I then tried to import them as JSON and limited to title & start times in an array. Using some test cases I know this works, but when I try to import the events, the calendar remains blank. What am I doing wrong?

+
// This Does NOT Work.
+var yellowEvents = [];
+var greyEvents = [];
+function loadEvents(importedData) {
+  // importedData is coming in as 
+  //     importedData = [
+  //       {title: "someTitle", start: ISODateTime, end: ISODateTime, color: "someColor"}, 
+  //       {title: "someTitle", start: ISODateTime, end: ISODateTime, color: "someColor"}, 
+  //      ...]
+  for (var k in importedData) {
+    var event = importedData[k];
+    if (event.color == 'yellow') {
+      yellowEvents.push({ title: event.title, start: event.start, end: event.end });
+    } else {
+      greyEvents.push({ title: event.title, start: event.start, end: event.end });
+    }
+  }
+}
+google.script.run.withSuccessHandler(loadEvents).getCalenderEventsAsJson();
+var calendar = new FullCalendar.Calendar(calendarEl, {
+  eventSources: [{
+    events: yellowEvents,
+    color: "yellow"
+  }, {
+    events: greyEvents,
+    color: "blue"
+  },
+  ]
+});
+
+
+
+// This Works.
+document.addEventListener('DOMContentLoaded', function() {
+  var calendar = new FullCalendar.Calendar(calendarEl, {
+    eventSources: [{
+        events: [
+          {title: "TEST", start: new Date().toISOString()},
+        ],
+        color: "red"
+      }, {
+        events: [
+          {title: "TEST", start: new Date(2022, 0, 23, 12, 30).toISOString(), end: new Date(new Date().setHours(18)).toISOString()},
+        ],
+        color: "blue"
+     },
+     ]
+   });
+   calendar.render();
+}
+
+

From checking the options object before calendar creation through the console, I am certain the events are making it into the calendar options. The final options look like this:

+
{...,
+  eventSources: {
+    0: {color: "yellow",
+        events: [
+          0: {title: 'Some Person', start: '2022-01-23T16:00:00.000Z', end: '2022-01-23T18:00:00.000Z'}, 
+          1: {title: 'Some OtherPerson', start: '2022-01-24T16:00:00.000Z', end: '2022-01-24T18:00:00.000Z'},
+          ...
+        ]
+    },
+    1: {color: "grey",
+        events: [
+          0: {title: 'Some Person', start: '2022-01-23T12:00:00.000Z', end: '2022-01-23T14:00:00.000Z'}, 
+          1: {title: 'Some OtherPerson', start: '2022-01-24T12:00:00.000Z', end: '2022-01-24T14:00:00.000Z'},
+          ...
+        ]
+    }
+  },
+...}
+
+

I also see them pre & post rendering in Calendar.currentData.eventSources.{SOME_NUMBER}.meta.

","

Eventually I did find an answer. The server side call "google.script.run" runs async so fullCalendar was treating it as an array with a length of zero even when the entries were added in. I am not familiar with promises so my attempts to use those in Google Apps Script failed. I then reordered the procedure to add the events after the for loop in loadEvents(importedData) and that fixed the error.

+
var yellowEvents = [];
+var greyEvents = [];
+function addEventsToFullCalendar(cal) {
+  function loadEvents(importedData) {
+    for (var k in importedData) {
+      var event = importedData[k];
+      if (event.color == 'yellow') {
+        yellowEvents.push({ title: event.title, start: event.start, end: event.end });
+      } else {
+        greyEvents.push({ title: event.title, start: event.start, end: event.end });
+      }
+    }
+    cal.addEventSource({
+      events: yellowEvents,
+      color: "yellow",
+      textColor: "black"
+    });
+    cal.addEventSource({
+      events: greyEvents ,
+      color: "grey"
+    });
+  }
+  google.script.run
+    .withSuccessHandler(loadEvents)
+    .getCalenderEventsAsJson();
+}
+
+document.addEventListener('DOMContentLoaded', function() {
+  var calendar = new FullCalendar.Calendar(calendarEl, options);
+  calendar.render();
+  addEventsToFullCalendar(calendar);
+}
+
",r +"Filter function with 2 array sets

I am trying to achieve the same result as i wrote in below syntax by implementing filter function to my script.

+

The current script i have

+
    let sheet = [
+        { $0: { 'Name': 'Report1' } },
+        { $0: { 'Name': 'Row Count' } },
+        { $0: { 'Name': 'Report2' } },
+        { $0: { 'Name': 'User' } }
+    ]
+
+    let nope = ['User','Row Count','Container']
+    let result = []
+
+    for(let i = 0; i < sheet.length ;i++){
+        if(sheet[i].$0.Name != nope[0] && sheet[i].$0.Name != nope[1] && sheet[i].$0.Name != nope[2]){
+            result.push(sheet[i])
+        }
+    }
+    
+    console.log(result)
+
+

On my browser inspect element, it will result of (2) [{…}, {…}] on console.log

+

I tried using filter function

+
    let result_2 = sheet.filter(w => !w.$0.Name.includes(nope[0]))
+    console.log(result_2)
+
+

1 : One problem and logic i face is that im unsure on how can i includes all the element of 'nope' in 'includes()'
+2 : I will have to hard code the index such as nope[0] which i dont think is advisable if its going to be a big array

","

You actually almost finish but you reverse the w.$0.Name and nope.

+

+
+
let sheet = [
+    { $0: { Name: ""Report1"" } },
+    { $0: { Name: ""Row Count"" } },
+    { $0: { Name: ""Report2"" } },
+    { $0: { Name: ""User"" } },
+];
+
+let nope = [""User"", ""Row Count"", ""Container""];
+
+let result_2 = sheet.filter(w => !nope.includes(w.$0.Name));
+
+console.log(result_2);
+
+
+

+

PS: I think you should take a break and drink some tea. :)

",r +"In JSDoc, how to apply param type as bunch of strings from a constant array of objects string property?

Let's say I have an object like this;

+
const typesOfIceCreams = [
+ {id: "CHOCOLATE", price: 0.49, rating: 4.5},
+ {id: "CHERRY", price: 0.54, rating: 4.3},
+ {id: "LEMON", price: 0.44, rating: 4.6},
+]
+
+

I want to get an object from typesOfIceCreams array by id property. So I have a function like this;

+
/**
+* @param {?} iceCreamId
+*/
+const getIceCreamById = (iceCreamId) => {
+ return typesOfIceCreams.find(iceCream => iceCream.id === iceCreamId);
+}
+
+

* @params { "CHOCOLATE" | "CHERRY" | "LEMON" } iceCreamId

+

I could have written like this. But it is time-consuming whenever I want to add new ice cream data to the array. I would like something similar to this;

+

* @params { typesOfIceCreams.map(iceCream => iceCream.id) }

+

Thus, I will be able to see that three options ("CHOCOLATE" | "CHERRY" | "LEMON") whenever I try to call getIceCreamById() function.

","

The following should do the trick. Just cast the array to const.

+
const typesOfIceCreams = /** @type {const} */([
+  {id: "CHOCOLATE", price: 0.49, rating: 4.5},
+  {id: "CHERRY", price: 0.54, rating: 4.3},
+  {id: "LEMON", price: 0.44, rating: 4.6},
+])
+
+/**
+* @param {typeof typesOfIceCreams[number]['id']} iceCreamId
+*/
+const getIceCreamById = (iceCreamId) => {
+ return typesOfIceCreams.find(iceCream => iceCream.id === iceCreamId);
+}
+
+

",r +"Convert columns into rows and insert missing values

lets say i have this table

+
df = pd.DataFrame({
+               'name':["a","b","c"],
+               'from':[1,1,2],
+               'to':[3,4,3]
+    })
+
+

what i am trying is to have this

+
df_result = pd.DataFrame({
+               'name':["a","a","a","b","b","b","b","c","c"],
+               'key':[1,2,3,1,2,3,4,2,3]
+    })
+
+

any ideas? i could simply use the melt function but then how do i fill the missing values?

","

You can create helper column key by range and then DataFrame.explode:

+
df = (df.assign(key = df.apply(lambda x: range(x['from'], x['to'] + 1), 1))
+        .explode('key')[['name','key']]
+        .reset_index(drop=True))
+print (df)
+  name key
+0    a   1
+1    a   2
+2    a   3
+3    b   1
+4    b   2
+5    b   3
+6    b   4
+7    c   2
+8    c   3
+
+

Or if need better performance use Index.repeat with DataFrame.loc and then use GroupBy.cumcount with add column from for column key:

+
df = df.assign(key = df['to'].add(1).sub(df['from']))
+df = df.loc[df.index.repeat(df['key'])]
+df['key'] = df.groupby(level=0).cumcount().add(df['from'])
+df = df[['name','key']].reset_index(drop=True)
+print (df)
+  name  key
+0    a    1
+1    a    2
+2    a    3
+3    b    1
+4    b    2
+5    b    3
+6    b    4
+7    c    2
+8    c    3
+
",r +"Collection update Meteor failure from failed regex validation but no regex

I am working with a Meteor schema that has a field defined as below:

+
export const MyCollectionSchema = new SimpleSchema({
+  myField: {
+    optional: true,
+    type: String,
+  },
+...
+});
+
+

We have also attached the behavior below:

+
export const MyCollection = new Meteor.Collection('my_collection');
+
+MyCollection.deny({
+  insert: () => true,
+  update: () => true,
+  remove: () => true,
+});
+
+MyCollection.attachBehaviour('timestampable', {
+  createdAt: 'insertedAt',
+  createdBy: 'insertedBy',
+  updatedAt: 'modifiedAt',
+  updatedBy: 'modifiedBy',
+});
+
+MyCollection.attachSchema(MyCollectionSchema);
+
+

I am trying to update an existing item with this call:

+
 MyCollection.update(
+    { _id: myId },
+    { $set: {
+      myField: myFieldValue,
+      modifiedAt: new Date().toString(),
+      modifiedBy:  userId,
+    } },
+  );
+
+

But it keeps failing because of regex validation failure:

+
+

(Error: Modified by failed regular expression validation in my_collection update)

+
+

I am not using regex in here and am not super familiar with meteor so am not sure if I should be using regex here. Help :/

","

If I read the documentation for the package you are using (I assume it's this one https://github.com/zimme/meteor-collection-timestampable), then the whole idea is that you won't need to set modifiedAt and modifiedBy. That's what the collection-timestamable package will do for you automatically. The error might happen because the package doesn't like you overriding it's fields. I would try just:

+
 MyCollection.update({ _id: myId }, {$set: {myField: myFieldValue}});
+
",r +"How can I get a value from an if statement and work out the difference

I have a function that checks if a user has the app open or closed. If opened take the current time and store it in a variable, if the app is closed, do the same. then it should work out the difference and print it back.

+

I'm trying to work out how long the user has spent on the app.

+

I just not sure how to get it to work, I've tried to assign it to a global and use it from there but that did not work, I've tried sending the values to another function but I keep getting null returned.

+

What can I do to fix this?

+

*.dart

+
activeTimer(value) {
+    print(value);
+
+    if (value == true) {
+      startTimer();
+      print("TRUE 1");
+      DateTime dateTimeStart = DateTime.now();
+    } else {
+      print("FALSE 1");
+      stopTimer();
+      DateTime dateTimeEnd = DateTime.now();
+    };
+
+  final differenceInDays = dateTimeEnd.difference(dateTimeStart).inMinutes;
+    print(differenceInDays);
+
+  }
+
","

You can check when your app is being closed (or placed in background), so just initialize a variable when the app starts and calculate the time when the app closes:

+

in your main.dart file

+
late DateTime app_start;
+@override
+  initState() {
+    super.initState();
+    WidgetsBinding.instance.addObserver(this);
+
+    app_start = DateTime.now();
+  }
+
+  @override
+  void dispose() {
+    WidgetsBinding.instance.removeObserver(this);
+
+    super.dispose();
+  }
+
+  @override
+  void didChangeAppLifecycleState(AppLifecycleState state) {
+    super.didChangeAppLifecycleState(state);
+    // check if app is closed -> substract current time from app_start
+    // save to local storage or send to cloud or smth
+  }
+
",r +"PWA: how to refresh content every time the app is opened

I created a PWA app which sends API call to my domotic server and prints the response on the home page (e.g. outside temperature and vacuum robot status).

+

While all the data get refreshed at very first app opening, if I minimize the app whithout completely shutting it off I have no data refreshing at all.

+

I was wondering how to force a refresh every time the app gets re-opened without having to do it manually (no pull-down to refresh, no refresh-button).

","

Found myself the solution adding the following code in service worker:

+
self.addEventListener('visibilitychange', function() {
+    if (document.visibilityState === 'visible') {
+        console.log('APP resumed');
+        window.location.reload();
+    }
+});
+
",r +"Alerts on Application Gateway Azure

I have two application gateways in azure whenever one goes down it switches to the other, but VM (outside of azure) is in on-premises.

+

How to generate an alert when one application gateway is Unavailable?

","

Monitoring application gateways is pretty straight forwards, if one gateway is down it would mean all backends are down and you can generate alerts on that easily using azure monitor and the alerts.

+

Documentation how to do this can be found here

",r +"Quantmod in R - How to work on multiple symbols efficiently?

I'm using quantmod to work on multiple symbols in R. My instinct is to combine the symbols into a list of xts objects, then use lapply do do what I need to do. However, some of the things that make quantmod convenient seem (to this neophyte) not to play nicely with lists. An example:

+
> symbols <- c("SPY","GLD")
+> getSymbols(symbols)
+> prices.list <- mget(symbols)
+> names(prices.list) <- symbols
+> returns.list <- lapply(prices.list, monthlyReturn, leading = FALSE)
+
+

This works. But it's unclear to me which column of prices it is using. If I try to specify adjusted close, it throws an error:

+
> returns.list <- lapply(Ad(prices.list), monthlyReturn, leading = FALSE)
+Error in Ad(prices.list) :
+  subscript out of bounds: no column name containing "Adjusted"
+
+

The help for Ad() confirms that it works on "a suitable OHLC object," not on a list of OHLC objects. In this particular case, how can I specify that lapply should apply the monthlyReturn function to the Adjusted column?

+

More generally, what is the best practice for working with multiple symbols in quantmod? Is it to use lists, or is another approach better suited?

","

Answer monthlyReturn:

+

All the **Return functions are based on periodReturn. The default check of periodReturn is to make sure it is an xts objects and then takes the open price as the start value and the close price as the last value and calculates the return. If these are available at least. If these are not available it will calculate the return based on the first value of the timeseries and the last value of the timeseries, taking into account the needed time interval (month, day, year, etc).

+

Answer for lapply:

+

You want do 2 operations on a list object, so using an function inside the lapply should be used:

+
lapply(prices.list, function(x) monthlyReturn(Ad(x), leading = FALSE))
+
+

This will get what you want.

+

Answer for multiple symbols:

+
    +
  1. Do what you are doing.

    +
  2. +
  3. run and lapply when getting the symbols: +stock_prices <- lapply(symbols, getSymbols, auto.assign = FALSE)

    +
  4. +
  5. use packages tidyquant or BatchGetSymbols to get all the data in a big tibble.

    +
  6. +
  7. ... probably forgot a few. There are multiple SO answers about this.

    +
  8. +
",r +"How to address type errors when removing data with chart.js?

I'm using chart.js to make a simple chart. No problem producing the chart, but now I've added a remove data function per the documentation but I'm getting a type error. I assume it's because I'm incorrectly accessing the data

+

The error is as follows, and I'll link a JS fiddle file so you can see everything without me dumping in a wall of text.

+

"main.js:49 Uncaught TypeError: Cannot read properties of undefined (reading 'labels')"

+

My understanding is that this error tends to pop up due to scope issues, but I've defined the data globally so the function should be able to access it. I also thought that I was maybe accessing it wrong since it has a few nested arrays, so I tried btn.onclick = removeData(chart[0]); to access the first item in the chart object (the data variable) but that produced a similar error as above, but swapped in 'data' for 'labels'. Thanks for any help/input!

+

JSFiddle of chart

","

First you didn't put the chart in a variable so you had no way of doing things with it. Second part, you didnt pass the function to the onclick but executed it and putted the result in the onClick.

+

The way it is described in the docs only works if you pass a chart variable to the function and dont do it with a button.

+

Also you are using a verry outdated version of chart.js with syntax for the latest. You either need to update your version or use the V2 docs

+

+
+
var data = {
+  labels: [""Jan"", ""Feb"", ""Mar"", ""Apr"", ""May"", ""Jun"", ""Jul""],
+  datasets: [
+    {
+      label: ""Dataset #1"",
+      backgroundColor: ""rgba(255,99,132,0.2)"",
+      borderColor: ""rgba(255,99,132,1)"",
+      borderWidth: 2,
+      hoverBackgroundColor: ""rgba(255,99,132,0.4)"",
+      hoverBorderColor: ""rgba(255,99,132,1)"",
+      data: [65, 59, 20, 81, 56, 55, 40],
+    },
+  ],
+};
+
+var options = {
+  maintainAspectRatio: false,
+};
+
+const chart = new Chart(""chart"", {
+  type: ""pie"",
+  options: options,
+  data: data,
+});
+
+function removeData() {
+  chart.data.labels.pop();
+  chart.data.datasets.forEach((dataset) => {
+    dataset.data.pop();
+  });
+  chart.update();
+}
+
+let btn = document.createElement(""button"");
+btn.innerHTML = ""Remove data"";
+btn.onclick = removeData;
+document.body.appendChild(btn);
+
body {
+  background: #1d1f20;
+  padding: 16px;
+}
+
+canvas {
+  border: 1px dotted red;
+}
+
+.chart-container {
+  position: relative;
+  margin: auto;
+  height: 80vh;
+  width: 80vw;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"" />
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
+  <meta http-equiv=""X-UA-Compatible"" content=""ie=edge"" />
+  <title>Chart.js tutorial</title>
+  <link rel=""stylesheet"" href=""style.css"" />
+</head>
+
+<body>
+  <div class=""chart-container"">
+    <canvas id=""chart""></canvas>
+  </div>
+  <script src=""https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js""></script>
+</body>
+
+</html>
+
+
+

",r +"Azure Functions Packet Capture and Network Trace

Is there a way to use Azure Network Watcher or any other service to capture packets from an Azure Functions App? I have tried with Azure Network Watcher, but it only gives me an option to capture packets from a VM. The functions app is hosted on an App Service Plan.

","

I have found that "Diagnose and solve problems" option on function app blade can be used to collect Network Trace.

+

Diagnose and solve problems --> Diagnostic Tools --> Collect Network Trace --> Choose duration to collect the Network Trace and then click on "Collect Network Trace". If the Functions app has multiple instances, Network Trace will be collected for all of the instances.

+

",r +"Highcharts: How to add another(custom) label/ legend/ something else to the top right of the graph?

In my highcharts, I already have a legend at the bottom left of the graph but want to add a custom status indicator for the entire graph. It's going to be a colored oval with a colored dot and a status on it like in the picture.

+

Should I be trying to use a custom legend or something else? I don't need to hide/show abiliity of the legend so maybe I'm thinking a label is more appropriate but it seems like those only go in the graph. I want something on the top right of the graph. I'm looking through the API to see what else is available but haven't found one that suites my needs.

+

edit- +seems like I might have to do "chart.renderer.text" but I'm not sure how to convert and make it work in typescript http://jsfiddle.net/phpdeveloperrahul/HW7Rm/

+
function (chart) {
+
+var point = chart.series[0].data[8],
+    text = chart.renderer.text(
+        'Max',
+        point.plotX + chart.plotLeft + 10,
+        point.plotY + chart.plotTop - 10
+    ).attr({
+        zIndex: 5
+    }).add(),
+    box = text.getBBox();
+
+chart.renderer.rect(box.x - 5, box.y - 5, box.width + 10, box.height + 10, 5)
+    .attr({
+        fill: '#FFFFEF',
+        stroke: 'gray',
+        'stroke-width': 1,
+        zIndex: 4
+    })
+    .add();
+
+

});

","

The best way to add a custom element inside the legend is to use the legend.labelFormatter.

+
events: {
+  render() {
+    let chart = this,
+      legendAttr = chart.legend.box.getBBox(),
+      padding = 5;
+
+    chart.plus = chart.renderer.text('| +', chart.legend.box.parentGroup.alignAttr.translateX + legendAttr.width + padding, chart.spacingBox.height + padding / 2).attr({
+      cursor: 'pointer',
+    }).css({
+      fontSize: 20
+    }).on(
+      "click",
+      function() {
+        alert('plus was clicked')
+      }
+    ).add()
+  }
+}
+
+

API References: +https://api.highcharts.com/highcharts/legend.labelFormatter,

+

Demo: https://jsfiddle.net/BlackLabel/yu7qm9jx/1/

",r +"Flutter debugging fails

I want to run a flutter application that I wrote on Visual Studio Code on the device. However, when I do this, I always get the following error. Normally this wouldn't happen, it's just starting to happen. I'm not entirely sure what I should do.

+
FAILURE: Build failed with an exception.
+       
+* What went wrong:
+Execution failed for task ':app:compileDebugKotlin'.
+> Kotlin could not find the required JDK tools in the Java installation '/usr/lib/jvm/oracle-java8-jre-amd64' used by Gradle. Make sure Gradle is running on a JDK, not JRE.
+   
+* Try:
+Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
+       
+* Get more help at https://help.gradle.org
+       
+BUİLD FAILED in 45s
+Exception: Gradle task assembleDebug failed with exit code 1
+
+
    +
  • OS : Ubuntu
  • +
  • Mobile Device : Samsung J500F
  • +
  • Android Version : 6.0.1
  • +
","

You need to have installed a JDK. Depending on which version of Ubuntu you should just be able to do sudo apt install openjdk-8-jre-headless

+

That said, I would target a higher Java version, if I were you, maybe 11?

+

Either way, if you look at the path your JRE is in, it's '/usr/lib/jvm/oracle-java8-jre-amd64'

+

You don't want to be using the regular JRE to build/run your application. You want to build and run with openjdk. That's why your error message says,

+
+

"Make sure Gradle is running on a JDK, not JRE."

+
",r +"What do I verify within a client bearer token?

I've got service A, an OAuth 2 authentication server, and service B.

+

Service A has an API and trusts the authentication server.

+

Service B needs to call service A's API, and to do so it needs to include a client (i.e., non-user-specific) bearer token in the request header.

+

Aside from client_id and sub (which should be the same as client_id), what information from the bearer token does service A need to use to verify with the authentication server that service B is who it says it is, that the bearer token is valid?

","
+

what information from the bearer token does service A need to use to verify with the auth server that service B is who it says it is, that the bearer token is valid?

+
+

In addition to sub, you should validate:

+
    +
  • That it is not expired.
  • +
  • That the token issuer iss is the server that you trust.
  • +
  • That the token is signed e.g. with RSA and signed by the issuers private certificate.
  • +
+

Common OAuth servers on the market can typically do these validations for you by using a http endpoint.

",r +"Why is express matching two routes?

I have an express API with a bunch of routes.

+
routes.get('/',                      perms('read', 'document'),   r(CRUD.getAll))
+routes.get('/search',                perms('read', 'document'),   r(CRUD.search))
+routes.get('/:id',                   perms('read', 'document'),   r(CRUD.getById))
+
+

I made sure to have /search above /:id, however, when a new request comes in to /search, I see both endpoints getting a hit (I added a console.log inside of each function).

+

I tried flipping the two and in that case, only /:id gets a hit.

+

Any idea of why this may be happening?

+

","

Think about Express routing as an array of handlers (middlewares), that have a matching rule (url). When a request comes in, the router starts checking each item in the array from the beginning. If it matches the rule, then the handler is run (some don't have conditions, so they just run on each request :)). The request chain does not end when a single url is matched! You can execute multiple handlers on the same request (and that's exactly how middlewares work).

+

Therefore, it really depends on what happens inside your handler. You can tell it to continue with the next item in the list, and if there's a match - the next handler will be executed (like /search and /:id, which will be search again).

+

Make sure you end your response. Beware if you call next and with what parameters. Post some samples of the handlers in order to debug it more :)

",r +"Why chain of trust is ok with different CA?

I have a .keystore file and Tomcat's configuration is: keystore=.keystore and truststore=.keystore
+The .keystore contains a PrivateKeyEntry (signed by CA1) and a trustedCertEntry (CA1).
+Everythink ok so far.
+If the trustedCertEntry would not be present when importing server certificate, I would get:
Failed to establish chain from reply
+When I delete the trustedCertEntry (CA1), Tomcat can not start because of:
java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

+Now my question: When I delete trustedCertEntry CA1 and import a trustedCertEntry CA2, Tomcat starts and the certificate chain (view in browser) is: The server certificate which is signed by CA1.
+How can this be possible? I would have expected that Tomcat can not start since the trustedCertEntry (CA2) does not match with the PrivateKeyEntry since PrivateKeyEntry was issued from CA1 and not CA2. And since Tomcat can not start without a trustedCertEntry.

","

Private key is not issued by CA. +Your server certificate is a pair of public and private key. Based on this key pair certificate request was created and this certificate request was signed by CA1. Certificate is valid in your browser as long as CA1 is in trusted CA in certificate store of your browser.

+

Changing CA in keystore doesn't affect server certificate.

+

It looks like at least one CA cert is requirement of SSL engine - I'm guessing that any CA cert (i.e. thawte.com/roots, or self-signed) imported to JKS will work for you - JKS must have at least one.

",r +"Refactor method chaining javascript

I call a function with bunch of nested method, i'm using web scraping tools called cheerio and i want to get the text out of it so i need to call a bunch of function. here's my example code.

+
        var text = $(el)
+          .children()
+          .first()
+          .children()
+          .first()
+          .children()
+          .first()
+          .text()
+          .replace(/\s\s+/g, " ");
+
+

My question is, how can i simplify my function so I have the same result without chaining my function?

","

A naive solution could be

+
var text = $(">*:nth-child(1)".repeat(3), el).text().replace(/\s+/g, " ");
+
+

For a good solution we'd need more context. Like what does the markup look like.

",r +"Display best selling items by status

Explaining my problem, I have two tables in my database called order and order_details.

+

On my dashboard, I display the three best-selling items (currently work!). However, I would like to display only the best selling items THAT have the status = delivered.

+

Today, it works like this:

+
$top_sell_items = OrderDetails::with(['product'])
+             ->select('product_id', DB::raw('SUM(quantity) as count'))
+             ->groupBy('product_id')
+             ->orderBy("count", 'desc')
+             ->take(3)
+             ->get();
+
+

The problem is that the order status is stored in another table, called orders, column order_status.

+

How can I create this rule and include it in my $top_sell_items?

","

if you relationship is done between this table already, you can use this code, if not you have to go to the OrderDetails Model and add new method orders

+
$top_sell_items = OrderDetails::with(['product', 'orders'])
+             ->whereHas('orders', function($query) {
+                $query->where('status', 'delivered');
+              })
+             ->select('product_id', DB::raw('SUM(quantity) as count'))
+             ->groupBy('product_id')
+             ->orderBy('count', 'desc')
+             ->take(3)
+             ->get();
+
",r +"How to split text value on comma?

How to split a text value on comma, to get two datapoints from it?

+
+

My code:

+
details = response.xpath('//div[@class="article-info"]')
+for detail in details:
+    body = detail.xpath('.//ul/li[1]/span[2]/span/text()').get()
+    item['body'] = released
+    yield item
+
+

My output:

+
+

293g (Wi-Fi) / 297g (Wi-Fi + Cellular), 6.3mm thickness

+
+
+

Desired output (Column A) | Weight

+
+

293g (Wi-Fi) / 297g (Wi-Fi + Cellular)

+
+

Desired output (Column B) | Dimensions

+
+

6.3mm

+
+
","

.split() takes an argument, so you can do this .split(", ") and unpack to weight and thickness.

+

Try this:

+
details = response.xpath('//div[@class="article-info"]')
+for detail in details:
+    weight, thickness = detail.xpath('.//ul/li[1]/span[2]/span/text()').get().split(", ")
+    item['weight'] = weight
+    item['thickness'] = thickness.split()[0] # gets you 6.3mm only
+    yield item
+
",r +"Exception in thread ""main"" java.lang.IndexOutOfBoundsException: Source does not fit in dest

I have Object:

+
static class Truck {
+    
+    ArrayList<Integer> route = new ArrayList<Integer>();
+    double weight = 0;
+    int route_weight = 0;
+
+    Truck() {
+    }
+
+    Truck(ArrayList<Integer> route) {
+        Collections.copy(this.route, route);
+    }
+    
+    //getters and setters
+}
+
+

Objects pulling into this list:

+
static ArrayList<Truck> trucks=new ArrayList<Trucks>();
+
+

I'm trying to make a full copy of the list:

+
        ArrayList<Truck> copy=new ArrayList<>();
+        copy=cloneList(trucks);
+
+
    public static ArrayList<Truck> cloneList(ArrayList<Truck> trucksList) {
+        ArrayList<Truck> clonedList = new ArrayList<Truck>();
+        for (Truck truck : trucks) {
+            Truck w=new Truck(truck.getroute());
+            clonedList.add(w);
+        }
+        return clonedList;
+    }
+
+

But I'm getting a error:

+
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
+
+

getroute returns:

+
[0, 9, 11, 1, 15, 3, 0]
+
","

Collections.copy requires that the size of the destination list is at least the size of the source list. Your this.route has a size of 0 when you try to do the copy so you get an exception.

+

Instead use addAll:

+
Truck(ArrayList<Integer> route) {
+   this.route.addAll(route);
+}
+
",r +"Webapp front-end structure using Firebase, Hosting vs Functions

I'm working on a small scale ERP using Firebase's free plan (for a single user). I started out hard-coding html and serving it with firebase hosting, a flow that proved uneffective in the long run. Soon I needed routes, authentication and a database, which led me to using a Express server running in a single firebase function for everything, so I could protect the routes and database access. This gives me the feel I'm doing something terribly wrong as firebase functions has an obnoxiously long URL and my API routes are just one directory away from my front-end routes.

+

I'm at a loss to how I should proceed but I believe there are the following options:

+
    +
  • A - Go back to using firebase hosting for the front-end, meaning I have to protect the static files with a function that checks localStorage for a web token (jwt) and redirects to the login page upon failure.
  • +
  • B - Create a second firebase function for the front-end, meaning I get to use ejs and express, but I have to keep the really long URL and I have no idea how to change it (using a redirect from an owned domain only serves as an alias, the domain name doesn't persist).
  • +
+

A seems unsafe and B annoys me as I don't get a custom URL, how should I proceed and serve the project?

","

By definition, your static code is public because there is no value in it. The value comes from the API calls that you perform to Functions or Database to fill in your static pages.

+

If your static code doesn't contain critical information, you can use firebase hosting to host it without any problem.

+

If not, you have to check the authentication AND the authorization (is that authenticated user has the permission to access that resource?) with dynamic code (i.e. a functions).

+

If default URL are too long, you can use a custom domain.

",r +"Django: how to update a ManyToManyField in a custom Django management task?

In Django I have a model where one of the fields (tags) is a ManyToManyField:

+
class MyModel(models.Model):
+
+   id = models.CharField(max_length=30, primary_key=True)
+   title = models.CharField(max_length=300, default='')
+   author = models.CharField(max_length=300)
+   copy = models.TextField(blank=True, default='')
+   tags = models.ManyToManyField(Tag)
+
+

I have a custom management task below where I'm getting all of the instances of the MyModel table on a server and using that to replace the instances of the MyModel table on my local server. (I'm running this custom management task from my local)

+

Here's what I'm trying so far.

+

However I'm getting this error: CommandError: Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead.

+

How can I update the tags field that's a ManyToMany field?

+
from bytes.models import MyModel
+
+class Command(BaseCommand):
+
+    def handle(self, *args, **options):
+
+        try:
+            // get queryset of MyModel instances from server
+            queryset = MyModel.objects.using('theserver').all()
+
+            // loop through that queryset and create a list of dictionaries
+            mymodel_list = [
+                {
+                    'id': mymodel['id'],
+                    'title': mymodel['title'],
+                    'author': mymodel['author'],
+                    'copy': mymodel['copy'],
+                    'tags': mymodel['tags']
+                } 
+                for mymodel in queryset
+            ]
+
+            //delete all objects in the local MyModel table
+            MyModel.objects.all().delete() 
+
+            //replace with MyModel instances from server
+            new_mymodel = [
+                MyModel(
+                    id=mymodel['id'],
+                    title=mymodel['title'],
+                    author=mymodel['author'],
+                    copy=mymodel['copy'],
+                    tags=mymodel['tags'] <--- causing error
+                )
+                for mymodel in mymodel_list
+            ]
+
+            MyModel.objects.bulk_create(new_mymodel)
+
","

ManyToMany fields are working differently from any other field. You cannot simply copy it's values, especially from strings. You can try add objects in a loop just after after creating MyModel:

+
    //replace with MyModel instances from server
+    new_mymodels = []
+    for mymodel in mymodel_list:
+        new_mymodel = MyModel(
+                id=mymodel['id'],
+                title=mymodel['title'],
+                author=mymodel['author'],
+                copy=mymodel['copy']
+            )
+
+        for tag in mymodel['tags']:
+            new_mymodel.tags.add(tag)
+
+        new_mymodels.append(new_mymodel)
+
+    MyModel.objects.bulk_create(new_mymodel)
+
+

It is possible, that you will have to firstfully find the Tag object before .add() method. It depends on values in mymodel['tags'].

",r +"Filter elements with both integer and NA in R

I am relatively new to R, and I have a simple question. +I have df as below.

+
df <- data.frame(T = c('A','A','B','B','C','D'), P = c(10, NA, 22, NA,33,NA))
+
+

After some filtering process, I want to see only the elements that have both an integer and NA from column P: in this case, only A and B remain.

+

What would be the best way to get this?

+

Thanks in advance for all help!

","

We can use a condition in filter to have both NA and non-NA after grouping - is.na returns TRUE for NA, ! converts the TRUE -> FALSE and viceversa. sum of the logical vector get the count, then change it to a logical vector (> 0 - count of NA greater than 0, count of non-NA greater than 0)

+
library(dplyr)
+df %>%
+   group_by(T) %>% 
+   filter(sum(is.na(P)) > 0, sum(!is.na(P)) > 0) %>%
+   ungroup
+
+

-output

+
# A tibble: 4 × 2
+  T         P
+  <chr> <dbl>
+1 A        10
+2 A        NA
+3 B        22
+4 B        NA
+
",r +"Widget doesn't change, although new state is called

I wanted to have a text, that changes every time one of the filter cards is selected/deselected. I made a global variable (I don't know what the best way to do that is but to me it seemed like it should work) and changed the value of it every time one of the filter cards was tapped. The problem is that the text widget, where the value is supposed to be displayed, doesn't change although the output shows, that the set state function worked. For more info see the pictures and code below.

+
    class FilterSelectCard extends StatefulWidget {
+  FilterSelectCard({
+    Key? key,
+    required this.filterCategory,
+    required this.filterSvg,
+    required this.filterIndex,
+    required this.appliedFilters,
+  }) : super(key: key);
+  List<String> filterCategory;
+  List<String> filterSvg;
+  int filterIndex;
+  ValueNotifier<int> appliedFilters;
+  @override
+  FilterSelectCardState createState() => FilterSelectCardState();
+}
+
+class FilterSelectCardState extends State<FilterSelectCard> {
+  Color filterColor = primaryColor;
+  Color borderColor = secondaryTextColor;
+  Color svgColor = secondaryTextColor;
+  bool filterStat = false;
+  TextStyle textStyle = unTextStyle;
+  ValueNotifier<int> appliedFilters = widget.appliedFilters; 
+
+  @override
+  Widget build(BuildContext context) {
+    return Padding(
+      padding: const EdgeInsets.only(
+        right: 12,
+      ),
+      child: GestureDetector(
+        onTap: () {
+          setState(() {
+            if (filterStat == false) {
+              filterColor = secondaryTextColor;
+              textStyle = selTextStyle;
+              borderColor = backgroundColor;
+              svgColor = mainTextColor;
+              appliedFilters.value += 1;
+              print(appliedFilters);
+            }
+            if (filterStat == true) {
+              filterColor = primaryColor;
+              textStyle = unTextStyle;
+              borderColor = secondaryTextColor;
+              svgColor = secondaryTextColor;
+              appliedFilters.value -= 1;
+              print(appliedFilters);
+            }
+            if (filterColor == primaryColor) {
+              filterStat = false;
+            }
+            if (filterColor == secondaryTextColor) {
+              filterStat = true;
+            }
+          });
+        },
+
+

and

+
Future<dynamic> filterMealsAndWines(BuildContext context) {
+    ValueNotifier<int> appliedFilters = ValueNotifier(0);
+    return showModalBottomSheet(
+      context: context,
+      shape: RoundedRectangleBorder(
+        borderRadius: BorderRadius.circular(35),
+      ),
+      builder: (BuildContext context) {
+        return Stack(
+           children:[Positioned(
+                    left: 110,
+                    top: 15,
+                    child: Container(
+                      height: 9,
+                      width: 20,
+                      decoration: BoxDecoration(
+                        color: primaryColor,
+                        borderRadius: BorderRadius.circular(
+                          20,
+                        ),
+                      ),
+                      child: ValueListenableBuilder(
+                        valueListenable: appliedFilters,
+                        builder: (context, appliedFilters, _) {
+                          return Center(
+                            child: Text(
+                              appliedFilters.toString(),
+                              style: GoogleFonts.poppins(
+                                textStyle: const TextStyle(
+                                  color: mainTextColor,
+                                  fontSize: 6,
+                                  fontWeight: FontWeight.w600,
+                                ),
+                              ),
+                            ),
+                          );
+                        },
+                      ),
+                    ),
+                  ),],
+
+

+

","

If this widget, is the widget you are trying to update when setState() is called, it doesn't work because it is not in same StatefulWidget as the setState() function in result the widget doesn't rebuild.

+
child: Center(
+  child: Text(
+    appliedFilters.toString(),
+    style: GoogleFonts.poppins(
+      textStyle: const TextStyle(
+        color: mainTextColor,
+        fontSize: 6,
+        fontWeight: FontWeight.w600,
+      ),
+    ),
+  ),
+),   
+
+

To solve you should read more about state managment in Flutter, but a temporary solution could be using a ValueListenableBuilder

+

So you should wrap your Text widget in ValueListenableBuilder and your your value appliedFilters will update the builder whenever it is changed

+
Future<dynamic> filterMealsAndWines(BuildContext context){
+  ValueNotifier<int> appliedFilters = ValueNotifier(0); 
+
+  //Your all previuos code 
+
+  ValueListenableBuilder<int>(
+    valueListenable: appliedFilters,
+    builder: (context, value, _) {
+      return Center(
+        child: Text(
+          appliedFilters.toString(),
+          style: GoogleFonts.poppins(
+            textStyle: const TextStyle(
+              color: mainTextColor,
+              fontSize: 6,
+              fontWeight: FontWeight.w600,
+            ),
+          ),
+        ),
+      );
+    }
+  ),
+}
+
+class FilterSelectCardState extends State<FilterSelectCard> {
+
+  @override
+  Widget build(BuildContext context) {
+    return Padding(
+      padding: const EdgeInsets.only(
+        right: 12,
+      ),
+      child: GestureDetector(
+        onTap: () {
+          setState(() {
+            //HERE YOU UPDATE THE VALUE
+            widget.appliedFilters.value += 1;
+          });
+        },
+      ),
+
+      //all your other code
+
+    );
+  }
+}
+
",r +"Azure app configuration throws exception & does not load the configuration when a disabled key vault secret is present as KV reference

I have an Azure app configuration with 2 keys. Both have key vault references as values. When one of the key-vault secrets is disabled for some reason (because expiration date has passed, not needed for now etc.,), entire configuration loading fails with KeyVault reference exception. +I tried using SetSecretResolver, but it looks like if the registered KV client encounters any exception, secret resolver fallback will not be called. Is there any solution for this issue? Basically, I don't want to stop loading the config, if any or some of the KV secrets are disabled. +BTW, I tried setting the "Options: true" to suppress the exception throwing, but that did not load the config.

+

app config Keys:-

+
abc:def:key1 - has a valid key vault secret
+abc:def:key2 - has a disabled key vault secret.
+
+

code:-

+
public IConfiguration AzureAppConfig { get; set; }
+public IConfigurationRefresher AzureAppConfigRefresher { get; set; }
+
+builder.AddAzureAppConfiguration(options =>
+                {
+                    options.Connect(new Uri("uri"), credential)
+                        .Select("abc:def:*")
+                        .ConfigureKeyVault(kvOptions =>
+                        {
+                            kvOptions.SetCredential(credential);
+                        })
+                    .ConfigureRefresh(refresh =>
+                    {
+                        refresh.Register("abc:def:key1")
+                            .SetCacheExpiration(TimeSpan.FromMinutes(30));
+                    });
+                    AzureAppConfigRefresher = options.GetRefresher();
+                });
+
+AzureAppConfig = builder.Build();
+
+

Thanks in advance for any help.

","

Key Vault does not allow read operations on disabled/expired secrets and throws 403 error. This is by design. App Config provider never hides the exceptions thrown by KeyVault because that would leave the application configuration in an undefined state. But if you want more control over error handling, you can implement your own secret resolver by using the SetSecretResolver API.

+
+

I tried using SetSecretResolver, but it looks like if the registered KV client encounters any exception, secret resolver fallback will not be called.

+
+

That is correct. SetSecretResolver doesn't handle errors thrown by registered SecretClient(s). It will only be used when no SecretClient has been registered with the same vault URI. This GitHub issue has more details about setting up your own secret resolution code: https://github.com/Azure/AppConfiguration-DotnetProvider/issues/209#issuecomment-743427521

+

Link to the same discussion on GitHub: https://github.com/Azure/AppConfiguration-DotnetProvider/issues/309

",r +"GeoChart with nodeJS

I'm trying to get only the values ​​with 2 characters, example: "AC", "RS" from the region variable to put in the chart, +I have to pass these values ​​inside the data variable so that the graph is formed correctly. +Values ​​with only 1 character will not be included in this graph values: 'null', "B", 'K', 'S', 'W', 'X'.

+

does anyone have any idea how i can do this?

+
      google.load('visualization', '1', {
+          'packages': ['geochart', 'table']
+      });
+      google.setOnLoadCallback(drawRegionsMap);
+      
+      async function drawRegionsMap() {
+
+    var region = [
+    {
+        "key": null,
+        "value": 15
+    },
+    {
+        "key": "AC",
+        "value": 162
+    },
+    {
+        "key": "AL",
+        "value": 861
+    },
+    {
+        "key": "AM",
+        "value": 358
+    },
+    {
+        "key": "AP",
+        "value": 73
+    },
+    {
+        "key": "B",
+        "value": 1
+    },
+    {
+        "key": "BA",
+        "value": 4889
+    },
+    {
+        "key": "CE",
+        "value": 2178
+    },
+    {
+        "key": "DF",
+        "value": 3396
+    },
+    {
+        "key": "ES",
+        "value": 4339
+    },
+    {
+        "key": "GO",
+        "value": 3226
+    },
+    {
+        "key": "K",
+        "value": 1
+    },
+    {
+        "key": "MA",
+        "value": 1422
+    },
+    {
+        "key": "MG",
+        "value": 19913
+    },
+    {
+        "key": "MS",
+        "value": 1221
+    },
+    {
+        "key": "MT",
+        "value": 1946
+    },
+    {
+        "key": "PA",
+        "value": 1280
+    },
+    {
+        "key": "PB",
+        "value": 1222
+    },
+    {
+        "key": "PE",
+        "value": 2785
+    },
+    {
+        "key": "PI",
+        "value": 1060
+    },
+    {
+        "key": "PR",
+        "value": 6483
+    },
+    {
+        "key": "RJ",
+        "value": 20454
+    },
+    {
+        "key": "RN",
+        "value": 1287
+    },
+    {
+        "key": "RO",
+        "value": 362
+    },
+    {
+        "key": "RR",
+        "value": 87
+    },
+    {
+        "key": "RS",
+        "value": 5646
+    },
+    {
+        "key": "S",
+        "value": 1
+    },
+    {
+        "key": "SC",
+        "value": 4150
+    },
+    {
+        "key": "SE",
+        "value": 768
+    },
+    {
+        "key": "SP",
+        "value": 43880
+    },
+    {
+        "key": "TO",
+        "value": 408
+    },
+    {
+        "key": "W",
+        "value": 1
+    },
+    {
+        "key": "X",
+        "value": 1
+    }
+]
+    
+          var data = google.visualization.arrayToDataTable([
+    
+          ['Country', {role: 'annotation'}],
+              ['BR-SP', 300],
+              ['BR-PE', 200],
+              ['BR-RS', 100],
+              ['BR-AM', 400]
+      
+          ]);
+      
+          var view = new google.visualization.DataView(data)
+          view.setColumns([0, 1])
+      
+          var options = {
+              region: 'BR',
+              resolution: 'provinces',
+              height: 600
+          };
+      
+          var chart = new google.visualization.GeoChart(
+          document.getElementById('chart_div'));
+          chart.draw(data, options);
+      
+          var geochart = new google.visualization.GeoChart(
+          document.getElementById('chart_div'));
+          var options = {
+              region: 'BR',
+              resolution: 'provinces',
+               displayMode: 'regions',
+              height: 600,
+              colorAxis: {
+                  colors: ['#d00d0d']
+              },  
+          };
+    
+          geochart.draw(data, options);
+
+

follow the graphic image:

+

","

My Answer

+
 google.load('visualization', '1', {
+ 'packages': ['geochart', 'table']
+  });
+  google.setOnLoadCallback(drawRegionsMap);
+  
+  async function drawRegionsMap() {
+      let region = await request();
+      
+      var lista = [];
+
+      for(var i = 0; i < region.length; i++){
+        lista.push("BR-" + region[i].key, region[i].value);
+      }
+
+      var estados = region.filter(myFunction);
+
+      function myFunction(estado){
+        if(estado.key != null){
+        return estado.key.length == 2;
+        }
+      }
+   
+      var charData = [
+      ['Estados', 'Pedidos']
+      ]
+
+      estados.forEach(pedido => charData.push(["BR-" + pedido.key, pedido.value]));
+
+      var data = google.visualization.arrayToDataTable(charData);
+  
+      var view = new google.visualization.DataView(data)
+      view.setColumns([0, 1])
+  
+      var options = {
+          region: 'BR',
+          resolution: 'provinces',
+          height: 600
+      };
+  
+      var chart = new google.visualization.GeoChart(
+      document.getElementById('chart_div'));
+      chart.draw(data, options);
+  
+      var geochart = new google.visualization.GeoChart(
+      document.getElementById('chart_div'));
+      var options = {
+          region: 'BR',
+          resolution: 'provinces',
+           displayMode: 'regions',
+          height: 600,
+          colorAxis: {
+              colors: ['#d00d0d']
+          },  
+      };
+
+      geochart.draw(data, options);
+  };
+
+

",r +"Post sign-up flow with Azure B2C

We are using Azure B2C for sign-ups of external users. +By default, we only provide limited access on sign-up, as we need to ensure the user gets assigned to the right profiles within AD and link things up with SalesForce.

+

Currently, this is done manually using a report, but we want to semi-automate it, by automatically raising a support ticket, so somebody can check it out

+

The question is how we can detect if a new user has signed up successfully and act on that? Preferably as part of the sign-up flow, but separate event-based flow could also be an option.

","

Just before sending the JWT in the signup/in flow, you could do e.g.

+
<Preconditions>
+    <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
+        <Value>newUser</Value>
+        <Action>SkipThisOrchestrationStep</Action>
+    </Precondition>
+</Preconditions>
+<ClaimsExchanges>
+    <ClaimsExchange Id="RaiseSupportTicket" TechnicalProfileReferenceId="REST-RaiseSupportTicket"/>
+</ClaimsExchanges>
+
+

and then call an API.

",r +"In express typescript app, error passed with next() does not get to error handling middleware

This is the code in question:

+
import express from 'express';
+
+// Non existing routes
+app.use((req: Request, res: Response, next: NextFunction) => {
+  return next(new Error('Test error));
+});
+
+// Error handling
+// Arbitrary example
+app.use((error: any, req: Request, res: Response) => {
+  res
+    .status(500)
+    .json({ 'Server error' });
+});
+
+

The problem is, for example when an error is passed in the next() function in the missing routes middleware it doesn't get to the error handling middleware and as result html instead of json is returned to the client.

","

I was able to resolve this problem by adding next argument in the error handling middleware:

+
// Error handling
+app.use((error: any, req: Request, res: Response, next: NextFunction) => {
+  res
+    .status(500)
+    .json({ 'Server error' });
+});
+
+

It is interesting what might be the cause for this behaviour, because this middleware function was working without this argument before adding typescript.

",r +"How to plot a line chart which has both the start and points outside the canvas area using Chart.js

I am currently using chart.js "2.9.4" and the "react-chartjs-2 "2.11.1". +My goal is to draw a line chart which has only two data points. Both these two data points are outside the canvas.

+

Here I attached a reference image.

+

+

Please help me to find a solution for this issue. Your help will be highly appreciated.

","

You can use a scatter chart and define ticks.min and ticks.max options on the x-axis to limit the view. In order to see the line, you need to add showLine: true on the dataset.

+
+

Consult the Chart.js documentation for further details about tick configuration.

+
+

Please take a look at the runnable code snippet below and see how it works.

+

+
+
new Chart('chart', {
+  type: 'scatter',
+  data: {
+    labels: [2018, 2024],
+    datasets: [{
+      data: [{ x: 2018, y: 10 }, { x: 2024, y: 0 }],
+      borderColor: 'rgb(0, 0, 255)',
+      showLine: true,
+      fill: false
+    }],
+  },
+  options: {
+    responsive: false,
+    legend: {
+      display: false
+    },
+    scales: {
+      xAxes: [{
+        ticks: {
+          min: 2020,
+          max: 2023,
+          stepSize: 1
+        }
+      }]
+    }
+  }
+});
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js""></script>
+<canvas id=""chart"" width=""300"" height=""200""></canvas>
+
+
+

",r +"Conditional inclusion: integral constant expression is unlimited?

Per C++11 (and newer) this code is valid:

+
#if 1.0 > 2.0 ? 1 : 0
+#endif
+
+

However, most (if not all) C++ compilers reject it:

+
$ echo "#if 1.0 > 2.0 ? 1 : 0" | g++ -xc++ - -std=c++11 -pedantic -c
+<stdin>:1:5: error: floating constant in preprocessor expression
+<stdin>:1:11: error: floating constant in preprocessor expression
+
+

N4849 has this (emphasis added):

+
+

The expression that controls conditional inclusion shall be an integral constant expression except that identifiers (including those lexically identical to keywords) are interpreted as described below143 and it may contain zero or more defined-macro-expressions and/or has-include-expressions and/or has-attribute-expressions as unary operator expressions.

+
+

and this (emphasis added):

+
+

An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.

+
+

The 1.0 > 2.0 ? 1 : 0 is integral constant expression.

+

So, where C++ standard prohibits using floating-point literal (for example) in the expression that controls conditional inclusion?

","

Answer from Richard Smith:

+
+

This is an error in the standard wording. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1436 for details and a proposed fix -- though that fix is known to be wrong too (it permits lambda-expressions).

+
",r +"element not interactable in Robot Framework

I am developing an automated test robot with fobotramework (python) +I get this error message after I run it: +ElementNotInteractableException: Message: element not interactable +(Session info: chrome = 89.0.4389.72) +Here is the code: +Click Element //input[@id='fs_nyilatkozat_tudkut'] ScreenShot FlipSwitchKijelolve.png Click Element //button[@id='bt_benyujtas'] Screenshot FlipSwitchKlikkAfterSleep.png

+

What's wrong, why doesn't it work?

","

May be element be hidden.

+

This link could be helpful. robot framework forum

",r +"Python Pandas: How to find element in a column with a matching string object of other column

I have this string object:

+
code = '1002'
+
+

And i also have the following Pandas Data Frame:

+
pd.DataFrame({'Code':['1001','1002','1003','1004'],
+              'Place':['Chile','Peru','Colombia','Argentina']})
+
+

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

","

You can use set_index first, if you want to get the actual value:

+
>>> df.set_index('Code').loc['1002', 'Place']
+'Peru'
+
",r +"Presto equivalent to StringTokenizerDelim (Vertica) / Explode(Python)

I am migrating a query from Vertica to Presto(0.246). The query contains a Vertica function StringTokenizerDelim, which basically explodes and array (market column) into rows.

+

This is the mockup of the table:

+
+----+---------+-------------+
+| id | product |   market    |
++----+---------+-------------+
+|  1 | Cabinet | AU,GB,FR    |
+|  2 | Chair   | US,GB       |
+|  3 | Desk    | BE,GB,FR,US |
++----+---------+-------------+
+
+

The output should be:

+
+----+---------+--------+
+| id | product | market |
++----+---------+--------+
+|  1 | Cabinet | AU     |
+|  1 | Cabinet | GB     |
+|  1 | Cabinet | FR     |
+|  2 | Chair   | US     |
+|  2 | Chair   | GB     |
+|  3 | Desk    | BE     |
+|  3 | Desk    | GB     |
+|  3 | Desk    | FR     |
+|  3 | Desk    | US     |
++----+---------+--------+
+
+

What is the equivalent to that function in Presto (if there is any? couldn't find it on the documentation)?

+

Cheers,

","

split with UNNEST should do the trick:

+
-- sample data
+WITH dataset (id, product,   market ) AS (
+    values (1, 'Cabinet', 'AU,GB,FR'),
+    (2, 'Chair', 'US,GB'),
+    (3, 'Desk', 'BE,GB,FR,US')
+) 
+
+--query
+SELECT id, product, m as market
+FROM dataset
+CROSS JOIN UNNEST (split(market, ',')) as t(m)
+
+

Output:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
idproductmarket
1CabinetAU
1CabinetGB
1CabinetFR
2ChairUS
2ChairGB
3DeskBE
3DeskGB
3DeskFR
3DeskUS
+
",r +"Unable to go back after refreshing from a Modal screen using React Navigation

Let's suppose I have a TabNavigator. In a screen, I'm able to navigate to a modal screen (full screen modal => it's placed outside the TabNavigator stack) and go back but, if I refresh the browser in the modal screen (F5), I'm unable to go back. The go back button disappears.

+

I can even reproduce it with the Expo init typescript tabbed default project.

+

Video describing the problem: https://recordit.co/4PULNdWRPT

+

Code: https://github.com/MADSENSE/Madsense.ReactNative.Sample/tree/master

+

Does anywone knows how to fix this / any workaround?

","

This is what you expect while navigating a web app. Whoever, you can force the icon to show and navigate to wherever you want manually.

+

example:

+
<Stack.Screen
+  name="..."
+  component={...}
+  options={navigation => ({
+    headerLeft: props => <IconComponent onPress={navigation.navigate("...")} />,
+  })}
+/>
+
+

Also, you have to navigate to a screen by its name navigation.navigate("...") because you can't tell from where the user went to your screen.

",r +"fill a freehand drawing with opacity

I have a simple fuction which fills the drawn image if the user chooses to

+
canvas.on('mouse:up', function() { 
+                if(main.mode == 'fill') {
+                  var object = main.canvas.item(main.canvas.getObjects().length-1);
+                  object.fill = main.pColor();  
+                  canvas.renderAll();
+                }
+            })
+
+

this works fine for solid(opacity 1) colors. When using a color with less opacity:

+

+

It seems the stoke and fill overlap yielding a darker line.

+

I experimented with globalCompositeOperation. I am thinking eliminate the stroke or set the stroke opacity to zero. I hope there is a better answer.

","

I tried a few approaches: setting stroke opacity to zero and trying to get rid of the stroke altogether.

+

what works best is adding

+
object.set('strokeWidth', 0);
+
+

to the handler above.

+

set ensures the canvas will be updated.

+

It is working well.

",r +"How to convert handlebars partial parameters to pug/jade?

Small but difficult question for me. How to convert this code to pug? I'm currently learning web programming and writing my first project in pug.

+
{{#each people}}
+   {{> myPartial prefix=../prefix firstname=firstname lastname=lastname}}.
+{{/each}}
+
","

Pug doesn't have partials, but it does have mixins, which are a similar concept that allow you to reuse and pass parameters to blocks of code.

+

Assuming you've rewritten myPartial as a valid mixin called myMixin, and assuming people is an array of objects with properties firstname and lastname, you could write this in Pug as:

+
each person in people
+  +myMixin(person.firstname, person.lastname)
+
",r +"Zip array of structs with array of ints into array of structs column

I have a dataframe that looks like this:

+
val sourceData = Seq(
+  Row(List(Row("a"), Row("b"), Row("c")), List(1, 2, 3)),
+  Row(List(Row("d"), Row("e")), List(4, 5))
+)
+
+val sourceSchema = StructType(List(
+  StructField("structs", ArrayType(StructType(List(StructField("structField", StringType))))),
+  StructField("ints", ArrayType(IntegerType))
+))
+
+val sourceDF = sparkSession.createDataFrame(sourceData, sourceSchema)
+
+

+

I want to transform it into a dataframe that looks like this:

+
val targetData = Seq(
+  Row(List(Row("a", 1), Row("b", 2), Row("c", 3))),
+  Row(List(Row("d", 4), Row("e", 5)))
+)
+
+val targetSchema = StructType(List(
+  StructField("structs", ArrayType(StructType(List(
+    StructField("structField", StringType),
+    StructField("value", IntegerType)))))
+))
+
+val targetDF = sparkSession.createDataFrame(targetData, targetSchema)
+
+

+

My best idea so far is to zip the two columns then run a UDF that puts the int value into the struct.

+

Is there an elegant way to do this, namely without UDFs?

","

Using zip_with function:

+
sourceDF.selectExpr(
+  "zip_with(structs, ints, (x, y) -> (x.structField as structField, y as value)) as structs"
+).show(false)
+
+//+------------------------+
+//|structs                 |
+//+------------------------+
+//|[[a, 1], [b, 2], [c, 3]]|
+//|[[d, 4], [e, 5]]        |
+//+------------------------+
+
",r +"Ruby: How to reference a variable defined outside of a module

How do I pass processor_pool to the method inside the module?

+
class Dummy
+
+  def initialize
+    processor_pool = Concurrent::FixedThreadPool.new(10)
+
+    @threadpool = Module.new do
+      extend Concurrent::Promises::FactoryMethods
+      def self.default_executor
+        return processor_pool  # this cannot find the processor_pool variable
+      end
+    end
+  end
+
+end
+
+

I get the same error even if I make it an instance variable like @processor_pool

","

Something like this (I simplified your class a bit to get rid of dependencies for the sake of example, but its structure is the same):

+
class Dummy
+  attr_reader :threadpool
+  
+  def initialize
+    processor_pool = "It works"
+
+    @threadpool = Module.new do
+      define_method :default_executor do
+        return processor_pool
+      end
+      module_function :default_executor
+    end
+  end
+end
+
+Dummy.new.threadpool.default_executor # => "It works"
+
",r +"How to access a cell ignoring the Title?

I;m trying to access an element of a cell from pretty table. When I tried that the title of the pretty table also comes as part of the output. is there a way to ignore it?

+
from prettytable import PrettyTable
+
+table = PrettyTable(["Column 1", "Column 2", "Column 3"])
+table.title = 'TESTING'
+table.add_row(["A", "B", "C"])
+table.add_row(["F", "O", "O"])
+table.add_row(["B", "A", "R"])
+
+
+for row in table:
+    row.border = False
+    row.header = False
+    print(row.get_string(fields = ['Column 1']).strip())
+
+

output is as follows:

+
| TESTING |
+  A
+| TESTING |
+  F
+| TESTING |
+  B
+
+

But i want only the fields particularly the cell values and i dont want the title. +can someone kindly help.

+

i tried searching throught the documentation of prettytable but could not find it online.

","

It doesn't look like get_string provides a straight forward API to achieve that, but we can cheat by using \r as the temporary title and use NONE for vrules:

+
from prettytable import PrettyTable, NONE
+...
+for row in table:
+    print(row.get_string(fields=['Column 1'],
+                         border=False,
+                         header=False,
+                         title='\r',
+                         vrules=NONE).strip())
+
+

Or we can use a lower-level API:

+
for row in table.rows:
+    print(row[0])
+
+

Both will output

+
A
+F
+B
+
+

To get a specific cell's value you can use start and stop arguments which are zero-based and are inclusive-exclusive (like Python's range):

+
print(table.get_string(fields=['Column 1'],
+                       border=False,
+                       header=False,
+                       title='\r',
+                       vrules=NONE,
+                       start=1,
+                       end=2).strip())
+
+

will output

+
F
+
",r +"How to extract a specific element value from an array in laravel controller

I do have the following output in the form of an array

+
$fetchSubFormDetailData = $this->PMSDS11FetchSubFormDetailTrait($request);
+echo 'Data Submitted' ;
+print_r($fetchSubFormDetailData);
+
+

The result shown because of print_r is as under

+

Data SubmittedArray +( +[LineId] => 10 +[IncomeTo] => 500000.00 +)

+

Now I want to extract IncomeTo from this array into a variable in this controller for validations. I tried using the following ways

+
$IncomeTo = $fetchSubFormDetailData[0]->IncomeTo;
+
+

I am keep on getting the following error in laravel8.

+

"message": "Undefined array key 0", +"exception": "ErrorException",

+

How can I extract the value (500000.00) of IncomeTo element from this array in my $IncomeTo variable?

+

Any help will be appreciated.

","

This should work

+
$IncomeTo = $fetchSubFormDetailData['IncomeTo'];
+
",r +"Can the endorsing peer see the transient data passed to its chaincode in Hyperledger Fabric?

I am trying to pass sensitive data of clients to the chaincode function as given in the private data example of Hyperledger Fabric. The documentation recommends to pass sensitive data as --transient data field and parse the transient map in the chaincode function execution:

+
    @Transaction(intent = Transaction.TYPE.SUBMIT)
+    public Asset CreateAsset(final Context ctx) {
+        ChaincodeStub stub = ctx.getStub();
+        Map<String, byte[]> transientMap = ctx.getStub().getTransient();
+        if (!transientMap.containsKey("asset_properties")) {
+            String errorMessage = String.format("CreateAsset call must specify asset_properties in Transient map input");
+            System.err.println(errorMessage);
+            throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString());
+        }
+        byte[] transientAssetJSON = transientMap.get("asset_properties");
+        final String assetID;
+        final String type;
+        final String color;
+        int appraisedValue = 0;
+        int size = 0;
+        try {
+            JSONObject json = new JSONObject(new String(transientAssetJSON, UTF_8));
+            Map<String, Object> tMap = json.toMap();
+            type = (String) tMap.get("objectType");
+            assetID = (String) tMap.get("assetID");
+            color = (String) tMap.get("color");
+            if (tMap.containsKey("size")) {
+                size = (Integer) tMap.get("size");
+            }
+            if (tMap.containsKey("appraisedValue")) {
+                appraisedValue = (Integer) tMap.get("appraisedValue");
+            }
+        } catch (Exception err) {
+            String errorMessage = String.format("TransientMap deserialized error: %s ", err);
+            System.err.println(errorMessage);
+            throw new ChaincodeException(errorMessage, AssetTransferErrors.INCOMPLETE_INPUT.toString());
+        }
+        //input validations
+
+

By definition, transient data gets excluded from the channel transaction and kept in a transient data store of a peer.

+

But are the transient fields protected against the endorsing peer itself?

+

Can the endorsing peer (who is the host of the chaincode) see transient data or possibly parse it?

+

If yes, what are some of the best practices to hide such sensitive from the endorsing peer?

+

Thank you.

","

Yes, the endorsing peer can see transient data within a transaction proposal that it receives. Best practice is to only send proposals containing private data to peers belonging to organisations that should be able to see that private data.

+

If you are using Hyperledger Fabric v2.4+ and the Fabric Gateway client APIs, this is taken care of for you. If you are using an older version of Fabric or continuing to use the legacy SDKs, you may need to explicitly specify the endorsing organisations or peers.

+

Just one other clarification is that the transient data itself is not stored anywhere. If the transaction function writes that transient data to a private data collection then the written data is recorded in that private collection, stored only on peers of organisations that are members of the collection. Similarly, if the transaction function writes any of that transient data to the ledger or returns it in the transaction response, those values will be recorded on the ledger when the transaction is committed.

",r +"Wordpress get_user_meta showing wrong value

Hello and thanks for spending the time to try and help me out. I am not experienced at all in PHP. I am attempting to do some custom snippets for my wordpress site. I have done a few already and this one for some reason isn't working. I use Formidable Forms on my site to sign users up and at the time of sign up there is a custom meta field created called "info" and the value is set to "no". This field is only changed when the user creates an entry in my customer-info form. Then the meta value is changed to "yes". This snippet is to force them to fill out the info form when they log in and direct them to that page but for some reason the value I get from the user meta is "no". which is wrong. any ideas? Code im using:

+
function my_logged_in_redirect() {
+$userid = get_current_user_id();
+$info = get_user_meta($userid, 'info', true);
+$loggedin = is_user_logged_in();
+if (is_page(1795)){
+    if ($loggedin == true && $info = 'no'){
+        wp_redirect(home_url('/dashboard/account-information'));
+    }
+    else if ($loggedin == true && $info = 'yes'){
+        wp_redirect(home_url('/dashboard'));
+    }
+    else if ($loggedin == false){
+        wp_redirect(home_url());
+    }
+}
+
+

} +add_action( 'template_redirect', 'my_logged_in_redirect' );

","

Well I think that right off the bat your if statement might be wrong. if ($loggedin == true && $info = 'no'){

+

should be changed to if ($loggedin == true && $info == 'no'){

+

also this else if ($loggedin == true && $info = 'yes'){

+

to this else if ($loggedin == true && $info == 'yes'){

+

Your code doesn't look wrong aside those points ^. Looks like the $info might have the correct value but just the if statement was incorrect.

",r +"Python argparse required?

How can I make it a required argument only if I don't select another option, so when I select version it shouldn't require -f, but the rest of the time it should be required?

+
parser = argparse.ArgumentParser(
+        description="This script will check the uri's from XXX")
+
+parser.add_argument(
+    "-f", "--file", help="XXX export file to use", required=True)
+parser.add_argument("-c", "--check", action="store_true",
+                    help="Check the uri's")
+parser.add_argument("-p", "--passwords", action="store_true",
+                    help="Check the weak passwords")
+parser.add_argument("-V", "--version", action="store_true",
+                    help="Show version")
+self.params = parser.parse_args(self.get_params())
+
","

So, two things:

+
    +
  1. In the general case, this is done with add_mutually_exclusive_group(required=True) and adding the mutually exclusive arguments to that group (this isn't exactly what you want, since it won't allow you to pass both, but it's close enough).
  2. +
  3. In this specific case, you should be using the action='version' action for displaying the version, which exists specifically for this purpose, and leave -f plain required=True as you've already written it.
  4. +
",r +"Shiny app with datatable with editable cells. How to save the edited content after the user removes rows from the table?

I have an app that uses plot_click functionality to draw points on a graph and create a table to track the coordinates of each point. As part of the app I have a remove button which lets users remove the selected rows if needed. If a row is removed then the plot is updated.

+

I added a column to my table that is editable, so users can write notes. The problem I have is that when I remove a row, the notes added on other cells also disappears.

+

I believe I have to update the remove event with input$mytable_cell_edit and probably create another event for cell edit but not sure how to to do this.

+

Sample code below

+
library(shiny)
+library(tidyverse)
+library(DT)
+
+
+#UI
+ui <- basicPage(
+  column(width = 3, plotOutput("plot", click = "plot_click", width = "350px", height="700px")),
+  column(width = 9, DTOutput("mytable")),
+  actionButton("remove", "remove")
+  
+)
+
+
+#server
+server <- function(input, output) {
+  
+  
+  #click inputs
+  val <- reactiveValues(
+    clickx = numeric(), 
+    clicky = numeric(), 
+    shape= 2, 
+    id = numeric(),
+    id_total = 0
+  )
+  
+  mytable <- reactive(
+    data.frame(`Location X` = round(val$clickx,2), 
+               `Location Y` = round(val$clicky,2),
+               ID = val$id)
+  )
+  
+  #bind clicks
+  observeEvent(input$plot_click, {
+    val$clickx = c(val$clickx, input$plot_click$x)
+    val$clicky = c(val$clicky, input$plot_click$y)
+    val$id_total <- val$id_total + 1
+    val$id <- c(val$id, val$id_total)
+  }) 
+  
+  #interactive plot
+  output$plot <- renderPlot({
+    plot(c(-25, 25), c(-50, 50), type = "n", axes = T , ylab = "", xlab = "")
+    points(val$clickx, val$clicky, cex = 2, pch=19, col = "black")
+  })
+  
+  #mytable
+  output$mytable <- renderDT({
+    datatable(mytable() %>%
+                mutate(Notes = "") %>%
+                arrange(desc(ID)) %>%
+                select(ID, everything()),
+              editable = list(target = "cell", disable = list(columns = 0:2)),
+              rownames= F)
+  })
+  # remove btn
+  observeEvent(input$remove, {
+    req(input$mytable_rows_selected)
+    selected_ids <-  sort(val$id, TRUE)[-input$mytable_rows_selected]
+    val$clickx <-  val$clickx[val$id %in% selected_ids]
+    val$clicky <-  val$clicky[val$id %in% selected_ids]
+    val$id <-  val$id[val$id %in% selected_ids]
+  })
+ 
+  
+}
+
+shinyApp(ui, server)
+
+
+

I tried a similar solution to this but didn't work.

","

This seems to work. Sorry I forgot the rounding.

+

+
library(shiny)
+library(DT)
+
+ui <- basicPage(
+  br(),
+  actionButton("remove", "remove", class = "btn-primary"),
+  br(),
+  fluidRow(
+    column(
+      width = 3, 
+      plotOutput("plot", click = "plot_click", width = "100%", height = "700px")
+    ),
+    column(
+      width = 9, 
+      DTOutput("mytable")
+    )
+  )
+)
+
+
+callback <- c(
+  '$("#remove").on("click", function(){',
+  '  table.rows(".selected").remove().draw();',
+  '});'
+)
+
+#server
+server <- function(input, output, session) {
+
+  mytable <- data.frame(
+    ID           = integer(),
+    `Location X` = numeric(),
+    `Location Y` = numeric(),
+    Notes        = character(),
+    check.names = FALSE
+  )
+  
+  ID <- reactiveVal(0L)
+  
+  Xcoords <- reactiveVal()
+  Ycoords <- reactiveVal()
+  
+  #mytable
+  output[["mytable"]] <- renderDT({
+    datatable(
+      mytable,
+      rownames = FALSE,
+      editable = list(target = "cell", disable = list(columns = c(0L, 1L, 2L))),
+      callback = JS(callback)
+    )
+  }, server = FALSE)
+  
+  proxy <- dataTableProxy("mytable")
+  
+  #bind clicks
+  observeEvent(input[["plot_click"]], {
+    x <- input[["plot_click"]][["x"]]
+    y <- input[["plot_click"]][["y"]]
+    Xcoords(c(Xcoords(), x))
+    Ycoords(c(Ycoords(), y))
+    newRow <- as.data.frame(list(ID() + 1L, x, y, ""))
+    ID(ID() + 1L)
+    addRow(proxy, newRow, resetPaging = FALSE)
+  }) 
+  
+  #interactive plot
+  output[["plot"]] <- renderPlot({
+    plot(c(-25, 25), c(-50, 50), type = "n", ylab = NA, xlab = NA)
+    points(Xcoords(), Ycoords(), cex = 2, pch = 19, col = "black")
+  })
+  
+  # remove btn
+  observeEvent(input[["remove"]], {
+    req(input[["mytable_rows_selected"]])
+    indices <- input[["mytable_rows_selected"]]
+    Xcoords(Xcoords()[-indices])
+    Ycoords(Ycoords()[-indices])
+  })
+  
+}
+
+shinyApp(ui, server)
+
",r +"React, MobX. The application state is not updated instantly

My store looks like this

+
count = 0
+increment = () => {
+this.count = this.count + 1;
+}
+
+

And my component, that wrapped in observer

+
<button onClick = {()=>{
+increment()
+console.log(count, "after")
+}}>{count}</button>
+
+

I expect that the console.log line will already have the updated value. That is, count will be equal to one. The component itself is updated, that is, the count value is changed. But in the console.log line, the count value will first be 0, you press again, the count in the component is 2, but in console.log it is one

","

That's just how closures works, it's not related to MobX. I expect that you have something like that in the code:

+
const {increment, count} = store
+
+return <button onClick = {()=>{
+  increment()
+  console.log(count, "after")
+  }}>{count}</button>
+
+

So on the first render your onClick has count === 0 in the scope, when you press the button increment increments the count, but onClick still has the old value because that's what it had when it rendered first time. And so on.

+

You can read more in React docs about it.

+

With MobX you can overcome it by not destructuring the store, then you will always have latest values everywhere:

+
return <button onClick = {()=>{
+  store.increment()
+  console.log(store.count, "after")
+  }}>{store.count}</button>
+
",r +"WooCommerce product attribute 'Custom Product Attribute' change text via functions.php?

I've added a handful of Custom Product Attribute's (CPA) to a product, and all displays as expected. The main issue is that I want to add a link to the Contact page ("COUNTRIES WE SHIP TO" attribute), which I cant do via the page builder.

+

In other places, I've used the add_filter facility to change the text on checkout pages etc, but can't find much on hooks for product attributes and specifically CPA's. Can anybody help with an example?

+

P.S.

+

See the answer below for the solution.

","

Easy once you have a little help from your friends...

+
add_filter( 'woocommerce_display_product_attributes', custom_product_additional_information', 10, 2 );
+function custom_product_additional_information( $product_attributes, $product ) {
+    $product_attributes[ 'attribute_' . 'custom-one' ] = array(
+        'label' => __('Quantity per Package'),
+        'value' => __('Value 1'),
+    );
+    return $product_attributes;
+}
+
+

Ciao

",r +"Select key and one value out of tuples with multiple values per key to create new dictionary

I started recently with learning programming Python and I am running into a problem. +I tried to solve this myself, unsuccessfully.

+

I have a dictionary with a formatted string as a keys and tuples with 3 values per key.

+

dict1 = { “a;2;1;1;” : ( 1, 2, 3), “a;3;2;1;” : ( 4, 5, 6)}

+

I want to create en new dictionary dict2 with all keys from dict1 and only the third value from each key.

+

dict2 = { “a;2;1;1;” : 3, “a;3;2;1;” : 6}

+

In these examples I used only a two key-value pair, the real dictionary has ten thousands of key-value pairs.

+

Any suggestions? +Help is appreciated.

","

Do it with a simple iteration:

+
dict2 = dict()
+for k in dict1:
+    dict2[k] = dict1[k][2]
+
+

Or use a dict-comprehension to do it in a single line:

+
dict2 = {k: dict1[k][2] for k in dict1}
+
",r +"How do I solve the 0 element problem in Google Earth Engine?

I used the .combine command to convert two image collections into a two-band image collection (in the last line) to use in a function in the next step. This command is executed but writes 0 elements in the console. Where does this problem come from?

+

code link: https://code.earthengine.google.com/ed0992093ff830d926c7dd14403477c6

+

Code:

+
           var ndvi = function(img){
+           var bands = img.select(['B2','B3','B4','B8']).multiply(0.0001)
+           .clip(geometry);
+           var index = bands.normalizedDifference(['B8','B4']).rename('NDVI_S2');
+           return index
+           .copyProperties(img,['system:time_start','system:time_end','system:index']);
+           };
+
+           var S2 = ee.ImageCollection('COPERNICUS/S2_SR')
+           .filterBounds(geometry)
+           .filterDate('2018-10-24','2019-06-30')
+          //.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE',20))
+          .map(ndvi);
+
+          print(S2);
+
+
+
+          var START = '2018-10-24';
+          var END = '2019-06-30';
+
+          var DATES = [ '2018-12-19', '2018-12-29', '2019-01-23', '2019-02-12', '2019-03-04',
+          '2019-03-19', '2019-04-08', '2019-04-13', '2019-05-13', '2019-05-18', '2019-05-23',
+          '2019-05-28', '2019-06-02', '2019-06-07', '2019-06-12', '2019-06-17', '2019-06-22',
+          '2019-06-27'];
+
+          var addTime = function(x) {
+            return x.set('Date', ee.Date(x.get('system:time_start')).format("YYYY-MM-dd"))};
+
+          var Sentinel = ee.ImageCollection(S2)
+             .filter(ee.Filter.date(START, END))
+             .map(addTime)
+             .filter(ee.Filter.inList('Date',ee.List(DATES)));
+          print(Sentinel);
+
+          var PMODIS = 
+          ee.Image('MODIS/006/MCD43A4/2018_12_19').select('Nadir_Reflectance_Band4');
+
+          var MODProjection = PMODIS.projection();
+          print('MODIS projection:', MODProjection);
+
+          var Viz = {min: 0, max: 1, palette: ['be6c44','ca3a3a','e4ae0c','565c04','819536']};
+
+
+          var S2_resampled = Sentinel.map(function(img){
+          var S2Mean = img
+          // Force the next reprojection to aggregate instead of resampling.
+          .reduceResolution({
+          reducer: ee.Reducer.mean(),
+          maxPixels: 2146
+          })
+         // Request the data at the scale and projection of the Sentinel image.
+         .reproject({
+         crs: MODProjection
+          });
+
+          return S2Mean
+        .copyProperties(img,['system:time_start','system:time_end','system:index']);
+        });
+
+        Map.addLayer(S2_resampled)
+
+        var M_ndvi = function(img){
+        var bands = 
+        img.select(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).multiply(0.0001)
+        .clip(geometry);
+        
+         var index=bands
+         .normalizedDifference(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5'])
+         .rename( 
+        'NDVI_MOD');
+         return index
+        .copyProperties(img,['system:time_start','system:time_end','system:index']);
+         };
+
+        var MOD = ee.ImageCollection('MODIS/006/MCD43A4')
+        .filterBounds(geometry)
+        .filterDate('2018-10-24','2019-06-30')
+        .map(M_ndvi);
+
+
+        var MODIS = ee.ImageCollection(MOD)
+            .filter(ee.Filter.date(START, END))
+            .map(addTime)
+            .filter(ee.Filter.inList('Date',ee.List(DATES)));
+        print(MODIS);
+
+        var S2_and_MOD = S2_resampled.combine(MODIS, false);
+        print(S2_and_MOD);
+
+        var Diff = S2_and_MOD.map(function(img){
+        var clip = img.clip(geometry);
+        var Diffe = clip.expression('NDVI_S2 - NDVI_MOD',
+        {'NDVI_S2':clip.select('NDVI_S2') , 
+        'NDVI_MOD':clip.select('NDVI_MOD')}).rename('Diff');
+
+        return Diffe
+        .copyProperties(img,['system:time_start','system:time_end']); });
+
+        print(Diff);
+
","

ee.Image.combine() uses the system:ID property to join the 2 images. See the documentation here. Since your images do not match, the resulting collection has no images.

+

A solution that should fit your needs utilizes the ee.Join.inner() to take advantage of the Date property that you have created to join the 2 image collections. A similar question was answered here.

+

Using inner join, I was able to accomplish what appeared to be your goal of finding the difference in NDVI between the S2 and MODIS collections. The full working script can be found here: https://code.earthengine.google.com/dc45df1b7cf83723d53e9f7917975e2d

+

Code:

+
// Function - Calculate S2 NDVI
+var ndvi = function(img){
+  var bands = img.select(['B2','B3','B4','B8']).multiply(0.0001)
+  .clip(geometry);
+  var index = bands.normalizedDifference(['B8','B4']).rename('NDVI_S2');
+  return index
+  .copyProperties(img,['system:time_start','system:time_end','system:index']);
+};
+
+// Get S2 NDVI images
+var S2 = ee.ImageCollection('COPERNICUS/S2_SR')
+.filterBounds(geometry)
+.filterDate('2018-10-24','2019-06-30')
+//.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE',20))
+.map(ndvi);
+
+print('S2 NDVI ImageCollection',S2);
+
+// Set Date Parameters
+var START = '2018-10-24';
+var END = '2019-06-30';
+
+// Create Date List
+var DATES = [ '2018-12-19', '2018-12-29', '2019-01-23', '2019-02-12', '2019-03-04',
+'2019-03-19', '2019-04-08', '2019-04-13', '2019-05-13', '2019-05-18', '2019-05-23',
+'2019-05-28', '2019-06-02', '2019-06-07', '2019-06-12', '2019-06-17', '2019-06-22',
+'2019-06-27'];
+
+// Function - Add 'Date' field to image
+var addTime = function(x) {
+  return x.set('Date', ee.Date(x.get('system:time_start')).format("YYYY-MM-dd"))};
+
+// Run addTime on S2 ImageCollection
+var Sentinel = ee.ImageCollection(S2)
+            .filter(ee.Filter.date(START, END))
+            .map(addTime)
+            .filter(ee.Filter.inList('Date',ee.List(DATES)));
+print('Date Added S2', Sentinel);
+
+// Get MODIS Projection
+var PMODIS = ee.Image('MODIS/006/MCD43A4/2018_12_19').select('Nadir_Reflectance_Band4');
+
+var MODProjection = PMODIS.projection();
+print('MODIS projection:', MODProjection);
+
+// Set Visualization Parameters
+var Viz = {min: 0, max: 1, palette: ['be6c44','ca3a3a','e4ae0c','565c04','819536']};
+
+
+// Reproject S2 images to MODIS projection
+var S2_resampled = Sentinel.map(function(img){
+  var S2Mean = img
+      // Force the next reprojection to aggregate instead of resampling.
+      .reduceResolution({
+        reducer: ee.Reducer.mean(),
+        maxPixels: 2146
+      })
+      // Request the data at the scale and projection of the Sentinel image.
+      .reproject({
+        crs: MODProjection
+      });
+  
+  return S2Mean
+  .copyProperties(img,['system:time_start','system:time_end','system:index']);
+});
+
+print('S2_resampled',S2_resampled);
+Map.addLayer(S2_resampled);
+
+// Function - Calculate MODIS NDVI
+var M_ndvi = function(img){
+  var bands = img.select(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).multiply(0.0001)
+  .clip(geometry);
+  var index = bands.normalizedDifference(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).rename('NDVI_MOD');
+  return index
+  .copyProperties(img,['system:time_start','system:time_end','system:index']);
+};
+
+// Get MODIS NDVI Images
+var MOD = ee.ImageCollection('MODIS/006/MCD43A4')
+.filterBounds(geometry)
+.filterDate('2018-10-24','2019-06-30')
+.map(M_ndvi);
+
+// Run addTime on MODIS ImageCollection
+var MODIS = ee.ImageCollection(MOD)
+            .filter(ee.Filter.date(START, END))
+            .map(addTime)
+            .filter(ee.Filter.inList('Date',ee.List(DATES)));
+print('MODIS',MODIS);
+
+// Combine MODIS and S2 Image Collections using Date
+// Specify the join type
+var join_type = ee.Join.inner();
+
+// Set the join parameter
+var filter = ee.Filter.equals({
+  leftField: 'Date',
+  rightField: 'Date'
+});
+
+// Execute the join
+var inner_join = ee.ImageCollection(join_type.apply(MODIS,S2_resampled,filter));
+
+// Flatten joined images into a single image with 2 bands
+var S2_and_MOD = inner_join.map(function(feature) {
+  return ee.Image.cat(feature.get('primary'), feature.get('secondary'));
+});
+
+print('Combined S2 and MODIS Collection:',S2_and_MOD);
+
+// Calculate the difference between S2 and MODIS NDVI values
+var Diff = S2_and_MOD.map(function(img){
+  var clip = img.clip(geometry);
+  var Diffe = clip.expression('NDVI_S2 - NDVI_MOD',
+  {'NDVI_S2':clip.select('NDVI_S2') , 'NDVI_MOD':clip.select('NDVI_MOD')}).rename('Diff');
+
+  return Diffe
+  .copyProperties(img,['system:time_start','system:time_end']); });
+
+print('NDVI Difference Collection',Diff);
+
+
",r +"Nest can't resolve dependencies of the AuthenticationService

I am new to nest js and I am trying to implement authenticating with nest js using JWT Token. I flow This article to implement my authenticating code.

+

When I run the code I get an error like this.

+

**

+
+

[Nest] 16236 - 01/29/2022, 7:16:06 PM ERROR [ExceptionHandler] Nest +can't resolve dependencies of the AuthenticationService (?, +JwtService, ConfigService). Please make sure that the argument +UsersService at index [0] is available in the AuthenticationModule +context. Potential solutions:

+
    +
  • If UsersService is a provider, is it part of the current AuthenticationModule?
  • +
  • If UsersService is exported from a separate @Module, is that module imported within AuthenticationModule? @Module({ +imports: [ /* the Module containing UsersService */ ] })
  • +
+
+

**

+

And I have no idea what is wrong with my code.

+

This is my UserModule :

+
@Module({
+  imports: [TypeOrmModule.forFeature([User])],
+  controllers: [UsersController],
+  providers: [UsersService],
+})
+export class UsersModule {}
+
+

This is my AuthenticationModule:

+
@Module({
+  imports: [
+    UsersModule,
+    PassportModule,
+    ConfigModule,
+    JwtModule.registerAsync({
+      imports: [ConfigModule],
+      inject: [ConfigService],
+      useFactory: async (configService: ConfigService) => ({
+        secret: configService.get('JWT_SECRET'),
+        signOptions: {
+          expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,
+        },
+      }),
+    }),
+  ],
+  controllers: [AuthenticationController],
+  providers: [AuthenticationService, LocalStrategy, JwtStrategy],
+})
+export class AuthenticationModule {}
+
+

This is my AppModule:

+
@Module({
+  imports: [
+    TypeOrmModule.forRoot(ORM_CONFIG),
+    ConfigModule.forRoot({
+      validationSchema: Joi.object({
+        JWT_SECRET: 'ABC',
+        JWT_EXPIRATION_TIME: '1d',
+      }),
+    }),
+    ItemModule,
+    CategoryModule,
+    ItemHasCategoryModule,
+    OrderModule,
+    OrderHasItemModule,
+    PaymentModule,
+    CustomerModule,
+    UsersModule,
+    AuthenticationModule,
+  ],
+  controllers: [],
+  providers: [],
+})
+export class AppModule {}
+
+

My AuthenticationService File :

+
@Injectable()
+export class AuthenticationService {
+  constructor(
+    private readonly usersService: UsersService,
+    private readonly jwtService: JwtService,
+    private readonly configService: ConfigService,
+  ) {}
+
+

My UsersService File :

+
@Injectable()
+export class UsersService {
+  constructor(
+    @InjectRepository(User) private readonly userRepository: Repository<User>,
+  ) {}
+
+

If anyone knows the answer to this...I really need your help..I am struggling with this error for hours...Thank you.

","

You need to export UserService to be able to use it in other modules.

+
@Module({
+  imports: [TypeOrmModule.forFeature([User])],
+  controllers: [UsersController],
+  providers: [UsersService],
+  exports: [UsersService] 
+}) 
+export class UsersModule {}
+
+

Explanation on exports array:

+
+

the subset of providers that are provided by this module and should be available in other modules which import this module. You can use either the provider itself or just its token (provide value)

+
+

More details on modules: https://docs.nestjs.com/modules

",r +"Calculating calendar weeks from fiscal weeks

So I am really new to this and struggling with something, which I feel should be quite simple.

+

I have a Pandas Dataframe containing two columns: Fiscal Week (str) and Amount sold (int).

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Fiscal WeekAmount sold
0201903124
1201904147
2201922134
3201923146
4201924135
+
+

My problem is the fiscal week column. It contains strings which describe the fiscal year and week . The fiscal year for this purpose starts on October 1st and ends on September 30th. So basically, 2019031 is the Monday (the 1 at the end) of the third week of October 2019. And 2019221 would be the 2nd week of March 2020. +The issue is that I want to turn this data into timeseries later. But I can't do that with the data in string format - I need it to be in date time format.

+

I actually added the 1s at the end of all these strings using

+
df['Fiscal Week']= df['Fiscal Week'].map('{}1'.format)
+
+

so that I can then turn it into a proper date:

+
df['Fiscal Week'] = pd.to_datetime(df['Fiscal Week'], format="%Y%W%w")
+
+

as I couldn't figure out how to do it with just the weeks and no day defined. +This, of course, returns the following:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Fiscal WeekAmount sold
02019-01-2124
12019-01-2847
22019-06-0334
32019-06-1046
42019-06-1735
+
+

As expected, this is clearly not what I need, as according to the definition of the fiscal year week 1 is not January at all but rather October.

+

Is there some simple solution to get the dates to what they are actually supposed to be?

+

Ideally I would like the final format to be e.g. 2019-03 for the first entry. So basically exactly like the string but in some kind of date format, that I can then work with later on. Alternatively, calendar weeks would also be fine.

","

Assuming you have a data frame with fiscal dates of the form 'YYYYWW' where YYY = the calendar year of the start of the fiscal year and ww = the number of weeks into the year, you can convert to calendar dates as follows:

+
def getCalendarDate(fy_date: str):
+    f_year = fy_date[0:4]
+    f_week = fy_date[4:]
+    fys = pd.to_datetime(f'{f_year}/10/01', format= '%Y/%m/%d')
+    return fys + pd.to_timedelta(int(f_week), "W")  
+
+

You can then use this function to create the column of calendar dates as follows:

+
df['Calendar Date]'] =  list(getCalendarDate(x) for x in df['Fiscal Week'].to_list())
+
",r +"How to scale the uploaded image in P5JS

I am trying to write a stamp tool function that can upload an image as a stamp. Unfortunately, I am unable to scale the image as a stamp size. For example. the image remains the original size but the stamp size is 50x50. Therefore, the stamp can only show the top left corner of the image.

+

I tried to use the size or resize function in P5js but it doesn't work.

+

I initialise a global variable called "stamp" and the size.

+
    stamp = loadImage('./stamps/star.png');
+    this.size = 50;
+
+

In the P5JS draw function

+
    image(stamp, mouseX, mouseY, this.size, this.size);
+
+

In my handleFile function

+
var handleFile = function (file) {
+    print(file);
+    if (file.type === 'image') {
+        var targetStamp = createDiv();
+        targetStamp.class('stamps');
+        newStamp = createImg(file.data, '', () => { newStamp.size(100, AUTO) });
+        targetStamp.child(newStamp);
+        stampSelector = select(".stampSelector");
+        stampSelector.child(targetStamp);
+
+        targetStamp.mouseClicked(function () {
+            var items = selectAll(".stamps");
+            for (var i = 0; i < items.length; i++) {
+                items[i].style('border', '0')
+            }
+            targetStamp.style("border", "2px solid blue");
+            stamp = newStamp;
+        })
+    } else {
+        img = null;
+    }
+}
+
+

The size is succeeded to change by CSS, but cannot use as a stamp. Anyone can help please.

","

When you say "cannot use as a stamp" it is not clear what the problem is. With a simplified version of your code it generally seems to work. However, it would appear that there is a bug with how the image() function handles source <img> elements that have been resized (it crops the source to the specified size, instead of using the original image dimensions, even when you explicitly specify source dimensions). There is a workaround though: using a CSS transform to control the size of the <img> element.

+

+
+
let img;
+let size = 50;
+
+function setup() {
+  createCanvas(400, 400);
+  let input = createFileInput(handleFile);
+  input.position(10, 10);
+  noLoop();
+  background(0);
+}
+
+function draw() {}
+
+function mouseClicked() {
+  if (img) {
+    image(img, mouseX, mouseY, size, size);
+  }
+}
+
+function handleFile(file) {
+  if (file.type === ""image"") {
+    img = createImg(file.data, ""uploaded image"", ""anonymous"", () => {
+      // This resizes the <img> tag, but will not effect the size of the image when drawn.
+      // img.size(100, AUTO);
+      img.style('transform', `scale(${100 / img.width})`);
+      img.style('transform-origin', 'top left');
+    });
+  } else {
+    img = null;
+  }
+}
+
<script src=""https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js""></script>
+
+
+

",r +"Bot no longer turning on (Discord.js v13)

I have a simple discord.js bot coded, but whenever I do "bot.login(process.env.TOKEN)", it simply doesn't work and no errors are logged. All I could find was when I used "client.on('debug', console.log)", which returned the following:

+
Hit a 429 while executing a request.
+    Global  : false
+    Method  : get
+    Path    : /gateway/bot
+    Route   : /gateway/bot
+    Limit   : Infinity
+    Timeout : 499ms
+    Sublimit: 3199000ms
+
+

Anyone know what this means or how I could possibly fix it?

","

This means your bot is rate-limited. There are a few solutions here:

+
    +
  1. Wait a bit, so that the timeout completes
  2. +
  3. If you are using replit or any hosting, type kill 1 in the terminal and try again
  4. +
+

And lastly, make sure you don't have any loops requesting to the API. Requests to the API include fetching data from the API or modifying things.

",r +"Problem with non-standard evaluation in disk.frame objects using data.table syntax

Problem

+

I'm currently trying to write a function that filters some rows of a disk.frame object using regular expressions. I, unfortunately, run into some issues with the evaluation of my search string in the filter function. My idea was to pass a regular expression as a string into a function argument (e.g. storm_name) and then pass that argument into my filtering call. I used the %like% function included in {data.table} for filtering rows.

+

My problem is that the storm_name object gets evaluated inside the disk.frame. However, since the storm_name is only included in the function environment, but not in the disk.frame object, I get the following error:

+
Error in .checkTypos(e, names_x) : 
+  Object 'storm_name' not found amongst name, year, month, day, hour and 8 more
+
+

I already tried to evaluate the storm_nameobject in the parent frame using eval(sotm_name, env = parent.env()), but that also didn't help. Interestingly, this problem only occurs with {disk.frame} objects but not with {data.table} objects.

+

For now I found a solution using {dplyr} instead. However, I would be grateful for any ideas on how this problem could be solved with {data.table}.

+

Reproducible Example

+
# Load packages
+library(data.table)
+library(disk.frame)
+
+# Create data table and diskframe object of storm data
+storms_df <- as.disk.frame(storms)
+storms_dt <- as.data.table(storms)
+
+# Create search function
+grep_storm_name <- function(dfr, storm_name){
+  
+  dfr[name %like% storm_name]
+  
+}
+
+# Check function with data.table object
+grep_storm_name(storms_dt, "^A")
+
+# Check function with diskframe object
+grep_storm_name(storms_df, "^A")
+
+

Session Info

+
R version 4.1.0 (2021-05-18)
+Platform: x86_64-w64-mingw32/x64 (64-bit)
+Running under: Windows 10 x64 (build 19043)
+
+Matrix products: default
+
+locale:
+[1] LC_COLLATE=English_Sweden.1252  LC_CTYPE=English_Sweden.1252    LC_MONETARY=English_Sweden.1252
+[4] LC_NUMERIC=C                    LC_TIME=English_Sweden.1252    
+
+attached base packages:
+[1] stats     graphics  grDevices utils     datasets  methods   base     
+
+other attached packages:
+[1] disk.frame_0.5.0  purrr_0.3.4       dplyr_1.0.7       data.table_1.14.0
+
+loaded via a namespace (and not attached):
+ [1] Rcpp_1.0.7            benchmarkmeData_1.0.4 pryr_0.1.4            pillar_1.6.4         
+ [5] compiler_4.1.0        iterators_1.0.13      tools_4.1.0           digest_0.6.27        
+ [9] bit_4.0.4             jsonlite_1.7.2        lifecycle_1.0.1       tibble_3.1.6         
+[13] lattice_0.20-44       pkgconfig_2.0.3       rlang_0.4.12          Matrix_1.3-3         
+[17] foreach_1.5.1         rstudioapi_0.13       DBI_1.1.1             parallel_4.1.0       
+[21] bigassertr_0.1.4      bigreadr_0.2.4        httr_1.4.2            stringr_1.4.0        
+[25] globals_0.14.0        generics_0.1.1        fs_1.5.0              vctrs_0.3.8          
+[29] bit64_4.0.5           grid_4.1.0            tidyselect_1.1.1      glue_1.6.0           
+[33] listenv_0.8.0         R6_2.5.1              future.apply_1.7.0    parallelly_1.25.0    
+[37] fansi_1.0.0           magrittr_2.0.1        codetools_0.2-18      ellipsis_0.3.2       
+[41] fst_0.9.4             assertthat_0.2.1      future_1.21.0         benchmarkme_1.0.7    
+[45] utf8_1.2.2            stringi_1.7.6         doParallel_1.0.16     crayon_1.4.2 
+
",

It now works since disk.frame v0.6

,r +"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined component issue

I'm getting an error called Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined in my newly built react-app after register and login which I'm unable to find the solution.

+

Here's => the Working Demo

+

and the screen

+

Seems like the error is for the private route

+

Please find the code piece below:

+
import React from 'react';
+import { Route, Redirect } from 'react-router-dom';
+
+export const PrivateRoute = ({ component: Component, ...rest }) => (
+    <Route {...rest} render={props => (
+        localStorage.getItem('user')
+            ? <Component {...props} />
+            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
+    )} />
+)
+
+

Need Solution.

","

Looks like export issue +Please export he QuizPage like this

+

+
+
const connectedQuizPage = connect(mapStateToProps, mapDispatchToProps)(App);
+export { connectedQuizPage as QuizPage };
+
+
+

",r +"React Navigation not passing props

I have a component that takes an object and passes it to a new screen upon navigating to the screen. However, when I go to the next screen the object passed is undefined. What am I doing wrong here? I have done the exact same thing with another component and it works perfectly fine, but on this component, it isn't passing the parameter properly. Is there something else I need to configure in the navigator?

+

GoalCard.JS

+
import * as React from 'react';
+
+import 'react-native-get-random-values';
+import { v4 as uuidv4 } from 'uuid';
+
+import { useNavigation } from "@react-navigation/core";
+import { Card, Chip, Divider, Paragraph, Text, Title } from 'react-native-paper';
+
+const GoalCard = ({ item }) => {
+
+    const navigation = useNavigation();
+    const goals = JSON.parse(item.Goals);
+    const tasks = JSON.parse(item.GoalTasks);
+    const [goalsData, setGoalsData] = React.useState(
+        {
+            GoalName: item.GoalName,
+            GoalID: item.GoalID,
+            GoalDescription: item.GoalDescription,
+            GoalComplete: item.GoalComplete,
+            GoalTasks: tasks,
+            Goals: goals,
+            UserID: item.UserID,
+            createdAt: item.createdAt,
+            updatedAt: item.updatedAt
+        }
+    );
+    
+    
+    return(
+        <Card className="card">
+            <Card.Content>
+                <Title>Goal Set: {item.GoalName}</Title>
+                <Divider/>
+                <Paragraph>
+                    <Chip
+                        onPress={() => {
+                            navigation.navigate(
+                                'Goals', {
+                                    goalsData: goalsData
+                                });
+                            }}
+                    >
+                    Edit
+                    </Chip>
+                    <Text onPress={() => console.log(goalsData)}>Log</Text>
+                    <Text>Description: {item.GoalDescription}</Text>
+                    <Divider/>
+                    {Object.entries(goals).map(obj => (
+                        <Text key={uuidv4()}>{obj[1].goal}{" "}</Text>
+                    ))}
+                </Paragraph>
+            </Card.Content>
+        </Card>
+    );
+}
+
+export default GoalCard;
+
+

GoalScreen.js

+

Pressing "Log" as seen in this file returns undefined

+
import React from "react";
+
+import { ScrollView, View } from "react-native";
+import { Text } from "react-native-paper";
+
+import { MainStyles } from "../../styles/Styles";
+
+const GoalScreen = ({ route }) => {
+    const { goalData } = route.params;
+
+    return (
+        <ScrollView>
+            <View style={MainStyles.col}>
+                <Text onPress={() => console.log(goalData)}>Log</Text>
+            </View>
+        </ScrollView>
+    );
+};
+
+export default GoalScreen;
+
","

There is a typo ... You are setting

+
goalsData: goalsData
+
+

But you are trying to read as below

+
const { goalData } = route.params;
+
+

try

+
const { goalsData } = route.params;
+
",r +"Message error by read timeout keeps appearing even though I add 'try except'
import schedule
+import subprocess
+
+try:
+    subprocess.call("my_code.py", shell=True)
+except:
+    pass
+
+def trigger():
+    try:
+        subprocess.call("my_code.py", shell=True)
+    except:
+        pass
+schedule.every(30).seconds.do(trigger)
+
+while 1:
+    schedule.run_pending()
+    sleep(1)
+
+

Inside my_code.py there is a:

+
response = requests.get(url, headers=headers, timeout=5).json()
+
+

So that there was no risk of kill the terminal or showing an error message, I added try except, thinking that this is how would not show errors and would continue looping the next calls.

+

But this message (along with several other lines with things written) appears:

+
requests.exceptions.ReadTimeout: 
+HTTPSConnectionPool(host='XXXXXXXXXX.com', port=443): 
+Read timed out. (read timeout=5)
+
+

When it reaches the 5 second limit, how should I proceed so that it doesn't happen since with try except it didn't solve the problem?

+

Detail, I didn't want to add a try except together to the request in my_code.py, I really would like to know if there is any way to protect my run terminal to these errors but just messing with this code I published.

","

Based on the information from: +https://docs.python.org/3/library/subprocess.html#older-high-level-api

+

You should pass subprocess.DEVNULL as value for stderr agument:

+
import subprocess
+subprocess.call(
+    "my_code.py",
+    shell=True,
+    stderr=subprocess.DEVNULL,
+    )
+
",r +"Jetpack Compose offset image vector in Canvas

I have a problem with vector image in Canvas. As shown below I can just call vector image but I can’t make any offset in Canvas. So I only can have it the way it is.

+

I don't know the reason why there is no Offset option like in drawCircle or drawRect, if someone has some ideas it would be great.

+
val vector = ImageVector.vectorResource(id = R.drawable.ic_test)
+val painter = rememberVectorPainter(image = vector)
+
+Box(contentAlignment = Alignment.Center) {
+    Canvas(
+        modifier = Modifier
+            .fillMaxWidth()
+            .padding(10.dp)
+    ) {
+            with(painter) {
+                draw(
+                    painter.intrinsicSize
+                )
+            }
+
+        }
+    }
+
+

I tried something like adding Offset into with(painter) but nothing changes:

+
with(painter) {
+    draw(
+        painter.intrinsicSize
+    )
+    Offset(x = 10f, y = 10f)
+}
+
","

You can use DrawScope.translate:

+
translate(left = 10f, top = 10f) {
+    with(painter) {
+        draw(
+            painter.intrinsicSize
+        )
+    }
+}
+
",r +"PowerAutomate ForEach user loop

I have an automate-admin account (as a global admin) that runs my flows.

+

Some graph API calls run in the context of the user, and return results related to the user calling (i.e. functions that list my planner tasks).

+

Is it possible for the automate-admin to run as a user so that when calling the graph API it would return the user info?

+

Pseudo code is below:

+
ForEach (user in users)
+   Context = SwitchUserContext(user)
+   Context.Switch()
+   // Any calls here are as if user is calling API
+   ... Call API ...
+
","

You can click on the three dots: ... +From that screen, you can choose if it's the user connection or your admin connection.

",r +"testContainers and Rancher

I have a Spring Boot application with integration tests that are using testContainers.

+

Till recently, I used Docker Desktop and was able to easily run the test from within Intellij or from CLI.

+

Recently I changed my Windows machine to Rancher desktop.

+

Now when trying to run the integration tests gradle integrationTest I'm getting this error:

+
+

Caused by: java.lang.IllegalStateException: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration +at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:109) +at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:136) +at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:178) +at org.testcontainers.LazyDockerClient.getDockerClient(LazyDockerClient.java:14) +at org.testcontainers.LazyDockerClient.authConfig(LazyDockerClient.java:12) +at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:310)

+
+

Is there an additional configuration that is needed in Intellij or Rancher or Windows to make it work?

","

UPDATE Feb 2022: As reported here TestContainers works nicely with Rancher Desktop 1.0.1.

+

Based on the following two closed issues - first, second - in the testcontainers-java github, Testcontainers doesn't seem to support Rancher Desktop, at least officially.

",r +"create default html opening code in Visual Studio Code

In some html editors when you create a new html file, some default codes as below created automatically:

+
<!DOCTYPE html>
+<html>
+<head>
+<title></title>
+<meta charset="utf-8"/>
+</head>
+<body>
+
+</body>
+</html>
+
+

how can I enable this feature in VSCode editor?

+

Thanks.

",

Press shift and 1 (!) It will show two options select the first one or type html:5 and enter the option it will give you default boilerplate for html

,r +"Dockerfile RUN layers vs script

Docker version 19.03.12, build 48a66213fe

+

So in a dockerfile, if I have the following lines:

+
RUN yum install aaa \
+        bbb \
+        ccc && \
+        <some cmd> && \
+        <etc> && \
+         <some cleanup> 
+
+

is that a best practice? Should I keep yum part separate than when I call other <commands/scripts>?

+

If I want a cleaner (vs traceable) Dockerfile, what if I put those lines in a .sh script can just call that script (i.e. COPY followed by a RUN statement). Will the build step run each time, even though nothing is changes inside .sh script**?** Looking for some gotchas here.

+

I'm thinking, whatever packages are stable, have a separate RUN <those packages> i.e. in one layer and lines which depend upon / change frequently i.e. may use user-defined (docker build time CLI level args) keep those in separate RUN layer (so I can use layer cache effectively).

+

Wondering if you think keeping a cleaner Dockerfile (calling RUN some.sh) would be less efficient than a traceable Dockerfile (where everything is listed in Dockerfile what makes that image).

+

Thanks.

","

In terms of the final image filesystem, you will notice no difference if you RUN the commands directly, or RUN a script, or have multiple RUN commands. The number of layers and the size of the command string doesn't really make any difference at all.

+

What can you observe?

+
    +
  • Particularly on the "classic" Docker build system, each RUN command becomes an image layer. In your example, you RUN yum install && ... && <some cleanup>; if this was split into multiple RUN commands then the un-cleaned-up content would be committed as part of the image and takes up space even though it's removed in a later layer.

    +

    "More layers" isn't necessarily bad on its own, unless you have so many layers that you hit an internal limit. The only real downside here is creating a layer with content that you're planning to delete, in which case its space will still be in the final image.

    +
  • +
  • As a more specific example of this, there's an occasional pattern where an image installs some development-only packages, runs an installation step, and uninstalls the packages. An Alpine-based example might look like

    +
    RUN apk add --virtual .build-deps \
    +      gcc make \
    + && make \
    + && make install \
    + && apk del .build-deps
    +
    +

    In this case you must run the "install" and "uninstall" in the same RUN command; otherwise Docker will create a layer that includes the build-only packages.

    +

    (A multi-stage build may be an easier way to accomplish the same goal of needing build-only tools, but not including them in the final image.)

    +
  • +
  • The actual text of the RUN command is visible in docker history and similar inspection commands.

    +
  • +
+

And...that's kind of it. If you think it's more maintainable to keep the installation steps in a separate script (maybe you have some way to use the same script in a non-Docker context) then go for it. I'd generally default to keeping the steps spelled out in RUN commands, and in general try to keep those setup steps as light-weight as possible.

",r +"Firebase emulator is stoping with error: Pub/Sub Emulator has exited with code: 1

Firebase emulator is stopping with the following error

+
!  pubsub: Fatal error occurred:
+   Pub/Sub Emulator has exited with code: 1,
+   stopping all running emulators
+
+

I don't know what is happening with emulator, even though I installed java and node correctly as said in the firebase documentation

+

Here is my firebase.json

+
{
+  "functions": {
+    "predeploy": [
+      "npm --prefix \"$RESOURCE_DIR\" run lint"
+    ],
+    "source": "functions"
+  },
+  "emulators": {
+    "auth": {
+      "port": 9099
+    },
+    "functions": {
+      "port": 5001
+    },
+    "firestore": {
+      "port": 8080
+    },
+    "pubsub": {
+      "port": 8085
+    },
+    "ui": {
+      "enabled": true
+    }
+  }
+}
+
",

I fixed by updating the JAVA_HOME variable and restarted the computer.

,r +"How to create Firestore subcollection using the new WebSDK 9?

Basically all I want to do is create a subcollection in my document, but using the webSDK 9, the tree-shakable SDK.

+

I've found solutions, but all of them are outdated and use the old sdk.

+

If this helps, I'm using NextJS and ES6.

","

You need to use the DocumentReference of the Firestore doc to which you want to add a subcollection, as follows:

+
const docRef = ....;
+const docSubcollectionRef = collection(docRef, 'theSubColl');
+await addDoc(docSubcollectionRef, {foo: 'bar'});
+
+
+

More concretely, if you have a doc in the theTempoColl collection with id doc1 (i.e. docRef = doc(db, 'theTempoColl', 'doc1')), the above code will generate a document with the following path: theTempoColl/doc1/theSubColl/{auto_generated_Id}

",r +"how to get if request got basic_ack or basic_nack in pika

For example I have a consumer and a producer.

+

In producer, I publish some data for the consumer.

+

And in consumer, I do some stuff and I can ack or reject the request.

+

How can I find out in producer.py that my request got basic_ack or basic_reject.

+

I couldn't find any methods to do some stuff on reject in producer.

+

Does anybody knows how can I do some stuff in producer on basic_ack, basic_nack or basic_reject?

","

You can't. This is not limited to Pika, but how queuing systems work. Your consumer would have to send a message back to RabbitMQ that the producer would then receive.

+
+

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

",r +"nativescript-firebase issue to get push token

I implemented the nativescript-firebase (https://github.com/EddyVerbruggen/nativescript-plugin-firebase) plugin in my mobile app. It used to work fine but since I updated to the 11.1.3 version I cannot get the push token. I tried to get back to the 10.6.3 version but it says it is not available anymore when I execute npm install.

+

Here is what I do in my main.js

+
import { messaging } from "@nativescript/firebase/messaging";
+import { firebase } from "@nativescript/firebase"
+firebase.init({
+    onMessageReceivedCallback: function(message) {
+      //do stuff
+    }
+}).then(function () {
+    messaging.getCurrentPushToken().then(token => {
+        console.log(token)
+    }).catch(e => {
+    console.log(e);
+  })
+},function (error) {
+  console.log("firebase.init error: " + error);
+});
+
+

This does not log the token but goes into the catch and logs this
+Uncomment firebase-messaging in the plugin's include.gradle first

+

Here is my package.json

+
{
+  "name": "*****",
+  "main": "./src/main.js",
+  "version": "4.4.0",
+  "description": "A native application built with NativeScript-Vue",
+  "author": "*****",
+  "license": "Propriétaire",
+  "dependencies": {
+    "@carployee/openapp": "^1.0.1",
+    "@nativescript-community/ui-material-bottomnavigationbar": "^6.2.4",
+    "@nativescript/appavailability": "^2.0.0",
+    "@nativescript/appversion": "^2.0.0",
+    "@nativescript/camera": "^5.0.10",
+    "@nativescript/core": "~8.1.5",
+    "@nativescript/datetimepicker": "^2.1.9",
+    "@nativescript/firebase": "^11.1.3",
+    "@nativescript/imagepicker": "^1.0.6",
+    "@nativescript/ios": "^8.1.0",
+    "@nativescript/iqkeyboardmanager": "^2.0.0",
+    "@nativescript/theme": "^3.0.2",
+    "@nstudio/nativescript-cardview": "^2.0.1",
+    "@nstudio/nativescript-loading-indicator": "^4.1.0",
+    "@nstudio/nativescript-pulltorefresh": "^3.0.1",
+    "@proplugins/nativescript-purchase": "git+https://gitlab.******",
+    "@vue/devtools": "^5.3.4",
+    "nativescript-dna-deviceinfo": "^3.7.3",
+    "nativescript-feedback": "^2.0.0",
+    "nativescript-google-maps-sdk": "^3.0.2",
+    "nativescript-inappbrowser": "^3.1.2",
+    "nativescript-open-app": "^0.3.0",
+    "nativescript-phone": "^3.0.2",
+    "nativescript-socketio": "^3.3.1",
+    "nativescript-toasty": "^3.0.0-alpha.2",
+    "nativescript-ui-dataform": "^8.0.1",
+    "nativescript-ui-listview": "^10.0.2",
+    "nativescript-ui-sidedrawer": "^10.0.2",
+    "nativescript-vue": "^2.9.0",
+    "nativescript-vue-devtools": "^1.5.1",
+    "nativescript-vue-fonticon": "^1.0.3",
+    "nativescript-websockets": "^2.0.0",
+    "npm-check": "^5.9.2",
+    "npm-check-updates": "^12.0.2"
+  },
+  "devDependencies": {
+    "@babel/core": "^7.16.0",
+    "@babel/preset-env": "^7.16.4",
+    "@nativescript/android": "~8.1.1",
+    "@nativescript/webpack": "~5.0.1",
+    "babel-loader": "^8.2.3",
+    "nativescript-vue-template-compiler": "^2.9.0",
+    "nativescript-worker-loader": "~0.12.1",
+    "sass": "^1.44.0",
+    "vue-loader": "^15.9.8"
+  }
+}
+
","

The message points you to the plugin's include.gradle file, or more specifically,

+
<app name>/node_modules/@nativescript/firebase/platforms/android/include.gradle
+
+

where you want to uncomment the line as shown below:

+
// Cloud Messaging (FCM)
+ implementation "com.google.firebase:firebase-messaging:20.1.0"
+//  implementation "me.leolin:ShortcutBadger:1.1.22@aar"
+
+

I expect if you reinstall the plugin you can answer the prompts so that this will get set for you.

",r +"Azure API Management, single API accept AAD or subscription key

Is it possible to have a single API in APIM that either accepts AAD token or subscription, based on what product it belongs to?

+

Default, this does not work, since unchecking "require subscription" on API-level will override setting product to require subscription.

+

So, I see two solutions.. create two APIs in APIM and place them in separate products (same backend), or write a custom policy. Is there a way to check context.Subscription.Key and match with the product subscriptions?

","

Should be possible by adding your API to two products:

+
    +
  • One with subscription requirement enabled
  • +
  • Another without subscription requirement enabled, but with validate-jwt policy added at product level to require AAD token
  • +
",r +"React Router 6 unmount component on route change

I use the same component on different react router routes. Does anyone know how to unmount component on route change? Now when I change the route, component doesn't unmount, here is my example: https://codesandbox.io/s/stupefied-cloud-bxfyf?file=/src/MyComponent.js

","

We can pass key to the componenet to uniquely identify the Component

+
const routes = [
+  {
+    path: "/",
+    element: <MyComponent key={1} />
+  },
+  {
+    path: "two",
+    element: <MyComponent key={2} />
+  }
+];
+
",r +"What is the more common way to build up a robot control structure?

I’m a college student and I’m trying to build an underwater robot with my team.

+

We plan to use stm32 and RPi. We will put our controller on stm32 and high-level algorithm (like path planning, object detection…) on Rpi. The reason we design it this way is that the controller needs to be calculated fast and high-level algorithms need more overhead.

+

But later I found out there is tons of package on ROS that support IMU and other attitude sensors. Therefore, I assume many people might build their controller on a board that can run ROS such as RPi.

+

As far as I know, RPi is slower than stm32 and has less port to connect to sensor and motor which makes me think that Rpi is not a desired place to run a controller.

+

So I’m wondering if I design it all wrong?

","

Robot application could vary so much, the suitable structure shall be very much according to use case, so it is difficult to have a standard answer, I just share my thoughts for your reference.

+

In general, I think Linux SBC(e.g. RPi) + MCU Controller(e.g. stm32/esp32) is a good solution for many use cases. I personally use RPi + ESP32 for a few robot designs, the reason is,

+
    +
  1. Linux is not a good realtime OS, MCU is good at handling time critical tasks, like motor control, IMU filtering;
  2. +
  3. Some protection mechnism need to be reliable even when central "brain" hang or whole system running into low voltage;
  4. +
  5. MCU is cheaper, smaller and flexible to distribute to any parts inside robot, it also helps our modularized design thinking;
  6. +
  7. Many new MCU is actually powerful enough to handle sophisticated tasks and could offload a lot from the central CPU;
  8. +
",r +"Brew formulae install options

I'm trying to write formulae for Brew that would allow the user to opt-in/opt-out of certain functionality of the tool that is being installed. I can't find any documentation whether that is possible.

+

More specifically I would like to give the developer option to opt-out of crash reports and then formulae could decide which source to use or something like that.

","

Formula Cookbook ¶ Adding optional steps might be helpful for you:

+
+

If you want to add an option:

+
class Yourformula < Formula
+  ...
+  option "with-ham", "Description of the option"
+  option "without-spam", "Another description"
+
+  depends_on "foo" => :optional  # will automatically add a with-foo option
+  ...
+
+

And then to define the effects the options have:

+
if build.with? "ham"
+  # note, no "with" in the option name (it is added by the build.with? method)
+end
+
+if build.without? "ham"
+  # works as you'd expect. True if `--without-ham` was given.
+end
+
+
",r +"Show request duration in drf-spectacular (Swagger)

I have a Django/DRF project with drf-spectacular (Swagger) integration and wondering how can I add a request duration as shown on the image below. Is there any way to achive elapsed time section? Thanks in advance.

+

","

That is a Swagger-UI feature independent of drf-spectacular. To pass it through simply set the setting like so:

+

+SPECTACULAR_SETTINGS = {
+    "SWAGGER_UI_SETTINGS": {
+        "displayRequestDuration": True,
+        # other swagger settings
+    },
+    # other spectcular settings
+}
+
+

other swagger settings can be found here

",r +"Wald confidence interval in gtsummary

Is there a way to specify the method of calculating confidence interval in gtsummary. Am asking this because of some inconsistencies with profile confidence intervals by confint fuction. +Have a look at the pvalues and CIs of var1 and var2 below:

+
library(tidyverse)
+library(gtsummary)
+
+set.seed(2021)
+
+testdata <- tibble(
+  var1 = rbinom(1114, 1, 0.12),
+  var2 = rbinom(1114, 1, 0.82),
+  var3 = rbinom(1114, 1, 0.60),
+  var4 = rbinom(1114, 1, 0.18),
+  var5 = rbinom(1114, 1, 0.12),
+  var6 = rbinom(1114, 1, 0.05),
+  var7 = rbinom(1114, 1, 0.63),
+  var8 = rbinom(1114, 1, 0.20),
+  var9 = rbinom(1114, 1, 0.06),
+  var10 = rbinom(1114, 1, 0.40),
+  var11 = rbinom(1114, 1, 0.35),
+  var12 = rbinom(1114, 1, 0.32),
+  outcome = rbinom(1114, 1, 0.04)
+) %>%
+  mutate(across(.cols = everything(),
+                ~factor(., levels = c(0, 1),
+                        labels = c("No", "Yes"))))
+
+
+
+mvariate.regress <- function(outcome, covariates, mydata) {
+  form <- paste(outcome, "~",
+                paste(covariates, collapse = " + "))
+
+  model1 <- glm(as.formula(form),
+                data = mydata, family = binomial)
+
+  model1
+
+}
+
+
+ipvars <- paste0("var", 1:12)
+
+mlogitfit <- mvariate.regress("outcome", ipvars, testdata)
+
+
+mlogitfit %>%
+  tbl_regression(
+    exponentiate = TRUE
+  ) %>%
+  bold_p() %>%
+  bold_p(t = 0.05) %>%
+  bold_labels() %>%
+  modify_header(label = "**Variable**",
+                estimate = "**adjusted OR**") %>%
+  modify_table_styling(
+    columns = c("ci", "estimate"),
+    rows = reference_row %in% TRUE,
+    missing_symbol = "Ref"
+  )
+
+

I would get the desired results if I were to use confint.default function

","

The gtstummary package website has a solution to this. Look for "Wald confidence interval" here or see below for the my_tidy function from there. You can calculate the Wald confidence interval separately and bind it to the table.

+
my_tidy <- function(x, exponentiate =  TRUE, conf.level = 0.95, ...) {
+  dplyr::bind_cols(
+    broom::tidy(x, exponentiate = exponentiate, conf.int = FALSE),
+    # calculate the confidence intervals, and save them in a tibble
+    stats::confint.default(x) %>%
+      tibble::as_tibble() %>%
+      rlang::set_names(c("conf.low", "conf.high"))  )
+}
+
+mlogitfit %>%
+  tbl_regression(tidy_fun = my_tidy) %>%
+  bold_p() %>%
+  bold_p(t = 0.05) %>%
+  bold_labels() %>%
+  modify_header(label = "**Variable**",
+                estimate = "**adjusted OR**") %>%
+  modify_table_styling(
+    columns = c("ci", "estimate"),
+    rows = reference_row %in% TRUE,
+    missing_symbol = "Ref"
+  )
+
",r +"How to add a custom RSA key pair to a .pem file

I created a custom RSA key pair just for test purposes in python. I want to add the private key and public key to a .pem file but I didnt find anything in my research. All i found is people generating a RSA key pair from a library. +I have the e, d and n variables for the public key[e, n] and private key[d, n].

","

Most major crypto libraries support this, e.g. PyCryptodome (via construct() and exportKey()) or Cryptography (as described in the Numbers and Key Serialization sections), e.g.

+

PyCryptodome:

+
from Crypto.PublicKey import RSA
+
+n = int("b83b...529b", 16);
+d = int("4eea...a721", 16);
+e = int("010001", 16);
+
+privateKey = RSA.construct((n, e, d))
+privateKeyPem = privateKey.exportKey(pkcs=8) # export in PKCS#8 format
+
+publicKey = RSA.construct((n, e))
+publicKeyPem = publicKey.exportKey() # export in X.509/SPKI format
+
+print(privateKeyPem.decode('utf8'))
+print(publicKeyPem.decode('utf8'))
+
+

or Cryptography:

+
from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.hazmat.primitives import serialization
+
+n = int("b83b...529b", 16);
+d = int("4eea...a721", 16);
+e = int("010001", 16);
+
+(q, p) = rsa.rsa_recover_prime_factors(n, e, d)
+dmq1 = rsa.rsa_crt_dmq1(d, q)
+dmp1 = rsa.rsa_crt_dmp1(d, p)
+iqmp = rsa.rsa_crt_iqmp(p, q)
+
+publicNumbers = rsa.RSAPublicNumbers(e, n)
+privateNumbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, publicNumbers)
+
+privateKey = privateNumbers.private_key();
+publicKey = publicNumbers.public_key();
+
+privateKeyPem = privateKey.private_bytes(
+   encoding=serialization.Encoding.PEM,
+   format=serialization.PrivateFormat.PKCS8,
+   encryption_algorithm=serialization.NoEncryption()
+)
+
+publicKeyPem = publicKey.public_bytes(
+   encoding=serialization.Encoding.PEM,
+   format=serialization.PublicFormat.SubjectPublicKeyInfo
+)
+
+print(privateKeyPem.decode('utf8'))
+print(publicKeyPem.decode('utf8'))
+
+

Note that the raw key is symmetric in p and q, so swapping p and q changes the PEM or DER encoded key, but not the raw key (n, e, d).

",r +"React custom input passing props to parent functional component while using custom hooks

Am new to react and i have a custom input where am handling the value and input handler via a custom hook but would like to get the value and the input handler to the parent component using the custom input but am stuck on how to achieve this. +I have written the following code.

+

On the custom hook

+
import {useReducer} from "react";
+
+const INITAL_STATE  = {value:'',valid:false,pristine:true,  error:''}
+const REDUCER_ACTIONS = { input:"INPUT", blur:"BLUR"}
+
+const reducer = (state,action)=>{
+ 
+  if (action.type === REDUCER_ACTIONS.input){
+    return {...state, value: action.value}
+  }
+  
+  if (action.type === REDUCER_ACTIONS.blur){
+     return {...state, pristine: false}
+   }
+ 
+  return INITAL_STATE;
+ }
+
+const useForm = () => {
+   const [inputState, dispatch] = useReducer(reducer,INITAL_STATE)
+
+   const onBlurHandler = (event) => {
+     dispatch({type:REDUCER_ACTIONS.blur});
+   }
+
+ const onInputHandler = (event) => {
+     dispatch({type:REDUCER_ACTIONS.input,value:event.target.value})
+ }
+
+return {
+    ...inputState,
+    onBlurHandler,
+    onInputHandler
+ }
+};
+export default useForm;
+
+

And for my custom input i have

+
import useForm from "../../hooks/use-form";
+const CustomInput = (props) => {
+   const {value, onInputHandler, onBlurHandler} = useForm(); //uses custom hook
+
+    return  <>
+         <label htmlFor={props.id}>{props.label}</label>
+         <input value={value} onBlur={onBlurHandler} onInput={onInputHandler} 
+   {...props} />
+        </>
+}
+export default CustomInput;
+
+

The above custom input has the onInput and onBlur pointing to the custom hooks since i want to reuse the functionality on other input types like select and date pickers without having to duplicate them.

+

On my parent component am simply calling the Custom input like

+
 function App() {
+
+    
+    
+    return (
+      <div className="container">
+          <CustomInput onInputHandler={} label="First name"/>
+      </div>
+   );
+  }
+
+export default App;
+
+

I would like to pass the onInputHandler and value as a props back to the parent component from the custom input but am stuck on how to do this. How do i proceed?

","

When you say you need to pass value, I guess you wanted to pass the initial value of the input to CustomInput. To achieve that you can pass another prop.

+
    +
  1. App.js pass initialValue to CustomInput
  2. +
+
<CustomInput
+    initialValue={"abc"}
+    label="First name"
+/>
+
+
    +
  1. In CustomInput pass initialValue prop to useForm hook as an argument.
  2. +
+
const { value, onInputHandler, onBlurHandler } = useForm(props.initialValue); 
+
+
    +
  1. Set the initialValue as the value in initial state in useForm.
  2. +
+
const useForm = (initialValue) => {
+  const [inputState, dispatch] = useReducer(reducer, {
+    ...INITAL_STATE,
+    value: initialValue
+  });
+  ...
+  ...
+}
+
+

To pass the onInputHandler as a prop you can check if onInputHandler is available as a prop and call it along with onInputHandler coming from useForm.

+
    +
  1. In App.js defines another function that accepts event as an argument.
  2. +
+
export default function App() {
+  const onInputHandler = (e) => {
+    console.log(e);
+  };
+
+  return (
+    <div className="App">
+      <CustomInput
+        ...
+        onInputHandler={onInputHandler}
+        label="First name"
+      />
+    </div>
+  );
+}
+
+
    +
  1. In CustomInput change the onInput handler like below. You can change the logic as per your needs (I called onInputHandler in useForm and prop).
  2. +
+
      <input
+        value={value}
+        onBlur={onBlurHandler}
+        onInput={(e) => {
+          props.onInputHandler && props.onInputHandler(e);
+          onInputHandler(e);
+        }}
+        {...props}
+      />
+
+

",r +"Noticeable delay when changing an image dynamically in Flutter

I am new to Flutter and experienced a problem while trying to make a mobile application. +When switching the image being displayed there is a noticeable delay, where nothing is shown, between the action and the new image appearing.
+Adding gaplessPlayback: true to the Image widget does prevent the original image disappearing until the other is loaded but the delay remains.
+I tried to precache both images but noticed no difference in load time. Is this delay to be expected or am I doing something wrong?

+

Issue without gaplessPlayback

+
class Wallpaper extends StatefulWidget {
+  @override
+  StateWallpaper createState() => StateWallpaper();
+}
+
+class StateWallpaper extends State<Wallpaper> {
+  late AssetImage walPath;
+  late AssetImage wal1;
+  late AssetImage wal2;
+
+  @override
+  void initState() {
+    wal1 = AssetImage('assets/wal_dark.jpg');
+    wal2 = AssetImage('assets/wal_light.jpg');
+    walPath = wal1; //Set default wallpaper
+    super.initState();
+  }
+
+  @override
+  void didChangeDependencies() {
+    precacheImage(wal1, context);
+    precacheImage(wal2, context);
+    super.didChangeDependencies();
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Column(children: [
+      FloatingActionButton(onPressed: () {
+        setState(() {
+          if (walPath == wal2) {
+            walPath = wal1;
+          } else {
+            walPath = wal2;
+          }
+        });
+      }),
+      Image(image: walPath, gaplessPlayback: true)
+    ]);
+  }
+}
+
","

How big are your images (width/height in pixels, and file size)? +Perhaps they are too large, and they are being resized before being displayed? +Try with images that are close to the pixel width/height of the device and see if it is faster... +Also, is it a release build?

",r +"Can Simple Realtime Server output a VOD of the user's video?

I'm currently learning how to use SRS and I believe it will mostly fit my needs. However, I need to be able to create a VOD (video on demand) of the user's live video. How would I accomplish this?

+

Thanks! +AJ

","

SRS is a realtime server, design for life streaming and WebRTC. While VoD(Video on Demand) is delivered by file-based web server, like Nginx or ATS, because Vod is actually files, whatever HLS, MP4 or DASH.

+

Very glad SRS fits your need, and you really need a set of tools to build your video platform, which normally should support live streaming, video conference and VoD.

+

Apart from Vod, the HLS for live streaming, should also be delivered by file based servers, because HLS is also file based protocol, see NGINX HLS Cluster, although it's generated by SRS or FFmpeg.

+

Let's see the stream flow:

+
Encoder -RTMP-> SRS -+-> RTMP/HTTP-FLV --------> Live Player(flv.js/fijkplayer)
+FFmpeg/OBS           |
+                     |
+                     |
+                     +--RTMP-> FFmpeg -> HLS/MP4 --+
+                     |                             |  (file-based)  (Live/Vod)
+                     +-->HLS/FLV/MP4---->----------+-> web servers --> Player
+
+

Please keep in mind that:

+
    +
  • SRS is designed for streaming, like RTMP/HTTP-FLV/WebRTC/SRT etc.
  • +
  • Although SRS could covert RTMP to HLS/FLV/MP4, but FFmpeg also could do this, and please use file-based web server like Nginx or ATS to deliver the files of HLS/DASH, see NGINX HLS Cluster.
  • +
  • VoD should directly use file-based web server to deliver, it's simple, see NGINX HLS Cluster. Please never use SRS to do this.
  • +
+

Any further discussion please contact us by discord.

",r +"Show separate number with comma in django tempalte

I have an issue that when the user is typing on text field the number is not separated by a comma

+

user is typing 500000, it shows 500000 not 500,000

+

in models

+
so_tien=models.PositiveIntegerField(max_length=50)
+
+

in forms

+
so_tien=forms.IntegerField(label="Số tiền",widget=forms.NumberInput(attrs={"class":"form-control",'onfocusout': 'numberWithCommas()',}),required=False)
+
+

template file

+
<div class="col-md-4" id="sotien" style="display:none">{{ form.so_tien}}</div>
+
+

javascript code numberWithCommas in the template file:

+
 <script language="JavaScript">
+function numberWithCommas(){
+  var input = document.getElementById('{{ form.so_tien.id_for_label}}');
+  input.value = parseInt(input.value).toLocaleString()
+
+

} +

+

Thanks for your reading

","

You're not changing value of your input you're just displaying it try assign new value to value attribute like this

+

Working example

+
+
+
function numberWithCommas(){
+  var input = document.getElementById('input');
+  input.value = parseInt(input.value).toLocaleString()
+}
+
<input type=""text"" id=""input"" onfocusout=""numberWithCommas()"">
+
+
+ +

for django you can do somthing like this
+in forms.py

+
so_tien=forms.CharField(label="Số tiền",widget=forms.TextInput(attrs={"class":"form-control", 'onfocusout': 'numberWithCommas()',}),required=False)
+
+

inside your templates

+
function numberWithCommas(){
+      var input = document.getElementById('{{ form.so_tien.id_for_label}}');
+      input.value = parseInt(input.value).toLocaleString()
+}
+
",r +"How do I make a reusable component for the Cards and how can I use the new makeStyles of material-ui?

In the demo.js, I wanted to use the Card along with its CardHeader and put wordings inside the CardContent. Also, I will be using the CardComponent in other files as well. How can I make the CardComponent reusable?

+

Sample codes: https://codesandbox.io/s/basiccard-material-demo-forked-kkshx?file=/demo.js

+

Below are the codes for the demo.js:

+
import * as React from "react";
+
+import CardComponent from "./CardComponent";
+
+export default function BasicCard() {
+  return (
+    <>
+      <h1>Hello</h1>
+      <CardComponent />
+    </>
+  );
+}
+
+

Below are the codes for the CardComponent:

+
import React from "react";
+
+import Card from "@mui/material/Card";
+import CardContent from "@mui/material/CardContent";
+import { CardHeader } from "@mui/material";
+
+const CardComponent = () => {
+  const CardStyle = {
+    maxWidth: 500,
+    margin: "0 auto",
+    marginBottom: "1rem",
+    marginTop: "1rem"
+  };
+  return (
+    <Card sx={{ minWidth: 275 }} elevation={5} style={CardStyle}>
+      <CardHeader title="Card Header Title here" />
+      <CardContent>//content here</CardContent>
+    </Card>
+  );
+};
+
+export default CardComponent;
+
+

I have another question as well under this component. Coming from material-ui4, mui5 was kind of confusing as I can no longer use the makeStyles. I tried adding this in the codesandbx example, however, it will say that dependency not found:

+
import { makeStyles } from '@mui/styles';
+
+

Hence, I settled with const CardStyle. Any help on how can I implement the newer version of the makeStyles? Also, do I need to install other dependecies from material-ui to make it work? Below is the package.json file.

+

+

Also in: https://www.reddit.com/r/reactjs/comments/sgqhh3/how_do_i_make_a_reusable_component_for_the_cards/

","

You can make it reusable adding props to your child card component. You can add as many props you want to make different cards using the same pattern.

+

To give styles to the component in mui v5 you have to use styled. You have to import it from @mui/material/styles

+

Here is the whole code of the new card component

+
import React from "react";
+import {styled} from "@mui/material/styles"
+import Card from "@mui/material/Card";
+import CardContent from "@mui/material/CardContent";
+import { CardHeader } from "@mui/material";
+
+const StyledCard = styled((props) => (
+  <Card
+      {...props}
+  />
+))(({ theme }) => ({
+  maxWidth: 500,
+    margin: "0 auto",
+    marginBottom: "1rem",
+    marginTop: "1rem"
+}));
+
+
+const CardComponent = (props) => {
+  const {title,content}=props
+
+  return (
+    <StyledCard sx={{ minWidth: 275 }} elevation={5}>
+      <CardHeader title={title} />
+      <CardContent>{content}</CardContent>
+    </StyledCard>
+  );
+};
+
+export default CardComponent;
+
+

And here it is the whole codesandbox.

+

",r +"How to include OpenGapps in AOSP 12 build?

I am building AOSP 12 for my Pixel 3a sargo. It worked but I wanted to install Gapps on it. When I tried to flash any Gapps zip in TWRP, it said that my system partition was read-only or full, so I tried remounting it with the read and write permissions. But it showed the same thing. After that, I saw that my system partition was full. So I was wondering, how I can include Gapps while building AOSP? But since OpenGapps is not available for Android 12 (I tried but the build failed), I don't know how to include Gapps in my build.

+

Can someone help me, please?

","

I finally found how to do this:

+

First add this to your repo manifest:

+
<remote name="MindTheGapps" fetch="https://gitlab.com/MindTheGapps/" />
+<project path="vendor/gapps" name="vendor_gapps" remote="MindTheGapps" revision="sigma" />
+
+

Then repo sync. +After, add this lines to your device.mk:

+
include vendor/gapps/arm64/arm64-vendor.mk
+
+

And build.

+

If you have an error with ELF files, add this line to your boardconfig.mk:

+
BUILD_BROKEN_ELF_PREBUILT_PRODUCT_COPY_FILES := true
+
+

and this should work.

",r +"Android react-native-video doesn't playback in m3u8 video
    +
  1. My problem is I can't playback m3u8 fragmented video through react-native-video. But another test m3u8 from different resources does work. I have thought my transcoded CMAF m3u8 is corrupted and by that reason doesn't work but it work on ios through react-native-video and i have tried to test it through demo.theoplayer and it works right.

    +
  2. +
  3. I do transcode from mp4 to CMAF m3u8 through AWS MediaConvert create job template and configure some settings.

    +
  4. +
  5. My code is quite simple:

    +
  6. +
+

+
+
<Video
+   style={{ flex: 1, backgroundColor: 'black' }}
+   source={{uri: 'https://d7m8ah93fnh1v.cloudfront.net/media/ROOM/03bc46a8-eb9f-4f94-950e-55da3c9b4a77/567e932f-d964-43c5-8866-247a9e777d35/567e932f-d964-43c5-8866-247a9e777d35.m3u8'}} 
+/>
+
+
+

","

Our suggestion is to determine if this is a stream formatting issue or a player side issue. To do this we suggest validating the stream with Apple's 'stream validator' tool, part of the 'HLS tools' package available from the Apple website. We also recommend checking the playback of the stream in other players such as JWplayer, Shaka player, etc. FYI I tried your source URL in the bitmovin test player and hls.js, and it plays fine for me in both.

+

If the playback issue is specific to react-native video player (which seems likely) then there are two paths to pursue: [a] open a bug with react team; and [b] check recommended settings for react player, then experiment with modifying your encoding settings to produce a stream react player will handle without issue.

",r +"spark sql Insert string column to struct of array type column

I am trying to insert a STRING type column to an ARRAY of STRUCT TYPE column, but facing errors. Could you help to provide the right direction to do the INSERT.

+

In databricks notebook, I have a raw table (raw_lms.rawTable) where all the columns are string type. This needs to insert into a transform table (tl_lms.transformedTable) where the columns are array of struct type.

+
CREATE TABLE raw_lms.rawTable
+ (  PrimaryOwners STRING
+  ,Owners STRING
+ )
+ USING DELTA LOCATION 'xxxx/rawTable'
+
+
CREATE TABLE tl_lms.transformedTable
+ (  PrimaryOwners array<struct<Id:STRING>>
+  ,Owners array<struct<Id:STRING>>
+ )
+ USING DELTA LOCATION 'xxxx/transformedTable'
+
+

Raw table has the below values populated: Eg.

+
INSERT INTO TABLE raw_lms.rawTable
+VALUES
+("[{'Id': '1393fe1b-bba2-4343-dff0-08d9dea59a03'}, {'Id': 'cf2e6549-5d07-458c-9d30-08d9dd5885cf'}]",
+ "[]"
+)
+
+

+

I try to insert to transform table and get the below error:

+
INSERT INTO tl_lms.transformedTable 
+SELECT PrimaryOwners,
+       Owners
+FROM raw_lms.rawTable
+
+
+

Error in SQL statement: AnalysisException: cannot resolve +'spark_catalog.raw_lms.rawTable.PrimaryOwners' due to data type +mismatch: cannot cast string to array<struct<Id:string>>;

+
+

I do not want to explode the data. I only need to simply insert row for a row between rawTable and transformedTable of different column data types.

+

Thanks for your time and help.

","

As the error messages states, you can't insert a string as array. You need to use array and named_struct functions.

+

Change the type of raw table to correct type and types not strings and try this:

+
INSERT INTO TABLE raw_lms.rawTable
+VALUES
+(array(named_struct('id', '1393fe1b-bba2-4343-dff0-08d9dea59a03'), named_struct('id', 'cf2e6549-5d07-458c-9d30-08d9dd5885cf')), 
+ null
+);
+
+

Or if you want to keep columns as string in raw table, then use from_json to parse the strings into correct type before inserting:

+
INSERT INTO tl_lms.transformedTable 
+SELECT from_json(PrimaryOwners, 'array<struct<Id:STRING>>'),
+       from_json(Owners, 'array<struct<Id:STRING>>')
+FROM raw_lms.rawTable
+
",r +"Formula using sumifs and indirect function for worksheets. Getting Reference error although Had it working with different columns

Using excel 365. I have used this same formula for "asset allocations" and it worked perfectly. +I decided to do the same for sector allocation and I can not figure out what is wrong. This has beat me down. I have tried for 2 days. I thought that I could just exchange the category for sector. Didn't work. Thank you for any help.

+

Here is the image which shows the sheet that I am using. +The formula in G6 is:

+

=SUMPRODUCT(SUMIFS(INDIRECT(K$6:K$11&"[Value]"),INDIRECT(K$6:K$11&"[Sectors]"),[@Sector])) +You can see a REF Error on the column "Value".

+

+

This image is to show where the "Sectors" are listed on the individual sheets that I wish to sum.

+

","

Unusual, but this is working fine in my test scenario.

+

Use the Evaluate Formula tool to see where the error creeps in. You may have a typo in the list of tables.

+

",r +"Collapse rows of a dataframe with common values and fill in blanks

I have a single data frame and every row is duplicated except for two values. In all cases the corresponding duplicate has a blank value in the corresponding row. I want to 'collapse' these rows and fill in the blanks.

+

In the example below, I want to collapse the top DataFrame to mirror the bottom

+

","

You can use groupby + first; first skips over NaN values by default:

+
collapsed_df = df.groupby("feature_id").first().reset_index()
+
+

If the empty spaces are not NaN values, probably will want to fill them with NaN first:

+
df = df.replace('', np.nan)
+
",r +"smooth animation of the size of a functional component during state change

As you can see, by clicking on the component underneath, we can change its size. I would like to make a transition between those sizes. Is it possible with CSSTransition ?

+
export const Liste_planete2 = () => {
+    const [height, setHeight] = useState<number>(30)
+
+    const handleClick=()=>{
+            setHeight(height+30)
+    }
+    return(
+        <div style={{height:height}} onClick={handleClick}>
+            Text
+        </div>
+    )
+}
+
","

Try it:

+
export const Liste_planete2 = () => {
+    const [height, setHeight] = useState<number>(30)
+
+    const handleClick=()=>{
+            setHeight(height+30)
+    }
+    return(
+        <div style={{height:height, transition: "all 0.5s"}} onClick={handleClick}>
+            Text
+        </div>
+    )
+}
+
",r +"Can I use hotwired turbo.js offline?

I'm trying to use turbo-flask in my python flask application. It tries to download turbo.js but failes because I'm not working with an internet connection. +I thought about inserting the js file directly into my project but couldnt find it anywhere. +Is it possible to use it offline?

","

Short answer: YES.

+

You can install Turbo as instructed in Turbo Handbook
+But that's without turbo-flask package, which uses CDN version as default.
+But it seems like you can do (for example) this:

+
{{ turbo(url=url_for('static', filename='js/turbo.js')) }}
+
+

and then your app uses this downloaded js. +That's if you just download current version of turbo js by hand. +If you are using other ways (such as npm), then your file will be somewhere else and you need to edit code accordingly.

",r +"How to get ""content_type"" using Get File Properties REST API for Azure Files Storage using Python

I'm trying to get the "content_type" property for files in Azure fileshare. I can get "last_modified" and "size" but not "content_type"

+
from azure.storage.file import *
+from azure.storage.fileshare import *
+
+def azure_connect_conn_string(source_file_connection_string, source_share_name):
+    try:
+        share_service = ShareServiceClient.from_connection_string(source_file_connection_string)#ShareServiceClient interact with the account level
+        share_client = share_service.get_share_client(source_share_name) #desired share name is accessed
+        file_service = FileService(connection_string=source_file_connection_string)
+        print("Connection String -- Connected.")
+        return share_client, file_service #returns the share client
+
+    except Exception as ex:
+        print("Error: " + str(ex))
+
+def fileshare_content_list(connection_instance, directory_name, file_service, share_name):
+    d_client = connection_instance.get_directory_client(directory_name)
+    my_files = d_client.list_directories_and_files()
+    directory_list = []
+
+    for file in my_files:
+        if file.get('is_directory'):
+            #cannot get size of directory, only of files
+            file_name = file.get('name')
+            file_lastmod = file.get('last_modified')
+            file_type = 'directory'
+            file_size = 'unknown'
+
+        else:
+            file_name = file.get('name')
+            file_props = file_service.get_file_properties(share_name, directory_name, file_name)
+            file_lastmod = file_props.properties.last_modified
+            file_size = file.get('size')
+            print(file_name)
+            print(file_lastmod)
+            print(file_size)
+            print(file_props.properties.content_type)
+
+def main():
+    try:
+        azure_connection_string = 'DefaultEndpointsProtocol=https;AccountName=ecpcdmsdatamartexternal;AccountKey=neNa1jtdyVljMN/j403/rHwdYBpPUtKTreeYM4UsKiosiOfKdePgyZdJl8SK9UdAlsXwVvOkNdNWZjnOCyn/lw==;EndpointSuffix=core.windows.net'
+        share_name = "ecdmpext"
+        directory_name = "data"
+        connection_instance, file_service = azure_connect_conn_string(azure_connection_string, share_name)
+
+        ## List files
+        fileshare_content_list(connection_instance, directory_name, file_service, share_name)
+        print('Done')
+    
+    except Exception as ex:
+        print('main | Error: ', ex)
+
+if __name__ == "__main__":
+    main()
+
+
+

I get error 'FileProperties' object has no attribute 'content_type'

+

When I try using file.get("content_type") I just get "None". +I use file.get() for "size" and "name", for "last_modified" I have to use file_service.get_file_properties.properties.last_modified but neither method works for "content_type".

","

You were almost there :). The content_type property is actually a sub property of content_settings property in File's property returned by get_file_properties.

+

So your code would be something like:

+
file_content_type = file_props.properties.content_settings.content_type
+
",r +"Creating a new column based on TRUE/FALSE of several columns in R

I am new in R and this is my first post. Please help me out.

+

I have a dataset that has 10 columns that look like this:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RedBlueGreen
TrueFalseFalse
TrueFalseFalse
FalseTrueFalse
FalseFalseTrue
+
+

I want one column that should look like:

+
+ + + + + + + + + + + + + + + + + + + + +
Color
Red
Red
Blue
Green
+
+

The 'True' should be read into that color. Only one 'True' across columns in a given row.

+

I tried: df <- df %>% add_column(color=ifelse(.$col_name == TRUE,colnames(df)[1],"")

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RedBlueGreencol_1col_2col_3
TrueFalseFalseRed
TrueFalseFalseRed
FalseTrueFalseBlue
FalseFalseTrueGreen
+
+

Thus creating 10 extra columns with a hope to merge them later. But I am stuck. Can anyone please help?

+

Thank you!

","

Here are tidyverse approaches.

+
df = tibble(Red = c(T,T,F,F), Blue = c(F,F,T,F), Green = c(F,F,F,T))
+
+

Approach 1: case_when, a vectorised multiple if - else.

+
df %>%
+  mutate(color = case_when(Red ~ "Red",
+                           Blue ~ "Blue",
+                           Green ~ "Green"))
+
+

Swap mutate with transmute to only return the new color column.
+Approach 2: Use column name properties.

+
df %>%
+  pivot_longer(everything(), names_to = "color") %>%
+  filter(value) %>%
+  select(color)
+
+

Approach 3: subset column names

+
df %>%
+  mutate(color = names(.)[apply(., 1, which)])
+
",r +"Overflow-y: scroll; on side navigation prevents tooltip functionality

I have a side navigation with the following styles

+
position: fixed;
+left: 0;
+top: 0;
+height: 100%;
+width: 78px;
+background: #11101D;
+padding: 6px 14px;
+z-index: 99;
+transition: all 0.5s ease;
+overflow-x: visible;
+overflow-y: scroll;
+
+

Which allows the user to scroll vertically on the side navigation.

+

When a user hovers on a navigation item, a tooltip appears to the right.

+
position: absolute;
+top: -20px;
+left: calc(100% + 15px);
+z-index: 3;
+background: #fff;
+box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
+padding: 6px 12px;
+border-radius: 4px;
+font-size: 15px;
+font-weight: 400;
+opacity: 0;
+white-space: nowrap;
+pointer-events: none;
+transition: 0s;
+
+

However, because of the overflow-y: scroll; on the parent, it doesn't overlap the sidebar, instead you scroll horizontally to see it, which isn't desired.

+

Current Tooltip

+

+

+

Desired Tooltip (with side nav scroll functionality)

+

+

I have a JSFiddle with all the markup and styles.

+

I want the the side nav to be vertically scrollable while still having the functionality to view the tooltip.

+

Any help would be greatly appreciated. This is based on a React Application, so would prefer non JQuery solutions.

","

Apparently, you can't, it's "written in the specs"

+

Source: CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

+

Source of the source: overflow-x: visible; doesn't work with overflow-y: auto; any workaround?

+

But you can wrap the menu in a container to split the overflows, the parent with overflow-x: auto and the child with overflow-y: scroll

",r +"How can I correctly use custom PagingSource with PagingDataAdapter, on local data?

The Problem

+

I have locally-generated data that I need to display in a RecyclerView. I tried to use a custom PagingSource with PagingDataAdapter to reduce the amount of data in memory, but I get visual effects when I invalidate the data, for example if I insert or delete one item:

+
    +
  • when the visible items belong to 2 different "pages", many unchanged items flash as if they had been modified
  • +
  • if all the visible items belong to the same page, everything is fine. Only the inserted / deleted item shows an animation.
  • +
+

I took an example application referenced by Google's doc (PagingSample) to test the concept. The original with Room does not show artefacts, but my modified version with custom PagingSource does.

+

The code generated and used by Room is too complicated to see any difference that would explain the issue.

+

My data must be locally-generated, I can't use Room as a work-around to display them.

+

My question

+

How can I properly define a PagingSource for my local data, and use it with PagingDataAdapter without visual glitches?

+

Optionally, how can I know when data is discarded (so I can discard my local data as well)?

+

Code excerpts and details

+

The full example project is hosted here: https://github.com/blueglyph/PagingSampleModified

+

Here is the data:

+
    private val _data = ArrayMap<Int, Cheese>()
+    val data = MutableLiveData <Map<Int, Cheese>>(_data)
+    val sortedData = data.map { data -> data.values.sortedBy { it.name.lowercase() } }
+
+

and the PagingSource. I'm using key = item position. I have tried with key = page number, each page containing 30 items (10 are visible), but it does not change anything.

+
    private class CheeseDataSource(val dao: CheeseDaoLocal, val pageSize: Int): PagingSource<Int, Cheese>() {
+        fun max(a: Int, b: Int): Int = if (a > b) a else b
+
+        override fun getRefreshKey(state: PagingState<Int, Cheese>): Int? {
+            val lastPos = dao.count() - 1
+            val key = state.anchorPosition?.let { anchorPosition ->
+                val anchorPage = state.closestPageToPosition(anchorPosition)
+                anchorPage?.prevKey?.plus(pageSize)?.coerceAtMost(lastPos) ?: anchorPage?.nextKey?.minus(pageSize)?.coerceAtLeast(0)
+            }
+            return key
+        }
+
+        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Cheese> {
+            val pageNumber = params.key ?: 0
+            val count = dao.count()
+            val data = dao.allCheesesOrdName().drop(pageNumber).take(pageSize)
+            return LoadResult.Page(
+                data = data,
+                prevKey = if (pageNumber > 0) max(0, pageNumber - pageSize) else null,
+                nextKey = if (pageNumber + pageSize < count) pageNumber + pageSize else null
+            )
+        }
+    }
+
+

The Flow on PagingData is created in the view model:

+
    val pageSize = 30
+    var dataSource: PagingSource<Int, Cheese>? = null
+    val allCheeses: Flow<PagingData<CheeseListItem>> = Pager(
+        config = PagingConfig(
+            pageSize = pageSize,
+            enablePlaceholders = false,
+            maxSize = 90
+        )
+    ) {
+        dataSource = dao.getDataSource(pageSize)
+        dataSource!!
+    }.flow
+        .map { pagingData -> pagingData.map { cheese -> CheeseListItem.Item(cheese) } }
+
+

with dao.getDataSource(pageSize) returning the CheeseDataSource shown above.

+

and in the activity, data pages are collected and submitted:

+
        lifecycleScope.launch {
+            viewModel.allCheeses.collectLatest { adapter.submitData(it) }
+        }
+
+

When the data is modified, an observer triggers an invalidation:

+
        dao.sortedData.observeForever {
+            dataSource?.invalidate()
+        }
+
+

The scrolling and loading of pages is fine, the only problems come when invalidate is used and when items from 2 pages are displayed simultaneously.

+

The adapter is classic:

+
class CheeseAdapter : PagingDataAdapter<CheeseListItem, CheeseViewHolder>(diffCallback) {
+...
+    companion object {
+        val diffCallback = object : DiffUtil.ItemCallback<CheeseListItem>() {
+            override fun areItemsTheSame(oldItem: CheeseListItem, newItem: CheeseListItem): Boolean {
+                return if (oldItem is CheeseListItem.Item && newItem is CheeseListItem.Item) {
+                    oldItem.cheese.id == newItem.cheese.id
+                } else if (oldItem is CheeseListItem.Separator && newItem is CheeseListItem.Separator) {
+                    oldItem.name == newItem.name
+                } else {
+                    oldItem == newItem
+                }
+            }
+            override fun areContentsTheSame(oldItem: CheeseListItem, newItem: CheeseListItem): Boolean {
+                return oldItem == newItem
+            }
+        }
+...
+
+

What I have tried (among many other things)

+
    +
  • use LiveData instead of Flow
  • +
  • using / removing the cache on the Flow
  • +
  • removing the observers and invalidating directly in insert/delete functions to make the code more direct
  • +
  • instead of key = position, using key = page number (0, 1, 2, ...) with each page containing pageSize=30 items
  • +
+

At this point, I'm not sure anymore that paging-3 is meant to be used for custom data. I'm observing so many operations for a simple insert/delete, such as 2000-4000 compare ops in the adapter, reloading 3 pages of data, ... that using ListAdapter directly on my data and doing the load/unload manually seems a better option.

","

UPDATE July 2022

+

There are some problems with paging-3. The most noticeable ones are

+
    +
  • failure to properly load the dataset when using an initial position with initialKey (see initial_key branch)
  • +
  • failure to properly jump to another position with scrollToPositionWithOffset or similar function (see test_scroll branch)
  • +
+

getRefreshKey function is called with weird (sometimes negative) values of anchorPosition, and load is called multiple times to load unnecessary data - sometimes loading iteratively every page from the end or from the beginning.

+

I believe the same problem can be observed when the PagingSource is generated by Room.

+

=> In short, it can only be used if you need to display the top items first, and if you don't need to jump to a particular position (seeing other items is only done when the user manually scrolls through the list). A fix is on the way but it could take time; it's still only alpha and compiles for a specific set of library versions / SDK.

+

You'll find another, simpler algorithm for getRefreshKey and load in the mentioned branches, in CheeseDao.kt.

+

End of update

+
+

I finally found out a possible solution, though I'm not sure it will work if the Paging-3 library is updated. I don't know yet if the behaviour explained above is due to bugs / limitations in the Paging-3 components or if that's just a bad explanation in the reference documentation, or something I missed entirely.

+

I. Work-around for the glitch issue.

+
    +
  1. In PagingConfig, we must have enablePlaceholders = true or it simply won't work correctly. With false I'm observing the scrollbar jumping on each load operation when scrolling up/down, and inserting items at the end will make all items glitch on the display, then the list will jump all the way to the top.

    +
  2. +
  3. The logic in getRefreshKey and load, as shown in Google's guide and reference documentation, is naive and will not work with custom data. I had to modify them as follows (modifications have been pushed in the github example):

    +
  4. +
+
        override fun getRefreshKey(state: PagingState<Int, Cheese>): Int? = state.anchorPosition
+
+        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Cheese> {
+            data class Args(
+                var start: Int = 0, var size: Int = 0, var prevKey: Int? = null, var nextKey: Int? = null,
+                var itemsBefore: Int = UNDEF, var itemsAfter: Int = UNDEF
+            )
+            val pos = params.key ?: 0
+            val args = Args()
+            when (params) {
+                is LoadParams.Append -> {
+                    args.start = pos
+                    args.prevKey = params.key
+                    //args.nextKey = if (args.start < count) min(args.start + params.loadSize, count) else null
+                    args.nextKey = if (args.start + params.loadSize < count) args.start + params.loadSize else null
+                }
+                is LoadParams.Prepend -> {
+                    args.start = max(pos - pageSize, 0)
+                    args.prevKey = if (args.start > 0) args.start else null
+                    args.nextKey = params.key
+                }
+                is LoadParams.Refresh -> {
+                    args.start = max((pos - params.loadSize/2)/pageSize*pageSize, 0)
+                    args.prevKey = if (args.start > 0) args.start else null
+                    args.nextKey = if (args.start + params.loadSize < count) min(args.start + params.loadSize, count - 1) else null
+                }
+            }
+            args.size = min(params.loadSize, count - args.start)
+            if (params is LoadParams.Refresh) {
+                args.itemsBefore = args.start
+                args.itemsAfter = count - args.size - args.start
+            }
+            val source = dao.allCheesesOrdName()
+            val data = source.drop(args.start).take(args.size)
+            if (params.key == null && data.count() == 0) {
+                return LoadResult.Error(Exception("Empty"))
+            }
+            val result = LoadResult.Page(
+                data = data,
+                prevKey = args.prevKey,
+                nextKey = args.nextKey,
+                itemsBefore = args.itemsBefore,
+                itemsAfter = args.itemsAfter
+            )
+            return result
+        }
+
+

I had to deduce that from the behaviour of Room-generated PagingSource, by inserting a wrapper between the DAO code and the view model to observe the params and LoadResult values.

+

Notes

+
    +
  • The commented line in LoadParam.Append mimics the Room-generated code behaviour, which is slightly incorrect when loading the last page. It makes the Pager loads an empty page at the end, which is not a serious issue but triggers unnecessary operations in the whole chain.
  • +
  • I'm not sure about the Refresh case, it was hard to induce any logic from Room's code behaviour. Here I'm placing the params.key position in the middle of the loaded range (params.loadSize items). At worst it will append data in a 2nd load operation.
  • +
+

II. Predicting the discarded data

+

This should be possible from the params given to the load function. In a simplified heuristic (the ranges must be min/max'ed to get actual indices):

+
LoadParams.Append  -> loads [key .. key+loadSize[, so discard [key-maxSize..key-maxSize+loadSize[
+LoadParams.Prepend -> loads [key-loadSize .. key[, do discard [key-loadSize+maxSize..key+maxSize[
+LoadParams.Refresh -> discard what is not reloaded
+
+

The Args.start .. Args.start + Args.size in the code above can be used as the range which is kept, from there it is easy to deduce what is discarded.

",r +"How to check proxy anonymity Python

How can I check proxy anonymities in Python?

+

I've tried searching this up but all I got that really made sense was this answer.

+

But I don't have the resources to host a "test site" to get the headers of the requests.

+

I've tried hosting my own site on localhost with Flask but my IP doesn't like being GET requested by random proxy servers.

+

I had an idea to use HttpBin's API but it ignores the Required Via and X-Forwarder-For request headers.

+

I could probbably use another API but I don't know about any others.

+

So, how can I check a http proxy's anonymity in Python?

","

Ok, After actually reading the article in full I found a solution. Using this website I can get the headers of any request using this program:

+
import requests
+import re
+
+html = requests.get("http://azenv.net/").text
+headers = {}
+
+r = re.findall(r"[^\n]+ = [^\n]+", html)
+
+for _ in r:
+    _ = _.split(" = ", 1)
+    headers[_[0]] = _[1]
+
+print(headers)
+
+
",r +"Change color of primeng input-switch

I have the following p-inputSwitch.

+
<p-inputSwitch class="ml-1 mr-1 align-middle"
+               (onChange)="setDefaultValues($event)"
+               [ngModel]="defaultValuesToggle">
+</p-inputSwitch>
+           
+
+

Is there a way to change the color from blue when selected? I have tried the following, but nothing changes the color:

+
.p-inputswitch {
+    background: red !important;
+}
+.p-inputswitch .p-inputswitch-slider {
+  background: red !important;
+}
+
","

You need to add the "selected" state to the selector by adding the class p-inputswitch-checked to .p-inputswitch and also add ::ng-deep infront of the selector to penetrate View Encapsulation:

+
::ng-deep .p-inputswitch.p-inputswitch-checked .p-inputswitch-slider {
+  background: purple;
+}
+
",r +"How can I with Ruby check if SHA1 username, password and verifier/salt is correct?

I have a username, password and this verifier, salt. How can I check with Ruby that it's correct?

+

The docs/instructions I'm following is this: +https://www.azerothcore.org/wiki/account

+

My code atm looks like this:

+
class Account < ApplicationRecord
+ self.table_name = "account"
+ def self.check_username_password(username, password)
+  account = Account.find_by(username: username)
+  h1 = Digest::SHA1.hexdigest(username.uppercase + password.uppercase)
+  h2 = Digest::SHA1.hexdigest( account.salt + ..... )
+  h2 == account.verifier
+ end
+end
+
","

The docs you link to describe the algorithm to calculate the verifier as:

+
+

verifier

+

verifier is derived from salt, as well as the user's username (all +uppercase) and their password (all uppercase).

+

To obtain the verifier you need to calculate:

+

Calculate h1 = SHA1("USERNAME:PASSWORD"), substituting the user's +username and password converted to uppercase.

+

Calculate h2 = SHA1(salt || h1), where || is concatenation (the . +operator in PHP).

+

NOTE: Both salt and h1 are binary, not hexadecimal strings!

+

Treat h2 as an integer in little-endian order (the first byte is the +least significant).

+

Calculate (g ^ h2) % N.

+

NOTE: g and N are parameters, which are fixed in the WoW +implementation.

+

g = 7

+

N = 0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7

+

Convert the result back to a byte array in little-endian order.

+
+

Based on the links to sample implementations, this appears to be the verifier from SRP6, which you might be able to use this gem for: https://github.com/grempe/sirp. However, it doesn't line up exactly with the docs, and I think this might be interesting, so I'll try to work through it anyway.

+

First, you've got a start on finding h1 and h2, but as the NOTE says, Both salt and h1 are binary, not hexadecimal strings!. So, you'll want to replace hexdigest with digest. Also, the uppercase method in Ruby is upcase and you'll need to put a colon between the two:

+
h1 = Digest::SHA1.digest("#{username.upcase}:#{password.upcase}")
+h2 = Digest::SHA1.digest(account.salt + h1)
+
+

Next, it says to turn h2 into an integer as if it was stored in little-endian. Remember that integers are stored as sequences of bytes, each byte being 8 bits; so a 32-bit integer is 4 bytes. Endianness describes if the first byte maps to the first 8 bits or the last 8 bits of the number. Here, the comment makes it clear it'll be the last. Now, SHA1 produces a 20-byte hash, so we'll use unpack method plus the H directive (which matches each hex byte) to get it all out.

+
h2_int = h2.reverse.unpack("H*").first.to_i(16)
+
+

Lastly, we do some math with the given constants and convert it back to a string. The ^ % construction must be modular exponentiation, which you can do in Ruby 2.5+ with just Integer#pow, or in Ruby 2.4 below with openssl's mod_exp:

+
g = 7
+n = 0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7
+
+verifier_int = g.pow(h2_int, n)
+
+# ruby 2.4 or below:
+#
+# require 'openssl'
+# verifier_int = g.to_bn.mod_exp(h2_int, n).to_i
+
+verifier = [verifier_int.to_s(16)].pack('H*').reverse
+
+

Put that all together:

+
h1 = Digest::SHA1.digest("#{username.upcase}:#{password.upcase}")
+h2 = Digest::SHA1.digest(account.salt + h1)
+
+h2_int = h2.reverse.unpack("H*").first.to_i(16)
+
+g = 7
+n = 0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7
+
+verifier_int = g.pow(h2_int, n)
+
+# ruby 2.4 or below:
+#
+# require 'openssl'
+# verifier_int = g.to_bn.mod_exp(h2_int, n).to_i
+
+verifier = [verifier_int.to_s(16)].pack('H*').reverse
+
+

With this code, I was able to verify that for the values:

+
username = "testaccount"
+password = "testaccount"
+account.salt = "\xB1V\x940(|\x0F\xA0\xD6|\x7F\x86\xADO'\x82':(\xCCW\xA0\x85\xE1\xB2\xE20\x1A|3g\x1C" # [0xb1569430287c0fa0d67c7f86ad4f2782273a28cc57a085e1b2e2301a7c33671c.to_s(16)].unpack('H*')
+
+

The produced verifier matches the expected verifier of:

+
"\xB6\x95\xFF\xEB\x8E\xA76u\x8F\xFB\x0F:\xE34M\t\xC0?\xE8\xD2\xF1\xD1\x8C\x058P\x8F\xCDyQ H"
+
+

In Rails

+

After testing this out, the following code works for me. Note that I've casted the encoding of salt to ascii-8bit here, instead of verifier to utf-8, but it doesn't change the result. However, for the final comparison, the encodings do need to be the same.

+
class Account < ApplicationRecord
+  def verify(password)
+    h1 = Digest::SHA1.digest("#{username.upcase}:#{password.upcase}")
+    h2 = Digest::SHA1.digest(salt.force_encoding('ascii-8bit') + h1)
+
+    h2_int = h2.reverse.unpack("H*").first.to_i(16)
+
+    g = 7
+    n = 0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7
+
+    verifier_int = g.pow(h2_int, n)
+    verifier = [verifier_int.to_s(16)].pack('H*').reverse
+
+    verifier == self.verifier
+  end
+end
+
",r +"who runs the smart contract in ethereum?

I am new to Smart Contracts. I want to know who runs the smart contact.

+
    +
  1. I thought the full node that serves http rpc endpoint runs the smart contracts that node received.

    +

    However solidity supports block attributes like block.coinbase, block.timestamp, block.difficulty. If just full node not miner runs contracts, I think it's impossible. Then the block creator runs the all smart contract execution transactions that in the mined block?

    +
  2. +
  3. If miner runs smart contracts, can miner pollute timestamp of block?

    +
  4. +
","

Contract function invoked by a transaction

+

Multiple entities run the contract code.

+
    +
  1. At first, all miners trying to generate a block including a transaction interacting with this contract. In order to calculate state changes (to be included in the block) resulting from the transaction, the miner needs to execute the function.

    +

    Only the winning miner includes these state changes in their block and broadcast the block. So effectively, from the outside view, you see the function being executed just once.

    +

    Values of these block.* global variables are values of the winning miner's metadata. If a different miner published the block, some of these values (such as coinbase and timestamp) would be different.

    +
    +

    If miner runs smart contracts, can miner pollute timestamp of block?

    +
    +

    Yes, they can chose to manipulate the timestamp of the whole block (affecting other transactions in the block as well) to an extent of few seconds. Or they can chose to include the transaction in a later arbitrary block number, or not include it at all.

    +
  2. +
  3. And then, all validator nodes execute the same function validating if they get the same result as the miner. As they are validators, they don't inject their own metadata and validate against the already published block data - such as the block.coinbase address published in the block.

    +
  4. +
+
+

Contract function invoked by a call

+

Only the node performing the call invokes the function. Since calls are read-only, they cannot produce any state changes, so the node only reads the data from their local copy of the blockchain.

+

Example: A web application is connected to a node, and asks the node to perform a call. Only this one node performs the call and returns the response back to the web app. No other nodes are involved.

",r +"Long polling with kotlin coroutines

I found this repository at GitHub Long Polling Redis

+

So in spring boot, we can use a deferred request to hold the client request for several seconds (AppMsgController.java#L72)

+

and it will send back to the client until the deferred request is filled with the result (AppMsgHandler.java#L74) or until it reaches the timeout.

+

I also notice this mechanism also can be implemented with CompetableFuture in java using completeOnTimeout.

+

But I wonder can we use something similar in Kotlin Coroutines?

","

In Kotlin coroutines there is the Deferred type, which is similar to CompletableFuture in the sense that it represents a value that is not yet available but probably will be in the future (if no error occurs/exception is thrown). @Joffrey pointed out that there is also a CompletableDeferred, which is even closer to ComplatableFuture enabling the user to manually call complete or exceptionallyComplete.

+

Deferreds can easily be created with the async extension function on CoroutineScope. If you want to set a timeout, Kotlin has you covered with the withTimeout function that cancels the block of code after a given time.

+

Note that withTimeout should be inside async and not the other way around.

+

Take a look at this example: https://pl.kotl.in/uYe12ds7g

",r +"Jupyter Notebook's File and Kernel menus disappear

I have an issue where my File and Kernel menus initially show while the notebook is loading, then disappear once the notebook is loaded.

+

I should be seeing this: +

+

but instead I see this: +

+

It used to work correctly. I am not sure what could have changed to make these menus disappear.

+

Thanks for any help with this.

","

This issue is related to your Virtual enviroment of python. +So what you can do for solving this issue, just create a new virtual enviroment from Python command prompt and change your virtual environment to the new one, which you created, or change your virtual environment to one of your existing virtual environments.

+

See list of virtual environment: conda info --envs (in the python command prompt)

+

Activate a virtual environment: conda activate * (* = name of one of existing virtual environments)

+

create a new virtual enviroment: conda create * (* = name of the virtual environment you want to create)

+

or if you do not want to change your virtual environment you can open your jupyter directly from anaconda)

+

another solution is that you can shift to jupyter lab which is more efficient with respect to the jupyter notebook.

+

in the python command prompt instead of writing "jupyter notebook", write "jupyter lab".

",r +"Android emulator (AVD) crashes on Wayland + NVIDIA (GBM)

Update: The problem does not occur with the NVIDIA driver version 510 anymore.

+

I am running Android Studio 2020.3.1 on Wayland and I'm using the proprietary NVIDIA driver version 495, which allows me to use the the regular GBM implementation of Wayland instead of the especially tailored EGL version.

+

My problem is, that every time I try to start an Android emulator (AVD) via the AVD Manager, I get the following message after a few seconds:

+
+

The emulator process for AVD Pixel_2_API_30 has terminated.

+
+

Starting the AVD from the command-line shows that a segmentation fault occurred:

+
INFO    | Android emulator version 31.1.4.0 (build_id 7920983) (CL:N/A)
+WARNING | unexpected system image feature string, emulator might not function correctly, please try updating the emulator.
+INFO    | Info: Warning: Ignoring XDG_SESSION_TYPE=wayland on Gnome. Use QT_QPA_PLATFORM=wayland to run on Wayland anyway. ((null):0, (null))
+
+Fontconfig warning: "/usr/share/fontconfig/conf.avail/05-reset-dirs-sample.conf", line 6: unknown element "reset-dirs"
+WARNING | cannot add library /home/letorbi/Android/Sdk/emulator/qemu/linux-x86_64/lib64/vulkan/libvulkan.so: failed
+INFO    | added library /home/letorbi/Android/Sdk/emulator/lib64/vulkan/libvulkan.so
+Segmentation fault (core dumped)
+
+

How can I get more information and is there a workaround to prevent the segfault?

+

For what it's worth, Wayland EGL is able to start the emulator somehow, but I see nothing but a black screen on the device. X11 is working, but I'd like to stay on Wayland if it is possible.

","

I was able to work around the segmentation fault, by disabling the Vulkan support for AVDs. This can be easily achieved by adding the following line to the file ~/.android/advancedFeatures.ini:

+
Vulkan = off
+
+

I've got this hint from an answer in a related question. This answer also suggests to add GLDirectMem = on, but that line was not needed to solve my problem. However, some benchmarking revealed that it might improve the performance a little bit, so you might want to add that line as well.

",r +"xPath - Why is this exact text selector not working with the data test id?

I have a block of code like so:

+
<ul class="open-menu">
+  <span>
+    <li data-testid="menu-item" class="menu-item option">
+      <svg>...</svg>
+      <div>
+        <strong>Text Here</strong>
+        <small>...</small>
+      </div>
+    </li>
+
+    <li data-testid="menu-item" class="menu-item option">
+      <svg>...</svg>
+      <div>
+        <strong>Text</strong>
+        <small>...</small>
+      </div>
+    </li>
+  </span>
+</ul>
+
+

I'm trying to select a menu item based on exact text like so in the dev tools:

+
$x('.//*[contains(@data-testid, "menu-item") and normalize-space() = "Text"]');
+
+

But this doesn't seem to be selecting the element. However, when I do:

+
$x('.//*[contains(@data-testid, "menu-item")]');
+
+

I can see both of the menu items.

+

UPDATE:

+

It seems that this works:

+
$x('.//*[contains(@class, "menu-item") and normalize-space() = "Text"]');
+
+

Not sure why using a class in this context works and not a data-testid. How can I get my xpath selector to work with my data-testid?

","
+

Why is this exact text selector not working

+
+

The fact that both li elements are matched by the XPath expression +if omitting the condition normalize-space() = "Text" is a clue. +normalize-space() returns ... Text Here ... for the first li +in the posted XML and ... Text ... for the second (or some other +content in place of ... from div/svg or div/small) causing +normalize-space() = "Text" to fail.

+

In an update you say the same condition succeeds. This has nothing to +do with using @class instead of @data-testid; it must be triggered +by some content change.

+
+

How can I get my xpath selector to work with my data-testid?

+
+

By testing for an exact text match in the li's descendant strong +element,

+
.//*[@data-testid = "menu-item" and div/strong = "Text"]
+
+

which matches the second li. Making the test more robust is usually +in order, e.g.

+
.//*[contains(@data-testid,"menu-item") and normalize-space(div/strong) = "Text"]
+
+

Append /div/small or /descendant::small, for example, to the XPath +expression to extract just the small text.

",r +"Excel Power Query import (same file but with different month name)

Each month I need to automate the importing of reference data, however the Excel file is named differently.

+

Monthly Data File January 2022.xlsx +Monthly Data File February 2022.xlsx

+

Could you point me in the right direction please?

","

In excel, use formulas ... name manager... to pick a cell and give it a range name, like NameVariable

+

Enter your filepath and filename C:\temp\Monthly Data File January 2022.xlsx in that named cell. Change the content of that range as needed when filename changes later

+

Load one file into powerquery, then in home ... advanced editor ... add a formula that refers to that range name, similar to this:

+
MVar = Excel.CurrentWorkbook(){[Name="NameVariable"]}[Content]{0}[Column1],
+
+

and change any hard coded references to the filename to use MVar instead

+

As an example, change

+
let Source = Excel.Workbook(File.Contents("C:\temp\Monthly Data File January 2022.xlsx"), null, true),
+
+

to be

+
let MVar = Excel.CurrentWorkbook(){[Name="NameVariable"]}[Content]{0}[Column1],
+Source = Excel.Workbook(File.Contents(MVar), null, true),
+
",r +"ggplot legend.box.background produces strange relics

This is a bit harder to explain than my last question because the problem is not exactly reproducible.

+

I am producing legends for a couple of maps and am drawing a box around both legends since one has only 1 item (a line feature) and the others are discrete fills (a polygon feature). Using geom_sf to plot both.

+

I end up with a weird artefact that looks like part of the lines are drawn twice with just a slightly shifted position.

+

+

I managed to produce a similar error with the iris dataset where legend.box.background is only partially drawn.

+
data(iris)
+
+ggplot(iris)+theme_classic()+
+  geom_point(aes(x=Petal.Length, y=Sepal.Length, color=Species, size=Sepal.Width))+
+  scale_color_manual(name=NULL, values=c("red","green","blue") ,labels=c("supersupersupersuperlong", "test2", "test3"))+
+  theme(legend.position=c(0.1,0.75),legend.box.background=element_rect(fill="white", color="black"), legend.spacing.y=unit(0,"cm"))
+
+
+
+
+

UPDATE

+

I noticed in my original example it had to do with text length, so I tried adding a space after some of the labels which changes the "arrangement" of the twice-drawn lines a little bit. But I can't find an arrangement of whitespace that makes it go away completely. +Anyone know how to manually change the size of the legend.box.background. If not I will draw a geometric rectangle and call it quits.

","

I think the problem here is that the legend.background (which is a white rectangle behind each component of your legend), is partially drawing over the line surrounding the legend.box, which is the rectangle surrounding the whole legend. You can simply remove the legend.background

+

For example, your plot goes from this:

+
ggplot(iris) + 
+  theme_classic() +
+  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
+                 size = Sepal.Width)) +
+  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
+                     labels = c("supersupersupersuperlong", "test2", "test3")) +
+  theme(legend.position = c(0.1, 0.75),
+        legend.box.background = element_rect(fill = "white", color = "black"), 
+        legend.spacing.y = unit(0, "cm"))
+
+

+

To this:

+
ggplot(iris) + 
+  theme_classic() +
+  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
+                 size = Sepal.Width)) +
+  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
+                     labels = c("supersupersupersuperlong", "test2", "test3")) +
+  theme(legend.position = c(0.1, 0.75),
+        legend.background = element_blank(),
+        legend.box.background = element_rect(fill = "white", color = "black"), 
+        legend.spacing.y = unit(0, "cm"))
+
+

",r +"How can I add multiple conditions in react?

I have button Description. When clicked description is displayed. Now I want to add Read more/less on description.

+

With the belpw code, I do not see button Description, description is displayed directly

+

Flow- Display button-> On click-> Show 200 character text (With Read more option)

+
  const [readMore, setReadMore] = useState(false);
+
+
+  const [displaydescription, setDisplayDescription] = useState(false);
+  const clickHandler = () => {
+    setDisplayDescription(true);
+  };
+
+ <p>
+          {displaydescription || readMore
+            ? description
+            : `${description.substring(0, 200)}`}
+        </p>
+
","

You have to change your code to first display description and then in second condition to verify if you want to show the full text like this:

+

+
+
const [readMore, setReadMore] = useState(false);
+const [displaydescription, setDisplayDescription] = useState(false);
+const clickHandler = () => {
+    setDisplayDescription(true);
+};
+
+ <p>
+    {displaydescription 
+       ? (
+            readMore
+               ? description
+               : `${description.substring(0, 200)
+         )
+       : null}`
+    }
+ </p>
+
+
+

",r +"Init servlet instantly after the embedded jetty server starts

I need to run my own logic after the jetty embedded server starts. I'm not starting it from the main class due to classloader issues. An ideal solution seemed to be running my server logic from a servlet initialization. But the init function and also the constructor is not called after the jetty server start. An instance of the servlet is being created during the first HTTP request. Is it possible to tell jetty to initialize my servlet instantly or do I really need to load all classes with my custom classloader and then start the jetty server?

+

This is the main class:

+
public class ServerLauncher {
+    public static void main(String[] args) {
+        JettyServerLauncher.launchHttp("target/server.war", "0.0.0.0", 8080);
+        // Starting my own logic here is causing classloader issues, because WebSocket classes are loaded by other classloader than my classes, that is the reason why I moved it into the servlet
+    }
+}
+
+

This is my jetty embedded server launcher:

+
import org.eclipse.jetty.annotations.AnnotationConfiguration;
+import org.eclipse.jetty.http.HttpVersion;
+import org.eclipse.jetty.plus.webapp.EnvConfiguration;
+import org.eclipse.jetty.plus.webapp.PlusConfiguration;
+import org.eclipse.jetty.server.*;
+import org.eclipse.jetty.server.handler.ContextHandlerCollection;
+import org.eclipse.jetty.server.handler.HandlerCollection;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.eclipse.jetty.webapp.*;
+
+import java.io.File;
+
+public class JettyServerLauncher {
+    private static boolean isHttps;
+    private static File keyStoreFile;
+    private static String warPath;
+    private static String host;
+    private static int httpPort;
+    private static int httpsPort;
+    private static String keyStorePath;
+    private static String keyStorePass;
+    private static boolean needClientAuth;
+
+    public static void launchHttp(String warPath, String host, int httpPort) {
+        JettyServerLauncher.isHttps = false;
+        JettyServerLauncher.warPath = warPath;
+        JettyServerLauncher.host = host;
+        JettyServerLauncher.httpPort = httpPort;
+
+        launch();
+    }
+
+    public static void launchHttps(String warPath, String host, String keyStorePath, String keyStorePass, int httpPort, int httpsPort, boolean needClientAuth) {
+        JettyServerLauncher.isHttps = true;
+        JettyServerLauncher.warPath = warPath;
+        JettyServerLauncher.host = host;
+        JettyServerLauncher.httpPort = httpPort;
+        JettyServerLauncher.httpsPort = httpsPort;
+        JettyServerLauncher.keyStorePath = keyStorePath;
+        JettyServerLauncher.keyStorePass = keyStorePass;
+        JettyServerLauncher.needClientAuth = needClientAuth;
+
+        launch();
+    }
+
+    private static void launch() {
+        Server server = null;
+
+        try {
+            System.out.println("Initializing jetty server...");
+
+            if (isHttps) loadKeyStores(keyStorePath);
+
+            // Create jetty server
+            server = new Server(httpPort);
+
+            // Setup connectors
+            Connector httpConnector = createHttpConnector(server, host, httpPort, httpsPort);
+            if (isHttps) {
+                Connector httpsConnector = createHttpsConnector(server, host, httpsPort, keyStoreFile, keyStorePass, needClientAuth);
+                server.setConnectors(new Connector[]{httpConnector, httpsConnector});
+            } else {
+                server.setConnectors(new Connector[]{httpConnector});
+            }
+
+            // Add handlers for requests to collection of handlers
+            HandlerCollection handlers = new ContextHandlerCollection();
+            //handlers.addHandler(new SecuredRedirectHandler());
+            handlers.addHandler(createWebApp(warPath));
+
+            server.setHandler(handlers);
+            server.dump();
+
+            System.out.println("Starting jetty websocket and web server...");
+            server.start();
+            server.join();
+        } catch (Throwable t) {
+            t.printStackTrace();
+            System.err.println("Server initialization failed!");
+            System.out.println("Stopping the server...");
+            try {
+                server.stop();
+            } catch (Exception ignored) {}
+        }
+    }
+
+    private static WebAppContext createWebApp(String warPath) {
+        WebAppContext webApp = new WebAppContext();
+        webApp.setContextPath("/");
+        webApp.setWar(new File(warPath).getAbsolutePath());
+        webApp.setThrowUnavailableOnStartupException(true);
+
+        // Enable support for JSR-356 javax.websocket
+        webApp.setAttribute("org.eclipse.jetty.websocket.jsr356", Boolean.TRUE);
+
+        // Jetty will scan project for configuration files... This is very important for loading websocket endpoints by annotation automatically
+        webApp.setConfigurations(new Configuration[] {
+                new AnnotationConfiguration(),
+                new WebInfConfiguration(),
+                new WebXmlConfiguration(),
+                new MetaInfConfiguration(),
+                new FragmentConfiguration(),
+                new EnvConfiguration(),
+                new PlusConfiguration(),
+                new JettyWebXmlConfiguration()
+        });
+
+        return webApp;
+    }
+
+    private static Connector createHttpConnector(Server server, String host, int httpPort, int httpsPort) {
+        HttpConfiguration httpConf = new HttpConfiguration();
+        httpConf.setSendServerVersion(false);
+        if (isHttps) httpConf.setSecurePort(httpsPort);
+        ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConf));
+        connector.setPort(httpPort);
+        connector.setHost(host);
+
+        return connector;
+    }
+
+    private static Connector createHttpsConnector(Server server, String host, int httpsPort, File keyStoreFile, String keyStorePass, boolean needClientAuth) {
+        SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+        sslContextFactory.setKeyStorePath(keyStoreFile.getAbsolutePath());
+        sslContextFactory.setKeyStorePassword(keyStorePass);
+        sslContextFactory.setNeedClientAuth(needClientAuth);
+
+        // Setup HTTPS Configuration
+        HttpConfiguration httpsConf = new HttpConfiguration();
+        httpsConf.setSendServerVersion(false);
+        httpsConf.setSecureScheme("https");
+        httpsConf.setSecurePort(httpsPort);
+        httpsConf.setOutputBufferSize(32768);
+        httpsConf.setRequestHeaderSize(8192);
+        httpsConf.setResponseHeaderSize(8192);
+        httpsConf.addCustomizer(new SecureRequestCustomizer()); // adds ssl info to request object
+
+        // Establish the HTTPS ServerConnector
+        ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConf));
+        httpsConnector.setPort(httpsPort);
+        httpsConnector.setHost(host);
+
+        return httpsConnector;
+    }
+
+    private static void loadKeyStores(String keyStorePath) {
+        keyStoreFile = new File(keyStorePath);
+        if (!keyStoreFile.exists()) {
+            throw new RuntimeException("Key store file does not exist on path '"+keyStoreFile.getAbsolutePath()+"'");
+        }
+    }
+}
+
+

This is my servlet:

+
import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet(displayName = "MyServlet", urlPatterns = { "/*" })
+public class MyServlet extends HttpServlet {
+    @Override
+    public void init() {
+        // start new Thread with my server logic here (avoid classloader issues)
+        // but at least one HTTP request is needed to start it from this place
+    }
+
+    @Override
+    public void destroy() {}
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
+        // handle http requests
+    }
+}
+
+

I found this on google, but I don't know how to use it in my case. https://www.eclipse.org/lists/jetty-users/msg02109.html

+

Thank you for your help.

","

If you just want the servlet to init on startup, then use the annotation ...

+
@WebServlet(
+    displayName = "MyServlet", 
+    urlPatterns = { "/*" },
+    loadOnStartup = 1
+)
+
+

Alternatively, you could register a javax.servlet.ServletContextListener that does the contextInitialized(ServletContextEvent sce) behavior you need.

+

Tip: if you define a custom the ServletContextListener for embedded use, you can just add it to the WebAppContext from outside of the WAR you are using.

+

Example:

+
webApp.getServletHandler()
+    .addListener(new ListenerHolder(MyContextListener.class));
+
+

Also, this block of code is wrong and shows you copy/pasted from an old code snippet (this technique is from circa Jetty 9.0.0 thru 9.2.16)

+
        webApp.setConfigurations(new Configuration[] {
+                new AnnotationConfiguration(),
+                new WebInfConfiguration(),
+                new WebXmlConfiguration(),
+                new MetaInfConfiguration(),
+                new FragmentConfiguration(),
+                new EnvConfiguration(),
+                new PlusConfiguration(),
+                new JettyWebXmlConfiguration()
+        });
+
+

In Jetty 9.4.x you never directly configure the webApp.setConfigurations() like that, use the Configuration.ClassList defined on the server instead ...

+

From: 9.4.44.v20210927 - embedded/LikeJettyXml.java

+
Configuration.ClassList classlist = Configuration.ClassList
+    .setServerDefault(server);
+classlist.addAfter(
+    "org.eclipse.jetty.webapp.FragmentConfiguration",
+    "org.eclipse.jetty.plus.webapp.EnvConfiguration",
+    "org.eclipse.jetty.plus.webapp.PlusConfiguration");
+classlist.addBefore(
+    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
+    "org.eclipse.jetty.annotations.AnnotationConfiguration");
+
+

Starting in Jetty 10.0.0, you never specify the Configuration classes, or their order, as the existence of the support JAR is enough, and internally in Jetty 10 the order is resolved properly.

+

But if you need to add Configurations (due to non-standard deployment concerns where the Java ServiceLoader doesn't work), then you still configure the additional Configurations on the server object (but without worrying about the correct order for those configurations)

+

From 10.0.7 - embedded/demos/LikeJettyXml.java

+
Configurations.setServerDefault(server).add(
+    new EnvConfiguration(), 
+    new PlusConfiguration(), 
+    new AnnotationConfiguration()
+);
+
",r +"Array initialization with ternary operator in Java

Why will Java let me initialize an array like this: +int[] anotherArray = {1,2,3,4,5};

+

But won't accept this: +int[] anArray = (arr.length > 0) ? {1,2,3,4,5}: {};

+

Image

","

To make your code work, do the following instead:

+
int[] anArray = (arr.length > 0) ? new int[]{1,2,3,4,5}: new int[]{};
+
+

To understand why the original code didn't work, we need to understand two things: 1) the ternary operator, and 2) the ways to initialize an array.

+

1. The ternary operator (?:)

+

The ...?...:... expression is called the ternary operator (not lambda). It is simply a shorthand for an if-else statement. You can find out more about the ternary operator in the Oracle tutorial.

+
+

Another conditional operator is ?:, which can be thought of as +shorthand for an if-then-else statement

+
+

2. Ways to initialize arrays in Java

+

int[] anArray = {1,2,3,4,5} (without new) is a shorthand for instantiating an array, and can only be used when initializing the array during declaration. When an array is instantiated outside of declaration, the new operator must be used ("new int[]{...}"). For example:

+
int[] b = new int[] {1, 2, 3} // ok
+int[] c = {1, 2, 3} // ok
+
+int[] arr;
+arr = new int[]{1, 2, 3} // ok
+arr = {1, 2, 3} // compilation error
+
+

More about array creation in the section "Creating, Initializing, and Accessing an Array" in the Oracle tutorial here.

+

Why the original code didn't work

+

Putting the above pieces of information together, 1) ?: is simply another way of writing an if-else statement, and 2) when instantiating an array outside of declaration the new operator is required. Your original statement is equivalent to the following:

+
int[] anArray;
+if (arr.length > 0) {
+    anArray = {1,2,3,4,5} // compilation error
+} else {
+    anArray = {}; // compilation error
+}
+
+

To fix the compilation error, the new operator should be used:

+
int[] anArray;
+if (arr.length > 0) {
+    anArray = new int[]{1,2,3,4,5} // ok
+} else {
+    anArray = new int[]{}; // ok
+}
+
+

Which then simplifies to:

+
int[] anArray = (arr.length > 0) ? new int[]{1,2,3,4,5}: new int[]{};
+
",r +"Issue with assigning sparkpoolname in synapse pipeline deployed from template

I am currently deploying our synapse workspace using az cli and json templates and after deploying, pipeline is unable to pickup the spark pool name from pipeline parameters as in the attached pic.

+

+

+

Any help is appreciated!!

","

After posting to Microsoft forum, came to know that this is a bug with synapse devops deployment. As a work around, I am deploying synapse notebook with powershell Az.Synapse module which will let me assign sparkpool. From this, triggering the pipeline will not give an issue.

",r +"How to move a model and generate its collision shape at the same time?

I have ModelEntity in SwiftUI and it moves. But the problem is: when adding generateCollisionShape method, it doesn't move anymore.

+

I want a collision effect as well as moving entity +how can I attain both?

+
modelEntityClone.generateCollisionShapes(recursive: true)
+
+modelEntityClone.physicsBody = PhysicsBodyComponent(massProperties: .default, 
+                                                          material: .default, 
+                                                              mode: .dynamic)
+
","

Hope this trick definitely helps. This physics lasts forever. ))

+

+
struct ARViewContainer: UIViewRepresentable {
+    
+    let ball = ModelEntity(mesh: .generateSphere(radius: 0.5))
+    let anchor = AnchorEntity()
+    
+    func makeUIView(context: Context) -> ARView {
+
+        let arView = ARView(frame: .zero)
+
+        ball.physicsBody = .init()
+        ball.physicsBody?.massProperties.mass = 0
+
+        ball.physicsMotion = .init()
+        ball.physicsMotion?.linearVelocity.x = 1.0
+        ball.physicsMotion?.angularVelocity.z = -.pi
+
+        ball.position.x = -4.0
+        ball.generateCollisionShapes(recursive: true)
+        anchor.addChild(ball)
+
+        anchor.position.z = -3.0
+        arView.scene.addAnchor(anchor)
+        return arView
+    }
+
+    func updateUIView(_ uiView: ARView, context: Context) { }
+}
+
",r +"Converting firebase 8 code to firebase 9 code (web, javascript) to fetch collection within collection

Hello I would like to convert the following firebase 8 code to firebase 9 and have no clue how to do it - any help would be welcome!

+

This piece of code should go inside the userDoc and then fetch the collection that is insdie that document and return all of the posts that belong to that user

+
if (userDoc) {
+    user = userDoc.data()
+    const postsQuery = userDoc.ref
+        .collection('posts')
+        .where('published', '==', true)
+        .orderBy('createdAt', 'desc')
+        .limit(5)
+    posts = (await postsQuery.get()).docs.map(postToJSON)
+}
+
+

enter image description here

","

Firestore's documentation has examples for both V8 and V9 so you can easily compare them and modify your code. Just switch to modular tab for the new syntax. The code in question would be like:

+
import { collection, query, where, getDocs, orderBy, limit } from "firebase/firestore";
+
+const q = query(collection(db, "posts"), where("published", "==", true), orderBy("createdAt", "desc"), limit(5));
+
+const querySnapshot = await getDocs(q);
+
+posts = querySnapshot.docs.map(postToJSON)
+
",r +"Google Maps Directions API blank response

I'm trying to get directions using the Google Maps Directions API.

+

It's pretty much what Google's own documentation shows to do https://developers.google.com/maps/documentation/directions/get-directions#maps_http_directions_toronto_montreal-java

+

The requested URL works when pasted into a browser, so that's correct.

+

And I can see an additional Directions API request after running this.

+

The response has no JSON directions in it.

+

What am I doing wrong?

+
private class getDirections extends AsyncTask<LatLng, Void, String> {
+        @Override
+        protected String doInBackground(LatLng... point) {
+            try {
+                OkHttpClient client = new OkHttpClient().newBuilder()
+                        .writeTimeout(60, TimeUnit.SECONDS)
+                        .readTimeout(60, TimeUnit.SECONDS)
+                        .build();
+                Request request = new Request.Builder()
+                        .url("https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key="+MAPS_API_KEY)
+                        .method("GET", null)
+                        .build();
+                    Response response = client.newCall(request).execute();
+                    Log.d("response1", response.message());
+                    if (response.message() == "") {
+                        return "error";
+                    }
+                    return response.body().string();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+                return null;
+        }
+
+    }
+
+

Image of 'response' in the debugger

","

response.message() is not the body, it's just the string after the 200.

+

HTTP/1.1 200

+

check the response numerically or via if (!response.isSuccessful) {

+

This query is working for me.

+
{
+  "geocoded_waypoints": [
+    {
+      "geocoder_status": "OK",
+      "place_id": "ChIJpTvG15DL1IkRd8S0KlBVNTI",
+      "types": [
+        "locality",
+        "political"
+      ]
+    },
+    {
+      "geocoder_status": "OK",
+      "place_id": "ChIJDbdkHFQayUwR7-8fITgxTmU",
+      "types": [
+        "locality",
+        "political"
+      ]
+    }
+  ],
+  "routes": [
+    {
+      "bounds": {
+        "northeast": {
+          "lat": 45.5017123,
+          "lng": -73.5672184
+        },
+        "southwest": {
+          "lat": 43.6533961,
+          "lng": -79.3834913
+        }
+      },
+
",r +"Getting bootstrap dropdown value return to work in flask

I am trying to get a value (player) from the dropdown select. Once I click the dropdown button, I want the value 'player' to get sent to flask and render the new player's image on the website. +HTML:

+
<form method="POST">
+    <div class="input-group">
+      <select class="custom-select" id="inputGroupSelect04" name="player" value="{{ player }}">
+          {% for key, value in team.items() %}
+            <option value={{ value }}>{{ value }}</option>
+          {% endfor %}
+      </select>
+      <div class="input-group-append">
+        <button class="btn btn-outline-secondary" type="submit">Select</button>
+      </div>
+    </div>
+
+</form>
+    <img src="/static/{{ player }}.png" alt="{{ player }}">
+
+

Flask:

+
@app.route("/", methods=['POST', 'GET'])
+def main_page():
+    player = okc[1628983]
+    if request.method == "POST":
+        print("this posted")
+        player = request.form.get('player')
+        print(request.form.get('player'))
+        return render_template("index.html", team=okc, player=player)
+    return render_template("index.html", team=okc, player=player)
+
",

Button wasn't posting - changed type from button to submit

,r +"When you execute chrome browser using Chrome DevTools Protocol, where does such session store stuff like history, cookies and extensions added?

I realized today that you can merge Chrome DevTools Protocol with Selenium in order to automate some very specific parts of a process within a website.

+

for instance: after some initial conditions have met, automate the process of uploading some files to an account and etc...

+

According to the official repository you use a sentence like the following on cmd to create a new chrome session with your user data:

+
chrome.exe --remote-debugging-port=9222 --user-data-dir:"C:\Users\ResetStoreX\AppData\Local\Google\Chrome\User Data"
+
+

So in my case, the sentence above generates the following output:

+

+

The thing is, in my original session I had some Chrome extensions added, and I know that If I were to work only with Selenium using its chromedriver.exe, I could easily add an extension (which must be compressed as a .crx file) by using the following sentence:

+
from selenium import webdriver
+from selenium.webdriver.chrome.options import Options
+opt = Options() #the variable that will store the selenium options
+opt.add_extension(fr'{extension_path}')
+
+

But it seems that Chrome DevTools Protocol can't just add as much Options as Selenium, so I would have to install all my extensions in this pseudo session of mine again, no problem.

+

But, after installing such extensions, will those keep installed and ready for use after I execute again chrome.exe --remote-debugging-port=9222 --user-data-dir:"C:\Users\ResetStoreX\AppData\Local\Google\Chrome\User Data", and if so, where?

+

Or if not, does that mean that I would have to re install those every single time I need to do tests with Chrome DevTools Protocol and my Chrome extensions? Thanks in advice.

","

Can confirm, a session opened with Chrome DevTools Protocol somehow stores permanently the extensions you re installed. It also remembers if you used some specific credentials for logging in to some sites.

",r +"How to inject an interface non managed by spring into a spring component

im relatively new to spring framework and facing a challenge currently.

+

I have an interface ABC from an external library with me and a class BCD. +Now, i need to use ABC in my class. But when i autowire it, it always comes as null and throws NPE. ABC is not annotated.

+
Constructor in BCD required a bean of type ABC that could not be found.
+
+

Please let me know if this is something that is poosible with spring & guide me in the right direction!!

+

Note - This is not inject spring bean in non-spring managed bean but the other way around. +ABC is not managed by spring and BCD is a @Component class.

+

Thanks in Advance!!

+
import SampleInterface from from a maven dependency
+
+@Component
+public class ABC {
+    
+    @Autowire
+    private SampleInterface SI;
+
+    // Do my stuff
+}
+
","

You should have a class that's annotated with @Configuration (a new one or an existing one). In that class, add a method that returns an instance of ABC and annotate that method with @Bean. This will turn the return value into a Spring bean that you can then inject anywhere.

",r +"How to solve the ""Intervention Slow network is detected."" error in React Native

I have been getting the following error:

+

"[Intervention] Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: http://localhost:19006/fonts/MaterialCommunityIcons.ttf"

+

While researching this error I have read a lot of people recommending to disable the error or just straight up ignore it, but since I have been getting this error the refresh time has increased substantially.

",

I had multiple instances running and hadn't restarted my PC in a while. After a restart it was fixed and back to loading almost instantly...

,r +"How to run what I have in package.json into Docker?

I have to dockerize an app but I didn't work with docker before. It's an angular app, but every time I try to build it I got an error because it can't run a script I have in package.json because it says there is no package.json? Can someone look over my dockerfile and tells me what's wrong?

+
FROM node:16.13.0-alpine as builder
+COPY ./ *
+WORKDIR /app
+RUN npm install 
+RUN npm start:complete-interceptor-example
+
+FROM nginx:1.17.10-alpine
+EXPOSE 80
+COPY --from=builder /app/dist/angular_task /usr/share/nginx/html
+
+
+"scripts": {
+    "ng": "ng",
+    "start": "ng serve",
+    "build": "ng build",
+    "build:prod": "ng build opentelemetry-interceptor --prod",
+    "test": "jest --coverage",
+    "lint": "ng lint",
+    "release": "standard-version",
+    "e2e": "ng e2e",
+    "cypress": "concurrently -k -p \"[{name}]\" -n \"backend,interceptor-example,cypress\" -c \"green.bold,cyan.bold,yellow.bold\" \"npm run start:backend-interceptor-example\" \"npm start interceptor-example\" \"cypress open\"",
+    
+    "cypress:run": "concurrently -k -s first -p \"[{name}]\" -n \"backend,interceptor-example,cypress\" -c \"green.bold,cyan.bold,yellow.bold\" \"npm run start:backend-interceptor-example\" \"npm start interceptor-example\" \"cypress run\"",
+    "start:backend-interceptor-example": "node ./projects/interceptor-example/src/backend-api.js",
+    "start:complete-interceptor-example": "concurrently -k -p \"[{name}]\" -n \"backend,interceptor-example\" -c \"green.bold,cyan.bold\" \"npm run start:backend-interceptor-example\" \"npm start interceptor-example\"",  
+    "compodoc": "npx compodoc -t -p projects/opentelemetry-interceptor/tsconfig.lib.json --theme material -d ./docs -n \"OpenTelemetry Angular Interceptor\""
+  },
+
+

this is inside the package.json +and this is my folder structure

+

+

I think I copy wrong the files. I can't find anything on Google that might work. +Thank you for your time!

","

WORKDIR changes the current dir, so when you COPY the files first and then set the WORKDIR, you copy the files to another directory than the workdir.

+

When you want your app to be served by Nginx, you also need to build, so you can copy the built app to Nginx.

+

Try this

+
FROM node:16.13.0-alpine as builder
+WORKDIR /app
+COPY . .
+RUN npm install 
+RUN npm run build
+
+FROM nginx:1.17.10-alpine
+EXPOSE 80
+COPY --from=builder /app/dist /usr/share/nginx/html
+
",r +"How to share a list object with custom form

Am trying to share posted objects on list view but each time that I click on the share button which redirect me to share_form.html after typing into the shared textarea and submit the form it doesn't submit the shared object form, unless I use context variable {{ form }} before the object could be shared, why is it that when I use my custom form it doesn't submit the shared post? but rather when i do say {{ form }} then it's able to share the post?

+
Here is my view to share post
+
+def share_post(request, pk):
+    original_post = Post.objects.prefetch_related('postimage_set').get(pk=pk)
+    form = ShareForm(request.POST, request.FILES)
+    if form.is_valid():
+        new_post1 = Post(
+            shared_body = request.POST.get('description'),
+            description = original_post.description,
+            username = original_post.username,
+            date_posted = original_post.date_posted,
+            video    = original_post.video,
+            shared_on = datetime.now(),
+            shared_user = request.user)
+        new_post1.save()
+        for image in original_post.postimage_set.all():
+            new_post = PostImage(post=new_post1, 
+                                username=original_post.username,
+                                 image=image.image)
+                
+            new_post.save() 
+        return redirect('feed:feed')
+        
+    ctx = {'form':form,'original_post':original_post}
+    return render(request,'feed/share_form.html', ctx)
+
+

My django form model to share post!

+
class ShareForm(forms.Form):
+    body = forms.CharField(label='',widget=forms.Textarea(attrs={
+    'rows': '3',
+    'placeholder': 'Say Something...'
+  }))
+        
+
+

My html form to share post

+
<div class="main_content">
+    <div class="mcontainer">
+ 
+ <div class="md:flex md:space-x-6 lg:mx-16">
+    <div class="space-y-5 flex-shrink-0 md:w-7/12">
+
+ <div class="card lg:mx-0 uk-animation-slide-bottom-small">
+   
+  <form method="POST" action="" enctype="multipart/form-data">
+    <div class="flex space-x-4 mb-5 relative">
+        <img src="{{ request.user.profile_image.url }}" alt="" class="rounded-full shadow w-12 h-12">
+        <div class="flex-1">
+            <form action="" method="POST" for='id_shared_body' enctype="multipart/form-data" >
+                {% csrf_token %}
+<div class="grid md:grid-cols-2 gap-4">
+  <div class="col-span-2">
+ <textarea name="shared_body" id="id_shared_body" cols="30" rows="6"  class="bg-gradient-to-b from-gray-100 to-gray-100"></textarea></div>
+<a href="#" type="submit" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
+<div class="uil-share-alt mr-1" type="submit"></div><button>Share Post</button></a>
+            </div>
+        </form>
+        </div>
+    </div>
+    <!-- post header-->
+    <div class="flex justify-between items-center lg:p-4 p-2.5">
+        <div class="flex flex-1 items-center space-x-4">
+            <a href="#">
+                <img src="{{original_post.username.profile_image.url }}" class="bg-gray-200 border border-white rounded-full w-10 h-10">
+            </a>
+            <div class="flex-1 font-semibold capitalize">
+                <a href="#" class="text-black dark:text-gray-100"> {{original_post.username.get_full_name}} </a>
+                <div class="text-gray-700 flex items-center space-x-2">  <span> {{ original_post.date_posted|timesince }}  </span> <ion-icon name="people"></ion-icon></div>
+            </div>
+        </div>
+      <div>
+        <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 dark:hover:bg-gray-700"></i> </a>
+        <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 dark:bg-gray-900 dark:text-gray-100 dark:border-gray-700" 
+        uk-drop="mode: click;pos: bottom-right;animation: uk-animation-slide-bottom-small">
+            <ul class="space-y-1">
+              <li> 
+                  <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
+                   <i class="uil-edit-alt mr-1"></i>  Edit Post 
+                  </a> 
+              </li>
+              <li> 
+                  <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
+                   <i class="uil-comment-slash mr-1"></i>   Disable comments
+                  </a> 
+              </li> 
+              <li> 
+                  <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
+                   <i class="uil-favorite mr-1"></i>  Add favorites 
+                  </a> 
+              </li>
+              <li>
+                <hr class="-mx-2 my-2 dark:border-gray-800">
+              </li>
+              <li> 
+                  <a href="#" class="flex items-center px-3 py-2 text-red-500 hover:bg-red-100 hover:text-red-500 rounded-md dark:hover:bg-red-600">
+                   <i class="uil-trash-alt mr-1"></i>  Delete
+                  </a> 
+              </li>
+            </ul>
+        
+        </div>
+      </div>
+    </div>
+    <div class="p-3 border-b dark:border-gray-700">
+        {{ original_post.description }}
+       </div>
+       {% if original_post.video %}
+       <div class="w-full h-full">
+              <video width="650" height="200" controls>
+                <source src="{% static original_post.video.url %}" >
+            </video>
+      </div>
+      {% endif %}
+      <div class="grid grid-cols-2 gap-2 p-2">
+      {% for p in original_post.postimage_set.all %}
+      {% if forloop.counter == 1 %}
+     <a href="{{ p.image.url }}" class="col-span-2">  
+     <img src=" {{ p.image.url }}  " alt="" class="rounded-md w-full lg:h-71 object-cover" >
+     </a>
+    {% endif %}
+    {% if forloop.counter == 2 %}
+    <a href="{{ p.image.url }}">  
+     <img src="{{ p.image.url }} "  alt="" class="rounded-md w-full h-full">
+    </a>
+   {% endif %}
+
+   {% if forloop.counter == 6 %}
+    <a href="{{ p.image.url }}" class="relative"> 
+    <img src=" {% if forloop.counter == 6 %}{{ p.image.url }}{% endif %}" alt="" class="rounded-md w-full h-full">
+   <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md inset-0 text-2xl"> + {{ forloop.counter }} more </div>
+   </a>
+   {% else %}
+   <a href="{{ p.image.url }}" class="relative" hidden> 
+    <img src=" {% if forloop.counter == 3 %}{{ p.image.url }}{% endif %}" alt="" class="rounded-md w-full h-full">
+    <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md inset-0 text-2xl"> + {{ forloop.counter }} more </div>
+   </a>
+{% endif %}
+{% endfor %}
+</div>
+    <div class="p-4 space-y-3"> 
+       
+        <div class="flex space-x-4 lg:font-bold">
+            <a href="#" class="flex items-center space-x-2">
+                <div class="p-2 rounded-full  text-black lg:bg-gray-100 dark:bg-gray-600">
+                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
+                        <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
+                    </svg>
+                </div>
+                <div> Like</div>
+            </a>
+            <a href="#" class="flex items-center space-x-2 flex-1 justify-end">
+                <div class="p-2 rounded-full  text-black lg:bg-gray-100 dark:bg-gray-600">
+                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
+                        <path fill-rule="evenodd" d="M18 5v8a2 2 0 01-2 2h-5l-5 4v-4H4a2 2 0 01-2-2V5a2 2 0 012-2h12a2 2 0 012 2zM7 8H5v2h2V8zm2 0h2v2H9V8zm6 0h-2v2h2V8z" clip-rule="evenodd" />
+                    </svg>
+                </div>
+                <div>  Comment</div>
+            </a>
+            
+        </div>
+       
+        {% for comment in original_post.g_comments.all %}
+        <div class="border-t py-4 space-y-4 dark:border-gray-600">
+            <div class="flex">
+                <div class="w-10 h-10 rounded-full relative flex-shrink-0">
+         <img src="" alt="" class="absolute h-full rounded-full w-full">
+                </div>
+                <div>
+ <div class="text-gray-700 py-2 px-3 rounded-md bg-gray-100 relative lg:ml-5 ml-2 lg:mr-12 dark:bg-gray-800 dark:text-gray-100">
+ <p class="leading-6">{{comment}} <i class="uil-grin-tongue-wink-alt"></i> </p>
+<div class="absolute w-3 h-3 top-3 -left-1 bg-gray-100 transform rotate-45 dark:bg-gray-800"></div>
+                    </div>
+<div class="text-xs flex items-center space-x-3 mt-2 ml-5">
+ <a href="#" class="text-red-600"> <i class="uil-heart"></i> Love </a>
+  <a href="#"> Replay </a>
+                        <span> 3d </span>
+                    </div>
+                </div>
+            </div>
+        </div>
+        
+        <a href="#" class="hover:text-blue-600 hover:underline">  Veiw 8 more Comments </a>
+
+        <div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t">
+            <input placeholder="Add your Comment.." class="bg-transparent max-h-10 shadow-none px-5">
+            <div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl">
+                <a href="#">
+                    <ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
+                </a>
+                <a href="#">
+                    <ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
+                </a>
+                <a href="#">
+                    <ion-icon name="link-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
+                </a> 
+            </div>
+        </div>
+    {% endfor %}
+    </div>
+
+</div> 
+</div>
+ </div>
+    </div>
+</form>
+
","

So after i had taken sometime to carefully analyzed the issue i had stable on a solution, actually the problem was coming from the form model:

+
 this where the problem was
+
+class ShareForm(forms.Form):
+    body = forms.CharField(label='',widget=forms.Textarea(attrs={
+    'rows': '3',
+    'placeholder': 'Say Something...'
+  }))
+
+

Instead i should have than something like this, i had omitted the description field, which was where my problem was !

+
class ShareForm(forms.Form):
+    description = forms.CharField(
+          label='',
+  widget=forms.Textarea(attrs={
+    'rows': '3',
+    'placeholder': 'Say Something...'
+  }))
+
",r +"How MVC client get tokens from IdentityServer4

I'm studying IdentityServer4 and creating the MVC client as this guide +https://docs.identityserver.io/en/latest/quickstarts/2_interactive_aspnetcore.html

+

what part I don't understand is that how Ids4 send id_token and access_token to mvc client after logged in Ids4?

","

Depending on the flow, but if you use the authorization code flow, then an authorization code is returned to the client after the user authenticates, and using this code, it can then send it back to IdentityServer to retrieve the actual tokens. This is done directly between the client and IdentityServer and this you don't see in the browser.

",r +"Docker permissions with base image for non-root user

I have a base image that does a couple of installments with root permission, then create a new user, change owner of the WORKDIR then switch to the user. The child image will inherit this image with FROM and run its Python task as user.

+
#base image
+
+FROM scratch
+WORKDIR /master
+
+RUN adduser ...
+
+RUN chown user:group -R .
+USER user:group
+
+

These two images will have different WORKDIR, where the child image's WORKDIR is the sub directory of the base image, created during image build.

+
#child image
+
+FROM base-image
+WORKDIR /master/worker
+
+...
+
+RUN pip install -e .
+
+

When building the child image, the last pip command got an error, it can not create new files because lack of permission

+
error: could not create 'python_project.egg-info': Permission denied
+
+

Apparently, the command chown in base image only grant permission to user for base image WORKDIR, not including newly created sub-directory in the child image's WORKDIR.

+

If I create master/worker during base image build then change owner, the child image works, because the user is now owner of both /master and /master/worker

+
#base image
+
+...
+
+MKDIR worker
+RUN chown user:group -R .
+USER user:group
+
+

But I prefer not to do this, since there might be more different WORKDIR created from other child images.

+

Is there any way I can grant permission to sub-directory in child image from the base image (that does not exist yet in there)? The chown -R flag doesn't work in this case.

","

I found the solution, just simply create the subfolder before setting it as WORKDIR in child image

+
RUN mkdir worker
+WORKDIR /master/worker
+
",r +"How to replace a numeric field value with its attribute?

My df

+
df = structure(list(record_id = c("8472", "6648"), 
+               ne_nombre = c("John",
+                             "Peter"), 
+               ne_cc = c("1234", "5678"), 
+               ne_idatencion = c(1111, 2222), 
+               nom_ips = structure(1:2, 
+                                   redcapLabels = c("Store 1",
+                                                    "Store 2"), 
+                                   redcapLevels = 1:2), 
+               ev_faudit = c("2022-04-27 09:48",
+                             "2022-04-27 12:49"), 
+               ev_nomusuar = c("jane", "joe"), 
+               
+               ev_obs2 = c("pending", 
+                           "pending")
+               ), 
+          row.names = c(NA, -2L), class = c("tbl_df", "tbl", 
+                                            "data.frame"))
+
+

The field df$nom_ips is a numeric type field which includes attribute data. I require to replace its numeric field with its associated label so df$nom_ips ends up being Store 1 Store 2

+

I have tried this with no luck :

+
. <- attr(df11$nom_ips, "redcapLabels")
+df11$nom_ips1 <- factor(df11$nom_ips, ., names(.))
+
+Error in factor(df11$nom_ips, ., names(.)) : 
+  invalid 'labels'; length 0 should be 1 or 2
+
","

Specify the argument name

+
df11$nom_ips1 <- factor(df11$nom_ips, levels = attr(df11$nom_ips,"redcapLevels"),
+    labels = attr(df11$nom_ips, "redcapLabels"))
+
+

-output

+
> df11$nom_ips1
+[1] Store 1 Store 2
+Levels: Store 1 Store 2
+
+
+

Or use do.call after changing the attribute names with labels and levels

+
 do.call(factor, c(list(df11$nom_ips), 
+    setNames(attributes(df11$nom_ips), c("labels", "levels"))))
+[1] Store 1 Store 2
+Levels: Store 1 Store 2
+
",r +"ReactJS - Modal is enabled inside component

I have a modal that I use on login(/) and home(/posts) pages. In my home page it works, but in the home page it doesn't work. It is displayed inside component that I call it. +The issue GIF: Issue reproduction

+

Any idea how to solve this, please?

+

The project structure folder is:

+
├── src
+│   ├── styles
+│   │   │   ├── globalstyles.tsx
+│   │   │   ├── render-theme.tsx
+│   │   │   ├── theme.ts
+│   ├── components
+│   │   ├── Modal
+│   │   │   ├── index.tsx
+│   │   │   ├── styles.ts
+│   ├── pages
+│   │   ├── Home
+│   │   │   ├── index.tsx
+│   │   │   ├── styles.ts
+│   │   ├── Posts
+│   │   │   ├── index.tsx
+│   │   │   ├── styles.ts
+
+

Besides login and delete post, the modal component will to be used to edit post:

+

Modal code:

+
import { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { env } from '../../environments';
+import { modalTypeEnum } from '../../utils/enum';
+import { Button } from '../Button';
+import { TextInput } from '../TextInput';
+import {
+  LoginModalContainer,
+  LoginModalBackground,
+  LoginModalContent,
+  LoginModalContentHeader,
+  LoginModalContentTitleText,
+  LoginModalContentBody,
+  LoginModalForm,
+  LoginModalContentBodyDeleteConfirm,
+  LoginModalContentBodyDeleteConfirmText,
+} from './styles';
+
+interface ModalProps {
+  type: modalTypeEnum;
+}
+
+export function Modal({ type }: ModalProps) {
+  const [username, setUsername] = useState<string>('');
+  const navigate = useNavigate();
+
+  const handleSubmit = (e: React.FormEvent) => {
+    e.preventDefault();
+    navigate(`${env.ROUTER_UTILS.base.posts}/${username}`);
+  };
+
+  const handleClose = async () => {
+    document.querySelector('.modal-visible')?.classList.add('modal-hide');
+  };
+
+  return (
+    <LoginModalContainer>
+      <LoginModalBackground
+        onClick={() => type !== modalTypeEnum.LOGIN && handleClose()}
+        className={type !== modalTypeEnum.LOGIN ? 'modal-visible' : ''}
+      >
+        <LoginModalContent
+          onClick={(e) => e.stopPropagation()}
+          width={window.innerWidth}
+        >
+          {type === modalTypeEnum.LOGIN && (
+            <LoginModalContentHeader>
+              <LoginModalContentTitleText>
+                Welcome to CodeLeap network!
+              </LoginModalContentTitleText>
+            </LoginModalContentHeader>
+          )}
+          <LoginModalContentBody>
+            {type !== modalTypeEnum.DELETE_POST && (
+              <LoginModalForm onSubmit={handleSubmit}>
+                <TextInput
+                  label={
+                    type === modalTypeEnum.LOGIN
+                      ? 'Please enter your username'
+                      : 'Title'
+                  }
+                  value={username}
+                  onChange={(e) => setUsername(e.target.value)}
+                />
+                <Button
+                  inputValue={username ? true : false}
+                  label="ENTER"
+                  isWhite={false}
+                />
+              </LoginModalForm>
+            )}
+            {type === modalTypeEnum.DELETE_POST && (
+              <LoginModalContentBodyDeleteConfirm>
+                <LoginModalContentBodyDeleteConfirmText>
+                  Are you sure you want to delete this item?
+                </LoginModalContentBodyDeleteConfirmText>
+              </LoginModalContentBodyDeleteConfirm>
+            )}
+          </LoginModalContentBody>
+        </LoginModalContent>
+      </LoginModalBackground>
+    </LoginModalContainer>
+  );
+}
+
+
+

Modal Styles code:

+
import styled, { css } from 'styled-components';
+
+interface LoginModalContentProps {
+  width: number;
+}
+
+export const LoginModalContainer = styled.div`
+  z-index: 9999;
+  display: flex;
+  .modal-visible.modal-hide {
+    display: none;
+  }
+`;
+
+export const LoginModalBackground = styled.div`
+  width: 100vw;
+  height: 100vh;
+  background: ${({ theme }) => theme.colors.modalBackground};
+  position: fixed;
+  top: 0px;
+  left: 0px;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+`;
+
+export const LoginModalContent = styled.div<LoginModalContentProps>`
+  flex-direction: column;
+  max-width: ${(p) => (p.width < 768 ? '' : '500px')};
+  ${({ theme }) => css`
+    background: ${theme.colors.white};
+    width: 85%;
+    min-width: 288px;
+    padding: 30px;
+    box-shadow: rgba(0, 0, 0, 0.6) 0px 7px 29px 0px;
+    display: flex;
+  `}
+`;
+export const LoginModalContentHeader = styled.div`
+  display: flex;
+  align-items: left;
+  margin-bottom: ${({ theme }) => theme.spacings.small};
+`;
+
+export const LoginModalContentTitleText = styled.h1``;
+
+export const LoginModalContentBody = styled.div`
+  display: flex;
+  width: 100%;
+`;
+export const LoginModalForm = styled.form``;
+
+export const LoginModalFormButtonDiv = styled.div`
+  width: 100%;
+  display: flex;
+  justify-content: flex-end;
+  margin-top: ${({ theme }) => theme.spacings.small};
+`;
+export const LoginModalFormConfirmButton = styled.button``;
+export const LoginModalContentBodyDeleteConfirm = styled.div``;
+export const LoginModalContentBodyDeleteConfirmText = styled.p``;
+
+

globalstyle code:

+
import { createGlobalStyle } from 'styled-components';
+import { Theme } from '../types/styled-components';
+
+export const GlobalStyles = createGlobalStyle<Theme>`
+ *{
+  margin: 0;
+  padding: 0;
+  outline: none;
+  box-sizing: border-box;
+}
+
+  html {
+    font-size: 62.5%;
+    scroll-behavior: smooth;
+  }
+
+  body {
+    font-size: 1.6rem;
+    font-family: ${({ theme }) => theme.font.family.default};
+  }
+
+  h1, h2, h3, h4, h5, h6 {
+    font-family: ${({ theme }) => theme.font.family.default};
+    color: ${({ theme }) => theme.colors.primaryColor};
+  }
+  h1 {
+    font-size: ${({ theme }) => theme.font.sizes.large};
+    font-weight: 700;
+  }
+
+  p {
+    margin: ${({ theme }) => theme.spacings.medium} 0 ${({ theme }) =>
+  theme.spacings.small} 0;
+    font-size: 1.125em;
+    color: ${({ theme }) => theme.colors.primaryColor};
+  }
+  /* a {
+    color: ${({ theme }) => theme.colors.primaryColor};
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    transition: all, 0.3s;
+    text-decoration: none;
+    margin: 10px;
+  }
+  a:hover {
+    color: ${({ theme }) => theme.colors.secondaryColor};
+  } */
+
+  button {
+    width: 111px;
+    color: ${({ theme }) => theme.colors.white};
+    cursor: pointer;
+    background: ${({ theme }) => theme.colors.primaryColor};
+    border: 2px solid ${({ theme }) => theme.colors.primaryColor};
+    padding: 5px 20px;
+    font-size: ${({ theme }) => theme.font.sizes.small};
+    transition: all, 0.3s;
+  }
+  button:hover {
+    border-color: ${({ theme }) => theme.colors.secondaryColor};
+  }
+
+  button:disabled {
+      background: ${({ theme }) => theme.colors.mediumGray};
+      border: 2px solid transparent;
+      cursor: not-allowed;
+    }
+
+  input[type='text'] {
+      font-size: ${({ theme }) => theme.font.sizes.large};
+      width: 100%;
+      padding: 5px 10px;
+      border-radius: 4px;
+      &::placeholder {
+        font-size: ${({ theme }) => theme.font.sizes.xsmall};
+      }
+  }
+  textarea {
+      border: 2px solid ${({ theme }) => theme.colors.primaryColor};
+      resize: none;
+      font-size: ${({ theme }) => theme.font.sizes.large};
+      width: 100%;
+      padding: 5px 10px;
+      border-radius: 4px;
+      &::placeholder {
+        font-size: ${({ theme }) => theme.font.sizes.xsmall};
+      }
+  }
+  /* .pressable {
+    cursor: pointer;
+    color: ${({ theme }) => theme.colors.primaryColor};
+    text-decoration: none;
+    border-color: transparent;
+    transition: all, 0.3s;
+  }
+  .pressable:hover {
+    color: ${({ theme }) => theme.colors.secondaryColor};
+  } */
+  form {
+    width: 100%;
+  }
+  .icon-pressable {
+    cursor: pointer;
+    color: ${({ theme }) => theme.colors.white};
+    text-decoration: none;
+    border-color: transparent;
+    transition: all, 0.3s;
+  }
+  .icon-pressable:hover {
+    transform: scale(1.4);
+  }
+`;
+
+
","

position: fixed doesn't work when there is transform css on one of the parent divs of the modal. Please try to not use transform on parent div.

+

So remove the transform: scale() css from parent div it should fix the issue.

",r +"Postgres - Pick 1 max row instead of all max rows in the same month on a LOD (group by)

Hi have a data set which has product, site, station, date and some numerical fields such as sn_count, blob etc. +Within every combination of product, site and station, if there are multiple entries for the same month from different dates, I want to only pick one row with max sn count in that month.

+

The code I have right now is working for the most part. It is filtering out rows with lesser sn counts in that month. But it gives me all rows with the same max sn count. Whereas, I just want 1 from a month.

+

This is my code:

+
FROM insight_info_temp a
+INNER JOIN
+(
+    SELECT distinct b.product_code,b.site_name,b.station_type,to_char(b.date_b, 'YYYY-MM') as date_new, 
+    MAX(dist_sn_count_at_blob) as max_sn
+    FROM insight_info_temp b
+    GROUP BY b.product_code,b.site_name,b.station_type,to_char(b.date_b, 'YYYY-MM')
+) b
+    ON a.product_code = b.product_code and
+    a.site_name = b.site_name and
+    a.station_type = b.station_type and
+    to_char(a.date_b, 'YYYY-MM') = b.date_new
+    AND a.dist_sn_count_at_blob = b.max_sn
+    where a.product_code = 'D00' 
+    and a.site_name = 'F00' and a.station_type = 'A00';
+    
+
+

This is the result I have: +

+

The highlighted rows have the same sn count and is the max sn count for that month. +I however, only want one of these rows. Not both.

","

My guess is that you have two observations with the same dist_sn_count_at_blob.

+

This is a candidate for PostgreSQL's distinct on.

+

Please try something like this:

+
select distinct on (product_code, site_name, station_type, 
+                    to_char(date_b, 'YYYY-MM'))
+       dist_sn_count_at_blob, last_updated_at_pkey, <other columns>
+  from insight_info_temp 
+ where a.product_code = 'D00' 
+   and a.site_name = 'F00' 
+   and a.station_type = 'A00'
+ order by product_code, site_name, station_type, 
+          to_char(date_b, 'YYYY-MM'), dist_sn_count_at_blob desc;
+
",r +"Grouping information by multiple criteria?

so I have a data frame similar to the one below where stamp is an date time index; +for context, it represents orders received and my goal is to match orders that may be the same but have come as two separate orders.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
StampPrice.indicatorEXqty
1234101d12
234530-1d13
+
+

I want to group entries that have the same date time stamp, given that those entries have the same EX and Indicator.

+

I think I know how to do this with just the stamp however I'm unsure how to add the conditions of EX and indicator to the groupby.

+

Beginner here so any help is greatly appreciated!

","

Try this:

+
df.groupby(["Stamp", "EX", "indicator"])
+
+

And if you then want to get the sum of quantities and prices you can do this:

+
df.groupby(["Stamp", "EX", "indicator"]).sum()
+
",r +"Failed returning data from array

i have a problem which that i cannot see the data inside array that i have pushed the data inside .then from axios

+

Here are the sample code +Axios from vue.js

+
export default {
+  name: 'facts',
+  data(){
+    const test = [{id: 'test',name: 'test'}]
+    const response = [];
+    const factsData = () => {
+      axios.get('http://localhost:3000').then(x=>response.push(x.data))
+    }
+    factsData();
+    console.log(response)
+    return{
+      test,
+      response
+    };
+  }
+};
+
+

When i tried to console.log the output data inside the promise(.then) it worked well and display the data that i expected like this +

+

+

and this is what happen when i tried to push the data from axios to response and show the output data in console.log with my current code above

+

+

when i tried to access it (console.log(response[0]), it shows undefined in console.log.

+

+

But strangely, when i back to my previous code to not to tried to access the data and i expand the array in console browser, it shows data that i expected which mean i couldn't access it.

+

+

The main purpose is i want to dipsplay the data to be rendered in table using v-for

+
<template>
+  <div class="about">
+    <center>
+      <table>
+        <thead>
+          <tr>
+            <th></th>
+            <th>ID</th>
+            <th>Username</th>
+          </tr>
+        </thead>
+        <tbody>
+          <tr v-for="(user,index) in test" :key="user.id">
+            <td>{{index + 1}}</td>
+            <td>{{user.id}}</td>
+            <td>{{user.name}}</td>
+          </tr>
+        </tbody>
+      </table>
+    </center>
+  </div>
+</template>
+
+

Please tell me what i'm missing. Thank you.

+

P.S : I'm new to this vue js

","

your code structure is not correct. use this code:

+
export default {
+  name: 'ProfilePage',
+
+  data() {
+    return {
+      response: []
+    }
+  },
+
+  created () {
+    this.getData();
+  },
+
+  methods: {
+    getData() {
+      axios.get('http://localhost:3000').then(x => this.response = x.data);
+    }
+  }
+}
+
",r +"Perform a calculation as a new column on multiindex dataframe

I have the following multiindex dataframe:

+
                                            MSISDN_COUNT
+NAME            DIM1    SEGMENT 
+JAN22           N       Detractor           307
+                        Passive             198
+                        Promoter            1256
+                Y       Detractor           237
+                        Passive             161
+                        Promoter            1096
+FEB22           N       Detractor           313
+                        Passive             222
+                        Promoter            1260
+                Y       Detractor           261
+                        Passive             169
+                        Promoter            1155
+
+

I want to create a new column, which will be calculated for each NAME and for each DIM1.

+

The calculation is: +((Promoter - Detractor) / (Promoter + Passive + Detractor) )* 100

+

So the expected output is

+
                                            MSISDN_COUNT    OUT
+NAME            DIM1    SEGMENT 
+JAN22           N       Detractor           307             53.88
+                        Passive             198
+                        Promoter            1256
+                Y       Detractor           237             57.49
+                        Passive             161
+                        Promoter            1096
+FEB22           N       Detractor           313             52.76
+                        Passive             222
+                        Promoter            1260
+                Y       Detractor           261             56.4
+                        Passive             169
+                        Promoter            1155
+
+

I can't figure out how to do this with the multi-level index dataframe.

+

Any help is appreciated!

","

Use DataFrame.xs for select DataFrames for 3 level, apply your formula, add third level SEGMENT with value Detractor and assign back:

+
Promoter = df.xs('Promoter', level=2)
+Detractor = df.xs('Detractor', level=2)
+Passive = df.xs('Passive', level=2)
+
+s = ((Promoter - Detractor) / (Promoter + Passive + Detractor) )* 100
+
+df['OUT'] = s.assign(SEGMENT='Detractor').set_index('SEGMENT', append=True)
+print (df)
+                      MSISDN_COUNT        OUT
+NAME  DIM1 SEGMENT                           
+JAN22 N    Detractor           307  53.889835
+           Passive             198        NaN
+           Promoter           1256        NaN
+      Y    Detractor           237  57.496653
+           Passive             161        NaN
+           Promoter           1096        NaN
+FEB22 N    Detractor           313  52.757660
+           Passive             222        NaN
+           Promoter           1260        NaN
+      Y    Detractor           261  56.403785
+           Passive             169        NaN
+           Promoter           1155        NaN
+
+

Details:

+
print (s)
+            MSISDN_COUNT
+NAME  DIM1              
+JAN22 N        53.889835
+      Y        57.496653
+FEB22 N        52.757660
+      Y        56.403785
+      
+print (s.assign(SEGMENT='Detractor').set_index('SEGMENT', append=True))
+                      MSISDN_COUNT
+NAME  DIM1 SEGMENT                
+JAN22 N    Detractor     53.889835
+      Y    Detractor     57.496653
+FEB22 N    Detractor     52.757660
+      Y    Detractor     56.403785
+
",r +"Sum conditional on difference between timestamps

Let's say we observe a video game player collecting points. Each observation reports how many points the player has collected since the last visit. Now I want to create an additional variable indicating how many points the user has collected during the last x (e.g., 90) seconds, including the current observation.

+

Example data:

+
example_da = data.frame(time = c("2015-04-11 21:24:34", "2015-04-11 21:24:50", "2015-04-11 21:25:20", "2015-04-11 21:27:52", "2015-04-11 21:27:59", "2015-04-11 21:28:13",
+                                 "2015-04-11 21:30:06", "2015-04-11 21:31:05", "2015-04-11 21:31:47", "2015-04-11 21:38:01", "2015-04-11 21:39:05", "2015-04-11 21:40:06"),
+                        points = c(2,3,1,6,2,5,1,1,3,5,2,4))
+
+> example_da
+                  time points
+1  2015-04-11 21:24:34      2
+2  2015-04-11 21:24:50      3
+3  2015-04-11 21:25:20      1
+4  2015-04-11 21:27:52      6
+5  2015-04-11 21:27:59      2
+6  2015-04-11 21:28:13      5
+7  2015-04-11 21:30:06      1
+8  2015-04-11 21:31:05      1
+9  2015-04-11 21:31:47      3
+10 2015-04-11 21:38:01      5
+11 2015-04-11 21:39:05      2
+12 2015-04-11 21:40:06      4
+
+

For instance, for observation 3 ("2015-04-11 21:25:20") we sum up the points of "2015-04-11 21:24:34" (= 2), "2015-04-11 21:24:50" (=3), "2015-04-11 21:25:20" (=1), since these points were all collected during the preceding 90 seconds, resulting in 6 points for our new variable "sum_points_preceding_90_seconds".

+
> target_da = data.frame(time = c("2015-04-11 21:24:34", "2015-04-11 21:24:50", "2015-04-11 21:25:20", "2015-04-11 21:27:52", "2015-04-11 21:27:59", "2015-04-11 21:28:13",
++                                 "2015-04-11 21:30:06", "2015-04-11 21:31:05", "2015-04-11 21:31:47", "2015-04-11 21:38:01", "2015-04-11 21:39:05", "2015-04-11 21:40:06"),
++                        points = c(2,3,1,6,2,5,1,1,3,5,2,4),
++                        sum_points_preceding_90_seconds = c(2, 5, 6, 6, 8, 13, 1, 2, 5, 5, 7, 6))
+> 
+> 
+> target_da                    
+                  time points sum_points_preceding_90_seconds
+1  2015-04-11 21:24:34      2                               2
+2  2015-04-11 21:24:50      3                               5
+3  2015-04-11 21:25:20      1                               6
+4  2015-04-11 21:27:52      6                               6
+5  2015-04-11 21:27:59      2                               8
+6  2015-04-11 21:28:13      5                              13
+7  2015-04-11 21:30:06      1                               1
+8  2015-04-11 21:31:05      1                               2
+9  2015-04-11 21:31:47      3                               5
+10 2015-04-11 21:38:01      5                               5
+11 2015-04-11 21:39:05      2                               7
+12 2015-04-11 21:40:06      4                               6
+
","

You can do this with the slider package using slide_index_sum(). It allows you specify an index and then create bounds before or after each element of that index to generate the sliding windows.

+

I think there may be an error with your expected result for 2015-04-11 21:31:47? It looks like it should result in 4 rather than 5?

+

You may need to adjust before depending on your exact requirements.

+
library(slider)
+library(dplyr)
+
+example_da <- tibble(
+  time = c(
+    "2015-04-11 21:24:34", "2015-04-11 21:24:50", "2015-04-11 21:25:20", 
+    "2015-04-11 21:27:52", "2015-04-11 21:27:59", "2015-04-11 21:28:13",
+    "2015-04-11 21:30:06", "2015-04-11 21:31:05", "2015-04-11 21:31:47", 
+    "2015-04-11 21:38:01", "2015-04-11 21:39:05", "2015-04-11 21:40:06"),
+  points = c(2,3,1,6,2,5,1,1,3,5,2,4)
+)
+
+example_da <- mutate(example_da, time = as.POSIXct(time, "UTC"))
+
+# The current time + 89 seconds before it = 90 seconds total
+example_da <- example_da %>%
+  mutate(
+    sum_points_preceding_90_seconds =
+      slide_index_sum(
+        x = points,
+        i = time,
+        before = 89
+      )
+  )
+
+example_da
+#> # A tibble: 12 × 3
+#>    time                points sum_points_preceding_90_seconds
+#>    <dttm>               <dbl>                           <dbl>
+#>  1 2015-04-11 21:24:34      2                               2
+#>  2 2015-04-11 21:24:50      3                               5
+#>  3 2015-04-11 21:25:20      1                               6
+#>  4 2015-04-11 21:27:52      6                               6
+#>  5 2015-04-11 21:27:59      2                               8
+#>  6 2015-04-11 21:28:13      5                              13
+#>  7 2015-04-11 21:30:06      1                               1
+#>  8 2015-04-11 21:31:05      1                               2
+#>  9 2015-04-11 21:31:47      3                               4
+#> 10 2015-04-11 21:38:01      5                               5
+#> 11 2015-04-11 21:39:05      2                               7
+#> 12 2015-04-11 21:40:06      4                               6
+
",r +"Docker compose can't correct build react app

I have api (net-core) and react-app projects in root folder. I start dockerize my project from react application. If docker-compose and docker file in same react-app folder, dockerize works correct. But i want in future start two docker from root folder. This my folder structure:

+
root
+      ├ client-app
+      │  ├ node_modules
+      │  ├ public
+      │  ├ src
+      │  │  ├ etc folders and files
+      │  ├ Dockerfile
+      │  ├ package.json
+      │  └ package-lock.json
+      ├ api folder
+      └ docker-compose.yml
+
+

This is dockerfile:

+
FROM node:alpine
+WORKDIR /client-app
+ENV PATH="./node_modules/.bin:$PATH"
+COPY ./client-app/package.json /client-app/
+RUN npm install
+COPY ./client-app/ /client-app/
+RUN npm run build
+
+

This is docker-compose:

+
version: "3.4"
+services:
+  app:
+    build:
+      context: .
+      dockerfile: client-app/Dockerfile
+    volumes:
+      - .:/client-app
+    ports:
+      - "3000:3000"
+    image: app/react
+    container_name: app_container
+    command: npm start
+
+

Then i start dockerize from root folder docker-compose up:

+
 => exporting to image                                                                                                                           4.4s 
+ => => exporting layers                                                                                                                          4.4s 
+ => => writing image sha256:38172c4db5efba2b309f84f3c0b6c02e1ecbae89e611f1899205f663a805646e                                                     0.0s 
+ => => naming to app/react                                                                                                                       0.0s 
+
+Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
+[+] Running 2/1
+ - Network larchkiktest_default     Created                                                                                                      0.0s 
+ - Container app_container  Created                                                                                                              0.1s
+Attaching to app_container
+app_container  | npm ERR! code ENOENT
+app_container  | npm ERR! syscall open
+app_container  | npm ERR! path /client-app/package.json
+app_container  | npm ERR! errno -2
+app_container  | npm ERR! enoent ENOENT: no such file or directory, open '/client-app/package.json'
+app_container  | npm ERR! enoent This is related to npm not being able to find a file.
+app_container  | npm ERR! enoent
+app_container  |
+app_container  | npm ERR! A complete log of this run can be found in:
+app_container  | npm ERR!     /root/.npm/_logs/2022-04-10T18_00_24_224Z-debug-0.log
+app_container exited with code 254
+
+

If i change folders in dockerfile, like this: +COPY package.json ./ or COPY . . then docker fail install packages or build project because can't find files. How i can fix build react app from root folder? Thank you.

","

I resolved error. Need to change Workdir /usr/src/app. Now my files are like this:

+
FROM node:alpine
+WORKDIR /usr/src/app
+ENV PATH="./node_modules/.bin:$PATH"
+COPY ./client-app/package*.json .
+RUN npm install
+COPY ./client-app/ .
+RUN npm run build
+
+version: "3.4"
+services:
+  app:
+    build:
+      context: .
+      dockerfile: client-app/Dockerfile
+    volumes:
+      - ./:/app
+    ports:
+      - "3000:3000"
+    image: app/react
+    container_name: app_container
+    command: npm start
+
",r +"How to execute generic query in ArangoJs?

I need to execute the following query:

+
const query = `FOR u IN ${collection} FILTER ${filter} RETURN u`
+
+

so that filter variable is generated somehow by me (it is corrects, checked with Arango console)

+

But

+
db.query(query)
+
+

always returns empty cursor, and

+
db.query(aql`FOR u IN ${db.collection(collection)} FILTER ${filter} RETURN u`)
+
+

ignores my filter - data is not filtered.

+

How to execute query with arangojs with pre-generated filter?

",

Fix: db.query(query).all() worked

,r +"Why I get this ts error when I want to add custom style to my image component?

I want to add my own style else I want to add an css image object. But I get this err:

+
No overload matches this call.
+  Overload 1 of 2, '(props: ImageProps | Readonly<ImageProps>): Image', gave the following error.
+    Type 'false | ViewStyle | RegisteredStyle<ViewStyle> | RecursiveArray<Falsy | ViewStyle | RegisteredStyle<ViewStyle>> | { ...; }' is not assignable to type 'StyleProp<ImageStyle>'.
+      Type 'ViewStyle' is not assignable to type 'StyleProp<ImageStyle>'.
+        Type 'ViewStyle' is not assignable to type 'ImageStyle'.
+          Types of property 'overflow' are incompatible.
+            Type '"visible" | "hidden" | "scroll" | undefined' is not assignable to type '"visible" | "hidden" | undefined'.
+              Type '"scroll"' is not assignable to type '"visible" | "hidden" | undefined'.
+  Overload 2 of 2, '(props: ImageProps, context: any): Image', gave the following error.
+    Type 'false | ViewStyle | RegisteredStyle<ViewStyle> | RecursiveArray<Falsy | ViewStyle | RegisteredStyle<ViewStyle>> | { ...; }' is not assignable to type 'StyleProp<ImageStyle>'.ts(2769)
+index.d.ts(3809, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Image> & Readonly<ImageProps> & Readonly<{ children?: ReactNode; }>'
+index.d.ts(3809, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Image> & Readonly<ImageProps> & Readonly<{ children?: ReactNode; }>'
+
+

Code:

+
...
+export interface IImageSlider {
+  ImageStyle?: StyleProp<ViewStyle>;
+}
+
+<Image source={{uri: item.photo}} style={ImageStyle ?? s.image} resizeMode='contain' />
+
+const s = StyleSheet.create({...})
+
+

The error comes on style={...}

+

What I am doing wrong ?

","

You must use ImageStyle from react-native since the Image components can has props that Views doesn't

+
export interface IImageSlider {
+  ImageStyle?: StyleProp<ImageStyle>;
+}
+
",r +"title: 'Unsupported Authentication', detail: 'Authenticating with OAuth 2.0 Application-Only is …OAuth 1.0a User Context, OAuth 2.0 User Context].'

I am using a Cloudflare worker and this is what my index.ts file looks like:

+
const tweet = async () => {
+  console.log('tweet function ran')
+  let request = await fetch("https://api.twitter.com/2/tweets", {
+    method: "POST",
+    headers: {
+      Authorization: "Bearer <ACCESS TOKEN HERE>",
+      'user-agent': "v2CreateTweetJS",
+      'content-type': "application/json",
+      'accept': "application/json"
+    },
+    body: JSON.stringify({"text": "my remote Tweet"})
+  })
+  console.log(await request.json())
+  return new Response("This response ran")
+}
+
+addEventListener('fetch', (event: FetchEvent) => {
+  event.respondWith(tweet());
+});
+
+

And when I run this code, I get this error:

+
<myusername>@<mycomputername> <myappname> % wrangler dev
+  Listening on http://127.0.0.1:8787
+  Detected changes...
+  Ignoring stale first change
+tweet function ran
+{ title: 'Unsupported Authentication', detail: 'Authenticating with OAuth 2.0 Application-Only is …OAuth 1.0a User Context, OAuth 2.0 User Context].', type: 'https://api.twitter.com/2/problems/unsupported-authentication', status: 403 }
+[2022-04-23 21:41:58] GET <myappname>.<mycloudflarworkername>.workers.dev/ HTTP/1.1 200 OK
+^C
+<myusername>@<mycomputername> <myappname> % 
+
+

How do I fix this? I would be fine with switching to v1 APIs but I can't find any info on how to do that either.

","

The error message

+
Authenticating with OAuth 2.0 Application-Only
+
+

Indicates that the bearer token sent in the API request represents the application and not the user on whose behalf the tweet is sent. You need to obtain a token for the user who is sending the tweet.

+

Tweet api only accepts user context authentication as per this:

+

https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

+

However, the error seems to indicate that both OAuth 1.0 and OAuth 2.0 are supported.

+

The other documentation page +confirms this by saying:

+

Please note that OAuth 1.0a is still required to issues requests on behalf of users.

+

https://developer.twitter.com/en/docs/authentication/oauth-2-0/application-only

+

So you should be fine with both methods.

+

OAuth 1.0a auth header is described here

+

https://developer.twitter.com/en/docs/authentication/oauth-1-0a/authorizing-a-request

",r +"Import table content from one database of one environment and write to other environment using XQUERY transformation in MARKLOGIC

I am being asked to work on a POC which is -

+

import data from one database from one environment and import the data to another environment using XQuery transformation in MarkLogic.

+

I am not sure if that can be possible as I understand that XQuery is basically used to transform any data within tables in same environment. +If the requirement is to import/export data to/from Marklogic , would not be the Marklogic Data Hub the only option? Or this can be achieved using XQuery too?

","

There are many options for exporting and importing data.

+

If there is a LOT of data, then backup/restore, flexible replication, or MLCP copy or archive might be your best bet.

+

You can always move the data within an XQuery module. You can read the document (if executing on the source system, using fn:doc() or if pulling from a remote system, using the REST endpoints such as /v1/documents or v1/search) and then insert with xdmp:document-insert() or sending to /v1/documents using xdmp:http-* methods. If there are a ton of docs to move, you may want to orchestrate those actions with a batch tool, such as CoRB, and execute the XQuery module for each document in a separate transaction.

",r +"Find Minimum Timestamp From 2 Users POSTGRES

This is my table_gamers:

+
+ + + + + + + + + + + + + + + + + + + + + + + +
game_iduser1user2timestamp
18901232022-01-01
21237682022-02-09
+
+

I need to find for each user:

+
    +
  • The first user they played.
  • +
  • Their first game ID.
  • +
  • Their MIN timestamp (timestamp from their first game).
  • +
+

This is what I need:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UserUser They PlayedGame IDtimestamp
89012312022-01-01
12389012022-01-01
76812322022-02-09
+
+

This is my query:

+
SELECT user1 FROM table_gamers WHERE MIN(timestamp)
+UNION ALL 
+SELECT user1 FROM table_gamers WHERE MIN(timestamp)
+
+

How do I query each User's First Opponent? I am confused.

","

doing step by step by some with_clauses: +first get all matches user1-user2, user2-user1 +second give some ids by ordering by timestamp +third get what you want:

+
with base_data as (
+select game_id,user1,user2,timestamp from table_gamers
+union all 
+select game_id,user2,user1,timestamp from table_gamers
+),
+base_id as (
+select
+  row_number() over (order by base_data.timestamp) as id,
+  row_number() over (PARTITION by base_data.user1 order by base_data.timestamp) as id_2,
+  *
+  from base_data
+)
+ 
+select * from base_id
+where id_2 = 1 order by timestamp
+
+

retults in

+
id  id_2    game_id user1   user2   timestamp
+2   1   1   123 890 2022-01-01T00:00:00.000Z
+1   1   1   890 123 2022-01-01T00:00:00.000Z
+4   1   2   768 123 2022-02-09T00:00:00.000Z
+
+

i hope that gives you the right idea

+

https://www.db-fiddle.com/f/9PrxioFeVaTmtVcYdteovj/0

",r +"Why does free() of a struct result in segfault (wrong usage of pointers)?

When I try to free my struct, the program crashes because of a segfault. Inspecting the program with valgrind I have found:

+
==9761== Invalid free() / delete / delete[] / realloc()
+==9761==    at 0x484827F: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
+==9761==    by 0x109242: destroyHashTable (hashtable.c:38)
+==9761==    by 0x10942E: main (hashtable_main.c:17)
+==9761==  Address 0x1ffefffa70 is on thread 1's stack
+==9761==  in frame #2, created by main (hashtable_main.c:7)
+
+

I cannot really say anything more useful than having no idea, how to solve it. The crash happens during the free(ht) in destroyHashTable(ht) in hashtable.c. What am I doing wrong?

+

Below the code hashTable_main.c:

+
#include <stdio.h>
+#include <stdlib.h>
+
+
+#include "hashtable.h"
+
+int main() {
+
+    hashTable* ht = NULL;
+
+    initHashTable(&ht);
+
+    int totalColCount = 0;
+
+    totalColCount += addHashTableEntry(&ht, "PRPR2");
+
+    destroyHashTable(&ht);
+
+    return EXIT_SUCCESS;
+}
+
+

hashtable.c:

+
#include <stdlib.h>
+#include <stdio.h>
+
+
+#include "hashtable.h"
+
+/* private internal API */
+int hash_funktion(char *string);
+hashtableEntry* createTableEntry(char* newKey) ;
+/* end of private internal API */
+
+
+int hash_funktion(char *string) {
+    unsigned int hash_adresse;
+    unsigned char *pointer;
+    hash_adresse = 0;
+    pointer = (unsigned char *) string;
+    while(*pointer != '\0') {
+        hash_adresse = 19 * hash_adresse + *pointer;
+        pointer++;
+    }
+    return hash_adresse % MAX_HASH;
+}
+
+hashtableEntry* createTableEntry(char* newKey) {
+     hashtableEntry* e = (hashtableEntry*) malloc (sizeof(hashtableEntry));
+     e->hashKey = newKey;
+     return e;
+}
+
+void initHashTable(hashTable* ht) {
+    ht = (hashTable*) malloc (sizeof (struct hashTable));
+    ht->table = (hashtableEntry*) malloc (MAX_HASH * sizeof (hashtableEntry));
+}
+
+void destroyHashTable(hashTable* ht) {
+    if (ht) {
+        free(ht);
+        ht = NULL;
+    }
+}
+
+int  addHashTableEntry(hashtableEntry* ht, char* keyValue) {
+    hashtableEntry *e = createTableEntry(keyValue);
+
+    int colCounter = 0;
+
+    int hashValue = hash_funktion(keyValue);
+
+    if (ht[hashValue].hashKey == NULL) {
+        ht[hashValue] = *e;
+        return 0;
+    } else {
+        int newVal = (hashValue + 1) % MAX_HASH;
+        colCounter++;
+        while (ht[newVal].hashKey != NULL && newVal != hashValue ) {
+            newVal = (newVal + 1) % MAX_HASH;
+            colCounter++;
+        }
+        if (newVal != hashValue) {
+            ht[newVal] = *e;  
+            return colCounter;      
+        } else {
+            return -1;
+        }
+    }
+}
+
+bool searchValue(hashtableEntry* ht, char* searchValue) {    
+    for (int i = 0; i < MAX_HASH; i++)
+    {
+        if(ht[i].hashKey == searchValue) {
+            return true;
+        }
+    }
+    return false;
+}
+
+

and hashtable.h:

+
#pragma once
+
+#define MAX_HASH 20
+#include <stdbool.h>
+
+typedef struct hashtableEntry {
+    char* hashKey;
+} hashtableEntry;
+
+typedef struct hashTable {
+    hashtableEntry* table;
+    int elemCount;
+} hashTable;
+
+void initHashTable(hashTable* ht);
+
+void destroyHashTable(hashTable* ht);
+
+int  addHashTableEntry(hashtableEntry* ht, char* keyValue);
+
+bool searchValue(hashtableEntry* ht, char* searchValue);
+
","

There never was a hashtable to begin with. The issue lies in initHashTable. It should be accepting a double pointer since it is given a pointer to a pointer it should initialize. The reason it can segfault despite the check in destroyHashTable is that the pointer is left uninitialized and may be non-zero at the start of program execution.

+
void initHashTable(hashTable** ht) {
+    *ht = (hashTable*) malloc (sizeof (struct hashTable));
+    (*ht)->table = (hashtableEntry*) malloc (MAX_HASH * sizeof (hashtableEntry));
+}
+
+

You may find it easier to instead return the newly created hash table. This better expresses that initHashTable is giving you a new hashTable * value.

+
hashTable *initHashTable() {
+    hashTable *ht = (hashTable *) malloc (sizeof (struct hashTable));
+    ht.table = (hashtableEntry *) malloc (MAX_HASH * sizeof (hashtableEntry));
+    return ht;
+}
+
+

There are also a bunch of other places where pointers are not handled correctly.

+
void doThing(Foo *foo) {
+    // This changes foo, but not the data foo points to.
+    foo = something;
+    // This changes the data foo points to
+    *foo = someOtherThing;
+}
+
+void doStuff() {
+    Foo *foo;
+
+    // This is incorrect since it creates a double pointer. doThing would need to
+    // be defined as "void doThing(Foo **foo)" to be correct.
+    doThing(&foo);
+
+    // Instead we can just pass the existing pointer
+    doThing(foo);
+
+
+    // We only need to create a reference if the value does not start out as a pointer
+    Foo bar;
+    doThing(&bar);
+}
+
",r +"Android - using activity getters from custom RecyclerView adapter

I've got the following classes:

+

MatchActivity.java:

+
public void setDart1(int playerIndex, int points) {
+        getDart1().set(playerIndex, points);
+    }
+
+    public ArrayList<Integer> getDart1() {
+        return dart1;
+    }
+
+    public void setDart2(int playerIndex, int points) {
+        getDart2().set(playerIndex, points);
+    }
+
+    public ArrayList<Integer> getDart2() {
+        return dart2;
+    }
+
+    public void setDart3(int playerIndex, int points) {
+        getDart3().set(playerIndex, points);
+    }
+
+    public ArrayList<Integer> getDart3() {
+        return dart3;
+    }
+
+

MatchActivityPlayerAdapter.java:

+
package de.tkirchmann.myaveragev3;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.constraintlayout.widget.ConstraintLayout;
+import androidx.recyclerview.widget.RecyclerView;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class MatchActivityPlayerAdapter extends RecyclerView.Adapter<MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder> {
+
+    private final List<Player> playerList;
+    private final Match match;
+    private Context context;
+
+    MatchActivityPlayerAdapter(List<Player> playerList, Match match) {
+        this.playerList = playerList;
+        this.match = match;
+    }
+
+    @NonNull
+    @Override
+    public MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.match_activity_row_layout, parent, false);
+        return new MatchActivityPlayerRowViewHolder(view);
+    }
+
+    @Override
+    public void onBindViewHolder(@NonNull MatchActivityPlayerAdapter.MatchActivityPlayerRowViewHolder holder, int position) {
+        final Player player = playerList.get(position);
+        MatchActivity matchActivity = new MatchActivity();
+
+        holder.nameTextView.setText(player.getPlayerName());
+        holder.pointsTextView.setText(matchActivity.getRemainingPoints().get(position));
+        holder.dart1.setText(matchActivity.getDart1().get(position));
+        holder.dart2.setText(matchActivity.getDart2().get(position));
+        holder.dart3.setText(matchActivity.getDart3().get(position));
+        holder.dartsCombined.setText(matchActivity.getDartsCombined().get(position));
+        /*holder.averageTextView.setText(matchActivity.getAverage().get(position));*/
+    }
+
+    @Override
+    public int getItemCount() {
+        return playerList.size();
+    }
+
+    class MatchActivityPlayerRowViewHolder extends RecyclerView.ViewHolder {
+        public TextView nameTextView, pointsTextView, averageTextView, dart1, dart2, dart3, dartsCombined;
+
+        public MatchActivityPlayerRowViewHolder(View playerRowView) {
+            super(playerRowView);
+            final ConstraintLayout playerRowRootLayout = playerRowView.findViewById(R.id.match_player_row_root_layout);
+            nameTextView = playerRowView.findViewById(R.id.name);
+            pointsTextView = playerRowView.findViewById(R.id.points);
+            averageTextView = playerRowView.findViewById(R.id.average);
+            dart1 = playerRowView.findViewById(R.id.dart1);
+            dart2 = playerRowView.findViewById(R.id.dart2);
+            dart3 = playerRowView.findViewById(R.id.dart3);
+            dartsCombined = playerRowView.findViewById(R.id.last_darts_combined);
+        }
+    }
+}
+
+

In the onBindViewHolder() method in the custom adapter I want to set the texts of my views by getting the values from the lists via getters from my activity. But I am getting a IndexOutOfBoundsException, so I propably don't have a correct reference/context when calling the getters.

+

How can I get the correct context/reference to my activity?

","

You can try this:

+
((YourActivityName) itemView.getContext()).getDart1();
+
+

and then so on for other getters. You can use any public method using this.

",r +"How to connect db ID to a db Value in javascript?

So I got a function that executes every X minutes/hours, when it executes it will select a random database array value, when it does, the selected will get + 1. Selected stands for the amount of times the row has been selected.

+
id: 5 name: tom selected: 17
+id: 8 name: tim selected: 12
+id: 2 name: tombie selected: 5
+id: 3 name: timbie selected: 4
+
+

This is my code from which I catch all of my database values

+
function setValue (value) {
+  console.log("Array", value);
+  result_arr = Object.values(JSON.parse(JSON.stringify(value)));
+  return result_arr;
+  
+}
+console.log("arr", result_arr);
+db.connect(function(err) {
+    db.query("SELECT * FROM developers", (err, result, fields) => {
+        if (err) {
+        console.log(err);
+        } else {
+        // selected = all.map(item => item.selected);
+        console.log("result", result);
+        setValue(result);
+        console.log("value", setValue(result));
+        removeMax()
+        
+        }
+    })
+
+

Lets say if we have Selected: 5, 4, 12 and 17. 17 is the highest selected count, to avoid it gaining more selected points, I ensure the highest numbers is removed from the array. Once the highest number is removed, I shuffle the numbers and it will select a random one.

+
function removeMax() {
+    const max = Math.max(result_arr.map(item => item.selected));
+    const newArr = result_arr.map(item => item.selected).filter(number => number !== max);
+    var shufflearray = newArr[Math.floor(Math.random()*newArr.length)];
+    return shufflearray;
+    
+}
+
+

Lets say from the shuffle I get 5. I now have to add + 1 to this, so 5 must become 6.

+

In function hi() I have an If statement, everyday at 8 am this code has to be executed. So as I said, I have to update the selected value.

+

Here comes the question: +Usually I would do UPDATE developers SET selected = 6 WHERE id = 2. but since I have multiple rows this wont work. Today It might be Timbie, tommorow It can be Tim. +How do I link the selected values with their IDs?

+
function hi() {
+    window.setInterval(function(){
+        var date = new Date();
+        if (date.getHours() === 8 && date.getMinutes() === 0) {
+            if (test) {
+                db.query( `UPDATE developers SET selected = ? WHERE id = ${item.id} `,[selected, id],
+                (err, result) => {
+                    if (err) {
+                        console.log(err);
+                    } else {
+                        res.send(result);
+                    }
+                });
+            }
+  
+
+
+
+
+
+        }
+        else {
+            const abort = "abort"
+        }
+    }, 60000);
+}
+
","

In the function removeMax(), the data is reduced to become just a list of the selected values. You would need to keep each item, not only the number of times it is selected.

+

Original code:

+
function removeMax() {
+    const max = Math.max(result_arr.map(item => item.selected));
+    const newArr = result_arr.map(item => item.selected).filter(number => number !== max);
+    var shufflearray = newArr[Math.floor(Math.random()*newArr.length)];
+    return shufflearray;
+    
+}
+
+

Original result:

+
var result_arr = [{'id': 1, 'selected': 10}, {'id': 2, 'selected': 5}, {'id': 3, 'selected': 15}, {'id': 4, 'selected': 7}]
+
+newArr = result_arr.map(item => item.selected)
+resulting newArr: [10, 5, 15, 7]
+
+

After that, you are removing the largest value. +Notice how all the id's are gone?

+

If you instead do:

+
newArr = result_arr.filter(item => item.selected !== max)
+
+resulting newArr: [{id: 1, selected: 10}, {id: 2, selected: 5}, {id: 4, selected: 7}]
+
+

Now that you have an array of objects, you can rearrange them as before, and afterwards access the # of selected with item.selected, and each id with item.id.

",r +"Is there a better way to joining updates from two keyed streams than time window I am doing?

So what I have is a Flink job that receives a message from Kafka and will create two updateObject events that are then sent through the job. For simplicity, one is an increase event and the other is a decrease event (So message comes in, business logic dictates what updateObjects to create so state is updated properly).

+

To give a sample updateObject:

+
{
+   "batchId":"b1",
+   "type":"increase",
+   "amount":1,
+   "stateToUpdate":"stateAlpha",
+   "stateToUpdateValue":null
+}
+
+

The updateObjects are then sent downstream in the job. Stream is keyed by a value which will have updateObject1 update one state and updateObject2 update a different one by the key. After each updates their state the updated value is in put into the updateObject's stateToUpdateValue and each is sent along through the job.

+

Now the piece that is tricky is the last step. The final output of the job is an array of the updateObjects from each message. The best idea that could be thought of was to have a tumbling time window of 1 second that collects updateObjects and then when it triggers after 1 second it will check all that are in its window and pair the ones with the same batchId and put them in the final output object and then output it. Obviously this is not one not guaranteeing all may have gotten to that window in the 1 second time, but it also causes a delay in processing since things just sit there.

+

There is not guarantee that there is always two updateObjects created for every message since its very much a case-by-case type of thing. And since the updateObjects get split into different keyed streams because their keys are always different, it can't be that a single object goes through the first keyed state and updates it and then goes through the next one with a single object that gets updated accordingly for each. Once the keying happens they aren't attached so to speak.

+

So I wanted to know if anyone could think of a better way to do this as I feel like there definitely has to be.

","

You are right to suspect that there's a better way to do this.

+

Doing this with tumbling windows has two problems:

+
    +
  1. You are going to wait half a second, on average, and one second at worst, for something that typically won't take that long.
  2. +
  3. Despite the fact that you're often spending all this time waiting around, this approach based on windows can still rather easily get things wrong. Even if a batch has only two events, and even if they are processed within a few milliseconds of each other, they can still fall on opposite sides of the window boundaries. This is because a one-second-long window is going to be from 12:00:00.000 to 12:00:00:999, for example, and your events might show up at 12:00:00.999 and 12:00:01.001.
  4. +
+

Here's an alternative:

+

At the end of your pipeline, re-key the stream by the batchId, and then use a KeyedProcessFunction to glue the batches back together.

+

For example, as each record belonging to a specific batch arrives, append it to a keyed ListState object. If you know exactly how many records belong to each batch, then you can keep a counter in ValueState, and when the batch is complete, you can iterate over the list and produce the final result (and don't forget to clear the state when you're finished with it). Or you can use a keyed Timer to wait for some specific duration (relative to the arrival of the first record from each batch), and produce the final result when the Timer fires.

+

There are examples of working with state and with process functions in the tutorials in Flink's documentation, and in the accompanying training exercises.

+

Alternatively, you could do this with Flink SQL, using OVER windows.

",r +"Opening a c# sqlite-net-sqlcypher database in a SQLite manager and vice versa

Situation : Windows 11 - Latest updates; .NET 6 console app - latest updates; sqlite-net-sqlcypher nuget package (1.8.116) - also latest version; Both Visual Studio (2019 and 2022) and Rider - All latest versions)

+

I have created a little test application (see below)

+
var options = new SQLiteConnectionString(databasePath, true, "testpassword");
+var db = new SQLiteConnection(options);
+
+db.CreateTable<AttributionRecord>();
+
+db.InsertOrReplace(new AttributionRecord(-1, "Test01", "Me", "Test Attribution 01"));
+
+string queryString = "select * from AttributionRecord";
+
+List<AttributionRecord> list = db.Query<AttributionRecord>(queryString);
+
+foreach (AttributionRecord attributionRecord in list)
+{
+    Console.WriteLine($"{attributionRecord.Id} - For Who : {attributionRecord.AttributionForWho} - For What : {attributionRecord.AttributionForWhat} - Attribution : {attributionRecord.Attribution}");
+}
+
+

That all works fine and I (finally) have an encrypted SQLite database. But when I try to open one of my newly created databases in either DB Browser (older versions (3.10.1) and newer versions (3.12.1)) and even in a bought app : SQLiteManager (Version 4.8.3) (from SQLabs : https://www.sqlabs.com/sqlitemanager.php +indicated that they support sqlcypher encrypted databases), I just cannot seem to open the database.

+

The reverse is also true, when I try to open a database protected with sqlcypher and created via the managers, I cannot open it in c# (sqlite exception - file is not a database).

+

This is not a duplicate of some other question on stackoverflow and I have tried all what was to find on it. For the older DB Browser, I used 4096 as the page size as that was advertised as the default page size for sqlcypher databases.

","

With SQLiteStudio (version 3.3.3) I can open and edit my encrypted databases and tables.

+

I'm just a little disappointed that a commercial product like SQLiteManager is unable to do what a free product can.

+

To be honest, I had never heard from SQLiteStudio before, but it is a nice open source project that does the job.

",r +"Serial Comunnication between Java and Arduino

I'm writing a code to send and receive data using the serial port of an arduino, for that I'm using the jserialcomm library. For sending and receiving data, I'm using a DataListener of the library which detect whether or not a bunch of bytes has been sent or received, the problem is that DataListener uses a method called getListneningEvents to list the events which the the DataListener will be able to use, but you can only return one of them because is overwriting an abstract method who returns only one integer, the documentation says that you can return one or more events but I trully don't know how to do it, if you can help with that pls.

+
public class MessageListener implements SerialPortMessageListener{
+@Override
+public int getListeningEvents() { 
+    return SerialPort.LISTENING_EVENT_DATA_WRITTEN;
+    // return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
+    // I want to return both methods
+}
+
+
+@Override
+public byte[] getMessageDelimiter(){ 
+    return new byte[] {
+        (byte)0x0A
+    }; 
+}
+
+@Override
+public boolean delimiterIndicatesEndOfMessage(){ 
+    return true; 
+}
+
+@Override
+public void serialEvent(SerialPortEvent event){
+    switch (event.getEventType()) {
+        //Evento para datos enviados
+        case SerialPort.LISTENING_EVENT_DATA_WRITTEN:
+            System.out.println("All bytes were successfully transmitted!");
+            break;
+        
+        //Evento para datos recibidos
+        case SerialPort.LISTENING_EVENT_DATA_RECEIVED:
+            byte[] delimitedMessage = event.getReceivedData();
+            String mensaje = new String(delimitedMessage, StandardCharsets.UTF_8);
+            mensaje = mensaje.replace("\n", "");
+            System.out.println("Received the following delimited message: " + mensaje);
+            break;
+    }
+    
+}
+
+

}

+

Documentation of that DataListener

","

You can listen for multiple events by OR'ing these together:

+
return SerialPort.LISTENING_EVENT_DATA_WRITTEN | SerialPort.LISTENING_EVENT_DATA_RECEIVED;
+
+
+

How this works:

+

Assume LISTENING_EVENT_DATA_WRITTEN has the value 1 and LISTENING_EVENT_DATA_RECEIVED has the value 2, in binary:

+

1 = 01
+2 = 10

+

If these two numbers are now OR'ed together using the logical OR operator |, the result is:

+

01 | 10 = 11

+

The library now checks if

+
11 & LISTENING_EVENT_DATA_WRITTEN == LISTENING_EVENT_DATA_WRITTEN
+
+

if this is the case, this is "passed on" to your class

",r +"Retrieve data that has the same factor in column B for both factors in column A and finding which assets that male does not share with female

In column A, there are two factors, male and female. +In column B, there are 5 assets, a to e.

+
df <- data.frame(ID = c(1:7),                                   
+                 gender = c("male","male", "male", "female", "female","female","female"),               
+                 assets = c("a,e","a,b,e,d", "b,c,e","b,c,e", "a,b,e,d", "c,d","a,d"))  
+
+   
+
+

How do I retrieve data where both male and female shared the same asset combinations?

+

I've zero clue how to write the R syntax for it and below is what I have tried

+
sameassets <- df %>% filter(filter(gender="male",assets) == filter(gender="female",assets))
+
+

desired output

+
sameassests <- data.frame(ID = c(2,5,3,4),                                   
+                          gender = c("male", "female", "male", "female"),               
+                          assets = c("a,b,e,d", "a,b,e,d", "b,c,e","b,c,e"))
+
+

Can someone help please?

+

Edit to include additional question. +I also want to find out which asset combination that male does not share with female.

+

So the desired output for this will look like

+
diffassests <- data.frame(ID = c(1,6,7),                                   
+                              gender = c("male", "female", "female"),               
+                              assets = c("a,e", "c,d", "a,d"))
+
","
df %>%
+   group_by(assets) %>%
+   filter(all(c('male', 'female') %in% gender))
+
+# A tibble: 4 x 3
+# Groups:   assets [2]
+     ID gender assets 
+  <int> <chr>  <chr>  
+1     2 male   a,b,e,d
+2     3 male   b,c,e  
+3     4 female b,c,e  
+4     5 female a,b,e,d
+
",r +"How do I make my own generic functional list implementation in Java behave covariantly?

I am implementing my own linked list in Java mainly as an attempt to learnt the syntax. I have some experience in Scala, and am trying to implement a functional, immutable linked list. I'm having trouble understanding how to make a covariant concatenation method. I want to be able to concatenate (append) a List<Sub> with (to) a List<Super>.

+
public abstract List<T> {
+    public abstract T head();
+    public abstract List<T> tail();
+    public abstract boolean isEmpty();
+    // ... more methods
+    public List<T> concat(List<? extends T> that) {
+        if (this.isEmpty()) return (List<T>) that; // Gross
+        else return new Cons<>(this.head(), this.tail().concat(that));
+    }
+}
+public class Cons<T> extends List<T> {
+    private final T head;
+    private final List<T> tail;
+    public boolean isEmpty() {return false;}
+    public Cons(T head, List<T> tail) {this.head = head; this.tail = tail;}
+    public T head() {return head;}
+    public List<T> tail() {return tail;}
+}
+public class Nil<T> extends List<T> {
+    public T head() {throw new NoSuchElementException();}
+    public List<T> tail() {throw new NoSuchElementException();}
+    public boolean isEmpty() {return true;}
+}
+
+

I seem to only be able to do this by explicitly casting the list of subtypes to a list of supertypes which seems ugly. I'm essentially trying to mimic Scala's List[+T] covariance formalism. Cheers.

","

As far as Java is concerned, a List<Subclass> isn't a List<Superclass>, and there's no way to tell it otherwise. Neither covariance nor contravariance is supported.

+

I can think of a few options here:

+
    +
  1. Declare concat as returning List<? extends T>, rather than promising that it will return exactly List<T>.
  2. +
  3. Do what you're doing — you know that, since your List class is immutable, it's safe to reinterpret a List<Subclass> as a List<Superclass>, so you can just cast it, plus an appropriate @SuppressWarnings annotation with a comment. (You'll probably want to centralize this in a private upcast method.)
  4. +
  5. Declare Cons.tail as having type List<? extends T>, and whenever you need to convert from List<? extends Superclass> to List<Superclass>, you can do so by destructuring and reconstructing — creating a new Cons<Superclass> or Nil<Superclass> with the same fields. (The reason to declare Cons.tail as List<? extends T> is so that you don't need to copy the whole list over, but just the first cons.) (As with #2, you'll probably want to centralize this in a private upcast method, which Nil and Cons can each implement appropriately.)
  6. +
",r +"Type of primary key index and what happens on modifying them in MySQL

The highest rated answer here mentions how in MySQL records are stored in the order of primary index. Does that mean the primary index created is a sparse index? And if so, what happens if one modifies the primary key, by changing the column on which it is constructed or modifying one of the entries.

+

Apologies for asking 2 questions in the same post, but I thought it was better asking them together. I came upon this doubt while dealing with tables which were extremely slow when queried, so I thought maybe inserting rows in some manner which is based on an actual column in the table would help.

","

I'll answer about MySQL's default storage engine, InnoDB. This is the storage engine you should use for all tables in MySQL, unless you have a very specific reason not to.

+

Answer to Question 1: The primary key is not a sparse index. I know that term to refer to an index that only has values for a subset of rows in the table. I.e. an index with a WHERE clause. But the primary key must account for all rows in the table. It is the column or columns you use if you need to reference any single row uniquely.

+

Even though the clustered index is stored in order by primary key values, it isn't necessarily stored in that order on disk. Each page in an InnoDB tablespace has a link to the "next" page, which may not be physically located immediately after. It may be much later in the file, or even earlier. The pages may be interspersed with pages for other indexes (even other table if you are using a shared tablespace). Is this what you meant by sparse index?

+

Answer to Question 2: If you change the column(s) of the table's primary key, the storage of the table must be restructured. InnoDB uses the primary key as the clustered index, which means the rest of the columns are stored along with leaf nodes of the B-tree data structure. Changing the primary key column(s) may change the order of storage, and also the size of each B-tree node (both internal nodes and leaf nodes).

+

This means while you are restructuring the primary key, your server temporarily needs a lot of extra storage space — up to double the size of the table. Once the restructuring is finished, the old version of the table is automatically dropped.

",r +"How to make inherited fields of non-audited base entity being audited for audited child entity in JPA?

I have a base entity not intended to be audited:

+
@Data
+@MappedSuperclass
+@EqualsAndHashCode(of = {"id"})
+public abstract class BaseEntity implements Serializable {
+    @CreationTimestamp
+    @Temporal(TemporalType.TIMESTAMP)
+    @Column(name = "created_at", updatable = false, nullable = false)
+    private Date createdAt;
+
+

and there is a subclass like:

+
@Entity
+@Audited
+@AuditTable(schema = "audit", value = "bank")
+@Table(name = "bank")
+public class Bank extends BaseEntity {
+    @Column(name = "name")
+    private String name;
+
+

so as the final result I get only name column falls into the audit.bank audit table, while created_at isn't. How I can make it being auditable, not breaking the inheritance of entities?

","
@AuditOverride(forClass = BaseEntity.class, isAudited = true)
+
+

helped me

",r +"How to display the final returned value from a Python program in terminal?

I'm simply writing a Python program that takes in 2 integers and returns the sum. The problem I encounter is that the terminal never displays the returned value, so I have to resort to making a print statement. Is there any way to have the terminal display the returned value of the program?

+

The code is as follows:

+
import argparse
+
+def simple_addition():
+    parser = argparse.ArgumentParser(description = "Simple Addition Program to Test CLI")
+
+    # each line add AN argument to our terminal inout
+    parser.add_argument("first_number", type = int, help = "enter the first integer")
+    parser.add_argument("second_number", type = int, help = "enter the second integer")
+    args = parser.parse_args()
+
+    # storing the entered argument internally within our code for ease of access
+    first = args.first_number
+    second = args.second_number
+
+    # calculate and return the sum
+    sum = first + second
+    print("A PRINT CALL (not return): ", sum)
+    return sum
+
+simple_addition()
+
+

Following is a screenshot of the terminal when I run this program.

+

","
#! /usr/bin/env python3
+
+import argparse
+
+def simple_addition():
+    parser = argparse.ArgumentParser(description = "Simple Addition Program to Test CLI")
+
+    # each line add AN argument to our terminal inout
+    parser.add_argument("first_number", type = int, help = "enter the first integer")
+    parser.add_argument("second_number", type = int, help = "enter the second integer")
+    args = parser.parse_args()
+
+    # storing the entered argument internally within our code for ease of access
+    first = args.first_number
+    second = args.second_number
+
+    # calculate and return the sum
+    sum = first + second
+    #print("A PRINT CALL (not return): ", sum)
+    return sum
+
+if __name__ == '__main__':
+    print(simple_addition())
+
+
    +
  1. add shebang on first line and chmod +x
  2. +
  3. do not print inside the function
  4. +
  5. do it only if it's main (so you can import the module if needed)
  6. +
+

then you can invoke it directly

+
./"CLI Testing.py" 35 45
+
",r +"Slicing a 3D image to create a 2D image

I have several 3D images of shape (32,32,32) and I want to create 2D images from them. I want to do that by getting each slice in the z-axis and putting each of them in a square array in order, something like this:

+

+

Because I want the 2D image to be square I need to fill the missing slices with zeros (Black in the example).

+

This is what I did:

+
# I created an array of the desired dimensions
+
+grid = np.zeros((6*32,6*32))
+
+# Then, I assigned to each section of the grid the values of every slice of the 3d_image:
+
+grid[0:32, 0:32] = 3d_image[:,:,0]
+grid[0:32, 32:64] = 3d_image[:,:,1]
+grid[0:32, 64:96] = 3d_image[:,:,2]
+grid[0:32, 96:128] = 3d_image[:,:,3]
+grid[0:32, 128:160] = 3d_image[:,:,4]
+grid[0:32, 160:192] = 3d_image[:,:,5]
+grid[32:64, 0:32] = 3d_image[:,:,6]
+grid[32:64, 32:64] = 3d_image[:,:,7]
+grid[32:64, 64:96] = 3d_image[:,:,8]
+grid[32:64, 96:128] = 3d_image[:,:,9]
+grid[32:64, 128:160] = 3d_image[:,:,10]
+grid[32:64, 160:192] = 3d_image[:,:,11]
+grid[64:96, 0:32] = 3d_image[:,:,12]
+grid[64:96, 32:64] = 3d_image[:,:,13]
+...
+grid[160:192, 160:192] = 3d_image[:,:,31]
+
+

And It worked!! But I want to automate it, so I tried this:

+
d = [0, 32, 64, 96, 128, 160]
+for j in range(6):
+  for i in d:
+    grid[0:32, i:i+32] = 3d_image[:,:,j]
+
+

But it didn't work, the slice index for 3d_image (j) is not changing, and I don't know how to change the index range for grid after every 6th slice.

+

Could you help me?

","

Here's an automated way to do it. Let's say your array with shape (32, 32, 32) is called n. Note that this method relies on all 3 dimensions having the same size.

+
num_layers = n.shape[0]
+
+# num_across = how many images will go in 1 row or column in the final array.
+num_across = int(np.ceil(np.sqrt(num_layers)))
+
+# new_shape = how many numbers go in a row in the final array.
+new_shape = num_across * num_layers
+final_im = np.zeros((new_shape**2)).reshape(new_shape, new_shape)
+
+for i in range(num_layers):
+
+  # Get what number row and column the image goes in (e.g. in the example, 
+  # the image labelled 28 is in the 4th (3rd with 0-indexing) column and 5th
+  # (4th with 0-indexing) row.
+
+  col_num = i % num_across
+  row_num = i // num_across
+  
+  # Put the image in the appropriate part of the final image.
+  final_im[row_num*num_layers:row_num*num_layers + num_layers, col_num*num_layers:col_num*num_layers + num_layers] = n[i]
+
+

final_im now contains what you want. Below is a representation where each image is a different color and the "black" areas are purple because matplotlib colormaps are funny like that: +

+

Anyway, you can tell that the images go where they're supposed to and you get your empty space along the bottom.

",r +"How to save the inputs, inside Data Frame which is inside the list?

I tried to keep reprex as simple as possible.

+

I want to save with the ADD button currently chosen inputs, inside Data Frame (selected by index passed by userId input), which is inside the list, and later on use this Data Frame to render a table (in the final app make a plot).

+

Here I figured out, how to save values inside the data frame. (not data frame inside a list)
+How to save input to data frame, and use it later in Shiny?

+

Now Add button returns this:
+Warning: Error in choosen_user: unused argument (rbind(choosen_user(), new_day_rate())) <- this is propably because I used reactive() not reactiveVal(), but with reactiveVal() there is this error:

+

Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. +You tried to do something that can only be done from inside a reactive consumer.

+
library(shiny)
+
+# Saved_users_list normally came from external file
+saved_users_list <- list(data.frame(date = c(as.Date("2022-04-18"),
+                                       as.Date("2022-04-19")),
+                              rate = c(8,1),
+                              day_comment = c("Found a gf",
+                                              "Broke my arm")),
+                   data.frame(date = c(as.Date("2022-04-18"),
+                                       as.Date("2022-04-19")),
+                              rate = c(10,1),
+                              day_comment = c("Found a job",
+                                              "They fired me")))
+
+
+ui <- fluidPage(
+  sidebarLayout(
+    sidebarPanel(
+      selectInput("userId", "userId", choices = c(1:2)),
+      sliderInput("day_rate", "Rate your day", min = 0, max = 10, value = 5, step = 0.5),
+      dateInput("date", "Pick a date"),
+      textAreaInput("comment", "Comment", placeholder = "Add a description (OPTIONAL)"),
+      actionButton("add", "Add"),
+      actionButton("test", "Test values") # Button to test inputs values
+      ),
+    mainPanel(
+      tableOutput("test_table")
+    )
+    )
+  )
+
+server <- function(input, output, session) {
+  
+  users_list <- reactiveVal(saved_users_list)
+  selected_user <- reactive(as.numeric(input$userId))
+  
+  output$test_table <- renderTable({
+    users_list()[selected_user()]
+  })
+  
+    new_day_rate <- reactive(list(data.frame(date = input$date,
+                                             rate = input$day_rate,
+                                             day_comment = input$comment)))
+    
+    choosen_user <- reactive(users_list()[[selected_user()]])
+    
+    # Button to add values to the data frame inside users_list
+    observeEvent(input$add, {
+    # users_list()[[selected_user()]]  <- rbind(users_list()[[selected_user()]], as.data.frame(new_day_rate())) # Error in <-: invalid (NULL) left side of assignment
+
+    choosen_user(rbind(choosen_user(), new_day_rate())) # Here I tried to implement a solution from linked question 
+  })
+  
+  # Button to test inputs values
+  observeEvent(input$test, {
+    message("userId: ", input$userId, " ", class(input$userId))
+    message("selected_user(): ", selected_user())
+    message("new_day_rate(): ", new_day_rate())
+    message("str(new_day_rate()): ", str(new_day_rate()))
+    message("users_list()[[selected_user()]]: ",users_list()[[selected_user()]])
+  })
+}
+
+shinyApp(ui, server)
+
","

I think you're after reactiveValues? Something like:

+
library(shiny)
+
+# Saved_users_list normally came from external file
+saved_users_list <- list(
+  data.frame(
+    date = c(as.Date("2022-04-18"), as.Date("2022-04-19")),
+    rate = c(8,1),
+    day_comment = c("Found a gf", "Broke my arm")
+  ),
+  data.frame(
+    date = c(as.Date("2022-04-18"), as.Date("2022-04-19")),
+    rate = c(10,1),
+    day_comment = c("Found a job", "They fired me")
+  )
+)
+
+ui <- fluidPage(
+  sidebarLayout(
+    sidebarPanel(
+      selectInput("userId", "userId", choices = c(1:2)),
+      sliderInput("day_rate", "Rate your day", min = 0, max = 10, value = 5, step = 0.5),
+      dateInput("date", "Pick a date"),
+      textAreaInput("comment", "Comment", placeholder = "Add a description (OPTIONAL)"),
+      actionButton("add", "Add"),
+      actionButton("test", "Test values") # Button to test inputs values
+    ),
+    mainPanel(
+      tableOutput("test_table")
+    )
+  )
+)
+
+server <- function(input, output, session) {
+  cache <- reactiveValues(saved_users = saved_users_list)
+  selected_user <- reactive(as.numeric(input$userId))
+
+  output$test_table <- renderTable({
+    cache$saved_users[selected_user()]
+  })
+
+  new_day_rate <- reactive(
+    data.frame(
+      date = as.Date(input$date),
+      rate = input$day_rate,
+      day_comment = input$comment
+    )
+  )
+
+  observeEvent(input$add, {
+    cache$saved_users[[selected_user()]] <- rbind(
+      cache$saved_users[[selected_user()]], new_day_rate()
+    )
+  })
+
+  observeEvent(input$test, {
+    message("userId: ", input$userId, " ", class(input$userId))
+    message("selected_user(): ", selected_user())
+    message("new_day_rate(): ", new_day_rate())
+    message("str(new_day_rate()): ", str(new_day_rate()))
+    message("users_list()[[selected_user()]]: ", cache$saved_users[[selected_user()]])
+  })
+}
+
+shinyApp(ui, server)
+
",r +"how to create a loop to find available values until it shows up true

I am working on a timeslot system that will give available time slots and unavailable but I am filtering available slots and loading the array. Sometimes many days don't have available timeslots. I wanted to find the next available slots on recently available days through the loop from the "available" Bool Parameter from the response below (I pasted only part of the response.

+
    {
+  "timeslots" : [
+    {
+      "slots" : [
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 160,
+          "available" : false,
+          "timeframe" : "10:00 - 12:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 161,
+          "available" : true,
+          "timeframe" : "12:00 - 14:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 162,
+          "available" : true,
+          "timeframe" : "15:00 - 17:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 163,
+          "available" : true,
+          "timeframe" : "17:00 - 19:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 164,
+          "available" : false,
+          "timeframe" : "19:00 - 21:00"
+        }
+      ],
+      "day_name" : "tuesday",
+      "date" : "2022-04-26",
+      "available" : 3,
+      "day_abbr" : "26 Apr"
+    },
+    {
+      "slots" : [
+        {
+          "pk" : 160,
+          "day" : "wednesday",
+          "timeframe" : "10:00 - 12:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 161,
+          "day" : "wednesday",
+          "timeframe" : "12:00 - 14:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 162,
+          "day" : "wednesday",
+          "timeframe" : "15:00 - 17:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 163,
+          "day" : "wednesday",
+          "timeframe" : "17:00 - 19:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 164,
+          "day" : "wednesday",
+          "timeframe" : "19:00 - 21:00",
+          "selected" : false,
+          "available" : false
+        }
+      ],
+      "day_name" : "wednesday",
+      "date" : "2022-04-27",
+      "available" : 4,
+      "day_abbr" : "27 Apr"
+    },
+
+

I did an iteration like this so far.

+
   switch response.result {
+              case let .success(value):
+                  let json = JSON(value)
+                  print("Time slot response: \(json)")
+                  self.slots.removeAll()
+                  self.daySlots.removeAll()
+                  self.typeOfSlot = slotType
+                  if let slotArray = json[slotType][self.dayIndex ?? 0]["slots"].array{
+                      if !slotArray.isEmpty || slotArray != [] {
+                          for slotJSON in slotArray {
+                              let slot = Slots.parseSlots(slotJSON: slotJSON)
+                              self.slots.append(slot)
+                          }
+                          self.slots = self.slots.filter({ $0.available ?? false })
+//
+                          if self.slots.count != 0{
+                          switch self.typeOfSlot{
+                                      case "seasonal_timeslots":
+                                      self.seasonalTimeSlotPK = self.slots.first?.pk
+                                      print("time slot pk \(self.seasonalTimeSlotPK ?? 0)")
+                                          UserDefaults.standard.set(self.seasonalTimeSlotPK, forKey:uds.kSeasonalTimeslotPK)
+                              self.selectedSeasonalTimeRange = self.slots.first?.timeFrame
+                                          UserDefaults.standard.set(self.selectedSeasonalTimeRange, forKey:uds.kSeasonalTimeRange)
+
+                                      case "timeslots":
+                                      self.timeSlotPK = self.slots.first?.pk
+                                      print("time slot pk \(self.timeSlotPK ?? 0)")
+                                          UserDefaults.standard.set(self.timeSlotPK ?? 0, forKey:uds.kTimeslotPK)
+                                      self.selectedTimeRange = self.slots.first?.timeFrame
+                                          UserDefaults.standard.set(self.selectedTimeRange ?? "", forKey:uds.kTimeRange)
+
+                                      default:
+                                          break
+                                      }
+                          }
+                          
+                         // timeframe
+
+                      }
+                      else {
+                        //  self.tableView.setEmptyView(title: "No available slots found for current date!", message: "Please tap on other days for next available slots.")
+                          self.view.makeToast("No Slots Found!", duration: 3.0, position: .bottom)
+                      }
+
+

Please give me code example for me to search for available slots and stops until it's found.

","

instead of using the json raw data, +you could re-structure your code and use specific models to do what you ask. Here is some example test code to show +how to get the slots.

+
struct Response: Identifiable, Codable {
+    let id = UUID()
+    var timeslots: [Timeslot]
+}
+
+struct Timeslot: Codable {
+    let slots: [Slot]
+    let dayName: String
+    let date: String
+    let available: Int
+    let dayAbbr: String
+
+    enum CodingKeys: String, CodingKey {
+        case slots
+        case dayName = "day_name"
+        case date, available
+        case dayAbbr = "day_abbr"
+    }
+}
+
+struct Slot: Identifiable, Codable {
+    let id = UUID()
+    let day: String
+    let selected: Bool
+    let pk: Int
+    let available: Bool
+    let timeframe: String
+}
+
+struct ContentView: View {
+    
+    var body: some View {
+        Text("testing")
+            .onAppear {
+                let json = """
+    {
+  "timeslots" : [
+    {
+      "slots" : [
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 160,
+          "available" : false,
+          "timeframe" : "10:00 - 12:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 161,
+          "available" : true,
+          "timeframe" : "12:00 - 14:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 162,
+          "available" : true,
+          "timeframe" : "15:00 - 17:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 163,
+          "available" : true,
+          "timeframe" : "17:00 - 19:00"
+        },
+        {
+          "day" : "tuesday",
+          "selected" : false,
+          "pk" : 164,
+          "available" : false,
+          "timeframe" : "19:00 - 21:00"
+        }
+      ],
+      "day_name" : "tuesday",
+      "date" : "2022-04-26",
+      "available" : 3,
+      "day_abbr" : "26 Apr"
+    },
+    {
+      "slots" : [
+        {
+          "pk" : 160,
+          "day" : "wednesday",
+          "timeframe" : "10:00 - 12:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 161,
+          "day" : "wednesday",
+          "timeframe" : "12:00 - 14:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 162,
+          "day" : "wednesday",
+          "timeframe" : "15:00 - 17:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 163,
+          "day" : "wednesday",
+          "timeframe" : "17:00 - 19:00",
+          "selected" : false,
+          "available" : true
+        },
+        {
+          "pk" : 164,
+          "day" : "wednesday",
+          "timeframe" : "19:00 - 21:00",
+          "selected" : false,
+          "available" : false
+        }
+      ],
+      "day_name" : "wednesday",
+      "date" : "2022-04-27",
+      "available" : 4,
+      "day_abbr" : "27 Apr"
+    }
+  ]
+}
+"""
+
+                let data = json.data(using: .utf8)!
+                do {
+                    let response = try JSONDecoder().decode(Response.self, from: data)
+                   // print("\n--> response: \(response) \n")
+                    
+                    // here loop over the timeslots
+                    for tmslot in response.timeslots {
+                        // here loop over the slots
+                        for slot in tmslot.slots {
+                            if slot.available {
+                                print("slot available: \(slot.day)  \(slot.timeframe)")
+                            }
+                        }
+                    }
+                    
+                } catch {
+                    print("error: \(error)")
+                }
+            }
+    }
+}
+
",r +"ReactJS MUI Component not rendering inside map function

I am using ReactJS along with Material UI Components. I am trying to render a custom element using the below code. The options array is never empty and the console logs are showing as expected - "Adding element to grid ..". However, the element is not rendered on the browser(I checked the browser Inspector to confirm).

+

What am I missing?

+
import React from "react";
+import Container from "@mui/material/Container";
+import Grid from "@mui/material/Grid";
+const Element = (props) => {
+  const {options} = props;
+  
+  return(
+     // If I simply pass a JSX component at this location, it renders fine. 
+     // But not inside the map function
+     {options.map((opt) => {
+        opt.elements.length > 0 && (
+          <Grid container spacing={4}>
+            {opt.elements.map((el) => (
+              <Grid item xs={12} sm={6}>
+                {console.log("Adding element to grid ..", el.element_name)}
+                <h1>{el.element_name}</h1>
+              </Grid>
+            ))}
+          </Grid>
+        );
+      })} 
+  )
+}
+
","

You should use parentheses instead of curly brackets inside the first map in the return()

+
{options.map((opt) => (
+        opt.elements.length > 0 && (
+          <Grid container spacing={4}>
+            {opt.elements.map((el) => (
+              <Grid item xs={12} sm={6}>
+                {console.log("Adding element to grid ..", el.element_name)}
+                <h1>{el.element_name}</h1>
+              </Grid>
+            ))}
+          </Grid>
+        );
+      ))} 
+
",r +"Barplot the mean of two columns in R

I want to make a simple bar chart showing the mean and standard deviation of two columns of a csv, but I cant seem to figure it out.

+

For example, say the csv looks like this.

+
unfiltered_data,filtered_data
+2,1
+3,4
+5,6
+7,8
+
+

Then using

+
test <- read.csv("Performance Metric Testing/test.csv")
+
+ggplot(test, aes(unfiltered_data, filtered_data)) + 
+  geom_bar(stat = "summary", fun.y = "mean")
+
+

Outputs an odd 4 bar graph. I cant seem to understand how to use the ggplot package.

+

","

As is quite often the case you have to convert your data to long or tidy format to get a barchart showing the means for your columns:

+
test_long <- tidyr::pivot_longer(test, everything(), names_to = "data")
+test_long
+#> # A tibble: 8 × 2
+#>   data            value
+#>   <chr>           <int>
+#> 1 unfiltered_data     2
+#> 2 filtered_data       1
+#> 3 unfiltered_data     3
+#> 4 filtered_data       4
+#> 5 unfiltered_data     5
+#> 6 filtered_data       6
+#> 7 unfiltered_data     7
+#> 8 filtered_data       8
+
+library(ggplot2)
+
+ggplot(test_long, aes(data, value)) +
+  stat_summary(fun = "mean", geom = "col") +
+  stat_summary(fun.data = "mean_se")
+
+

+

DATA

+
test <- structure(list(unfiltered_data = c(2L, 3L, 5L, 7L), filtered_data = c(
+  1L,
+  4L, 6L, 8L
+)), class = "data.frame", row.names = c(NA, -4L))
+
",r +"python script error in docker detached mode, but executes correctly in docker attached mode

I am using JayDeBeAPI and UCanAccess to extract data from MS Access .mdb files (as per this advice). My python script runs in docker debian container (FROM python:3.9-slim) and everything is OK if it runs in the "attached mode", but if I run the container in the "detached mode" and try to execute the script, I get this error:

+
jdbc.UcanaccessSQLException: UCAExc:::5.0.1 user lacks privilege or object not found: EXPORT in statement [SELECT * from export]"
+...
+
+

How to make the script executing in the docker detached mode? What could be wrong?

","

What seemed to have fixed the problem was installing sudo in the docker image:

+
RUN apt-get install -y sudo
+
+

Strange, since I was executing docker exec as root already ... (?)

",r +"Inject cronjob once namespace created

This mainly for GKE cluster with preemptible nodes. Google Cloud would shutdown any node without warning, which leaves lots of pods with Terminated and / or NodeShutdown state. My current UAT environment is a GKE cluster with hundreds of tenants, where each tenant occupies one namespace. Delete all pods with Terminated and / or NodeShutdown state (means across namespace) would take a very time and not really practical as single run, so I think it might be better for each namespace running its own 'janitor' Cronjob. Now, I could create Cronjob manually with existing namespaces, but I can't stop my colleagues to create other namespaces for their tenants. So I start to think of if I could do similar thing just like Istio auto sidecar injection.

+

Just curious anybody know what documents / github repo I should dig from here. Or, if what I thought might be totally wrong, please point a correct way to solve this problem.

","
+

so I think it might be better for each namespace running its own +'janitor' Cronjob. Now, I could create Cronjob manually with existing +namespaces, but I can't stop my colleagues to create other namespaces +for their tenants. So I start to think of if I could do similar thing +just like Istio auto sidecar injection.

+
+

You can write your own CRD or controller to inject Job or Cronjob to the newly created namespace by default.

+

Anyone who creates a new namespace, it will have this cronjob(janitor) running for cleaning up.

+

i was looking into this CRD or controller daemonjob which will run on each of Node as JOB. Maybe you could take as base and update it further to implement your scenario.

+

https://github.com/AmitKumarDas/metac/blob/master/examples/daemonjob/sync.py

",r +"React router dom v-6 not working on build version

I'm working on a chat application that has some paths like below

+
            <Routes>
+                <Route path="/" element={<WelcomeScreen />} />
+                <Route path="channels" element={<Home />} />
+                <Route path="channels/:id" element={<Home />} />
+                <Route path="*" element={<Navigate replace to="/" />} />
+            </Routes>
+
+

Once the users are authenticated, they are redirected from welcome screen to home page that has all the chats which is on /channels. So if a user were to access /channels or in the case of 404, I redirected to the / path.

+

Everything works fine when I run it on localhost but once I host it on netlify and when I refresh at /channels instead of redirecting I get a 404 message and <Route path="*" element={<Navigate replace to="/" />} /> Doesn't work.

+

Can someone tell me what's the problem? Any help would be appreciated.

","

Change your <BrowserRouter> to <HashRouter>. It lets refreshing individual page without 404 error.

+Reference: https://reactrouter.com/docs/en/v6/api#reference +

+

Update

+

If you are using Netlify you can do this to be able to use <BrowserRouter> and avoid hash # in the routes +

+Create a file named _redirects with following content in your build folder

+
/* /index.html 200    
+
",r +How to represent 2 Entity with 2 Relation in ER diagram

Suppose I have 2 entity set one user and other books and the user contains two types of user.roles : student and admin the admin adds books and student reads them so how to I represent these entity user and books with relations reads and adds in an ER Diagram.

,"

+

The top line is representing the admin role. I assumed a book is added by only by one admin and an admin may add many books. A book is required to be added by an admin and a new admin may not have added any books.

+

The bottom line is representing the student role. A student may read many books and a book may be read by many students. A student may not have read any books and a book my not yet have been read by a student.

+

The answer already included here mentioned you need a join table for the many-to-many relationship when putting this into a DBMS. The notation here is crow's foot. Here is a link for an explanation of the notation if you're not familiar, https://vertabelo.com/blog/crow-s-foot-notation/.

",r +"Tkinter Toplevel window with autoresize background image does not work

I am able to create a normal window in tkinter having a background image resizing with the window itself. But I am not able to do the same thing for a Toplevel window. The TopWin window derived from Toplevel resize indefinitely without doing any action. +I do not understand why and what is the problem. +I reported below my test code:

+
from tkinter import *
+from PIL import Image, ImageTk
+
+class FrameWin(Frame):
+    def __init__(self, master, *pargs):
+        Frame.__init__(self, master, *pargs)
+        self.image = Image.open("../idata/bkg-3.png")
+        self.img_copy= self.image.copy()
+        self.background_image = ImageTk.PhotoImage(self.image)
+        self.background = Label(self, image=self.background_image)
+        self.background.pack(fill=BOTH, expand=YES)
+        self.background.bind('<Configure>', self._resize_image)
+    #---------------------------------------------------------------------------
+
+    def _resize_image(self,event):
+        new_width = event.width
+        new_height = event.height
+        self.image = self.img_copy.resize((new_width, new_height))
+        self.background_image = ImageTk.PhotoImage(self.image)
+        self.background.configure(image = self.background_image)
+    #---------------------------------------------------------------------------
+#---------------------------------------------------------------------------
+#---------------------------------------------------------------------------
+
+class TopWin(Toplevel):
+    def __init__(self, master, **kwargs):
+        # super().__init__(**kwargs)
+        Toplevel.__init__(self, **kwargs)
+        self.image = Image.open("../idata/bkg-3.png")
+        self.img_copy= self.image.copy()
+        self.background_image = ImageTk.PhotoImage(self.image)
+        self.background = Label(self, image=self.background_image)
+        self.background.pack(fill=BOTH, expand=YES)
+        self.background.bind('<Configure>', self._resize_image)
+    #---------------------------------------------------------------------------
+
+    def _resize_image(self,event):
+        new_width = event.width
+        new_height = event.height
+        self.image = self.img_copy.resize((new_width, new_height))
+        self.background_image = ImageTk.PhotoImage(self.image)
+        self.background.configure(image = self.background_image)
+    #---------------------------------------------------------------------------
+#---------------------------------------------------------------------------
+#---------------------------------------------------------------------------
+
+
+def workingMain():
+    root = Tk()
+    root.title("Title")
+    root.geometry("600x400")
+    root.configure(background="black")
+
+    w = FrameWin(root)
+    w.pack(fill=BOTH, expand=YES)
+    root.mainloop()
+#---------------------------------------------------------------------------
+
+def notWorkingMain():
+    root = Tk()
+    root.title("Title")
+    root.geometry("600x400")
+    root.configure(background="black")
+    w = TopWin(root)
+
+    root.mainloop()
+#---------------------------------------------------------------------------
+
+notWorkingMain()
+#---------------------------------------------------------------------------
+#---------------------------------------------------------------------------
+
","

FrameWin works because you use fill = BOTH and expand = YES on the label and frame. I'm not certain why this makes it work, but I think that when the window is resized, the label is also resized which triggers the Configure event and resizes the image to the dimensions of the window. If you don't use fill and expand, the image will resize repeatedly until it fills the window, similar to the problem you face with TopWin as the Configure event is called until the label fills the window. Once it fills the window, it can't expand any more so Configure stops being called.

+

To resolve this, you can add a check the resize method to check if the window and image sizes are the same. If they're not, you expand the image. This prevents the image from expanding indefinitely. Note that the event binding is on the TopLevel itself, not the Label.

+
class TopWin(Toplevel):
+    def __init__(self, master, **kwargs):
+        # super().__init__(**kwargs)
+        Toplevel.__init__(self, **kwargs)
+        self.image = Image.open("../idata/bkg-3.png")
+        self.img_copy= self.image.copy()
+        self.background_image = ImageTk.PhotoImage(self.image)
+        self.background = Label(self, image=self.background_image)
+        self.background.pack(fill=BOTH, expand=YES)
+        self.bind('<Configure>', self._resize_image) # Bind the toplevel, not the label
+    #---------------------------------------------------------------------------
+
+    def _resize_image(self,event):
+        # These are now the height/width of the window
+        new_width = event.width
+        new_height = event.height
+        # Check if the image is the same size as the window
+        if self.background.winfo_width() != new_width or self.background.winfo_height() != new_height:
+            # If it isn't, resize
+            self.image = self.img_copy.resize((new_width, new_height))
+            self.background_image = ImageTk.PhotoImage(self.image)
+            self.background.configure(image = self.background_image)
+
",r +"Refactoring ruby CSV import method

Writing out a rake task to import from csv, one would tend to write

+
Article.create(
+   category_id: row[0],
+   label: row[1],
+   name: row[2],
+   integer: row[3],
+   priority: row[4]
+)
+
+

But these need to be refactored taking into account a meta-structure where

+
Class Import  
+  has_many :importattributes
+
+

The following is syntactically incorrect

+
Article.create(
+  import.importattributes.each do |importattribute|
+    m_attr = importattribute.mapped_attribute
+    sequence = importattribute.position.to_i
+    m_attr: row[sequence]
+  end
+)
+
+

on the line complaining about syntax error, unexpected ':', expecting 'end'
+m_attr: row[sequence] If that line is commented out, other actions run as they do not parse this error beforehand.

+

I assume this is mistaken for the proper creation of array of attributes, because an update action, on a per attribute basis

+
import.importattributes.each do |importattribute|
+  m_attr = importattribute.mapped_attribute
+  sequence = importattribute.position.to_i
+  Article.update(m_attr: row[sequence])
+end
+
+

does not raise the error.

","

This is not a valid syntax m_attr: row[sequence]. When used as an argument for update it is treated as a hash { m_attr: row[sequence] } and curly brackets can be omitted.

+
Article.create(
+  import.importattributes.each do |importattribute|  # returns `import.importattributes`
+                                                     # and used as argument for `create`
+                                                     # nothing from `each` block is used
+
+    m_attr = importattribute.mapped_attribute        # `m_attr` is unused
+
+    sequence = importattribute.position.to_i
+
+    m_attr: row[sequence]                            # invalid syntax
+    # at the very least it has to be wrapped in {} and used with hashrocket syntax
+    # to make use of m_attr variable.
+    # { m_attr => row[sequence] }
+  end                                                
+)
+
+

create accepts a hash of attributes to create a single record or an array of hashes to create multiple records. The return value of the import logic has to be one of these two options. For clarity, it can be done in three steps:

+
attributes = {}
+
+import.importattributes.each do |importattribute|
+  attribute_name = importattribute.mapped_attribute 
+  csv_column     = importattribute.position.to_i
+  attributes[attribute_name] = row[csv_column] }
+end
+
+Article.create(attributes)
+
+

or in one step using inject

+
Article.create(
+  import.importattributes.inject({}) do |attributes, importattribute| 
+    attributes[importattribute.mapped_attribute] = row[importattribute.position.to_i] 
+    attributes
+  end
+)
+
",r +"Using the Same jQuery Function in Separate Buttons

I'm trying to get each button to change color on click. However, I want to separate buttons 1-3 from buttons 4-6 so they are independent from each other. I want to be able to click buttons 1-3 and they change color without affecting 4-6 and vice versa. My code is attached. I'm sure this is very simple but my feeble mind can't figure it out :-) Any suggestions?

+

+
+
$(document).ready(function(){
+  $(""button"").click(function() {
+    $("".featuredBtn.active"").removeClass(""active"");
+    $(this).addClass(""active"");
+  });
+});
+
+$(document).ready(function(){
+  $(""button"").click(function() {
+    $("".featuredBtn2.active"").removeClass(""active"");
+    $(this).addClass(""active"");
+  });
+});
+
.featuredBtn.active,
+.featuredBtn2.active {
+    background-color: #bf9471;
+    color: white;
+  }
+
+  .featuredBtn,
+  .featuredBtn2 {
+    width: 250px;
+    height: 50px;
+    color: #8c8c8c;
+    font-weight: 700;
+    background-color: #f4efeb;
+    border: none;
+    letter-spacing: 2px;
+    outline: none;
+  }
+
+  .row {
+    margin-bottom: 40px;
+  }
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Document</title>
+    <script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js""></script>
+    <script src=""test.js""></script>
+    <link rel=""stylesheet"" href=""test.css"">
+</head>
+<body>
+
+    <div class=""row"">
+        <div class=""col-lg-12 col-xs-12"" style=""text-align: center;"">
+          <button type=""button"" class=""featuredBtn active"" id=""btnOne"">BUTTON ONE</button>
+          <button type=""button"" class=""featuredBtn"" id=""btnTwo"">BUTTON TWO</button>
+          <button type=""button"" class=""featuredBtn"" id=""btnThree"">BUTTON THREE</button>
+        </div>
+    </div>
+
+    <div class=""row2"">
+        <div class=""col-lg-12 col-xs-12"" style=""text-align: center;"">
+          <button type=""button"" class=""featuredBtn2 active"" id=""btnFour"">BUTTON FOUR</button>
+          <button type=""button"" class=""featuredBtn2"" id=""btnFive"">BUTTON FIVE</button>
+          <button type=""button"" class=""featuredBtn2"" id=""btnSix"">BUTTON SIX</button>
+        </div>
+    </div>
+
+</body>
+</html>
+
+
+

","

Instead of applying both handlers to all instances of $('button'), specifically target the instances you want. Your current markup separates them by class, so you can use $(".featuredBtn") and $(".featuredBtn2") to identify those elements:

+

+
+
$(document).ready(function(){
+  $("".featuredBtn"").click(function() {
+    $("".featuredBtn.active"").removeClass(""active"");
+    $(this).addClass(""active"");
+  });
+});
+
+$(document).ready(function(){
+  $("".featuredBtn2"").click(function() {
+    $("".featuredBtn2.active"").removeClass(""active"");
+    $(this).addClass(""active"");
+  });
+});
+
.featuredBtn.active,
+.featuredBtn2.active {
+    background-color: #bf9471;
+    color: white;
+  }
+
+  .featuredBtn,
+  .featuredBtn2 {
+    width: 250px;
+    height: 50px;
+    color: #8c8c8c;
+    font-weight: 700;
+    background-color: #f4efeb;
+    border: none;
+    letter-spacing: 2px;
+    outline: none;
+  }
+
+  .row {
+    margin-bottom: 40px;
+  }
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Document</title>
+    <script src=""https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js""></script>
+    <script src=""test.js""></script>
+    <link rel=""stylesheet"" href=""test.css"">
+</head>
+<body>
+
+    <div class=""row"">
+        <div class=""col-lg-12 col-xs-12"" style=""text-align: center;"">
+          <button type=""button"" class=""featuredBtn active"" id=""btnOne"">BUTTON ONE</button>
+          <button type=""button"" class=""featuredBtn"" id=""btnTwo"">BUTTON TWO</button>
+          <button type=""button"" class=""featuredBtn"" id=""btnThree"">BUTTON THREE</button>
+        </div>
+    </div>
+
+    <div class=""row2"">
+        <div class=""col-lg-12 col-xs-12"" style=""text-align: center;"">
+          <button type=""button"" class=""featuredBtn2 active"" id=""btnFour"">BUTTON FOUR</button>
+          <button type=""button"" class=""featuredBtn2"" id=""btnFive"">BUTTON FIVE</button>
+          <button type=""button"" class=""featuredBtn2"" id=""btnSix"">BUTTON SIX</button>
+        </div>
+    </div>
+
+</body>
+</html>
+
+
+

",r +"How to get all selected values of Tag Picker in Fluent UI

In the docs, some of the props do not exist on the component, so I guess it's outdated.

+

I have a TagPicker component, I'm using the Tag Picker with inline suggestions one.

+
<TagPicker
+    onResolveSuggestions={filterSuggestedTags}
+    getTextFromItem={getTextFromItem}
+    pickerSuggestionsProps={{
+      suggestionsHeaderText: 'Tags',
+      noResultsFoundText: 'No tags found',
+    }}
+    pickerCalloutProps={{ doNotLayer: true }}
+    inputProps={inputProps}
+  />
+
+

And I want its value to be stored in a state (as an array of strings). +I tried to find events of selecting and removing but couldn't find them. +Thanks in advance!

","

Use onChange event for add/remove items and selectedItems for component state.

+
// Import ITag interface from FluentUI.
+const [selectedItems, setSelectedItems] = useState<ITag[]>([])
+
+<TagPicker
+  ...
+  onChange={items => items && setSelectedItems(items)}
+  selectedItems={selectedItems}
+/>
+
+

Codepen working example.

",r +"Typescript: handle data from service

I would like to display users' data, but I have a problem with displaying the correct profile pictures. If a user does not have a profile picture, I get "undefined" in the console. If one user has a profile picture, then the same picture will be displayed for all the users. I need help finding the error in my code.

+
export interface UserData {
+ id: number,
+ name: string
+}
+
+export interface UserWithImage extends UserData{
+  image?: string
+}
+
+export interface UserProfileImage {
+  id: number,
+  url: string
+}
+
+

After I get the necessary data from the services, I try to push the profile image into the userData.

+

user-data.ts

+
userData: UserWithImage[];
+userProfiles: UserProfileImage[];
+userProfileImage: UserProfileImage[];
+
+getUserData() {
+  this.userData = this.userService.getData();
+  this.userProfiles = await this.imagesService.getProfilePicture(this.userData?.map(u => u.id));
+  this.userProfileImage = this.userProfiles.filter(u => u.url);
+  this.userData?.forEach((data, i) => {
+    data.image = this.userProfileImage[i].url;
+  });
+}
+
+
+

images.service.ts

+
public async getProfilePicture(ids: number[]): Promise<UserProfileImage[]> {
+  const toLoad = ids.filter(id => !this.userProfileImages.find(up => up.id === id)).map(u => u);
+  if (toLoad || toLoad.length) {
+  const loaded = (await firstValueFrom(this.httpClient.post<UserProfile[]> 
+  (this.imgService.getServiceUrl(customersScope, `${basePath}settings/users/profil`), JSON.stringify(toLoad), {headers}))).map(sp => {
+    return {
+      id: sp.userId,
+      url: sp.profilepicId ? this.imgService.getServiceUrl(customersScope, 
+      `${basePath}web/download/profilepic/${sp.profilepicId}/users/${sp.userId}`, true) : ''
+    } as UserProfileImage
+  });
+  this.userProfileImages = [...loaded, ...this.userProfileImages];
+}
+return this.userProfileImages;
+}
+
+

user-data.html

+
<div ngFor="data of userData">
+  <etc-profil [name]="data.name" [image]="data.image"></etc-profil>
+</div>
+
","
this.userData = this.userService.getData();
+
+

Is this an async function (i.e. are you missing an await)?

+
this.userProfiles = await this.imagesService.getProfilePicture(this.userData?.map(u => u.id));
+
+

This line would fail is this.userData is a promise. this.userProfiles would be undefined due to the use of optional chaining (?.)

+
this.userProfileImage = this.userProfiles.filter(u => u.url);
+
+

This line appears to do nothing, the filter predicate is saying that anything with a url property that is not null or undefined is included, but the interface says that url is non-optional and doesn't support null or undefined.

+
this.userData?.forEach((data, i) => {
+  data.image = this.userProfileImage[i].url;
+});
+
+

Again, if this.userData is a promise, this will do nothing due to the optional chaining.

+

If it does run, its assumed that there is a one-to-one relationship between users and profile images (index count and order must be the same).

+

I didn't consider the implementation of getProfilePicture because I think these issues need resolving first.

",r +"Create a zip file in memory and then store to AWS S3

I'm trying to create a zip file in memory (using TypeScript) and then store it in an AWS S3 bucket. The input is a plain text CSV string (data).

+

I'm not sure what I'm doing wrong as the zip file that is created in s3 is unreadable when I download the file.

+

The code:

+
const zip = new AdmZip();
+zip.addFile('tmp.txt', Buffer.from(data, 'utf-8'));
+const zipData = await zip.toBufferPromise();
+try {
+  const now = dayjs().format('YYYYMMDDTHHmmss');
+  const fileName = `Feedback-${now}`;
+  await this._storageService.saveFile(zipData.toString('binary'), 'sprintFeedback', fileName);
+
","

The solution was near and simple: +Just send the outcome of the following line to your s3 bucket and it's stored as a proper zip file;

+
const zipData: Buffer = await zip.toBufferPromise();
+
+const command = new PutObjectCommand({
+  Bucket: bucketName,
+  Body: zipData,
+  Key: fileName,
+});
+
+await this._s3Client.send(command);
+
",r +"Python, how to fill an empty dataframe with lists

I'm trying to write a code to save in a matrix the common elements between some lists. +Example:

+

Data frame with all the lists:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
IDelements of the ID
G1P1,P2,P3,P4
G2P3,P5
G3P1,P3,P5
G4P6
+
+

I start with an empty matrix having G1,G2,G3,G4 as columns and rows names and the cells filled with nan, the result I would like to obtain is the following:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XG1G2G3G4
G1P1,P2,P3,P4P3P1None
G2P3P3,P5P3,P5None
G3P1,P5P3,P5P1,P3,P5None
G4NoneNoneNoneP6
+
+

This is my code:

+
import sys
+import pandas as pd
+
+def intersection(lst1, lst2):
+    return [value for value in lst1 if value in lst2]
+
+data = pd.read_csv(sys.argv[1], sep="\t")
+p_mat = pd.read_csv(sys.argv[2], sep="\t", index_col=0)
+c_mat = pd.read_csv(sys.argv[3], sep="\t", index_col=0)
+
+#I need this since the elements of the second column once imported are seen as a single string instead of being lists
+for i in range(0,len(data)):
+    data['MP term list'][i] = data['MP term list'][i].split(",")
+
+
+for i in p_mat:
+    for j in p_mat.columns:
+        r = intersection(data[data['MGI id'] == i]['MP term list'].values.tolist()[0],data[data['MGI id'] == j]['MP term list'].values.tolist()[0])
+        if len(r)!=0:
+            p_mat.at[i,j] = r
+        else:
+            p_mat.at[i, j] = None
+        del(r) 
+
+

For now I'm able to fill only the first cell correctly, then at the first non-empty result that I try to store in a cell I get this error:

+

ValueError: Must have equal len keys and value when setting with an iterable

+

How can I fix it?

","

Try with a cross merge, set intersection and pivot:

+
df["elements"] = df["elements of the ID"].str.split(",").map(set)
+
+cross = df[["ID", "elements"]].merge(df[["ID", "elements"]], how="cross")
+cross["intersection"] = (cross.apply(lambda row: row["elements_x"].intersection(row["elements_y"]), axis=1)
+                              .map(",".join)
+                              .replace("",None)
+                        )
+
+output = cross.pivot("ID_x", "ID_y", "intersection").rename_axis(None, axis=1).rename_axis(None)
+
+>>> output
+             G1     G2        G3    G4
+G1  P2,P1,P3,P4     P3     P1,P3  None
+G2           P3  P3,P5     P3,P5  None
+G3        P1,P3  P3,P5  P1,P3,P5  None
+G4         None   None      None    P6
+
+
Input df:
+
df = pd.DataFrame({"ID": [f"G{i+1}" for i in range(4)],
+                   "elements of the ID": ["P1,P2,P3,P4", "P3,P5", "P1,P3,P5", "P6"]})
+
",r +"How to change style from react bootstrap scss file?

I was creating a footer for a website. There I added some icons with fontawesome and use anchor tags with them. Now because of the style of anchor tag from a react bootstrap scss file my icons are getting blue and I can't change them. What can I do?

+
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import {fab, faYoutube, faFacebook, faGithub} from "@fortawesome/free-brands-svg-icons";
+import React from 'react';
+import { library } from '@fortawesome/fontawesome-svg-core';
+
+library.add(fab, faYoutube, faFacebook, faGithub);
+
+const Footer = () => {
+    const today = new Date();
+    const year = today.getFullYear();
+    return (
+        <footer className='text-center mt-auto bg-danger text-white fst-italic d-lg-flex justify-content-between'>
+            <h3 className='p-3'>Copyright &copy; {year} by Fruit Jet</h3>
+            <div className='fs-2 text-white d-inline-flex'>
+                <div className='p-3'>
+                    <a href="https://www.facebook.com/groups/288111895977592" target="_blank" rel="noopener noreferrer">
+                        <FontAwesomeIcon icon={['fab', 'fa-facebook']} />
+                    </a>
+                </div>
+                <div className='p-3'>
+                    <a href="https://www.youtube.com/c/ProgrammingHero" target="_blank" rel="noopener noreferrer">
+                        <FontAwesomeIcon icon={['fab', 'fa-youtube']} />
+                    </a>
+                </div>
+                <div className='p-3'>
+                    <a href="https://github.com/ProgrammingHero1" target="_blank" rel="noopener noreferrer">
+                        <FontAwesomeIcon icon={['fab', 'fa-github']} />
+                    </a>
+                </div>
+            </div>
+        </footer>
+    );
+};
+
+export default Footer;
+
+

This picture tells that a file from react bootstrap is generating this blue color

","

You have many options:

+
    +
  • Use style attribute - style={{ color: "white" }}
  • +
  • Use className attribute. Here you can just directly use a bootstrap class or create your own className="text-white"
  • +
  • Create a css or scss and target links directly or via class: a svg { color: white; }
  • +
  • You can also override bootstrap defaults, so ALL your links are white.
  • +
+

It really depends on what you try to achieve. Generally you can just override bootstrap styles with tool of your choice. If it doesn't work, add "!important".

+

Please look into following code sandbox: +https://codesandbox.io/s/eloquent-haze-764x9l

",r +"how to parsing web socket response (JSON) in flutter

I have a task, I want to take the data through the web socket, and display them on the screen of the application. But I did not even find a normal example to do so. I will be grateful if someone helps to do it, or someone sets an example. +I have the socket web address:

+
wss: //ws-sandbox.coinapi.io/v1/
+
+

I also have a body that I will send to the socket to return the data:

+
{ "type": "hello", "apikey": "C4F12EA7-D405-4619-99FD-62F4B00A8111", "heartbeat": false, "subscribe_data_type": ["exrate"], "subscribe_filter_asset_id": ["BTC / USD"] }
+
+

Here's what comes back in the web socket:

+
{
+  "time": "2022-04-28T16: 45: 31.0000000Z",
+  "asset_id_base": "BTC",
+  "asset_id_quote": "USD",
+  "rate": 39693.575,
+  "type": "exrate"
+}
+
+

I want to display "rate" data on the screen. +I will be grateful for your help)

+

My code

+

+
+
import 'package:flutter/material.dart';
+import 'package:web_socket_channel/web_socket_channel.dart';
+import 'package:web_socket_channel/io.dart';
+
+void main() => runApp(new MyApp());
+
+class MyApp extends StatelessWidget {
+  @override
+  Widget build(BuildContext context) {
+    return MaterialApp(
+      home: MyHomePage(),
+    );
+  }
+}
+
+class MyHomePage extends StatefulWidget {
+  WebSocketChannel channel = IOWebSocketChannel.connect(""wss://ws-sandbox.coinapi.io/v1/"");
+
+  @override
+  MyHomePageState createState() {
+    return MyHomePageState();
+  }
+}
+
+
+
+class MyHomePageState extends State<MyHomePage> {
+  TextEditingController _controller = TextEditingController();
+  @override
+  Widget build(BuildContext context) {
+    return  Scaffold(
+      appBar: AppBar(
+        title:  Text(""Web Socket""),
+      ),
+      body: Padding(
+        padding: const EdgeInsets.all(20.0),
+        child: Column(
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: <Widget>[
+            Form(
+              child: TextFormField(
+                decoration: InputDecoration(labelText: ""Send any message to the server""),
+                controller: _controller,
+              ),
+            ),
+            StreamBuilder(
+              stream: widget.channel.stream,
+              builder: (context, snapshot) {
+                return Padding(
+                  padding: const EdgeInsets.all(20.0),
+                  child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
+                );
+              },
+            )
+          ],
+        ),
+      ),
+      floatingActionButton: FloatingActionButton(
+        child: Icon(Icons.send),
+        onPressed: sendData,
+      ),
+    );
+  }
+
+  void sendData() {
+    if (_controller.text.isNotEmpty) {
+      widget.channel.sink.add(_controller.text);
+    }
+  }
+
+  @override
+  void dispose() {
+    widget.channel.sink.close();
+    super.dispose();
+  }
+}
+
+
+ +The problem is that I return all the JSON(string). And I want to return only the data "rate" +My scrin: +

","

In this case you do not want to display the entire json body. So instead of using snapshot.data you need to parse it first.

+

snapshot.data has a dynamic type so I do not know what kind of data you are working with but if you somehow parse it to a Map<String, dynamic> you can just do data['rate'].

+

When using the regular http library you can parse a http.Response like this:

+
jsonDecode(response.body).cast<Map<String, dynamic>>();
+
+

If you tell me the type of snapshot.data I might be able to give you more information.

+
+

Edit: I just tried your code and as suspected you are getting a String that we can parse with jsonDecode:

+
jsonDecode(snapshot.data)["rate"]
+
+

If we apply this to your problem this should be the solution:

+

Your Widget should look like this:

+
Text(getExtractedRate(snapshot))
+
+

The getExtractedRate method should looke like this:

+
  String getExtractedRate(AsyncSnapshot<dynamic> snapshot) {
+    return snapshot.hasData ? '${jsonDecode(snapshot.data)["rate"]}' : '';
+  }
+
+

Keep in mind that I am using the dynamic type to avoid typing conflicts. jsonDecode requires a String while snapshot.data is Object?. In your production code you also might want to check if the key rate is present before accessing it.

",r +"group_by and slice on groups based on condition

I have a data frame which looks like:

+
             Municipios_Names                    Distritos_Names                                  Zonas_Names
+1           Barcelona Capital                       Ciutat Vella                                 Ciutat Vella
+2           Barcelona Capital                       Ciutat Vella                                  Barri Gòtic
+3           Barcelona Capital                       Ciutat Vella                                     El Raval
+4           Barcelona Capital                       Ciutat Vella                               La Barceloneta
+5           Barcelona Capital                       Ciutat Vella         Sant Pere, Sta. Caterina i la Ribera
+6           Barcelona Capital                           Eixample                                     Eixample
+7           Barcelona Capital                           Eixample                          Dreta de l'Eixample
+8           Barcelona Capital                           Eixample                                   Fort Pienc
+9           Barcelona Capital                           Eixample               La Nova Esquerra de l'Eixample
+10          Barcelona Capital                           Eixample              L'Antiga Esquerra de l'Eixample
+11          Barcelona Capital                           Eixample                              Sagrada Família
+12          Barcelona Capital                           Eixample                                  Sant Antoni
+13          Barcelona Capital                             Gràcia                                       Gràcia
+14          Barcelona Capital                             Gràcia           El Camp d'en Grassot i Gràcia Nova
+15          Barcelona Capital                             Gràcia                                      El Coll
+16          Barcelona Capital                             Gràcia                                     La Salut
+17          Barcelona Capital                             Gràcia                    Vallcarca i els Penitents
+18          Barcelona Capital                             Gràcia                               Vila de Gràcia
+19          Barcelona Capital                   Horta - Guinardó                             Horta - Guinardó
+20          Barcelona Capital                   Horta - Guinardó                                     Can Baró
+21          Barcelona Capital                   Horta - Guinardó                             El Baix Guinardó
+
+

I have some duplicate rows I want to remove. The duplicates are the first item within each Distritos_Names "group". i.e. Ciutat Vella, Eixample, Gràcia, Horta - Guinardó etc. and as a result they are duplicated into Zonas_Names. That is, I want to remove the following:

+
Distritos_Names                                  Zonas_Names
+Ciutat Vella                                 Ciutat Vella
+Eixample                                     Eixample
+Gràcia                                       Gràcia
+Horta - Guinardó                             Horta - Guinardó
+
+

Since the names appear in both columns.

+

I have tried group_by(Municipios_Names, Distritos_Names) %>% slice(1) but this does not solve my issue. I run into issues when I have the following data.

+
130 L'Hospitalet de Llobregat            La Florida - Les Planes                      La Florida - Les Planes
+131 L'Hospitalet de Llobregat            La Florida - Les Planes                                   La Florida
+132 L'Hospitalet de Llobregat            La Florida - Les Planes                                   Les Planes
+133 L'Hospitalet de Llobregat                      Santa Eulàlia                                Santa Eulàlia
+134       Sant Adrià de Besòs                Sant Adrià de Besòs                          Sant Adrià de Besòs
+135  Santa Coloma de Gramenet                      Can Franquesa                                Can Franquesa
+136  Santa Coloma de Gramenet                        Can Mariner                                  Can Mariner
+137  Santa Coloma de Gramenet                     Cementiri Vell                               Cementiri Vell
+138  Santa Coloma de Gramenet                             Centre                                       Centre
+139  Santa Coloma de Gramenet                           El Raval                                     El Raval
+140  Santa Coloma de Gramenet                              Fondo                                        Fondo
+141  Santa Coloma de Gramenet                         Guinardera                                   Guinardera
+142  Santa Coloma de Gramenet                       Les Oliveres                                 Les Oliveres
+
+

I want to correctly remove:

+
130 L'Hospitalet de Llobregat            La Florida - Les Planes                      La Florida - Les Planes
+
+

Since there are more than one observation for L'Hospitalet de Llobregat and always the first observation in the group is the duplicate - but I don't want to remove:

+
133 L'Hospitalet de Llobregat                      Santa Eulàlia                                Santa Eulàlia
+
+

Since this is only a single observation for this group and is therefore not a duplicate. Additionally, I don't want to remove:

+
134       Sant Adrià de Besòs                Sant Adrià de Besòs                          Sant Adrià de Besòs
+
+

Since again this is a single observation for this group and is not a duplicate. So, I want to apply the slice(1) only to groups greater than 1 (or remove the first observation when Distritos_Names == Zonas_Names only when the size of the group > 1.

+

Data:

+
df <- structure(list(Municipios_Names = c("Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Barcelona Capital", "Barcelona Capital", 
+"Barcelona Capital", "Badalona", "Badalona", "Badalona", "Badalona", 
+"Badalona", "Badalona", "Badalona", "Badalona", "Badalona", "Badalona", 
+"Badalona", "Badalona", "Badalona", "Badalona", "Badalona", "Badalona", 
+"Badalona", "Badalona", "Badalona", "Badalona", "Badalona", "Badalona", 
+"Badalona", "Badalona", "Badalona", "Badalona", "Badalona", "Badalona", 
+"Badalona", "Badalona", "Badalona", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", 
+"L'Hospitalet de Llobregat", "L'Hospitalet de Llobregat", "Sant Adrià de Besòs", 
+"Santa Coloma de Gramenet", "Santa Coloma de Gramenet", "Santa Coloma de Gramenet", 
+"Santa Coloma de Gramenet", "Santa Coloma de Gramenet", "Santa Coloma de Gramenet", 
+"Santa Coloma de Gramenet", "Santa Coloma de Gramenet", "Santa Coloma de Gramenet", 
+"Santa Coloma de Gramenet", "Santa Coloma de Gramenet", "Santa Coloma de Gramenet", 
+"Santa Coloma de Gramenet", "Santa Coloma de Gramenet", "Santa Coloma de Gramenet"
+), Distritos_Names = c("Ciutat Vella", "Ciutat Vella", "Ciutat Vella", 
+"Ciutat Vella", "Ciutat Vella", "Eixample", "Eixample", "Eixample", 
+"Eixample", "Eixample", "Eixample", "Eixample", "Gràcia", "Gràcia", 
+"Gràcia", "Gràcia", "Gràcia", "Gràcia", "Horta - Guinardó", 
+"Horta - Guinardó", "Horta - Guinardó", "Horta - Guinardó", 
+"Horta - Guinardó", "Horta - Guinardó", "Horta - Guinardó", 
+"Horta - Guinardó", "Horta - Guinardó", "Horta - Guinardó", 
+"Horta - Guinardó", "Horta - Guinardó", "Les Corts", "Les Corts", 
+"Les Corts", "Les Corts", "Nou Barris", "Nou Barris", "Nou Barris", 
+"Nou Barris", "Nou Barris", "Nou Barris", "Nou Barris", "Nou Barris", 
+"Nou Barris", "Nou Barris", "Nou Barris", "Nou Barris", "Nou Barris", 
+"Nou Barris", "Sant Andreu", "Sant Andreu", "Sant Andreu", "Sant Andreu", 
+"Sant Andreu", "Sant Andreu", "Sant Andreu", "Sant Andreu", "Sant Martí", 
+"Sant Martí", "Sant Martí", "Sant Martí", "Sant Martí", "Sant Martí", 
+"Sant Martí", "Sant Martí", "Sant Martí", "Sant Martí", "Sant Martí", 
+"Sants - Montjuïc", "Sants - Montjuïc", "Sants - Montjuïc", 
+"Sants - Montjuïc", "Sants - Montjuïc", "Sants - Montjuïc", 
+"Sants - Montjuïc", "Sants - Montjuïc", "Sants - Montjuïc", 
+"Sants - Montjuïc", "Sarrià - Sant Gervasi", "Sarrià - Sant Gervasi", 
+"Sarrià - Sant Gervasi", "Sarrià - Sant Gervasi", "Sarrià - Sant Gervasi", 
+"Sarrià - Sant Gervasi", "Sarrià - Sant Gervasi", "Artigues - Llefià", 
+"Artigues - Llefià", "Artigues - Llefià", "Artigues - Llefià", 
+"Bonavista - Bufalà - Morera", "Bonavista - Bufalà - Morera", 
+"Bonavista - Bufalà - Morera", "Bonavista - Bufalà - Morera", 
+"Canyet - Pomar", "Canyet - Pomar", "Canyet - Pomar", "Canyet - Pomar", 
+"Casagemes - Canyadó", "Casagemes - Canyadó", "Casagemes - Canyadó", 
+"Casagemes - Canyadó", "Centre Badalona", "Gorg - Progrés", 
+"Gorg - Progrés", "Gorg - Progrés", "Gorg - Progrés", "Gorg - Progrés", 
+"Montigalà - Sant Crist", "Montigalà - Sant Crist", "Montigalà - Sant Crist", 
+"Montigalà - Sant Crist", "Port", "Salut - Lloreda", "Salut - Lloreda", 
+"Salut - Lloreda", "Salut - Lloreda", "Bellvitge - El Gornal - Granvia LH", 
+"Bellvitge - El Gornal - Granvia LH", "Bellvitge - El Gornal - Granvia LH", 
+"Bellvitge - El Gornal - Granvia LH", "Can Serra - Pubilla Cases", 
+"Can Serra - Pubilla Cases", "Can Serra - Pubilla Cases", "Centre - Sant Josep - Sanfeliu", 
+"Centre - Sant Josep - Sanfeliu", "Centre - Sant Josep - Sanfeliu", 
+"Centre - Sant Josep - Sanfeliu", "Collblanc - La Torrassa", 
+"Collblanc - La Torrassa", "Collblanc - La Torrassa", "La Florida - Les Planes", 
+"La Florida - Les Planes", "La Florida - Les Planes", "Santa Eulàlia", 
+"Sant Adrià de Besòs", "Can Franquesa", "Can Mariner", "Cementiri Vell", 
+"Centre", "El Raval", "Fondo", "Guinardera", "Les Oliveres", 
+"Llatí", "Riera Alta", "Riu Nord", "Riu Sud", "Safaretjos", 
+"Santa Rosa", "Singuerlín"), Zonas_Names = c("Ciutat Vella", 
+"Barri Gòtic", "El Raval", "La Barceloneta", "Sant Pere, Sta. Caterina i la Ribera", 
+"Eixample", "Dreta de l'Eixample", "Fort Pienc", "La Nova Esquerra de l'Eixample", 
+"L'Antiga Esquerra de l'Eixample", "Sagrada Família", "Sant Antoni", 
+"Gràcia", "El Camp d'en Grassot i Gràcia Nova", "El Coll", 
+"La Salut", "Vallcarca i els Penitents", "Vila de Gràcia", "Horta - Guinardó", 
+"Can Baró", "El Baix Guinardó", "El Carmel", "El Guinardó", 
+"Horta", "La Clota", "La Font d'en Fargues", "La Teixonera", 
+"La Vall d'Hebron", "Montbau", "Sant Genís dels Agudells", "Les Corts", 
+"Barri de les Corts", "La Maternitat i Sant Ramon", "Pedralbes", 
+"Nou Barris", "Can Peguera", "Canyelles", "Ciutat Meridiana", 
+"El Turó de la Peira", "La Guineueta", "La Prosperitat", "La Trinitat Nova", 
+"Les Roquetes", "Porta", "Torre Baró", "Vallbona", "Verdum", 
+"Vilapicina i la Torre Llobeta", "Sant Andreu", "Baró de Viver", 
+"El Bon Pastor", "El Congrés i els Indians", "La Sagrera", "Navas", 
+"Sant Andreu del Palomar", "Trinitat Vella", "Sant Martí", "Diagonal Mar i el Front Marítim del Poblenou", 
+"El Besós i el Maresme", "El Camp de l'Arpa del Clot", "El Clot", 
+"El Parc i la Llacuna del Poblenou", "El Poblenou", "La Verneda i la Pau", 
+"La Vila Olímpica del Poblenou", "Provençals del Poblenou", 
+"Sant Martí de Provençals", "Sants - Montjuïc", "El Poble Sec - Parc de Montjuïc", 
+"Hostafrancs", "La Bordeta", "La Font de la Guatlla", "La Marina del Port", 
+"La Marina del Prat Vermell", "Sants", "Sants-Badal", "Zona Franca - Port", 
+"Sarrià - Sant Gervasi", "El Putget i el Farró", "Les Tres Torres", 
+"Sant Gervasi- Galvany", "Sant Gervasi i la Bonanova", "Sarrià", 
+"Vallvidrera - Tibidabo - Les Planes", "Artigues - Llefià", 
+"Artigues", "Llefià", "Sant Roc", "Bonavista - Bufalà - Morera", 
+"Bonavista", "Bufalà", "Morera", "Canyet - Pomar", "Canyet", 
+"Mas Ram", "Pomar", "Casagemes - Canyadó", "Canyadó", "Casagemes", 
+"Manresà", "Centre Badalona", "Gorg - Progrés", "Congrés", 
+"El Remei", "Gorg", "Progrés - Pep Ventura", "Montigalà - Sant Crist", 
+"Montigalà", "Puigfred", "Sant Crist", "Port", "Salut - Lloreda", 
+"La Salut", "Lloreda", "Sistrells", "Bellvitge - El Gornal - Granvia LH", 
+"Bellvitge", "El Gornal", "Granvia LH", "Can Serra - Pubilla Cases", 
+"Can Serra", "Pubilla Cases", "Centre - Sant Josep - Sanfeliu", 
+"Centre", "Sanfeliu", "Sant Josep", "Collblanc - La Torrassa", 
+"Collblanc", "La Torrassa", "La Florida - Les Planes", "La Florida", 
+"Les Planes", "Santa Eulàlia", "Sant Adrià de Besòs", "Can Franquesa", 
+"Can Mariner", "Cementiri Vell", "Centre", "El Raval", "Fondo", 
+"Guinardera", "Les Oliveres", "Llatí", "Riera Alta", "Riu Nord", 
+"Riu Sud", "Safaretjos", "Santa Rosa", "Singuerlín")), class = "data.frame", row.names = c(NA, 
+-149L))
+
","

You can filter for data that only has one record OR records with Zonas_Names different from the first record of Zonas_Names per group_by.

+
library(dplyr)
+
+df %>% 
+  group_by(Municipios_Names, Distritos_Names) %>% 
+  filter(n() == 1 | Zonas_Names != first(Zonas_Names)) 
+
",r +"How can this code be optimised, so that it has fewer lines of code and is more consise?

I want to make this code shorter. Like a loop or something? It would be great if anyone helps me to make the code shorter so that I can add more nth-child. like nth-child:4, 5.

+
$(document).ready(function(){
+    var src=$(".gallery-grid-item:nth-child(1) img").data("src");
+    $.ajax({
+        url:src,
+        xhrFields:{
+            responseType:'blob'
+        },
+        success:function(data){
+            var url=window.URL||window.webkitURL;
+            $(".gallery-grid-item:nth-child(1) img").attr("src",url.createObjectURL(data));
+        }
+    });
+});
+
+$(document).ready(function(){
+    var src=$(".gallery-grid-item:nth-child(2) img").data("src");
+    $.ajax({
+        url:src,
+        xhrFields:{
+            responseType:'blob'
+        },
+        success:function(data){
+            var url=window.URL||window.webkitURL;
+            $(".gallery-grid-item:nth-child(2) img").attr("src",url.createObjectURL(data));
+        }
+    });
+});
+
+$(document).ready(function(){
+    var src=$(".gallery-grid-item:nth-child(3) img").data("src");
+    $.ajax({
+        url:src,
+        xhrFields:{
+            responseType:'blob'
+        },
+        success:function(data){
+            var url=window.URL||window.webkitURL;
+            $(".gallery-grid-item:nth-child(3) img").attr("src",url.createObjectURL(data));
+        }
+    });
+});
+
","
<script> 
+$(document).ready(function(){
+    numberOfNthChilds = 5
+    for (let i = 1; i < numberOfNthChilds + 1; i++) {
+        var src=$(".gallery-grid-item:nth-child(" + i + ") img").data("src");
+        $.ajax({
+            url:src,
+            xhrFields:{
+                responseType:'blob'
+            },
+            success:function(data){
+                var url=window.URL||window.webkitURL;
+                $(".gallery-grid-item:nth-child(" + i + ") img").attr("src",url.createObjectURL(data));
+            }
+        });
+    }
+});
+</script>
+
",r +"Add elements dynamically on a page in React

I have to print 10 elements in a column, like 1,2,3 ... with a timeout of 1 second. But in my code I don't know how to print message in a loop . I tried with innerHTML but I don't think it's a right way to do.

+
import { useState } from 'react'
+
+export default function Timeout() {
+  const [message, setMessage] = useState(1)
+
+  while (message <= 10) {
+    setTimeout(() => {
+      setMessage(message)
+    }, 1000)
+    message++
+  }
+
+  return <div>{message}</div>
+}
+
","

Try this one:

+
import {useState } from "react";
+
+export default function Timeout() {
+ const [message, setMessage] = useState([1]);
+  const Markup = (
+   <ul>
+    {message?.map((n) => (
+    <li>{n}</li>
+    ))}
+   </ul>
+  );
+  setTimeout(() => {
+  if (message.length <= 9) {
+    setMessage([...message, message[message.length - 1] + 1]);
+  }
+ }, 1000);
+
+ return <div>{Markup}</div>;
+}
+
",r +"Create animated chart of a dataset with multiples columns by year

the dataset is

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
yearIDtop_1top_2top_3
195225701266476419
195328885071656470
195431818876787246
195534858684857525
195637885085168163
19574075256501NA
19584381886165NA
195946670761875630
+
+

I want to get something like this +

+

I am not sure what to put in aes() argument

+
p <- ggplot( data = x , aes(year, y = ??  ) +
+  geom_bar( stat = "identity" ) +
+  transition_states(year) +
+  labs(title = "abc") +
+  coord_cartesian(ylim = c(5500 , 9000)) +
+  xlab("") +
+  ylab("hgt")
+animate(p, nframes = 450, fps=16)
+
","

First you need to reshape your data using melt. After that, you can set transition_states to show different years of the barplot. To show the year in the title you can use {next_state}. You can use the following code:

+
library(tidyverse)
+library(gganimate)
+library(reshape)
+
+df_melted <- melt(df, id = c("ID", "year"))
+
+p <- df_melted %>%
+  ggplot(aes(x = variable, y = value, fill = variable)) +
+  geom_bar(stat = "identity" ) +
+  transition_states(
+    year,
+    transition_length = 2,
+    state_length = 1
+  ) +
+  ease_aes('sine-in-out') +
+  labs(title = "Heighest 3 peaks in Year: {next_state}") +
+  xlab("") +
+  ylab("hgt")
+p  
+
+

Output:

+

",r +"Protege inconsistent ontology ambiguous explanation

I have a class Course and a data property courseCode on the domain Course with range xsd:string.

+

I added an individual, a Course named "Databases". I also wanted to add the data property assertion courceCode with a value of "DAT475" and a type of xsd:string. But after doing that I get this error:

+

+

What does this mean? What did I do wrong?

+

Edit: The file I'm working on is using turtle syntax.

","

You have a plain literal (the presence of an @en language tag separates a plain literal from a string literal) as filler for a property whose range is defined as xsd:string (i.e., limited to string literals only).

+

It's a bit counterintuitive, but the problem is that plain string literals and strings are not in the same datatype.

",r +"Replace all elements in vector with its ordinal number

data frame:

+
#    V1    V2
+1    abc   23
+2    bcd   43
+3    cde   54
+4    def   10
+
+

How to replace V1 with its ordinal number?

+
#    V1    V2
+1    1     23
+2    2     43
+3    3     54
+4    4     10
+
","

Do you mean this?

+
# Original
+dat <- structure(list(V1 = c("abc", "bcd", "cde", "def"), V2 = c(23L, 
+43L, 54L, 10L)), row.names = c(NA, -4L), class = "data.frame")
+dat
+  V1 V2
+1 abc 23
+2 bcd 43
+3 cde 54
+4 def 10
+
+# Change V1 with numbers
+dat$V1 <- 1:nrow(dat)
+  V1 V2
+1  1 23
+2  2 43
+3  3 54
+4  4 10
+
",r +"selenium python for loop printing only first element repeatedly

I am trying to get business info from this page.

+

Here I am selecting the main container for each item then using for loop for getting business title from each container.

+

Here is my code:

+
container = driver.find_elements_by_css_selector(".businessCapsule--mainRow")
+for i in container:
+    business_title = driver.find_element_by_css_selector('.text-h2')
+    print(business_title) 
+
+

result:

+
Mirror & Glass Processing Ltd
+Mirror & Glass Processing Ltd
+Mirror & Glass Processing Ltd
+Mirror & Glass Processing Ltd
+
+

Why It's printing only first item repeatedly? Where I am doing mistake in my above code.

+

If I tried without selecting main container then it's working.

+
business_title = driver.find_elements_by_css_selector(".text-h2")
+for i in business_title:
+        business_title = i.text
+        print(business_title)
+
+

result:

+
Mirror & Glass Processing Ltd
+J.E.D Double Glazing Repairs
+B & R Glazing Co.Ltd
+Durham Window & Door Centre Ltd
+Ken Rose Joinery & Glazing
+
","

Under the for loop code block you have to use i instead of driver

+
business_title = i.find_element_by_css_selector('.text-h2')
+
",r +"Working with multiple parameters in CriteriaBuilder

I have a need to use JpaSpecificationExecutor. +Initially, I assumed that one parameter would be given as input and I would process it like this:

+
List<Car> findCarsByParameters(
+            String brand,
+            Integer color
+    ) {
+        Specification<Car> querySpec = new Specification<Car>() {
+            @Override
+            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
+                List<Predicate> predicates = new ArrayList<>();
+                if (!brand.isEmpty()) {
+                    predicates.add(criteriaBuilder.like(root.get("brand"), brand));
+                }
+                if (color != null) {
+                    predicates.add(criteriaBuilder.equal(root.get("color"), color));
+                }
+                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
+            }
+        };
+        return carRepository.findAll(querySpec);
+    }
+
+

CarRepository :

+
public interface CarRepository extends CrudRepository<Car, Long>, JpaSpecificationExecutor 
+
+

However, I need to be able to work with:

+
List<String> brands,
+List<Integer> colors
+
+

And in response to me came all the options for suitable machines.

+

For example input:

+
brand = {honda, toyota},
+color = {0x00ffff, 0x800000}
+
+

At the output, I want to get all the machines whose properties fall under one of the following conditions:

+
{honda,0x00ffff};{honda,0x800000};{toyota,0x00ffff};{toyota,0x800000}
+
+

How do I need to modify my code so that it works like I gave in the example? Or where can I read about it?

","

This article perfectly explains what you need.

+

You basically iterate through the List<Brand>, create a list of brand predicates then consider this list as one block of predicate.

+
List<Car> findCarsByParameters(
+        List<String> brands,
+        List<Integer> colors
+) {
+    Specification<Car> querySpec = new Specification<Car>() {
+        @Override
+        public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
+            List<Predicate> brandPredicates = new ArrayList<>();
+
+            if (brands != null && !brand.isEmpty()) {
+                brandPredicates = brands.stream()
+                                        .map((brand) -> criteriaBuilder.like(root.get("brand"), brand))
+                                        .collect(Collectors.toList());
+            }
+
+            Predicate predicateForBrand = criteriaBuilder.or(brandPredicates.toArray(Predicate[]::new));
+            List<Predicate> colorPredicates = new ArrayList<>();
+
+            if (colors != null && !colors.isEmpty()) {
+                colorPredicates = colors.stream()
+                                        .map((color) -> criteriaBuilder.like(root.get("color"), color))
+                                        .collect(Collectors.toList());
+            }
+
+            Predicated predicateForColor = criteriaBuilder.or(colorPredicates.toArray(Predicate[]::new));
+            return criteriaBuilder.and(predicateForColor, predicateForBrand);
+        }
+    };
+    return carRepository.findAll(querySpec);
+}
+
",r +"Process json data to generate bar graph

I am trying to create a simple highchart bar graph with JSON that returns the value something like this :

+
[{
+"name":"Apple",
+"price":"40",
+"date":"2022-02-04"
+},
+{
+"name":"Mango",
+"price":"80",
+"date":"2022-08-02"
+},
+{
+"name":"Orange",
+"price":"60",
+"date":"2021-01-09"
+}]
+
+

and here is my fiddle http://jsfiddle.net/o246u8bt/ I am trying to achieve. It is not generating the bar with the different bar colors. Is this the right way of updating the series? Here is exactly the way I want my graph to look like http://jsfiddle.net/6hkcn4qf/2/

+

Thanks in advance!

","

A couple of issues in your code. This is your function for ajax successful request:

+
success: function(data) {
+  alert(JSON.stringify(data));
+  const processedData = [];
+
+  for (let key in data) {
+    // alert(key);
+  
+    processedData.push({
+      name: data[key].name,
+      y: data[key].price
+    });
+  }
+
+  options.series.data = processedData;
+
+  Highcharts.chart('container', options);
+}
+
+
1. Your data are strings, not numbers
+

Your JSON.stringified data are strings, so you're mapping strings in y: data[key].price.

+

Simply change into => y: +data[key].price. With the plus sign you transform strings into numbers.

+
2. Your options.series is an array, not an object
+

So, you are not setting anything here: options.series.data = processedData (as options.series is an array of objects, it has indexes, not keys)

+

Simply change this into => options.series[0].data = processedData to create the data key of the first object inside the options.series array.

+
3. Use Stackoverflow's internal snippets, not external ones - if possible.
+

As external fiddles in a couple of months may be deleted or overwritten. +Or the external site can be offline.

+

So, this question could become un-understandable or useless for others users in a short time.

",r +"DataGrid is updating itself in realtime and holding unsaved changes

I have a problem with DataGrid and after week trying to solve this I am out of mind.

+

I am using Prism.MVVM to handle loading properties, INotifyPropertyChanged etc.

+

My datagrid is being populated from database (EF) by of course ViewModel. When I double click on the row edit window will open with populated fields etc. I am doing this by "SelectedItem". Everything to this moment is working fine, but:

+

• When I editing my "Stock" textbox I see in the ProductListView window that this value is changing in realtime and even if I hit Cancel (and the window closed) it stays as I left it in ProductView and even after opening edit window again "Stock" value remain wrong, but in database the value is correct.

+

• When I edit for example "Category" or "Name" I do not see changes in datagrid in realtime (in this case values in DataGrid stay correct), but if I hit Cancel (and the window closed) an reopen edit window again value remain wrong, but in database the value is correct.

+

I tried to DeepCopy it and then Override SelectedItem back after edit and it work for database (it getting updated), but view (DataGrid) does not.

+

ProductListView:

+
    <DataGrid ColumnWidth="Auto" Grid.Row="1" ItemsSource="{Binding ProductsCollectionView, UpdateSourceTrigger=PropertyChanged}"
+SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="False" IsReadOnly="True"
+ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Visible"  ScrollViewer.HorizontalScrollBarVisibility="Auto">
+
+

Methods/Commands responsible for edit in ProductListViewModel:

+
    private Product _selectedItem;
+    public Product SelectedItem
+    {
+        get => _selectedItem;
+        set => SetProperty(ref _selectedItem, value);
+    }
+
+public ProductListViewModel() // Contructor
+    {
+        _service = new ProductService();
+
+        Load();
+        ProductsCollectionView = CollectionViewSource.GetDefaultView(Data);
+        ProductsCollectionView.Filter = FilterProducts;
+        LoadCommands();
+
+        EditCommand = new DelegateCommand(Edit);
+
+    }
+
+
+public ICommand EditCommand { get; set; }
+
+private void Edit()
+    {    
+        var dialog = new ProductView(SelectedItem);
+        dialog.ShowDialog();
+
+        if (dialog.DialogResult == true)
+        {
+            _service.UpdateProductData(SelectedItem);
+            _service.SaveChanges();
+        }
+    }
+
+

ProductView (Btw. I am using same View for Adding and Editing products, that is why I passing "SeleectedItem through the constructor)

+
<StackPanel Margin="0,0,13,0" Grid.Column="0">
+                <TextBlock Text="Product type" Style="{StaticResource StackPanelTextBox}"/>
+                <Grid>
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="41*" />
+                        <ColumnDefinition Width="251*"/>
+                        <ColumnDefinition Width="31*" />
+                    </Grid.ColumnDefinitions>
+                    <ComboBox IsEditable="True" IsTextSearchEnabled="True" ItemsSource="{Binding ProductTypes}" DisplayMemberPath="Name" SelectedValuePath="ProductTypeId" SelectedValue="{Binding Data.ProductTypeId, UpdateSourceTrigger=PropertyChanged}" Grid.ColumnSpan="2"/>
+                    <Button Grid.Column="1" Command="{Binding AddProductTypeCommand}" FontSize="12" Padding="0" Height="15" Background="Transparent" Grid.ColumnSpan="2" Margin="251,6,0,6"/>
+                </Grid>
+            </StackPanel>
+
+            <StackPanel Margin="0,0,13,0" Grid.Column="1">
+                <TextBlock Text="Signature" Style="{StaticResource StackPanelTextBox}"/>
+                <TextBox Text="{Binding Data.Signature}"/>
+            </StackPanel>
+
+            <StackPanel Margin="0,0,0,0" Grid.Column="2">
+                <TextBlock Text="EAN" Style="{StaticResource StackPanelTextBox}"/>
+                <TextBox MaxLength="13" Text="{Binding Data.Ean}"/>
+            </StackPanel>
+            <Grid Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="3">
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="80*" />
+                    <ColumnDefinition Width="20*" />
+                </Grid.ColumnDefinitions>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="*"/>
+                </Grid.RowDefinitions>
+
+                <StackPanel Grid.Column="0" Grid.Row="0" Margin="0,7,13,10">
+                    <TextBlock Text="Name" Style="{StaticResource StackPanelTextBox}"/>
+                    <TextBox x:Name="tbName" Text="{Binding Data.Name}"/>
+                </StackPanel>
+                <StackPanel Grid.Column="1" Grid.Row="0" Margin="0,0,0,0" VerticalAlignment="Center">
+                    <TextBlock Text="Stock"/>
+                    <mah:NumericUpDown Margin="0,3,0,3" Minimum="0" Interval="1" Value="{Binding Data.InStock}" />
+                </StackPanel>
+            </Grid>
+
+

ProductView.xaml.cs

+
public ProductView(Product product)
+        {
+            InitializeComponent();
+            var viewModel = new ProductViewModel(product);
+            WindowStartupLocation = WindowStartupLocation.CenterScreen;
+
+            viewModel.SaveAction = () =>
+            {
+                DialogResult = true;
+            };
+
+            viewModel.CancelAction = () =>
+            {
+                DialogResult = false;
+            };
+
+            DataContext = viewModel;
+        }
+
+

ProductViewModel

+
public Action SaveAction { get; set; }
+        public Action CancelAction { get; set; }
+        public ICommand Save { get; set; }
+        public ICommand Cancel { get; set; }
+
+
+        private Product _data;
+        public Product Data
+        {
+            get => _data;
+            set => SetProperty(ref _data, value);
+        }
+
+        public ProductViewModel(Product data)
+        {
+            LoadSellers();
+            LoadProductTypes();
+            LoadPackages();
+
+            Data = data;
+            NettoPrice = Data.PurchasePrice;
+
+            Save = new DelegateCommand(() => SaveAction?.Invoke());
+            Cancel = new DelegateCommand(() => CancelAction?.Invoke());
+            HideData = new DelegateCommand(HideMethod);
+            AddProductTypeCommand = new DelegateCommand(AddProductType);
+            EyeColor = @"..\Resources\Images\Eye-grey-48.png";
+        }
+
","

You need an extra data layer if you want to implement edit and cancel behavior of a data model. You can do this by implementing the IEditableObject interface.

+

You should never open the dialog from the view model. Instead, open it from a Button.Click handler in the code-behind. Define a DataTemplate for the dialog and assign it to the Window.ContentTemplate property. Also make sure that the database handling is implemented inside the model.

+

The following example shows how to display a reusable EditDialog (that operates on IEditableObject implementations) from the view. The example also shows how to cancel or commit data changes to the data model.

+

App.xaml

+
<DataTemplate DataType="{x:Type local:Product}">
+  <TextBox Text="{Binding Signature}" />
+</DataTemplate>
+
+

EditDialog.xaml
+Reusable dialog. Simply define a DataTemplate for the Window.ContentTemplate property to change the hosted Content.
+Assign the data to be edited to the EditDialog.DataContext. This dialog can host any data that implements IEditableObject.

+
<Window Content="{Binding}">
+  <Window.Template>
+    <ControlTemplate TargetType="Window">
+      <Grid Background="{TemplateBinding Background}">
+        <Grid.RowDefinitions>
+          <RowDefinition />
+          <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+
+        <AdornerDecorator Grid.Row="0">
+          <ContentPresenter />
+        </AdornerDecorator>
+
+        <!-- Dialog chrome -->
+        <Grid Grid.Row="1">
+          <StackPanel Orientation="Horizontal">
+            <Button Content="Commit"
+                    Click="OnOkButtonClicked" />
+            <Button Content="Cancel"
+                    Click="OnCancelButtonClicked"
+                    IsCancel="True"
+                    IsDefault="True" />
+          </StackPanel>
+
+          <ResizeGrip x:Name="WindowResizeGrip"
+                      HorizontalAlignment="Right"
+                      VerticalAlignment="Bottom"
+                      Visibility="Collapsed"
+                      IsTabStop="false" />
+        </Grid>
+      </Grid>
+      <ControlTemplate.Triggers>
+        <Trigger Property="ResizeMode"
+                 Value="CanResizeWithGrip">
+          <Setter TargetName="WindowResizeGrip"
+                  Property="Visibility"
+                  Value="Visible" />
+        </Trigger>
+      </ControlTemplate.Triggers>
+    </ControlTemplate>
+  </Window.Template>
+</Window>
+
+

EditDialog.xaml.cs

+
public partial class EditDialog : Window
+{
+  public EditDialog()
+  {
+    InitializeComponent();
+    this.Loaded += OnLoaded;
+  }
+
+  // In case the Window is closed using the chrome button
+  protected override void OnClosing(CancelEventArgs e)
+  {
+    if (this.Content is IEditableObject editableObject)
+    {
+      editableObject.CancelEdit();
+    }
+    base.OnClosing(e);
+  }
+
+  private void OnLoaded(object sender, EventArgs e)
+  {
+    // Content is set via data binding
+    if (this.Content is IEditableObject editableObject)
+    {
+      editableObject.BeginEdit();
+    }
+  }
+
+  private void OnCancelButtonClicked(object sender, RoutedEventArgs e)
+  {
+    if (this.Content is IEditableObject editableObject)
+    {
+      editableObject.CancelEdit();
+    }
+    this.Close();
+  }
+
+  private void OnOkButtonClicked(object sender, RoutedEventArgs e)
+  {
+    if (this.Content is IEditableObject editableObject)
+    {
+      editableObject.EndEdit();
+    }
+    this.Close();
+  }
+}
+
+

MainWindow.xaml

+
<DataGrid ItemsSource="{Binding ProductsCollectionView}"
+          SelectedItem="{Binding SelectedItem}">
+  <DataGrid.RowStyle>
+    <Style TargetType="DataGridRow">
+      <EventSetter Event="MouseDoubleClick"
+                   Handler="DataGridRow_MouseDoubleClick" />
+    </Style>
+  </DataGrid.RowStyle>
+</DataGrid>
+
+

MainWindow.xaml.cs

+
partial class MainWindow : Window
+{
+  public MainWindow()
+  {
+    InitializeComponent();
+    this.DataContext = new ProductListViewModel();
+  }
+
+  private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
+  {
+    var productListViewModel = this.DataContext as ProductListViewModel;
+
+    // Alternatively, create a e.g., EditItem dependency property
+    // and bind it to the DataGrid.SelectedItem
+    Product editItem = productListViewModel.SelectedItem;
+
+    var editDialog = new EditDialog()
+    {
+      DataContext = editItem 
+    };
+    editDialog.ShowDialog();
+  }
+}
+
+

Product.cs

+
class Product : INotifyPropertyChanged, IEditableObject
+{
+  internal class ProductData
+  {
+    // Use object.MemberwiseClone to create a shallow copy
+    public ProductData Clone() => MemberwiseClone() as ProductData;
+
+    public string Signature { get; set; }
+  }
+
+  public Product()
+  {
+    this.EditData = new ProductData();
+    this.BackupData = new ProductData();
+  }
+
+  public void BeginEdit()
+  {
+    if (this.IsInEditMode)
+    {
+      // Consider to throw an exception
+      return;
+    }
+
+    // Creates a shallow copy.
+    // If required, use a copy constructor to create a deep copy.
+    this.BackupData = this.EditData.Clone();
+
+    this.IsInEditMode = true;
+  }
+
+  public void CancelEdit()
+  {
+    if (!this.IsInEditMode)
+    {
+      // Consider to throw an exception
+      return;
+    }
+    this.EditData = this.BackupData;
+    this.IsInEditMode = false;
+
+    // Raise change notification for all public properties
+    // to undo potential binding changes
+    OnPropertyChanged(null);
+  }
+
+  public void EndEdit()
+  {
+    this.IsInEditMode = false;
+  }
+
+  public string Signature
+  {
+    get => this.EditData.Signature;
+    set
+    {
+      this.EditData.Signature = value;
+      OnPropertyChanged();
+    }
+  }
+
+  public bool IsInEditMode { get; private set; }
+  private ProductData BackupData { get; set; }
+  private ProductData EditData { get; set; }
+}
+
",r +"How to extract Parent.Parent field value from SOQL Query?

This is my query

+
SOBject acc = [Select Id, Name, (Select Id, Account.Parent.Parent.Name, Name from Contacts__r) from Sales_Location__c where Id ='a005j000009xxxBAxU'];
+Contact abc =(Contact)(acc.getSobjects('Contacts__r')).get(0);
+System.debug(abc.get('Account.Parent.Parent.Name'));
+
+

But instead of using get() if I directly use abc.Account.Parent.Parent.Name, I am getting result. But I don't know why my code fails in case of get(). In Actual scenario abc is of SObject type that's why I need to use get() here.

","

sObject.get() works on only 1 field, it will not travel via "dots". See https://salesforce.stackexchange.com/a/24804/799 (shameless plug, it's my own answer)

+

You can try like that

+
Sales_Location__c location = [Select Id, Name, 
+    (Select Id, Account.Parent.Parent.Name, Name from Contacts__r)
+    from Sales_Location__c 
+    where Id ='a005j000009xxxBAxU'];
+
+if(!location.Contacts__r.isEmpty()){
+    Contact abc = location.Contacts__r[0];
+    if(abc.Account != null && abc.Account.Parent != null && abc.Account.Parent.Parent != null){
+        System.debug(abc.Account.Parent.Parent.Name);
+    } else {
+        System.debug('there is no grandparent account');
+    }
+}
+
+

but this null checking gets very annoying after a while. There's a fairly recent addition https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SafeNavigationOperator.htm

+
// the query is stupid, the parent name will always be null
+// but my point is it's accessed safely, it won't throw the
+// null reference exception
+Contact c = [SELECT Account.Parent.Name 
+    FROM Contact 
+    WHERE Account.ParentId = null
+    LIMIT 1];
+System.debug(c.Account?.Parent?.Name);
+
+

P.S. even if your function receives a generic sObject - you can always try to cast it back to the original

+

Sales_Location__c loc = (Sales_Location__c) abc;

+

So it'll give you simpler code later on, compile-time checks... Don't suffer with generic sobjects if you don't have to. Check instanceof too if your function can accept sobjects from multiple sources

",r +"Java - Create a button from a shape

I am learning Java currently and have been given the assignmnet of finidhing off a program to create the game Conways's life (we started with some code provided to us and must add features etc to this).

+

I am currently stuck on a menu option for the game. I want it to start off at the menu screen, wherein buttons appear at the top for "Start", "Random", "Load", Save". I have written code so that the program displays these buttons, through a fillRect option in my paint method.

+

My question is, how do I use the mousePressed method to recognise the cells selected so that I can get an action to occur when they are selected. I been looking at this for a while but can't seem to get this working.

+

Any suggestion would be a massive help. I have shared my code below. It's a work in progress but I would really like to get this working before continuing on with the other functionality.

+
import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import java.awt.image.*;
+
+public class ConwaysLife extends JFrame implements Runnable, MouseListener {
+    
+    // member data
+    private BufferStrategy strategy;
+    private Graphics offscreenBuffer;
+    private boolean gameState[][] = new boolean[40][40];
+    private boolean isGameInProgress = false;
+    
+    // constructor
+    public ConwaysLife () {
+        //Display the window, centred on the screen
+         Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
+         int x = screensize.width/2 - 400;
+         int y = screensize.height/2 - 400;
+         setBounds(x, y, 800, 800);
+         setVisible(true);
+         this.setTitle("Conway's game of life");
+        
+         // initialise double-buffering
+         createBufferStrategy(2);
+         strategy = getBufferStrategy();
+         offscreenBuffer = strategy.getDrawGraphics();
+        
+         // register the Jframe itself to receive mouse events
+         addMouseListener(this);
+        
+         // initialise the game state
+         for (x=0;x<40;x++) {
+         for (y=0;y<40;y++) {
+             gameState[x][y]=false;
+         }
+         }
+         
+         // create and start our animation thread
+         Thread t = new Thread(this);
+         t.start();
+    }
+    
+    // thread's entry point
+    public void run() {
+        while ( 1==1 ) {
+        // 1: sleep for 1/5 sec
+            try {
+                Thread.sleep(200);
+        } catch (InterruptedException e) { }
+            
+        // 2: animate game objects [nothing yet!]
+        /*if (isGameInProgress == false) {
+            this.repaint();
+        }*/
+            
+            
+            
+            
+            
+        
+        // 3: force an application repaint
+        this.repaint();
+    }
+    }
+    
+    
+    // mouse events which must be implemented for MouseListener
+     public void mousePressed(MouseEvent e) {
+         
+         while (!isGameInProgress) {
+             int x = e.getX()/20;
+             int y = e.getY()/20;
+             if(x >= 10 && x <= 80 && y >= 40 && y <= 65) {
+                 isGameInProgress = !isGameInProgress;
+                 this.repaint();
+             }
+             
+         }
+         
+    
+     // determine which cell of the gameState array was clicked on
+         int x = e.getX()/20;
+         int y = e.getY()/20;
+         // toggle the state of the cell
+         gameState[x][y] = !gameState[x][y];
+         // request an extra repaint, to get immediate visual feedback
+         this.repaint();
+     }
+     
+     
+     public void mouseReleased(MouseEvent e) { }
+     public void mouseEntered(MouseEvent e) { }
+     public void mouseExited(MouseEvent e) { }
+     public void mouseClicked(MouseEvent e) { }
+    //
+     
+    
+     
+    // application's paint method
+    public void paint(Graphics g) {
+        Font font = new Font("Veranda", Font.BOLD, 20);
+            
+        g = offscreenBuffer; // draw to off screen buffer
+        
+        // clear the canvas with a big black rectangle
+        g.setColor(Color.BLACK);
+        g.fillRect(0, 0, 800, 800);
+        
+        /*look to add a while game in progress loop here!!!*/
+        // draw menu options
+        if(!isGameInProgress) {
+        g.setColor(Color.green); 
+        g.fillRect(10, 40, 70, 25);
+        g.fillRect(100, 40, 100, 25);
+        g.fillRect(300, 40, 170, 25);
+    
+        g.setColor(Color.BLACK);
+        g.setFont(font);
+        g.drawString("Start", 15, 60);
+        g.drawString("Random", 105, 60);
+        g.drawString("Load", 305, 60);
+        g.drawString("Save", 395, 60);
+        }
+            
+        // redraw all game objects
+        g.setColor(Color.WHITE);
+             for (int x=0;x<40;x++) {
+                 for (int y=0;y<40;y++) {
+                     if (gameState[x][y]) {
+                         g.fillRect(x*20, y*20, 20, 20);
+                     }
+                 }
+             }
+             
+            // flip the buffers
+            strategy.show();
+    }
+    
+    // application entry point
+    public static void main(String[] args) {
+    ConwaysLife w = new ConwaysLife();
+    }
+}
+
","

You're not going to like the answer, but it's the "correct" way to approach the problem.

+

What you need to understand is, Swing/AWT is using a "passive" rendering workflow and BufferStrategy is using a "active" rendering workflow, these are incompatible with each other.

+

As a general rule, you should not be overriding paint of top level containers like JFrame, this is going to end in no end of issues. Instead, you should be starting with something like JPanel and overriding it's paintComponent method instead.

+

Having said that, there's a "simpler" solution available to you. CardLayout. This will allow you to seperate the workflows of the menu from the game and resolve the issue between Swing/AWT and BufferStrategy

+

For example...

+
import java.awt.Canvas;
+import java.awt.CardLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.EventQueue;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.image.BufferStrategy;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+
+public final class Main {
+    public static void main(String[] args) {
+        new Main();
+    }
+
+    public Main() {
+        EventQueue.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                JFrame frame = new JFrame();
+                frame.add(new MainPane());
+                frame.pack();
+                frame.setLocationRelativeTo(null);
+                frame.setVisible(true);
+            }
+        });
+    }
+
+    public class MainPane extends JPanel {
+
+        enum View {
+            MENU, GAME;
+        }
+
+        private CardLayout cardLayout = new CardLayout();
+        private GamePane gamePane;
+
+        public MainPane() {
+            setLayout(cardLayout);
+
+            gamePane = new GamePane();
+
+            add(new MenuPane(new MenuPane.Observer() {
+                @Override
+                public void startNewGame() {
+                    showGame();
+                }
+
+                @Override
+                public void randomGame() {
+                }
+
+                @Override
+                public void loadGame() {
+                }
+
+                @Override
+                public void saveGame() {
+                }
+            }), View.MENU);
+            add(gamePane, View.GAME);
+        }
+
+        protected void add(Component compent, View view) {
+            add(compent, view.name());
+        }
+
+        protected void showGame() {
+            show(View.GAME);
+            gamePane.start();
+        }
+
+        protected void showMenu() {
+            gamePane.stop();
+            show(View.MENU);
+        }
+
+        protected void show(View view) {
+            cardLayout.show(this, view.name());
+        }
+
+    }
+
+    public class MenuPane extends JPanel {
+
+        public interface Observer {
+            public void startNewGame();
+            public void randomGame();
+            public void loadGame();
+            public void saveGame();
+        }
+
+        private Observer observer;
+
+        public MenuPane(Observer observer) {
+            this.observer = observer;
+
+            JButton startButton = new JButton("Start");
+            JButton randomButton = new JButton("Random");
+            JButton loadButton = new JButton("Load");
+            JButton saveButton = new JButton("Save");
+
+            setLayout(new GridBagLayout());
+            GridBagConstraints gbc = new GridBagConstraints();
+            gbc.ipadx = 10;
+            gbc.ipady = 10;
+            gbc.insets = new Insets(8, 8, 8, 8);
+            gbc.weightx = GridBagConstraints.REMAINDER;
+
+            add(startButton, gbc);
+            add(randomButton, gbc);
+            add(loadButton, gbc);
+            add(saveButton, gbc);
+
+            startButton.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    observer.startNewGame();
+                }
+            });
+            randomButton.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    observer.randomGame();
+                }
+            });
+            loadButton.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    observer.loadGame();
+                }
+            });
+            saveButton.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    observer.saveGame();
+                }
+            });
+        }
+
+    }
+
+    public class GamePane extends Canvas {
+
+        private Thread thread;
+        private volatile boolean isRunning = false;
+
+        public GamePane() {
+            setBackground(Color.BLACK);
+        }
+
+        @Override
+        public Dimension getPreferredSize() {
+            return new Dimension(800, 800);
+        }
+
+        protected void start() {
+            if (isRunning) {
+                return;
+            }
+            createBufferStrategy(3);
+            isRunning = true;
+            thread = new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    mainLoop();
+                }
+            });
+            thread.start();
+        }
+
+        protected void stop() {
+            if (!isRunning || thread == null) {
+                return;
+            }
+            isRunning = false;
+            try {
+                thread.join();
+            } catch (InterruptedException ex) {
+            }
+            thread = null;
+        }
+
+        protected void mainLoop() {
+            try {
+                while (isRunning) {
+                    render();
+                    Thread.sleep(16);
+                }
+            } catch (InterruptedException ex) {
+            }
+        }
+
+        protected void render() {
+            BufferStrategy strategy = getBufferStrategy();
+            if (strategy == null) {
+                return;
+            }
+            // Render single frame
+            do {
+                // The following loop ensures that the contents of the drawing buffer
+                // are consistent in case the underlying surface was recreated
+                do {
+                    // Get a new graphics context every time through the loop
+                    // to make sure the strategy is validated
+                    Graphics graphics = strategy.getDrawGraphics();
+
+                    FontMetrics fm = graphics.getFontMetrics();
+                    String text = "All your game are belong to us";
+                    int x = (getWidth() - fm.stringWidth(text)) / 2;
+                    int y = (getHeight() - fm.getHeight()) / 2;
+
+                    graphics.setColor(Color.WHITE);
+                    graphics.drawString(text, x, y + fm.getAscent());
+
+                    // Render to graphics
+                    // ...
+                    // Dispose the graphics
+                    graphics.dispose();
+
+                    // Repeat the rendering if the drawing buffer contents
+                    // were restored
+                } while (strategy.contentsRestored());
+
+                // Display the buffer
+                strategy.show();
+
+                // Repeat the rendering if the drawing buffer was lost
+            } while (strategy.contentsLost());
+        }
+    }
+}
+
+

I would strongly recommend that you take the time to read through:

+ +

A "fully" BufferStrategy based approach...

+

Now, if you can't use Swing, "for reasons", you can still achieve a simular concept using "delegation".

+

Basically this means "delegating" responsibility for performing some workflow to another. In this case, we want to delegate the rendering and the handling of the mouse events.

+

This allows you to have a dedicated workflow for the menu and a dedicated workflow for the game, without having to try and mix a lot of state.

+

Why do I keep on insisting on separating these two workflows? Simply, because it makes it MUCH easier to manage and reason about, but also because it supports the Single Responsibility Principle.

+

The follow example makes use of Renderable interface to define the core functionality that end "render" delegate will need to implement, in this case, it's pretty simple, we want to tell the renderer to "render" it's content on each paint pass and we want to (optionally) delegate mouse clicked events (this could be done via a second interface or even just the MouseListener interface directly, but I've made it a requirement of the Renderable interface for demonstration purposes.

+

The "basic" solution to your actual question is found through the use of Rectangle#contains(Point).

+

This basically inspects each "button" Rectangle to determine if the supplied MouseEvent occurs within it's bounds, if it does, we take action.

+

It is, however, a little more complicated then that, as we need to have the Rectangles built ahead of time, not difficult, but it's state which is actually reliant on the parent, as we need to know the area in which the renderer is been displayed, run the example, you'll see what I mean

+
import java.awt.Canvas;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.EventQueue;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.geom.RoundRectangle2D;
+import java.awt.image.BufferStrategy;
+import javax.swing.JFrame;
+
+public final class Main {
+    public static void main(String[] args) {
+        new Main();
+    }
+
+    public Main() {
+        EventQueue.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                MainPane mainPane = new MainPane();
+                JFrame frame = new JFrame();
+                frame.add(mainPane);
+                frame.pack();
+                frame.setLocationRelativeTo(null);
+                frame.setVisible(true);
+
+                mainPane.start();
+            }
+        });
+    }
+
+    public interface Renderable {
+        public void render(Graphics2D g2d, Dimension size);
+
+        // We could just extend from MouseListener
+        // but I don't need all those event handlers
+        public void mouseClicked(MouseEvent e);
+    }
+
+    public class MainPane extends Canvas {
+
+        private Thread thread;
+        private volatile boolean isRunning = false;
+
+        private Renderable currentRenderer;
+
+        private MenuRenderer menuRenderer;
+        private GameRenderer gameRenderer;
+
+        public MainPane() {
+            setBackground(Color.BLACK);
+
+            gameRenderer = new GameRenderer();
+            menuRenderer = new MenuRenderer(new MenuRenderer.Observer() {
+                @Override
+                public void startNewGame() {
+                    showGame();
+                }
+
+                @Override
+                public void randomGame() {
+                }
+
+                @Override
+                public void loadGame() {
+                }
+
+                @Override
+                public void saveGame() {
+                }
+            });
+
+            showMenu();
+
+            addMouseListener(new MouseAdapter() {
+                @Override
+                public void mouseClicked(MouseEvent e) {
+                    if (currentRenderer == null) {
+                        return;
+                    }
+                    currentRenderer.mouseClicked(e);
+                }
+            });
+        }
+
+        protected void showMenu() {
+            // This may need to tell the game renderer to stop
+            // or pause
+            currentRenderer = menuRenderer;
+        }
+
+        protected void showGame() {
+            currentRenderer = gameRenderer;
+        }
+
+        @Override
+        public Dimension getPreferredSize() {
+            return new Dimension(800, 800);
+        }
+
+        protected void start() {
+            if (isRunning) {
+                return;
+            }
+            createBufferStrategy(3);
+            isRunning = true;
+            thread = new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    mainLoop();
+                }
+            });
+            thread.start();
+        }
+
+        protected void stop() {
+            if (!isRunning || thread == null) {
+                return;
+            }
+            isRunning = false;
+            try {
+                thread.join();
+            } catch (InterruptedException ex) {
+            }
+            thread = null;
+        }
+
+        protected void mainLoop() {
+            try {
+                while (isRunning) {
+                    render();
+                    Thread.sleep(16);
+                }
+            } catch (InterruptedException ex) {
+            }
+        }
+
+        protected void render() {
+            BufferStrategy strategy = getBufferStrategy();
+            if (strategy == null && currentRenderer != null) {
+                return;
+            }
+            // Render single frame
+            do {
+                // The following loop ensures that the contents of the drawing buffer
+                // are consistent in case the underlying surface was recreated
+                do {
+                    // Get a new graphics context every time through the loop
+                    // to make sure the strategy is validated
+                    Graphics2D g2d = (Graphics2D) strategy.getDrawGraphics();
+                    g2d.setBackground(Color.BLACK);
+                    g2d.fillRect(0, 0, getWidth(), getHeight());
+                    RenderingHints hints = new RenderingHints(
+                            RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON
+                    );
+                    g2d.setRenderingHints(hints);
+                    // Render to graphics
+                    currentRenderer.render(g2d, getSize());
+                    // Dispose the graphics
+                    g2d.dispose();
+                    // Repeat the rendering if the drawing buffer contents
+                    // were restored
+                } while (strategy.contentsRestored());
+
+                // Display the buffer
+                strategy.show();
+
+                // Repeat the rendering if the drawing buffer was lost
+            } while (strategy.contentsLost());
+        }
+    }
+
+    public class GameRenderer implements Renderable {
+        @Override
+        public void render(Graphics2D g2d, Dimension size) {
+            FontMetrics fm = g2d.getFontMetrics();
+            String text = "All your game are belong to us";
+            int x = (size.width - fm.stringWidth(text)) / 2;
+            int y = (size.height - fm.getHeight()) / 2;
+
+            g2d.setColor(Color.WHITE);
+            g2d.drawString(text, x, y + fm.getAscent());
+        }
+
+        @Override
+        public void mouseClicked(MouseEvent e) {
+        }
+    }
+
+    public class MenuRenderer implements Renderable {
+
+        public interface Observer {
+            public void startNewGame();
+            public void randomGame();
+            public void loadGame();
+            public void saveGame();
+        }
+
+        private Observer observer;
+
+        private String[] menuOptions = new String[]{
+            "New Game",
+            "Random",
+            "Load Game",
+            "Save Game"
+        };
+
+        private Rectangle[] menuBounds;
+
+        private int internalPadding = 20;
+        private int horizontalGap = 16;
+
+        public MenuRenderer(Observer observer) {
+            this.observer = observer;
+        }
+
+        @Override
+        public void render(Graphics2D g2d, Dimension size) {
+            if (menuBounds == null) {
+                createMenus(g2d, size);
+            }
+            renderMenus(g2d);
+        }
+
+        protected void createMenus(Graphics2D g2d, Dimension size) {
+            FontMetrics fm = g2d.getFontMetrics();
+            int totalHeight = (((fm.getHeight() + internalPadding) + horizontalGap) * menuOptions.length) - horizontalGap;
+            int buttonHeight = fm.getHeight() + internalPadding;
+
+            menuBounds = new Rectangle[menuOptions.length];
+
+            int buttonWidth = 0;
+            for (int index = 0; index < menuOptions.length; index++) {
+                int width = fm.stringWidth(menuOptions[index]) + internalPadding;
+                buttonWidth = Math.max(width, buttonWidth);
+            }
+
+            int yPos = (size.height - totalHeight) / 2;
+            for (int index = 0; index < menuOptions.length; index++) {
+                int xPos = (size.width - buttonWidth) / 2;
+                Rectangle menuRectangle = new Rectangle(xPos, yPos, buttonWidth, buttonHeight);
+                menuBounds[index] = menuRectangle;
+                yPos += buttonHeight + (horizontalGap / 2);
+            }
+        }
+
+        protected void renderMenus(Graphics2D g2d) {
+            for (int index = 0; index < menuOptions.length; index++) {
+                String text = menuOptions[index];
+                Rectangle bounds = menuBounds[index];
+                renderMenu(g2d, text, bounds);
+            }
+        }
+
+        protected void renderMenu(Graphics2D g2d, String text, Rectangle bounds) {
+            FontMetrics fm = g2d.getFontMetrics();
+            int textWidth = fm.stringWidth(text);
+
+            int textXPos = (bounds.x + (internalPadding / 2)) + ((bounds.width - internalPadding - textWidth) / 2);
+            int textYPos = bounds.y + (internalPadding / 2);
+
+            RoundRectangle2D buttonBackground = new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height, 20, 20);
+
+            g2d.setColor(Color.BLUE.darker());
+            g2d.fill(buttonBackground);
+
+            g2d.setColor(Color.WHITE);
+            g2d.drawString(text, textXPos, textYPos + fm.getAscent());
+        }
+
+        @Override
+        public void mouseClicked(MouseEvent e) {
+            if (menuBounds == null) {
+                return;
+            }
+            for (int index = 0; index < menuOptions.length; index++) {
+                if (menuBounds[index].contains(e.getPoint())) {
+                    switch (index) {
+                        case 0:
+                            observer.startNewGame();
+                            break;
+                        case 2:
+                            observer.randomGame();
+                            break;
+                        case 3:
+                            observer.loadGame();
+                            break;
+                        case 4:
+                            observer.saveGame();
+                            break;
+                    }
+                }
+            }
+        }
+    }
+}
+
",r +"Java Stack error after getting last element via pop method

I have the following code for the solution of Hackerrank.

+
public static void main(String[] args) {
+        System.out.println(isBalanced("{(([])[])[]}"));
+}
+
+public static String isBalanced(String s) {
+    Stack<Character> stack = new Stack<>();
+    stack.push(s.charAt(0));
+
+    for (int i = 1; i < s.length(); i++) {
+        Character c = s.charAt(i);
+        Character cStack = stack.peek();
+
+
+        if (cStack == '{' && c == '}' 
+            || cStack == '[' && c == ']' 
+            || cStack == '(' && c == ')') {
+            stack.pop();
+        } else {
+            stack.push(c);
+        }
+    }
+
+    if (stack.isEmpty())
+        return "YES";
+    return "NO";
+}
+
+

Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.

+

So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?

+

Update:

+
public static String isBalanced(String s) {
+    Stack<Character> stack = new Stack<>();
+    stack.push(s.charAt(0));
+
+    for (int i = 1; i < s.length(); i++) {
+        Character c = s.charAt(i);
+
+        if (c == '{' || c == '[' || c == '(') {
+            stack.push(c);
+        } else if (stack != null) {
+            Character cStack = stack.peek();
+            if (cStack == '{' && c == '}'
+                    || cStack == '[' && c == ']'
+                    || cStack == '(' && c == ')') {
+                stack.pop();
+            }
+        }
+    }
+    if (stack.isEmpty())
+        return "YES";
+    return "NO";
+}
+
","

Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
+If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.

",r +"SQL inner-join query

I'm trying to make a inner-join, but I can get it to work. +This is my sql query

+
SELECT highscore.score, bruger.brugerNavn FROM highscore INNER JOIN bruger ON highscore.brugerID ON bruger.brugerID ORDER BY score DESC
+
+

I end up with this error

+
SELECT highscore.score, bruger.brugerNavn FROM highscore INNER JOIN bruger ON highscore.brugerID ON bruger.brugerID LIMIT 0, 25
+#1064 - There is an error in the SQL syntax near 'ON bruger.brugerID LIMIT 0, 25' at line 1
+
+

I would appreciate any help:)

","

Try this first:

+
SELECT h.score, b.brugerNavn 
+FROM highscore as h
+JOIN bruger as b ON h.brugerID = b.brugerID
+
+

I usually add aliases for easier handling.

",r +how to show back press button in a fragment

yes there are a lot of results about it i tried but i couldn't find the right answer. I have a navigation graph team. I have an activity and Four Fragments. I want to put the back press button in the transition between the fragments

,"

Just use findNavController, it is easy to navigate but be sure to add action to your navigation. It will add a back button automatically. +For connect to each other: +nav_graph:

+
<?xml version="1.0" encoding="utf-8"?>
+<navigation
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/my_nav"
+    app:startDestination="@id/firstFragment">
+
+    <fragment
+        android:id="@+id/firstFragment"
+        android:name="com.example.testbackbutton.FirstFragment"
+        android:label="fragment_first"
+        tools:layout="@layout/fragment_first" >
+        <action
+            android:id="@+id/action_firstFragment_to_secondFragment"
+            app:destination="@id/secondFragment" />
+    </fragment>
+    <fragment
+        android:id="@+id/secondFragment"
+        android:name="com.example.testbackbutton.SecondFragment"
+        android:label="fragment_second"
+        tools:layout="@layout/fragment_second" >
+        <action
+            android:id="@+id/action_secondFragment_to_firstFragment"
+            app:destination="@id/firstFragment" />
+    </fragment>
+</navigation>
+
+

MainActivity:

+
class MainActivity : AppCompatActivity() {
+    private lateinit var binding: ActivityMainBinding
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        binding = ActivityMainBinding.inflate(layoutInflater)
+        setContentView(binding.root)
+
+        setupActionBarWithNavController(findNavController(R.id.fragmentContainerView))
+
+    }
+    override fun onSupportNavigateUp(): Boolean {
+        val navController = findNavController(R.id.fragmentContainerView)
+        return navController.navigateUp() or super.onSupportNavigateUp()
+    }
+}
+
+

First fragment:

+
class FirstFragment : Fragment() {
+    private var _binding: FragmentFirstBinding? = null
+    private val binding get() = _binding!!
+    override fun onCreateView(
+        inflater: LayoutInflater, container: ViewGroup?,
+        savedInstanceState: Bundle?
+    ): View? {
+        // Inflate the layout for this fragment
+
+
+        _binding = FragmentFirstBinding.inflate(inflater, container, false)
+
+        binding.btn.setOnClickListener{
+            findNavController().navigate(R.id.action_firstFragment_to_secondFragment)
+        }
+
+        return binding.root
+    }
+    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+        setHasOptionsMenu(true)
+    }
+} 
+
+

First fragment XML:

+
<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context=".FirstFragment">
+
+    <!-- TODO: Update blank fragment layout -->
+    <Button
+        android:id="@+id/btn"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/hello_blank_fragment"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintTop_toTopOf="parent" />
+
+</androidx.constraintlayout.widget.ConstraintLayout>
+
+

The second fragment is the default. +Click the button on the first fragment then you will see the back button on the second fragment.

",r +"Adjust place of downloading buttons of a DT table in Shiny

please see this picture +I have a DT table in the shiny. I added buttons for downloading the content of the table (Copy, CSV, Excel, PDF). But I would like to change the distance between the first button and "show number of entries" (please see the attached picture and below code). How can I set the distance between the first button and "show entries"?

+
output$fancyTable<- renderDataTable ({    
+DT::datatable(data, extensions = "Buttons", options = list(paging = TRUE, scrollX=TRUE, searching = TRUE, ordering = TRUE,dom = 'l<"sep">Bfrtip',
+
+                                 buttons = c('copy', 'csv', 'excel', 'pdf'),
+                                 pageLength=5,
+                                 lengthMenu=c(5,10,20,100) ))
+
+

here is my UI code for the table:

+
 mainPanel(
+                 # actionButton("download1", "Download table"),
+                  tags$head(
+                   tags$style(HTML("
+                .sep {
+                   width: 20px;
+                   }
+                     "))
+                       ),
+                 DT::dataTableOutput("fancyTable"),
+                 tags$hr(),
+                 plotlyOutput("fancyPlot"
+                              ,width = "auto"
+                              , height = "auto"
+                 ),
+                 
+
+

enter image description here

","

You can do dom = 'l<"sep">Bfrtip' and this will add a div between l and B having class sep. Then in your shiny app define the CSS for the sep class:

+
.sep {
+  width: 20px;
+  height: 1px;
+  float: left;
+}
+
+

You can set this CSS in the Shiny UI as below:

+
tags$head(
+  tags$style(HTML("
+    .sep {
+      width: 20px;
+      height: 1px;
+      float: left;
+    }
+  "))
+)
+
",r +"can I make validators like in textfield in my custom widget?
   TextFormField(
+      validator: validator,
+   ),
+
+

in textfield, there is a property called validator that can be used with Form widget to show an error. I need to make a validator in my custom widget that can also work inside the Form widget. how to do that?

+

let say my custom widget is like below:

+
class MyCustomWidget extends StatelessWidget {
+  const MyCustomWidget({Key? key}) : super(key: key);
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      width: double.infinity,
+      height: 100,
+      color: Colors.green,
+    );
+  }
+}
+
+

how to make my own validator to show error below that green container that can work inside the Form widget ?

","

Yes, You can make a custom form field like the below.

+
class CounterFormField extends FormField<int> {
+
+  CounterFormField({
+    FormFieldSetter<int> onSaved,
+    FormFieldValidator<int> validator,
+    int initialValue = 0,
+    bool autovalidate = false
+  }) : super(
+      onSaved: onSaved,
+      validator: validator,
+      initialValue: initialValue,
+      autovalidate: autovalidate,
+      builder: (FormFieldState<int> state) {
+        return Column(
+          children: <Widget>[
+            Row(
+              mainAxisSize: MainAxisSize.min,
+              children: <Widget>[
+                IconButton(
+                  icon: Icon(Icons.remove),
+                  onPressed: () {
+                    state.didChange(state.value - 1);
+                  },
+                ),
+                Text(
+                    state.value.toString()
+                ),
+                IconButton(
+                  icon: Icon(Icons.add),
+                  onPressed: () {
+                    state.didChange(state.value + 1);
+                  },
+                ),
+              ],
+            ),
+            state.hasError?
+            Text(
+              state.errorText,
+              style: TextStyle(
+                  color: Colors.red
+              ),
+            ) :
+            Container()
+          ],
+        );
+      }
+  );
+
+

Use

+
CounterFormField(
+   autovalidate: false,
+   validator: (value) {
+     if (value < 0) {
+       return 'Negative values not supported';
+     }
+    },
+   onSaved: (value) => this._age = value,
+)
+
",r +"How to delete specific users in bulk in WordPress?

How can WordPress delete users in bulk when the user_id is already known?

+

Is there an easy way to do this? For example SQL CLI or PHP CLI or something like that. Has anyone already done this?

","

Use the WordPress CLI. There's a user delete command which can accept a list.

+

Examples from the docs:

+
# Delete user 123 and reassign posts to user 567
+$ wp user delete 123 --reassign=567
+Success: Removed user 123 from http://example.com
+
+# Delete all contributors and reassign their posts to user 2
+$ wp user delete $(wp user list --role=contributor --field=ID) --reassign=2
+
+

Documentation: https://developer.wordpress.org/cli/commands/user/delete/

",r +"Watir Set value of input type=""text""

I am trying to set an email into this span but I'm having trouble selecting it and updating it. The span id is created dynamically but the class is not

+
<div class="input input-lg    form-input">
+
+    <span id="foundation-text-input-3535" class="input-label ">Email*</span>
+
+    <input type="text" aria-labelledby="foundation-text-input-3535" placeholder="" value="" autocomplete="off" data-qa="email_input"></div>
+
","

it should be getting set via the input element, not the span, right?

+
browser.text_field(data_qa: 'email_input').set email_address
+
+

You can also use regular expressions as well if you need to locate things that way:

+
browser.span(id: /foundation-text-input/)
+
+

Results from irb:

+
irb(main):001:0> require 'watir'
+=> true
+irb(main):002:0> browser = Watir::Browser.new
+=> #<Watir::Browser:0x6e1ac1ec79323ad4 url="data:," title="">
+irb(main):003:0> browser.goto "https://portal.sysco.com/login"
+=> "https://portal.sysco.com/login"
+irb(main):004:0> browser.text_field(data_qa: 'email_input').set "test"
+=> nil
+irb(main):005:0> browser.text_field(data_qa: 'email_input').value
+=> "test"
+
",r +"Jetpack Compose - Make the first element in a LazyRow be aligned to the center of the screen

I want to obtain a LazyRow that looks like this:

+

|--aaa-b|bb-cccc|-dd... ...|w--x---|

+

|-------| is one screen width

+

The size of the elements varies but they have a fixed spacing between them. +I thought I could add some start content padding to the LazyRow so that the "aaa" Composable is aligned to the center of the screen, but I don't know its width.

+

If you think it's not clear what I'm asking, please drop a comment.

+

UPDATE

+

Added a gif for better understanding

+

","

You can use the BoxWithConstraints to get screen width. Then you can use Layout to properly positioning the item in the list.

+
@Composable
+fun BigCarousel() {
+    val items = (0..10).map { "Item $it" }
+    BoxWithConstraints {
+        LazyRow {
+            itemsIndexed(items) { index, item ->
+                Layout(
+                    content = {
+                        // Here's the content of each list item.
+                        Box(
+                            Modifier
+                                .size(200.dp)
+                                .padding(8.dp)
+                                .background(Color.Gray)
+                        ) {
+                            Text(text = item, Modifier.align(Alignment.Center))
+                        }
+                    },
+                    measurePolicy = { measurables, constraints ->
+                        // I'm assuming you'll declaring just one root 
+                        // composable in the content function above
+                        // so it's measuring just the Box
+                        val placeable = measurables.first().measure(constraints)
+                        // maxWidth is from the BoxWithConstraints
+                        val maxWidthInPx = maxWidth.roundToPx()
+                        // Box width
+                        val itemWidth = placeable.width
+                        // Calculating the space for the first and last item
+                        val startSpace =
+                            if (index == 0) (maxWidthInPx - itemWidth) / 2 else 0
+                        val endSpace =
+                            if (index == items.lastIndex) (maxWidthInPx - itemWidth) / 2 else 0
+                        // The width of the box + extra space
+                        val width = startSpace + placeable.width + endSpace
+                        layout(width, placeable.height) {
+                            // Placing the Box in the right X position
+                            val x = if (index == 0) startSpace else 0
+                            placeable.place(x, 0)
+                        }
+                    }
+                )
+            }
+        }
+    }
+}
+
+

Here's the result:

+

",r +"Python reflection after module reloading

I am trying to reflect a module after reloading it. Every time I change the module, I need to reflect it to see its current state. The problem is that it remembers all of its previous states. Here is my code.

+

main.py

+
from tkinter import *
+from importlib import reload
+
+def fun():
+    import second
+    reload(second)
+    print(dir(second))
+
+root=Tk()
+Button(root,text='reload',command=fun).pack()
+root.mainloop()
+
+

second.py

+
var1='hello'
+
+

When I change the variable name in 'second.py' from 'var1' to 'var2' for example, it prints both variables 'var1' and 'var2'. +I need only the latest version of the module (only 'var2').

+

Thanks for help

","

importlib.reload updates the module's global namespace, i.e. it retains the old name bindings. If you want a fresh module object, you can remove the old one from sys.modules before importing it:

+
def fun():
+    sys.modules.pop('second', None)
+    import second
+    ...
+
",r +"Google Spreadsheet: Hide/Unhide any row that meets x condition in a group of rows when clicking button?

When clicking "button1" I would like the code to check the First Cell (Column A) of Rows 38-58 and hide the Row if the corresponding cell is empty and show if it isn't.

+

Empty in this case means the cell still has a formula but is just blank. If that's not possible, the "Hide Condition" can be Cells that are not a number.

+

I'd like to combine it with the code below, which hides and shows Rows 10 and 11 when Cell C4 and D4 equal 0 respectively.

+
function button2(){
+  var ss = SpreadsheetApp.getActive();
+  var sheet = ss.getActiveSheet();
+
+  var cellRef1 = "C4";
+  var cellRef2 = "D4";
+  var cell1 = sheet.getRange(cellRef1);
+  var cell2 = sheet.getRange(cellRef2);
+  var value1 = cell1.getValue();
+  var value2 = cell2.getValue();
+  
+  if (value1 == "0"){
+    sheet.hideRows(10);
+  }
+  if (value2 == "0"){
+    sheet.hideRows(11);
+  }
+  if (value1 != "0"){
+    sheet.showRows(10);
+  }
+  if (value2 != "0"){
+    sheet.showRows(11);
+  };
+};
+
","

You can hide/unhide the rows this way:

+
function hide_unhide_rows() {
+  var sheet = SpreadsheetApp.getActiveSheet();
+  var rows = sheet.getRange('a38:a58').getDisplayValues().flat();
+
+  rows.forEach((cell_value,i) => {
+    let index = i+38;
+    if (cell_value == '' && !sheet.isRowHiddenByUser(index)) sheet.hideRows(index);
+    if (cell_value != '' &&  sheet.isRowHiddenByUser(index)) sheet.unhideRows(index);
+  });
+}
+
+

As for the how it can be combine with your code, you can just add at the end of your function this line:

+
hide_unhide_rows();
+
+

Or, here is the full combined code:

+
function button2() {
+  var sheet = SpreadsheetApp.getActiveSheet();
+  var value1 = sheet.getRange('c4').getValue();
+  var value2 = sheet.getRange('d4').getValue();
+  
+  if (value1 == 0) { sheet.hideRows(10) } else { sheet.showRows(10) }
+  if (value2 == 0) { sheet.hideRows(11) } else { sheet.showRows(11) }
+
+  var rows = sheet.getRange('a38:a58').getDisplayValues().flat();
+
+  rows.forEach((cell_value, i) => {
+    let index = i+38;
+    if (cell_value == '' && !sheet.isRowHiddenByUser(index)) sheet.hideRows(index);
+    if (cell_value != '' &&  sheet.isRowHiddenByUser(index)) sheet.unhideRows(index);
+  });
+}
+
+

Update

+

If you have several ranges to process, you have to change several lines in the code this way:

+
function button(){
+  var sheet = SpreadsheetApp.getActiveSheet();
+  var value1 = sheet.getRange('c4').getValue();
+  var value2 = sheet.getRange('d4').getValue();
+
+  if (value1 == 0) { sheet.hideRows(10) } else { sheet.showRows(10) }
+  if (value2 == 0) { sheet.hideRows(11) } else { sheet.showRows(11) }
+  
+  var list = ['a27:a29','a41:a60','a66:a85']; // <----------------- here
+  var rangeList = sheet.getRangeList(list).getRanges(); // <------- here
+  for (var range in rangeList){
+    var rows = rangeList[range].getDisplayValues().flat();
+    var shift = +list[range].split(':')[0].slice(1); // <---------- here
+
+    rows.forEach((cell_value, i) => {
+      let index = (i + shift); // <-------------------------------- here
+      if (cell_value == '' && !sheet.isRowHiddenByUser(index)) sheet.hideRows(index);
+      if (cell_value != '' &&  sheet.isRowHiddenByUser(index)) sheet.showRows(index);
+    
+    });
+  }
+}
+
+

If you have too many ranges the code can work slowly. There is a way to improve it a bit. But the hide/unhide operation is sluggish by design. So the code will be quite slow anyway.

",r +"index.android.bundle missing in APK after upgrading to RN 0.68

After upgrading our RN app to RN 0.68, we are getting errors with the release build:

+
FATAL EXCEPTION: create_react_context
+Process: com.app, PID: 15057
+java.lang.RuntimeException: Unable to load script. Make sure you're either running Metro (run 'npx react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release.
+
+

The app works fine in development, and was fine before upgrading. It is using Hermes, but not using the new Fabric architecture.

+

When building the APK and then looking into its content, we can see that the bundle is not copied. But it is correctly built in the intermediate artifacts:

+
$ ./gradlew assembleRelease
+…
+BUILD SUCCESSFUL in 45s
+1050 actionable tasks: 14 executed, 1036 up-to-date
+
+$ unzip -l app/build/outputs/apk/release/app-arm64-v8a-release.apk | grep bundle
+<nothing>
+
+$ ls -l app/build/outputs/apk/release/app-arm64-v8a-release.apk
+-rw-r--r--  1 renchap  staff  15618010 Apr 12 21:03 app/build/outputs/apk/release/app-arm64-v8a-release.apk
+
+$ find . -name "index.android.bundle"
+./app/build/generated/assets/react/release/index.android.bundle
+./app/build/intermediates/merged_assets/release/out/index.android.bundle
+./app/build/intermediates/merged_assets/release/mergeReleaseAssets/out/index.android.bundle
+./app/build/intermediates/assets/release/index.android.bundle
+
+$ ls -lh ./app/build/intermediates/assets/release/index.android.bundle
+-rw-r--r--  1 renchap  staff    11M Apr 12 19:48 ./app/build/intermediates/assets/release/index.android.bundle
+
+

I am suspecting that there is a missing build step and it is not copied to the final directory, but I am not familiar enough with Gradle or RN's build process to check this.

+

Do you have any idea of what can cause this, or where to look at to troubleshoot this?

","

Found it after comparing the build files with a brand new RN app!

+

I had

+
classpath("com.android.tools.build:gradle:7.1.2")
+
+

in android/build.gradle

+

But with RN 0.68, you need to depend exactly on version 7.0.4, otherwise the JS bundle is not copied into the final APK.

+

The release APK is now working after switching to

+
classpath("com.android.tools.build:gradle:7.0.4")
+
",r +"Get max date from columns in Redshift using a dynamically changing list of columns and tables with Python?

I am have a list of timestamp columns that correspond to specific tables in Redshift. I want to be able to grab the most recent date of all the timestamp columns for a given table. I can't just write the column names out because the tables have different column names. I have a dataframe with the table name and columns that I need

+
table_name      column              data_type
+  tbl1       sent_at          timestamp without timezone
+  tbl1       message_received timestamp without timezone
+  tbl1       scene_updated    timestamp without timezone
+  tbl2       phone_updated    timestamp without timezone
+  tbl2       col2_updated     timestamp without timezone
+  tbl3       sent_at          timestamp without timezone
+  tbl3       number_updated   timestamp without timezone
+
+

I want to check from each table, the most recent date of all the timestamp columns. I am trying to create a query that involves creating a string that uses 'max()' and then populates inside the parenthesis to use within the query. Like so:

+
for table in set(df.table_name):
+   sub = df[df.table_name == table]
+   cols = [x for x in sub.column.values.tolist()]
+   str_max = 'max()' * len(cols)
+   que = 'select' + str_max + 'from {}'.format(table)
+   time_table = pd.read_sql_query(que, conn) 
+   .... 
+   
+
+

Then, I would used pandas to get the max value of all the columns. However, I can't figure out how to insert the column name in between the '()' to get the max value when all the column names change. Maybe there is a way within Redshift to look at the max of all column values while using a data_type filter but I don't know how to do that.

","

I solved this by using another for loop and appending the column names to a string. Then, I joined the list into a single string so I could put it into a single query. After the query ran, I used max() to find the max value of all columns.

+
for table in set(df.table_name):
+    sub = created_at_tables[created_at_tables.table_name ==  table]
+    cols = [x for x in sub.column_name.values.tolist() if x != 'table_updated_at']
+    col_str = []
+    for i in cols: 
+       col_str.append('max(' + i + ') as ' + i)
+    col_str = ','.join(col_str)
+    que = 'select {} from schema.{}'.format(col_str, table)
+    new_table = pd.read_sql_query(que, rsm.dbengine)
+    new_table.dropna(axis = 1, inplace = True)
+    most_recent_date = new_table.max(axis=1).reset_index()[0][0]
+
",r +"Firebase tree structure

I am trying to create an application that manages shopping lists. A shopping list has users and products. Which way should I use to create the JSON tree structure:

+
"ShoppingLists": {
+  "ShoppingListId" : {
+    "name" : "String",
+    "description": "String",
+    "imageUrl": "String",
+    "Users" : {
+      "User1Id" : {
+        "username" :"String",
+        "photoUrl" : "String"
+      },
+      "User2Id" : {
+        "username" :"String",
+        "photoUrl" : "String"
+      }
+    },
+    "Products" : {
+      "ProductId1" : {
+        "name" : "String",
+        "productPhotoUrl" : "String"
+      }
+    }
+  }
+
+

This is the first option

+
"ShoppingLists": {
+  "ShoppingListId" : {
+    "name" : "String",
+    "description": "String",
+    "imageUrl": "String",
+    "Users" : {
+      "UserId1" : "String", 
+      "UserId2" : "String"
+    },
+    "Products" : {
+      "ProductId1" : "String"
+    }
+  }
+
+

And this is the second one. In the second option I get the username and the photoUrl using the userId.

+

Which one is better or are both of them bad?

","

There is no objective "better" for a NoSQL database design; it all depends on the use-cases of your app.

+

That said, a common antipattern is to nest multiple types of data under a single branch of your JSON tree. A more regular structure would be to separate those out into their own top-level branches, with the same keys:

+
"ShoppingLists": {
+  "ShoppingListId" : {
+    "name" : "String",
+    "description": "String",
+    "imageUrl": "String",
+  }
+},
+"ShoppingListUsers" : {
+  "ShoppingListId" : {
+      "User1Id" : {
+        "username" :"String",
+        "photoUrl" : "String"
+      },
+      "User2Id" : {
+        "username" :"String",
+        "photoUrl" : "String"
+      }
+    },
+  }
+},
+"ShoppingListProducts" : {
+  "ShoppingListId" : {
+    "Products" : {
+      "ProductId1" : {
+        "name" : "String",
+        "productPhotoUrl" : "String"
+      }
+    }
+  }
+}
+
+

Now you can read all shopping lists, without having to also read the users and products in each shopping list. Plus, this way you can have separate security rules for the lists themselves, their users, and their products.

+

Note that I'm intentionally not focusing on what you store for each user/product in a shopping list, but merely on the nesting of data types.

+

To learn more about this, also see:

+",r +"VSTEST@2 - error could not find testhost | Azure Pipelines

I'm running tests solution on azure pipeline with help of vstest@2 task. +Pipeline distributes test cases on 4 agents and then runs them.

+

Task yaml:

+
  - task: VSTest@2
+    inputs:
+      testSelector: 'testAssemblies'
+      testAssemblyVer2: |
+        **/*.Tests.dll
+      searchFolder: '$(System.DefaultWorkingDirectory)'
+      distributionBatchType: basedOnExecutionTime
+      runInParallel: true
+
+

On beginning of the run I get bunch of these messages :

+
##[error]DiscoveryMessage : Microsoft.VisualStudio.TestPlatform.ObjectModel.TestPlatformException: Could not find testhost
+   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager.GetTestHostProcessStartInfo(IEnumerable`1 sources, IDictionary`2 environmentVariables, TestRunnerConnectionInfo connectionInfo)
+   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources, String runSettings)
+   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyDiscoveryManager.DiscoverTests(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler)
+
+

and after that tests start passing and run goes further.

+

I have two questions about this - what does these messages actually mean / should I intervene in some way?

+

Can I somehow disable these messages so they dont spam my run log ?

","

You can try the below workaround to resolve the above issue, instead of using **/*.Tests.dll try to use **\*test.dll

+
- task: VSTest@2
+    inputs:
+      testSelector: 'testAssemblies'
+      testAssemblyVer2: |
+        **\*test.dll
+      searchFolder: '$(System.DefaultWorkingDirectory)'
+      distributionBatchType: basedOnExecutionTime
+      runInParallel: true
+
+

And also based on the MS DOC :

+
+

The VsTest task doesn't support running tests that target multiple +target frameworks at a time as this is a limitation from the vstest +platform side. If you want to run tests that belong to multiple target +frameworks, you'll need multiple instances of the vstest task, one per +set of dlls that target a particular framework.

+
+

For more information please refer the below links for the similar issue:

+",r +"How to filter a table via a selectbox using angular

Given a custom table component as well as a custom select box component, I want to be able to filter the table rows by selecting an option from the select box.

+

My idea was to first add a click-listener to the options of my select box, so when clicking on an option, the onOptionClicked() method will be executed. Inside this onOptionClicked() method, I will emit an optionSelected event:

+
  @Output() optionSelected = new EventEmitter<string>();
+
+  onOptionClicked(option: string) {
+    this.optionSelected.emit(option);
+  }
+
+

My table component will react upon the event optionSelected:

+
<div class="tbl" (optionSelected)="filterTableRows($event)">
+  <table>
+    <thead>
+...
+
+

There seems to be something fundamentally wrong with this idea, however:

+
    +
  1. My IDE shows an error saying Event optionSelected is not emitted by any applicable directives nor by div element .

    +
  2. +
  3. The table does not react on the optionSelected event.

    +
  4. +
+

It seems the issue is that my table component and my select-box component are different components, apparently they cannot communicate via event emitters. Can someone help me out, please?

","

I think there is a misunderstanding on the use of the @Output() decorator. This is something to be used to emit signals to other components using this one. You seem to be using it in the same component.

+

Instead, use a ReplaySubject to retain your filter:

+
optionSelected$ = new ReplaySubject<string>('');
+
+onOptionClicked(option: string) {
+  this.optionSelected$.next(option);
+}
+
+

To do the data filtering you could subscribe to the replay subject:

+
this.optionSelected$.subscribe(filter => {
+  this.yourFilteredData = this.yourData.filter(item => { 
+   // <-- you filter code
+  });
+})
+
+

Note: please remember to complete any subscriptions when the component is destroyed to avoid the common memory leak.

",r +"How to use u8_to_u32_iterator in Boost Spirit X3?

I am using Boost Spirit X3 to create a programming language, but when I try to support Unicode, I get an error!
+Here is an example of a simplified version of that program.

+
#define BOOST_SPIRIT_X3_UNICODE
+#include <boost/spirit/home/x3.hpp>
+
+namespace x3 = boost::spirit::x3;
+
+struct sample : x3::symbols<unsigned> {
+    sample()
+    {
+        add("48", 10);
+    }
+};
+
+int main()
+{
+  const std::string s("");
+
+  boost::u8_to_u32_iterator<std::string::const_iterator> first{cbegin(s)},
+    last{cend(s)};
+
+  x3::parse(first, last, sample{});
+}
+
+

Live on wandbox

+

What should I do?

","

As you noticed, internally char_encoding::unicode employs char32_t.

+

So, first changing the symbols accordingly:

+
template <typename T>
+using symbols = x3::symbols_parser<boost::spirit::char_encoding::unicode, T>;
+
+struct sample : symbols<unsigned> {
+    sample() { add(U"48", 10); }
+};
+
+

Now the code fails calling into case_compare:

+
/home/sehe/custom/boost_1_78_0/boost/spirit/home/x3/string/detail/tst.hpp|74 col 33| error: no match for call to ‘(boost::spirit::x3::case_compare<boost::spirit::char_encoding::unicode>) (reference, char32_t&)’
+
+

As you can see it expects a char32_t reference, but u8_to_u32_iterator returns unsigned ints (std::uint32_t).

+

Just for comparison / sanity check: https://godbolt.org/z/1zozxq96W

+

Luckily you can instruct the u8_to_u32_iterator to use another co-domain type:

+

Live On Compiler Explorer

+
#define BOOST_SPIRIT_X3_UNICODE
+#include <boost/spirit/home/x3.hpp>
+#include <iomanip>
+#include <iostream>
+
+namespace x3 = boost::spirit::x3;
+
+template <typename T>
+using symbols = x3::symbols_parser<boost::spirit::char_encoding::unicode, T>;
+
+struct sample : symbols<unsigned> {
+    sample() { add(U"48", 10)(U"", 11); }
+};
+
+int main() {
+    auto test = [](auto const& s) {
+        boost::u8_to_u32_iterator<decltype(cbegin(s)), char32_t> first{
+            cbegin(s)},
+            last{cend(s)};
+
+        unsigned parsed_value;
+        if (x3::parse(first, last, sample{}, parsed_value)) {
+            std::cout << s << " -> " << parsed_value << "\n";
+        } else {
+            std::cout << s << " FAIL\n";
+        }
+    };
+
+    for (std::string s : {"", "48", ""})
+        test(s);
+}
+
+

Prints

+
 -> 11
+48 -> 10
+ FAIL
+
",r +"Rowwise average over increasing no. of columns using for loop inside mutate : dplyr R

I want to perform something like this.

+
a <- data.frame(A=c(1,5,9),
+                B=c(2,6,10),
+                C=c(3,7,11),
+                D=c(4,8,12))
+
+a <- a %>% rowwise()
+a <- a %>% mutate(mean(c_across(1:2)))
+a <- a %>% mutate(mean(c_across(1:3)))
+a <- a %>% mutate(mean(c_across(1:4)))
+
+

This gives:

+
A   B   C   D  mean(c_across(1:2)) mean(c_across(1:3)) mean(c_across(1:4))
+1   2   3   4                  1.5                   2                 2.5
+5   6   7   8                  5.5                   6                 6.5
+9   10  11  12                 9.5                  10                10.5
+
+

I would like to get the same results using a for loop. I tried this:

+
a <- data.frame(A=c(1,5,9),
+                B=c(2,6,10),
+                C=c(3,7,11),
+                D=c(4,8,12))
+
+a <- a %>% rowwise()
+for(i in 2:4){
+  a <- a %>% mutate(mean(c_across(1:i)))
+}
+
+

But it only shows the results of last value of i=4

+
A   B   C   D  mean(c_across(1:i))
+1   2   3   4                  2.5
+5   6   7   8                  6.5
+9   10  11  12                10.5
+
+

Can anyone explain what is happening? Whenever I use a for loop when using dplyr, I immediately feel like I am doing something wrong. Is there any other better approach to this?

","

You can use purrr::reduce(or base::Reduce) to do the iteration.

+
library(tidyverse)
+
+reduce(2:4, ~ mutate(.x, !!paste0("col1to", .y) := mean(c_across(1:.y))), .init = rowwise(a))
+
+# A tibble: 3 x 7
+# Rowwise: 
+      A     B     C     D col1to2 col1to3 col1to4
+  <dbl> <dbl> <dbl> <dbl>   <dbl>   <dbl>   <dbl>
+1     1     2     3     4     1.5       2     2.5
+2     5     6     7     8     5.5       6     6.5
+3     9    10    11    12     9.5      10    10.5
+
+
    +
  • base::Reduce version:
  • +
+
Reduce(\(x, y) mutate(x, !!paste0("col1to", y) := mean(c_across(1:y))), 2:4, init = rowwise(a))
+
+
+

To fix your for loop, you need to set different column name to each new column. Otherwise, every new column will have the same name, i.e. "mean(c_across(1:i))", and overrides the former column.

+
b <- rowwise(a)
+for(i in 2:4) {
+  b <- b %>% mutate(!!paste0("col1to", i) := mean(c_across(1:i)))
+}
+
+b
+
+
+

Another choice using tidyr::unnest_wider():

+
a %>%
+  rowwise() %>%
+  mutate(mean = list(cummean(c_across(1:4))[-1])) %>%
+  unnest_wider(mean, names_sep = "_")
+
",r +"Sorting vector of objects by object's variable

I have a vector of objects. Each of these objects has 2 fields (the values of which can be repeated), e.g:

+
//myClass name = myClass(x,y)
+myClass obj1 = myClass(2,5);
+myClass obj2 = myClass(2,4);
+myClass obj3 = myClass(1,5);
+myClass obj4 = myClass(3,2);
+ 
+std::vector<myClass> myVector;
+ 
+myVector.push_back(obj1);
+myVector.push_back(obj2);
+myVector.push_back(obj3);
+myVector.push_back(obj4);
+
+

I want to sort the vector. First it should be sorted by 1st values. If the values of the 1st variable is the same, then should be sorted by second variable. Vector after sorting should be like that:

+
+
    +
  1. obj3 //(1,5)
  2. +
  3. obj2 //(2,4)
  4. +
  5. obj1 //(2,5)
  6. +
  7. obj4 //(3,2)
  8. +
+
+

I have wrote this simple code with bubble sort:

+
for (int i = 0; i < myVector.size(); i++)
+    {
+        for (int j = 0; j < myVector.size() - 1; j++)
+        {
+            if (myVector[j].x < myVector[j + 1].x)
+                std::swap(myVector[j], myVector[j + 1]);
+        }
+    }
+
+

Now myVector is sorted by first value, but how to sort elements, which first value it the same, by second value? Like in example?

","

You can try something like that:

+
for (int i = 0; i < myVector.size(); i++)
+    {
+        for (int j = 0; j < myVector.size() - 1; j++)
+        {
+            if (myVector[j].x < myVector[j + 1].x)
+            {
+                std::swap(myVector[j], myVector[j + 1]);
+            }
+            else if (myVector[j].x == myVector[j + 1].x)
+            {
+                if (myVector[j].y < myVector[j + 1].y)
+                    std::swap(myVector[j], myVector[j + 1]);
+            }
+        }
+    }
+
",r +"Retrive a value from different rows from database to lable ASP.NET

I have an assignment in ASP.NET Using Visual Studio

+

I have created three web forms and connected them to the database(Register webform, login web form , UserDetailWebform)

+

When I use the login page it will send me to the userDetail page, in userDetail page, It always shows me the first Full name and Email for the first account on database, and for the other account it will show nothing (the label will not change)

+

Here is my database

+

enter image description here

+

Ex: when I press login on the login page I want to see Kelly's Fullname and her Email, in my code below only I can see the Fullname and email for the first account other account I cannot retrieve thier Fullname and email

+

the code that I use in the UserDetail Page

+
  protected void Page_Load(object sender, EventArgs e)
+    {
+        con.Open();
+        string checkUser = "select * from userDetail";
+        SqlCommand com = new SqlCommand(checkUser, con);
+        SqlDataReader dr = com.ExecuteReader(); 
+        if (dr.Read())
+        {
+            if (Session["Email"].ToString() == dr["Email"].ToString())
+            {
+                Label1.Text = dr["Fname"].ToString();
+                Label2.Text = dr["Email"].ToString();
+            }
+           
+            
+
+        }
+
+    }
+
","

Well, the Read() command only reads one row at a time.

+

I suggest you do it this way:

+
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
+        {
+            string strSQL = "SELECT * FROM userDetail WHERE email = @email";
+            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
+            {
+                conn.Open();
+                cmdSQL.Parameters.Add("@email", SqlDbType.NVarChar).Value = Session["Email"];
+
+                DataTable rstData = new DataTable();
+                rstData.Load(cmdSQL.ExecuteReader());
+                Label1.Text = rstData.Rows[0]["Fname"].ToString();
+                Label2.Text = rstData.Rows[0]["Email"].ToString();
+            }
+        }
+
",r +"How to assign JSON field from one data source to another in Logic App

I have two different JSON data coming into my Logic App:

+

Data 1:

+
[
+   {
+      "EmployeeCode":"123",
+      "Username":"abc"
+   },
+   {
+      "EmployeeCode":"456",
+      "Username":"def"
+   }
+]
+
+

Data 2:

+
[
+   {
+      "EmployeeCode":"123",
+      "Team":"IT"
+   },
+   {
+      "EmployeeCode":"456",
+      "Team":"Finance"
+   }
+]
+
+

And I want to generate final output like this:

+

Final output:

+
[
+   {
+      "EmployeeCode":"123",
+      "Username":"abc",
+      "Team":"IT"
+   },
+   {
+      "EmployeeCode":"456",
+      "Username":"def",
+      "Team":"Finance"
+   }
+]
+
+

Is there a simple way to achieve this in Logic App itself? Without using JavaScript or Azure Function or anything?

","

After reproducing from our end here is how we could able to achieve your requirement.

+

First, we have used 2 Parse JSON for each data to extract the items in the JSON.

+

+

then used a condition connector to compare the EmployeeCode, and then merged using compose connector.

+

+

However to make the whole JSON to be used for future purposes we have initialized an array variable and then appended the successful runs from the condition connector. Here is my logic app.

+

+

RESULTS:

+

+

Below is the code view of my logic app

+
{
+    "definition": {
+        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
+        "actions": {
+            "FinalJSON": {
+                "inputs": "@variables('FinalJson')",
+                "runAfter": {
+                    "For_each": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "Compose"
+            },
+            "For_each": {
+                "actions": {
+                    "For_each_2": {
+                        "actions": {
+                            "Condition": {
+                                "actions": {
+                                    "Append_to_array_variable": {
+                                        "inputs": {
+                                            "name": "FinalJson",
+                                            "value": "@outputs('Compose')"
+                                        },
+                                        "runAfter": {
+                                            "Compose": [
+                                                "Succeeded"
+                                            ]
+                                        },
+                                        "type": "AppendToArrayVariable"
+                                    },
+                                    "Compose": {
+                                        "inputs": {
+                                            "EmployeeCode": "@{items('For_each')['EmployeeCode']}",
+                                            "Team": "@{items('For_each_2')['Team']}",
+                                            "Username": "@{items('For_each')['Username']}"
+                                        },
+                                        "runAfter": {},
+                                        "type": "Compose"
+                                    }
+                                },
+                                "expression": {
+                                    "and": [
+                                        {
+                                            "equals": [
+                                                "@items('For_each')['EmployeeCode']",
+                                                "@items('For_each_2')['EmployeeCode']"
+                                            ]
+                                        }
+                                    ]
+                                },
+                                "runAfter": {},
+                                "type": "If"
+                            }
+                        },
+                        "foreach": "@body('Parse_JSON2')",
+                        "runAfter": {},
+                        "type": "Foreach"
+                    }
+                },
+                "foreach": "@body('Parse_JSON1')",
+                "runAfter": {
+                    "Initialize_variable": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "Foreach"
+            },
+            "Initialize_variable": {
+                "inputs": {
+                    "variables": [
+                        {
+                            "name": "FinalJson",
+                            "type": "array"
+                        }
+                    ]
+                },
+                "runAfter": {
+                    "Parse_JSON2": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "InitializeVariable"
+            },
+            "JSON1": {
+                "inputs": [
+                    {
+                        "EmployeeCode": "123",
+                        "Username": "abc"
+                    },
+                    {
+                        "EmployeeCode": "456",
+                        "Username": "def"
+                    }
+                ],
+                "runAfter": {},
+                "type": "Compose"
+            },
+            "JSON2": {
+                "inputs": [
+                    {
+                        "EmployeeCode": "123",
+                        "Team": "IT"
+                    },
+                    {
+                        "EmployeeCode": "456",
+                        "Team": "Finance"
+                    }
+                ],
+                "runAfter": {
+                    "JSON1": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "Compose"
+            },
+            "Parse_JSON1": {
+                "inputs": {
+                    "content": "@outputs('JSON1')",
+                    "schema": {
+                        "items": {
+                            "properties": {
+                                "EmployeeCode": {
+                                    "type": "string"
+                                },
+                                "Username": {
+                                    "type": "string"
+                                }
+                            },
+                            "required": [
+                                "EmployeeCode",
+                                "Username"
+                            ],
+                            "type": "object"
+                        },
+                        "type": "array"
+                    }
+                },
+                "runAfter": {
+                    "JSON2": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "ParseJson"
+            },
+            "Parse_JSON2": {
+                "inputs": {
+                    "content": "@outputs('JSON2')",
+                    "schema": {
+                        "items": {
+                            "properties": {
+                                "EmployeeCode": {
+                                    "type": "string"
+                                },
+                                "Team": {
+                                    "type": "string"
+                                }
+                            },
+                            "required": [
+                                "EmployeeCode",
+                                "Team"
+                            ],
+                            "type": "object"
+                        },
+                        "type": "array"
+                    }
+                },
+                "runAfter": {
+                    "Parse_JSON1": [
+                        "Succeeded"
+                    ]
+                },
+                "type": "ParseJson"
+            }
+        },
+        "contentVersion": "1.0.0.0",
+        "outputs": {},
+        "parameters": {},
+        "triggers": {
+            "manual": {
+                "inputs": {
+                    "schema": {}
+                },
+                "kind": "Http",
+                "type": "Request"
+            }
+        }
+    },
+    "parameters": {}
+}
+
",r +"Finding common elemnts between two lists occuring at the same positions in Prolog

I am using Prolog and I am trying to find a way to implement a predicate in which it takes as arguments two lists and returns a list containing the common elements between them which are found in the same positions in both lists.

+

The predicate is as follows:

+

correct_positions(List1, List2,R): succeeds if R is a list containing the letters that +occur in both List1 and List2 in the same positions.

+

Example:

+
?- correct_positions([h,e,l,l,o],[h,o,r,s,e],R).
+R=[h];
+false.
+
+
+

The letter "h" in the previous example is found in both lists at the 1st position, so it should be added to R(the result list). Both letters "e" and "o" also occur in both lists, but they do not occur at the same positions so they are not added to the result list.

+

Another example:

+
?- correct_positions([o,r,l,l,a],[l,o,r,l,a],R).
+R=[l,a];
+false.
+
+

In the previous example, the letter "l" occurs twice in both lists, but only the occurrence in the 4th position will be added to the result(because it is found in the same positions in both lists) as well as the letter "a" which is found in the 5th position in both lists. (Letters "r" and "o" also occur in the two lists. However, they do not occur at the same positions so they are not added to the result list.

","

Assuming same length input lists, a possible solution is as follows:

+
correct_positions([], [], []).
+correct_positions([X|A], [X|B], [X|C]) :-
+    correct_positions(A, B, C).
+correct_positions([X|A], [Y|B], C) :- 
+    dif(X, Y), 
+    correct_positions(A, B, C).
+
+

Examples:

+
?- correct_positions([h,e,l,l,o], [h,o,r,s,e], R).
+R = [h] ;
+false.
+
+?- correct_positions([o,r,l,l,a], [l,o,r,l,a], R).
+R = [l, a] ;
+false.
+
+?- correct_positions([X,r,l,l,a], [l,o,r,l,a], R).
+X = l,
+R = [l, l, a] ;
+R = [l, a],
+dif(X, l) ;
+false.
+
+

Remark To deal with input lists of different lengths, you need to generalize the base case.

+
correct_positions([], [], []).            % lists of the same length
+correct_positions([], [_|_], []).         % first list is the shortest
+correct_positions([_|_], [], []).         % first list is the longest
+correct_positions([X|A], [X|B], [X|C]) :-
+    correct_positions(A, B, C).
+correct_positions([X|A], [Y|B], C) :-
+    dif(X, Y),
+    correct_positions(A, B, C).
+
",r +"gstreamer buffers/bytes in queue2, appsrc

Having read the gst-inspect-1.0 docs for queue2, appsrc, +I am confused. What is buffer and bytes (and time) ? Which one gets priority over the other. +Its possible to set max-size-bytes, max-size-time and max-size-buffers on a pipeline. +But I don't get the right amount of buffering on the queue2. +Ex: +max-size-bytes=100 max-size-buffers=10 +Would it mean total buffer size=1000, and at each burst of data arrival up to 10 bytes allowed?

+

Ideally I'd like to have a known amount of buffering at the appsrc or a queue2 right next to the appsrc. +The source is live-streamed mpeg2-TS. Could someone suggest a right setting for it.

","

You can use all three max-size-bytes, max-size-time and max-size-buffers simultaneously. They all limit the amount of data that can be buffered internally in the queue. The first one to be hit blocks the buffering. For example, if your set max-size-buffer=100, max-size-time=10000000000 and max-size-bytes=20 you are:

+
    +
  1. Allowing a maximum of 100 buffers inside the queue
  2. +
  3. Allowing a maximum of 10 seconds worth of buffers inside the queue
  4. +
  5. Allowing a maximum of 20 bytes of buffer data inside the queue
  6. +
+

As you can see, even though you have configured 100 buffers or 10 seconds, the 20 bytes will be hit first (likely on the first buffer), so you'll only be able to queue 1 buffer at a time (assuming that indeed the buffer data is larger that 20 bytes).

+

BTW, if you do not have a specific reason to use queue2, you should be using queue.

+

Finally, I don't understand how appsrc fits in your question.

",r +"Small files available in ADLS Gen2 location even after delta optimization

I am having a comparatively big external delta table which have data on ADLS gen2 location. +This table is partitioned by id and signal_date

+

I am running a delta optimize query on this table on weekly basis. The query is as shown below.

+

+

For few partitions we could see optimization runs more than 2 hrs as highlighted above.

+

And for the entire partitions for a week, this job is running more than 48 hrs and have to kill it in between in order to proceed with data load into this table. (otherwise encounter with concurrent operation failure error on the partition)

+

Even after this optimization I could see many small files in the ADLS location for that partition as shown below.

+

+

+

Is there anything wrong happening during the optimization considering the huge time for execution and availability of small files after optimization?

+

Any thoughts/points appreciated!

+

Thanks In Advance.

","

OPTIMIZE doesn't remove the small files after it's finished - it creates a new version that refers new, bigger files, and marks old small files as removed, but the actual removal will happen when you run VACUUM.

+

Here an example of the transaction log for OPTIMIZE performed:

+
{"add":{"path":"part-00000-5046c283-8633-4fe2-8c99-ada26908e2d0-c000.snappy.parquet",
+  "partitionValues":{},"size":1105,"modificationTime":1650281913487,
+  "dataChange":false,"stats":"{\"numRecords\":200,\"minValues\":{\"id\":0},\"maxValues\":{\"id\":99},\"nullCount\":{\"id\":0}}"}}
+{"remove":{"path":"part-00002-57c4253a-5bdc-4d3e-9886-601fa793cdf6-c000.snappy.parquet",
+  "deletionTimestamp":1650281912032,"dataChange":false,
+  "extendedFileMetadata":true,"partitionValues":{},"size":536}}
+...other remove entries...
+{"commitInfo":{"timestamp":1650281913514,"operation":"OPTIMIZE",
+  "operationParameters":{"predicate":"[\"true\"]"},"readVersion":1,
+  "isolationLevel":"SnapshotIsolation","isBlindAppend":false,
+  "operationMetrics":{"numRemovedFiles":"16","numRemovedBytes":"8640","p25FileSize":"1105","minFileSize":"1105","numAddedFiles":"1","maxFileSize":"1105","p75FileSize":"1105","p50FileSize":"1105","numAddedBytes":"1105"},
+  "engineInfo":"Apache-Spark/3.2.1 Delta-Lake/1.2.0",
+  "txnId":"31a68055-7932-4266-8290-9939af7e6a84"}}
+
",r +"Apache ignite Partition Map Exchange , Baseline Autoadjustment and Data Rebalancing
    +
  1. My question is how these operations are related?
  2. +
  3. are there events to capture start and end of PME(Partition Map Exchange) and Data rebalancing?
  4. +
","

Long story short, these topics are about data distribution.

+

Each node contains a predefined set of partitions where your actual caches reside. The number of partitions is fixed and is 1024 by default. That's said, if you had 2 nodes and a new one has been added, the data needs to be redistributed to the new one which means instead of having 1024/2 partitions on every node, it now needs to be 1024/3.

+

The process of sending and receiving data due to topology changes is called data rebalancing. As you might expect, this process might be resource and time-consuming depending on the amount of data in your cluster. Sometimes a node might experience short outages, for example if there was an error or due to some maintenance works. In that case, when persistence is enabled and the data is being stored on disk, there is no need for 2 rebalances (when a node leave and when it's back), instead, we would like to avoid the rebalance. To achive that behavior, baseline topology has been introduced. Baseline topology might be confusing at first glance, but it defines a set of nodes that contains the data, every change in baseline will require data rebalance.

+

When you add a new persistent node, it won't trigger a rebalance automatically, instead, you shoul include it into the baseline topology either manually, for example using the control script, or configuring Baseline Autoadjustment which means making baseline changes after some timeout. One the baseline is changed, the data is being redistributing.

+

Befire data rebalancing starts, another process called Partition Map Exchange (PME) takes place. This is a cluster-wide process triggered when server or clent node joins or leaves the cluster or you are starting or destroying a cache. It's primary goal is to sync cluster information between all nodes and make some disitions like do we need to cancel some tasks (if a client failed), are there any partition lost (if no more partition owners left in the cluster) and so on.

+

It's better to refer to the official documentation and blog posts for the details. Data Distribution in Apache Ignite

+

Answering to the last questions:

+

Yes, it's possible to listent for EVTS_CACHE_REBALANCE (not sure about PME-events.), though I can't see why would you like to do it.

",r +"My ArrayAdapter gives me null value - Kotlin

I'm trying to display my sqlite data in textview with kotlin android app. But i have an error with this. When i run my app, it breaks. What is the problem?

+

Here is my read_data function in dbhelper:

+
fun read_data():MutableList<Kullanici> {
+    val userList:MutableList<Kullanici> = ArrayList()
+    val db = this.readableDatabase
+    val query = "SELECT * FROM $table_name"
+
+    val result = db.rawQuery(query,null)
+    if(result.moveToFirst()) {
+        do {
+            val kullanici = Kullanici()
+            kullanici.id = result.getString(result.getColumnIndexOrThrow(column_id)).toInt()
+            kullanici.hamle = result.getString(result.getColumnIndexOrThrow(column_hamle)).toInt()
+            kullanici.sure = result.getString(result.getColumnIndexOrThrow(column_sure)).toInt()
+            userList.add(kullanici)
+
+        }while (result.moveToNext())
+    }
+
+    result.close()
+    db.close()
+    return userList
+
+}
+
+

And here is my main acitivity:

+
override fun onCreate(savedInstanceState: Bundle?) {
+
+    val lv = findViewById<ListView>(R.id.listView)
+    val db  = DataBaseHelper(this)
+
+    super.onCreate(savedInstanceState)
+    setContentView(R.layout.activity_main)
+    supportActionBar?.hide()
+    val kolay_butonu = findViewById<Button>(R.id.button2)
+    kolay_butonu.setOnClickListener {
+        val intent = Intent(this, Kolay::class.java)
+        startActivity(intent)
+    }
+
+
+    val liste = db.read_data()
+    val adapter_: ArrayAdapter<*>
+    adapter_ = ArrayAdapter(this, android.R.layout.simple_list_item_1, liste)
+    lv.adapter = adapter_
+
+}
+
+

and finally the error i encountered:

+
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
+
","

you should call findViewById after setContentView. The view is only inflated when setContentView is called, so when you find view before setContentView is called, it will return null.

+

just move this line

+
val lv = findViewById<ListView>(R.id.listView)
+
+

after setContentView

",r +"automaticlly send E-mails when a new entry is created on strapi

Let's say I have a content type named Order with the following fields:

+
+ + + + + + + + +
NameProductE-mail
+
+

and the public has permission to post new entries for this type.

+

How can I send an email confirming the order when ever a new post request ( new entry ) is made by the public ?

","

You can do it using webhooks on entry.create event, integrating it with some worker or email API.

+

On this example, we can see a cloudflare worker for email sending:

+

https://dev.to/gzuidhof/sending-e-mails-from-cloudflare-workers-2abl

+

Here the Strapi documentation about how to deal with webhooks:

+

https://docs.strapi.io/developer-docs/latest/development/backend-customization/webhooks.html#entry-create

",r +"How to get total length of all items in object with arrays

I want to get the total of all items in object with array. for example

+
const obj = {
+  one: [1, 4],
+  two: [4, 6]
+}
+
+

I should get total of 4.

+

I tried

+

+
+
const obj = {
+  one: [1, 4],
+  two: [4, 6]
+}
+
+let total = 0;
+const objKeys = Object.keys(obj);
+
+for (let index = 0; index < objKeys.length; index++) {
+  total += obj[objKeys[index]].length
+}
+
+console.log(total);
+
+
+

+

Is there a simpler way of doing this?

","

You could grab the values of your object, which would be an array of arrays of the following shape:

+
[[1, 4], [4, 6]]
+
+

and then flatten this array with .flat() which gives:

+
[1, 4, 4, 6];
+
+

And then grab the .length of that array.

+

See example below:

+

+
+
const obj = {one: [1, 4],two: [4, 6]}; 
+
+const res = Object.values(obj).flat().length;
+console.log(res);
+
+
+

+

Note, that if your goal is for efficiency, you can use a standard for...in loop to loop the keys of your object, and then add to a total like as shown below. This also avoids the overhead of creating additional arrays to store the keys/values:

+

+
+
const obj = {one: [1, 4], two: [4, 6]};
+let total = 0;
+for(const key in obj) 
+  total += obj[key].length;
+console.log(total);
+
+
+

",r +"Filter for Row from Multiple Data Frame in R

I have five data frames with the same dimension (8 by 2) but with different column names as follows:

+
nbb <- data.frame(
+nbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+nbb_RMSE = c(1.0152338, 0.7199394, 0.7990978, 0.9045563, 1.6514406, 0.5160516, 0.4964024, 0.2617795)
+)
+
+mbb <- data.frame(
+mbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+mbb_RMSE = c(0.8324074, 0.9278236, 1.9817984, 0.9567368, 0.2814623, 0.1129459, 0.1233126, 0.4222578)
+)
+
+cbb <- data.frame(
+cbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+cbb_RMSE = c(1.27782499, 1.96332220, 0.74704997, 0.46579943, 1.10850563, 0.40456698, 0.26027359, 0.02452239)
+)
+
+tmbb <- data.frame(
+tmbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+tmbb_RMSE = c(0.83240742, 1.05126826, 0.08290467, 0.76397988, 1.23772208, 0.57628337, 0.56437185, 0.46460279)
+)
+
+tcbb <- data.frame(
+tcbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+tcbb_RMSE = c(0.9328510, 0.8312332, 0.9402116, 1.6029357, 2.0001519, 0.4387557, 0.5965582, 0.4148854)
+)
+
+

I want to create a new data frame that will contain each row that contains minimum RMSE in the five(5) data frames above. If I make the row names to be the name of different data frames as (nbb, mbb, cbb, tmbb, tcbb)

+
rownames(df) <- c("nbb", "mbb", "cbb", "tmbb", "tcbb")
+
+

I desire to have a result like the below:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
dflbRMSE
nbb90.2617795
mbb70.1129459
cbb90.02452239
tmbb40.08290467
tcbb80.4387557
+
","

Here is a base R way.
+First put the data.frames in a list with mget, then lapply the list an anonymous function outputting the minimum RMSE row. Bind the output rows and reorder according to the wanted row names.

+
nbb <- data.frame(
+  nbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+  nbb_RMSE = c(1.0152338, 0.7199394, 0.7990978, 0.9045563, 1.6514406, 0.5160516, 0.4964024, 0.2617795)
+)
+
+mbb <- data.frame(
+  mbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+  mbb_RMSE = c(0.8324074, 0.9278236, 1.9817984, 0.9567368, 0.2814623, 0.1129459, 0.1233126, 0.4222578)
+)
+
+cbb <- data.frame(
+  cbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+  cbb_RMSE = c(1.27782499, 1.96332220, 0.74704997, 0.46579943, 1.10850563, 0.40456698, 0.26027359, 0.02452239)
+)
+
+tmbb <- data.frame(
+  tmbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+  tmbb_RMSE = c(0.83240742, 1.05126826, 0.08290467, 0.76397988, 1.23772208, 0.57628337, 0.56437185, 0.46460279)
+)
+
+tcbb <- data.frame(
+  tcbb_lb = c(2, 3, 4, 5, 6, 7, 8, 9),
+  tcbb_RMSE = c(0.9328510, 0.8312332, 0.9402116, 1.6029357, 2.0001519, 0.4387557, 0.5965582, 0.4148854)
+)
+
+df_list <- mget(ls(pattern = "bb$"))
+
+tmp <- lapply(df_list, \(x){
+  i <- which.min(x[[2]])
+  if(length(i) > 0L) {
+    data.frame(lb = x[i, 1], RMSE = x[i, 2])
+  } else NULL
+})
+res <- do.call(rbind, tmp)
+rm(tmp)
+res <- cbind.data.frame(df = names(df_list), res)
+
+i <- order(c("nbb", "mbb", "cbb", "tmbb", "tcbb"))
+res <- res[i,]
+res
+#>        df lb       RMSE
+#> nbb   nbb  9 0.26177950
+#> mbb   mbb  7 0.11294590
+#> cbb   cbb  9 0.02452239
+#> tmbb tmbb  4 0.08290467
+#> tcbb tcbb  9 0.41488540
+
+

Created on 2022-04-10 by the reprex package (v2.0.1)

",r +"How should I set the arguments and parameters in createAsyncThunk?

Sometimes when I run loadPosts dispatch, I don't send any data, sometimes I send lastId data to same loadPosts disaptch.

+

At this time, I don't know how to define the type of data in createAsyncThunk . +When I run my code I get a red warning in loadPosts.

+

like this Screenshot

+

+

it says +Expected 1 arguments, but got 0.

+

How can i fix my code?

+

this is my code

+
    dispatch(loadPosts());
+
+
+    dispatch(loadPosts(lastId:lastId));
+
+
+
+    export const loadPosts = createAsyncThunk(
+      'post/loadPosts',
+      async (data: any, thunkAPI) => {
+        try {
+          const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
+          return response.data;
+        } catch (error: any) {
+          return thunkAPI.rejectWithValue(error.response.data);
+        }
+      },
+
","

RTK Docs: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk

+
export const loadPosts = createAsyncThunk<
+  YourReturnType,
+  {
+    lastId: number;
+  } | void,
+  { state: AppStore }
+>('post/loadPosts', async (data, thunkAPI) => {
+  try {
+    const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
+    return response.data;
+  } catch (error) {
+    return thunkAPI.rejectWithValue(error.response.data);
+  }
+});
+
",r +"ASP.NET MVC / Entity Framework - Controller generation is somehow using old properties

After adding and altering columns in the SQL database, I've refreshed the Entity Model (Entity Framework 6) and deleted all controllers and views, to generate them again according to the refreshed entity model.

+

Somehow the newly generated controllers and views are still based on the "old version" of the entity model. The newly added columns of the tables are not included. All models from Entity Framework are looking ok and updated.

+

I've already tried to delete the whole entity model and recreate it again without any luck. The controllers and views will show errors for all altered columns, of course because the column names are not correct anymore.

+

Is it possible that the old entity model is cached somehow in Visual Studio? Or why does this happen and how can it be fixed?

",

To fix it you have to rebuild the project in Visual Studio.

,r +"GraalVM JS: How I do pass Truffle options via Bindings (Nashorn compat mode) and Context in a Java application?

I'm trying to understand performance of my JavaScript running within a Java application but I can't find a way to pass Truffle options through the Java interfaces like Bindings (when in Nashorn compat mode) and Context.

+

Specifically, I'm trying to turn on compilation info --engine.TraceCompilation mentioned in: +https://www.graalvm.org/22.1/graalvm-as-a-platform/language-implementation-framework/Options/

+

but all I find are examples like this:

+
ScriptEngine js = scriptEngineManager.getEngineByName("graal.js");
+
+Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
+
+bindings.put("polyglot.js.allowHostAccess", true);
+bindings.put("polyglot.js.nashorn-compat", true);
+
+// -------   I want to do something like this: -----------
+bindings.put("polyglot.js.engine.TraceCompilation", true); // <-- does not work
+//--------------------------------------------------------
+
+

This guide mentions the list of options that can be passed this way and none of the Truffle options are listed: +https://www.graalvm.org/22.1/reference-manual/js/ScriptEngine/

+

Note that for legacy reasons I need to use Nashorn compatibility mode to run the JavaScript code.

","

as the documentation states, those are language launcher options. You would typically provide them to a launcher like js, node or similar.

+
$ js --engine.TraceCompilation yourJSFile.js
+
+

As you seem to start from Java, you can also provide them to the Java process with system properties (by preprending polyglot and explicitly providing true for boolean options):

+
$ java -Dpolyglot.engine.TraceCompilation=true yourJavaClass
+
+

I don't believe you can provide those options as late as in the bindings of the language, because they should not affect the language but the overall GraalVM system. (this is also why your polyglot.js.engine.TraceCompilation is off; the option has nothing to do with js)

+

HTH, Christian

",r +"python in Rmarkdown using reticulate cannot read packages

I am using R on a MacBook. I have an Rmarkdown document and I'm trying to use reticulate in order to use python within R.

+

First I download the libraries:

+
```{r libraries, warning = FALSE, message = FALSE}
+
+library(dplyr)
+library(reticulate)
+
+```
+
+

Next I look at an R chunk and figure out my working directory. Then I write mtcars to my desktop.

+
```{r chunk, warning = FALSE, message = FALSE}
+
+getwd()
+
+write.csv(mtcars, '/Users/name/Desktop/mtcars.csv', row.names = TRUE)
+
+```
+
+

Then I try to use python instead to read in that csv that I just wrote to my desktop.

+
```{python}
+
+import pandas as pd
+
+mtcars = pd.read_csv('/Users/name/Desktop/mtcars.csv')
+
+```
+
+

But I get this error:

+
ModuleNotFoundError: No module named 'pandas'
+NameError: name 'pd' is not defined
+
+

So I went to this R documentation website and discovered that with python you have to import packages differently. So I went to terminal and then I typed in

+
python -m pip install pandas
+
+

It seemed to download OK? But when I return to my Rmarkdown document I can't seem to get the python code to run and read in the csv. I still get the same error message.

+

I also saw a similar question on this SO post but I'm certain that my RStudio version is newer than the version in this question, so I don't the answer hits on the same error exactly.

","

An option is to create a virtualenv, install the package and then specify the virtual env to be used

+
virtualenv_create("py-proj")
+py_install("pandas", envname = "py-proj")
+
+

In the rmarkdown, we can use

+
---
+title: "Testing"
+output:
+  pdf_document: default
+  html_document: default
+---
+
+```{r libraries, warning = FALSE, message = FALSE}
+library(reticulate)
+use_virtualenv("py-proj")
+```
+
+
+```{r chunk, warning = FALSE, message = FALSE}
+
+
+
+write.csv(mtcars, "/Users/name/Desktop/mtcars.csv", row.names = TRUE)
+
+```
+```{python}
+
+import pandas as pd
+mtcars = pd.read_csv("/Users/name/Desktop/mtcars.csv")
+mtcars.head(5)
+```
+
+

-output

+

",r +"Transform array into object with custom properties

I have this array

+
myarr = [
+  '=title1',
+  'longText0...',
+  'longtText1...',
+  '=title2',
+  'longTextA...',
+  'longtTextB...',
+  'longtTextC...'     
+];
+
+

symbol = indicates that is is a property, next to that is a list of items that belongs to that property

+

I want to transform that array into object

+
myObj = {
+   title1: [
+     'longText0...',
+     'longtText1...',   
+   ],
+
+   title2: [
+     'longTextA...',
+     'longtTextB...',  
+     'longtTextC...'
+   ]
+}
+
+

I come up with this code so far:

+
const arrayToObject = (array) =>
+   array.reduce((obj, item) => {
+     if(item.startsWith('=')) {
+       const itemName = item.replace('=', '')
+       obj[itemName] = itemName;
+     } else {
+       
+       //add the rest....
+     }
+ 
+
+     return obj
+   }, {})
+
+
+console.log(arrayToObject(myarr))
+
+

My challenges so far is that I am not sure how to turn obj[itemName] so I can assign the items to it. Any ideas how to do that?

","

A reduce based approach which does not depend on outer scope references for keeping track of the currently to be built/aggregated property makes this information part of the reducer function's first parameter, the previousValue which serves as an accumulator/collector object.

+

Thus, as for the OP's task, this collector would feature two properties, the currentKey and the result, where the former holds the state of the currently processed property name and the latter being the programmatically built result.

+

+
+
// - reducer function which aggregates entries at time,
+//   either by creating a new property or by pushing a
+//   value into the currently processed property value.
+// - keeps the state of the currently processed property
+//   by the accumulator`s/collector's `currentKey` property
+//   whereas the result programmatically gets build as
+//   the accumulator`s/collector's `result` property.
+
+function aggregateEntry({ currentKey = null, result = {} }, item) {
+  const key = (item.startsWith('=') && item.slice(1));
+  if (
+    (key !== false) &&
+    (key !== currentKey)
+  ) {
+    // keep track of the currently processed property name.
+    currentKey = key;
+
+    // create a new entry (key value pair).
+    result[currentKey] = [];
+  } else {
+    // push value into the currently processed property value.
+    result[currentKey].push(item);
+  }
+  return { currentKey, result };
+}
+console.log([
+  '=title1',
+  'longText0...',
+  'longtText1...',
+  '=title2',
+  'longTextA...',
+  'longtTextB...',
+  'longtTextC...',
+].reduce(aggregateEntry, { result: {} }).result);
+
.as-console-wrapper { min-height: 100%!important; top: 0; }
+
+
+

",r +"How to get the highest value from list of Device Names

Generating a list of windows workstation computer names by reading the active directory and I need to find the highest number so that I can then assign a new device with the next available number - I am not having any success in doing this - how to do it? And as you can see from the list of names, I also have missing numbers in the sequence that ideally, I would like to fill in with new devices also...

+

The code I am using to get the list from AD is below.

+
((Get-ADComputer -Filter {operatingsystem -notlike "*server*" -and Name -like $NamingConvention -and enabled -eq "true"} -Credential $credential -server $ADServerIP).Name)
+
+

List of device names

+
+

PC01 +PC28 +PC29 +PC30 +PC31 +PC32 +PC33 +PC34 +PC35 +PC36 +PC37 +PC38 +PC40 +PC41 +PC42 +PC43 +PC44 +PC45 +PC46 +PC47 +PC27 +PC48 +PC26 +PC24 +PC179 +PC18 +PC180 +PC181 +PC182 +PC183 +PC184 +PC185 +PC186 +PC187 +PC188 +PC189 +PC19 +PC190 +PC191 +PC192 +PC21 +PC22 +PC23 +PC25 +PC178 +PC49 +PC51 +PC77 +PC78 +PC79 +PC80 +PC81 +PC83 +PC84 +PC85 +PC87 +PC88 +PC89 +PC90 +PC91 +PC92 +PC93 +PC94 +PC95 +PC96 +PC97 +PC76 +PC50 +PC75 +PC72 +PC52 +PC53 +PC54 +PC55 +PC56 +PC57 +PC59 +PC60 +PC61 +PC62 +PC63 +PC64 +PC65 +PC66 +PC67 +PC68 +PC69 +PC70 +PC71 +PC73 +PC98 +PC177 +PC175 +PC115 +PC116 +PC117 +PC118 +PC119 +PC12 +PC120 +PC121 +PC122 +PC123 +PC124 +PC125 +PC126 +PC127 +PC128 +PC129 +PC13 +PC130 +PC131 +PC114 +PC132 +PC113 +PC111 +PC02 +PC03 +PC04 +PC06 +PC08 +PC09 +PC10 +PC100 +PC101 +PC102 +PC103 +PC104 +PC105 +PC106 +PC107 +PC108 +PC109 +PC11 +PC110 +PC112 +PC176 +PC133 +PC135 +PC158 +PC159 +PC16 +PC160 +PC161 +PC162 +PC163 +PC164 +PC165 +PC166 +PC167 +PC168 +PC169 +PC17 +PC170 +PC171 +PC172 +PC173 +PC174 +PC157 +PC134 +PC156 +PC154 +PC136 +PC137 +PC138 +PC139 +PC14 +PC140 +PC141 +PC142 +PC143 +PC144 +PC145 +PC146 +PC147 +PC148 +PC149 +PC150 +PC151 +PC152 +PC153 +PC155 +PC99

+
","

Here's a solution that will give you the highest number ($dataMax), the missing numbers ($dataMissing), and the next number to use ($dataNext). The next number to use will be either the 1st missing number, or if there are no missing numbers then it will be the highest number + 1

+
# load the computers list
+$data = ((Get-ADComputer -Filter {operatingsystem -notlike "*server*" -and Name -like $NamingConvention -and enabled -eq "true"} -Credential $credential -server $ADServerIP).Name)
+
+# create an array by splitting the data text using the "space" character as a delimiter
+$data = $data.Split(" ")
+
+# remove all the alpha characters ("PC"), leaving only the number values so it can be sorted easier
+$dataCleaned = $data -replace "[^0-9]" , '' | sort { [int]$_ }
+
+# after sorting the data, [-1] represents the last element in the array which will be the highest number
+[int]$dataMax = $dataCleaned[-1]
+
+# create a number range that represents all the numbers from 1 to the highest number
+$range = 1..$dataMax | foreach-object { '{0:d2}' -f $_ }
+
+# compare the created range against the numbers actually in the computer array to find the missing numbers
+$dataMissing = @(compare $range $dataCleaned -PassThru)
+
+# if there's a missing value, [0] represents the first element in the array of missing numbers
+if ($dataMissing)
+{
+    $dataNext = $dataMissing[0]
+}
+
+# if there's no missing values, the next value is the max value + 1
+else
+{
+    $dataMissing = "none"
+    $dataNext = $dataMax + 1
+}
+
+Write-Host "The highest number is:"('{0:d2}' -f $dataMax)
+Write-Host "The missing numbers are: $dataMissing"
+Write-Host "The next number to use is:" ('{0:d2}' -f $dataNext)
+
",r +"Finding index of an element in a specified array

I'm in the making of a google sheets app script where I want to check if a value from one cell is in an array of values, then find what the index is so I can direct my function to that cell.

+

I'm at the point where I have my array in a variable called distArray, and I want to check if "id" is in that array.

+

Here's the code to better visualize:

+
function logs() {
+  let app = SpreadsheetApp
+  let dest = app.getActiveSpreadsheet().getSheetByName("Baza Danych");
+  let lastrow = dest.getLastRow();
+
+  let destArr = dest.getRange(2, 1, lastrow).getValues();
+  let id = app.getActiveSpreadsheet().getSheetByName("Zgloszenia").getRange(6, 2).getValue();
+  let position = destArr.indexOf(id);
+
+  Logger.log(id)
+  Logger.log(destArr)
+  Logger.log(position)
+}
+
+

And here is the output I get.

+

My problem is that no matter what the value of "id" is, the index is either -1 or 0 meaning the value either is not in the array or is in the first cell.

","

Try to add .flat() at the end of the line:

+
let destArr = dest.getRange(2, 1, lastrow).getValues();
+
+

This way:

+
let destArr = dest.getRange(2, 1, lastrow).getValues().flat();
+
+

Explanation:

+

The method getValues() gives you a 2d array [[1],[2],[3],...].

+

The flat() method converts a 2d array into an ordinary flat array [1,2,3,...].

+

After that you will able to use array.indexOf(element) to get an index of the element in the array.

",r +"How to write custom input function for Flex in C++ mode?

I have a game engine and a shader parser. The engine has an API for reading from a virtual file system. I would like to be able to load shaders through this API. I was thinking about implementing my own std::ifstream but I don't like it, my api is very simple and I don't want to do a lot of unnecessary work. I just need to be able to read N bytes from the VFS. I used a C++ mod for more convenience, but in the end I can not find a solution to this problem, since there is very little official information about this. Everything is there for the C API, at least I can call the scan_string function, I did not find such a function in the yyFlexParser interface.

+

To be honest, I wanted to abandon the std::ifstream in the parser, and return only the C api . The only thing I used the Flex C++ mode for is to interact with the Bison C++ API and so that the parser can be used in a multi-threaded environment, but this can also be achieved with the C API. +I just couldn't compile the C parser with the C++ compiler.

+
    +
  1. I would be happy if there is a way to add such functionality through some kind of macro.
  2. +
  3. I wouldn't mind if there was a way to return the yy_scan_string function, I could read the whole file myself and provide just a string.
  4. +
","

The simple solution, if you just want to provide a string input, is to make the string into a std::istringstream, which is a valid std::istream. The simplicity of this solution reduces the need for an equivalent to yy_scan_string.

+

On the other hand, if you have a data source you want to read from which is not derived from std::istream, you can easily create a lexical scanner which does whatever is necessary. Just subclass yyFlexLexer, add whatever private data members you will need and a constructor which initialises them, and override int LexerInput(char* buffer, size_t maxsize); to read at least one and no more than maxsize bytes into buffer, returning the number of characters read. (YY_INPUT also works in the C++ interface, but subclassing is more convenient precisely because it lets you maintain your own reader state.)

+

Notes:

+
    +
  1. If you decide to subclass and override LexerInput, you need to be aware that "interactive" mode is actually implemented in LexerInput. So if you want your lexer to have an interactive mode, you'll have to implement it in your override, too. In interactive mode, LexerInput always reads exactly one character (unless, of course, it's at the end of the file).

    +
  2. +
  3. As you can see in the Flex code repository, a future version of Flex will use refactored versions of these functions, so you might need to be prepared to modify your code in the future, although Flex generally maintains backwards compatibility for a long time.

    +
  4. +
",r +"Postgres: Python: TypeError: SQL.__init__() takes 2 positional arguments but 3 were given

Hello I am getting error from my code, can someone help me please?

+

def query_builder(self, field_name, table_name, pkey, id):

+
    queryx=sql.SQL("select {field} from {table} where {pkey} = %s",(id)).format(
+        field=sql.Identifier(field_name),
+        table=sql.Identifier(table_name),
+        pkey=sql.Identifier(pkey))
+    
+    self.cur.execute(queryx.as_string(self.conn))
+
","

I'm going to assume you are using psycopg2.

+

If so the issues are, first:

+
"select {field} from {table} where {pkey} = %s",(id) ..."
+
+
+

Do not include the argument (id) in the string. Also this is not proper form for a single value in a tuple. Python requires it be (id,), note the comma.

+

Second:

+
self.cur.execute(queryx.as_string(self.conn))
+
+

Should be:

+
self.cur.execute(queryx, (id,))
+
+

The execute is where you supply the argument. Also the composable sql.SQL(...) can be passed directly to execute without being run through as_string. See here sql for more examples.

+

UPDATE

+

To use "*" there are two ways:

+
cur.execute(sql.SQL("select * from {table} where {pkey} = %s).format(table.sql.Identifier(table_name), pkey=sql.Identifier(pkey))
+
+--OR
+
+cur.execute(sql.SQL("select {field} from {table} where {pkey} = %s).format(field=sql.SQL("*"), table=sql.Identifier(table_name), pkey=sql.Identifier(pkey))
+
+

Warning, the second does allow for SQL injection as sql.SQL() does not escape values.

+

As to multiple fields the sql section of the docs has multiple examples. For instance:

+
+

If part of your query is a variable sequence of arguments, such as a comma-separated list of field names, you can use the SQL.join() method to pass them to the query:

+
+
query = sql.SQL("select {fields} from {table}").format(
+    fields=sql.SQL(',').join([
+        sql.Identifier('field1'),
+        sql.Identifier('field2'),
+        sql.Identifier('field3'),
+    ]),
+    table=sql.Identifier('some_table'))
+
",r +"NGINX rewrite / redirect / alias wildcard for full path

I've found a few different ways to redirect a path in NGINX. The issue is I have a submodule that contains paths to /foo/ with subdirs like /foo/wisdom/script.js.

+

The closest I've come is: +rewrite ^(/foo/)(.*)$ /bar/$2 permanent; +Which throws 404 for js and css files.

+

Apparently the fix is to use and alias instead, I found this:

+
location ~* ^/foo/.*\.(jpg|png|css|js|appcache|xml|ogg|m4a)$ {
+    alias /bar/;
+}
+
+

However the wildcard doesn't match properly and I'm not sure how to fix it.

+

EDIT: +Adding nginx.conf for more info:

+
worker_processes    auto;
+pid                 /run/nginx.pid;
+error_log           /dev/stdout info;
+
+events {
+    worker_connections 1024;
+}
+
+http {
+   include       mime.types;
+   default_type  application/octet-stream;
+   
+   server {
+        listen              80;
+        server_name         localhost;
+        keepalive_timeout   70;
+
+        access_log          /dev/stdout;
+        error_page          404    /404.php;
+
+        add_header X-Frame-Options "SAMEORIGIN";
+        add_header X-XSS-Protection "1; mode=block";
+        server_tokens off;
+
+        if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) {
+            return 405; 
+        }
+        ## THIS WORKS BUT NESTED JS AND CSS RETURN 404
+        #rewrite ^(/foo/)(.*)$ /bar/$2 permanent;
+        ## THIS DOESN'T MATCH
+        #location ~* ^(/foo/)(.*)$ {
+        #    alias /bar/$2;
+        #}
+        ## THIS DOESN'T MATCH
+        #location ~* ^/foo/.*\.(jpg|png|css|js|appcache|xml|ogg|m4a)${
+        #     alias /bar/$1;
+        #}
+        location /api/query1 {
+            proxy_pass http://api:1234/api/query1;
+        }
+        location /api/query2 {
+            proxy_pass http://api:1234/api/query2;
+        }
+        location /api/query3 {
+            proxy_pass http://api:1234/api/query3;
+        }
+        location /api/query4 {
+            proxy_pass http://api:1234/api/query4;
+        }
+        location /api/query5 {
+            proxy_pass http://api:1234/api/query5;
+        }
+        location /api/query6 {
+            proxy_pass http://api:1234/api/query6;
+        }
+        location /api/query7 {
+            proxy_pass http://api:1234/api/query7;
+        }
+        location /api/query8 {
+            proxy_pass http://api:1234/api/query8;
+        }
+        location /api/query9 {
+            proxy_pass http://api:1234/api/query9;
+        }
+        location /api/query10 {
+            proxy_pass http://api:1234/api/query10;
+        }
+        location /api/query11 {
+            proxy_pass http://api:1234/api/query11;
+        } 
+        location /bar {
+            proxy_pass http://api:5000/foo;
+            proxy_http_version 1.1;
+            proxy_set_header Upgrade $http_upgrade;
+            proxy_set_header Connection "upgrade";
+            proxy_read_timeout 43200000;
+
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header Host $http_host;
+            proxy_set_header X-NginX-Proxy true;
+            expires       30d;
+            tcp_nodelay   off;
+            access_log    off;
+        }
+
+        location / {
+            if ($request_uri ~ ^/(.*)\.php) {
+                return 302 /$1;
+            }
+            autoindex   off;
+            index       index.php;
+            root        /var/www;
+            try_files $uri $uri.html $uri.php $uri/ =404;
+            #rewrite ^/assets/([a-z\-]+)-([a-z0-9]+).(css|js|png|webp) /assets/$1.$3;
+        }
+        location ~* \.php$ {
+                fastcgi_pass    127.0.0.1:9000;
+                include         fastcgi_params;
+                fastcgi_index   index.php;
+                fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
+                fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
+                root /var/www;
+        }
+        location ~ \.css {
+            root        /var/www;
+            add_header  Content-Type    text/css;
+        }
+        location ~ \.js {
+            root        /var/www;
+            add_header  Content-Type    application/x-javascript;
+        }
+        location = /404.php {
+            root        /var/www;
+        }
+   }
+}
+
+
+

EDIT 2: +This also partially works:

+
location ~ ^/foo/(.*) {
+    return 301 /bar/$1;
+}
+
+

However when checking error logs I can see nginx is looking for css and js files in /var/www/bar/... instead of http://localhost/bar/... which is https://api:5000/foo/... proxied in my config above.

","

So the rewrite was the correct solution. My proxy was incorrect. Solution as follows.

+

Rewrite:

+
rewrite ^(/foo/)(.*)$ /bar/$2 permanent;
+
+

Proxy:

+
location ^~ /bar {
+            proxy_pass http://api:5000/foo;
+            proxy_http_version 1.1;
+            proxy_set_header Upgrade $http_upgrade;
+            proxy_set_header Connection "upgrade";
+            proxy_read_timeout 43200000;
+
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header Host $http_host;
+            proxy_set_header X-NginX-Proxy true;
+        }
+
+

Take note of the ^~ after the location tag.

",r +"Accessing nested nodes in a Firebase RTDB, using Flutter

I've got a database that stores user information such as their name and all their friends. The DB look something like this:

+
{
+  "users": {
+    "userID here": {
+      "bio": "",
+      "country": "",
+      "dateOfBirth": "2022-04-13 17:49:45.906226",
+      "emergencyContacts": {
+        "mom": {
+          "emailAdd": "mom@gmail.com",
+          "name": "mom",
+          "phoneNumber": "07492017492",
+          "picUrl": "url here'"
+        }
+      },
+      "friends": {
+        "auto-generated ID (used push method)": {
+          "country": "",
+          "profilePicUrl": "url here",
+          "userID": "userID here",
+          "username": "newOne"
+        }
+      },
+      "fullName": "name",
+      "gender": "Female",
+      "hobbies": "[]",
+      "knownMH": "[]",
+      "lastMessageTime": "2022-04-14 08:44:40.639944",      
+  }
+}
+
+

I would like to access the "friends" node. While doing so, I'd also like to store the data in a 2d array. So, each sub-array will contain the data about the user we're currently looping through and one of their friends. This should happen until we've looped through all of the user's friends and then move on to the next user.

+

It's also worth mentioning; I've used a push method for adding friends so I get randomly assigned keys for the nodes.

+

I've used the method below, but it's not working, it's returning the wrong list of friends and not looping through all users. Please find the code that I've used below (any help is much appreciated):

+
  void _retrieveAllFriendships() {
+    final allUsersDb = FirebaseDatabase.instance.ref().child('users');
+    _allUserssStream = allUsersDb.onValue.listen((event) {
+      if (event.snapshot.exists) {
+        final data = new Map<dynamic, dynamic>.from(
+            event.snapshot.value as Map<dynamic, dynamic>);
+
+        data.forEach((key, value) {
+          allUsersDb.child(key).onValue.listen((event) {
+            final acc = new Map<dynamic, dynamic>.from(
+                event.snapshot.value as Map<dynamic, dynamic>);
+
+            final username = acc['username'] as String;
+            final profilePicUrl = acc['profilePicUrl'] as String;
+            final country = acc['country'] as String;
+            final userID = acc['userID'] as String;
+
+            user = new FriendSuggestionModel(
+              picture: profilePicUrl,
+              name: username,
+              location: country,
+              userID: userID,
+            );
+
+            _friendshipStream = allUsersDb
+                .child(userID)
+                .child("friends")
+                .onValue
+                .listen((event) {
+              if (event.snapshot.exists) {
+                final data = new Map<dynamic, dynamic>.from(
+                    event.snapshot.value as Map<dynamic, dynamic>);
+
+                data.forEach((key, value) {
+                  allUsersDb
+                      .child(userID)
+                      .child("friends")
+                      .child(key)
+                      .onValue
+                      .listen((event) {
+                    final friend = new Map<dynamic, dynamic>.from(
+                        event.snapshot.value as Map<dynamic, dynamic>);
+
+                    final username = friend['username'] as String;
+                    final profilePicUrl = friend['profilePicUrl'] as String;
+                    final country = friend['country'] as String;
+                    final userID = friend['userID'] as String;
+
+                    friendModel = new FriendSuggestionModel(
+                        picture: profilePicUrl,
+                        name: username,
+                        location: country,
+                        userID: userID);
+                    List<FriendSuggestionModel> friendship = [
+                      user,
+                      friendModel
+                    ];
+                    allFriendships.add(friendship);
+
+                    setState(() {
+                      for (int i = 0; i < allFriendships.length; i++) {
+                        print(
+                            "${allFriendships[i][0].name} is friends with: ${allFriendships[i][1].name}");
+                      }
+                    });
+                  });
+                });
+              }
+            });
+          });
+        });
+      }
+    });
+  }
+
","

When you attach a listener to allUsersDb.onValue all data under that path is already present in the event.snapshot and you don't need any more listeners for that data.

+

If you know the name of a child snapshot you want to access, you can get this by snapshot.child("friends"). If you don't know the name of the child snapshots, you can loop over all of them with snapshot.children.forEach.

",r +"Python: Formatting a Pandas dataframe head with LaTex

I have made a Pandas dataframe from several NumPy arrays and tried to format columns heads using LaTex, but it looks awful. I'm working with Jupyter Notebook.

+
import numpy as np
+import pandas as pd
+
+

Arrays (one instance out of five) look like this:

+
coeficientes = [0.5601, 0.3315, 0.2260, 0.1429, 0.0695]
+coeficientes = np.array(coeficientes)
+
+

The dataframe:

+
tabla_resumen = pd.DataFrame({'$x_{n-i+1}$': submuestra1, 
+                              '$x_{i}$': submuestra2, 
+                              '$x_{n-i+1} - x_{i}$': diferencias, 
+                              '$a_{n-i+i}$': coeficientes,
+                              '$(x_{n-i+1} - x_{i})(a_{n-i+i})$': sumandos
+                             })
+tabla_resumen
+
+

The way it looks:

+

+

Are there any formatting options to make it look better?

","

Try this:

+

Function to convert to subscript

+
def get_sub(x):
+    normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()"
+    sub_s = "ₐ₈CDₑբGₕᵢⱼₖₗₘₙₒₚQᵣₛₜᵤᵥwₓᵧZₐ♭꜀ᑯₑբ₉ₕᵢⱼₖₗₘₙₒₚ૧ᵣₛₜᵤᵥwₓᵧ₂₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎"
+    res = x.maketrans(''.join(normal), ''.join(sub_s))
+    return x.translate(res)
+
+

Display subscript

+
print('H{}SO{}'.format(get_sub('2'),get_sub('4'))) #H₂SO₄
+
",r +"How to work with column containg array in H2 database to get n 1 row

I am new to H2 database. I have 3 tables in database for example,

+

table t1 :

+
+ + + + + + + + + + + + + + + + + +
IDdescsomethingcondition_id
1EN 142868 151508XYZ[4686, 4687]
+

table condition

+
+ + + + + + + + + + + + + + + + + + + + +
CONDITION_IDdescCOLUMN3
4686desc1something1
4687desc2something2
+
+

And I need output like this

+
+ + + + + + + + + + + + + + + + + +
IDdesct1somethingjoined Column
1EN 142868 151508XYZdesc1 something1, desc2 somethin2
+
+

How to do this, I tried with array_contains, but its giving 2 rows as a result like' t1ID t1desc t1something joined Column 1 EN 142868 151508 XYZ desc1 something1 1 EN 142868 151508 XYZ desc2 somethin2

+

Please help. Thank you in advance

","

You need to group rows from table T1 and aggregate rows from table CONDITION:

+
CREATE TABLE T1(ID INT, DESC VARCHAR, SOMETHING VARCHAR, CONDITION_ID INT ARRAY)
+AS VALUES (1, 'EN 142868 151508', 'XYZ', ARRAY[4686, 4687]);
+
+CREATE TABLE CONDITION(CONDITION_ID INT, DESC VARCHAR, COLUMN3 VARCHAR)
+AS VALUES (4686, 'desc1', 'something1'), (4687, 'desc2', 'something2');
+
+SELECT T1.ID, T1.DESC, T1.SOMETHING,
+    LISTAGG(CONDITION.DESC || ' ' || CONDITION.COLUMN3, ', ') JOINED_COLUMN
+FROM T1 LEFT JOIN CONDITION ON ARRAY_CONTAINS(T1.CONDITION_ID, CONDITION.CONDITION_ID)
+GROUP BY T1.ID, T1.DESC, T1.SOMETHING;
+> ID | DESC             | SOMETHING | JOINED_COLUMN
+> -- | ---------------- | --------- | ----------------------------------
+> 1  | EN 142868 151508 | XYZ       | desc1 something1, desc2 something2
+
+

If you want to exclude rows from T1 without corresponding entries in CONDITION, use inner JOIN instead of LEFT JOIN.

+

You may also want to add WITHIN GROUP (ODRER BY some_columns) clause to LISTAGG aggregate function if you need some exact order of entries:

+
LISTAGG(CONDITION.DESC || ' ' || CONDITION.COLUMN3, ', ')
+WITHIN GROUP (ORDER BY CONDITION.CONDITION_ID)
+JOINED_COLUMN
+
+

Alternatively, you can use a subquery:

+
SELECT T1.ID, T1.DESC, T1.SOMETHING,
+  (
+    SELECT LISTAGG(CONDITION.DESC || ' ' || CONDITION.COLUMN3, ', ')
+    FROM CONDITION
+    WHERE ARRAY_CONTAINS(T1.CONDITION_ID, CONDITION.CONDITION_ID)
+  ) JOINED_COLUMN
+FROM T1;
+
",r +"Twilio IVR flow with translations

I am trying to add multiple languages to my studio flow. 1 - English, 2 - Spanish, 3 - French.

+

When the user selects the language I am saving the selected lang in {{flow.variables.lang}}. Based on the selected lang, I then load the respective translations.

+

I have multiple strings which use values set in the previous widget. I am not understanding how to set these values dynamically.

+

For Example:

+

String: "Welcome to Studio flow, we found your information in our system with zip code {{widgets.User_Information.parsed.zipCode}}"

+

In the translation file, I have this string set to key "User_Zip_Code".

+

In the widget "Gather Input on call" I added {{widgets.Translation_Function.parsed.User_Zip_Code}} in the text to say field. But when the voice reads it out, I expected Twilio would parse the and insert the dynamic value, but it just read it out as is. Is there a way to dynamically insert these flow variables in the string dynamically?

+

One way I could think of is to call a function and have that function return the string after replacing the values, but for some reason, there are a lot of gaps that I am seeing when the flow moves from one function to another, so I am trying to avoid function calls.

+

EDIT:

+

Adding the data shown in the Widget & Flow Properties

+
 "User_Information": {
+      "status_code": 200,
+      "content_type": "application/json",
+      "parsed": {
+        "zipCode": 201010
+      },
+}
+
+
    "Translation_Function": {
+      "status_code": 200,
+      "content_type": "application/json",
+      "parsed": {
+          "User_Zip_Code": "Welcome to Studio flow, we found your information in our system with zip code {{widgets.User_Information.parsed.zipCode}}. Press pound to continue.”
+    },
+}
+
+

Thanks in advance

","

It should work as you explained. Are you sure the reference in the liquid syntax is indeed correct, for example: {{widgets.User_Information.parsed.zipCode}} ?

+

Try looking at the Studio Flow Execution Logs (under Logs) to see the path you must refer to in the liquid syntax is correct/

+

+

Update:

+

It appears you are nesting Liquid Syntax expressions. What I mean by that is your Gather Input on Call Widget is referencing parsed JSON from an earlier Widget and that JSON has a liquid syntax expression in it.

+

Example JSON:

+

"FT_Fee_Information": "We found your account in our XX payment system. As a reminder, payments processed through this system are subject to a $x.xx convenience fee. Payments without a fee can be made through the My Account portal on our website at example.com. If you would like to use the stored payment information to make a payment on account ending in {{widgets.Validate_Number.parsed.accountNumber}}. Please enter the 5 digit zip code associated with this account. If you would like to pay on a different account press the pound key.

+

I am pretty sure that is the reason for your issue, you can't nest these liquid syntax expression. Instead, can you pass in the Studio data to the Function calling the JSON so that Function can pre-populate this information (static data) into JSON (instead of using a liquid expression) before returning the JSON blob to Studio?

",r +"How to generate random data for association table?

I am working on an e-shop with three tables: products, atributes and product_atributes. I have already filled tables products and atributes:

+
insert into atribute(name)
+select random_atribute()
+from generate_series(1,10000) as seq(i);
+
+insert into product(price)
+select floor(1 + random() * 100)::int
+from generate_series(1,20000) as seq(i);
+
+

I want to generate random data for the table product_atributes: There can be 1 attribute for 1 product but also all attributes for just 1 product. The result should look like:

+
product_atributes
+id  product_id     atribute_id
+1      5               12
+2      5               76
+3      5               10
+4      5                7
+5      1               45
+6      1               109
+...
+
+

Table product_atributes is created like this:

+
create table product_atributes(
+  id serial primary key,
+  atribute_id integer references atribute(id),
+  product_id integer references product(id)
+);
+
+

I tried sth. like this, but it's not working:

+
with data as (
+    select  s.i,
+            random_atribute_id() as atribute_id,
+            s.id as product_id
+   
+    from (generate_series(1, 1000) as seq(i)
+             cross join lateral (select seq.i, * from product order by random() limit 1) as s)
+)
+
+insert into product_atributes(atribute_id, product_id)
+select atribute_id, product_id from data;
+
+

How can I do this?

","

Simple

+

To insert every possible combination with an even chance of 1 percent:

+
INSERT INTO product_atributes(product_id, atribut_id)
+SELECT p.product_id, a.atribut_id
+FROM   product p
+JOIN   atribute a ON random() >= 0.99;
+
+

More sophisitcated & faster

+

This offers more control over minimum and maximum number of attributes.

+

And it's a lot faster for your particular setup with gap-less attribute IDs (from 1 to 10000):

+
INSERT INTO product_atributes(product_id, atribut_id)
+SELECT p.product_id, a.atribut_id
+FROM  (SELECT product_id, trunc(random() * 10)::int AS ct FROM product) p
+CROSS  JOIN LATERAL (
+   SELECT DISTINCT 1 + trunc(random() * 10000) AS atribut_id
+   FROM   generate_series (0, p.ct) g
+   ) a;
+
+

This generates 0 to 10 completely random associations per product.
+2 + trunc(random() * 6)::int AS ct would generate 3 to 8 associations. (Note the 0-based generate_series()!)

+

Generate the number of attributes (ct) in a subquery to avoid single evaluation of random() resulting in the same number for all products.

+

We can optimize performance for gap-less IDs quite a bit. Instead of walking through all 10000 attribute for every product, just generate random numbers for the given range of IDs. Much faster.
+Throw in DISTINCT to eliminate (unlikely) duplicates. Hardly matters for 10 our of 10000, but we can't allow duplicates. (So it's possible to get fewer associations in rare cases.)

+

We could even work with a few gaps. There are quite a few subtleties to selecting random rows. See:

+ +

Asides

+

You could also populate all three tables with random data in a single query using data-modifying CTEs. Simple example for a 1:n relationship:

+ +

Same principle for your case, jut two CTEs ...

+

Related:

+ +

"Attributes" are spelled like this.

",r +"How to initialize react usecontext state value during jest tests?

I have code where user can click on the ingredient and then I store his selected ingredient inside context and redirect him to a details page:

+
  const [, setSelectedItem] = useContext(itemContext);
+  const [, setSelectedMealNumber] = useContext(selectedMealNumberContext);
+
+  const editIngredient = (event: React.MouseEvent<HTMLElement>) => {
+    setSelectedItem(ingredient);
+    setSelectedMealNumber(mealNumber);
+    router.push(`/i/${ingredient?.uid}`);
+  };
+
+

However selectedItem is initialized as null in my context provider:

+
// Provider component
+
+function ApiStore({ children }) {
+  const [selectedItem, setSelectedItem] = useState(null);
+
+

So when testing details page:

+
it("renders the selected item productName", () => {
+  const queryClient = new QueryClient();
+  render(
+    <ApiStore>
+      <QueryClientProvider client={queryClient}>
+        <IngredientExpanded />
+      </QueryClientProvider>
+    </ApiStore>
+  );
+  const productName = screen.getByText(FakeItem1.productName);
+  expect(productName).toBeInTheDocument();
+});
+
+

Test fails, because selectedItem is null.

+

At the moment I manually initialize the value in my context provider like this and my test succeeds:

+
  const [selectedItem, setSelectedItem] = useState(FakeItem1);
+
+

But since I need this value only for my tests and not the actual app, I have to remove it and set it back to null on my production app.

+

I don't need to mock everything since, everything else works. How can I simply inject the selectedItem during my test?

","

The easiest way is to add value props for ApiStore component. Then you can provide the initial value for the context provider.

+

index.ts:

+
import React, { useContext, useState } from 'react';
+
+const ItemContext = React.createContext({
+  selectedItem: null,
+  setSelectedItem: (state) => {},
+});
+
+export const ApiStore = ({ children, value }) => {
+  const [selectedItem, setSelectedItem] = useState(value);
+
+  return <ItemContext.Provider value={{ selectedItem, setSelectedItem }}>{children}</ItemContext.Provider>;
+};
+
+export const IngredientExpanded = () => {
+  const { selectedItem } = useContext(ItemContext);
+
+  return <div>{selectedItem}</div>;
+};
+
+

index.test.ts:

+
import { render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom/extend-expect';
+import React from 'react';
+import { ApiStore, IngredientExpanded } from '.';
+
+describe('72047880', () => {
+  test('should find the selected item', () => {
+    render(
+      <ApiStore value={'product name'}>
+        <IngredientExpanded />
+      </ApiStore>
+    );
+    const productName = screen.getByText('product name');
+    expect(productName).toBeInTheDocument();
+  });
+
+  test('should not find the selected item', () => {
+    render(
+      <ApiStore value={null}>
+        <IngredientExpanded />
+      </ApiStore>
+    );
+    const productName = screen.queryByText('product name');
+    expect(productName).not.toBeInTheDocument();
+  });
+});
+
+

test result:

+
 PASS  stackoverflow/72047880/index.test.tsx (11.239 s)
+  72047880
+    ✓ should find the selected item (23 ms)
+    ✓ should not find the selected item (3 ms)
+
+Test Suites: 1 passed, 1 total
+Tests:       2 passed, 2 total
+Snapshots:   0 total
+Time:        12.855 s
+
",r +"Delete a field from Firebase Firestore where the field/key has a period/punctuation (""."") - modular v9 JavaScript SDK

This question is for a React Native Expo mobile App if that matters.

+

I have a flat database object. Using the documentation as an example:

+ +

I have added a field/key called "example.com" with some arbitrary value. +The object then looks like this:

+
{
+capital: "words",
+location: "other words",
+"example.com": "more words"
+}
+
+

I want to delete the key "example.com" key from the database, and I am using pretty much the same code as in the example from the documentation.

+
const cityRef = doc(db, "cities", "BJ");
+const payload = {
+    "example.com": deleteField(),
+};
+await updateDoc(cityRef, payload);
+
+

This does not delete the "example.com" key. I understand that this attempts to delete the "com" key from the "example" object within the main database document, which is not what I want, but I do not understand how to rework this code to treat the entire string as a key.

+

I have looked at some similar questions here on SO(links at the bottom) that came to the conclusion that they had to use FieldPath, but the syntax is outdated, and no longer works on the current version of Firestore(or at least I can not find the documentation for FieldPath for the version I am using, linked above).

+

And tips on how to get this working (deleting a field with a period) would be appreciated.

+

Link to similar problems:

+","

You still need to use FieldPath, but the API is different in the new v9 module SDK. You can see FieldPath in the API docs. Just import it along with any other functions that you use from the Firestore SDK.

+

I haven't used it myself, but based on the linked docs, my guess is that it works like this:

+
import { updateDoc, deleteField, FieldPath } from "firebase/firestore";
+...
+updateDoc(cityRef, new FieldPath("example.com"), deleteField());
+
",r +"Google Calendar API all day event spanning an extra day?

In my Google calendar, which is in the America/Toronto timezone, I have an event that is marked as an all day on the 13 April 2022, but it is coming back as starting on 2022-04-13 and ending on 2022-04-14. I have some other all day event behaving in the same way.

+

This is happening from my code, but also when I try with the API test form here:

+

https://developers.google.com/calendar/api/v3/reference/events/list

+

With parameters:

+
    +
  • timeMin: 2022-04-10T18:36:39.000Z
  • +
  • timeMax: 2022-04-17T18:36:39.000Z
  • +
+

This returns me the following response (certain fields masked):

+
 "kind": "calendar#events",
+ "etag": "\"p328ftm5rim7ve0g\"",
+ "summary": "My Test Calendar",
+ "updated": "2022-04-12T18:36:40.074Z",
+ "timeZone": "America/Toronto",
+ "accessRole": "owner",
+ "defaultReminders": [],
+ "nextSyncToken": "xxx-xxxx_cCEJD-2LuVj_cCGAUg8t3t0QE=",
+ "items": [
+  {
+   "kind": "calendar#event",
+   "etag": "\"3299577200148000\"",
+   "id": "xxxxga02nqb11ub6dm29dgg9t",
+   "status": "confirmed",
+   "htmlLink": "https://www.google.com/calendar/event?eid=xxxxxxnYTAybnFiMTF1YjZkbTI5ZGdnOXQgY19uZ2hqOXFzb25tYjRtNDRqN2doaTNxNzY5a0Bn&ctz=UTC",
+   "created": "2022-04-12T18:36:39.000Z",
+   "updated": "2022-04-12T18:36:40.074Z",
+   "summary": "Dummy Event",
+   "creator": {
+    "email": "xxxxxx",
+    "displayName": "xxxxxx"
+   },
+   "organizer": {
+    "email": "xxxxxxx@group.calendar.google.com",
+    "displayName": "My Test Calendar",
+    "self": true
+   },
+   "start": {
+    "date": "2022-04-13"
+   },
+   "end": {
+    "date": "2022-04-14"
+   },
+   "transparency": "transparent",
+   "iCalUID": "xxxxx@google.com",
+   "sequence": 0,
+   "reminders": {
+    "useDefault": false
+   },
+   "eventType": "default"
+  }
+ ]
+}
+
+
+

I tried providing both 'America/Toronto' and 'UTC' as timeZone parameters in the request, but this does not change anything.

+

Can anyone suggest how to get an all day event to span only the day it is meant to be happening on?

+

BTW below you can see the event was only on a single day:

+

","

This is an expected behavior from the Calendar API. All day event last for 24 hours. Lasting from midnight of start date to midnight of the next day.

+

It is also written in the Event Resource that end is exclusive.

+

An alternative solution to this is to -1 the end date of the response body or manually plot the time. But if you try to manually create an All day event by plotting the time, It can only last for 23.5 hrs.

+

",r +"CodeIgniter 4 \Config\Service::my-instance-method returns NULL on true $getShared

Config\Services is a class made to reduce huge code development on singleton. Unfortunately I have committed an error.

+

When repositoryFacade is got from getShared,

+
Services::repositoryFacade(Services::userRepository(), TRUE);
+
+

The code will fail and says:

+
Config\Services::repositoryFacade(): Return value must be of type App\Domain\Core\IRepositoryFacade, null returned
+
+

The following code has been set in app/Config/Service.php

+
public static function repositoryFacade(IRepository $repository, bool $getShared = false): IRepositoryFacade{
+    if ($getShared) {
+        return self::getSharedInstance('resourceFacade');
+    }
+
+    return new RepositoryFacade($repository);
+}
+
+public static function userRepository(bool $getShared = true): IRepository
+{
+    if ($getShared) {
+        return self::getSharedInstance('userRepository');
+    }
+
+    return new UserRepository(model(UserModel::class));
+}
+
+

RepositoryFacade is in infrastructure layer to serve IRepository domain interface one by one, while UserRepository is a concrete class in infrastructure layer, its duty is to let RepositoryFacade to perform ORM, without any touch to domain layer.

+

Is the getShared not useful at all? There is no error when TRUE value has been removed.

+
Services::repositoryFacade(Services::userRepository());
+
","

This line of code is incorrect logically.

+
Services::repositoryFacade(Services::userRepository(), TRUE);
+
+

Change it to below works perfectly.

+
Services::repositoryFacade(Services::userRepository(TRUE));
+
+

It would be more than one RepositoryFacade class instances can be made to serve Repository instances, such as UserRepository, ProductRepository, thus we no need to get the same instance of RepositoryFacade.

+

UserRepository should be unchanged all the times. Therefore we can get the same instance of UserRepository by:

+
Services::userRepository(TRUE)
+
+

If it is needed to use the facade with UserRepository more than once, just

+
$facade = Services::repositoryFacade(Services::userRepository(TRUE));
+
+// use multiple times with the facade 
+$result = $facade->findById(5);
+if (!empty($result)) $facade->delete(5); 
+
",r +"Shortcut to reveal in Finder for currently opened file in Android Studio?

Is there any keyboard short cut to open currently open file in the finder? I know it can be done like below?

+

","

No. It is not present but we can add it. Go to Preferences -> Keymap and then search Finder (For Mac). There you see Reveal in Finder. DO right click and click Add Keyboard Shortcut there you can add your desired shortcut. See the image ->

+
    +
  1. Step 1
  2. +
+

+
    +
  1. Step 2
  2. +
+

",r +"How to redirect external link in a Docker container to local service

I'm still early on my Docker journey and I'm trying to 'Dockerise' an existing UI/API/DB web app where the UI & API/DB are on two different servers. It's gone fairly well so far and my docker-compose fires up services for UI, API & DB (and phpMyAdmin) just fine. I know that those services can communicate inherently using service names as host names due to the default networking method of Docker.

+

The UI (an Angular codebase) makes various calls to https://api.myproject.com which works fine in the live sites but isn't ideal in my Docker version as I want it to reach my API service in the container not the API live site.

+

I know that I can edit the code on the UI container and replace calls to https://api.myproject.com with calls to 'api' but that's inconvenient and lacks portability if I want to redeploy on different servers (as it is now) in future.

+

Is it possible for a container to redirect all POST/GET etc. for a URL to a container service? I thought the --add-host might do something like this but it seems to want an IP address rather than a service name.

+

Thanks in advance.

+

EDIT [clarification] +My issue lies in the UI page (HTML/JS) that the user sees in the browser. When the page is loaded it throws some GET requests to the API URL and that's what I was hoping to redirect to the container API service.

","

You can use network aliases for the given container and those can override an existing fqdn.

+

Here is a 2mn crafted example:

+

docker-compose.yml

+
---
+services:
+  search_engine:
+    image: nginx:latest
+    networks:
+      default:
+        aliases:
+          - google.com
+          - www.google.com
+
+  client:
+    image: alpine:latest
+    command: tail -f /dev/null
+
+

You can start this project with:

+
docker-compose up -d
+
+

Then log into the client container with

+
docker-compose exec client sh
+
+

And try to reach your search_engine service with either of the following

+
wget http://search_engine
+wget http://google.com
+wget http://www.google.com
+
+

In all cases you will get the default index.html page of a brand new installed nginx server.

",r +"KQL Azure Workbook: Filtering AppInsights cross-resource query by subscription

I want to filter ApplicationInsights resources by a workbook parameter for subscriptions set in the Azure Workbook. I don't see documentation on how to do this, does anyone have a solution?

+

My cross-resource query takes the following form. I need to filter by subscriptionId and there is no parameter to do so on the resulting table, how do I filter in this way?

+
union withsource=SourceApp 
+app('Contoso-app1').requests,  
+app('Contoso-app2').requests, 
+app('Contoso-app3').requests, 
+app('Contoso-app4').requests, 
+app('Contoso-app5').requests 
+| parse SourceApp with * "('" applicationName "')" *  
+| where success = False
+
+

Thanks in advance.

","

In legacy application insights instance the appName property of any telemetry item has the following structure:

+
/subscriptions/<subscriptionId>/resourcegroups/<resourceGroup>/providers/microsoft.insights/components/<appInsightsName>
+
+

However, as you and I found out, sometimes the appName just reflects the name instead of the resource id. Anyway, when it is filled properly it can be used to get what you want.

+

By using the split() function we can extract the subscriptionId and create a filter using where like this:

+
union withsource=SourceApp 
+app('Contoso-app1').requests,  
+app('Contoso-app2').requests, 
+app('Contoso-app3').requests, 
+app('Contoso-app4').requests, 
+app('Contoso-app5').requests 
+| parse SourceApp with * "('" applicationName "')" *
+| extend subscription = split(appName, "/")[2]
+| where subscription == "<a subscriptionId>"
+
+

Workspace based application insights instances have a property _ResourceId that can be used, instead of appName. If you are using a legacy instance, convert it to a Workspace based application insights instance and new(!) log entries will get this _ResourceId property:

+
union withsource=SourceApp 
+app('Contoso-app1').requests,  
+app('Contoso-app2').requests, 
+app('Contoso-app3').requests, 
+app('Contoso-app4').requests, 
+app('Contoso-app5').requests 
+| parse SourceApp with * "('" applicationName "')" *
+| extend subscription = split(_ResourceId, "/")[2]
+| where subscription == "<a subscriptionId>"
+
",r +"Object not awaitable when returning Task instead of List

I have this method that should return only one Project object. +IntelliSense is telling me to update it to return a Task<List> but then I have to change the declaration of the property (I want to confirm that only one project is being returned, hence the .Result.First() +however I'm getting an error saying that Project is not awaitable.

+
 public async Task<Project> GetProjectDataAsync(int projectId)
+        {
+            return await _db.LoadData<Project, dynamic>("dbo.Sp_Get_Project_Data_By_ProjectId",
+                new { projectId },
+                ConnectionStringName,
+                true).Result.First();
+        }
+
+

this is the call:

+
 public Project Project { get; set; }
+ public async Task OnGetAsync(int projectId)
+        {
+            Project = await _db.GetProjectDataAsync(projectId);
+
+        }
+
+

If it worth noting, I'm using Dapper to connect to DB with the following definition for LoadData:

+
 public async Task<List<T>> LoadData<T, U>(string sqlStatement, U parameters, string connectionStringName, bool isStoredProcedure = false)
+        {
+            string connectionString = _config.GetConnectionString(connectionStringName)!;
+
+            CommandType commandType = CommandType.Text;
+
+            if (isStoredProcedure == true)
+            {
+                commandType = CommandType.StoredProcedure;
+            }
+
+            using (IDbConnection connection = new SqlConnection(connectionString))
+            {
+                var rows = await connection.QueryAsync<T>(sqlStatement, parameters, commandType: commandType);
+                return rows.ToList();
+            }
+        }
+
","

Get rid of the .Result call. It's essentially trying to make the asynchronous operation synchronous. (And then .First() is indeed not awaitable.)

+

The awaitable operation is _db.LoadData<Project, dynamic>(...), for example:

+
var data = await _db.LoadData<Project, dynamic>(
+  "dbo.Sp_Get_Project_Data_By_ProjectId",
+  new { projectId },
+  ConnectionStringName,
+  true
+);
+return data.First();
+
+

Or if you want to do it in one line, still await the call to LoadData and wrap that operation in parentheses:

+
return (await _db.LoadData<Project, dynamic>(
+  "dbo.Sp_Get_Project_Data_By_ProjectId",
+  new { projectId },
+  ConnectionStringName,
+  true
+)).First();
+
",r +"How to get Custom Log tables from Azure Log Analytics Workspace through PowerShell script?

I am looking for a way to get all custom log tables from an Azure log analytics workspace through PowerShell code.

+

Below is an example of three custom log tables of which I would like to see the names in an object (array/list/...).

+

+

I am able to create a custom log table, insert and check data in it, but I am not able to upfront check if the table already exists, before I query on it.

+

I am using the Invoke-AzOperationalInsightsQuery PowerShell cmdlet to query on the custom log table, but this fails if the log does not exist yet. Hence the question.

+

Thanks for your input.

","
    +
  • I have created sample custom log tables
  • +
+

+

and executed the below command

+
Get-AzOperationalInsightsDataSource -Kind CustomLog -ResourceGroupName RGName -WorkspaceName LogAnalyticsWorkSpaceName
+
+

+

Get-AzOperationalInsightsDataSource - Gets datasources under Azure Log Analytics workspace.

",r +"Problem targeting a component to set style

I have a custom component that uses a mat-checkbox. And i want to only change the bqckground for that component but i don't have much luck.

+

My Template code is below

+
<form novalidate [formGroup]="form">
+    <mat-form-field>
+    <mat-label>{{labelText}}</mat-label>
+    <mat-select class="select" #select [multiple]="multiselect" [formControl]="selectField" >
+      <div class="select-all">
+          <mat-checkbox *ngIf="multiselect" [(ngModel)]="allSelected"
+                         class="mat-check-all"
+                          [ngModelOptions]="{standalone: true}"
+                          [indeterminate]="isIndeterminate()"
+                          [checked]="isChecked()" 
+                          (click)="$event.stopPropagation()"
+                          (change)="toggleAllSelection($event)">{{text}}</mat-checkbox>
+      </div>
+      <mat-option *ngFor="let item of data" [value]="item[idField]">
+        {{item[fieldName]}}
+      </mat-option>
+    </mat-select>
+    </mat-form-field>
+    </form>
+
+

i tried the following with no luck

+
.mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+.mat-check-all .mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+.select-all .mat-check-all .mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+.select .select-all .mat-check-all .mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+::ng-deep .select .select-all .mat-check-all .mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+
+

neither of the above made any difference. When i used

+
::ng-deep .mat-checkbox-checked.mat-accent .mat-checkbox-background {
+    background-color: rgb(49, 201, 11);
+  }
+
+

it changed the color for my checkbox but also for any other checkbox on the form. So how can i limit the change to the checkbox in my componenet ?

","

Based on your above template code you can just simply set the color for your custom component via

+
::ng-deep
+  .select-all
+  .mat-checkbox-checked.mat-accent
+  .mat-checkbox-background {
+  background-color: rgb(224, 198, 28) !important;
+}
+
+

You can verify in the forked StackBlitz Sample

",r +"Loop valueboxes in R-Flexdashboards

Happy Easter!

+

I wonder if there is any smart programming for looping value boxes (or even better: whole r-markdown-code) in R-flexdashboards using R-shiny.

+

My problem is:

+

I have data, which is updated every day. +Every day I can display several keyfigueres. +I do this with value-boxes, becaus it is very easy to add special colors for different treshholds.

+

I want to show the data of the last week (7-days), see image, widch show the data for 4 days:

+

+

Is there a possibility to loop my code day by day?

+

My executable code example is only for two days an the valuebox for date (1st column in the image):

+
---
+title: "Test for Loop value boxes"
+author: StatistiVolker
+output: 
+  flexdashboard::flex_dashboard:
+    
+    orientation: rows
+    vertical_layout: fill
+runtime: shiny
+---
+
+```{r setup, include=FALSE}
+require(shiny)
+require(flexdashboard)
+require(tidyverse)
+```
+
+<!-- C19J_Summary.Rmd -->
+
+Testcode
+=======================================================================
+
+Sidebar {.sidebar}
+-----------------------------------------------------------------------
+  
+### Settings
+
+```{r}
+sliderInput("sliderSumDate",
+            "Datum",
+            min = as.Date("2020-03-01"),  #min(C19JKInz()$datI),
+            max = Sys.Date()-1,
+            value = Sys.Date()-1,
+            animate = TRUE)
+
+```
+
+```{r}   
+# Date
+selSumDate <- reactive({
+  input$sliderSumDate
+})
+
+```
+
+<!-- Is it possible to loop this Code? -->
+
+
+Row 
+-----------------------------------------------------------------------
+<!-- actual day -->
+
+###  {.value-box}
+
+```{r}   
+# Emit the download count
+renderValueBox({
+  valueBox(format(as.Date(selSumDate()-0),"%d.%m.%Y (%a)"), 
+           caption = "Datum",
+           # icon = "fa-calendar", 
+           color = "cornflowerblue")
+})
+
+``` 
+
+<!-- Next Code is almost the same as above, except one day earlier -->
+<!-- Is it possible to loop this Code? -->
+
+Row 
+-----------------------------------------------------------------------
+<!-- day before -->
+
+###  {.value-box}
+
+```{r}   
+# Emit the download count
+renderValueBox({
+  valueBox(format(as.Date(selSumDate()-1),"%d.%m.%Y (%a)"), 
+           caption = "Datum",
+           # icon = "fa-calendar", 
+           color = "cornflowerblue")
+})
+
+```  
+
+

Thank you for any idea to solve my problem.

+

PS: This was not useful, because it is not possible to control the colors for different treshholds

","

you have found an Easter egg:

+
---
+title: "Test for Loop value boxes"
+author: StatistiVolker
+output: 
+  flexdashboard::flex_dashboard:
+    
+    orientation: rows
+    vertical_layout: fill
+runtime: shiny
+---
+
+```{r setup, include=FALSE}
+require(shiny)
+require(flexdashboard)
+require(tidyverse)
+```
+
+<!-- C19J_Summary.Rmd -->
+# Sidebar {.sidebar data-width=350}
+  
+### Settings
+
+```{r}
+sliderInput("sliderSumDate",
+            "Datum",
+            min = as.Date("2020-03-01"),  #min(C19JKInz()$datI),
+            max = Sys.Date()-1,
+            value = Sys.Date()-1,
+            animate = TRUE)
+
+```
+
+```{r}   
+# Date
+selSumDate <- reactive({
+  input$sliderSumDate
+})
+
+```
+
+<!-- Is it possible to loop this Code? -->
+```{r}
+myValueBox <- function(title, caption="", color="cornflowerblue", myicon="", fontsize="25px"){
+    div(
+        class = "value-box level3",
+        style = glue::glue(
+            '
+            background-color: @{color}@;
+            height: 106px;
+            width: 18%;
+            display: inline-block;
+            overflow: hidden;
+            word-break: keep-all;
+            text-overflow: ellipsis;
+            ', .open = '@{', .close = '}@'
+        ),
+        div(
+            class = "inner",
+            p(class = "value", title, style = glue::glue("font-size:{fontsize}")),
+            p(class = "caption", caption)
+        ),
+        div(class = "icon", myicon)
+    )
+}
+```
+
+
+Testcode
+=======================================================================
+<!-- actual day -->
+```{r}
+uiOutput("el")
+```
+
+
+
+
+```{r}   
+# Emit the download count
+colors = c("#8b0000", "#000000", "#228b22", "#ffd700")
+output$el <- renderUI({
+    lapply(0:-6, function(x) {
+        div(
+            myValueBox(format(as.Date(selSumDate()-x),"%d.%m.%Y (%a)"), "Datum", myicon = icon("calendar")),
+            myValueBox(sample(1000, 1), "Infizierte", color = sample(colors, 1)),
+            myValueBox(sample(1000, 1), "Aktiv erkrankt", color = sample(colors, 1)),
+            myValueBox(sample(1000, 1), "Genesene", color = sample(colors, 1)),
+            myValueBox(sample(1000, 1), "Verstorbene", color = sample(colors, 1))
+        )
+    })
+})
+``` 
+
+
+
    +
  • Impossible to create what you want with original {flexdashboard} package, no way to control row/column layout automatically. However, we can create our own value box.
  • +
  • Works the best on bigger screens (> 1000px width), also works on mobile (<670px), different styles will apply on small screens. Medium screens (670-1000) may have some problems, try to change width: 18%; to a number you want.
  • +
  • overflow text due to screen size issues are trimmed off. Change the +fontsize argument may also help.
  • +
+

Bigger screen

+

+

Mobile

+

",r +"Get earliest date from dataframe columns

I just started working with DataFrames and i'm struggling with a request:

+

I have a df with this structure:

+
id req_date             spec_date
+1  2021-09-28T07:19:43  2021-09-24T07:17:02
+2  2021-04-28T07:19:43  
+3                       2021-02-21T07:14:41
+
+

I'm trying to create a new column for which the values to be the earliest dates between the req_date and spec_date. It's working as expected when both column have values , but if one of them is empty then the new column value will also be empty, how do i treat this case?

","

You can try pandas.DataFrame.min along columns with skipna=False

+
df['col'] = (df[['req_date', 'spec_date']]
+             .apply(pd.to_datetime)
+             .min(axis=1, skipna=False)
+             .dt.strftime('%Y-%m-%dT%H:%M:%S')
+)
+
+
print(df)
+
+   id             req_date            spec_date                  col
+0   1  2021-09-28T07:19:43  2021-09-24T07:17:02  2021-09-24T07:17:02
+1   2  2021-04-28T07:19:43                 None                  NaN
+2   3                 None  2021-02-21T07:14:41                  NaN
+
+

Depending if you want to skip NAN, you can adjust skipna

+
df['col'] = (df[['req_date', 'spec_date']]
+             .apply(pd.to_datetime)
+             .min(axis=1)   # <-- difference here
+             .dt.strftime('%Y-%m-%dT%H:%M:%S')
+)
+
+
print(df)
+
+   id             req_date            spec_date                  col
+0   1  2021-09-28T07:19:43  2021-09-24T07:17:02  2021-09-24T07:17:02
+1   2  2021-04-28T07:19:43                 None  2021-04-28T07:19:43
+2   3                 None  2021-02-21T07:14:41  2021-02-21T07:14:41
+
",r +"How to use customer credit balance without invoice in stripe?

I want to create a system in bubble.io app with stripe, in which:

+
    +
  1. the customer while purchasing products will pay though their credit balance but the invoice should not generate (or without invoice). +if it possible, then how? and if not then:

    +
  2. +
  3. customer should transfer money to stripe platform balance and whenever they make a purchase the money should transfer from stripe platform balance to the seller.

    +
  4. +
+

any solution?

","
    +
  1. The customer's credit balance automatically applies toward the next invoice of the customer. So if you are not using invoices, it won't work. The alternative is to keep track of the customer's balance on your end, and change the amount they need to pay accordingly.
  2. +
  3. If you want the platform account to charge the customer, and then later send the funds to the connected account(s), then you should use separate charges & transfers.
  4. +
",r +"How to handle and redirect when blocked by CORS policy occurs in React application

I have a function that receives a result.text (this is a string from qr scan camera eg string:565650). +When i have the result i saved in const productString, and then i make a get request with that string. If the response is ok i have my product and adding it to my checkout-bag,until that spot everything is working perfectly.

+

Also when i will scan a non product - qr code which means my result.text will not get a response i want to redirect the user in a 404 page. In addition i get Cors policy error.

+

+

I want after my scan if is not successfull to redirect the user in 404 page my code is below in that function.

+
  const handleScanResult = (result) => {
+    setLoading(true);
+    setProductString(formatString(result.text))
+    fetchData(`${API_URL}/products/${formatString(result.text)}`)
+      .then((data) => {
+        handleAddMemo(data);
+        setLoading(false);
+        setOpenAddMemoDialog(true);
+        handleClose();
+      })
+      .catch((ex) => {
+        setLoading(false);
+        console.log(ex,"ex")
+      })
+  };
+
","

Cors is a browser security mechanism, you cannot skip it... Well in fact you can try but you'll face issue, see Trying to use fetch and pass in mode: no-cors

+

I recommand you to follow the rules. So either:

+
    +
  • you server both app and api on the same host+port
  • +
  • you put a proxy like nginx to serve both on same host+port
  • +
  • you change your api to follow the needed rules, mostly headers and option method.
  • +
+

There is a good explanation here : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

+

Here is a simple config file for Nginx if you want to give it a try

+
    server_name myapp.localhost;
+
+    listen 80;
+
+    location /api/myApp {
+        proxy_pass http://127.0.0.1:15000;
+        #Change 15000 to the API port you use
+    }
+
+    location / {
+        proxy_set_header Upgrade $http_upgrade;
+        proxy_set_header Connection "upgrade";
+        proxy_http_version 1.1;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header Host $host;
+        proxy_pass http://127.0.0.1:17050;
+        #Change 17050 to the APP port you use
+    }
+}
+
",r +"Webpack transpiled Typescript service worker code doesn't seem to work

I'm trying to implement a service worker, but fail to make it execute the service worker code work if it is transpiled for Typescript with Webpack + Bable. Registration works fine and the worker is shown as activated, but neither the install, nor activate events are ever fired - I assume due to the code not being executed correctly. Now, if I replace the transpiled code with the same code in plain Javascript everything works fine.

+

Everything else is working fine in the browser, so it doesn't seem to be some inherent issue with my settings - at least none I understand. I'd really like to understand what is causing this issue!

+

Here is the relevant code and config:

+

service-worker.ts:

+
declare const self: ServiceWorkerGlobalScope;
+
+// Incrementing OFFLINE_VERSION will kick off the install event and force
+//  previously cached resources to be updated from the network.
+// This variable is intentionally declared and unused.
+const OFFLINE_VERSION = 1;
+const CACHE_NAME = "offline";
+const OFFLINE_URL = "offline.html";
+
+self.addEventListener("install", (event) => {
+  console.debug("Install service worker");
+
+  event.waitUntil(
+    (async () => {
+      const cache = await caches.open(CACHE_NAME);
+      await cache.add(new Request(OFFLINE_URL, {cache: "reload"}));
+
+      console.debug("Service worker installed");
+    })()
+  );
+  void self.skipWaiting();
+});
+
+self.addEventListener("activate", (event) => {
+  console.debug("Activate service worker");
+
+  event.waitUntil(
+    (async () => {
+      // Enable navigation preload if it's supported.
+      // See https://developers.google.com/web/updates/2017/02/navigation-preload
+      if ("navigationPreload" in self.registration) {
+        // @ts-ignore this is only called if the browser supports it
+        await self.registration.navigationPreload.enable();
+
+        console.debug("Service worker enabled navigationPreload");
+      }
+    })()
+  );
+
+  void self.clients.claim();
+});
+
+self.addEventListener("fetch", (event) => {
+  if (event.request.mode === "navigate") {
+    event.respondWith(
+      (async () => {
+        try {
+          // @ts-ignore
+          const preloadResponse = await event.preloadResponse;
+          if (preloadResponse) {
+            console.debug("Returning preloaded response for fetch request");
+
+            return preloadResponse;
+          }
+
+          const networkResponse = await fetch(event.request);
+
+          console.debug("Returning network response for fetch request");
+
+          return networkResponse;
+        } catch (error) {
+          // catch is only triggered if an exception is thrown, which is likely
+          // due to a network error.
+          // If fetch() returns a valid HTTP response with a response code in
+          // the 4xx or 5xx range, the catch() will NOT be called.
+          console.debug(`Fetch failed; returning offline page instead: ${error}`);
+
+          const cache = await caches.open(CACHE_NAME);
+          const cachedResponse = await cache.match(OFFLINE_URL);
+          return cachedResponse;
+        }
+      })()
+    );
+  } else {
+    console.debug("Fetch request not handled by service worker");
+  }
+});
+
+export default null;
+
+

The transpiled service-worker.js:

+
"use strict";
+/*
+ * ATTENTION: An "eval-source-map" devtool has been used.
+ * This devtool is neither made for production nor for readable output files.
+ * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
+ * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
+ * or disable the default devtool with "devtool: false".
+ * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
+ */
+(self["webpackChunkspritstat"] = self["webpackChunkspritstat"] || []).push([["service-worker"],{
+
+/***/ "./src/service-worker.ts":
+/*!*******************************!*\
+  !*** ./src/service-worker.ts ***!
+  \*******************************/
+/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
+
+eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ \"./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js\");\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ \"./node_modules/@babel/runtime/regenerator/index.js\");\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);\n\n\n// Incrementing OFFLINE_VERSION will kick off the install event and force\n//  previously cached resources to be updated from the network.\n// This variable is intentionally declared and unused.\nvar OFFLINE_VERSION = 1;\nvar CACHE_NAME = \"offline\";\nvar OFFLINE_URL = \"offline.html\";\nself.addEventListener(\"install\", function (event) {\n  console.debug(\"Install service worker\");\n  event.waitUntil((0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__[\"default\"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().mark(function _callee() {\n    var cache;\n    return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().wrap(function _callee$(_context) {\n      while (1) {\n        switch (_context.prev = _context.next) {\n          case 0:\n            _context.next = 2;\n            return caches.open(CACHE_NAME);\n\n          case 2:\n            cache = _context.sent;\n            _context.next = 5;\n            return cache.add(new Request(OFFLINE_URL, {\n              cache: \"reload\"\n            }));\n\n          case 5:\n            console.debug(\"Service worker installed\");\n\n          case 6:\n          case \"end\":\n            return _context.stop();\n        }\n      }\n    }, _callee);\n  }))());\n  void self.skipWaiting();\n});\nself.addEventListener(\"activate\", function (event) {\n  console.debug(\"Activate service worker\");\n  event.waitUntil((0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__[\"default\"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().mark(function _callee2() {\n    return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().wrap(function _callee2$(_context2) {\n      while (1) {\n        switch (_context2.prev = _context2.next) {\n          case 0:\n            if (!(\"navigationPreload\" in self.registration)) {\n              _context2.next = 4;\n              break;\n            }\n\n            _context2.next = 3;\n            return self.registration.navigationPreload.enable();\n\n          case 3:\n            console.debug(\"Service worker enabled navigationPreload\");\n\n          case 4:\n          case \"end\":\n            return _context2.stop();\n        }\n      }\n    }, _callee2);\n  }))());\n  void self.clients.claim();\n});\nself.addEventListener(\"fetch\", function (event) {\n  if (event.request.mode === \"navigate\") {\n    event.respondWith((0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__[\"default\"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().mark(function _callee3() {\n      var preloadResponse, networkResponse, cache, cachedResponse;\n      return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default().wrap(function _callee3$(_context3) {\n        while (1) {\n          switch (_context3.prev = _context3.next) {\n            case 0:\n              _context3.prev = 0;\n              _context3.next = 3;\n              return event.preloadResponse;\n\n            case 3:\n              preloadResponse = _context3.sent;\n\n              if (!preloadResponse) {\n                _context3.next = 7;\n                break;\n              }\n\n              console.debug(\"Returning preloaded response for fetch request\");\n              return _context3.abrupt(\"return\", preloadResponse);\n\n            case 7:\n              _context3.next = 9;\n              return fetch(event.request);\n\n            case 9:\n              networkResponse = _context3.sent;\n              console.debug(\"Returning network response for fetch request\");\n              return _context3.abrupt(\"return\", networkResponse);\n\n            case 14:\n              _context3.prev = 14;\n              _context3.t0 = _context3[\"catch\"](0);\n              // catch is only triggered if an exception is thrown, which is likely\n              // due to a network error.\n              // If fetch() returns a valid HTTP response with a response code in\n              // the 4xx or 5xx range, the catch() will NOT be called.\n              console.debug(\"Fetch failed; returning offline page instead: \".concat(_context3.t0));\n              _context3.next = 19;\n              return caches.open(CACHE_NAME);\n\n            case 19:\n              cache = _context3.sent;\n              _context3.next = 22;\n              return cache.match(OFFLINE_URL);\n\n            case 22:\n              cachedResponse = _context3.sent;\n              return _context3.abrupt(\"return\", cachedResponse);\n\n            case 24:\n            case \"end\":\n              return _context3.stop();\n          }\n        }\n      }, _callee3, null, [[0, 14]]);\n    }))());\n  } else {\n    console.debug(\"Fetch request not handled by service worker\");\n  }\n});\n/* harmony default export */ __webpack_exports__[\"default\"] = (null);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9zcmMvc2VydmljZS13b3JrZXIudHMuanMiLCJtYXBwaW5ncyI6Ijs7Ozs7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsSUFBTUEsZUFBZSxHQUFHLENBQXhCO0FBQ0EsSUFBTUMsVUFBVSxHQUFHLFNBQW5CO0FBQ0EsSUFBTUMsV0FBVyxHQUFHLGNBQXBCO0FBRUFDLElBQUksQ0FBQ0MsZ0JBQUwsQ0FBc0IsU0FBdEIsRUFBaUMsVUFBQ0MsS0FBRCxFQUFXO0FBQzFDQyxFQUFBQSxPQUFPLENBQUNDLEtBQVIsQ0FBYyx3QkFBZDtBQUVBRixFQUFBQSxLQUFLLENBQUNHLFNBQU4sQ0FDRSx5S0FBQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG1CQUNxQkMsTUFBTSxDQUFDQyxJQUFQLENBQVlULFVBQVosQ0FEckI7O0FBQUE7QUFDT1UsWUFBQUEsS0FEUDtBQUFBO0FBQUEsbUJBRU9BLEtBQUssQ0FBQ0MsR0FBTixDQUFVLElBQUlDLE9BQUosQ0FBWVgsV0FBWixFQUF5QjtBQUFDUyxjQUFBQSxLQUFLLEVBQUU7QUFBUixhQUF6QixDQUFWLENBRlA7O0FBQUE7QUFJQ0wsWUFBQUEsT0FBTyxDQUFDQyxLQUFSLENBQWMsMEJBQWQ7O0FBSkQ7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsR0FBRCxJQURGO0FBUUEsT0FBS0osSUFBSSxDQUFDVyxXQUFMLEVBQUw7QUFDRCxDQVpEO0FBY0FYLElBQUksQ0FBQ0MsZ0JBQUwsQ0FBc0IsVUFBdEIsRUFBa0MsVUFBQ0MsS0FBRCxFQUFXO0FBQzNDQyxFQUFBQSxPQUFPLENBQUNDLEtBQVIsQ0FBYyx5QkFBZDtBQUVBRixFQUFBQSxLQUFLLENBQUNHLFNBQU4sQ0FDRSx5S0FBQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBR0ssdUJBQXVCTCxJQUFJLENBQUNZLFlBSGpDO0FBQUE7QUFBQTtBQUFBOztBQUFBO0FBQUEsbUJBS1NaLElBQUksQ0FBQ1ksWUFBTCxDQUFrQkMsaUJBQWxCLENBQW9DQyxNQUFwQyxFQUxUOztBQUFBO0FBT0dYLFlBQUFBLE9BQU8sQ0FBQ0MsS0FBUixDQUFjLDBDQUFkOztBQVBIO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLEdBQUQsSUFERjtBQWFBLE9BQUtKLElBQUksQ0FBQ2UsT0FBTCxDQUFhQyxLQUFiLEVBQUw7QUFDRCxDQWpCRDtBQW1CQWhCLElBQUksQ0FBQ0MsZ0JBQUwsQ0FBc0IsT0FBdEIsRUFBK0IsVUFBQ0MsS0FBRCxFQUFXO0FBQ3hDLE1BQUlBLEtBQUssQ0FBQ2UsT0FBTixDQUFjQyxJQUFkLEtBQXVCLFVBQTNCLEVBQXVDO0FBQ3JDaEIsSUFBQUEsS0FBSyxDQUFDaUIsV0FBTixDQUNFLHlLQUFDO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxxQkFHaUNqQixLQUFLLENBQUNrQixlQUh2Qzs7QUFBQTtBQUdTQSxjQUFBQSxlQUhUOztBQUFBLG1CQUlPQSxlQUpQO0FBQUE7QUFBQTtBQUFBOztBQUtLakIsY0FBQUEsT0FBTyxDQUFDQyxLQUFSLENBQWMsZ0RBQWQ7QUFMTCxnREFPWWdCLGVBUFo7O0FBQUE7QUFBQTtBQUFBLHFCQVVpQ0MsS0FBSyxDQUFDbkIsS0FBSyxDQUFDZSxPQUFQLENBVnRDOztBQUFBO0FBVVNLLGNBQUFBLGVBVlQ7QUFZR25CLGNBQUFBLE9BQU8sQ0FBQ0MsS0FBUixDQUFjLDhDQUFkO0FBWkgsZ0RBY1VrQixlQWRWOztBQUFBO0FBQUE7QUFBQTtBQWdCRztBQUNBO0FBQ0E7QUFDQTtBQUNBbkIsY0FBQUEsT0FBTyxDQUFDQyxLQUFSO0FBcEJIO0FBQUEscUJBc0J1QkUsTUFBTSxDQUFDQyxJQUFQLENBQVlULFVBQVosQ0F0QnZCOztBQUFBO0FBc0JTVSxjQUFBQSxLQXRCVDtBQUFBO0FBQUEscUJBdUJnQ0EsS0FBSyxDQUFDZSxLQUFOLENBQVl4QixXQUFaLENBdkJoQzs7QUFBQTtBQXVCU3lCLGNBQUFBLGNBdkJUO0FBQUEsZ0RBd0JVQSxjQXhCVjs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUFELElBREY7QUE2QkQsR0E5QkQsTUE4Qk87QUFDTHJCLElBQUFBLE9BQU8sQ0FBQ0MsS0FBUixDQUFjLDZDQUFkO0FBQ0Q7QUFDRixDQWxDRDtBQW9DQSwrREFBZSxJQUFmIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vc3ByaXRzdGF0Ly4vc3JjL3NlcnZpY2Utd29ya2VyLnRzPzdmNTgiXSwic291cmNlc0NvbnRlbnQiOlsiZGVjbGFyZSBjb25zdCBzZWxmOiBTZXJ2aWNlV29ya2VyR2xvYmFsU2NvcGU7XG5cbi8vIEluY3JlbWVudGluZyBPRkZMSU5FX1ZFUlNJT04gd2lsbCBraWNrIG9mZiB0aGUgaW5zdGFsbCBldmVudCBhbmQgZm9yY2Vcbi8vICBwcmV2aW91c2x5IGNhY2hlZCByZXNvdXJjZXMgdG8gYmUgdXBkYXRlZCBmcm9tIHRoZSBuZXR3b3JrLlxuLy8gVGhpcyB2YXJpYWJsZSBpcyBpbnRlbnRpb25hbGx5IGRlY2xhcmVkIGFuZCB1bnVzZWQuXG5jb25zdCBPRkZMSU5FX1ZFUlNJT04gPSAxO1xuY29uc3QgQ0FDSEVfTkFNRSA9IFwib2ZmbGluZVwiO1xuY29uc3QgT0ZGTElORV9VUkwgPSBcIm9mZmxpbmUuaHRtbFwiO1xuXG5zZWxmLmFkZEV2ZW50TGlzdGVuZXIoXCJpbnN0YWxsXCIsIChldmVudCkgPT4ge1xuICBjb25zb2xlLmRlYnVnKFwiSW5zdGFsbCBzZXJ2aWNlIHdvcmtlclwiKTtcblxuICBldmVudC53YWl0VW50aWwoXG4gICAgKGFzeW5jICgpID0+IHtcbiAgICAgIGNvbnN0IGNhY2hlID0gYXdhaXQgY2FjaGVzLm9wZW4oQ0FDSEVfTkFNRSk7XG4gICAgICBhd2FpdCBjYWNoZS5hZGQobmV3IFJlcXVlc3QoT0ZGTElORV9VUkwsIHtjYWNoZTogXCJyZWxvYWRcIn0pKTtcblxuICAgICAgY29uc29sZS5kZWJ1ZyhcIlNlcnZpY2Ugd29ya2VyIGluc3RhbGxlZFwiKTtcbiAgICB9KSgpXG4gICk7XG4gIHZvaWQgc2VsZi5za2lwV2FpdGluZygpO1xufSk7XG5cbnNlbGYuYWRkRXZlbnRMaXN0ZW5lcihcImFjdGl2YXRlXCIsIChldmVudCkgPT4ge1xuICBjb25zb2xlLmRlYnVnKFwiQWN0aXZhdGUgc2VydmljZSB3b3JrZXJcIik7XG5cbiAgZXZlbnQud2FpdFVudGlsKFxuICAgIChhc3luYyAoKSA9PiB7XG4gICAgICAvLyBFbmFibGUgbmF2aWdhdGlvbiBwcmVsb2FkIGlmIGl0J3Mgc3VwcG9ydGVkLlxuICAgICAgLy8gU2VlIGh0dHBzOi8vZGV2ZWxvcGVycy5nb29nbGUuY29tL3dlYi91cGRhdGVzLzIwMTcvMDIvbmF2aWdhdGlvbi1wcmVsb2FkXG4gICAgICBpZiAoXCJuYXZpZ2F0aW9uUHJlbG9hZFwiIGluIHNlbGYucmVnaXN0cmF0aW9uKSB7XG4gICAgICAgIC8vIEB0cy1pZ25vcmUgdGhpcyBpcyBvbmx5IGNhbGxlZCBpZiB0aGUgYnJvd3NlciBzdXBwb3J0cyBpdFxuICAgICAgICBhd2FpdCBzZWxmLnJlZ2lzdHJhdGlvbi5uYXZpZ2F0aW9uUHJlbG9hZC5lbmFibGUoKTtcblxuICAgICAgICBjb25zb2xlLmRlYnVnKFwiU2VydmljZSB3b3JrZXIgZW5hYmxlZCBuYXZpZ2F0aW9uUHJlbG9hZFwiKTtcbiAgICAgIH1cbiAgICB9KSgpXG4gICk7XG5cbiAgdm9pZCBzZWxmLmNsaWVudHMuY2xhaW0oKTtcbn0pO1xuXG5zZWxmLmFkZEV2ZW50TGlzdGVuZXIoXCJmZXRjaFwiLCAoZXZlbnQpID0+IHtcbiAgaWYgKGV2ZW50LnJlcXVlc3QubW9kZSA9PT0gXCJuYXZpZ2F0ZVwiKSB7XG4gICAgZXZlbnQucmVzcG9uZFdpdGgoXG4gICAgICAoYXN5bmMgKCkgPT4ge1xuICAgICAgICB0cnkge1xuICAgICAgICAgIC8vIEB0cy1pZ25vcmVcbiAgICAgICAgICBjb25zdCBwcmVsb2FkUmVzcG9uc2UgPSBhd2FpdCBldmVudC5wcmVsb2FkUmVzcG9uc2U7XG4gICAgICAgICAgaWYgKHByZWxvYWRSZXNwb25zZSkge1xuICAgICAgICAgICAgY29uc29sZS5kZWJ1ZyhcIlJldHVybmluZyBwcmVsb2FkZWQgcmVzcG9uc2UgZm9yIGZldGNoIHJlcXVlc3RcIik7XG5cbiAgICAgICAgICAgIHJldHVybiBwcmVsb2FkUmVzcG9uc2U7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY29uc3QgbmV0d29ya1Jlc3BvbnNlID0gYXdhaXQgZmV0Y2goZXZlbnQucmVxdWVzdCk7XG5cbiAgICAgICAgICBjb25zb2xlLmRlYnVnKFwiUmV0dXJuaW5nIG5ldHdvcmsgcmVzcG9uc2UgZm9yIGZldGNoIHJlcXVlc3RcIik7XG5cbiAgICAgICAgICByZXR1cm4gbmV0d29ya1Jlc3BvbnNlO1xuICAgICAgICB9IGNhdGNoIChlcnJvcikge1xuICAgICAgICAgIC8vIGNhdGNoIGlzIG9ubHkgdHJpZ2dlcmVkIGlmIGFuIGV4Y2VwdGlvbiBpcyB0aHJvd24sIHdoaWNoIGlzIGxpa2VseVxuICAgICAgICAgIC8vIGR1ZSB0byBhIG5ldHdvcmsgZXJyb3IuXG4gICAgICAgICAgLy8gSWYgZmV0Y2goKSByZXR1cm5zIGEgdmFsaWQgSFRUUCByZXNwb25zZSB3aXRoIGEgcmVzcG9uc2UgY29kZSBpblxuICAgICAgICAgIC8vIHRoZSA0eHggb3IgNXh4IHJhbmdlLCB0aGUgY2F0Y2goKSB3aWxsIE5PVCBiZSBjYWxsZWQuXG4gICAgICAgICAgY29uc29sZS5kZWJ1ZyhgRmV0Y2ggZmFpbGVkOyByZXR1cm5pbmcgb2ZmbGluZSBwYWdlIGluc3RlYWQ6ICR7ZXJyb3J9YCk7XG5cbiAgICAgICAgICBjb25zdCBjYWNoZSA9IGF3YWl0IGNhY2hlcy5vcGVuKENBQ0hFX05BTUUpO1xuICAgICAgICAgIGNvbnN0IGNhY2hlZFJlc3BvbnNlID0gYXdhaXQgY2FjaGUubWF0Y2goT0ZGTElORV9VUkwpO1xuICAgICAgICAgIHJldHVybiBjYWNoZWRSZXNwb25zZTtcbiAgICAgICAgfVxuICAgICAgfSkoKVxuICAgICk7XG4gIH0gZWxzZSB7XG4gICAgY29uc29sZS5kZWJ1ZyhcIkZldGNoIHJlcXVlc3Qgbm90IGhhbmRsZWQgYnkgc2VydmljZSB3b3JrZXJcIik7XG4gIH1cbn0pO1xuXG5leHBvcnQgZGVmYXVsdCBudWxsO1xuIl0sIm5hbWVzIjpbIk9GRkxJTkVfVkVSU0lPTiIsIkNBQ0hFX05BTUUiLCJPRkZMSU5FX1VSTCIsInNlbGYiLCJhZGRFdmVudExpc3RlbmVyIiwiZXZlbnQiLCJjb25zb2xlIiwiZGVidWciLCJ3YWl0VW50aWwiLCJjYWNoZXMiLCJvcGVuIiwiY2FjaGUiLCJhZGQiLCJSZXF1ZXN0Iiwic2tpcFdhaXRpbmciLCJyZWdpc3RyYXRpb24iLCJuYXZpZ2F0aW9uUHJlbG9hZCIsImVuYWJsZSIsImNsaWVudHMiLCJjbGFpbSIsInJlcXVlc3QiLCJtb2RlIiwicmVzcG9uZFdpdGgiLCJwcmVsb2FkUmVzcG9uc2UiLCJmZXRjaCIsIm5ldHdvcmtSZXNwb25zZSIsIm1hdGNoIiwiY2FjaGVkUmVzcG9uc2UiXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./src/service-worker.ts\n");
+
+/***/ })
+
+},
+/******/ function(__webpack_require__) { // webpackRuntimeModules
+/******/ var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId); }
+/******/ __webpack_require__.O(0, ["framework-node_modules_babel_runtime_regenerator_index_js-node_modules_babel_runtime_helpers_-23c3ae"], function() { return __webpack_exec__("./src/service-worker.ts"); });
+/******/ var __webpack_exports__ = __webpack_require__.O();
+/******/ }
+]);
+
+

index.ts where the service worker gets registered:

+
import "./index.sass";
+import "intro.js/introjs.css";
+import "intro.js/themes/introjs-modern.css"
+
+import React from "react";
+import {createRoot} from "react-dom/client";
+import {BrowserRouter} from "react-router-dom";
+import {Provider} from "react-redux";
+
+import App from "./app/App";
+import {store} from "./app/store";
+
+
+window.addEventListener("load", async () => {
+  if ("serviceWorker" in navigator) {
+    console.debug("Register service worker");
+
+    await navigator.serviceWorker.register("/service-worker.js");
+  }
+});
+
+console.debug("Start application");
+
+const container = document.getElementById("root");
+const root = createRoot(container!);
+root.render(
+  <React.StrictMode>
+    <Provider store={store}>
+      <BrowserRouter>
+        <App/>
+      </BrowserRouter>
+    </Provider>
+  </React.StrictMode>
+);
+
+

package.json:

+
{
+  "name": "test",
+  "version": "0.1.0",
+  "homepage": ".",
+  "browser": "webpack.config.js",
+  "scripts": {
+    "start": "npm run trans:compile && webpack --mode=development --watch",
+    "build:dev": "npm run trans:compile && webpack --mode=development",
+    "build": "npm run trans:compile && webpack --mode=production",
+    "db:flush": "python ../manage.py flush --noinput",
+    "db:seed": "python ../manage.py loaddata",
+    "test": "cypress run",
+    "cy:open": "cypress open",
+    "trans:extract": "formatjs extract 'src/**/*.ts*' --ignore='**/*.d.ts' --out-file translation/locales/de.json",
+    "trans:manage": "babel-node -x .ts -- translation/manageTranslations.ts",
+    "trans": "npm run trans:extract && npm run trans:manage",
+    "trans:compile": "formatjs compile 'translation/locales/en.json' --ast --out-file 'src/locales/en.json'"
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version",
+      "last 1 opera version"
+    ]
+  },
+  "dependencies": {
+    "@fortawesome/fontawesome-svg-core": "^6.1.1",
+    "@fortawesome/free-brands-svg-icons": "^6.1.1",
+    "@fortawesome/free-solid-svg-icons": "^6.1.1",
+    "@fortawesome/react-fontawesome": "^0.1.18",
+    "@reduxjs/toolkit": "^1.8.1",
+    "bulma": "^0.9.3",
+    "bulma-switch": "^2.0.4",
+    "chart.js": "^3.7.1",
+    "chartjs-plugin-zoom": "^1.2.1",
+    "intro.js": "^5.1.0",
+    "intro.js-react": "^0.6.0",
+    "lodash.debounce": "^4.0.8",
+    "moment-timezone": "^0.5.34",
+    "nanoid": "^3.3.3",
+    "react": "^18.1.0",
+    "react-cookie": "^4.1.1",
+    "react-dom": "^18.1.0",
+    "react-intl": "^5.25.1",
+    "react-redux": "^8.0.1",
+    "react-router-dom": "^6.3.0",
+    "universal-cookie": "^4.0.4"
+  },
+  "devDependencies": {
+    "@babel/core": "^7.17.9",
+    "@babel/node": "^7.16.8",
+    "@babel/plugin-transform-runtime": "^7.17.0",
+    "@babel/preset-env": "^7.16.11",
+    "@babel/preset-react": "^7.16.7",
+    "@babel/preset-typescript": "^7.16.7",
+    "@babel/runtime": "^7.17.9",
+    "@formatjs/cli": "^4.8.4",
+    "@types/google.maps": "^3.48.7",
+    "@types/intro.js": "^3.0.2",
+    "@types/lodash.debounce": "^4.0.7",
+    "@types/node": "^17.0.30",
+    "@types/react": "^18.0.8",
+    "@types/react-dom": "^18.0.3",
+    "@types/react-router-dom": "^5.3.3",
+    "babel-loader": "^8.2.5",
+    "babel-plugin-formatjs": "^10.3.20",
+    "clean-webpack-plugin": "^4.0.0",
+    "compression-webpack-plugin": "^9.2.0",
+    "copy-webpack-plugin": "^10.2.4",
+    "css-loader": "^6.7.1",
+    "css-minimizer-webpack-plugin": "^3.4.1",
+    "cypress": "^9.6.0",
+    "cypress-real-events": "^1.7.0",
+    "file-loader": "^6.2.0",
+    "mini-css-extract-plugin": "^2.6.0",
+    "moment-locales-webpack-plugin": "^1.2.0",
+    "node-sass": "^7.0.1",
+    "prettier": "^2.6.2",
+    "sass-loader": "^12.6.0",
+    "style-loader": "^3.3.1",
+    "terser-webpack-plugin": "^5.3.1",
+    "typescript": "^4.6.4",
+    "webpack": "^5.72.0",
+    "webpack-cli": "^4.9.2",
+    "webpack-manifest-plugin": "^5.0.0"
+  },
+  "keywords": [],
+  "author": "eega",
+  "license": "MIT",
+  "description": ""
+}
+
+

babel.config.json:

+
{
+  "plugins": [
+    "@babel/plugin-transform-runtime",
+    [
+      "formatjs", {
+        "idInterpolationPattern": "[sha512:contenthash:base64:6]",
+        "ast": true
+      }
+    ]
+  ],
+  "presets": [
+    "@babel/preset-env",
+    "@babel/preset-react",
+    "@babel/preset-typescript"
+  ]
+}
+
+

tsconfig.json:

+
{
+  "compilerOptions": {
+    "target": "es5",
+    "module": "ESNext",
+    "lib": [
+      "dom",
+      "dom.iterable",
+      "esnext",
+      "es2017.intl",
+      "es2018.intl",
+      "webworker"
+    ],
+    "skipLibCheck": true,
+    "esModuleInterop": true,
+    "allowSyntheticDefaultImports": true,
+    "strict": true,
+    "forceConsistentCasingInFileNames": true,
+    "noFallthroughCasesInSwitch": true,
+    "moduleResolution": "node",
+    "resolveJsonModule": true,
+    "isolatedModules": true,
+    "noEmit": true,
+    "jsx": "react-jsx"
+  },
+  "include": [
+    "src/**/*",
+  ]
+}
+
+

webpack.config.json:

+
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
+const CompressionPlugin = require("compression-webpack-plugin");
+const CopyWebpackPlugin = require("copy-webpack-plugin");
+const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
+const MiniCssExtractPlugin = require("mini-css-extract-plugin");
+const MomentLocalesPlugin = require("moment-locales-webpack-plugin");
+const {resolve} = require("path");
+const TerserPlugin = require("terser-webpack-plugin");
+const webpack = require("webpack");
+const {WebpackManifestPlugin} = require("webpack-manifest-plugin");
+const zlib = require("zlib");
+
+
+module.exports = {
+  devtool: "eval-source-map",
+  entry: {
+    app: resolve(__dirname, "src/index.tsx"),
+    "service-worker": {
+      import: resolve(__dirname, "src/service-worker.ts"),
+      filename: "js/service-worker.js"
+    }
+  },
+  mode: process.env.NODE_ENV ? process.env.NODE_ENV : "production",
+  module: {
+    rules: [
+      {
+        test: /\.(ts|js)x?$/,
+
+        exclude: /node_modules\/(?!react-intl|intl-messageformat|@formatjs\/icu-messageformat-parser)/,
+        use: ["babel-loader"],
+      },
+      {
+        test: /.*/,
+        include: resolve(__dirname, "assets/img"),
+        options: {
+          context: resolve(__dirname, "assets/"),
+          name: "[path][name]-[contenthash].[ext]",
+        },
+        loader: "file-loader",
+      },
+      {
+        test: /\.css$/i,
+        use: ["style-loader", "css-loader"],
+      },
+      {
+        test: /\.sass$/,
+        use: [
+          MiniCssExtractPlugin.loader,
+          "css-loader",
+          {
+            loader: "sass-loader",
+            options: {
+              sourceMap: true,
+            },
+          },
+        ],
+      },
+    ],
+  },
+  output: {
+    path: resolve(__dirname, "public/"),
+    filename: "js/[name]-[contenthash].js",
+    chunkFilename: "js/[name]-[contenthash].chunk.js",
+  },
+  optimization: {
+    runtimeChunk: {
+      name: "runtime"
+    },
+    splitChunks: {
+      chunks: "all",
+      cacheGroups: {
+        // disable webpack's default cacheGroup
+        default: false,
+        // disable webpack's default vendor cacheGroup
+        vendors: false,
+        // Create a framework bundle that contains React libraries
+        // They hardly change so we bundle them together to improve
+        framework: {},
+        // Big modules that are over 160kb are moved to their own file to
+        // optimize browser parsing & execution
+        lib: {},
+        // All libraries that are used on all pages are moved into a common chunk
+        commons: {},
+        // When a module is used more than once we create a shared bundle to save user's bandwidth
+        shared: {},
+        // All CSS is bundled into one stylesheet
+        styles: {}
+      },
+      // Keep maximum initial requests to 25
+      maxInitialRequests: 25,
+      // A chunk should be at least 20kb before using splitChunks
+      minSize: 20000
+    },
+    minimizer: [
+      new CompressionPlugin({
+        filename: "[path][base].gz",
+        algorithm: "gzip",
+        test: /\.js$|\.css$|\.html$/,
+        threshold: 10240,
+        minRatio: 0.8,
+      }),
+      new CompressionPlugin({
+        filename: "[path][base].br",
+        algorithm: "brotliCompress",
+        test: /\.(js|css|html|png|svg)$/,
+        compressionOptions: {
+          params: {
+            [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
+          },
+        },
+        threshold: 10240,
+        minRatio: 0.8,
+      }),
+      new CssMinimizerPlugin(),
+      new TerserPlugin(),
+    ]
+  },
+  plugins: [
+    new webpack.NoEmitOnErrorsPlugin(),
+    new CleanWebpackPlugin(),
+    new WebpackManifestPlugin({
+      fileName: "webpack_manifest.json",
+      publicPath: ""
+    }),
+    new MiniCssExtractPlugin({
+      filename: "css/[name].css",
+      chunkFilename: "css/[id]-[contenthash].css",
+    }),
+    new CopyWebpackPlugin({
+      patterns: [
+        {
+          from: "assets/img/favicon.ico",
+          to: "img",
+        },
+      ],
+    }),
+    // These are files used in the progressive web app manifest only, so they wouldn't
+    //  be processed without this.
+    new CopyWebpackPlugin({
+      patterns: [
+        {
+          from: "assets/img/logo_small_*.png",
+          to: "img/[name]-[contenthash].png",
+          toType: "template"
+        },
+      ],
+    }),
+    new MomentLocalesPlugin({
+      localesToKeep: ["de", "en"],
+    })
+  ],
+  resolve: {
+    extensions: [".js", ".jsx", ".tsx", ".ts"],
+    modules: [
+      resolve(__dirname, "src"),
+      resolve(__dirname, "node_modules"),
+    ]
+  },
+};
+
+
","

The cause of my issue was Webpack optimization, namely the following 2 issues:

+
    +
  1. Extraction of the runtime was enabled for all chunks by setting the runtimeChunk config to name: "runtime". This caused the runtime for the service worker to be extracted into a separate chunk, but this chunk wasn't imported by the service worker
  2. +
  3. Splitting of chunks was enabled for the service worker also by setting the splitChunks config option chunks to "all", which means that the service worker file was also part of chunking, which led to an transpile error
  4. +
+

Changing webpack.config.js like this solved the issue:

+
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
+const CompressionPlugin = require("compression-webpack-plugin");
+const CopyWebpackPlugin = require("copy-webpack-plugin");
+const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
+const MiniCssExtractPlugin = require("mini-css-extract-plugin");
+const MomentLocalesPlugin = require("moment-locales-webpack-plugin");
+const {resolve} = require("path");
+const TerserPlugin = require("terser-webpack-plugin");
+const webpack = require("webpack");
+const {WebpackManifestPlugin} = require("webpack-manifest-plugin");
+const zlib = require("zlib");
+
+
+module.exports = {
+  devtool: "eval-source-map",
+  entry: {
+    app: resolve(__dirname, "src/index.tsx"),
+    "service-worker": {
+      import: resolve(__dirname, "src/service-worker.ts"),
+      filename: "js/service-worker.js"
+    }
+  },
+  mode: process.env.NODE_ENV ? process.env.NODE_ENV : "production",
+  module: {
+    rules: [
+      {
+        test: /\.(ts|js)x?$/,
+
+        exclude: /node_modules\/(?!react-intl|intl-messageformat|@formatjs\/icu-messageformat-parser)/,
+        use: ["babel-loader"],
+      },
+      {
+        test: /.*/,
+        include: resolve(__dirname, "assets/img"),
+        options: {
+          context: resolve(__dirname, "assets/"),
+          name: "[path][name]-[contenthash].[ext]",
+        },
+        loader: "file-loader",
+      },
+      {
+        test: /\.css$/i,
+        use: ["style-loader", "css-loader"],
+      },
+      {
+        test: /\.sass$/,
+        use: [
+          MiniCssExtractPlugin.loader,
+          "css-loader",
+          {
+            loader: "sass-loader",
+            options: {
+              sourceMap: true,
+            },
+          },
+        ],
+      },
+    ],
+  },
+  output: {
+    path: resolve(__dirname, "public/"),
+    filename: "js/[name]-[contenthash].js",
+    chunkFilename: "js/[name]-[contenthash].chunk.js",
+  },
+  optimization: {
+    runtimeChunk: {
+      name: (entrypoint) => {
+        if (entrypoint.name.startsWith("service-worker")) {
+          return null;
+        }
+
+        return `runtime-${entrypoint.name}`
+      }
+    },
+    splitChunks: {
+      chunks(chunk) {
+        return chunk.name !== "service-worker";
+      },
+      cacheGroups: {
+        // disable webpack's default cacheGroup
+        default: false,
+        // disable webpack's default vendor cacheGroup
+        vendors: false,
+        // Create a framework bundle that contains React libraries
+        // They hardly change so we bundle them together to improve
+        framework: {},
+        // Big modules that are over 160kb are moved to their own file to
+        // optimize browser parsing & execution
+        lib: {},
+        // All libraries that are used on all pages are moved into a common chunk
+        commons: {},
+        // When a module is used more than once we create a shared bundle to save user's bandwidth
+        shared: {},
+        // All CSS is bundled into one stylesheet
+        styles: {}
+      },
+      // Keep maximum initial requests to 25
+      maxInitialRequests: 25,
+      // A chunk should be at least 20kb before using splitChunks
+      minSize: 20000
+    },
+    minimizer: [
+      new CompressionPlugin({
+        filename: "[path][base].gz",
+        algorithm: "gzip",
+        test: /\.js$|\.css$|\.html$/,
+        threshold: 10240,
+        minRatio: 0.8,
+      }),
+      new CompressionPlugin({
+        filename: "[path][base].br",
+        algorithm: "brotliCompress",
+        test: /\.(js|css|html|png|svg)$/,
+        compressionOptions: {
+          params: {
+            [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
+          },
+        },
+        threshold: 10240,
+        minRatio: 0.8,
+      }),
+      new CssMinimizerPlugin(),
+      new TerserPlugin(),
+    ]
+  },
+  plugins: [
+    new webpack.NoEmitOnErrorsPlugin(),
+    new CleanWebpackPlugin(),
+    new WebpackManifestPlugin({
+      fileName: "webpack_manifest.json",
+      publicPath: ""
+    }),
+    new MiniCssExtractPlugin({
+      filename: "css/[name].css",
+      chunkFilename: "css/[id]-[contenthash].css",
+    }),
+    new CopyWebpackPlugin({
+      patterns: [
+        {
+          from: "assets/img/favicon.ico",
+          to: "img",
+        },
+      ],
+    }),
+    // These are files used in the progressive web app manifest only, so they wouldn't
+    //  be processed without this.
+    new CopyWebpackPlugin({
+      patterns: [
+        {
+          from: "assets/img/logo_small_*.png",
+          to: "img/[name]-[contenthash].png",
+          toType: "template"
+        },
+      ],
+    }),
+    new MomentLocalesPlugin({
+      localesToKeep: ["de", "en"],
+    })
+  ],
+  resolve: {
+    extensions: [".js", ".jsx", ".tsx", ".ts"],
+    modules: [
+      resolve(__dirname, "src"),
+      resolve(__dirname, "node_modules"),
+    ]
+  },
+};
+
+
",r +"function that reverses a string every time a vowel appears in it?

I'm trying to make a function that, for every occurrence of a vowel in a string, reverses said-string (and includes the vowel when it does this). The function is somewhat complex for my understanding so I'd like some help and a maybe a breakdown of it. However, I would only like to use the operators and statements that I'm currently learning (for/while and if). If possible, I would also like to avoid using list comprehension.

+

Here's what the inputs and outputs should look like:

+

an example input would be reverse_per_vowel('aerith') +which returns 'iraeth'

+

If we break the process of this function into steps, it should look like:

+

(a)erith → (a)erith (the first letter is a vowel, so it is reversed. However, because it is the first letter in the string, there are no visible changes.)

+

(ae)rith → (ea)rith (the second letter is also a vowel, so every letter in the string leading up to and including the vowel is reversed.)

+

(eari)th → (irae)th (the fourth letter is a vowel, so everything leading up to and including it is also reversed. Note how it accounts for the letters in the string that were reversed previously.)

+

as you can see, the amount of times the string is reversed is cumulative and I'm not quite sure how to code for this. However, I've attempted to write a component of the function.

+

What I'm trying

+
vowellist = 'aeiouAEIOU'
+sampleword = 'aerith'
+
+indexlist = []
+for i in range(len(sampleword)):
+    if sampleword[i] in vowel_list:
+        indexlist.append(i)
+indexlist
+
+

output: [0, 1, 3]

+

this excerpt does not reverse any parts of the string, however it returns indexes where the string should be reversed. What I planned on doing was plugging these indexes back into the sample word somehow and using [::-1] to reverse a portion of the string. However, I don't know how I would do this nor if it would be a good idea. Any help would be appreciated.

","

If there are many vowels, then the repeated reversals seem like they could be avoided, as a second reversal somewhat is an undo of the previous reversal.

+

And yes, you could use this algorithm:

+
    +
  • Build two strings. They start emtpy, and mark the second of them as the "active" one.

    +
  • +
  • Visit the input characters in reversed order: from last to first

    +
      +
    • As long as they are consonants add them to the currently active string
    • +
    • When it is a vowel, switch the active string to be the other one, and add the vowel there
    • +
    +
  • +
  • At the end of this process, reverse the second string and return the concatenation of the two strings:

    +
  • +
+
VOWELS = set("aeiouAEIOU")
+
+def reverse_per_vowel(s):
+    endings = ["", ""]
+    side = 1
+    for c in reversed(s):
+        if c in VOWELS:
+            side = 1 - side  # Toggle between 0 and 1
+        endings[side] += c
+    return endings[0] + endings[1][::-1]
+
+

As this algorithm is not reversing each time it meets a vowel, but only performs one reversal at the end, it runs with linear time complexity, contrary to what you would get if you implement the described process literally, which has a worst case time complexity of O(n²).

+

With this complexity analysis I assume that extending a string with a character is a constant time process. If there is doubt about this, then implement it with two lists of characters, calling append and perform a join at the end of the process to get the final string:

+
VOWELS = set("aeiouAEIOU")
+
+def reverse_per_vowel(s):
+    endings = [[], []]
+    side = 1
+    for c in reversed(s):
+        if c in VOWELS:
+            side = 1 - side  # Toggle between 0 and 1
+        endings[side].append(c)
+    
+    return "".join(endings[0] + endings[1][::-1])
+
",r +"Cant set min and max date of datetime picker for ionic

In my ion-datetime I have dates to select. These dates are the dates provided from a function that finds the next available dates for delivery.

+

Here we have the function that gets the dates then set our result:

+
let result = getValidDates()
+let temp = []
+result.forEach(res => {
+        temp.push(res.getDate())
+    }
+this.min = result[0].toLocaleDateString()
+this.max = result.slice(-1)[0].toLocaleDateString()
+this.pickupdates = result
+
+

Then we have our component with the dayValues property which is the result from the above function:

+
<ion-datetime
+  mode='md'
+  presentation="date"
+  [showDefaultButtons]="true"
+  [dayValues] = "pickupdates"
+  [min] = "min"
+  [max] = "max"
+>
+</ion-datetime>
+
+

This then gives us the proper selectable dates. But those very same dates are the same dates that can be selected in the next month. +Ive tried tried to limit this by adding the min and max properties, but this then breaks and bring up the error: +"Cannot destructure property 'month' of 'parseDate(...)' as it is undefined." +and +"TypeError: Cannot read properties of undefined (reading 'month')"

+

In this case min and max would be:

+
min = "26/04/2022"
+max = "02/05/2022"
+
+

but still brings up that error

",

the reason is min date max date should be yyyy/mm/dd or mm/dd/yyyy to be brief min="04/26/2022" and max="05/02/2022"

,r +"How to extract values of a raster stack into separate columns?

I have rasters of different vegetation measurements (i.e., canopy height, veg density). I want to stack the layers and use dplyr to extract values and assign to different columns. How can I do this? Sample code below. Sorry for not having a reproducible example.

+

Instead of this:

+
RSF_df.sf <- RSF_df.sf %>%
+  mutate(can_cover5m = raster::extract(can_cover5m, RSF_df.sf),
+         veg_density1mheight_5m = raster::extract(veg_density1mheight_5m, RSF_df.sf),
+         veg_density2mheight_5m = raster::extract(veg_density2mheight_5m, RSF_df.sf),
+         veg_density3mheight_5m = raster::extract(veg_density3mheight_5m, RSF_df.sf),
+         veg_density4mheight_5m = raster::extract(veg_density4mheight_5m, RSF_df.sf),
+         veg_density5mheight_5m = raster::extract(veg_density5mheight_5m, RSF_df.sf),
+         veg_density_over5mheight_5m = raster::extract(veg_density_over5mheight_5m, RSF_df.sf))
+summary(RSF_df.sf)
+
+

I want this, but with each veg. measurement in a separate column:

+
all_land_data<-addLayer(can_cover5m,veg_density1mheight_5m,veg_density2mheight_5m,veg_density3mheight_5m,
+                        veg_density4mheight_5m,veg_density5mheight_5m,veg_density_over5mheight_5m)
+
+del <- RSF_df.sf %>%
+  mutate(all_land_data = raster::extract(raster stack, RSF_df.sf)) #I need values for each veg. measurment in seperate columns
+summary(del)
+
","

Unless I misunderstood, I think you are making this more complicated than necessary. If you use the terra package, and read all rasters in together, a SpatRaster stack is created. Then, using terra::extract to extract values for each feature in a terra::vect object will produce a data.frame with columns for each raster layer in the stack.

+

i.e.

+
library(terra)
+veg_stk <- c(rast(veg_density1mheight_5m), rast(veg_density2mheight_5m), rast(veg_density3mheight_5m), rast(can_cover5m)
+RSF_vect <- vect(RSF_df.sf)
+
+del <- terra::extract(veg_stk, RSF_vect, fun = mean)  # returns a DF
+
",r +"Changing top tab bar background color when active

I have one top tab bar with two tabs on the screen which is created with React Navigation. I want to change the grey background colour to pink when tab is active, I have tried to find some solution, but can't find any. Is that even possible to do?

+

Any help is appreciated!

+

Navigator.js:

+
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
+import { Tab1 } from "../pages/Tab1";
+import { Tab2 } from "../pages/Tab2";
+
+const TopTab = createMaterialTopTabNavigator();
+
+export function TopTabNavigator() {
+  return (
+    <TopTab.Navigator
+      screenOptions={{
+        tabBarLabelStyle: {
+          fontSize: 12,
+          textTransform: "none",
+        },
+        tabBarItemStyle: {
+          fontSize: 12,
+          textTransform: "none",
+          height: 30,
+          minHeight: 10,
+          backgroundColor: "#706c6c",
+          borderRadius: 100,
+          margin: 10,
+          marginVertical: 10,
+          padding: 3,
+        },
+        tabBarStyle: {
+          backgroundColor: "transparent",
+        },
+        tabBarIndicator: () => null,
+      }}
+    >
+      <TopTab.Screen name="Tab1" component={Tab1} />
+      <TopTab.Screen name="Tab2" component={Tab2} />
+    </TopTab.Navigator>
+  );
+}
+
+

App.js:

+
import { NavigationContainer } from "@react-navigation/native";
+import { TopTabNavigator } from "./src/routes/Navigator";
+
+export default function App() {
+  return (
+    <NavigationContainer>
+      <TopTabNavigator />
+    </NavigationContainer>
+  );
+}
+
+

This is how it looks like right now, only the text colour will change to some whiter colour when it is active. +

","

Here you go, i created a snack so you can test it : snack

+

you can basically play on the variable isFocused to change whatever you want

",r +"How to deploy React TypeScript app to Vercel with Vite

I'm trying to deploy a React TypeScript project to Vercel, building with Vite. However, Vercel doesn't install devDependencies during build time like Heroku does, so it doesn't know what "vite build" is (same for tsc).

+

I've followed the Vite guide for Vercel deployment.

+

It feels very odd to include Vite and TypeScript as a normal dependency, so that it'll be included in the bundle. I know it's possible to configure Vite to exclude certain dependencies on your bundle, but is this really the way to do it?

","

Have a read of these two tweets:

+

https://twitter.com/dan_abramov/status/1098234219506085889 +https://twitter.com/dan_abramov/status/1098234004954857472

+

He's talking about CRA, but the same principle applies here to vite.

+

Because vite build produces static HTML/CSS/JS and not a node app, the difference between devDependencies and dependencies is moot.

+

Strictly speaking, your package.json lists the required dependencies for the code that builds your static bundle to build your app.

+

It's similar to the way that a factory requires paint, electricity, metal, etc to produce a car, but once the car is finished and has left the factory it's self-contained and has all the paint and metal it needs. Your codebase is (strictly speaking) a factory, and your package.json lists the requirements for the factory, not the car itself.

+

TLDR; perfectly fine to add it to dependencies, it won't end up in the final bundle.

+
+

EDIT: if you're wondering why the distinction between dependencies and devDependencies exists, it's because it's designed to separate what packages are required during ongoing production operation of a node app (eg, for an app that's serving HTTP requests, a core networking module) vs packages that are only needed locally (eg, a code formatter).

+

When the "production" app is an ephemeral script that runs for a few seconds inside a build pipeline to generate some static HTML/CSS/JS, the difference between dependencies and devDependencies doesn't mean much. It's a common misconception that it has any kind of effect on what ends up inside the static bundle.

",r +"Creating global variables for UDP client program

I am creating a UDP tunnel client program to receive random packets from client OS system and send the data packets to a UDP server using a reader thread function. Similarly I am reading packets from the UDP server and sending it to the client's tunnel IP address. The reader and writer threads must run simultaneously. I get the following error when I execute the program.

+
use of moved value: `socket`
+value used here after moverustcE0382
+basic.rs(68, 38): value moved into closure here
+basic.rs(74, 21): variable moved due to use in closure
+basic.rs(101, 21): use occurs due to use in closure
+basic.rs(58, 9): move occurs because `socket` has type `UdpSocket`, which does not implement the `Copy` trait
+
+

How do I declare the socket variable as global variable to remove the error occurring at writer thread when I use the keyword move?

+
let socket = UdpSocket::bind("8.0.0.1:8000") //create client socket object with ip and port
+                       .expect("Could not bind client socket");
+
+socket.connect("8.0.0.10:8888") //SERVER IP /PORT
+                      .expect("Could not connect to server");
+
+thread::sleep(time::Duration::from_secs(5)); // PROVIDING TIME TO ESTABLISH SOCKET CONNECTION TO SERVER
+
+
+
+let reader_session = session.clone();
+
+let reader = std::thread::spawn( move || {
+    while RUNNING.load(Ordering::Relaxed) {
+        match reader_session.receive_blocking() {
+            Ok(packet) => {                     //receiving random packets from OS
+                let bytes = packet.bytes();
+                let leng = bytes.len();
+                socket.send(&bytes[0..leng]);     //SENDING RANDOM PACKETS TO SERVER
+
+                println!
+                (
+                    "Version & IHL: {}  Service Type: {}  Packet Length: {} {}  Identification: {} {}  Flags&Fragment: {} {}  
+                    TTL: {}  Protocol: {}  Checksum: {} {}  SourceIP: {}.{}.{}.{}  DestIP: {}.{}.{}.{}",
+                    &bytes[0],&bytes[1],&bytes[2],&bytes[3],&bytes[4],&bytes[5],&bytes[6],&bytes[7],
+                    &bytes[8],&bytes[9],&bytes[10],&bytes[11],
+                    &bytes[12],&bytes[13],&bytes[14],&bytes[15],&bytes[16],&bytes[17],&bytes[18],&bytes[19]
+                );
+                println!();
+                
+            }
+            
+            Err(_) => println!("Got error while reading packet"),
+        }
+    }
+});
+
+
+ 
+let writer_session = session.clone();
+let writer_socket = socket.try_clone()?;
+let writer = std::thread::spawn(move || {
+    info!("Starting writer");
+
+while RUNNING.load(Ordering::Relaxed) {
+        let mut buffer = [0u8; 1500]; 
+                writer_socket.recv_from(&mut buffer) //get message from server
+                     .expect("Could not read into buffer");
+        let mut leng1 = buffer.len();
+
+
+                println!("From server: {}", str::from_utf8(&buffer) //print message from server
+                     .expect("Could not write buffer as string"));
+                     socket.send_to(&buffer[0..leng1],"6.0.0.1"); //send message from server to tunnel ip
+    }
+});
+
","

You should be able to clone the UdpSocket using the try_clone() method which creates a new variable referencing the same underlying socket.

+

e.g.

+
...
+let reader_session = session.clone();
+let reader_socket = socket.try_clone().expect("Couldn't clone the socket");
+
+let reader = std::thread::spawn( move || {
+...
+       reader_socket.send(&bytes[0..leng]);
+
+

https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.try_clone

",r +"How to reuse assertions for scenarios in single feature file using Karate?

I want to assert responseTime of all scenarios. But i do not want to repeat the assertion code in every scenario. Below is my feature file:

+
Feature: Reqres api test cases
+
+  Background: base url
+    Given url base_url
+
+  Scenario: list single user get request
+    Given path single_user_path
+    When method get
+    Then status 200
+    And assert responseTime < 4000
+
+Scenario: create user using post and inline json payload
+    * def path = '/users'
+    Given path path
+    And request {"name": "morpheus","job": "leader"}
+    When method post
+    Then status 201
+    And assert responseTime < 4000
+
+

In the above code block, I want to avoid responseTime assertion duplication. How to achieve this in karate?. Please help.

","

No this is not supported and not planned either. It is unlikely every API call will have the exact same SLA. Also this is what the Gatling integration is for: https://stackoverflow.com/a/55146463/143475

+

EDIT as an example of how you can do "reuse" of response assertions:

+
Feature:
+
+Background:
+* def validateResponse =
+"""
+function() {
+  var contentType = karate.get("responseHeaders['Content-Type'][0]");
+  if (contentType !== 'application/json') {
+    karate.fail('content type is not json');
+  }
+  var responseType = karate.get('responseType');
+  if (responseType !== 'json') {
+    karate.fail('response type is not json');
+  }
+}
+"""
+
+Scenario:
+* url 'https://httpbin.org/post'
+* request { foo: 'bar' }
+* method post
+* validateResponse()
+
+

Please note that I absolutely don't recommend the above approach because of reasons best explained here: https://stackoverflow.com/a/54126724/143475

",r +"Sentry SDK with Asp.Net 4.6.1 Not working

I have an Asp.Net app, using .net 4.6.1 version. When I installed Sentry nuget and used Sentry SDK, nothing working, no events are being sent to Sentry. Below is global.asax configs where I tried this Sentry.

+
<%@ Application Language="C#" %>
+<%@ Import Namespace="Sentry" %>
+<%@ Import Namespace="Sentry.AspNet" %>
+<%@ Import Namespace="Sentry.Extensibility" %>
+<script runat="server">
+    private IDisposable _sentry;
+
+    protected void Application_Start()
+    {
+       _sentry = SentrySdk.Init(o =>
+        {
+            o.Dsn = "dsn url";
+            
+        });
+
+        // Initialize Sentry to capture AppDomain unhandled exceptions and more.
+        
+    }
+    // Global error catcher
+    protected void Application_Error()
+    {
+        var exception = Server.GetLastError();
+
+        SentrySdk.CaptureException(exception);
+    }
+
+
+    protected void Application_End()
+    {
+        if (_sentry != null)
+            _sentry.Dispose();
+    }
+</script>
+
+

Can anyone help me? Thanks

","

Refer to the sample in the documentation here. Specifically, you need to change your code as follows:

+
    +
  • Add o.AddAspNet(); to the body of your SentrySdk.Init call
  • +
  • Use Server.CaptureLastError() in your Application_Error method
  • +
+

If you want to enable Sentry's performance monitoring features, you also need to:

+
    +
  • Set a TracesSampleRate in your options

    +
  • +
  • Add the following code:

    +
    protected void Application_BeginRequest()
    +{
    +    Context.StartSentryTransaction();
    +}
    +
    +protected void Application_EndRequest()
    +{
    +    Context.FinishSentryTransaction();
    +}
    +
    +
  • +
",r +"flatten a nested array of objects using RxJS

our data structure is a nested array with objects

+
interface dtModel {
+  id: number;
+  permission: number;
+  childs: dtModel[];
+}
+
+const data: dtModel[] = [
+  {
+    id: 1,
+    permission: 2,
+    childs: [
+      {
+        id: 2,
+        permission: 1,
+        childs: [
+          {
+            id: 3,
+            permission: 3,
+            childs: [],
+          },
+        ],
+      },
+    ],
+  },
+  {
+    id: 4,
+    permission: 1,
+    childs: [
+      {
+        id: 5,
+        permission: 2,
+        childs: [
+          {
+            id: 6,
+            permission: 3,
+            childs: [
+              {
+                id: 7,
+                permission: 1,
+                childs: [],
+              },
+            ],
+          },
+        ],
+      },
+    ],
+  },
+];
+
+

I tried with help of RxJs to create a flattened array like this which is I'm not succeeded yet

+
[
+  {id:1,permission:2},
+  {id:2,permission:1},
+  {id:3,permission:3},
+  {id:4,permission:1},
+  {id:5,permission:2},
+  {id:6,permission:3},
+  {id:7,permission:1}
+]
+
+

I tried to do that with help of 'reduce' but because my childs' property does not always have the same length I couldn't do that with this approach.

+
of(data)
+  .pipe(
+    map((items: dtModel[]) => {
+      return items.reduce((res, curr) => {
+        res.push({ id: curr.id, permission: curr.permission });
+        return res;
+      }, []);
+    })
+  )
+  .subscribe(console.log);
+
+

StackBlitz

","

need to make recursion

+

+
+
const source = [
+  {
+    id: 1,
+    permission: 2,
+    childs: [
+      {
+        id: 2,
+        permission: 1,
+        childs: [
+          {
+            id: 3,
+            permission: 3,
+            childs: [],
+          },
+        ],
+      },
+    ],
+  },
+  {
+    id: 4,
+    permission: 1,
+    childs: [
+      {
+        id: 5,
+        permission: 2,
+        childs: [
+          {
+            id: 6,
+            permission: 3,
+            childs: [
+              {
+                id: 7,
+                permission: 1,
+                childs: [],
+              },
+            ],
+          },
+        ],
+      },
+    ],
+  },
+];
+
+const result  = [];
+
+const getAllItemsPerChildren = (item) => {
+  result.push({ id: item.id, permission: item.permission });
+  if (item.childs) {
+    return item.childs.map((i) => getAllItemsPerChildren(i));
+  }
+};
+
+source.forEach((i) => getAllItemsPerChildren(i));
+
+console.log(result)
+
+
+

+

RXJS SOLUTION

+

demo: https://stackblitz.com/edit/typescript-dlva1z?file=index.ts

+

+const source$ = of({
+  data: [],
+  last: false,
+  check: source,
+}).pipe(
+  expand((data) =>
+    data.last
+      ? EMPTY
+      : of(data.check).pipe(
+          map((currentItem) => {
+            const childs = (currentItem as any).flatMap((i) => i?.childs || []);
+            return {
+              data: currentItem.map((i) => ({
+                id: i.id,
+                permissions: i.permission,
+              })),
+              last: !childs?.length,
+              check: childs,
+            };
+          })
+        )
+  ),
+  reduce((acc, items) => [...acc, ...(items as any).data], [])
+);
+source$.subscribe((data) => console.log('result ', data));
+
+

Explanation:

+
    +
  • The main idea to use expand operator - it allow us to create recursion.
  • +
  • To stop recursion need to return EMPTY
  • +
  • of({data: [],last: false, check: source}) - it is our store
  • +
  • data is assigned to keep parsed item - that will be used in reduce operator - to concat the whole data
  • +
  • one return from expand equal to one emit
  • +
  • last allows to control recusrion, we are checking if all items is parsed
  • +
  • check - element to parse, intial value set to your entire data
  • +
",r +"How to skip Row in the following App Script in Google Sheet?

I am Copy and Pasting the data one sheet another sheet with cell value following script working fine.

+

I need to Skip the row 1 & 2 will copying in Maint.Schedule sheet

+
function moveRows() {
+  var ss=SpreadsheetApp.getActive();
+  var sheet=ss.getSheetByName('Maint. Schedule');
+  var vA=sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getValues();
+  var csh=ss.getSheetByName('History');
+  var d=0;//deleted row counter
+  var data=[];
+  for(var i=0;i<vA.length;i++) {
+    if (vA[i][12]=='Completed') {
+      data.push(vA[i]);
+      sheet.deleteRow(i+1-d++);//increment deleted row counter as you delete rows
+    }
+  }
+  csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
+}
+
+

Thanks in Advance

+

Johnn

","

Change for(var i=0;i<vA.length;i++) by

+
for(var i=2;i<vA.length;i++)
+
",r +"WooCommerce Subscriptions - Automatically complete renewal orders and Subscription status

I am working on a site which uses WooCommerce Subscriptions and WooCommerce Memberships. It sells subscriptions which renew annually.

+

The only payment gateway being used is Cheque (renamed to Pay via Invoice), so all renewals are manual renewals. An invoice is sent to the customer (outside of WooCommerce) and the store owners mark the order as Completed in admin when payment has been made.

+

The Subscription status is tied to the latest order status:

+
    +
  • if the order is completed, the sub is Active.

    +
  • +
  • if the order is pending, processing, on hold etc, the sub is On Hold.

    +
  • +
+

As invoices are being sent and processed via an external accounting system, the client wants to have renewal orders automatically complete so that there is no break in membership access for users.

+

I've looked at similar questions such as here and I'm running into similar issues.

+

Change subscription status to active based on order id WooCommerce

+

I've tested the hook woocommerce_new_order and can see it's firing for all orders, including renewals.

+

Using wcs_get_subscriptions_for_order(), it's possible to pass 'renewal' as an order_type to test if the given order is a renewal or a new customer.

+

I have a very small bit of code to check the new order, update it if applicable, and update the subscription status afterwards. However, it seems that my first if block is being skipped over - it always runs to the code in the else block.

+

Additionally, if I move the lines to update the order and sub status to the else block (so it does update all orders), the order status updates but the sub stays as On Hold.

+

I'm guessing there must be some trigger that is usually called if updating the order from admin or via payment that isn't firing, but I can't see from the docs what it would be.

+

Can anyone advise where I'm going wrong here, please?

+
<?php
+
+/**
+ * Autocomplete Renewal Orders
+ */
+
+function ctz_autocomplete_renewal_order($order_id) {
+  
+  /**
+   * Check if the order is associated with a subscription 
+   * 
+   * WC Subscriptions gives us a function to obtain the related orders for a subscription in an array. The second parameter allows us to retrieve only renewal orders.
+   * 
+   * We can use this function to check if the given order ID is for a new customer order or an existing customer's renewal. 
+   * 
+   * If this array returns blank, it's a first order, and should be skipped over.
+   */
+  
+  // Get related Subscriptions 
+  
+  $subscriptions = wcs_get_subscriptions_for_order($order_id, array('order_type' => 'renewal'));
+  
+  if(is_array($subscriptions) && !empty($subscriptions) ) :                                 
+    
+    // This is a renewal order - change the status 
+  
+    $order = wc_get_order($order_id);
+    
+    $order->update_status( 'completed');
+    
+    $order->save();
+    
+    // Check and update the subscription status
+    
+    activate_subscriptions_for_order($order);
+    
+    // Log the change
+    
+    $message = $order_id . " Renewal automatically completed.";
+  
+    ctz_custom_logs('autorenewals', $message);
+  
+  else :
+    
+  // This is a new order - leave unchanged 
+  
+    $message = $order_id . " Initial order - status unchanged.";
+  
+    ctz_custom_logs('autorenewals', $message);
+  
+  endif;
+ 
+}
+
+add_action('woocommerce_new_order', 'ctz_autocomplete_renewal_order', 11, 1);
+
+?>
+
+
+

FYI the logging function I'm using is just for debugging and records the given message to a file.

+

Thanks in advance.

","
add_filter('wcs_renewal_order_created', 'wcs_after_create_renewal_order', 10, 2);
+
+function wcs_after_create_renewal_order($renewal_order, $subscription) {
+
+    // Set the current renewal order as completed.
+    $renewal_order->update_status('completed');
+    $renewal_order->add_order_note( __( 'Renewal automatically processed' ) );
+
+    // Set the corresponding subscription as active.
+    $subscription->update_status('active');
+    return $renewal_order;
+}
+
+

The hook wcs_renewal_order_created is fired only after a renewal order is created. Simply add the code snippet above into your active theme functions.php file.

",r +"How do I make my scores work in a game of scissors, paper stone?

I am new to javascript and html. I am trying to make a scissors, paper stone game that the player plays against the computer. However I am not able to get the score to play or get the score to display in html. I have tried adding a rendering function too but doesn't work. What is wrong with my scoreWindow code? Why does it show as error and null? +Please help.

+

+
+
let choises = ['rock', 'paper', 'scissors'];
+
+choises.rock = document.querySelector('.rock');
+choises.paper = document.querySelector('.paper');
+choises.scissors = document.querySelector('.scissors');
+
+/*let userScore = document.querySelector('.scores .scorePlayer');
+let computerScore = document.querySelector('.scores .scoreComp');*/
+let scoreWindow = document.querySelector('.scores');
+let playerSelection;
+let computerSelection;
+
+let computerScore = 0;
+let userScore = 0;
+
+scoreWindow.innerHTML = userScore + ' : ' + computerScore;
+
+function computerPlay() {
+  let computerAction = Math.floor(Math.random() * choises.length);
+  computerSelection = choises[computerAction];
+  return computerSelection;
+}
+
+
+function playRound(playerSelection, computerSelection) {
+  if (playerSelection === computerSelection) {
+    userScore = userScore + 1;
+    computerScore = computerScore + 1;
+  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
+    (playerSelection === choises.rock && computerSelection === choises.rock) ||
+    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
+    userScore = userScore++;
+  } else {
+    computerScore = computerScore++;
+  }
+
+  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
+  return (computerScore, userScore);
+}
+
+function doChoises() {
+  choises.rock.addEventListener('click', () => {
+    playerSelection = choises[0];
+    console.log(computerPlay());
+    console.log(playerSelection);
+    console.log(playRound(playerSelection, computerSelection));
+  });
+  choises.paper.addEventListener('click', () => {
+    playerSelection = choises[1];
+    console.log(computerPlay());
+    playRound();
+  });
+  choises.scissors.addEventListener('click', () => {
+    playerSelection = choises[2];
+    console.log(computerPlay());
+    playRound();
+  });
+}
+
+function renderScore(computerScore, userScore) {
+  scoreWindow.innerText = `${computerScore} : ${userScore}`;
+}
+renderScore();
+doChoises();
+
<div class=""battlefield"">
+  <div class=""battlefield__back"">
+    <div class=""scores"">
+      <span>:</span>
+    </div>
+
+    <div class=""battlefield__weapon"">
+      <button class=""rock"">
+                <img src=""./rock.png""/>
+            </button>
+      <button class=""paper"">
+                <img src=""./paper.png""/>
+            </button>
+      <button class=""scissors"">
+                <img src=""./scissors.png""/>
+            </button>
+    </div>
+  </div>
+</div>
+
+
+

","

You need to make the following 3 changes to make the score work correctly. I just tried it and the rest of your game code works fine once you make the changes. It is not a script loading problem as some answers suggest.

+

(1) Remove the parameters from function playRound because you want the function to use the global variables. The problem with this might not be obvious. Yet, these parameters are overriding the global values with the same name. And they are always both null and so the logic for determining the score doesn't work correctly.

+
    // function playRound(playerSelection, computerSelection) {
+    function playRound() {
+
+

(2 & 3) Increment the user and computer scores correctly.

+
    //userScore = userScore++;
+    userScore++;
+
+
+    //computerScore = computerScore++;
+    computerScore++;
+
+

+
+
let choises = ['rock', 'paper', 'scissors'];
+
+choises.rock = document.querySelector('.rock');
+choises.paper = document.querySelector('.paper');
+choises.scissors = document.querySelector('.scissors');
+
+/*let userScore = document.querySelector('.scores .scorePlayer');
+let computerScore = document.querySelector('.scores .scoreComp');*/
+let scoreWindow = document.querySelector('.scores');
+let playerSelection;
+let computerSelection;
+
+let computerScore = 0;
+let userScore = 0;
+
+scoreWindow.innerHTML = userScore + ' : ' + computerScore;
+
+function computerPlay() {
+  let computerAction = Math.floor(Math.random() * choises.length);
+  computerSelection = choises[computerAction];
+  return computerSelection;
+}
+
+
+function playRound() {
+  if (playerSelection === computerSelection) {
+    userScore++;
+    computerScore++;
+  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
+    (playerSelection === choises.rock && computerSelection === choises.rock) ||
+    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
+    userScore++;
+  } else {
+    computerScore++;
+  }
+
+  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
+  return (computerScore, userScore);
+}
+
+function doChoises() {
+  choises.rock.addEventListener('click', () => {
+    playerSelection = choises[0];
+    console.log(computerPlay());
+    console.log(playerSelection);
+    console.log(playRound(playerSelection, computerSelection));
+  });
+  choises.paper.addEventListener('click', () => {
+    playerSelection = choises[1];
+    console.log(computerPlay());
+    playRound();
+  });
+  choises.scissors.addEventListener('click', () => {
+    playerSelection = choises[2];
+    console.log(computerPlay());
+    playRound();
+  });
+}
+
+function renderScore(computerScore, userScore) {
+  scoreWindow.innerText = `${computerScore} : ${userScore}`;
+}
+renderScore();
+doChoises();
+
<div class=""battlefield"">
+  <div class=""battlefield__back"">
+    <div class=""scores"">
+      <span>:</span>
+    </div>
+
+    <div class=""battlefield__weapon"">
+      <button class=""rock"">
+                <img alt=""rock"" src=""./rock.png""/>
+            </button>
+      <button class=""paper"">
+                <img alt=""paper"" src=""./paper.png""/>
+            </button>
+      <button class=""scissors"">
+                <img alt=""scissors"" src=""./scissors.png""/>
+            </button>
+    </div>
+  </div>
+</div>
+
+
+

",r +"Flutter - spinning wheel

Im trying to build this kind of spinning wheel. is there any plugin or widget that can help to achieve this?

+

click here for image

","

ListWheelScrollView class

+

List Wheel scroll view class will solve your problem

",r +"What does it mean to have Azure service tagged with (Preview) ? is it okay to start using it for production releases?

I was reading and found a very nice service in Azure called "Azure Container Apps", but i found it in (Preview). +What does it mean, like i have some doubts:

+
    +
  • Can i consider this for a production releases ?
  • +
  • Does it affect the SLA ?
  • +
  • How long time is usually takes to stay in Preview ?
  • +
","
+

Azure may include preview, beta, or other pre-release features, services, software, or regions offered by Microsoft ("Previews"). Previews are licensed to you as part of your agreement governing use of Azure.

+

Pursuant to the terms of your Azure subscription, PREVIEWS ARE PROVIDED "AS-IS," "WITH ALL FAULTS," AND "AS AVAILABLE," AND ARE EXCLUDED FROM THE SERVICE LEVEL AGREEMENTS AND LIMITED WARRANTY. Previews may not be covered by customer support. Previews may be subject to reduced or different security, compliance and privacy commitments, as further explained in the Microsoft Privacy Statement, Microsoft Azure Trust Center, the Product Terms, the DPA, and any additional notices provided with the Preview. The following terms in the DPA do not apply to Previews: Processing of Personal Data; GDPR, Data Security, and HIPAA Business Associate. Customers should not use Previews to process Personal Data or other data that is subject to heightened legal or regulatory requirements.

+

Certain named Previews are subject to additional terms set forth below, if any. These Previews are made available to you pursuant to these additional terms, which supplement your agreement governing use of Azure. We may change or discontinue Previews at any time without notice. We also may choose not to release a Preview into "General Availability".

+
+

Source (and more information): Supplemental Terms of Use for Microsoft Azure Previews.

+

In short, to me the answers to your questions would be:

+
    +
  1. Yes, you can... however. It might mean you need to take into account that stuff might break or change and prepare for that.
  2. +
  3. It does (read above)
  4. +
  5. That completely depends on the service
  6. +
+

If you want to stay up to date with services, Previews, General Availability and more, see Azure updates.

+

Some Preview services are more Preview than others. There have been Preview services in the past, where you could be pretty sure it would most probably propagate into it being a full blown Azure service in the future. And then there are services that are in early Preview that will probably have some big changes before moving to GA, if they are moving there at all.

+

As far as Container Apps goes: I think Microsoft hit a sweet spot between Kubernetes and App Services with Container Apps. I think chances of it not moving to general availability are close to zero.

+

Also, Microsoft Build is just around the corner (May 24th to 26th 2022). These are normally the times quite a few new Preview services are announced, or existing ones move to GA.

+

EDIT:
+For a product roadmap on Azure Container Apps, please see its GitHub repo.

",r +"why is the form not validated? validator flutter form validation
import 'package:flutter/material.dart';
+import 'package:sumanthk07/utilities/routes.dart';
+
+class LoginPage extends StatefulWidget {
+const LoginPage({Key? key}) : super(key: key);
+
+@override
+State<LoginPage> createState() => _LoginPageState();
+}
+
+class _LoginPageState extends State<LoginPage> {
+final _formkey = GlobalKey<FormState>();
+
+// ignore: avoid_types_as_parameter_names, non_constant_identifier_names
+moveToHome(BuildContext) async{
+Navigator.pushNamed(context, MyRoutes.homeRoute);
+}
+
+ @override
+Widget build(BuildContext context) {
+  return Material(
+    color: Colors.white,
+    child: SingleChildScrollView(
+    child: Form(
+       key: _formkey,
+      child: Column(
+        children: [
+          Image.asset("assets/images/login.png", fit: BoxFit.cover),
+          const SizedBox(
+            height: 20.0,
+          ),
+          const Text(
+            'Welcome',
+            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
+          ),
+          const SizedBox(
+            height: 20.0,
+          ),
+          Padding(
+            padding: const EdgeInsets.symmetric(
+                vertical: 16.0, horizontal: 32.0),
+            child: Column(
+              children: [
+                TextFormField(
+                  decoration: const InputDecoration(
+                      hintText: "Enter User name", labelText: "Username "),
+                      initialValue: "",
+                  validator: (String? value) {
+                    if (value !=null && value.isEmpty ) {
+                      return "User name cannot be empty";
+                    }
+                    return null;
+                  },
+                  onChanged: (value) {
+                    setState(() {});
+                  },
+                ),
+                TextFormField(
+                  obscureText: true,
+                  decoration: const InputDecoration(
+                      hintText: "Enter password", labelText: "Password "),
+                      initialValue: "",
+                  validator: (String? value) {
+                    if (value !=null && value.isEmpty ) {
+                      return "Password name cannot be empty";
+                    }
+                    return null;
+                  },
+                ),
+                const SizedBox(
+                  height: 20.0,
+                ),
+
+                InkWell(
+                  onTap: () => moveToHome(context),
+                  child: AnimatedContainer(
+                    duration: const Duration(seconds: 1),
+                    height: 40,
+                    width: 80,
+                    alignment: Alignment.center,
+                    child: const Text("Login",
+                        style: TextStyle(
+                          color: Colors.white,
+                          fontWeight: FontWeight.bold,
+                          fontSize: 18,
+                        )),
+                    decoration: BoxDecoration(
+                        color: Colors.red,
+                        // ignore: unnecessary_const
+                        borderRadius: BorderRadius.circular(20)),
+                  ),
+                )
+
+                // ElevatedButton(
+                //   child: const Text("Login"),
+                //   style: TextButton.styleFrom(),
+                //   onPressed: () {
+                //     // ignore: unused_local_variable
+                //     var myRoutes = MyRoutes;
+                //     Navigator.pushNamed(context, MyRoutes.homeRoute);
+                //   },
+                // )
+              ],
+            ),
+          )
+        ],
+      ),
+    ),
+  ),
+ );
+}
+
+ BorderRadius newMethod() => BorderRadius.circular(20);
+ }
+
+

Hi All, I'm a beginner to flutter and I'm trying to add validator to widget but I'm not getting the validation when I run the application.

+

I searched and tried the ways to do it but I didn't get the desired outcome.

+

Can you guys look into my code and suggest the right way.

+

no errors found but validation is not working.

","

First assign TextEditingController to your both fields.

+
  final TextEditingController _controllerUserName = TextEditingController();
+  final TextEditingController _controllerPassword = TextEditingController();
+
+

And also assign autovalidateMode to your text field so you can validate at user input like this. It's not necessary it's optional but you can add it to validate your field on input field changes. Although you can validate your form at submission time.

+
TextFormField(
+              decoration: const InputDecoration(
+                  hintText: "Enter User name", labelText: "Username "),
+                  initialValue: "",
+              validator: (String? value) {
+                if (value !=null && value.isEmpty ) {
+                  return "User name cannot be empty";
+                }
+                return null;
+              },
+              onChanged: (value) {
+                setState(() {});
+              },
+              autovalidate : AutovalidateMode.onUserInteraction,
+              controller:_controllerUserName
+            ),
+
+

And also you have not validate your form at submission time. try this

+
moveToHome(BuildContext) async{
+   if (_formkey.currentState.validate()) {
+       Navigator.pushNamed(context, MyRoutes.homeRoute);
+   }
+ }
+
",r +"How to stringify PostgreSQL JSON data?

I have seen a lot of questions similar to this (e.g. this one) but couldn't find one that helps. I'm looking for the equivalent of Javascript's JSON.stringify() but for PostgreSQL.

+

E.g.:

+
db=# \pset null
+Null display is "(null)".
+db=# create table x(c1 json);
+CREATE TABLE
+db=# insert into x (c1) values (null), ('"blah"'::json), ('{"a":1}'::json);
+INSERT 0 3
+db=# select * from x;
+   c1
+---------
+ (null)
+ "blah"
+ {"a":1}
+(3 rows)
+
+db=# select '''' || c1::text || '''' from x;
+ ?column?
+-----------
+ (null)     --- this is wrong, should be 'null'
+ '"blah"'
+ '{"a":1}'
+(3 rows)
+
+db=# select '''' || (c1 #>> '{}') || '''' from x;
+ ?column?
+-----------
+ (null)     --- this is wrong, should be 'null'
+ 'blah'     --- this is wrong, should be '"blah"'
+ '{"a":1}'
+(3 rows)
+
+db=# select '''' || case when c1 is null then 'null' else c1::text end || '''' from x;
+ ?column?
+-----------
+ 'null'
+ '"blah"'
+ '{"a":1}'
+(3 rows)
+
+

Can the last example be done without a CASE...END clause? And is it always right for all possible inputs?

","

You are confusing JSON null with SQL NULL. Per here JSON type:

+
+

Table 8.23. JSON Primitive Types and Corresponding PostgreSQL Types

+
+
+

JSON primitive type PostgreSQL type Notes

+
+
+

...

+
+
+

null (none) SQL NULL is a different concept

+
+

So:

+
insert into x (c1) values ('null'), ('"blah"'::json), ('{"a":1}'::json);
+
+ select '''' || c1::text || '''' from x;
+ ?column?  
+-----------
+ 'null'
+ '"blah"'
+ '{"a":1}'
+
+
",r +"Docker container runs locally but fails on Cloud Run to serve dbt docs

Idea here is simple - dbt provides a way to generate static files and serve them by using commands dbt docs generate and dbt docs serve and I want to share in a way that everyone in my organization can see them (bypassing security concerns as of now). For this task I thought Cloud Run would be ideal solution as I already have Dockerfile and bash scrips which do some background work (cron job to clone git repo every x hours, etc.). Running this container locally works fine. But deploying this image in Cloud Run wasn't successful - it fails on the last step (which is dbt docs server --port 8080) with default error message Cloud Run error: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information. No additional information in logs before that wasn't printed.

+

Dockerfile:

+
FROM --platform=$build_for python:3.9.9-slim-bullseye 
+WORKDIR /usr/src/dbtdocs
+RUN apt-get update && apt-get install -y --no-install-recommends git apt-transport-https ca-certificates gnupg curl cron \
+    && apt-get clean
+RUN DEBIAN_FRONTEND=noninteractive apt-get -y install tzdata
+RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] http://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list && curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg  add - && apt-get update -y && apt-get install google-cloud-sdk -y
+RUN python -m pip install --upgrade pip setuptools wheel --no-cache-dir
+RUN pip install dbt-bigquery
+RUN ln -s /usr/local/bin/dbt /usr/bin/
+RUN rm -rf /var/lib/apt/lists/*
+COPY ./api-entrypoint.sh /usr/src/dbtdocs/
+COPY ./cron_dbt_docs.sh /usr/src/dbtdocs/
+COPY ./cron_script.sh /usr/src/dbtdocs/
+ENV PORT=8080
+RUN chmod 755 api-entrypoint.sh
+RUN chmod 755 cron_dbt_docs.sh
+RUN chmod 755 cron_script.sh
+ENTRYPOINT ["/bin/bash", "-c", "/usr/src/dbtdocs/api-entrypoint.sh" ] ```
+
+

api-entrypoint.sh

+
#!/bin/bash
+
+#set -e
+#catch() {
+#    echo 'catching!'
+#    if [ "$1" != "0" ]; then
+#    echo "Error $1 occurred on $2"
+#    fi
+#}
+#trap 'catch $? $LINENO' EXIT
+exec 2>&1
+echo 'Starting DBT Workload'
+echo 'Checking dependencies'
+
+dbt --version
+git --version
+
+mkdir -p /data/dbt/ && cd /data/dbt/
+echo 'Cloning dbt Repo'
+git clone ${GITLINK} /data/dbt/
+
+echo 'Working on dbt directory'
+export DBT_PROFILES_DIR=/data/dbt/profile/
+
+echo "Authentificate at GCP"
+echo "Decrypting and saving sa.json file"
+mkdir -p /usr/src/secret/
+echo "${SA_SECRET}" | base64 --decode > /usr/src/secret/sa.json
+gcloud auth activate-service-account ${SA_EMAIL} --key-file /usr/src/secret/sa.json
+echo 'The Project set'
+if test "${PROJECT_ID}"; then
+    gcloud config set project ${PROJECT_ID}
+    gcloud config set disable_prompts true
+else
+    echo "Project Name not in environment variables ${PROJECT_ID}"
+fi
+echo 'Use Google Cloud Secret Manager Secret'
+if test "${PROFILE_SECRET_NAME}"; then
+    #mkdir -p /root/.dbt/
+    mkdir -p /root/secret/
+    gcloud secrets versions access latest --secret="${PROFILE_SECRET_NAME}" > /root/secret/creds.json
+    export GOOGLE_APPLICATION_CREDENTIALS=/root/secret/creds.json
+else
+    echo 'No Secret Name described - GCP Secret Manager'
+fi
+
+echo 'Apply cron Scheduler'
+sh -c "/usr/src/dbtdocs/cron_script.sh install"
+/etc/init.d/cron restart
+touch /data/dbt_docs_job.log
+sh -c "/usr/src/dbtdocs/cron_dbt_docs.sh"
+touch /data/cron_up.log
+tail -f /data/dbt_docs_job.log &
+tail -f /data/cron_up.log &
+dbt docs serve --port 8080
+
+

Container port is set to 8080 when creating Cloud Run service, so I don't think it's a problem here. +Have someone actually encountered similar problems using Cloud Run?

+

Logs in Cloud Logging

","

Your container is not listening/responding on port 8080 and has been terminated before the server process starts listening.

+

Review the last line in the logs. The previous line is building catalog.

+

Your container is taking too long to startup. Containers should start within 10 seconds because Cloud Run will only keep pending requests for 10 seconds.

+

All of the work I see in the logs should be performed before the container is deployed and not during container start.

+

The solution is to redesign how you are building and deploying this container so that the application begins responding to requests as soon as the container starts.

",r +"Model was constructed with shape (None, 50) for input KerasTensor(type_spec=TensorSpec(shape=(None, 50),

I have followed some kind of training and the final Jupyter notebook was this:

+

https://colab.research.google.com/drive/1Lmh1b5Ge9NodxIrukCTJC3cpYQDn9VuM?usp=sharing

+

I understand the entire code, and how the model was trained.

+

However, at the end I am predicting emotions for tweets in the test dataset like this:

+
i = random.randint(0, len(test_labels)-1)
+print('Sentence:', test_tweets[i])
+print('Emotion:', index_to_class[test_labels[i]])
+p = model.predict(np.expand_dims(test_seq[i], axis=0))[0]
+pred_class = index_to_class[np.argmax(p).astype('uint8')]
+print('Predicted Emotion:', pred_class)
+
+

This works perfectly fine.

+

However I want to test the model prediction with random sentences, like:

+
sentence = 'I love you more than ever'
+print('Sentence:',  sentence)
+#print('Emotion:', index_to_class[test_labels[i]])
+p = model.predict(np.expand_dims(sentence, axis=0))[0]
+pred_class = index_to_class[np.argmax(p).astype('uint8')]
+print('Predicted Emotion:', pred_class)
+
+

But I got this error:

+
Sentence: I love you more than ever
+WARNING:tensorflow:Model was constructed with shape (None, 50) for input KerasTensor(type_spec=TensorSpec(shape=(None, 50), dtype=tf.float32, name='embedding_input'), name='embedding_input', description="created by layer 'embedding_input'"), but it was called on an input with incompatible shape (None,).
+
+

What am I missing here?

","

Your model needs an integer sequence, not a raw string. Try converting the sentence to its corresponding integer sequence first:

+
sentence = 'I love you more than ever'
+print('Sentence:',  sentence)
+#print('Emotion:', index_to_class[test_labels[i]])
+sentence = get_sequences(tokenizer, np.expand_dims(sentence, axis=0))
+p = model.predict(sentence)[0]
+pred_class = index_to_class[np.argmax(p).astype('uint8')]
+print('Predicted Emotion:', pred_class)
+
+
Sentence: I love you more than ever
+Predicted Emotion: joy
+
",r +"Type mismatch in lambda function - Kotlin

I want the text to be taken from string resource, depends on item.route, which is specified before bellow code.

+

But whole "when" expression gives me the error: +"Type mismatch: inferred type is () -> Int but Int was expected." +I don't have idea how to resolve it.

+

+Text(
+        text = stringResource(id = {
+            when (item.route) {
+                "menu_screen" -> R.string.menu
+                "orders_screen" -> R.string.orders
+                else -> R.string.orders
+            }
+        }),
+        textAlign = TextAlign.Center
+    )
+
","

When you put bare brackets { } around something, it is interpreted as a lambda function. By "bare" I mean not after a class/fun/when/if/else, etc. You need to remove the extra brackets you put in there.

+
Text(
+    text = stringResource(id = 
+        when (item.route) {
+            "menu_screen" -> R.string.menu
+            "orders_screen" -> R.string.orders
+            else -> R.string.orders
+        }
+    ),
+    textAlign = TextAlign.Center
+)
+
+

Some other languages (such as Java) let you surround code with brackets to limit the scope of variables declared inside or to compute something that takes multiple expressions. To do this in Kotlin, you have to use a scope inline function such as run { }.

",r +"How to send scheduled email with Crontab in Django

I like to send scheduled emails in Django with Crontab. I made a very simple app to test how can I send an email in every minutes (just for testing purposes). I think I am doing something wrong, because I can't get the mails.

+

users/cron.py

+
from django.core.mail import send_mail
+
+def my_scheduled_job():
+    
+    send_mail(
+        'subject',
+        'Here is the message.',
+        'something@example.com',
+        ['me@gmail.com'],
+        fail_silently=False,
+    )
+    print('Successfully sent')
+
+

settings.py

+
CRONJOBS = [
+    ('*/1 * * * *', 'users.cron.my_scheduled_job')
+]
+
+

I added the job like this:

+
python3 manage.py crontab add
+
+

then

+
python3 manage.py runserver
+
+

My mailing server configured fine, every other emails are sent, but I can't get these emails, nothing happens. I don't like to use Celery or Django Q.

","

You can use built-in Django commands to avoid third party integrations or external libraries. +For example you can add the following in a my_app/management/commands/my_scheduled_job.py file:

+
from django.core.mail import send_mail
+from django.core.management.base import BaseCommand
+
+class Command(BaseCommand):
+    def handle(self, *args, **options):
+        # ... do the job here
+        send_mail(
+            # ...
+        )
+        print('Successfully sent')
+
+

and then you can just configure your crontab command as usual, for example every day at 8PM:

+
0 20 * * * python manage.py my_scheduled_job
+
+

Here additional info about custom Django commands.

",r +"persisting Babylonjs texture cache across engine/scene instances

Long time listener, first time caller. I am working on a babylon-js project within the context of a React app. In an effort to help improve performance, I would like to load textures only once and preserve that across scene/engine disposals. The engine and scene are disposed because the canvas running babylon-js does not exist on all pages in the app. I have investigated serializing the scene, materials etc, but that did not seem to work as the textures are still loaded again (albeit from indexdb now that I am using an offline provider). The current running hypothesis is to extract the canvas outside the react vDOM and just toggle its visibility css upon entering or exiting the babylon-js viewer component. The question I have is that: am I missing something? Extracting the canvas outside the react context strikes me as an anti-pattern

","

Frequently creating and disposing webgl contexts is a big no-no as it's not only resource/computationally intensive but can also causes loss of context to other tabs since there's only a limited amount of contexts the browser can provide and resources are freed asynchronously. Keep in mind that patterns are concepts, not rules and have to be evaluated as such on a per case basis.

+

So to answer your question: no you didn't miss anything, the best solution is to store the webgl canvas outside of reacts vDOM.

",r +"Adding new rows with new values at some specific columns in pandas

Assume we have a table looks like the following:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
idweek_numpeopledatelevelab
11201990101123
12301990108123
13401990115123
151001990129123
171001990212123
+
+

week_num skip the "4" and "6" because the corresponding "people" is 0. However, we want the all the rows included like the following table.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
idweek_numpeopledatelevelab
11201990101123
12301990108123
13401990115123
1401990122123
151001990129123
1601990205123
171001990212123
+
+

The date starts with 1990101, the next row must +7 days if it is a continuous week_num(Ex: 1,2 is continuous; 1,3 is not).

+

How can we use python(pandas) to achieve this goal?

+

Note: Each id has 10 week_num(1,2,3,...,10), the output must include all "week_num" with corresponding "people" and "date".

+

Update: Other columns like "level","a","b" should stay the same even we add the skipped week_num.

","

This assumes that the date restarts at 1990-01-01 for each id:

+
import itertools
+# reindex to get all combinations of ids and week numbers
+df_full = (df.set_index(["id", "week_num"])
+             .reindex(list(itertools.product([1,2], range(1, 11))))
+             .reset_index())
+# fill people with zero
+df_full = df_full.fillna({"people": 0})
+# forward fill some other columns
+cols_ffill = ["level", "a", "b"]
+df_full[cols_ffill] = df_full[cols_ffill].ffill()
+# reconstruct date from week starting from 1990-01-01 for each id
+df_full["date"] = pd.to_datetime("1990-01-01") + (df_full.week_num - 1) * pd.Timedelta("1w")
+df_full
+
+# out:
+    id  week_num  people       date  level    a    b
+0    1         1    20.0 1990-01-01    1.0  2.0  3.0
+1    1         2    30.0 1990-01-08    1.0  2.0  3.0
+2    1         3    40.0 1990-01-15    1.0  2.0  3.0
+3    1         4     0.0 1990-01-22    1.0  2.0  3.0
+4    1         5   100.0 1990-01-29    1.0  2.0  3.0
+5    1         6     0.0 1990-02-05    1.0  2.0  3.0
+6    1         7   100.0 1990-02-12    1.0  2.0  3.0
+7    1         8     0.0 1990-02-19    1.0  2.0  3.0
+8    1         9     0.0 1990-02-26    1.0  2.0  3.0
+9    1        10     0.0 1990-03-05    1.0  2.0  3.0
+10   2         1     0.0 1990-01-01    1.0  2.0  3.0
+11   2         2     0.0 1990-01-08    1.0  2.0  3.0
+12   2         3     0.0 1990-01-15    1.0  2.0  3.0
+13   2         4     0.0 1990-01-22    1.0  2.0  3.0
+14   2         5     0.0 1990-01-29    1.0  2.0  3.0
+15   2         6     0.0 1990-02-05    1.0  2.0  3.0
+16   2         7     0.0 1990-02-12    1.0  2.0  3.0
+17   2         8     0.0 1990-02-19    1.0  2.0  3.0
+18   2         9     0.0 1990-02-26    1.0  2.0  3.0
+19   2        10     0.0 1990-03-05    1.0  2.0  3.0
+
",r +"How to create Plotly benchmarking bar chart with average value as base axis

I want to develop a kind of cool benchmark chart that will show on the Y-axis some categories (in my case companies), on the X-axis there will be some numeric values representing a given measurement e.g. daily number of sold products.

+

And I want present it in a way that somewhere in the middle of the X-axis I will show a long straight line which will represent the average of my measurement - and then I want to use it as my base axis. And for each category, I will show a bar chart that will have a 0 (start) value at the average line, and the end will be the difference between the measurement of the given category and the average (category measurement - average). +Below is an example that I draw in PowerPoint. I hope it will give you a short overview of what I want to achieve.

+

+

To be honest I don't know if it's possible with Plotly library. My initial idea is that I need to put the average line as a separate element on the given chart, and then I need to somehow dynamically calculate the start, and end of the given category bar chart and put it on the chart. But don't know if it makes sense.

+

Could you help me with this case?

","

Assume you have some data,

+
import pandas as pd
+import plotly.graph_objects as go
+
+data = pd.DataFrame({
+    'companies': ['Comp1', 'Comp2', 'Comp3', 'Comp4'], 
+    'performance': [26, 37, 54, 19]
+})
+
+# if you want a manual benchmark
+benchmark_value = 40
+
+# or in case the average
+benchmark_value = data['performance'].mean()
+
+data['benchmark_score'] = data['performance'] - benchmark_value
+
+fig = go.Figure(
+    go.Bar(
+        y=data['companies'],
+        x=data['benchmark_score'],
+        marker=dict(color=['red' if score < 0 else 'green' for score in data['benchmark_score']]),
+        orientation='h',
+        text=data['benchmark_score'],
+    )
+)
+
+# add vertical line at 0 but with benchmark value as annotation
+fig.add_vline(x=0, line_width=2, line_dash="dash", annotation_text=benchmark_value)
+
+fig.show()
+
+

Output:

+

+

You can customize a bit on some attributes such as bar colors and text annotation.

",r +"THREE.js revolving smoke effect works only for one element instead of applying to all elements

I am trying to create a custom post header background for a forum website. But because I always want to make my life more difficult I tried to make it fancy. I also need to link to that script in every post.

+

When I duplicate the post (or simulate it by just ctrl+a ctrl+c ctrl+v ctrl+v the HTMP code) only the last post gets any smoke effect background. I tried to add the function to the window on init and loop it for every element with the SiffrinSmoke class but still only one smoke is displayed - at the bottom.

+

HTML:

+
<div class="SiffrinBody">
+    <div class="SiffrinHeader">
+        <div class="SiffrinSmoke">
+            <!--h1>Siffrin<br>Drauglir</h1-->
+            <h1 data-heading="Siffrin&#xa;Drauglir"></h1>
+        </div>
+        <div class="SiffrinCanvasBackground" id="SiffrinCanvasBackground"></div>
+        <div class="SiffrinCanvasForeground" id="SiffrinCanvasForeground"></div>
+        <img id="SiffrinHeaderBackground" src="https://i.imgur.com/iYnkBdZ.jpg">
+        <img id="SiffrinWolf" src="https://i.imgur.com/MBLqG00.png">
+    </div>
+</div>
+
+

CSS:

+
 @import url('https://fonts.googleapis.com/css2?family=Arvo:ital@0;1&family=Carter+One&family=Dosis:wght@400;500;600&display=swap');
+
+    .SiffrinBody .SiffrinHeader .SiffrinCanvasBackground{
+        height: 330px;
+        width: 656px;
+        position: absolute;
+        left: inherit;
+        top: inherit;
+        z-index: 5;
+    }
+
+    .SiffrinBody .SiffrinHeader .SiffrinCanvasForeground{
+        height: 330px;
+        width: 656px;
+        position: absolute;
+        left: inherit;
+        top: inherit;
+        z-index: 7;
+    }
+
+    .SiffrinBody .SiffrinHeader img{
+        position: absolute;
+        height: 330px;
+        width: 656px;
+        grid-row: 1;
+    }
+
+    .SiffrinBody .SiffrinHeader .SiffrinSmoke{
+        width: 328px;
+        height: 330px;
+        position: relative;
+        z-index: 6;
+        float: right;
+        display: block;
+    }
+
+    .SiffrinBody .SiffrinHeader .SiffrinSmoke canvas{
+        position: absolute;
+        top: 0;
+        left: 0;
+        z-index: -4;
+    }
+
+    .SiffrinBody .SiffrinHeader #SiffrinHeaderBackground{
+        z-index: 4;
+    }
+
+    .SiffrinBody .SiffrinHeader #SiffrinWolf{
+        z-index: 6;
+
+    }
+
+    .SiffrinBody .SiffrinHeader h1{
+        font-family: Carter One;
+        z-index: 1000;
+        color: white;
+        grid-column: 2;
+        font-size: 50;
+        margin-top: 32%;
+        text-align: center;
+        background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/209981/6963bbf342d87b3a2150bd8f59682b89.jpg);
+        -webkit-background-clip: text;
+        background-size: cover;
+        width: 100%;
+        color: transparent;
+        font-weight: 900;
+        display: block;
+        white-space: pre-wrap !important;
+        line-height: 1.1em;
+        text-shadow:  2px 2px 6px rgba(46,146,211,0.8);
+    }
+
+    .SiffrinBody .SiffrinHeader h1::before{
+        content: attr(data-heading);
+        position: relative;
+        left: 0;
+        top: 0;
+        width: 100%;
+        background: linear-gradient(45deg, rgba(255,255,255,0) 45%,rgba(255,255,255,0.8) 50%,rgba(255,255,255,0) 55%,rgba(255,255,255,0) 100%);
+        -webkit-background-clip: text;
+        color: transparent;
+        mix-blend-mode: screen;
+        animation: SiffrinShine 15s infinite linear;
+        background-size: 200%;
+    }
+
+    .SiffrinBody .SiffrinHeader #SiffrinName{
+        z-index: 22;
+        transform: scale(0.8);
+        left: 150px;
+    }
+
+    .SiffrinBody .SiffrinHeader{
+        grid-row: 1;
+        mask-image: linear-gradient(
+            to top,
+            rgba(255, 255, 255, 0) 0,
+            rgba(255, 255, 255, 1) 15px
+        );
+    }
+
+    .SiffrinBody .SiffrinHeader > *{
+        user-select: none;
+    }
+
+    .SiffrinBody{
+        color: white;
+        display: grid;
+        grid-template-rows: 330px auto auto;
+        grid-template-columns: 1fr;
+        margin: 0;
+        padding: 0;
+        width: 656px;
+        /*background-image: linear-gradient(#bad4eb, #bad4eb, #a7c8e7, #4789c6, #037ccf);*/
+        background-image: url("https://i.imgur.com/UqFcRzS.jpg");
+        background-repeat: repeat;
+    }
+
+    .SiffrinBody *::selection{
+        background: rgba(225, 0, 255, 0.3);
+        color: inherit;
+    }
+
+    .SiffrinBody .SiffrinHeader{
+        /*
+        z-index: 7;
+        text-align: center;
+        font-family: Oleo Script;
+        margin: auto;
+        font-size: 30px;
+        transition-duration: 2s;
+        transition-timing-function: ease-in-out;
+        background-image: radial-gradient(#0e111800, #232b3e00, #24212a00, #403b6600);
+        user-select: none;
+        */
+    }
+
+    .SiffrinBody .SiffrinBody:hover .SiffrinHeader{
+        /*
+        letter-spacing: 0.35em;
+        transition-duration: 3s;
+        transition-timing-function: ease-in-out;
+        transform: translate(0px, 40px);
+        */
+    }
+
+    .SiffrinBody .SiffrinText{
+        z-index: 7;
+        margin: 10px 50px;
+        padding: 20px;
+        background-color: rgba(0, 0, 0, 0.5);
+        font-family: Dosis;
+        font-size: 17px;
+        margin-bottom: 0;
+        line-height: 1.235em;
+        font-weight: 500;
+    }
+
+    .SiffrinBody .SiffrinText::before{
+  
+        border-top: 3px solid blue;
+        border-right: 3px solid blue;
+    }
+
+    .SiffrinBody .SiffrinText::after{
+
+        border-bottom: 3px solid orange;
+        border-left: 3px solid orange;
+    }
+
+    .SiffrinBody .SiffrinText p{
+        padding: 0;
+        margin-bottom: 1em;
+    }
+
+    .SiffrinBody .SiffrinText p u,
+    .SiffrinBody .SiffrinText p i,
+    .SiffrinBody .SiffrinText p q{
+        font-family: Arvo;
+        font-size: 16px;
+    }
+
+    .SiffrinBody .SiffrinText p u{
+        text-decoration: none;
+        color:rgb(250, 210, 255);
+    }
+
+    .SiffrinBody .SiffrinText p u::before {
+        content: "“"
+    }
+
+    .SiffrinBody.SiffrinText p u::after {
+        content: "”"
+    }
+
+    .SiffrinBody .SiffrinText p i{
+        font-family: Arvo;
+        color:rgb(250, 210, 255);
+        font-style: italic;
+    }
+
+    .SiffrinBody .SiffrinText p q{
+        text-decoration: none;
+        color:rgb(219, 223, 255);
+    }
+
+    .SiffrinBody .SiffrinText p:last-child{
+        margin: 0;
+    }
+
+    .SiffrinBody .SiffrinText p:first-child{
+        margin-top: 0;
+    }
+
+    .SiffrinBody .SiffrinFooter{
+        display: flex;
+        align-items: center;
+        justify-content: center;
+        padding: 10px;
+        margin: 0;
+    }
+
+    .SiffrinBody .SiffrinFooter p{
+        text-align: center;
+        font-size: 20px;
+        color: #f8f7fd;
+        text-align: center;
+    }
+
+    @keyframes SiffrinShine {
+        0% {background-position: 110%;}
+        60% {background-position: -90%;}
+        100% {background-position: -90%;}
+    }
+
+

Import THREE:

+
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
+
+

JS:

+
function initiateSmoke() {
+        smokeBackgrounds = document.getElementsByClassName('SiffrinSmoke');
+        clock = new THREE.Clock();
+        renderW = smokeBackgrounds[0].offsetWidth;
+        renderH = smokeBackgrounds[0].offsetHeight;
+        renderer = new THREE.WebGLRenderer({ alpha: true });
+        renderer.setSize( renderW, renderH );
+
+        scene = new THREE.Scene();
+    
+        camera = new THREE.PerspectiveCamera( 75, renderW / renderH , 1, 10000 );
+        camera.position.z = 1300;
+        scene.add( camera );
+    
+        geometry = new THREE.CubeGeometry( 200, 200, 200 );
+        material = new THREE.MeshLambertMaterial( { color: 0xaa6666, wireframe: false } );
+        mesh = new THREE.Mesh( geometry, material );
+        cubeSineDriver = 0;
+    
+        textGeo = new THREE.PlaneGeometry(300,300);
+        THREE.ImageUtils.crossOrigin = ''; //Need this to pull in crossdomain images from AWS
+
+        light = new THREE.DirectionalLight(0xffffff, 1);
+        light.position.set(-1,0,1);
+        scene.add(light);
+    
+        smokeTexture = THREE.ImageUtils.loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/95637/Smoke-Element.png');
+        smokeMaterial = new THREE.MeshLambertMaterial({color: 0x333333, opacity: 1, map: smokeTexture, transparent: true});
+        smokeGeo = new THREE.PlaneGeometry(650,650);
+        smokeParticles = [];
+
+        for (p = 0; p < 36; p++) {
+            particle = new THREE.Mesh(smokeGeo,smokeMaterial);
+            particle.position.set(Math.random() * 950 - 500, Math.random() * 620 - 300, Math.random() * 200 - 100);
+            particle.rotation.z = Math.random() * 360;
+            particle.scale.set(2,2,2);
+            scene.add(particle);
+            smokeParticles.push(particle);
+        }
+        for(i = 0; i < smokeBackgrounds.length; i++) {
+            smokeBackgrounds[i].appendChild( renderer.domElement );
+        }
+    }
+        
+    function animateSmoke() {
+        // note: three.js includes requestAnimationFrame shim
+        delta = clock.getDelta();
+        requestAnimationFrame( animateSmoke );
+        evolveSmoke();
+        render();
+    }
+        
+    function evolveSmoke() {
+        var sp = smokeParticles.length;
+        while(sp--) {
+            smokeParticles[sp].rotation.z += (delta * 0.2);
+        }
+    }
+
+    function render() {
+        mesh.rotation.x += 0.005;
+        mesh.rotation.y += 0.01;
+        cubeSineDriver += .01;
+        mesh.position.z = 100 + (Math.sin(cubeSineDriver) * 500);
+        renderer.render( scene, camera );
+    }
+
+    window.onload = function Snowfall(){
+        initiateSmoke();
+        animateSmoke();
+}
+
+

Do you know how to apply that same effect as background for every element with that class? Maybe another tool would be better for the job?

+

EDIT: Solution +The Smoke init function accepts the background elements from before and returns relevant objects

+
function initiateSmoke(smokeBackground) {
+[...]
+        return({
+            "renderer": renderer,
+            "scene": scene,
+            "camera": camera,
+            "mesh": mesh,
+            "cubeSineDriver": cubeSineDriver,
+            "smokeParticles": smokeParticles
+        })
+}
+
+

Then in window.onloadI have this loop

+
        smokeBackgrounds = document.getElementsByClassName('SiffrinSmoke');
+
+        for(i = 0; i < smokeBackgrounds.length; i++) {
+            smokeScenes[i] = initiateSmoke(smokeBackgrounds[i]);
+            smokeBackgrounds[i].appendChild(smokeScenes[i]['renderer'].domElement);
+        }
+        
+        animateSmoke();
+
+

I also edited the animate functions

+
    function animateSmoke() {
+        delta = clock.getDelta();
+        requestAnimationFrame(animateSmoke);
+        evolveSmoke();
+        render();
+    }
+        
+    function evolveSmoke() {
+        for(i = 0; i < smokeScenes.length; i++) {
+            smokeScene = smokeScenes[i];
+            var sp = smokeScene['smokeParticles'].length;
+            while(sp--) {
+                smokeScene['smokeParticles'][sp].rotation.z += (delta * 0.2);
+            }
+        }
+    }
+
+    function render() {
+        for(i = 0; i < smokeScenes.length; i++) {
+            smokeScene = smokeScenes[i];
+            smokeScene['mesh'].rotation.x += 0.005;
+            smokeScene['mesh'].rotation.y += 0.01;
+            smokeScene['cubeSineDriver'] += .01;
+            smokeScene['mesh'].position.z = 100 + (Math.sin(smokeScene['cubeSineDriver']) * 500);
+            smokeScene['renderer'].render( smokeScene['scene'], smokeScene['camera']);
+        }
+    }
+
+    let smokeScenes = []
+    let clock = new THREE.Clock();
+
+

and that works!

","

It's because you're only creating one canvas, and just appending that to each "smokeBackgrounds" in the loop. But each one overwrites the last one, because there's only one canvas (renderer.domElement).

+

There's a few ways you could solve it:

+
    +
  1. Create a loop outside of this code that loops through smokeBackgrounds, and calls initiateSmoke(smokeBackgrounds[i]), and then change that loop towards the end of the method to use the passed-in dom element.
  2. +
  3. Clone the canvas itself, and assign each new instance a smokeBackgrounds.
  4. +
  5. (Hard) Create multiple threejs scenes within the code, and assign each a position on the page. This way you can stretch the canvas to the full-page, and just move around the smoke positions to be associated with where the HTML elements are. The advantage of this is it's lighter because you won't have multiple canvas's running.
  6. +
",r +"How do I convert timestamp to datetime format in python for cosmos data?

After querying cosmos db I receive a ts column in my dataframe(df) which has datetime in the below format

+
df
+_ts         etag
+1646255207   xyz
+1646257427   abc
+1646297798
+1646333451   dfg
+
+

How do I convert this to a datetime format. The reason i want to is because, I only want data from last 24 hours.

+

I tried-

+
from datetime import datetime
+d = "1646255207"
+d = int(d[:10])
+datetime.fromtimestamp(d).strftime('%Y-%m-%d %I:%M:%S %p')
+Out[39]: '2022-03-02 04:06:47 PM'
+
+

Is there a better way to just add a filter to _ts and get last 24 hour data from _ts itself?

","

Use pd.to_datetime with unit="s":

+
df["Date"] = pd.to_datetime(df["_ts"], unit="s")
+print(df)
+
+

Prints:

+
          _ts  etag                Date
+0  1646255207   xyz 2022-03-02 21:06:47
+1  1646257427   abc 2022-03-02 21:43:47
+2  1646297798  None 2022-03-03 08:56:38
+3  1646333451   dfg 2022-03-03 18:50:51
+
+
+

And to get last 24h data:

+
print(df[df["Date"] > df["Date"].max() - pd.Timedelta(hours=24)])
+
",r +"az aks with --admin switch does not require a password?

If I connect to my AKS cluster with,

+
az aks get-credentials --resource-group <rgname> --name <clustername> --admin
+
+

it does not require any credentials. Is this expected? Or is it using my "Az login" credentials and passing that through? My cluster is enabled for AD access but I was reading that the --admin flag can be used to force it to use the k8s admin. Should this be blocked for security reasons?

+

Sorry, quite new to AKS and Kubernetes.

","

Yes, The below cmdlet will not require any addinational credential to connect to the AKS, Az login is enough to connect to the AKS who has access of subscription in which AKS created.

+
 az aks get-credentials --resource-group <rgname> --name <clustername> --admin
+
+
+

--admin flag can be used to force it to use the k8s admin. Should this be blocked for security reasons?

+
+

Yes you are correct,This should be blocked for secuirity purpose, But unfortunatlly switch –admin access on or off using a simple switch with az aks commands still in preview state, This is not recommanded for production use as of now.

+

For more information how to disable local user account (–admin) in Azure Kubernetes Service you can refer this document

+

There is also workaround given in this Github Disccussion you can also go through that.

",r +"model-viewer and cursor moverment

I am using model-viewer for a 3D-Model and I want to move the 3D-Model according to cursor movement. I am not sure how I can connect the HTML variable in attribute "camera-controls" so that I can change them in js. +So far I have written this in HTML:

+
<div class="hero">
+ <model-viewer src="{% static "images/file_name.glb" %}" alt="3d model"
+        loading="eager" camera-controls disable-zoom 
+        reveal="auto" auto-rotate rotation-per-second="60deg"
+        id="model">
+ </model-viewer>
+</div>
+
","

I managed to solve it with the following code:

+
const modelViewer = document.getElementById('model'); 
+
+document.onmousemove = handleMouseMove;
+    function handleMouseMove(event) {
+        var eventDoc, doc, body;
+
+        event = event || window.event; // IE-ism
+
+        // If pageX/Y aren't available and clientX/Y are,
+        // calculate pageX/Y - logic taken from jQuery.
+        // (This is to support old IE)
+        if (event.pageX == null && event.clientX != null) {
+            eventDoc = (event.target && event.target.ownerDocument) || document;
+            doc = eventDoc.documentElement;
+            body = eventDoc.body;
+
+            event.pageX = event.clientX +
+              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
+              (doc && doc.clientLeft || body && body.clientLeft || 0);
+            event.pageY = event.clientY +
+              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
+              (doc && doc.clientTop  || body && body.clientTop  || 0 );
+        }
+
+        // Use event.pageX / event.pageY here
+        x = - (event.pageX / window.innerWidth * 100 - 50)
+        if(media_change.matches){
+          x = - (event.pageX / window.innerWidth * 100 - 30)
+        }
+        y = - (event.pageY / window.innerHeight * 50) + 120
+    }
+
",r +"how to run testcontainer with dynamic port for spring data elasticsearch

My test case uses @SpringBootTest annotations to bring up the context and has Autowired some repository. Testcontainer is started in @BeforeAll() method. The problem is RestClientConfig is being initialized/injected before @BeforeAll() in test case. When testcontainer starts, it exports some dynamic port.

+

I have to set some fixed port in testcontainer 34343 and use the same port in properties file for RestClientConfig.

+
container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
+        .withEnv("discovery.type", "single-node")
+        .withExposedPorts(9200)     
+        .withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(
+                    new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(34343), new ExposedPort(9200)))));
+
+

Is there a way to start container and get its dynamic port then use it to initialize RestClientConfig?

+

I didn't use annoation @Testcontainers though. Is it needed?

","
    +
  1. You can use context configuration initialiser to set properties during runtime, which you can later use in your RestClientConfig.
  2. +
+

Let me show you on the example of Postgresql container setup:

+
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
+@ContextConfiguration(initializers = AbstractTestcontainersTest.DockerPostgreDataSourceInitializer.class)
+public abstract class AbstractTestcontainersTest {
+
+    protected static final String DB_CONTAINER_NAME = "postgres-auth-test";
+    protected static PostgreSQLContainer<?> postgreDBContainer =
+            new PostgreSQLContainer<>(DockerImageName.parse("public.ecr.aws/docker/library/postgres:12.10-alpine")
+                    .asCompatibleSubstituteFor("postgres"))
+            .withUsername("postgres")
+            .withPassword("change_me")
+            .withInitScript("db.sql")
+            .withCreateContainerCmdModifier(cmd -> cmd.withName(DB_CONTAINER_NAME))
+            .withDatabaseName("zpot_main");
+
+    @BeforeAll
+    public static void beforeAll() throws ShellExecutionException {
+        postgreDBContainer.start();
+    }
+
+    @AfterAll
+    public static void afterAll() {
+        postgreDBContainer.stop();
+    }
+
+    public static class DockerPostgreDataSourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
+
+        @Override
+        public void initialize(ConfigurableApplicationContext applicationContext) {
+
+            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
+                    applicationContext,
+                    "spring.datasource.url=" + postgreDBContainer.getJdbcUrl(),
+                    "spring.datasource.username=" + postgreDBContainer.getUsername(),
+                    "spring.datasource.password=" + postgreDBContainer.getPassword()
+            );
+        }
+    }
+}
+
+

All the configuration is done in DockerPostgreDataSourceInitializer, where I set all the properties I need. You also need to annotate your test class with @ContextConfiguration annotaion. You can do something similar with your ElasticSearchContainer. As I just checked the ElasticSearchContainer has a method getHttpHostAddress() which returns host+dynamic_port combination for your container. You can get that host-port pair and set in in properties to be used later in your client configuration. If you need just port you can call container.getMappedPort(9200) and again set that port in properties.

+
    +
  1. Regarding @Testcontainers annotation, you need it if you want testcontainers to manage your container lifecycle. In that case you also need to annotate container with @Container annotation. Your container will be started either once before all test methods in a class if your container is a static field or before each test method if it's a regular field. You can read more about that here: https://www.testcontainers.org/test_framework_integration/junit_5/#extension. +Or you can start your container manually either in @BeforeAll or @BeforeEach annotated setup methods. In other words no, you don't have to use @Testcontainers annotation.
  2. +
",r +"npm ERR! Missing script, but the script is there when I run ""npm run""?

I am trying to run a .bat file that simply echoes 'hello', to learn more about package.json and scripts. I have this:

+
"scripts": {
+   "buildSwaggerFiles": "buildSwaggerFiles",
+ },
+
+

but when I run npm run buildSwaggerFiles, I recieve the error that I either misspelled the command, or it doesn't exist (It's in german otherwise I'd just paste the error here). The same error pops up if I add .bat:

+
"scripts": {
+   "buildSwaggerFiles": "buildSwaggerFiles.bat",
+ },
+
+

So I thought I needed to add the path, even though I haven't seen that online anywhere? It then looked like this:

+
"scripts": {
+   "buildSwaggerFiles": "projects/common/src/lib/buildSwaggerFiles.bat",
+ },
+
+

Same error, so I added npm run:

+
"scripts": {
+   "buildSwaggerFiles": "npm run projects/common/src/lib/buildSwaggerFiles.bat",
+ },
+
+

And then I get the error npm ERR! Missing script: "projects/common/src/lib/buildSwaggerFiles.bat", however when I run npm run, it shows me this:

+
Scripts available in angular-library@0.0.0 via npm run-script:
+buildSwaggerFiles
+    projects/common/src/lib/buildSwaggerFiles.bat
+
+

At this point I am lost. Am I in the wrong Terminal? The terminal destination is Angular-Library, which contains the mentioned 'projects' folder, as well as the package.json. To clarify, the package.json is in the same folder as the projects folder that contains the script I am trying to run. Is that my problem? Can I not run .bat files through package.json? What else can I try? Thank you in advance.

","

For anyone who may find this useful: +I managed to solve it by putting node before listing the path to my script file, like so:"buildSwaggerFiles": "node projects/common/src/lib/buildSwaggerFiles.bat",

",r +"Azure AD Parameter values

I am working on Azure AD authentication. I always get 401 even though my token is valid. Where can I get the value of Tenant and ValidAudience?

+
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
+            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
+            {
+                Tenant = 
+                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
+                {
+                    ValidAudience = 
+                }
+            });
+
","

The usual WindowsAzureActiveDirectoryBearerAuthentication middleware uses a +metadata endpoint which is not supported by the v2.0 endpoint. Instead, this +OpenIdConnectSecurityTokenProvider implementation can be used to fetch & use the OpenIdConnect metadata document - which for the v2 endpoint is https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

+
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
+        {
+            AccessTokenFormat = new JwtFormat(
+                new TokenValidationParameters
+                {
+                    // Check if the audience is intended to be this application
+                    ValidAudiences = new[] { clientId, "api://clientId" },
+
+                    // Change below to 'true' if you want this Web API to accept tokens issued to one Azure AD tenant only (single-tenant)
+                    // Note that this is a simplification for the quickstart here. You should validate the issuer. For details, 
+                    // see https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore
+                    ValidateIssuer = false,
+
+                },
+                new OpenIdConnectSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")
+            ),
+        });
+
",r +"DOCKER Python Path

I am new to Docker. 1 Thing is confusing me, when I print the output of which python in Docker, it points towards the system's python, even though I have mentioned the python3.7 as a base image, so it should be pointing towards image python right?

+

My docker file is as follows:

+
FROM python:3.7
+
+RUN which python3
+RUN which python3.7
+RUN which python
+
+
+

The output is

+
Sending build context to Docker daemon  2.048kB
+Step 1/4 : FROM python:3.7
+ ---> 7c891de3e220
+Step 2/4 : RUN which python3
+ ---> Running in bfcab000b493
+/usr/local/bin/python3
+Removing intermediate container bfcab000b493
+ ---> be30731a0a5a
+Step 3/4 : RUN which python3.7
+ ---> Running in 144cf28963eb
+/usr/local/bin/python3.7
+Removing intermediate container 144cf28963eb
+ ---> 7434c6aa69cb
+Step 4/4 : RUN which python
+ ---> Running in 88e3133f4e41
+/usr/local/bin/python
+Removing intermediate container 88e3133f4e41
+ ---> 872bfb66fc7d
+Successfully built 872bfb66fc7d
+Successfully tagged docker_testing:latest
+
+

You can see that it is responding all the python to /usr/bin/pythonx

+

I want to ask if this is the Docker's Python that is being used or not, or is it using my system's Python.

+

Thanks.

","

When you run RUN which python3 that is path in your docker image not your system path, you can try RUN touch /usr/bin/testtesttest and check in your system.

+

Data in docker container can storage in your system only when you mount

",r +"does the IndexedDB Wrapper Dexie.js support all kinds of Web browser?

I'm planning to use IndexedDB Wrapper Dexie.js for my react.js application. +Does Dexie.js support all kinds of web browsers? +If there is any limitation, kindly let me know

+

Thanks in advance.

","

Dexie.js supports all major modern browsers including but not limited to:

+
    +
  • Chrome - all versions younger than 7 years.
  • +
  • Firefox - all versions younger than 7 years.
  • +
  • Safari - all versions younger than 3 years.
  • +
  • Opera - all versions younger than 7 years.
  • +
  • Edge - all versions younger than 3 years.
  • +
  • Internet Explorer 11 - partial support
  • +
  • Edge legacy - partial support
  • +
",r +"Extract tags from Go struct as a reflect.Value

I'm trying to extract tags from a certain Value which is a struct. I am able to get the fields of the struct but unable to extract the tags. What am I doing wrong here? I've tried many different ways (using reflect.Type, interface{} etc) but all failed.

+

+type House struct {
+    Room string
+    Humans Human
+}
+
+type Human struct {
+    Name         string `anonymize:"true"` // Unable to get this tag
+    Body         string
+    Tail         string `anonymize:"true"` // Unable to get this tag
+}
+
+func printStructTags(f reflect.Value) { // f is of struct type `human`
+    for i := 0; i < f.NumField(); i++ {
+        fmt.Printf("Tags are %s\n", reflect.TypeOf(f).Field(i).Tag) // TAGS AREN'T PRINTED
+    }
+}
+
+

The reason I use reflect.Value as the parameter is because this function is called from another function in the following manner

+
    var payload interface{}
+    payload = &House{}
+    // Setup complete
+    v := reflect.ValueOf(payload).Elem()
+    for j := 0; j < v.NumField(); j++ { // Go through all fields of payload
+        f := v.Field(j)
+        if f.Kind().String() == "struct" { 
+            printStructTags(f)
+        }
+    }
+
+

Any insights would be extremely valuable

","

When you call reflect.TypeOf(f) you get the type of f, which is already a reflect.Value.

+

Use the Type() func of this f to get the type and do the Field check on it:

+
func printStructTags(f reflect.Value) { // f is of struct type `human`
+    for i := 0; i < f.NumField(); i++ {
+        fmt.Printf("Tags are %s\n", f.Type().Field(i).Tag) 
+    }
+}
+
+

However, it's easier to check for a tag and get its value with f.Type().Field(i).Tag.Get("anonymize"). This way you directly get the assigned value, for example true in your case and an empty string if the tag doesn't exist.

",r +"compiling js failed react native expected buffer size

My code was working fine and then suddenly start showing error something like this:-

+

Compiling JS failed: 180820:25:';' expected Buffer size 7070676 starts with:....... and has protection mode(s): r--p

+

Error Screenshot
+

+

I tried resetting the cache with

+
npx react-native start --reset-cache
+
+

I am using the latest version of every module in my code the last change is to remove the "AsyncStorage" module.

","

After reviewing the change I made, it seems that I used and await call outside an async function, and that's what caused this error.

",r +"Is it possible to get the selector from a locator object in playwright?

I'm using the page-object-model in developing my automated tests in playwright. As such, I'm building a class to hold my locators and expose the locators, but not necessarily the used selector. Does the locator have a way to share its selector?

+
exports.MyWebPageModel = class MyWebPageModel {
+  constructor(page) {
+    this.myMultiSelect = page.locator('#select-group select');
+    this.submitButton = page.locator('#submit-btn');
+  }
+}
+
+
test('validate multi-select submission', ({page}) -> {
+  const myPage = new MyWebPageModel(page);
+  const selectChoices = ['choice1', 'choice2', 'choice4'];
+  await myPage.myMultiSelect.selectOptions(selectedChoices);
+  Promise.all([
+    page.waitForNavigation(),
+    myPage.submitButton.click()
+  ]);
+
+  /* do tests on new page, click it's back button to return to previous page */
+
+  const allSelectedValues = await page.$eval(myPage.myMultiSelect.???, e => Array.from(e.selectedOptions).map(option => option.value));  // get the selected options from select element
+  expect(allSelectedValues).toEqual(selectedChoices);  // verify the selected options matches selectChoices.
+});
+
","

By doing the following:

+
const myLoc = page.locator('#myElement');
+Object.getOwnPropertyNames(myLoc).forEach(prop => { 
+  console.log(prop + " = " + row_locator[prop]); 
+});
+
+

I was able to discover there is a _selector, which returns the internal selector used for the Locator object.

+

So the answer is to use the locator's "private" property _selector. This is the value that is used when generating a locator error.

+

So, given a table:

+
<table id="colors">
+  <thead>
+  <trow>
+    <th>Key</th>
+    <th>Color</th>
+  </trow>
+  </thead>
+  <tbody>
+  <trow>
+    <td>R</td><td>Red</td>
+  </trow>
+  <trow>
+    <td>B</td><td>Blue</td>
+  </trow>
+  <trow>
+    <td>G</td><td>Green</td>
+  </trow>
+  </tbody>
+</table>
+
+

And, perhaps you build your playwright object as follows:

+
exports.ColorTable = class ColorTable {
+  constructor(page) {
+    this.page = page;
+    this.table = this.page.locator("#colors");
+    this.tableData = this.table.locator('tbody tr');
+  }
+}
+
+

The result of the following

+
const myT = new ColorTable(page);
+console.log(myT.tableData._selector);
+
+

might look like: Locator@#colors >> tbody tr

",r +"Haskell - Sort by first second element and then by first element

I have a list of tuples and I would like to sort it by second element (descending) and then by first element (ascending).

+

My code looks like this:

+
sortedOcc :: Eq a => [a] -> [(a, Int)]
+sortedOcc = sortBy (flip compare `on` snd) . occurences
+
+

and this is the first sorting by the second element of list returned by occurences (function). How should I add the second sort (ascending) by the first element?

","

The Data.Ord module provides a Down newtype whose purpose is solely to reverse the ordering.

+

It also provides a comparing function:

+
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
+
+

which must be fed some transformation function before it can be passed to sortBy.

+

Like this:

+
$ ghci
+ GHCi, version 8.8.4: https://www.haskell.org/ghc/  :? for help
+ λ> 
+ λ> sortBy  (comparing (\(a,v) -> (Down v, a)))   [(1,2),(1,3),(5,2),(5,3)]
+ [(1,3),(5,3),(1,2),(5,2)]
+ λ> 
+
+

The values returned by the transformation function are then sorted using their own “natural” order. In our case, this is the lexicographic order on pairs of ordered types.

+

Overall, the code would require an Ord a constraint:

+
sortedOcc :: Ord a => [a] -> [(a, Int)]
+sortedOcc = sortBy (comparing (\(a,v) -> (Down v, a)))  .  occurences
+
",r +"how to brace initialize vector of custom class in C++?

Having this simple code:

+
#include <iostream>
+#include <vector>
+#include <string>
+
+class Person{
+public:
+    Person(std::string const& name) : name(name) {}
+    std::string const& getName() const {
+        return name;
+    }
+private:
+    std::string name;
+};
+
+int main(){
+//    std::vector<int> ar = {1,2,3};
+    std::vector<Person> persons = {"John", "David", "Peter"};
+}
+
+

I am getting error:

+
could not convert ‘{"John", "David", "Peter"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Person>’
+
+

So why vector of ints is enabled to brace-initialize, but custom class with implicit constructor (with std::string) cannot? And how to enable it?

","

You just need more braces:

+
std::vector<Person> persons = {
+    {"John"}, {"David"}, {"Peter"}
+};
+
",r +"Pass a string in payload of POST

Usually we pass key-value pair in JSON payload for POST/PUT request. Is it possible to pass a sting only ex: +

+

If so what do we set the object for @RequestBody? Would it be String type or JSONObject?

","

What worked for me is setting

+
@PutMapping(value = "/test/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
+String updateInfo(@RequestHeader(@PathVariable("id") String id, @RequestBody String payload){...}
+
+

and passing the string payload by escacping the double quotes

+
updateInfo(token, id, "\"TEST\"");
+
",r +"AWS RDS: error: password authentication failed for user ""ubuntu"" from EC2

I have a postgres RDS instance which my Node.js web application running on an EC2 instance is not able to connect to. The error in my EC2 node logs is: error: password authentication failed for user "ubuntu"

+

I can confirm that I have the right username, password, database name, etc because it is working correctly on the development build on my machine. I copied all the .env parameters exactly into my ec2 machine for the production build. When attempting to connect to RDS on my production application web page, it fails. I have restarted my Node.js server multiple times and have rebooted the whole ec2 machine. I have confirmed that the env variables are there with printenv.

+

What would you recommend trying to fix this issue?

+

EDIT for more details: My nodejs setup should be correct because my nodejs server will call some external APIs that do not require my postgres database and those calls work properly.

+

EDIT2: This is strange because my username for RDS is postgres, while my username for EC2 is ubuntu. I wonder if somehow there's some clash between env variables. I checked printenv but didn't find any though

+

EDIT3: See comments for my workaround.

",

I would suggest to test the database credentials by directly connecting to RDS database using psql client on EC2 instance.

,r +"How to list only enabled local administrators

Trying to list only local administrator accounts that are enabled on windows workstations.

+

Have this code so far but I am running into issues beyond this point trying to compare if the active user is an administrator.

+
$enabledUsers = (Get-LocalUser | Select * | sort Name, FullName, Enabled) | where-object enabled -eq $true
+
+$enabledUsers | Select Name, Fullname
+
","

You can use Get-LocalGroupMember to get all members of the Administrators group, however this cmdlet doesn't tell us if the returned users are Enabled, we can pass the SID of each user to Get-LocalUser and filter for those Enabled ones:

+
Get-LocalGroupMember Administrators | Where-Object { (Get-LocalUser $_.SID -EA 0).Enabled }
+
+

-EA 0 (-ErrorAction SilentlyContinue) is used in this example because the members of the group may not be of the class User, in which case, the cmdlet would throw an error (which we want to avoid).

+

If you need LocalUser objects instead of LocalPrincipal objects, you can use this instead:

+
Get-LocalGroupMember Administrators | ForEach-Object {
+    if(($usr = Get-LocalUser $_.SID -EA 0) -and $usr.Enabled) {
+        $usr | Select-Object Name, FullName
+    }
+}
+
",r +"gRPC streaming call which takes longer than 2 minutes is killed by hardware (routers, etc.) in between client and server

Grpc.Net client:

+
    +
  • a gRpc client sends large amount of data to a gRpc server
  • +
  • after the gRpc server receives the data from the client, the http2 channel becomes idle (but is open) until the server returns the response to the client
  • +
  • the gRpc server receives the data and starts processing it. If the data processing takes longer than 2 minutes (which is the default idle timeout for http calls) then the response never reaches the client because the channel is actually disconnected, but the client does not know this because it was shutdown by other hardware in between due to long idle time.
  • +
+

Solution:

+
    +
  • when the channel is created at the gRpc client side, it must have a httpClient set on it
  • +
  • the httpClient must be instantiated from a socketsHttpHandler with +the following properties set (PooledConnectionIdleTimeout, PooledConnectionLifetime, KeepAlivePingPolicy, KeepAlivePingTimeout, KeepAlivePingDelay)
  • +
+

Code snipped:

+
SocketsHttpHandler socketsHttpHandler = new SocketsHttpHandler()
+{
+    PooledConnectionIdleTimeout = TimeSpan.FromMinutes(180),
+    PooledConnectionLifetime = TimeSpan.FromMinutes(180),
+    KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
+    KeepAlivePingTimeout = TimeSpan.FromSeconds(90),
+    KeepAlivePingDelay = TimeSpan.FromSeconds(90)
+};
+
+socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
+
+HttpClient httpClient = new HttpClient(socketsHttpHandler);
+httpClient.Timeout = TimeSpan.FromMinutes(180);
+
+var channel = GrpcChannel.ForAddress(_agentServerURL, new GrpcChannelOptions
+{
+    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
+    MaxReceiveMessageSize = null,
+    MaxSendMessageSize = null,
+    MaxRetryAttempts = null,
+    MaxRetryBufferPerCallSize = null,
+    MaxRetryBufferSize = null,
+    HttpClient = httpClient
+});
+
","

this is what I needed. I had this problem for months now, but my only solution was to decrease the volume of data.

",r +"Pyshark get specific protocol name not just TCP/UDP

I'm building a tool to inspect PCAP files using PyShark, however am struggling to extract the specific protocols from the packets (e.g. SSH, MQTT, ARP) rather than just TCP or UDP.

+

I'm wondering if anyone has experience with this? I've tried packet.ip.proto but that just returns TCP and UDP ID numbers, not names such as SSH or ARP.

+

I'm trying to get the same information as Wireshark shows in the below example: +

+

Thanks!

","

Think I've figured it out. Looks like each specific type of protocol adds its own layer to the packet, so by printing out all the layers in a packet, you can identify any non-standard layers.

+
with pyshark.FileCapture(TEST_FILE) as cap:
+    for i, pkt in enumerate(cap):
+        print(pkt.layers)
+
+

Output:

+
[<ETH Layer>, <IP Layer>, <TCP Layer>, <SYNERGY Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>, <SYNERGY Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>, <SYNERGY Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>, <SSH Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>, <SSH Layer>]
+[<ETH Layer>, <IP Layer>, <TCP Layer>, <SSH Layer>]
+
+

You can get a usable list of the layer names like so:

+
with pyshark.FileCapture(TEST_FILE) as cap:
+    for i, pkt in enumerate(cap):
+        try:
+            print([pkt.layers[i].layer_name for i, lay in enumerate(pkt.layers)])
+        except AttributeError as ex:
+            print(ex)
+
+

Output:

+
['eth', 'ip', 'tcp', 'synergy']
+['eth', 'ip', 'tcp', 'synergy']
+['eth', 'ip', 'tcp', 'synergy']
+['eth', 'ip', 'tcp']
+['eth', 'ip', 'tcp', 'ssh']
+['eth', 'ip', 'tcp', 'ssh']
+['eth', 'ip', 'tcp', 'ssh']
+
",r +"Strategy: Understanding strategy.exit() and strategy.close(). How to decide which one should be used?

In a strategy template I found and established my understanding on, both strategy.exit() and strategy.close() are included after strategy.entry() but in the manual, there's only one of them, see below:

+

Strategy.Exit

+
//@version=5
+strategy(title = "simple strategy exit example")
+strategy.entry("long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
+strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"
+
+

Strategy.Close

+
//@version=5
+strategy("closeEntry Demo", overlay=false)
+strategy.entry("buy", strategy.long, when = open > close)
+strategy.close("buy", when = open < close, qty_percent = 50, comment = "close buy entry for 50%")
+plot(strategy.position_size)
+
+

How to decide which should be used in a certain case? Should they both be used? Which one is for what?

+

I can see that strategy.exit() has more arguments to be specified.

+
strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, when, alert_message) → void
+
+strategy.close(id, when, comment, qty, qty_percent, alert_message) → void
+
+

I may prefer strategy.exit() if I'm not wrong…?

","

Use strategy.exit() when you want to exit when the price reaches to a calculated value (TP/SL). In fact, you must have at least one of the following parameters: profit, limit, loss, stop or else it will throw an error.

+

To close the position at market price, use strategy.close().

",r +"Flutter Getx Store Data locally

I am currently working on an app where the user can mark ListTimes as favorites. +These favorites are then displayed on a second page.

+

I am using GetX for this and the functionality works. But as soon as the app gets closed the state of the app resets and the favorites are deleted.

+

Does anyone knows how I can store the favorites locally?

+

Here is my code:

+

GetX controller:

+
import 'package:get/state_manager.dart';
+
+class FavouriteController extends GetxController {
+  var favItems = <Entries>[].obs;
+  int get count => favItems.length;
+
+  addToCart(Entries product) {
+    favItems.add(product);
+  }
+
+

Favorites page:

+
import 'package:flutter/material.dart';
+import 'package:get/get.dart';
+
+
+class Favs extends StatelessWidget {
+  final favouritesController = Get.put(FavouriteController());
+  final entriesController = Get.put(EntriesController());
+
+  Favs({Key? key}) : super(key: key);
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      backgroundColor: backGround,
+      appBar: AppBar(
+        backgroundColor: appbarColor,
+        title: const Text('Favs'),
+      ),
+      body: SafeArea(
+        child: Column(
+          children: [
+            const SizedBox(height: 10),
+            Expanded(
+              child: GetX<FavouriteController>(
+                builder: (controller) {
+                  return ListView.builder(
+                    itemCount: controller.favItems.length,
+                    itemBuilder: (context, index) {
+                      return Card(
+                          margin: const EdgeInsets.all(12),
+                          color: container,
+                          shape: RoundedRectangleBorder(
+                              borderRadius: BorderRadius.circular(15.0)),
+                          child: ListTile(
+                            title: Text(
+                              controller.favItems[index].name,
+                              style: const TextStyle(
+                                  fontSize: 16, color: Colors.white),
+                            ),
+                            trailing: IconButton(
+                              onPressed: () {
+                                favouritesController
+                                    .deleteEntries(controller.favItems[index]);
+                              },
+                              icon: const Icon(
+                                Icons.delete_forever,
+                                color: titleColor,
+                              ),
+                            ),
+                            onTap: () {
+                              Navigator.push(
+                                  context,
+                                  MaterialPageRoute(
+                                      builder: (context) => controller
+                                          .favItems[index].navigation));
+                            },
+                          ));
+                    },
+                  );
+                },
+              ),
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
","

With sqflite you can store data on device.

+

terminal:

+
+

flutter pub add sqflite and flutter pub get

+
import 'package:sqflite/sqflite.dart';
+
+
+
// Get a location using getDatabasesPath
+var databasesPath = await getDatabasesPath();
+String path = join(databasesPath, 'demo.db');
+
+// Delete the database
+await deleteDatabase(path);
+
+// open the database
+Database database = await openDatabase(path, version: 1,
+    onCreate: (Database db, int version) async {
+  // When creating the db, create the table
+  await db.execute(
+      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
+});
+
+// Insert some records in a transaction
+await database.transaction((txn) async {
+  int id1 = await txn.rawInsert(
+      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
+  print('inserted1: $id1');
+  int id2 = await txn.rawInsert(
+      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
+      ['another name', 12345678, 3.1416]);
+  print('inserted2: $id2');
+});
+
+// Update some record
+int count = await database.rawUpdate(
+    'UPDATE Test SET name = ?, value = ? WHERE name = ?',
+    ['updated name', '9876', 'some name']);
+print('updated: $count');
+
+// Get the records
+List<Map> list = await database.rawQuery('SELECT * FROM Test');
+List<Map> expectedList = [
+  {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
+  {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
+];
+print(list);
+print(expectedList);
+assert(const DeepCollectionEquality().equals(list, expectedList));
+
+// Count the records
+count = Sqflite
+    .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
+assert(count == 2);
+
+// Delete a record
+count = await database
+    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
+assert(count == 1);
+
+// Close the database
+await database.close();
+
+

(is a quote)

+

More detailed information: https://pub.dev/packages/sqflite

",r +"How to Iterate over a parameter pack

I need to define a function with template parameter pack with C++14.

+

The caller of the function makes sure that the size of Args... must be even, such as 2, 4, 6... And my function will pass them two by two to two functions.

+
template<typename F, typename F2, typename... Args>
+void func(F f, F2 f2, Args&&... params) {
+    using params_t = std::tuple<Args...>;
+    auto tp = std::make_tuple(params...);
+    for (std::size_t i = 0; i < sizeof...(Args); ++i) {
+        f(std::get<i>(tp));
+        f2(std::get<++i>(tp));
+    }
+}
+
+// caller
+func(f1, f2, "abc", 3, "def", "ppp");
+
+

This won't work because i is not a constant expression.

+

What could I do? Is it the right and the only way to iterate over a parameter pack with std::tuple?

","

To use a std::tuple to iterate over a parameter pack, you would usually use a std::index_sequence to introduce a new pack of indices, and use a fold expression to do the actual iteration. Something like this:

+
template<typename F, typename F2, typename... Args, std::size_t... I>
+void func_impl(F& f, F2& f2, std::tuple<Args...> params, std::index_sequence<I...>) {
+    // This would be a fold expression over a comma in C++17:
+    /*
+    (([&]{}(
+        f(std::get<I*2>(params));
+        f2(std::get<I*2+1>(params));
+    )), ...);
+    */
+    // C++14 version
+    using consume = int[];
+    (void) consume{ 0, [&]{
+        f(std::get<I*2>(params));
+        f2(std::get<I*2+1>(params));
+        return 0;
+    }()... };
+}
+
+template<typename F, typename F2, typename... Args>
+void func(F f, F2 f2, Args&&... args) {
+    static_assert(sizeof...(args) % 2 == 0, "Must pass a multiple of 2 args to func");
+    func_impl(
+        f, f2,
+        std::forward_as_tuple(std::forward<Args>(args)...),
+        std::make_index_sequence<sizeof...(args) / 2>{}
+    );
+}
+
+

But you can also iterate with recursion, which might be easier in your case:

+
template<typename F, typename F2>
+void func(F&& f, F2&& f2) {
+    // base case: do nothing
+}
+
+template<typename F, typename F2, typename Arg1, typename Arg2, typename... Args>
+void func(F&& f, F2&& f2, Arg1&& arg1, Arg2&& arg2, Args&&... args) {
+    // recursive case
+    f(arg1);
+    f2(arg2);
+    func(std::forward<F>(f), std::forward<F2>(f2), std::forward<Args>(args)...);
+}
+
",r +"Why do I keep getting ""Missing/Malformed URL Parameters"" when consuming my API in C# (RestSharp) with VS 2022?

I'm trying to do a POST request in C#, using RestSharp, in Visual Studio 2022.

+

I tested the API using Postman, which was successful. The API requires a 64-bit encoded Basic Auth (which I have), and a unique API key (which I also have). I then looked at the C# Restsharp code provided by Postman, and tried to copy paste it into my VS project, but most of the libraries were deprecated. I then ended up modifying the code so it didn't give me any errors, and the code itself runs, but getting a semantic error: the request returns "Missing or Malformed URL parameters". In the body parameter, I send one parameter in the form

+
var body = @"{""fieldNameHere"": intHere}"; 
+
+

My full code (redacted):

+
        var options = new RestClientOptions("URLHERE")
+        {
+            Timeout = -1
+        };
+        var client = new RestClient(options);
+        var request = new RestRequest
+        {
+            Method = Method.Post
+        };
+
+        request.AddHeader("API_KEY", "keyHere");
+        request.AddHeader("Authorization", "authHere");
+        request.AddHeader("Content-Type", "application/json");
+        var body = @"{""fieldNameHere"": intHere}";
+        request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
+        request.RequestFormat = DataFormat.Json;
+
+        RestResponse response = await client.ExecuteAsync(request);
+
+

So I tried using a JObject for the parameter, got the same error, this is my code:

+
        JObject jObjectBody = new JObject();
+        jObjectBody.Add("FieldName", intHere);
+
+        request.AddParameter("application/json", jObjectBody, ParameterType.RequestBody);
+
+            var clientValue = await client.ExecuteAsync(request);
+
+        
+
+

I also tried using HttpWebRequest, but got an auth error so not sure what was going on there, didn't get that anywhere else. Would prefer to use RestClient anyway. This is the other way I tried to do the body parameter:

+
string postData = "{\"FieldNameHere\":" + intHere + "}";
+byte[] byteArray = Encoding.UTF8.GetBytes(postData);
+
+

I haven't found anything that works yet. If someone can guide me towards a solution I'd be mad grateful, thanks. It definitely seems to be the body giving me the issue.

","

Ah! For some reason, phrasing my body like this worked:

+
var body = new { FieldNameHere = intHere }
+request.AddJsonBody(body);
+
+

I have no idea why this worked, but it did!

+

A list of things that DID NOT work:

+
    +
  • JObject technique
  • +
  • switching header placement
  • +
  • encoding the auth myself
  • +
  • how the RR instantiation is set up
  • +
  • with and without explicitly saying application/json (also including the charset and excluding)
  • +
  • using HttpWebRequest instead of RestSharp
  • +
",r +"React - Set state object using args

I have an object saved in a state I am trying to create a function to update parts of the object.

+
function removeError(val) {
+    setPersonsState((prevState) => ({
+      ...prevState,
+      val: "",
+    }));
+  }
+
+

I have tried to pass val to the object key to update it.

+

onClick={removeError('Bob')}

+

Where Bob replaces val to update in the object. Sorry if terminology is bad.

","

Well, you should change it to be in the following way, sine you don't want to change a key named val, but the key with name equal to the value of val

+
function removeError(val) {
+    setPersonsState((prevState) => ({
+        ...prevState,
+        [val]: "",
+    }));
+}
+
+

And, as suggested in the comments by @RoshanKanwar, also the click handler is not correct, it should be

+
onClick = {() => removeError('Bob')}
+
",r +"specify a variable name in a dataframe, using an element from list

I'm trying to use an element from a list to specify a variable name in a dataframe. +I know I can create a dataframe like this, creating variable A and C

+
list_A <- c(1,3,6,9,10)
+List_C <- c(2,3,5,6,10)
+df <- data.frame( A = list_A , C = List_C ) 
+> df
+   A  C
+1  1  2
+2  3  3
+3  6  5
+4  9  6
+5 10 10
+
+

However, I'd like to specify the variable names from elements from a list, in this manner

+
nameslist <- c("A","B","C")
+df <- data.frame( eval(parse(text=nameslist[1])) = List_A , eval(parse(text=nameslist[3])) = List_C ) 
+
+

I tried this, but cant get this code to run. Is there a way to adjust the "eval/parse" bit to make this work? Many thanks in advance.

","
nameslist <- c("A","B","C")
+setNames(data.frame(sapply(nameslist[c(1,3)], \(x) 1:5)), nameslist[c(1,3)])
+
+

Or, if you simply had a set of values_for_A and a set of values_for_C, you could do something like this:

+
setNames(data.frame(list(values_for_A, values_for_C)), nameslist[c(1,3)])
+
",r +"Background-color for area below line chart in chartJs?

I am creating a chart to render some data using chart js.

+
  const data = {
+    labels: ["1 Dec", "8 Dec", "16 Dec", "31 Dec"],
+    datasets: [
+      {
+        label: "Sales Made",
+        data: [3, 7, 4, 5],
+        borderColor: ["#03A9F5"],
+      },
+    ],
+  };
+  const options = {
+    tension: 0.4,
+    title: {
+      display: true,
+      text: "linechrt",
+    },
+    scales: {
+      y: [
+        {
+          display: true,
+          stacked: true,
+          ticks: {
+            beginAtZero: true,
+            steps: 10,
+            stepValue: 5,
+            min: 0,
+            max: 100,
+          },
+        },
+      ],
+    },
+  };
+
+

now I've looked at online tutorials and even the documentation but I've not gotten a clear answer on how to paint the area below the line. ChartJs has a lot of versions and previous answers to this question especially here on Stack don't seem to work.

+

For other charts like bar the code

+
backGroundColor: ["red"]
+
+

on the datasets object works fine but if I try to do the same for a line chart it doesn't. The top +label icon that you click to hide or show the chart is the only one that seems to respond to the background color change. The area below the line doesn't. Please help.

+
<Line data={data} options={options} />
+
","

You need to set fill to true in your dataset. And depending on if you are using treeshaking you also will need to import and register filler from chart.js.

+
  const data = {
+    labels: ["1 Dec", "8 Dec", "16 Dec", "31 Dec"],
+    datasets: [
+      {
+        label: "Sales Made",
+        data: [3, 7, 4, 5],
+        borderColor: ["#03A9F5"],
+        fill: true,
+        backgroundColor: 'pink'
+      },
+    ],
+  };
+
",r +"Generate results like '2015-16 season' for values like '1516REG' for this value and other years in the future

As of now I'm handling the situation as shown below. But it is going to be a problem going forward in the future. Do I need to come up with a new table and do a join or is there any regex or substring I can use in the select statement?

+

+

I'm having a table with some values like this. So when a new value like 2223REG comes up I need to return 2022-23 Season.

+
season
+-------
+2021REG \n
+2122REG \n
+1516REG \n
+
","

I would remove that case expression. It is cumbersome and not at all dynamic. You could use STUFF for this. Might a need a little tweaking if you plan on running this code in 80 years. But it will work fine until the year 2100.

+
declare @Something table(SomeVal varchar(20))
+
+insert @Something
+select '2021REG \n' union all
+select '2324REG \n'
+
+select '20' + stuff(left(s.SomeVal, 4), 3, 0, '-') + ' Season'
+from @Something s
+
",r +"What's the worst space complexity of a loop which create an arrayat each iteration

I am struggling to find a proper definition of worst space complexity whether it is the sum of the total amount of the algorithm used or if it is only the space consumed by the algorithm at a critical time, the worst one.

+

As an example:

+
void myFunc(n) {
+  for(int j = 0; j < n ; ++j) {
+     int* myTab = malloc(n*sizeof(int));
+     for(int i = 0; i < n; ++i) {
+        myTab[i] = 1;
+     }
+      free(myTab);
+   }
+}
+
+

For the first definition it is roughly O(N²) and for the second one O(N).

","

It would be O(n). You are explicitly freeing up the memory after the assignment is done. I agree the inner workings of the malloc would be useful but assuming a normal implementation which doesn't use memory enough to change the space complexity ( For tracking O(n) memory allocation it keeps O(n^2) amounts of metadata - just a weird example).

+

An interesting point, to clear up your idea. If you comment out this free(..) line, then the space complexity would be O(n^2). This is what is known as memory leakage.

",r +"website scraping not showing full html elements

I'm new to the world of programming and I've been trying to scrape a web site https://www.boove.se/butiker/mc but its not showing the full HTML elements of the website.

+

my code:

+
   from selenium import webdriver
+   from selenium.webdriver.chrome.service import Service
+
+   chromedriver_path = "C:\chromedriver_win32\chromedriver.exe"
+   driver = webdriver.Chrome(service=Service(chromedriver_path))
+   url = "https://www.boove.se/butiker/mc"
+   driver.get(url)
+   content = driver.find_elements(by=By.CSS_SELECTOR, value= "h3 .address desktop")
+   print(content)
+   driver.close()
+
","

There are two issues with your code:

+
    +
  • It needs the correct css selector to find the elements

    +
  • +
  • You have to wait until the elements are located

    +
    wait = WebDriverWait(driver, 10)
    +wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'h3.address.desktop')))
    +
    +
  • +
+
Example
+
from selenium import webdriver
+from selenium.webdriver.common.by import By
+from webdriver_manager.chrome import ChromeDriverManager
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+
+url = 'https://www.boove.se/butiker/mc'
+
+driver = webdriver.Chrome(ChromeDriverManager().install())
+driver.maximize_window()
+driver.get(url)
+
+wait = WebDriverWait(driver, 10)
+wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'h3.address.desktop')))
+
+content = driver.find_elements(By.CSS_SELECTOR, 'h3.address.desktop')
+
+for i in content:
+    print(i.text)
+driver.close()
+
+
Output
+
Odenskogsvägen 35, 83148 Östersund
+STORGATAN 43, 77100 Ludvika
+INÄLVSVÄGEN 1, 69152 Karlskoga
+VÄNE-RYR, 46293 Vänersborg
+Västbergavägen 24, 12630 Hägersten
+TENNGATAN 15, 23435 Lomma
+HÄGERSTENS ALLE 12, 12937 Hägersten
+SÅGVÄGEN 11A, 18440 Åkersberga
+Sollentuna, 19278 Rotebro
+Kuskvägen 2, 19162 Sollentuna
+Mölndalsvägen 25, 41263 GÖTEBORG
+SALAVÄGEN 5, 74537 Enköping
+Lundbygårdsgata 3, 72134 Västerås
+...
+
",r +"What difference between select and without select in NgRx?

I have two ways usually use when I subscribe to a state of a store. +Is it any difference between them (like performance or something)

+
constructor(private store : Store<MyState>){
+    //1
+    this.store.pipe(select(x=>x.myComplexObject)).subscribe(x=> {
+        this.data = x;
+    })
+    //2
+    this.store.subscribe(x=> {
+        this.data = x.myComplexObject;
+    })
+}
+
","

Both are the same. +But, I would suggest moving to selectors because these have several advantages:

+
    +
  • multiple selectors can be combined
  • +
  • easy to test
  • +
  • performant because it's memoized
  • +
+

https://ngrx.io/guide/store/selectors

",r +"is it possible to have two parameters in limit_choices_to in django models?

I'll shorten the code as simple as possible. Supposedly, we do have two models.

+

models.py > Products table

+
CATEGORY = (
+    ('Hard Disk Drive', 'Hard Disk Drive'),
+    ('Solid State Drive', 'Solid State Drive'),
+    ('Graphics Card', 'Graphics Card'),
+    ('Laptop', 'Laptop'),
+    ('RAM', 'RAM'),
+    ('Charger', 'Charger'),
+    ('UPS', 'UPS'),
+    ('Mouse', 'Mouse'),
+    ('Keyboard', 'Keyboard'),
+    ('Motherboard', 'Motherboard'),
+    ('Monitor', 'Monitor'),
+    ('Power Supply', 'Power Supply'),
+    ('Router', 'Router'),
+    ('AVR', 'AVR'),
+    ('Tablet', 'Tablet'),
+    ('System Unit', 'System Unit'),
+    ('Audio Devices', 'Audio Devices'),
+    ('CPU', 'CPU'),
+    ('Others', 'Others'),
+)
+
+class Product(models.Model):
+model_name = models.CharField(max_length=100, null=True, blank=True)
+asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True)
+date = models.DateField(null=True, blank=True)
+
+

And the other table > Order table

+
class Order(models.Model):
+product_order = models.ForeignKey(Product, on_delete=models.CASCADE, null=False)
+employee = models.ForeignKey(User, models.CASCADE, null=False)
+date = models.DateTimeField(auto_now_add=True)
+remarks = models.TextField()
+
+

And we all know that adding this code will limit the foreignkey choices under the Order form.

+
limit_choices_to={"asset_type": "Hard Disk Drive"}
+limit_choices_to={"asset_type": "Solid State Drive"}
+
+

My goal here is to show items from Products table whose asset_type is either "Hard Disk Drive" OR "Solid State Drive". I've read the documentation of Django for "limit_choices_to" and can't see any pertaining to some kind of solution in here. Thank you in advance who knows a way to make this possible.

","

You can work with the __in lookup [Django-doc] to specify a list of allowed values:

+
class Order(models.Model):
+    product_order = models.ForeignKey(
+        Product,
+        on_delete=models.CASCADE,
+        limit_choices_to=dict(asset_type__in=['Hard Disk Drive', 'Solid State Drive'])
+    )
+    # …
+
+
+

Note: Specifying null=False [Django-doc] is not necessary: fields are by default not NULLable.

+
+
+
+

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

+
",r +"Run react native application on windows with npx react-native run-windows

I created a test app with react native via npx react-native init Test --template react-native-template-typescript (https://reactnative.dev/docs/typescript).
+This seems to work fine, although it cant find the typescript template (log as text +| log as pictures).
+Now I cd into the created directory with cd Test, and run npx react-native-windows-init --overwrite according to the docs. This works fine, log here.
+When I now run npx react-native run-windows as its being said in the documentation, I get the error message Build failed with message Building Solution - error code 1. Check your build configuration (log here or picture)

+

What I tried:

+
    +
  • running the rnw-dependencies.ps1 file a) from the pc and b) via Set-ExecutionPolicy Unrestricted -Scope Process -Force; iex (New-Object System.Net.WebClient).DownloadString('https://aka.ms/rnw-deps.ps1') in an elevated power shell. This resulted in an big error message when I try to install the Compilers, build tools, SKDs and Visual Studio. The error message is pretty big, you can find the full log of the powershell here or pictures. - UPDATE: installed every component by hand, now running rnw-dependencies.ps1 causes no error anymore, everything is Ok; however the build error still persists
  • +
  • installing the MSVC v143 - VS 2022 C++-x64/x86-Buildtools (latest) component with Visual Studio
  • +
  • installing the Windows 10 SDK (10.0.19041.0)
  • +
+

What I am using:

+
    +
  • Windows 10
  • +
  • nvm v1.1.7
  • +
  • node v14.18.1, I stepped down because one on the internet suggested that, also available are v17.5.0 and v12.18.3, both dont work
  • +
  • Visual Studio Community 2022 - 17.1.0 (installed components and workloads picture here)
  • +
  • npx v6.14.15
  • +
  • react-native-cli v2.0.1
  • +
  • yarn v1.22.15
  • +
","

I fixed it by installing the Visual Studio 19 version. Apperently, the 2022 version doesnt work.

",r +"How to change id of datatable?

I have some websocket listening code that already do good things when receiveing some events.

+

I now need to force reloading of datatable ONLY if I am in a specific page.

+

I'd like to specify the id the of the datatable iteself (or add a data-, or add a class) in the List Operation, so i can check presence and do specific things only if user is watching the specific class

+

How can I customize the datatable in the List Operation (without ovverride the .blade.php) to add id, class or data- to the datatable?

","

In short - you can't. But maybe you can:

+

(A) force reload the datatable only if on the correct route;

+

(B) force reload the datatable if something is present in the DOM; and you can add things to the page using widgets;

",r +"How do I add .so file to lib folder in APK?

If I add the following to my cmakelists.txt file:

+
add_library( # Sets the name of the library.
+        extralib
+
+        # Sets the library as a shared library.
+        MODULE
+
+        # Provides a relative path to your source file(s).
+        extra.cpp)
+
+

and I build my Android application, then the APK will have libextralib.so in its 'lib' folder. In the above case, 'extralib' is built from a source code file (extra.cpp). How can I use a pre-built .so file as 'source' for extralib?

+

I tried:

+
add_library( # Sets the name of the library.
+        extralib
+
+        # Sets the library as a shared library.
+        MODULE
+
+        # Provides a relative path to your source file(s).
+        extra.so)
+
+

but Android Studio does not like that. I get the following error:

+

CMake Error: CMake can not determine linker language for target: extralib

+

I am trying to figure out how I can add extra .so files to the APK lib folder (they will be loaded at dynamically at runtime) where some .so files are built from source code while others are prebuilt .so files. I know I can just create a jniLibs folder and stuff all my .so files into that folder, but I don't want to do that. I want it all defined in cmakelists.txt instead.

","

This method should still work:

+
 add_library(lib_extra SHARED IMPORTED)
+ set_target_properties(lib_extra PROPERTIES IMPORTED_LOCATION
+    ${your-extra-lib-location}/${ANDROID_ABI}/libextra.so)
+ 
+ target_link_libraries(${project-lib-name} lib_extra)
+
+

Make sure you have a binary(extra.so) for each ABI you plan to include in your app. After build APK, you can check they are there with Studio's build -> Analyze APK... (or just unzip the APK file).

",r +"Testing: how to access ""model_has_error_on_field""?

I was looking at Mastodon tests for inspiration, and I noticed this model_has_error_on_field method on their User model tests.

+

Anyone know from where this method is defined and how could I access it in my test suite ?

","

Found it, it's a custom Rspec::Matchers defined in mastodon/spec/support/matchers/model/model_have_error_on_field.rb

+
+If you want to use it: + +
Dir[Rails.root.join('spect', 'support', '**', '*.rb')].sort.each { |f| require f }
+
",r +"Firebase Database user's profileImageUrl not updating

I want to update firestore databases property profileImageUrl with my uploaded pictures storage url ( storage code works fine, I can see the uploaded image with its own URL ) any ideas ?

+
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
+    myImage = image
+    self.mainProfilePicImage.image = image
+} // where I choose image
+
+guard let imageData = self.mainProfilePicImage.image?.jpegData(compressionQuality: 0.4) else {
+    return
+} // compressing to jpeg
+
+let userID = Auth.auth().currentUser!.uid
+let storageRef = Storage.storage().reference(forURL: "gs://xxxxxxx.appspot.com/") // my firebase storage
+let storageProfileRef = storageRef.child("profile").child(userID)
+
+let metadata = StorageMetadata()
+metadata.contentType = "image/jpeg"
+storageProfileRef.putData(imageData,metadata: metadata) { (storageMetadata, error) in
+    if error != nil {
+    print("error")
+    }
+    storageProfileRef.downloadURL(completion: {(url,error) in
+        if let metaImageUrl = url?.absoluteString { // downloading url from storage of picked image 
+            print("meta image url: \(metaImageUrl)") // printing URL
+            let db = Firestore.firestore()
+            db.collection("users").document(userID).updateData([
+                "profileImageUrl": metaImageUrl,
+            ]) { err in
+                if let err = err {
+                    print("Error updating document: \(err)")
+                } else {
+                    print("Document successfully updated")
+                }
+            }
+        }
+    })
+}
+
+

","

The main problem was in my db.collection("users").document(userID) line, I found out that "users" document had different id, so I updated with code below:

+
                db.collection("users")
+                    .whereField("uid", isEqualTo: userID)
+                    .getDocuments() { (querySnapshot, err) in
+                        if let err = err {
+                            print("Couldnt update : \(err)")
+                        } else {
+                            let document = querySnapshot!.documents.first
+                            document!.reference.updateData([
+                                "profileImageUrl": url?.absoluteString
+                            ])
+                        }
+                    }
+
",r +"Get the first created user per organization
SELECT email, org_id, MIN(created_at) as first_user_created
+FROM users
+WHERE org_id IN (SELECT org_id FROM subscriptions)
+GROUP BY email, org_id;
+
+

Result of the above query gives me multiple user records per org_id.

+

What I want: Per organization - return the email, org_id and first_user_created of user that got created the earliest.

","

One solution uses DISTINCT ON:

+
SELECT DISTINCT ON (u.org_id) u.email, u.org_id, u.created_at
+FROM users u
+INNER JOIN subscriptions s
+    ON s.org_id = u.org_id
+ORDER BY u.org_id, u.created_at;
+
+

Another way to do this uses RANK():

+
WITH cte AS (
+    SELECT u.email, u.org_id, u.created_at,
+           RANK() OVER (PARTITION BY u.org_id ORDER BY u.created_at) rnk
+    FROM users u
+    INNER JOIN subscriptions s ON s.org_id = u.org_id
+)
+
+SELECT email, org_id, created_at
+FROM cte
+WHERE rnk = 1;
+
",r +"What’s the difference between Next.js rewrites and HTTP proxy middleware?

Just trying to figure out the differences between Next.js rewrites and setting up a proxy with http-proxy-middleware. I have a Next.js project with some proxies setup in the API and wondering if I can swap out the proxies for rewrites.

+

What are the differences, if any? Is there something I’m missing?

","

rewrites are a convenient way of proxying requests without having to setup your own logic in a server - Next.js handles it for you instead.

+

Just like http-proxy-middleware, they allow you to map an incoming request path to a different destination. The main difference is that rewrites are also applied to client-side routing, when using Next.js' built-in router (through next/link or next/router) to navigate between pages.

+

From the rewrites documentation:

+
+

Rewrites act as a URL proxy and mask the destination path, making it +appear the user hasn't changed their location on the site.

+

(...) Rewrites are applied to client-side routing, a <Link href="/about"> +will have the rewrite applied in the above example.

+
",r +"How to add multilevel expandable menu in drawer

I was trying to find a way to add sub-menus to this drawer and to collapse them on tap. +Ie: I want to call this widget with a title and 3 subtitles like :

+
    +
  • Flutter +
      +
    • List item
    • +
    • List item
    • +
    • List item
    • +
    +
  • +
+

Any help would be appreciated. +Thank you.

+
    class DrawerListTile extends StatelessWidget {
+  const DrawerListTile({
+    Key key, @required this.title,@required this.svgSrc,@required this.press,
+  }) : super(key: key);
+
+  final String title,svgSrc;
+  final VoidCallback press;
+  @override
+  Widget build(BuildContext context) {
+    return ListTile(
+      onTap:press,
+      horizontalTitleGap: 0.0,
+      leading: SvgPicture.asset(
+        svgSrc,
+        color: Colors.black,
+        height:16,
+      ),
+      title:Text(
+        title,
+        style: TextStyle(color: Colors.black),
+      ),
+      trailing: Icon(Icons.arrow_drop_down,size:15),
+    );
+  }
+}
+
","

I think the ExpansionTile widget is what you're looking for. +This would provide a tile that hides/shows the child tiles when it's tapped. You can also specify a custom trailing icon with the trailing parameter. Below is a quick example pulled from the docs.

+
Widget build(BuildContext context) {
+    return ExpansionTile(
+        title: Text('ExpansionTile'),
+        subtitle: Text('Expanding tile subtitle'),
+        children: <Widget>[
+          ListTile(title: Text('This is tile number 1')),
+          ListTile(title: Text('This is tile number 2')),
+          ListTile(title: Text('This is tile number 3')),
+          ListTile(title: Text('This is tile number 4')),
+        ],
+    );
+}
+
",r +"Why is there space between the img and the button and why doesn't the hover animation work?

When I run the file below, there is space between the img and the the button, why and how do I fix this issue?

+

Plus there seems to be no animation when I hover the div, but the cursor does change shape so why don't the other CSS rules work too? The transform: rotateY: (360deg); actually seems to work a little bit, but it looks like it only did very little.

+

+
+
body {
+  margin: 0%;
+}
+
+#Homepage {
+  margin: 5%;
+  font-family: sans-serif;
+}
+
+#Homepage .selection {
+  width: 40%;
+  position: relative;
+  display: flex;
+  flex-direction: column;
+  border: 5px solid;
+  border-radius: 20px;
+  overflow: hidden;
+}
+
+#Homepage .selection :hover {
+  cursor: pointer;
+  bottom: 100;
+  transform: rotateY(360deg);
+}
+
+#Homepage .selection img {
+  box-sizing: border-box;
+  width: 100%;
+}
+
+#Homepage .selection button {
+  width: 100%;
+    height: 100px;
+  border: none;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+    <head>
+        <meta charset=""utf-8"">
+        <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    </head>
+    <body>
+        <div id=""Homepage"">
+            <div class=""selection"" style=""float: left;"">
+                <a href=""#"" onclick=""show(SecondAttempt, Homepage);"">
+                    <img src=""https://via.placeholder.com/200x100.png?text=Lorem+Ipsum"" alt=""Preview of my second attempt to make a game"">
+                    
+                    <button type=""button""><h2><strong>2nd attempt to make a game</strong></h2></button>
+                </a>
+            </div>
+
+            <div class=""selection"" style=""float: right;"">
+                <a href=""#"" onclick=""show(ScrollingTest, Homepage);"">
+                    <img src=""https://via.placeholder.com/200x100.png?text=Lorem+Ipsum"" alt=""Preview of my second attempt to make a game"">
+                    
+                    <button type=""button""><h2><strong>Scrolling Test</strong></h2></button>
+                </a>
+            </div>
+        </div>
+    </body>
+</html>
+
+
+

","

To remove the space, add display: block; to the image

+

As of animation, I'm not quiet sure what animation supposed to be, and since you don't have any transition affects for tranform, the rotateY(360deg) simply rotates element to it's original state without any visual change.

+

+
+
body {
+  margin: 0%;
+}
+
+#Homepage {
+  margin: 5%;
+  font-family: sans-serif;
+}
+
+/* Note, added new DIV.inner container in HTML, without it, animation glitches when cursor is moving */
+#Homepage .selection > .inner {       /* changed */
+  width: 100%;                        /* changed */
+  position: relative;
+  display: flex;
+  flex-direction: column;
+  border: 5px solid;
+  border-radius: 20px;
+  overflow: hidden;
+}
+                                      /* added */
+#Homepage .selection {
+  width: 40%;
+}
+
+
+                                      /* added */
+/* uncomment this if you want reverse animation when cursor moves away */
+/*
+#Homepage .selection > .inner {       
+  transition: transform 1s;  
+}
+*/
+
+#Homepage .selection:hover > .inner { /* changed */
+  cursor: pointer;
+  bottom: 100;                        /* wrong value */
+  transition: transform 1s;           /* added */
+  transform: rotateY(360deg);
+}
+
+#Homepage .selection img {
+  box-sizing: border-box;
+  width: 100%;
+  display: block;                     /* added */
+}
+
+#Homepage .selection button {
+  width: 100%;
+    height: 100px;
+  border: none;
+}
+
+@keyframes left {
+  from {right: 10%;}
+  to {right: 0;}
+}
+
+@keyframes right {
+  from {left: 10%;}
+  to {left: 0px;}
+}
+
+                                   /* added */
+.selection.left
+{
+  float: left;
+}
+
+.selection.right
+{
+  float: right;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+    <head>
+        <meta charset=""utf-8"">
+        <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    </head>
+    <body>
+        <div id=""Homepage"">
+            <div class=""selection left"">
+              <div class=""inner"">
+                <a href=""#"" onclick=""show(SecondAttempt, Homepage);"">
+                    <img src=""https://via.placeholder.com/200x100.png?text=Lorem+Ipsum"" alt=""Preview of my second attempt to make a game"">
+                    
+                    <button type=""button""><h2><strong>2nd attempt to make a game</strong></h2></button>
+                </a>
+              </div>
+            </div>
+
+            <div class=""selection right"">
+              <div class=""inner"">
+                <a href=""#"" onclick=""show(ScrollingTest, Homepage);"">
+                    <img src=""https://via.placeholder.com/200x100.png?text=Lorem+Ipsum"" alt=""Preview of my second attempt to make a game"">
+                    
+                    <button type=""button""><h2><strong>Scrolling Test</strong></h2></button>
+                </a>
+              </div>
+            </div>
+        </div>
+    </body>
+</html>
+
+
+

",css +"Trying to get my grid go side by side instead of being stacked on top of each other

I'm trying to make a grid that is two columns and three rows. Right now i just have 1 big column i cant get them to go side by side.

+

+
+
.container {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  grid-template-rows: 1fr 1fr;
+  gap: 0px 0px;
+  grid-template-areas: ""fox llama"" ""wolf pangolin"" ""marmoset panda"";
+}
+
+.fox {
+  grid-area: fox;
+}
+
+.llama {
+  grid-area: llama;
+}
+
+.wolf {
+  grid-area: wolf;
+}
+
+.marmoset {
+  grid-area: marmoset;
+}
+
+.panda {
+  grid-area: panda;
+}
+
+.pangolin {
+  grid-area: pangolin;
+}
+
<div class=""container"">
+  <div class=""main-background"">
+    <div class=""fox"">
+      <h2 class=""fox"">FENNEC FOX</h2>
+      <img src=""./assets/images/fennec-fox.jpg"" alt=""FENNEC FOX"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+
+    <div class=""llama"">
+      <h2 class=""llama"">LLAMA</h2>
+      <img src=""./assets/images/llama.jpg"" alt=""LLAMA"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+    
+    <div class=""wolf"">
+      <h2 class=""wolf"">MANED WOLF</h2>
+      <img src=""./assets/images/maned-wolf.jpg"" alt=""MANED WOLF"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+
+    <div class=""pangolin"">
+      <h2 class=""pangolin"">PANGOLIN</h2>
+      <img src=""./assets/images/pangolin.jpg"" alt=""PANGOLIN"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+
+    <div class=""marmoset"">
+      <h2 class=""marmoset"">PYGMY MARMOSET</h2>
+      <img src=""./assets/images/pygmy-marmoset.jpg"" alt=""PYGMY MARMOSET"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+
+    <div class=""panda"">
+      <h2 class=""panda"">RED PANDA</h2>
+      <img src=""./assets/images/red-panda.jpg"" alt=""RED PANDA"">
+      <p></p>
+      <p class=""TLM"">TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a></p>
+    </div>
+    
+  </div>
+</div>
+
+
+

+

This is what i want the finished code to look like when it is correct.

+

https://imgur.com/a/fL41gcV

+

Just adding more text because it says i have to even though i dont know what else to add.

","

You have a .main-background inside of your .container with all the other elements in it. So the .container grid does not affect the elements but only the .main-background. Either move the .main-background out of the .container or use the .main-background as the grid. You could also close the .main-backgound inside the .container and position it absolute.

+

If you don't know how many rows your grid will have, you can use grid-auto-rows: 1fr;.

+

+
+
.main-background {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  grid-auto-rows: 1fr;
+  grid-template-areas:
+    ""fox llama""
+    ""wolf pangolin""
+    ""marmoset panda"";
+}
+
+.fox {
+  grid-area: fox;
+}
+
+.llama {
+  grid-area: llama;
+}
+
+.wolf {
+  grid-area: wolf;
+}
+
+.marmoset {
+  grid-area: marmoset;
+}
+
+.panda {
+  grid-area: panda;
+}
+
+.pangolin {
+  grid-area: pangolin;
+}
+
<div class=""container"">
+  <div class=""main-background"">
+    <div class=""fox"">
+      <h2 class=""fox"">FENNEC FOX</h2>
+
+      <img src=""./assets/images/fennec-fox.jpg"" alt=""FENNEC FOX"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+
+    <div class=""llama"">
+      <h2 class=""llama"">LLAMA</h2>
+
+      <img src=""./assets/images/llama.jpg"" alt=""LLAMA"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+
+    <div class=""wolf"">
+      <h2 class=""wolf"">MANED WOLF</h2>
+
+      <img src=""./assets/images/maned-wolf.jpg"" alt=""MANED WOLF"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+
+    <div class=""pangolin"">
+      <h2 class=""pangolin"">PANGOLIN</h2>
+
+      <img src=""./assets/images/pangolin.jpg"" alt=""PANGOLIN"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+
+    <div class=""marmoset"">
+      <h2 class=""marmoset"">PYGMY MARMOSET</h2>
+
+      <img src=""./assets/images/pygmy-marmoset.jpg"" alt=""PYGMY MARMOSET"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+
+    <div class=""panda"">
+      <h2 class=""panda"">RED PANDA</h2>
+
+      <img src=""./assets/images/red-panda.jpg"" alt=""RED PANDA"" />
+
+      <p></p>
+
+      <p class=""TLM"">
+        TO LEARN MORE <a href=""#"" target=""_blank"" class=""CH"">CLICK HERE</a>
+      </p>
+    </div>
+  </div>
+</div>
+
+
+

",css +"Can you have different transition times on the same transition property?

I have a settings button (img with an icon as the src) that I want to spin when the cursor is hovering, and then scale down and back to normal when the user presses on it.

+
#settings-button:hover {
+    transition: transform 1s ease-out;
+    transform: rotate(360deg);
+}
+
+#settings-button:active {
+    transition: transform 50ms ease-out;
+    transform: scale(0.90);
+}
+
+

With the current code, it scales down at the correct speed, but it takes 1s to get back to the normal size. If I change the duration in :hover it works fine, but then it spins so fast you can't see it.

+

Is there anyway to have different durations for the same transition property?

","

You can accomplish this with CSS Houdini.

+

But it's possible to achieve what you're looking for, by simply having 2 CSS animations and toggling between them with JavaScript. One will simply be faster or slower than the other.

",css +"How to align icons to the right

I have a menu with a bulleted list, I would like to align an arrow type icon to the right, but the alignments are not done exactly.

+

Here is an image below of my problem...

+

image

+

I think the problem is here?

+
.sidebar .nav-links li i {
+    min-width: 60px;
+    text-align: center;
+    font-size: 18px;
+    color: #fff;
+}
+
+

Here is a reproduction of the project.

+

HTML

+
<ul class="nav-links">
+  <li *ngFor="let menu of menus; let i = index" [class.active]="menu.active">
+    <ng-container>
+      <a class="item" (click)="selectMenu(menu)">
+        <i [class]="menu.iconClass"></i>
+        <span class="links_name">{{ menu.name }}</span>
+        <i class="fa fa-chevron-down"></i>
+      </a>
+      <ul
+        class="submenu"
+        #submenu
+        [ngStyle]="{ 'height': menu.active ? submenu.scrollHeight + 'px' : 0 + 'px' } "
+      >
+        <li *ngFor="let submenu of menu.submenu">
+          <a routerLink="{{ submenu.url }} "
+            ><span class="links_subname">{{ submenu.name }}</span>
+          </a>
+        </li>
+      </ul>
+    </ng-container>
+  </li>
+</ul>
+
+

CSS

+
.sidebar .nav-links {
+    margin-top: 10px;
+}
+
+.sidebar .nav-links li {
+    position: relative;
+    list-style: none;
+}
+
+.sidebar .nav-links li a {
+    height: 100%;
+    width: 100%;
+    display: flex;
+    align-items: center;
+    text-decoration: none;
+    transition: all 0.4s ease;
+    border-bottom: 1px solid #ccc;
+    padding: 13px 0;
+}
+
+.sidebar .nav-links li a.active {
+    background: #081D45;
+}
+
+.sidebar .nav-links li a:hover {
+    background: #081D45;
+}
+
+.sidebar .nav-links li i {
+    min-width: 60px;
+    text-align: center;
+    font-size: 18px;
+    color: #fff;
+}
+
+.sidebar .nav-links .item {
+    text-transform: uppercase;
+}
+
+.sidebar .nav-links li i.fa-chevron-down {
+    right: 1rem;
+    left: auto;
+}
+
+.sidebar .nav-links li.active i.fa-chevron-down {
+    transform: rotate(180deg);
+}
+
+.sidebar .nav-links li.active i {
+    color: white;
+}
+
+.sidebar .nav-links li a .links_name {
+    color: #fff;
+    font-size: 15px;
+    font-weight: 400;
+    white-space: nowrap;
+}
+
+

Thank you a lot for your help.

","

Use this:

+
.sidebar .nav-links li a {
+  display: flex;
+  justify-content: space-between;
+}
+
+

Remove the min-width: 60px; on the .navlinks li i and set flex-basis: 20%;.

",css +"Why is doesn't my content fill the full width in devtools responsive size

When visiting www.felkru.com and opening it in chrome devtools after resizing the window in responsive mode a bar appears on the right side of my content.The error also occures when zooming out on iOS. In Firefox, after following the same steps, no bar appears. How can I fix this?

+

","

The problem is with the picture. width: 100vw and padding section .about

+

solution:

+
section {
+  overflow: hidden;
+}
+
+

or

+
#portrait {
+  position: relative;
+  left: 0;
+  bottom: -0.3em;
+  max-width: 100%;
+}
+
",css +"Big blank space at the bottom of page

I'm having this problem, when I added a background image to a flexbox column, I can see that there is a big blank space at the bottom at the bottom. I tried to inspect the page but could not find the problem. I have no idea how to fix the problem, what I want to do is remove the blank space or make the picture go down all the way.

+

+
+
body {
+    background-color: rgb(245, 245, 245);
+    font-family: 'Roboto', sans-serif;
+    padding: 0;
+    margin: 0;
+    overflow: auto;
+}
+.main {
+    display: flex;
+    justify-content: space-evenly;
+}
+.row {
+    flex: 50%;
+    padding: 3em;
+    padding-left: 15em;
+}
+.row1 {
+    flex: 50%;
+}
+.row-text-top {
+    padding-bottom: 1em;
+    font-size: 21px;
+}
+.row-text-mid {
+    padding-bottom: 3em;
+    font-size: 16px;
+}
+.row-text-mid1 {
+    font-size: 25px;
+    border-left: 5px solid #ff9b7c;
+    padding: 0.5em;
+    padding-top: 0.1em;
+    padding-bottom: 0.1em;
+    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif
+}
+.row-text-low {
+    padding-top: 3em;
+}
+.row1 {
+    background-image: url(earth.jpg);
+    background-size: cover;
+}
+
<!DOCTYPE html>
+<html>
+    <head>
+        <meta charset=""utf-8"">
+        <title>City</title>
+        <link href=""wwd.css"" rel=""stylesheet"" type=""text/css"">
+        <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+        <script src=""index.js""></script>
+    </head>
+    <body>
+        <div class=""main"">
+            <div class=""row"">
+                <h1>Overview</h1>
+                <div class=""row-text-top"">
+                    One of the most urgent issues of our time, climate change has widespread                     implications — from the exacerbation of 
+                    poverty, to the breakdown of infrastructure, to the loss of                                 environmental, political, economic and social security. 
+                    Experts agree that climate change threatens to set back development                         efforts by decades, placing least developed countries 
+                    and already-vulnerable populations in an even more precarious position.
+                </div>
+                <div class=""row-text-mid"">
+                    The latest Intergovernmental Panel on Climate Change (IPCC) Fifth                           Assessment Report (AR5), signed 
+                    off by almost 200 nations, concludes with 95% certainty or more that                         humans have caused the majority 
+                    of climate change since the 1950s. It predicts global surface                               temperature to continue to rise, along 
+                    with increased sea level rise, melting of glaciers and ice sheets,                           acidification of oceans, increase 
+                    in the intensity of tropical storms and changes in precipitation                             patterns.
+                </div>
+                <div class=""row-text-mid1"">
+                    In other words; the science on climate change is clearer than ever, and                     so is the urgency for human action.
+                </div>
+                <div class=""row-text-low"">
+                    As a global community, we all have a role in developing and implementing                     solutions toward significant 
+                    transformation in our development patterns. It requires not only a shift                     in awareness and accountability 
+                    for our own individual choices but in a social, political and economic                       shift towards enabling conditions 
+                    for these sustainable choices to be made– and in turn, a more just,                         equal and healthy planet.
+                </div>
+            </div>
+            <div class=""row1"">
+            </div>
+        </div>
+    </body>
+</html>
+
+
+

+

It's a bit hard to see because of the image not being there but I will add a picture as well:

+

","

The issue is here:

+
.row {
+  flex: 50%;
+  padding: 3em;         <---- This line
+  padding-left: 15em;
+}
+
+

You're adding additional padding all around the row element, including the bottom. After removing this padding, the space at the bottom of the screen is gone.

+

Here's a working demo: https://codepen.io/Lissy93/pen/yLvBJLe

+

Tip: I recommend using the developer tools, with the element selector you can hover over the space, and it will show exactly which element is causing it, and show whether it is (green for) padding and (orange for) margin.

",css +"Why isn't this flexbox with inputs working?

It's HTML inside PHP. The input boxes are just under each other. I want to position them to be in an horizontal flexbox inside a rectangle, side by side to fill the rectangle.

+

+
+
#retang1{
+  display: flex;
+  position: absolute;
+  width: 1118px;
+  height: 95px;
+  left: 117px;
+  top: 290px;
+
+  background: linear-gradient(90deg, #5FC5B7 0%, #3A857B 100%);
+  box-shadow: 8px 8px 15px rgba(0, 0, 0, 0.25);
+  border-radius: 17px;
+} 
+    
+#retang1 > div {
+  background-color: #f1f1f1;
+  margin: 10px;
+  padding: 20px;
+  font-size: 30px;
+}
+
<div id=""retang1"">
+  <form action=""enviarinfos.php"" method=""POST"">
+    <div>
+      <input type=""text"" name=""materia"" value=""Matéria"">
+      <br>
+    </div>
+    <div>
+      <input type=""text"" name=""trab"" value=""Trabalho"">
+      <br>
+    </div>
+    <div>
+      <input type=""text"" name=""prova"" value=""Prova"">
+      <br>
+    </div>
+    <div>
+      <button type=""submit"" name=""submit"">Enviar</button>
+    </div>
+  </form>
+</div>
+
+
+

","

Add this to your style:

+
form {
+    display: flex;
+}
+
+

And style accordingly. +You can read this link too. https://www.w3schools.com/css/css3_flexbox.asp

",css +"How can I apply margin depending on text wrapping?

Please tell me how can I make the margin-left of the .number block be only if there is no wrapping in the text block. +In the first option, everything is OK, in the second, the indent is not needed.

+

+
+
.block {
+  height: auto;
+  background: grey;
+  overflow: hidden;
+  margin-bottom: 20px;
+}
+
+.block .text {
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.block .text .number {
+  background: blue;
+  color: white;
+  margin: 0px 10px;
+}
+
<div class=""block"" style=""width: 140px;"">
+  <div class=""text"">TEXT
+    <div class=""number"">123</div>TEXT
+  </div>
+</div>
+
+<div class=""block"" style=""width: 50px;"">
+  <div class=""text"">TEXT
+    <div class=""number"">123</div>TEXT
+  </div>
+</div>
+
+
+

","

I handle my flex wrapping by only using right margins.

+

+
+
.block {
+  height: auto;
+  background: grey;
+  overflow: hidden;
+  margin-bottom: 20px;
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.block > div {
+  margin-right: 10px;
+}
+
+.block .number {
+  background: blue;
+  color: white;
+}
+
<div class=""block"" style=""width: 100px;"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+<div class=""block"" style=""width: 50px;"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+
+

+

You can optionally omit the final margin if you want a flush final block.

+

+
+
.block {
+  height: auto;
+  background: grey;
+  overflow: hidden;
+  margin-bottom: 20px;
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.block > div:not(:last-of-type) {
+  margin-right: 10px;
+}
+
+.block .number {
+  background: blue;
+  color: white;
+}
+
<div class=""block"" style=""width: 100px;"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+<div class=""block"" style=""width: 50px;"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+
+

+

If you want to get a clean consistant bounding box no matter how manny flex items are in the container and no matter what size the width is you can use top left spacing on the container and bottom right on the children:

+

+
+
.block {
+  height: auto;
+  background: grey;
+  overflow: hidden;
+  margin-bottom: 20px;
+  display: inline-flex;
+  flex-wrap: wrap;
+  padding: 10px 0 0 10px;
+}
+
+.block > div {
+  margin: 0 10px 10px 0;
+}
+
+.block .number {
+  background: blue;
+  color: white;
+}
+
+
+.w50{
+  max-width:50px;
+}
+
<div class=""block"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+<div class=""block w50"">
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+  <div class=""text"">TEXT</div>
+  <div class=""number"">123</div>
+</div>
+
+
+

+

Alternatively if your width is being determined by screen size then you can simple use a media query to alter the block once it wraps.

+
@media all and (max-width:100px) {
+  .block .text .number {
+    margin: 0;
+  }
+}
+
",css +"Background image from css is not visible on github, but visible in localhost

I have made a project just for fun in which i had applied background images from css, they are very well working in localhost but when uploaded on github all the images are visible except the one on the background. +The link for the github is below. +https://github.com/AmanShahwaz/Driver-s-Community

+

Thanks in advance

","

Here is your problem:

+
<img src="/D-Community/imgaes/1.jpg" alt="" srcset="">
+
+

Your repo name is "Driver-s-Community", which is also the base URL of your github pages site (https://amanshahwaz.github.io/Driver-s-Community/).

+

However, your code URLs link to https://amanshahwaz.github.io/D-Community/, which simply does not exist (it did not at the time of writing), and thus gives the broken links. This is probably due to you having a different name for your local folder from your repository name. To prevent such conflicts, you should keep both names consistent.

+

The solution is to either rename your local working directory to "Driver-s-Community" or your repo to "D-Community", and change your base URLs accordingly.

+

If you rename your local folder to Driver-s-Community, then your URLs should look something like this:

+
<img src="/Driver-s-Community/imgaes/1.jpg" alt="" srcset="">
+
+

Otherwise, no need to change your URLs.

+

Also, just as a side note, considering your project structure, you should probably use ./ instead of explicitly typing out your base URL. This helps to avoid such mishaps.

+

Hoped this helped and if it did, please mark as accepted answer. Thanks!

+

P.S. you have a typo in "imgaes", should be "images". :)

",css +"html ignores files paths

I have a html file:

+
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Online Shop</title>
+    <link rel="stylesheet" type="style/css" href="./sass/style.css">
+  </head>
+  <body>
+    <header>
+      <img alt="shop logo" src="./img/header-logo.webp" width="50px" height="50px"/>
+      <input type="text" class="header-search">
+    </header>
+
+    <script src="./script.js"></script>
+  </body>
+</html>
+
+

File structure:

+

+

Path in WebStorm: +

+

And idk why but html automatically cuts each path to file to file name only. +In code: ./img/header-search.webp. In devtools: header-search.webp +And if I change the path in devtools then it works. This problem appears with any file type. How can I fix it?

",

I'm sorry but I'm really dumb xD. In link tag I wrote type="style/css" instead of type="text/css" and the problem was here. Be attentive guys and don't be like me xD

,css +"How to prevent long table from being hidden by an image with position: fixed when printing html page

I have a multiple long html tables featuring a lot of tr lines that i want to print with a footer image, to put the image to the bottom of the table i use the 'position: fixed' css tag with 'bottom: 0', it works, but if a table is too long, it's hidden behind the footer image on the bottom of the preview page.

+

my html is like that

+
<div class='page-break'> (to break page after this div)
+    <table>
+        <tr><td>content</td></tr>
+        ...lots of lines, more than 1 print page long
+    </table>
+    <div class='footer'><img src='footer_image' /></div>
+</div>
+... and repeated many times
+
","

I found the answer is as said on this article

+

https://medium.com/@Idan_Co/the-ultimate-print-html-template-with-header-footer-568f415f6d2a

+

Basically put a div (empty) the size of your recurrent footer in the tfoot of your table.

+
<table>
+    <tbody>
+        ... your table content
+    </tbody>
+    <tfoot>
+        <tr><td><div class='spacer'>&nbsp;</div></td></tr>
+    </tfoot>
+</table>
+<div class='footer'>footer content</div>
+
+CSS:
+.spacer {
+    height: 150px;
+}
+.footer {
+    height: 150px;
+    position: fixed;
+    bottom: 0;
+}
+
",css +"Checkbox toggle square getting lost

I have been working on a custom-styled checkbox, but for some reason, the square when the toggle is checked is getting lost.

+

Anyone could please point out what I did wrong with this checkbox?

+

https://jsfiddle.net/d67k5uyq/6/

+

HTML

+
<!DOCTYPE html>
+<html lang="en">
+   <head>
+      <meta charset="UTF-8">
+      <title>switch toggle menu using html css only</title>
+   </head>
+   <body>
+      <div class="container">
+      
+        <div>
+          <input type="checkbox" class="toggle" id="default">
+          <label for="default" data-checked="Checked" data-unchecked="Unchecked"></label>      
+        </div>
+        
+     </div>
+   </body>
+</html>
+
+

I believe is something to do with the before and after where I'm forgetting to set some value.

+

CSS

+
body{
+  background: #485461;
+  font-family: sans-serif;
+  height: 100vh;
+  overflow: hidden;
+}
+
+.container{
+  margin: 0 auto;
+  text-align: center;
+  padding-top: 30px;
+  color: white; 
+}
+
+input[type=checkbox].toggle{
+  display: none;
+}
+
+input[type=checkbox].toggle + label{
+  display: inline-block;
+  height: 60px;
+  width: 200px;
+  position: relative;
+  font-size:20px;
+  border: 4px solid white;
+  padding: 0;
+  margin: 0;
+  cursor: pointer;
+  box-sizing: border-box;
+  transition: all 0.3s ease; 
+}
+
+input[type=checkbox].toggle + label:before{
+  position: absolute;
+  top: 4px;
+  height: 44px;
+  width: 44px;
+  content: '';
+  transition: all 0.3s ease;
+  z-index: 3;
+}
+
+input[type=checkbox].toggle + label:after{
+  width: 140px;
+  text-align: center;
+  z-index: 2;
+  text-transform: uppercase;
+  position: absolute;
+  top: 50%;
+  transform: translateY(-50%);
+  text-overflow: ellipsis;
+  overflow: hidden;
+ }
+
+input[type=checkbox].toggle:not(:checked) + label{
+ background-color: transparent;
+ text-align: right;
+}
+
+input[type=checkbox].toggle:not(:checked) + label:after{
+  content: attr(data-unchecked);
+  right: 0;
+  left: auto;
+  opacity: 1;
+  color: white;
+}
+
+input[type=checkbox].toggle:not(:checked) + label:before{
+   left: 4px;
+   background-color: white;
+}
+
+input[type=checkbox].toggle:checked + label{
+   text-align: left;
+   border-color: yellow;
+}
+
+input[type=checkbox].toggle:checked + label:after{
+   content: attr(data-checked);
+   left: 4px;
+   right: auto;
+   opacity: 1;
+   color: white;
+}
+
+input[type=checkbox].toggle:checked + label:before{
+   left: 144px;
+   border-color: yellow;
+}
+
","

When the input is unchecked then the before pseudo element is given a background color of white.

+

When it is checked then it is given a color to the border, but the border has not been given any width.

+

Assuming you want a yellow bordered square the this snippet not only sets the border color but also solid and 1px width.

+

+
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <title>switch toggle menu using html css only</title>
+  <style>
+    body {
+      background: #485461;
+      font-family: sans-serif;
+      height: 100vh;
+      overflow: hidden;
+    }
+    
+    .container {
+      margin: 0 auto;
+      text-align: center;
+      padding-top: 30px;
+      color: white;
+    }
+    
+    input[type=checkbox].toggle {
+      display: none;
+    }
+    
+    input[type=checkbox].toggle+label {
+      display: inline-block;
+      height: 60px;
+      width: 200px;
+      position: relative;
+      font-size: 20px;
+      border: 4px solid white;
+      padding: 0;
+      margin: 0;
+      cursor: pointer;
+      box-sizing: border-box;
+      transition: all 0.3s ease;
+    }
+    
+    input[type=checkbox].toggle+label::before {
+      position: absolute;
+      top: 4px;
+      height: 44px;
+      width: 44px;
+      content: '';
+      transition: all 0.3s ease;
+      z-index: 3;
+    }
+    
+    input[type=checkbox].toggle+label::after {
+      width: 140px;
+      text-align: center;
+      z-index: 2;
+      text-transform: uppercase;
+      position: absolute;
+      top: 50%;
+      transform: translateY(-50%);
+      text-overflow: ellipsis;
+      overflow: hidden;
+      content: 'A';
+    }
+    
+    input[type=checkbox].toggle:not(:checked)+label {
+      background-color: transparent;
+      text-align: right;
+    }
+    
+    input[type=checkbox].toggle:not(:checked)+label::after {
+      content: attr(data-unchecked);
+      right: 0;
+      left: auto;
+      opacity: 1;
+      color: white;
+    }
+    
+    input[type=checkbox].toggle:not(:checked)+label::before {
+      left: 4px;
+      background-color: white;
+    }
+    
+    input[type=checkbox].toggle:checked+label {
+      text-align: left;
+      border-color: yellow;
+    }
+    
+    input[type=checkbox].toggle:checked+label::after {
+      content: attr(data-checked);
+      left: 4px;
+      right: auto;
+      opacity: 0.5;
+      color: white;
+    }
+    
+    input[type=checkbox].toggle:checked+label::before {
+      left: 144px;
+      border-color: yellow;
+      border-style: solid;
+      border-width: 1px;
+    }
+  </style>
+
+</head>
+
+<body>
+  <div class=""container"">
+
+    <div>
+      <input type=""checkbox"" class=""toggle"" id=""default"">
+      <label for=""default"" data-checked=""Checked"" data-unchecked=""Unchecked""></label>
+    </div>
+
+  </div>
+</body>
+
+</html>
+
+
+

",css +"Grid display separates when viewed fullscreen

I'm having trouble understanding whats going on with a grid I created. I made some code for a grid via javascript that changes the cell color when the mousepointer passes over it, however whenever I view this grid in a fullscreen window the view of the grid changes to four separate columns. This only happens when I look at the grid in fullscreen however, when viewing the grid in any smaller sized window it looks exactly how you envison a grid; with no spaces in between columns.

+

gridProblem

+

+This is how the grid looks fullscreen with the spacing issue shown

+

grid solution

+

+This is how the grid looks in any window sizing outside of maximized, and how I would like the grid to display 100% of the time.

+

Just in case, here is the code I'm using:

+

HTML:

+
    <!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <link rel="stylesheet" href="styles.css">
+    <title>Etch N Sketch</title>
+</head>
+<body>
+<div class="container" id="container"></div>
+<script src="script.js"></script>
+</body>
+</html>
+
+

Javascript:

+
const board = document.getElementById("container");
+for (x=0; x <= 15; x++) {
+    const cell = document.createElement('div');
+    cell.className = "cells";
+    cell.setAttribute("style", "height: 200px; width: 200px; color: black;");
+    cell.style.backgroundColor = "blue";
+    cell.style.border = "solid 2px";
+    cell.style.borderColor = "black";
+    board.style.columnGap = "0px";
+    board.style.display ="grid";
+    board.style.gridTemplateColumns = "auto auto auto auto";
+    board.appendChild(cell);
+    cell.addEventListener("mouseover", change = () => 
+    cell.style.backgroundColor = "red")
+    cell.addEventListener("mouseout", reset = () => cell.style.backgroundColor = "blue")
+} 
+
","

The issue is that you set the width and height to be absolute values here

+

cell.setAttribute("style", "height: 200px; width: 200px; color: black;");

+

so at a smaller screen size 200px is fine but once the area that the squares need to cover becomes larger than 200px your limiting them by having these values tied to them.

",css +"How do I size a scrollable div's child to its ""natural"" width?

I have a text where I want the lines to be broken exactly at the position given with <br>. This text should be scrollable in a view port whose width is smaller than the width of the text. If I know the width of the text by experimenting, I can set the corresponding text div's width property to that width, as done in the following example:

+
<!DOCTYPE html>
+<html>
+<head>
+  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
+  <title>overflow css property</title>
+
+  <style type="text/css">
+
+    div.container {
+      position: absolute;
+      width: 150px;
+      height: 110px;
+      border: 1px solid black;
+      left: 30px;
+      top: 20px;
+      overflow: scroll;
+    }
+
+    div.text {
+      position: static;
+      background-color:yellow;
+      width:300px; /* I'd rather not hardcode this value */
+    }
+
+    
+  </style>
+
+</head>
+<body>
+
+
+  <div class='container' id='right'>
+    <div class='text'>
+    Lorem ipsum dolor sit amet, consectetur<br>
+    adipiscing elit, sed do eiusmod tempor<br>
+    incididunt ut labore et dolore magna aliqua.<br>
+    Ut enim ad minim veniam, quis nostrud<br>
+    exercitation ullamco laboris nisi ut aliquip<br>
+    ex ea commodo consequat.<br>
+    Duis aute irure dolor in reprehenderit in<br>
+    voluptate velit esse cillum dolore eu fugiat<br>
+    nulla pariatur. Excepteur sint occaecat<br>
+    cupidatat non proident, sunt in culpa qui<br>
+    officia deserunt mollit anim id est laborum.
+    </div>
+  </div>
+
+</body>
+</html>
+
+

This works fine, but I'd rather not hardcode the width to 300px because the actual text is dynamically created and its width might vary. Thus the question: is it possible to make the text div's width to be the "natural" width?

","

I suppose you don't want a line-break elsewhere than where you defined it, then you can use min-width: max-content; so there is no need to hardcode the exact value of the width (that may vary, e.g., if the user want to zoom-in your text).

+

+
+
.text {
+  min-width: max-content; 
+  font: 1rem/1.5 system-ui;
+}
+
<div class='text'>
+    Lorem ipsum dolor sit amet, consectetur<br>
+    adipiscing elit, sed do eiusmod tempor<br>
+    incididunt ut labore et dolore magna aliqua.<br>
+    Ut enim ad minim veniam, quis nostrud<br>
+    exercitation ullamco laboris nisi ut aliquip<br>
+    ex ea commodo consequat.<br>
+    Duis aute irure dolor in reprehenderit in<br>
+    voluptate velit esse cillum dolore eu fugiat<br>
+    nulla pariatur. Excepteur sint occaecat<br>
+    cupidatat non proident, sunt in culpa qui<br>
+    officia deserunt mollit anim id est laborum.
+</div>
+
+
+

",css +"bootstrap 5 link hover color doesn't work

I'm trying to do so that when you pass with the mouse over the links the text of the navbar its color changes and border bottom, border bottom worked but i don't understand why color text doesn't change

+

HTML

+
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+   <meta charset="UTF-8">
+   <meta http-equiv="X-UA-Compatible" content="IE=edge">
+   <meta name="viewport" content="width=device-width, initial-scale=1.0">
+   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
+   <link rel="stylesheet" href="css/style.css">
+   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
+   <title>Savinov Denis</title>
+</head>
+
+<body>
+   <nav class="navbar navbar-expand-lg fixed-top navbar-custom">
+       <div class="container">
+           <a class="navbar-brand" href="#">
+               <img src="logo.png" alt="Avatar Logo" style="width:40px;" class="rounded-pill">
+           </a>
+
+           <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
+               aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
+               <span class="navbar-toggler-icon"></span>
+           </button>
+
+           <div class="collapse navbar-collapse justify-content-center" id="navbarNav">
+               <ul class="navbar-nav justify-content-center">
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading1">Home</a>
+                   </li>
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading2">Services</a>
+                   </li>
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading3">Compétences</a>
+                   </li>
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading4">Portfolio</a>
+                   </li>
+
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading6">À Propos</a>
+                   </li>
+                   <li class="nav-item">
+                       <a class="nav-link" href="#scrollspyHeading7">Contact</a>
+                   </li>
+               </ul>
+           </div>
+       </div>
+   </nav>
+
+
+   <div id="carouselExampleFade" class="carousel slide carousel-fade" data-bs-ride="carousel">
+       <div class="carousel-inner">
+           <div class="carousel-item active">
+               <img src="images/114-1144561_copyright-free-images-on-desk-with-laptop-and.jpg" class="d-block w-100"
+                   style="filter: brightness(10%);" alt="...">
+               <div class="carousel-caption d-none d-md-block">
+                   <h5>SAVINOV Denis</h5>
+                   <p>Développeur Web Indépendant</p>
+               </div>
+           </div>
+           <div class="carousel-item">
+               <img src="images/269-2698560_high-resolution-laptop-desktop-wallpaper-hd.jpg" class="d-block w-100"
+                   style="filter: brightness(10%);" alt="...">
+               <div class="carousel-caption d-none d-md-block">
+                   <h5 class="text-center">Création de sites web</h5>
+                   <p class="text-center">Site vitrine, e-commerce, forum et autres</p>
+               </div>
+           </div>
+           <div class="carousel-item">
+               <img src="images/10705380.jpg" class="d-block w-100" style="filter: brightness(10%);" alt="...">
+               <div class="carousel-caption d-none d-md-block">
+                   <h5 class="text-center">Web design, conception graphiques</h5>
+                   <p class="text-center">Logos, plaquettes publicitaire, cartes de visites,
+                       newsletters</p>
+               </div>
+           </div>
+       </div>
+       <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev">
+           <span class="carousel-control-prev-icon" aria-hidden="true"></span>
+           <span class="visually-hidden">Previous</span>
+       </button>
+       <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next">
+           <span class="carousel-control-next-icon" aria-hidden="true"></span>
+           <span class="visually-hidden">Next</span>
+       </button>
+   </div>
+   <div class="container text-center" href="scrollspyHeading1">
+       <h1>MES SERVICES</h1>
+       <h3>Des prestations adaptées à vos besoins</h3>
+   </div>
+   <div class="container text-center" href="scrollspyHeading2">
+       <div class="row">
+           <div class="col">
+               <h5 class="text-end">Gestion de projets web</h5>
+               
+               <p class="text-end">Site vitrine, corporate, évènementiel, e-commerce, intranet, application mobile.</p>
+               <h5 class="text-end">Intégration Web</h5>
+               <p class="text-end">Des intégrations (X)HTML / CSS respectueuses des standards du Web.</p>
+               <h5 class="text-end">Développements spécifiques</h5>
+               <p class="text-end">Des outils adaptés à votre coeur de métier,
+                   applications & solutions personnalisées.</p>
+               <h5 class="text-end">Référencement naturel</h5>
+               <p class="text-end">Affichage sémantique des informations,
+                   des pages propres pour un référencement optimal.</p>
+           </div>
+           <div class="col">
+               <img src="images/index.jpeg" class="d-block w-100" alt="...">
+           </div>
+           <div class="col">
+               <h5 class="text-start">Conception graphique & Webdesign</h5>
+               <p class="text-start">Logos, templates Web, plaquettes publicitaires,
+                   cartes de visite, newsletters...</p>
+               <h5 class="text-start">Dynamisme des pages</h5>
+               <p class="text-start">Des animations de contenu non intrusives
+                   pour embellir votre projet.</p>
+               <h5 class="text-start">Interface d'administration</h5>
+               <p class="text-start">Outils spécifiques au bon fonctionnement
+                   de votre entreprise.</p>
+               <h5 class="text-start">Responsive design</h5>
+               <p class="text-start">Compatible tous supports, tablette & application mobile.</p>
+           </div>
+       </div>
+
+       <p>Compatible Mobile, Tablettes & P.C</p>
+       <h3>Développement Web Responsive</h3>
+   </div>
+
+   <div class="container text-center" href="scrollspyHeading3">
+       <h1>MES COMPÉTENCES</h1>
+       <h3>Des compétences à votre service</h3>
+       <div class="container text-center">
+           <div class="row">
+               <div class="col">
+                   <h1 class="text-start">Domaines de compétences</h1>
+                   <h4 class="text-start"> Gestion de projets web </h4>
+                   <p class="text-start">Site vitrine, corporate, évènementiel, e-commerce, intranet, application
+                       mobile.</p>
+
+                   <h4 class="text-start"> Conception graphique & Webdesign </h4>
+                   <p class="text-start">Logos, templates Web, plaquettes publicitaires, cartes de visite,
+                       newsletters...</p>
+
+                   <h4 class="text-start">Applications spécifiques et Interface d'administration</h4>
+                   <p class="text-start">PHP - MySQL - AJAX / ASP.NET - C# - SQL</p>
+
+                   <h4 class="text-start">Mise en place / Modification / Gestion de CMS</h4>
+                   <p class="text-start">Wordpress, Joomla, Prestashop, phpBB, IPBoard</p>
+
+                   <h4 class="text-start">Intégration (X)HTML / CSS</h4>
+                   <p class="text-start">Codage à la main respectueux des standards du Web</p>
+
+                   <h4 class="text-start"> Dynamise des pages par JavaScript / AJAX </h4>
+                   <p class="text-start">jQuery, Prototype, Mootools, Scriptaculous</p>
+
+                   <h4 class="text-start">Validation W3C, WAI & référencement naturel SEO</h4>
+                   <p class="text-start"> Accessibilité & ergonomie des pages web </p>
+
+                   <h4 class="text-start"> Conception multi-plateformes </h4>
+                   <p class="text-start">Compatible tous supports, tablette & application mobile</p>
+               </div>
+
+               <div class="col">
+                   <h1>Compétences en développement</h1>
+                   <h1>Compétences en conception graphique</h1>
+               </div>
+
+               <h1 class="text-center">Une idée ? Un projet ? N'hésitez pas à demander un devis ! [GRATUIT]</h1>
+           </div>
+       </div>
+   </div>
+
+   <div class="container text-center" href="scrollspyHeading4">
+       <h1>MES PROJETS</h1>
+       <h4>Une partie des projets sur lesquels j'ai travaillé</h4>
+   </div>
+
+   <div class="container text-center" href="scrollspyHeading6">
+       <h1>À PROPOS</h1>
+       <h4>Je suis développeur web freelance et j'aime ça !</h4>
+       <div class="row">
+           <div class="col">
+               <h4 class="text-start">Un développeur web passionné !</h4>
+               <p class="text-start">Ma passion pour le développement web commence en 2003 et m'a demandé un changement
+                   radical de cursus
+                   afin de pouvoir pleinement l'exploiter.</br> </br>
+
+                   Dès lors, je mis tout en oeuvre pour percer dans cette voie, tout en prenant du plaisir sur les
+                   divers projets développés.</br> </br>
+
+                   En Mai 2009, je décide de devenir développeur web indépendant après plusieurs postes en tant que
+                   développeur web « full-stack » réussis, qui me conforteront dans cette idée afin de toucher un plus
+                   large panel de domaines d'activités, voir du pays et conquérir le monde !</p>
+           </div>
+
+           <div class="col">
+               <img src="images/index.jpeg" class="d-block w-100" alt="...">
+           </div>
+
+           <div class="col">
+
+               <h4 class="text-start">Expérience en développement</h4>
+
+               <p class="text-start"> Mon expérience acquise au fil des projets me permet de mieux comprendre les
+                   attentes d'un client
+                   et de
+                   répondre précisement au besoin demandé en fonction du domaine d'activité.</p>
+
+               <p class="text-start">Du site vitrine au projet plus complexe, je vous propose une expertise et un
+                   développement web qui
+                   correspond à vos attentes & à vos besoins.</p>
+
+               <h3 class="text-start">Un tarif adapté à votre projet</h3>
+
+               <p class="text-start"> Travaillant régulièrement avec des PME, associations ou particuliers, je vous
+                   propose des solutions
+                   à
+                   votre portée & adaptée à votre budget.</p>
+
+           </div>
+       </div>
+   </div>
+
+   <div class="container text-center" href="scrollspyHeading7">
+       <h1>CONTACTEZ-MOI</h1>
+       <h3>Une idée ? Un projet ? N'hésitez pas à demander un devis ! [GRATUIT]</h3>
+
+       <div class="row">
+           <div class="col text-start">
+               <h6>ADRESSE</h6>
+               <p>45, allée des Grives 83390 Cuers</p>
+               <h6>Téléphone</h6>
+               <p>(+33) 6.15.42.10.45</p>
+               <h6>E-mail</h6>
+               <p>contact@mcrevoulin.com</p>
+               <h6>Horaires</h6>
+               <p>Lundi - Vendredi
+
+                   09H00 - 18H00</p>
+               <h6>S.I.R.E.N</h6>
+               <p>522 491 000</p>
+           </div>
+           <div class="col">
+               <iframe
+                   src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d84484.16954505828!2d7.69203969606045!3d48.56905316140801!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4796c8495e18b2c1%3A0x971a483118e7241f!2sStra%C3%9Fburg%2C%20Frankreich!5e0!3m2!1sde!2sde!4v1658941325979!5m2!1sde!2sde"
+                   width="300" height="200" style="border:0;" allowfullscreen="" loading="lazy"
+                   referrerpolicy="no-referrer-when-downgrade"></iframe>
+               <iframe
+                   src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d316530.06898113067!2d38.75890546037433!3d51.69843674434513!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x413b2f5ce874e813%3A0x48d94c0efba762bd!2sWoronesch%2C%20Oblast%20Woronesch%2C%20Russland!5e0!3m2!1sde!2sde!4v1658941426253!5m2!1sde!2sde"
+                   width="300" height="200" style="border:0;" allowfullscreen="" loading="lazy"
+                   referrerpolicy="no-referrer-when-downgrade"></iframe>
+           </div>
+           <div class="col">
+               Column
+           </div>
+       </div>
+
+   </div>
+
+
+   <script src="js/javascript.js"></script>
+   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"
+       integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
+       crossorigin="anonymous"></script>
+</body>
+
+</html>
+
+

CSS

+
@import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css");
+/* Modify the background color */
+.navbar-custom {
+  background-color: rgba(255, 255, 255, 0.37);
+}
+
+.navbar-nav .nav-item .nav-link {
+
+  color: white;
+
+}
+
+
+
+.nav-item a:hover {
+  color: cyan;
+  box-shadow: inset 0 -2.5px 0 0 cyan; 
+}
+
+
+.carousel-inner .carousel-item>img {
+  -webkit-animation: thing 20s;
+  -o-animation: thing 20s;
+  animation: thing 20s;
+}
+
+@keyframes thing {
+  from {
+    transform: scale(1, 1);
+  }
+
+  to {
+    transform: scale(1.5, 1.5);
+  }
+}
+
+
+

But it does not work I do not understand why, it seems to me that the code is correct but when I pass on the links of the navbar the hover to change colors does not work. What should I do to fix this code issue? I have try code from others topic but don't resolved my problem

","

It is because of the parent selectors you are using before the :hover on this line

+
.navbar-nav .nav-item .nav-link {
+
+  color: white;
+
+}
+
+

Try with

+
.navbar-nav .nav-item .nav-link:hover {
+  color: cyan;
+  box-shadow: inset 0 -2.5px 0 0 cyan; 
+}
+
",css +"You may need an additional loader to handle the result of these loaders. Angular 14

I updated from Angular 7 to Angular 14 after removing all the errors in my project this is the only error that is stopping me from compiling successfully. I am getting this error on ng serve:

+
+
+

/src/app/shared/styles/themes/theme-f.scss:1:6 - Error: Module parse failed: Unexpected token (1:6) File was processed with these loaders: +*/node_modules/resolve-url-loader/index.js +*/node_modules/sass-loader/dist/cjs.js +You may need an additional loader to handle the result of these loaders. +body, .wrapper > section { | background-color: #f5f7fa; | color: #73879C;

+
+
+

here is my tsconfig.json file

+

+
+
{
+  ""compileOnSave"": false,
+  ""compilerOptions"": {
+    ""strictPropertyInitialization"": false,
+    ""baseUrl"": ""./"",
+    ""outDir"": ""./dist/out-tsc"",
+    ""sourceMap"": true,
+    ""declaration"": false,
+    ""module"": ""es2020"",
+    ""moduleResolution"": ""node"",
+    ""experimentalDecorators"": true,
+    ""importHelpers"": true,
+    ""target"": ""es2019"",
+    ""skipLibCheck"": true,
+    ""typeRoots"": [
+      ""node_modules/@types""
+    ],
+    ""types"": [ ""googlemaps"" ],
+    ""lib"": [
+      ""es2018"",
+      ""DOM"",
+      ""DOM.Iterable"",
+      //""ScriptHost""
+    ]
+  },
+  ""angularCompilerOptions"": {
+    //""enableLegacyTemplate"": true,
+    //""enableI18nLegacyMessageIdFormat"": false,
+    ""disableTypeScriptVersionCheck"": true,
+    ""strictInjectionParameters"": true,
+    ""strictInputAccessModifiers"": true,
+    ""strictTemplates"": true
+  },
+  ""browserslist"": [
+    "">0.2%"",
+    ""not dead"",
+    ""not op_mini all""
+  ]
+}
+
+
+

+

This my package.json file:

+

+
+
{
+  ""name"": ""wsi-portal"",
+  ""version"": ""0.0.0"",
+  ""scripts"": {
+    ""ng"": ""ng"",
+    ""install"": ""npm run napa"",
+    ""start"": ""ng serve"",
+    ""build"": ""ng build"",
+    ""test"": ""ng test"",
+    ""lint"": ""ng lint"",
+    ""e2e"": ""ng e2e"",
+    ""modernizr"": ""modernizr -c modernizr-config.json -d src/modernizr.js"",
+    ""postinstall"": ""node ./node_modules/protractor/bin/webdriver-manager update"",
+    ""napa"": ""napa"",
+    ""ng-high-memory"": ""node --max_old_space_size=16384 ./node_modules/@angular/cli/bin/ng""
+  },
+  ""browser"": {
+    ""child_process"": false
+  },
+  ""private"": true,
+  ""napa"": {
+    ""jquery.flot.spline"": ""miloszfalinski/jquery.flot.spline"",
+    ""ika.jvectormap"": ""kakirigi/ika.jvectormap"",
+    ""flot"": ""flot/flot#v0.8.3""
+  },
+  ""dependencies"": {
+    ""@agm/core"": ""^1.0.0-beta.3"",
+    ""@angular-devkit/build-webpack"": ""^0.1401.0"",
+    ""@angular/animations"": ""~14.0.5"",
+    ""@angular/cdk"": ""^14.0.4"",
+    ""@angular/common"": ""~14.0.5"",
+    ""@angular/compiler"": ""~14.0.5"",
+    ""@angular/core"": ""~14.0.5"",
+    ""@angular/forms"": ""~14.0.5"",
+    ""@angular/material"": ""^14.0.4"",
+    ""@angular/platform-browser"": ""~14.0.5"",
+    ""@angular/platform-browser-dynamic"": ""~14.0.5"",
+    ""@angular/router"": ""^14.0.5"",
+    ""@fullcalendar/angular"": ""^5.11.0"",
+    ""@fullcalendar/bootstrap"": ""^5.11.0"",
+    ""@fullcalendar/core"": ""^5.11.0"",
+    ""@fullcalendar/daygrid"": ""^5.11.0"",
+    ""@fullcalendar/google-calendar"": ""^5.11.0"",
+    ""@fullcalendar/interaction"": ""^5.11.0"",
+    ""@fullcalendar/list"": ""^5.11.0"",
+    ""@fullcalendar/luxon"": ""^5.11.0"",
+    ""@fullcalendar/moment"": ""^5.11.0"",
+    ""@fullcalendar/moment-timezone"": ""^5.11.0"",
+    ""@fullcalendar/rrule"": ""^5.11.0"",
+    ""@fullcalendar/timegrid"": ""^5.11.0"",
+    ""@kolkov/angular-editor"": ""^2.1.0"",
+    ""@ngx-translate/core"": ""^14.0.0"",
+    ""@ngx-translate/http-loader"": ""^7.0.0"",
+    ""@pascalhonegger/ng-datatable"": ""^14.0.0"",
+    ""@types/angular"": ""^1.8.4"",
+    ""angular-datatable2"": ""^0.9.31"",
+    ""angular-datatables"": ""^14.0.0"",
+    ""angular-date-value-accessor"": ""0.0.2"",
+    ""angular-google-recaptcha"": ""^1.0.3"",
+    ""angular-mgl-timeline"": ""^0.3.3"",
+    ""angular-tabs-component"": ""^1.0.3"",
+    ""angular-tree-component"": ""^8.0.1"",
+    ""angular2-datatable-serverpagination"": ""^0.6.3"",
+    ""angular2-text-mask"": ""^9.0.0"",
+    ""angular2-toaster"": ""^7.0.0"",
+    ""bootstrap"": ""^3.3.7"",
+    ""chart.js"": ""^2.7.1"",
+    ""codemirror"": ""^5.46.0"",
+    ""easy-pie-chart"": ""^2.1.7"",
+    ""font-awesome"": ""^4.7.0"",
+    ""format-currency"": ""^1.0.0"",
+    ""fullcalendar"": ""^5.11.0"",
+    ""html2canvas"": ""1.0.0-rc.1"",
+    ""https-proxy-agent"": ""^5.0.1"",
+    ""jquery"": ""^3.4.1"",
+    ""jquery-slimscroll"": ""^1.3.8"",
+    ""jquery-sparkline"": ""^2.4.0"",
+    ""jquery-ui"": ""^1.12.1"",
+    ""jquery.browser"": ""^0.1.0"",
+    ""jquery.flot.tooltip"": ""github:krzysu/flot.tooltip"",
+    ""jspdf-autotable"": ""^3.1.1"",
+    ""loaders.css"": ""0.1.2"",
+    ""lodash"": ""^4.17.11"",
+    ""mime"": ""^2.4.4"",
+    ""moment"": ""^2.24.0"",
+    ""ng-multiselect-dropdown"": ""^0.2.3"",
+    ""ng-pick-datetime"": ""^7.0.0"",
+    ""ng-select"": ""^1.0.2"",
+    ""ng-zorro-antd"": ""^13.3.2"",
+    ""ng2-alt-summernote"": ""^2.0.0"",
+    ""ng2-charts"": ""^2.4.2"",
+    ""ng2-ckeditor"": ""^1.3.3"",
+    ""ng2-daterangepicker"": ""^3.0.1"",
+    ""ng2-dnd"": ""^4.2.0"",
+    ""ng2-file-upload"": ""^1.4.0"",
+    ""ng2-pdf-viewer"": ""^9.0.0"",
+    ""ng2-pdfjs-viewer"": ""^13.2.2"",
+    ""ng2-progress-bar"": ""0.0.8"",
+    ""ng2-select"": ""^2.0.0"",
+    ""ng2-table"": ""^1.3.2"",
+    ""ng2-validation"": ""^4.1.0"",
+    ""ng4-click-outside"": ""^1.0.1"",
+    ""ngx-bootstrap"": ""^8.0.0"",
+    ""ngx-chips"": ""^1.9.8"",
+    ""ngx-materialize"": ""^0.0.1"",
+    ""ngx-modialog"": ""^5.0.1"",
+    ""ngx-progress-bar"": ""^0.0.10"",
+    ""node-sass"": ""^7.0.1"",
+    ""npm-check-updates"": ""^14.1.1"",
+    ""pdfmake"": ""^0.2.5"",
+    ""popper"": ""^1.0.1"",
+    ""popsicle-proxy-agent"": ""^3.0.0"",
+    ""rxjs"": ""7.5.5"",
+    ""rxjs-compat"": ""^6.6.7"",
+    ""rxjs-observable"": ""^0.0.7"",
+    ""screenfull"": ""^3.3.3"",
+    ""simple-line-icons"": ""^2.4.1"",
+    ""summernote"": ""^0.8.11"",
+    ""sweetalert"": ""^1.1.3"",
+    ""tslib"": ""^2.4.0"",
+    ""typings"": ""^2.1.1"",
+    ""web-animations-js"": ""^2.3.1"",
+    ""zone.js"": ""~0.11.6""
+  },
+  ""devDependencies"": {
+    ""@angular-devkit/build-angular"": ""^14.0.5"",
+    ""@angular/cli"": ""^14.0.5"",
+    ""@angular/compiler-cli"": ""~14.0.5"",
+    ""@angular/language-service"": ""~14.0.5"",
+    ""@angular/localize"": ""^14.0.5"",
+    ""@types/googlemaps"": ""^3.30.20"",
+    ""@types/jasmine"": ""~2.8.8"",
+    ""@types/jasminewd2"": ""~2.0.3"",
+    ""@types/jest"": ""^28.1.4"",
+    ""@types/jquery"": ""^3.5.14"",
+    ""@types/lodash"": ""^4.14.108"",
+    ""@types/mocha"": ""^9.1.1"",
+    ""@types/node"": ""^8.10.48"",
+    ""codelyzer"": ""~4.5.0"",
+    ""core-js"": ""^3.23.3"",
+    ""husky"": ""^8.0.1"",
+    ""jasmine-core"": ""~2.99.1"",
+    ""jasmine-spec-reporter"": ""~4.2.1"",
+    ""jspdf"": ""^1.5.3"",
+    ""karma"": ""^6.4.0"",
+    ""karma-chrome-launcher"": ""~2.2.0"",
+    ""karma-coverage-istanbul-reporter"": ""~2.0.1"",
+    ""karma-jasmine"": ""~1.1.2"",
+    ""karma-jasmine-html-reporter"": ""^0.2.2"",
+    ""napa"": ""^3.0.0"",
+    ""protractor"": ""~7.0.0"",
+    ""ts-node"": ""~7.0.0"",
+    ""tslint"": ""~5.11.0"",
+    ""typescript"": ""~4.7.4""
+  }
+}
+
+
+

+

This is my angular.json file:

+

+
+
{
+  ""$schema"": ""./node_modules/@angular/cli/lib/config/schema.json"",
+  ""version"": 1,
+  ""newProjectRoot"": ""projects"",
+  ""projects"": {
+    ""wsi-portal"": {
+      ""root"": """",
+      ""sourceRoot"": ""src"",
+      ""projectType"": ""application"",
+      ""prefix"": ""app"",
+      ""schematics"": {
+        ""@schematics/angular:component"": {
+          ""style"": ""scss""
+        }
+      },
+      ""architect"": {
+        ""build"": {
+          ""builder"": ""@angular-devkit/build-angular:browser"",
+          ""options"": {
+            ""outputPath"": ""dist/wsi-portal"",
+            ""index"": ""src/index.html"",
+            ""main"": ""src/main.ts"",
+            ""polyfills"": ""src/polyfills.ts"",
+            ""tsConfig"": ""src/tsconfig.app.json"",
+            ""assets"": [
+              ""src/favicon.ico"",
+              ""src/assets""
+            ],
+            ""styles"": [
+              ""src/styles.scss"",
+              ""node_modules/font-awesome/css/font-awesome.css"",
+              ""node_modules/loaders.css/loaders.css"",
+              ""node_modules/codemirror/lib/codemirror.css"",
+              ""node_modules/summernote/dist/summernote.css"",
+              ""node_modules/sweetalert/dist/sweetalert.css"",
+              ""node_modules/simple-line-icons/css/simple-line-icons.css"",
+              ""node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css"",
+              ""node_modules/@fullcalendar/common/main.css"",
+              ""node_modules/@fullcalendar/daygrid/main.css"",
+              ""node_modules/@fullcalendar/timegrid/main.css"",
+              ""node_modules/@fullcalendar/list/main.css""
+
+            ],
+            ""scripts"": [
+              ""node_modules/jquery/dist/jquery.js"",
+              ""node_modules/jquery/dist/jquery.slim.min.js"",
+              ""node_modules/bootstrap/dist/js/bootstrap.js"",
+              ""node_modules/bootstrap/dist/js/bootstrap.min.js"",
+              ""node_modules/flot/jquery.flot.js"",
+              ""node_modules/jquery.flot.tooltip/js/jquery.flot.tooltip.js"",
+              ""node_modules/flot/jquery.flot.resize.js"",
+              ""node_modules/flot/jquery.flot.pie.js"",
+              ""node_modules/flot/jquery.flot.time.js"",
+              ""node_modules/flot/jquery.flot.categories.js"",
+              ""node_modules/jquery.flot.spline/jquery.flot.spline.js"",
+              ""node_modules/jquery-sparkline/jquery.sparkline.js"",
+              ""node_modules/easy-pie-chart/dist/easypiechart.js"",
+              ""node_modules/chart.js/dist/Chart.bundle.js"",
+              ""node_modules/bootstrap/js/modal.js"",
+              ""node_modules/bootstrap/js/dropdown.js"",
+              ""node_modules/bootstrap/js/tooltip.js"",
+              ""node_modules/summernote/dist/summernote.js"",
+              ""node_modules/sweetalert/dist/sweetalert.min.js"",
+              ""node_modules/jquery-slimscroll/jquery.slimscroll.js""
+            ]
+            //,""es5BrowserSupport"": true
+          },
+          ""configurations"": {
+            ""production"": {
+              ""fileReplacements"": [
+                {
+                  ""replace"": ""src/environments/environment.ts"",
+                  ""with"": ""src/environments/environment.prod.ts""
+                }
+              ],
+              ""optimization"": true,
+              ""outputHashing"": ""all"",
+              ""sourceMap"": false,
+              //""extractCss"": true,
+              ""namedChunks"": false,
+              ""aot"": true,
+              ""extractLicenses"": true,
+              ""vendorChunk"": false,
+              ""buildOptimizer"": true,
+              ""budgets"": [
+                {
+                  ""type"": ""initial"",
+                  ""maximumWarning"": ""30mb"",
+                  ""maximumError"": ""30mb""
+                },
+                {
+                  ""type"": ""anyComponentStyle"",
+                  ""maximumWarning"": ""6kb"",
+                  ""maximumError"": ""10kb""
+                }
+              ]
+            }
+          }
+        },
+        ""serve"": {
+          ""builder"": ""@angular-devkit/build-angular:dev-server"",
+          ""options"": {
+            ""browserTarget"": ""wsi-portal:build""
+          },
+          ""configurations"": {
+            ""production"": {
+              ""browserTarget"": ""wsi-portal:build:production""
+            }
+          }
+        },
+        ""extract-i18n"": {
+          ""builder"": ""@angular-devkit/build-angular:extract-i18n"",
+          ""options"": {
+            ""browserTarget"": ""wsi-portal:build""
+          }
+        },
+        ""test"": {
+          ""builder"": ""@angular-devkit/build-angular:karma"",
+          ""options"": {
+            ""main"": ""src/test.ts"",
+            ""polyfills"": ""src/polyfills.ts"",
+            ""tsConfig"": ""src/tsconfig.spec.json"",
+            ""karmaConfig"": ""src/karma.conf.js"",
+            ""styles"": [
+              ""src/styles.scss""
+            ],
+            ""scripts"": [],
+            ""assets"": [
+              ""src/favicon.ico"",
+              ""src/assets""
+            ]
+          }
+        },
+        ""lint"": {
+          ""builder"": ""@angular-devkit/build-angular:tslint"",
+          ""options"": {
+            ""tsConfig"": [
+              ""src/tsconfig.app.json"",
+              ""src/tsconfig.spec.json""
+            ],
+            ""exclude"": [
+              ""**/node_modules/**""
+            ]
+          }
+        }
+      }
+    },
+    ""wsi-portal-e2e"": {
+      ""root"": ""e2e/"",
+      ""projectType"": ""application"",
+      ""prefix"": """",
+      ""architect"": {
+        ""e2e"": {
+          ""builder"": ""@angular-devkit/build-angular:protractor"",
+          ""options"": {
+            ""protractorConfig"": ""e2e/protractor.conf.js"",
+            ""devServerTarget"": ""wsi-portal:serve""
+          },
+          ""configurations"": {
+            ""production"": {
+              ""devServerTarget"": ""wsi-portal:serve:production""
+            }
+          }
+        },
+        ""lint"": {
+          ""builder"": ""@angular-devkit/build-angular:tslint"",
+          ""options"": {
+            ""tsConfig"": ""e2e/tsconfig.e2e.json"",
+            ""exclude"": [
+              ""**/node_modules/**""
+            ]
+          }
+        }
+      }
+    }
+  },
+  ""defaultProject"": ""wsi-portal""
+}
+
+
+

+

Any help would be appreciated!

","

I have resolved this error of Loaders by adding my "/src/app/shared/styles/themes/theme-f.scss" file in angular.json file

+

+
+
""architect"": {
+        ""build"": {
+          ""builder"": ""@angular-devkit/build-angular:browser"",
+         ""options"": {
+            ""styles"": [
+              ""src/app/shared/styles/themes/theme-f.scss""
+              ]}}
+
+
+

",css +"Image not resizing using CSS

My image is not resizing using CSS. I tried all the suggestions on previously asked questions but still can't get it to resize. My style sheet is linked because it moves the items to the center. Please advise what I am doing wrong. TIA

+

+
+
* {
+  padding: 0;
+  margin: 0;
+  box-sizing: border-box;
+}
+
+.menuContainer {
+  display: grid;
+  place-items: center;
+  height: 100vh;
+}
+
+.menuBox img {
+  width: 300px;
+  height: 300px;
+}
+
<div class=""menuContainer"">
+  <div class=""menuBox""></div>
+  <h1 id=""item"">Food Item1</h1>
+  <p id=""oneLiner"">Lorem ipsum dolor sit amet. Et deleniti officiis eos possimus omnis e! </p>
+  <img src=""https://img.freepik.com/free-photo/delicious-fried-chicken-plate_144627-27383.jpg?size=626&ext=jpg&ga=GA1.2.404766179.1658308353"" alt=""img"" id=""img"">
+
+  <h2 id=""hotel"">Hotel name1</h2>
+  <p id=""desc"">Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid deserunt pariatur dolorem quo necessitatibus quas voluptatibus eaque placeat soluta voluptatem?</p>
+  <div class=""btn"">
+    <button id=""prev""><img src=https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtb_on3v-MaK_PJ7IQW4odw2kfxHc9Tw_GkQ&usqp=CAU> </button>
+    <button id=""random"">Random Menu</button>
+    <button id=""next"">:arrrow </button>
+  </div>
+
+</div>
+
+
+

","
<div class="menuBox"></div>
+
+

versus

+
.menuBox img
+
+

The css Code adresses an image in a Container with the class menuBox. +In your example the Container does not contain the image.

+

So your code would look like this: +

+
+
* {
+  padding: 0;
+  margin: 0;
+  box-sizing: border-box;
+}
+
+.menuContainer {
+  display: grid;
+  place-items: center;
+  height: 100vh;
+}
+
+.menuBox img {
+  width: 300px;
+  height: 300px;
+}
+
<div class=""menuContainer"">
+  <div class=""menuBox"">
+    <h1 id=""item"">Food Item1</h1>
+    <p id=""oneLiner"">Lorem ipsum dolor sit amet. Et deleniti officiis eos possimus omnis e! </p>
+    <img src=""https://img.freepik.com/free-photo/delicious-fried-chicken-plate_144627-27383.jpg?size=626&ext=jpg&ga=GA1.2.404766179.1658308353"" alt=""img"" id=""img"">
+  </div>
+  <h2 id=""hotel"">Hotel name1</h2>
+  <p id=""desc"">Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid deserunt pariatur dolorem quo necessitatibus quas voluptatibus eaque placeat soluta voluptatem?</p>
+  <div class=""btn"">
+    <button id=""prev""><img src=https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtb_on3v-MaK_PJ7IQW4odw2kfxHc9Tw_GkQ&usqp=CAU> </button>
+    <button id=""random"">Random Menu</button>
+    <button id=""next"">:arrrow </button>
+  </div>
+
+</div>
+
+
+

",css +"How to achievea top-maincontent-bottom layout with CSS?

I'm trying to achieve the following layout:

+
    +
  1. Top bar
  2. +
  3. Main content placeholder
  4. +
  5. Bottom bar
  6. +
+

The main content has (always one at the same time though) children, one of which is a table which should always be square.

+

How can I do this with CSS? I've tried flexbox and CSS grid including aspect-ratio but couldn't get it to work.

+

The idea is basically the following:

+
    +
  1. Top/Main content/Bottom is always the same height/full width
  2. +
  3. If there's a table inside the main content, it should be square. The main content placeholder should remain the size but the table within should always be automatically resized to be square (ideally with the minimum of available width or height)
  4. +
  5. To achieve this, it's okay for the top bar the change its height, the bottom bar should remain fixed
  6. +
+

Here's some example code I've tried:

+

+
+
<!DOCTYPE html>
+<html lang=""en"" style=""height: 100%;"">
+
+<head>
+  <meta charset=""UTF-8"">
+  <title>Test</title>
+  <style>
+    .main {
+      background: gray;
+      height: 100vh;
+      grid-template-rows: 20% 60% 20%;
+      display: grid;
+    }
+    
+    .top {
+      background: red;
+    }
+    
+    .placeholder {
+      background: green;
+      width: 100%;
+      height: 100%;
+      position: relative;
+    }
+    
+    .square-table {
+      background: yellow;
+      aspect-ratio: 1/1;
+      height: 100%;
+      position: absolute;
+    }
+    
+    .bottom {
+      background: blue;
+    }
+  </style>
+</head>
+
+<body style=""height: 100%;"">
+  <div class=""main"">
+    <div class=""top"">Top</div>
+    <div class=""placeholder"">
+      <p>Generic placeholder</p>
+      <table class=""square-table"">
+        <tbody>
+          <tr>
+            <td>abc</td>
+          </tr>
+        </tbody>
+      </table>
+    </div>
+    <div class=""bottom"">Bottom</div>
+  </div>
+</body>
+
+</html>
+
+
+

+

Any help or pointers in the right direction would be much appreciated.

","

Grid children have min-height: auto set by default which means they will always resize based on the content. So you can set min-height: 100% on the .placeholder div. Then I set the placeholder div to also be a grid, and then the min-height fix on the table again -- see solution below

+

+
+
body { color: white; margin: 0; font-family: sans-serif; text-align: center }
+
+.main { background: gray }
+.top { background: red }
+.placeholder { background: green }
+.bottom { background: blue }
+.square-table { background: yellow; color: black }
+
+.main {
+  height: 100vh;
+  grid-template-rows: 20% 60% 20%;
+  display: grid;
+}
+
+.placeholder {
+  min-height: 100%;
+  grid-template-rows: fit-content(0) 1fr;
+  display: grid;
+  justify-content: center;
+}
+
+.square-table {
+  margin: auto;
+  max-height: 100%;
+  min-height: 100%;
+  aspect-ratio: 1/1;
+}
+
<div class=""main"">
+  <div class=""top"">Top</div>
+  <div class=""placeholder"">
+    <div> <!-- if no intro just remove <p> tag and leave the <div> empty -->
+      <p>Generic placeholder</p>
+    </div>
+    <table class=""square-table"">
+      <tbody>
+        <tr>
+          <td>abc</td>
+        </tr>
+      </tbody>
+    </table>
+  </div>
+  <div class=""bottom"">Bottom</div>
+</div>
+
+
+

",css +"How to block the width extension of sibling elements when creating a hover with a css transition

I need to increase the width of a list of elements when I hover over a certain element using a CSS transition. +The CSS functionality works, but the problem is that the hover moves the sibling elements. How can this problem be overcome with CSS?

+

+
+
.aside-menu__element {
+  width: 68px;
+  height: 68px;
+  background-color: #999;
+  color: #fff;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  cursor: pointer;
+  transition: all 1s;
+}
+
+.aside-menu__element:hover {
+  background-color: green;
+  border-radius: 20px;
+  width: 300px;
+}
+
<div class=""aside-menu"">
+  <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-up-long""></i></div>
+  <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-right-long""></i></div>
+  <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-left-long""></i></div>
+</div>
+
+
+

+

The link below shows the HTML and CSS code I used: codepen

","

just add this code

+
.aside-menu { 
+  position:fixed;
+  right:50px;
+  top:150px;
+  display: flex;    
+  align-items: flex-end;
+  flex-direction: column;
+}
+
+

working sample codepen

+

+
+
.aside-menu {
+    position:fixed;
+    right:50px;
+    top:0px;
+   display: flex;    
+  align-items: flex-end;
+  flex-direction: column;
+}
+
+.aside-menu__element {
+     width: 68px;
+    height: 68px;
+    background-color: #999;
+    color: #fff;
+    display: flex;
+    justify-content: center;
+    align-items: center;
+    cursor: pointer;
+    transition: all 1s;
+}
+
+.aside-menu__element:hover {
+    background-color: green;
+    border-radius: 20px;
+    width: 300px;
+}
+
<div class=""aside-menu"">
+  <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-up-long""></i></div>
+    <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-right-long""></i></div>
+    <div class=""aside-menu__element""><i class=""fa-solid fa-arrow-left-long""></i></div>
+</div>
+
+
+

",css +"Table cells lose spacing when inside div

I'm building a web app using HTML & SVG, and I've run into a weird problem with tables. When I move my table into a particular div, all the cells lose their spacing.

+

This is my expected result:

+

+

This is what I actually get:

+

+

To achieve the expected result, I put my table 'habitruler' inside 'main' but above 'habits':

+

+

What I want to do though is put 'habitruler' inside 'habits' like this:

+

+

All I'm doing is moving it inside another div, but the moment I do that all the spacing disappears between cells as you see in image #2.

+

This is the css for the div 'habits':

+

+

And this is the table inside 'habitruler':

+

+

This even happens when I remove all the other child elements from 'habits'. I can't find anything out of the ordinary that would cause this. I also can't find any information on tables that would explain this behaviour. Does anyone have an idea why this is happening, or what I can try next to find out?

","

habitruler maybe inherits style from habits, try !important

+

(also show css from devtools for habitruler)

",css +"How to detect classname with onclick event

I want to be able to click on an element and then depending on whether it has a specific class name, do something.

+

Here is what I have so far:

+
<div class="my-class" onclick="myFunction()"/>
+
+
function myFunction() {
+  if (element.classList.contains("my-class")) {
+    //do something
+  }
+}
+
+

where am I going wrong?

","

You need to pass the click event then get the target element which in this case is the clicked element.

+

+
+
function myFunction(event) {
+  if (event.target.classList.contains(""my-class"")) {
+    alert(""I Do things becuase i have (my-class)"")
+  }
+}
+
<button class=""my-class"" onclick=""myFunction(event)"">Click me</button>
+<br/>
+<br/>
+<br/>
+<br/>
+<button onclick=""myFunction(event)"">I Do nothing</button>
+
+
+

",css +"dynamically created button onclick is not working in react js

I dynamically create a button element in my javascript function and then add an onclick event to that button. But after I press that button I get this error Uncaught ReferenceError: removeQuestionis not defined (removeQuestionis is my function name )

+

this is the button i created inside of my js function

+
const addQuestions = () => {
+   const removeBtn = '<a color="primary" onClick={removeQuestion}> x</a>';
+   window.document.body.insertAdjacentHTML('beforeend', removeBtn);
+};
+
+

this function are called by onclick

+
const removeQuestion = () => {
+        console.log('test')
+    };
+
","

this is issue with insertAdjacentHTML i used React.createElement and after rendered using ReactDOM.render

+
let input = React.createElement("input",{className:"questionTextInput",name:"textInputQuestion[]"},null);
+   ReactDOM.render(input,questionPreview);
+
",css +"Can an element be hidden and shown without Javascript?

I'm working on an app where I am using the DOMTokenList for shown and hidden an element using add() and remove() methods but the code is getting big. Example:

+
button.addEventListener("click", () => {
+   elem1.classList.add("display-none");
+   elem2.classList.remove("display-none");
+   elem3.classList.remove("display-none");
+   elem4.classList.add("display-none");
+});
+
+button2.addEventListener("click", () => {
+   elem1.classList.remove("display-none");
+   elem2.classList.add("display-none");
+   elem3.classList.add("display-none");
+   elem4.classList.remove("display-none");
+});
+
+

I've seven code parts similar to the example and I started looking others ways but I tried with CSS

+

+
+
.box {
+    --displayRed: block;
+    --displayGreen: none;
+    --displayBlue: none;
+    height: 100px;
+    width: 100px;
+}
+
+.box--red { 
+    display: var(--displayRed);
+    background-color: #ff0000;
+}
+
+.box--green { 
+    display: var(--displayGreen);
+    background-color: #00ff00;
+}
+
+.box--blue { 
+    display: var(--displayBlue);
+    background-color: #0000ff;
+}
+
+.box--red:target {
+  --displayRed: block;
+  --displayGreen: none;
+  --displayBlue: none;
+}
+
+.box--green:target {
+  --displayRed: none;
+  --displayGreen: block;
+  --displayBlue: none;
+}
+
+.box--blue:target {
+  --displayRed: none;
+  --displayGreen: none;
+  --displayBlue: block;
+}
+
<div>
+    <div class=""box"">
+        <div id=""boxRed"" class=""box box--red""></div>
+        <div id=""boxGreen"" class=""box box--green""></div>
+        <div id=""boxBlue"" class=""box box--blue""></div>
+    </div>
+    
+    <nav>
+      <ul>
+        <li><a href=""#boxRed"">Show red box</a></li>
+        <li><a href=""#boxGreen"">Show green box</a></li>
+        <li><a href=""#boxBlue"">Show blue box</a></li>
+      </ul>
+    </nav>
+</div>
+
+
+

+

I was expecting the red box to hide when I clicked the link to show the yellow box but it only scrolled down and didn't hide the red box. I tried to find others solution with videos, Pseudo-classes, Selectors, even with two question that are Can text be hidden and shown using just CSS (no JavaScript code)? [closed] and Ocultar y Mostrar un elemento css but I can't find the perfect idea. I ACCEPT SUGGESTIONS

","

The trick is defaulting to the red box when there's no hash fragment. I'm not sure you can do that with a pure CSS solution. (Edit: it turns out you can, as shown by Kaiido, provided you can put the default at the end; I should have thought of the general sibling combinator! But the CSS custom properties [aka "variables"] aren't actually doing anything in that AFAICS, see this fiddle.)

+

I don't know if it's possible to do this with CSS custom properties (aka "variables"); I tend to think not, since setting a custom property in the selector rule for one sibling (say, .box--blue:target) doesn't change its value for any elements not inside that .box--blue element (doesn't change it for the .box--red sibling, for instance). (Fiddle.) But you can definitely show/hide boxes with the old checkbox/radio button trick:

+
    +
  1. Define the boxes as display: none.

    +
  2. +
  3. Have invisible radio buttons immediately prior to the box the radio button will relate to in the same parent:

    +
    <input type="radio" name="box-controller" id="chk-box--red" checked>
    +<div id="boxRed" class="box box--red"></div>
    +
    +
  4. +
  5. Have label elements that tick the radio button for that box (via id/for) instead of links.

    +
    <label tab-index="0" for="chk-box--red">Show red box</label>
    +
    +

    In the above, note that I've added tab-index to the label so it show sup in the tabbing order. We probably also want CSS that underlines it or similar.

    +
  6. +
  7. Have a CSS rule that says the .box immediately after a checked radio button should be display: block:

    +
    input[name=box-controller]:checked + .box {
    +    display: block;
    +}
    +
    +
  8. +
+

Live example:

+

+
+
.box {
+    height: 100px;
+    width: 100px;
+}
+/* Hide boxes inside the outer box until/unless shown */
+.box .box {
+    display: none;
+}
+
+label {
+    text-decoration: underline;
+}
+
+input[name=box-controller] {
+    display: none;
+}
+input[name=box-controller]:checked + .box {
+    display: block;
+}
+
+.box--red { 
+    background-color: #ff0000;
+}
+
+.box--green { 
+    background-color: #00ff00;
+}
+
+.box--blue { 
+    background-color: #0000ff;
+}
+
<div>
+    <div class=""box"">
+        <input type=""radio"" name=""box-controller"" id=""chk-box--red"" checked>
+        <div id=""boxRed"" class=""box box--red""></div>
+        <input type=""radio"" name=""box-controller"" id=""chk-box--green"">
+        <div id=""boxGreen"" class=""box box--green""></div>
+        <input type=""radio"" name=""box-controller"" id=""chk-box--blue"">
+        <div id=""boxBlue"" class=""box box--blue""></div>
+    </div>
+    
+    <nav>
+      <ul>
+        <li><label tab-index""0"" for=""chk-box--red"">Show red box</label></li>
+        <li><label tab-index""0"" for=""chk-box--green"">Show green box</label></li>
+        <li><label tab-index""0"" for=""chk-box--blue"">Show blue box</label></li>
+      </ul>
+    </nav>
+</div>
+
+
+

+

Important caveat: With the above, the URL is no longer driving the process (it doesn't change as you choose boxes). That's because you can't have a label inside an a, and if you put the a inside the label because it prevents the label doing its job. If having the state in the URL is important to you, look at the JavaScript solution (which doesn't repeat itself) below.

+
+

You indicated that your concern with the JavaScript solution was that you were repeating a lot of code. There's no need to do that. Just for what it's worth, here's a JavaScript solution driven the hash fragment that works regardless of how many boxes you have; comments within:

+

+
+
// The function that shows the current box, hiding others
+function showCurrentBox() {
+    // Get the box to show, defaulting to `boxRed`
+    const hash = location.hash.replace(/^#/, """") || ""boxRed"";
+
+    // Hide any box we've previously shown
+    // (Note the use of optional chaining, since `querySelector` may return `null`)
+    document.querySelector("".box.showing"")?.classList.remove(""showing"");
+
+    // Show the box (again with optional chaining in case the fragment doesn't identify a box)
+    document.getElementById(hash)?.classList.add(""showing"");
+}
+// Run on startup
+showCurrentBox();
+// Run whenver the hash changes
+window.addEventListener(""hashchange"", showCurrentBox);
+
.box {
+    height: 100px;
+    width: 100px;
+}
+
+/* Hide boxes inside the outer box until/unless shown */
+.box .box {
+    display: none;
+}
+
+.box.showing {
+    display: block;
+}
+
+.box--red { 
+    background-color: #ff0000;
+}
+
+.box--green { 
+    background-color: #00ff00;
+}
+
+.box--blue { 
+    background-color: #0000ff;
+}
+
<div>
+    <div class=""box"">
+        <div id=""boxRed"" class=""box box--red showing""></div>
+        <div id=""boxGreen"" class=""box box--green""></div>
+        <div id=""boxBlue"" class=""box box--blue""></div>
+    </div>
+    
+    <nav>
+      <ul>
+        <li><a href=""#boxRed"">Show red box</a></li>
+        <li><a href=""#boxGreen"">Show green box</a></li>
+        <li><a href=""#boxBlue"">Show blue box</a></li>
+      </ul>
+    </nav>
+</div>
+
+
+

+

Adding boxes to that is just a matter of defining their CSS and giving them an ID; the JavaScript code doesn't change.

+

With this solution, the URL does drive the boxes. Bookmark the URL showing the green box, and that's what shows when you come back to it.

",css +"How to animate a class in css?

I am very new to this and trying to animate my "rd" class but I can not figure out why it is not animating. +My final goal is when I scroll down to next page the items on the first page will fade out. +I would appreciate any help. +here what I got so far: +Codepen

+

+
+
.rd {
+  display: flex;
+  flex-direction: column;
+  justify-items: center;
+  align-items: center;
+  overflow: visible;
+  height: 100%;
+  opacity: 100%;
+  animation: RD 5s infinite;
+}
+@keyframes rd {
+  0% {
+    left: 0px; opacity:100%;
+  }
+
+  50% {
+    left: 200px; opacity:0%;
+  }
+
+  100% {
+    left: 0px; opacity:100%;
+  }
+}
+
+.crown {
+  height: 200px;
+}
+
+.heart {
+  position: relative;
+  transform: rotateZ(45deg);
+  animation: heart 1s infinite;
+  margin-top: -50px;
+}
+
+@keyframes heart {
+  0% {
+    height: 100px;
+    width: 100px;
+  }
+
+  50% {
+    height: 50px;
+    width: 50px;
+  }
+
+  100% {
+    height: 100px;
+    width: 100px;
+  }
+}
+
<div id=""fullpage"">
+  <section class=""vertical-scrolling"">
+    <div class=""rd"">
+      <img class=""crown"" src=""https://m.media-amazon.com/images/I/6176t0uwOEL._SL1200_.jpg"" alt=""crown"" />
+      <img class=""heart"" src=""https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Heart_coraz%C3%B3n.svg/1920px-Heart_coraz%C3%B3n.svg.png"">
+      </d>
+
+    </div>
+  </section>
+</div>
+
+
+

","

There are two small things you are missing. +Both are in your .rd class properties

+
    +
  1. animation: RD 5s infinite; +Your keyframe is named rd with small letters, in your animation property you are using RD with uppercase letters. Both need to match, so either both lower case or uppercase +-> animation: rd 5s infinite;

    +
  2. +
  3. left property needs position: relative | absolute +Your animation is doing a "left" position change. In order to change positions (top | left | bottom | right), your element need to be position: relative or position: absolute +In your case relative is enough

    +
  4. +
+

+
+
.rd {
+  display: flex;
+  flex-direction: column;
+  justify-items: center;
+  align-items: center;
+  overflow: visible;
+  height: 100%;
+  opacity: 100%;
+  animation: rd 5s infinite;
+  position: relative;
+}
+@keyframes rd {
+  0% {
+    left: 0px;
+  }
+
+  50% {
+    left: 200px;
+  }
+
+  100% {
+    left: 0px;
+  }
+}
+
+.crown {
+  height: 200px;
+}
+
+.heart {
+  position: relative;
+  transform: rotateZ(45deg);
+  animation: heart 1s infinite;
+  margin-top: -50px;
+}
+
+@keyframes heart {
+  0% {
+    height: 100px;
+    width: 100px;
+  }
+
+  50% {
+    height: 50px;
+    width: 50px;
+  }
+
+  100% {
+    height: 100px;
+    width: 100px;
+  }
+}
+
<div id=""fullpage"">
+  <section class=""vertical-scrolling"">
+    <div class=""rd"">
+      <img class=""crown"" src=""https://m.media-amazon.com/images/I/6176t0uwOEL._SL1200_.jpg"" alt=""crown"" />
+      <img class=""heart"" src=""https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Heart_coraz%C3%B3n.svg/1920px-Heart_coraz%C3%B3n.svg.png"">
+      </d>
+
+    </div>
+  </section>
+</div>
+
+
+

",css +"How to change flex column width while keeping item centered

I have a flexbox in my HTML, and I have two columns. What I have trouble doing is changing the right column's width. If I set the width to, say, width: 50%, the .container is no longer centered on the page, and the Google Maps size is also changed. I am trying to shrink the .container size but keep the whole flexbox centered on the page and the size of the maps the same. Any help would be greatly appreciated.

+

+
+
#google-maps
+{
+    background: #FFFFFF;
+}
+
+.hours-and-location
+{
+}
+
+#hours-and-location-container
+{
+    display: flex;
+    flex-direction: row;
+    justify-content: center;
+    margin: 3em;
+    width: 50%;
+}
+
+.column
+{
+    display: flex;
+    flex-direction: column;
+    margin: 1em;
+}
+
+.locations
+{
+    width: 100%;
+}
+
+.page-title-header
+{
+    text-align: center;
+}
+
<h1 class=""page-title-header"">
+    Hours and Locations
+</h1>
+
+<div id=""hours-and-location-container"">
+    <iframe class=""column"" id=""google-maps""
+            src=""https://www.google.com/maps/d/u/0/embed?mid=1_iD-tpjnLUFwGIWoEcsx05qBgbx112w&ehbc=2E312F""
+            width=""600"" height=""500"">
+    </iframe>
+
+    <div class=""hours-and-location"">
+        <div class=""locations column"">
+            <h2>
+                Locations
+            </h2>
+            <p>
+                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
+                ut labore et dolore magna aliqua.
+            </p>
+            <p>
+                Augue mauris augue neque gravida in. Est sit amet facilisis magna. In vitae turpis massa sed
+                elementum tempus egestas sed.
+            </p>
+            <p>
+                Lectus quam id leo in vitae turpis massa sed.
+            </p>
+            <p>
+                Imperdiet proin fermentum leo vel orci porta non pulvinar. A iaculis at erat pellentesque adipiscing
+                commodo elit at imperdiet. Semper eget duis at tellus at urna condimentum. Purus in massa tempor
+                nec feugiat nisl.
+            </p>
+        </div>
+        <div class=""hours"">
+
+        </div>
+    </div>
+</div>
+
+
+

","

I think you're looking for this

+

+
+
#google-maps
+{
+    background: #FFFFFF;
+}
+
+.hours-and-location
+{
+  width:40vh
+}
+
+#hours-and-location-container
+{
+    display: flex;
+    flex-direction: row;
+    justify-content: center;
+    align-items:center;
+    margin: 3em;
+
+}
+
+.column
+{
+
+    margin: 1em;
+}
+
+
+
+.page-title-header
+{
+    text-align: center;
+}
+
<h1 class=""page-title-header"">
+    Hours and Locations
+</h1>
+
+<div id=""hours-and-location-container"">
+    <iframe class=""column"" id=""google-maps""
+            src=""https://www.google.com/maps/d/u/0/embed?mid=1_iD-tpjnLUFwGIWoEcsx05qBgbx112w&ehbc=2E312F""
+            width=""600"" height=""500"">
+    </iframe>
+
+    <div class=""hours-and-location"">
+        <div class=""locations column"">
+            <h2>
+                Locations
+            </h2>
+            <p>
+                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
+                ut labore et dolore magna aliqua.
+            </p>
+            <p>
+                Augue mauris augue neque gravida in. Est sit amet facilisis magna. In vitae turpis massa sed
+                elementum tempus egestas sed.
+            </p>
+            <p>
+                Lectus quam id leo in vitae turpis massa sed.
+            </p>
+            <p>
+                Imperdiet proin fermentum leo vel orci porta non pulvinar. A iaculis at erat pellentesque adipiscing
+                commodo elit at imperdiet. Semper eget duis at tellus at urna condimentum. Purus in massa tempor
+                nec feugiat nisl.
+            </p>
+        </div>
+        <div class=""hours"">
+
+        </div>
+    </div>
+</div>
+
+
+

",css +"Css animation - with vertical line on a horizontal line

I have an expanding line animation in css as can be seen in the demo link

+

I would like some help in figuring out how to add a vertical line at both ends when the animation stops.

+

Something like the attached image : +

+

Can someone please help me with this ?

","

Perhaps using pseudo elements

+
.line::before,
+.line::after
+{
+  content: ''; /* important for pseudo elements */
+  width: 4px;
+  height: 20px;
+  position: absolute;
+  background: red;
+}
+.line::after { right: 0 } /* snap to right */
+.line::before { left: 0 } /* snap to left */
+
",css +"What's the best color scheme for an Order Form Page?

I'm creating a random order form and just wanted to know which colors I should use and for which elements. Fore example, I'm using rgb(11, 11, 93) for background and white for font color. But I need help with choosing the colors for other elements like the background-color for the input fields and what should be the height for the input field.

+

+
+
body {
+    background-color: rgb(11, 11, 93); 
+    color: white;
+    font-family: 'Poppins', sans-serif;
+    font-size: 20px;
+    font-weight: 400;
+    line-height: 1.4;
+    margin: 0;
+    height: 100vh;
+   }
+   h1, p {
+    text-align: center;
+   }
+   p {
+    margin-top: -12px;
+    font-style: italic;
+   }
+   form {
+    max-width: 700px;
+    margin-right: auto;
+    margin-left: auto;
+   }
+   fieldset {
+    padding: 10px 0;
+    border: none;
+    border-bottom: 3px solid rgb(66, 23, 146);
+   }
+   label {
+    display: block;
+    font-size: 1.125rem;
+   }
+   input {
+    margin: 5px auto;
+    padding: 3px;
+    background:rgb(66, 23, 146);
+    color: aqua;
+    border: none;
+    border-radius: 7px;
+   }
+   #radio, #checkbox {
+    display: block
+    min-height: 1.5rem;
+    min-width: 1.25rem;
+   }
+   #bio {
+    display: block;
+   }
+   .input-field {
+    width: 40%;
+    height: 1.7em; 
+    font-size: 17px;
+   }
+   .question {
+    font-size: 18px;
+    color:aqua
+   }
+   select {
+    display: block;
+    margin: 5px 0;
+   }
+   .input-field {
+    height: 20px;
+   }
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+    <meta charset=""UTF-8"">
+    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+    <title>Build a Survey Form Project</title>
+    <link rel=""stylesheet"" href=""styles.css"">
+</head>
+
+    
+  <body>
+    <h1 id=""title"">Order Form</h1>
+    <p id=""description"">Order any kind of responsive website for your business, blog, portfolio,etc.</p>
+<form id=""survey-form"">
+  <fieldset id=""bio"">
+  <label id=""name-label"">Name: <input type=""text"" class=""input-field"" id=""name"" placeholder=""Enter your name"" required></label>
+  <label id=""email-label"">Email: <input type=""email"" class=""input-field"" id=""email"" placeholder=""Enter your Email"" required></label>
+<label id=""number-label"">Age: <input type=""number"" min=""16"" max=""70"" class=""input-field"" placeholder=""Age""></label>
+</fieldset>
+
+<fieldset>
+  <label class=""question"">What kind of Website are you looking for? 
+  <select id=""dropdown"" class=""input-field"">
+    <option>(Select Website type)</option>
+    <option>Business</option>
+    <option>Blog</option>
+    <option>Personal</option>
+    <option>Portfolio</option>
+  </select>
+  </label>
+
+  <label class=""question"">Have you had a website in the past?</label>
+  <label><input type=""radio"" id=""radio"" name=""yes-no"" value=""yes""> Yes</label>
+  <label><input type=""radio"" id=""radio"" name=""yes-no"" value=""no""> No</label>
+
+  <label class=""question"">Which pages should be in your website?</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Home</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Contact</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page"">
+  Services</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Blog</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Portfolio</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Store</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> About Us</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Privacy Policy</label>
+  <label><input type=""checkbox"" id=""checkbox"" value=""contact-page""> Terms and Conditions</label>
+
+</fieldset>
+</form>
+  </body>
+</html>
+
+
+

+

You can say that I've completed the basic layout. I'm inserting the code for you to look at what I've created. +One more thing. I'm learning web development and and this is just a practice project that I need help with.

","

There's a lot of subjectivity to questions like this, as there is no "best" color scheme, in general, for anything. One way to get started with color is to think about not just the color but the value of the color: how light or dark it is. Colors may look great in isolation but play poorly together due to any number of variables, but if the values are correct, you can guarantee legibility.

+

The colors you choose anywhere in design are not random, and you need to consider things such as your audience, the aesthetic you are trying to achieve, legibility, accessibility, the type of screen and time of day (light vs. dark modes), etc.

+

When in doubt, copy what others have done before you. Look at a website that feels good to you, try to learn from the choices they made. Are their input fields the same size as their type? Are they larger? How much white-space/padding/margin are they using? What colors are the type, how dark or light are they compared to the background? Is it easy to read?

+

If you just need to pick anything at random, you can also try copying from a palette like one of the randomly generated ones at https://coolors.co/generate.

",css +"Input box not displaying bigger value on to the users page
+

I want the programme to get the biggest number that the user has enter in one of the input boxes and display the bigger number to the user.I would also like some improvements to my code. I would it also be possible to do it with one input box instead of two

+
+
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        body{
+            text-align: center;
+        }
+    </style>
+</head>
+<body>
+    <h1>Max number</h1>
+    <input id="box1" placeholder="Enter the fist number" type="number">
+    <input id="box2" placeholder="Enter the second number" type="number">
+    <button >Submit</button>
+    <div id="store"></div>
+    <script>
+        const box1 = document.getElementById('box1');
+        const box2 = document.getElementById('box2');
+        const store = document.getElementById('store');
+        
+        function max(){
+            
+            const element = document.createElement('div');
+            const  num1 = box1.value;
+            const  num2 = box2.value;
+
+            if (num1<num2 ){
+                    element.innerHTML= num2;
+                    store.appendChild(element);
+                }
+            if (num2<num1){
+                element.innerHTML= num1;
+                store.appendChild(element);
+            }
+        }
+    
+    
+    
+    
+    
+    </script>
+</body>
+</html>
+
","

First of all, ECMAScript comes with a Math.max() function, so there is no need to re-implement that comparison logic.

+

Also, your max function doesn’t run automatically. You need to register it as an event listener on the “Submit” button using addEventListener and the click event in order to have it invoked upon clicking the button.

+

+
+
const box1 = document.getElementById('box1');
+const box2 = document.getElementById('box2');
+const store = document.getElementById('store');
+const button = document.getElementById('submit');
+
+// upon clicking on the button …
+button.addEventListener('click', () => {
+    max(); // … run `max()``
+});
+
+function max() {
+  const element = document.createElement('div');
+  element.innerText = Math.max(box1.value, box2.value);
+  store.appendChild(element);
+}
+
 <h1>Max number</h1>
+ <input id=""box1"" placeholder=""Enter the fist number"" type=""number"">
+ <input id=""box2"" placeholder=""Enter the second number"" type=""number"">
+ <button id=""submit"">Submit</button>
+ <div id=""store""></div>
+
+
+

+

Of course, there is not yet a validation that checks if the given values are actually numbers.

+

I don’t understand your request about doing it with only “one input box”, though, as determining the larger number (out of many) implies having more than one input, so please specify. Do you mean “multiple values in one input box” like comma-separated?

",css +"Using multiple input sliders to change their own individual class

So basically the idea is to start a presentation of different fonts/typography with simple options the first one being the possibility to change the size of each font. So I tried a very non-economical logic by changing the querySelector with a class but it seems to only take the first input range slider that changes the whole body. My question is how can I make multiple input range sliders that can change specific things (here the example is size but later on I would like to add spacing, line height & width per font). So I don't know how to get around this and apply one input slider to a certain class?

+

+
+
document.querySelector('input').addEventListener('input', e => document.querySelector('.font_1').style.fontSize = e
+  .target.value + 'em');
+document.querySelector('input').addEventListener('input', e => document.querySelector('.font_2').style.fontSize = e
+  .target.value + 'em');
+document.querySelector('input').addEventListener('input', e => document.querySelector('.font_3').style.fontSize = e
+  .target.value + 'em');
+document.querySelector('input').addEventListener('input', e => document.querySelector('.font_4').style.fontSize = e
+  .target.value + 'em');
+document.querySelector('input').addEventListener('input', e => document.querySelector('.font_5').style.fontSize = e
+  .target.value + 'em');
+document.querySelector('input').addEventListener('input', e => document.querySelector('.font_6').style.fontSize = e
+  .target.value + 'em');
+
body {
+  margin: 0;
+  padding: 0;
+  box-sizing: border-box;
+  height: 100vh;
+  width: 100vw;
+  overflow: hidden;
+}
+
<div class=""container"">
+  <header>
+    <label>Change font-size</label>
+    <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" />
+    <p class=""font_1"">Some text that should dynamically change size.</p>
+    <label>Change font-size</label>
+    <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" />
+    <p class=""font_2"">Some text that should dynamically change size.</p>
+    <label>Change font-size</label>
+    <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" />
+    <p class=""font_3"">Some text that should dynamically change size.</p>
+    <label>Change font-size</label>
+    <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" />
+    <p class=""font_4"">Some text that should dynamically change size.</p>
+    <label>Change font-size</label>
+    <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" />
+    <p class=""font_5"">Some text that should dynamically change size.</p>
+  </header>
+</div>
+
+
+

","

I think a way to do it would be to add an identifier to each of the p elements. It could be a class, an id or event an attribute. +Then you can also add an attribute to each of the inputs telling them which p element they should affect.

+

I have created a little snippet for you, where i use the class-to-change attribute on the inputs with the corresponding class name of the p element they should change.

+

Then we loop through the inputs and when an input changes we also change the font-size of the corresponding p element.

+

Both the html and js could use a bit of cleaning up (the different inputs shouldn't have the same id, we should use a class to select the inputs, catch possible errors on the js, ...), but i think you can handle that!

+

+
+
const inputs = document.querySelectorAll('input');
+
+inputs.forEach((input) => {
+  input.addEventListener('change', handleInputChange);
+})
+
+function handleInputChange(event) {
+  const classToChange = event.target.getAttribute('class-to-change');
+  const propertyToChange = event.target.getAttribute('property-to-change');
+  const targetPElement = document.querySelector(`.${classToChange}`);
+  
+  targetPElement.style[propertyToChange] = `${event.target.value}em`;
+}
+
<header>
+      <label>Change font-size</label>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_1"" property-to-change=""fontSize""/>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_1"" property-to-change=""letterSpacing""/>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_1"" property-to-change=""lineHeight""/>
+      <p class=""font_1"">Some text that should dynamically change size.</p>
+      <label>Change font-size</label>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_2"" property-to-change=""fontSize""/>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_2"" property-to-change=""letterSpacing""/>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_2"" property-to-change=""lineHeight""/>
+      <p class=""font_2"">Some text that should dynamically change size.</p>
+      <label>Change font-size</label>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_3""/>
+      <p class=""font_3"">Some text that should dynamically change size.</p>
+      <label>Change font-size</label>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_4""/>
+      <p class=""font_4"">Some text that should dynamically change size.</p>
+      <label>Change font-size</label>
+      <input type=""range"" value=""1.2"" min=""1.2"" max=""2.6"" step="".0002"" id=""slider"" class-to-change=""font_5""/>
+      <p class=""font_5"">Some text that should dynamically change size.</p>
+    </header>
+
+
+

",css +"Why isnt my border containing the Button?

I want the "Dive" button to be surrounded by the border aswell. Anybody got an Idea? +jsfiddle

","

You played a little too much with position:relative. You can solve your problem by adding a padding-bottom:40px for class logboxcontain, but I would recommend trying using less relative positioning.

",css +"Something goes wrong when I unhover the div

I'm trying to change the text on hover, it works, but I'm wondering why the text goes to the right when you unhover the div.

+

I want to make the same effect when you unhover the div. Is it because the position absolute? I'm pretty new to web development.

+

+
+
.article-title {
+    opacity: 1;
+    width: 24%;
+    position: absolute;
+    padding-bottom: 10px;
+    color: #ff0099;
+    font-size: 30px;
+    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
+}
+
+.article-desc {
+    width: 23%;
+    position: absolute;
+    opacity: 0;
+    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
+}
+
+.box-link {
+    display: flex;
+    flex-direction: column;
+    padding: 10px;
+    border: 2px solid black;
+    border-radius: 10px;
+    height: 200px;
+    width: 25%;
+    text-align: center;
+    cursor: pointer;
+    transition: transform .5s, box-shadow .2s;
+}
+
+.box-link:hover {
+    transform: scale(1.15);
+    box-shadow: 0 0 51px rgba(33, 33, 33, .4);
+}
+
+.box-link:hover .article-title {
+    width: 89%;
+    position: absolute;
+    opacity: 0;
+}
+
+.box-link:hover .article-desc {
+    width: 95%;
+    opacity: 1;
+}
+
<div class=""box-link article-1"">
+    <a class=""article-title"">The ultimate guide to Australian native flowers</a>
+    <a class=""article-desc"">Looking to add a touch of Australiana when building a bouquet or growing your garden? There are so many stunning Australian native flowers to choose from.</a>
+</div>
+
+
+

","

Change your CSS to :

+

+
+
.article-title {
+    opacity: 1;
+    position: absolute;
+    padding-bottom: 10px;
+    color: #ff0099;
+    font-size: 30px;
+    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
+}
+
+.article-desc {
+    position: absolute;
+    opacity: 0;
+    transition: all .5s ease-in-out, width 0s linear, absolute 0s linear;
+}
+
+.box-link {
+    display: flex;
+    flex-direction: column;
+    padding: 10px;
+    border: 2px solid black;
+    border-radius: 10px;
+    height: 200px;
+    width: 25%;
+    text-align: center;
+    cursor: pointer;
+    transition: transform .5s, box-shadow .2s;
+  position: relative;
+}
+
+.box-link:hover {
+    transform: scale(1.15);
+    box-shadow: 0 0 51px rgba(33, 33, 33, .4);
+}
+
+.box-link:hover .article-title {
+    position: absolute;
+    opacity: 0;
+}
+
+.box-link:hover .article-desc {
+    opacity: 1;
+}
+
<div class=""box-link article-1"">
+                <a class=""article-title"">The ultimate guide to Australian native flowers</a>
+                <a class=""article-desc"">Looking to add a touch of Australiana when building a bouquet or growing your garden? There are so
+                    many stunning Australian native flowers to choose from.</a>
+            </div>
+
+
+

+

The idea is to make the parent position relative so that you no longer need width explicitly to containerize the childs.

",css +"HTML + CSS - Button not returning to initial state after click

I am trying to implement a counter, but right now I'm only working with HTML, CSS and Bootstrap.

+
<button class="btn btn-purple ts24r">+</button>
+
+
.btn-purple {
+   background-color: var(--purple);
+   color: var(--white);
+}
+
+.btn-purple:hover {
+   background-color: var(--green);
+}
+
+

The problem is that when I click my button its background-color disappears and only appears again when I click somewhere else on the page.

+

The three states of the button: before click, hover and after click

+

I tried the following code, and it works at first glance, but now the button isn't "clickable" anymore, it stays red (only used for test purpose) and doesn't change color when hovered. As before, it only returns to purple and allows hover when I click elsewhere.

+
.btn-purple:focus {
+   background-color: red;
+}
+
+

Is there a way to make the button accepts multiple clicks, always staying purple and only changing when hovered (which was the initial state)?

","

It seems this is an issue with Bootstrap on MacOS and Chrome.

+

You may do something like below to remove the focus:

+
<a class="btn btn-purple ts24r" onclick="this.blur();">+</a>
+
+

Reference: How to remove focus around buttons on click

",css +"Adding a hover on card media does not work
      const mediaStyle = {
+    transition: "transform 1s",
+    "&:hover": {
+      transform: "scale(1.6)",
+    },
+  };
+
+

I have this card. Once I hover on a specific card, the card media or the picture on it will pop up. I tried the codes above, but it does not work

+
{data.map((i) => (
+          <Grid
+            item
+            xs={12}
+            sm={6}
+            md={4}
+            lg={3}
+            key={listOfPrjects.indexOf(elem)}
+          >
+            <Card style={cardStyle}>
+              <CardMedia  style={{ mediaStyle }}
+              />
+              <CardHeader title={i.title}/>
+            </Card>
+          </Grid>
+        ))}
+      </Grid>
+
","

In your CardMedia inside the Card component you can add the styling for the hovering

+
return (
+<>
+  {data.map((i, elementIndex) => (
+    <Card
+      sx={{
+        maxWidth: 345,
+        "&:hover": {
+          ".MuiCardMedia-root": {
+            transform: "scale3d(1.6, 1.6, 1)"
+          }
+        }
+      }}
+    >
+      <CardMedia
+        component="img"
+        height="140"
+        image="https://mui.com/static/images/cards/contemplative-reptile.jpg"
+        alt="green iguana"
+        // Add this if you want the hover on the image only and remove the above hover
+        // sx={{
+        //   transition: "all 0.2s ease",
+        //   "&:hover": {
+        //     transform: "scale3d(1.6, 1.6, 1)"
+        //   }
+        // }}
+      />
+      <CardContent>
+        <Typography gutterBottom variant="h5" component="div">
+          Lizard
+        </Typography>
+        <Typography variant="body2" color="text.secondary">
+          Lizards are a widespread group of squamate reptiles, with over
+          6,000 species, ranging across all continents except Antarctica
+        </Typography>
+      </CardContent>
+      <CardActions>
+        <Button size="small">Share</Button>
+        <Button size="small">Learn More</Button>
+      </CardActions>
+    </Card>
+  ))}
+</>
+
+

);

+

Here is a working codesandbox

",css +"Media Query Order not working, need to understand order rules

I have the following media queries in my CSS.

+

I have noticed that they are not acting correctly and some are being overwritten by others. What is the correct order for this? What are the rules for media queries and order?

+
1) @media screen and (max-width:767px) {
+2) @media screen and (max-width:992px) {
+3) @media screen and (max-width:1000px){
+4) @media screen and (max-width:480px){
+5) @media screen and (max-width:580px){
+6) @media screen and (max-width:632px){
+7) @media screen and (max-width:1170px){
+8) @media screen and (min-width: 650px){
+9) @media screen and (min-width: 993px){
+10) @media screen and (min-width:992px) and (max-width:1199px) {
+
+
+

UPDATED QUESTION:

+

Is it incorrect to use both min-width and max-width?

","

Your html/browser/etc.. read the css like a batchfile, from beginning to the end.

+

the last hit/match in a css file always overwrites the previous one

+

if you got this and your screen size is 700px:

+

Order 1:

+
@media screen and (max-width:767px){}
+@media screen and (max-width:992px){}
+
+

you will get the media of max-width:992px now

+

Order 2:

+
@media screen and (max-width:992px){}
+@media screen and (max-width:767px){}
+
+

you will get the media of max-width:767px now

+

This is your correct order:

+
@media screen and (max-width:1170px){}
+@media screen and (max-width:1000px){}
+@media screen and (max-width:992px){}
+@media screen and (max-width:767px){}
+@media screen and (max-width:632px){}
+@media screen and (max-width:580px){}
+@media screen and (max-width:480px){}
+
+

I make the example with out the min media

+

If your size is now 1171px your html/browser/etc.. will take/read the standard style of your css(outside the media queries), but again from the beginning to the end.

+

Check this too:

+

Responsive Web Design - Media Queries

+

Using media queries

",css +"Popup popping up under div html, svelte, tailwind css

I'm trying to make a website using svelte and tailwind. I made a little popup that pops up when you hover over the home icon. But when I later added a div it pops up under the div and does not show fully. How do I fix this? +Code: +Div that popup goes under: (is in seprate svelte component and is imported in index.svelte.)

+
<div class="fixed ml-15 mb-auto w-screen h-10 bg-gray-700">
+<h1 class="text-center text-white font-extrabold text-lg">Welcome.</h1>
+</div>
+
+

Div for the one of the popups and icons: (this one is also in another separate svelte component and is imported in index.svelte.)

+
    <div class="sidebar-icon group">
+    <a href="https://github.com/ratinchat" target="_blank">
+        <DiGithubBadge />
+    </a>
+    <span class="sidebar-tooltip group-hover:scale-100">Github</span>
+</div>
+
+

Css for popup:

+
.sidebar-tooltip {
+    @apply absolute w-auto p-2 m-2 min-w-max left-14 rounded-md shadow-md
+    text-white bg-gray-900 
+    text-xs font-bold 
+    transition-all duration-100 scale-0 origin-left;
+}
+
+

Helpfull images:

+

No popups

+

With popups

+

The home button popup is hidden under the topbar div. +How can I make it so that the popup (also named tooltip.) pops above the div instead of below. (specifically the home but what if I wanted to make more divs under?) Any help would be greatly appreciated.

","

Add the TailwindCSS class z-10 or higher to .sidebar-tooltip.

+

Without setting a z-index your elements will be rendered on the same plane as each other, causing overlaps to occur.

",css +"safe-area-inset-bottom not working on ios 15 safari

I'm trying to get my website to fit inside my phone screen. I have tried many variations of env(safe-area-inset-bottom) and constant(safe-area-inset-bottom) but both always return 0px (I've been using an app called Inspect to debug CSS on my iPhone 13).

+

Here's a link to the github repo. All code that relates to this issue should be in /src/app.tsx. Here is a link to the live site if you want to see the problem yourself.

+

UPDATE: I've been doing some testing and have found that in portrait mode, safe-area-inset-* is ALWAYS 0px, but in landscape mode it works as expected. Does this mean that safe-area-inset-* isn't the correct solution for ios 15 safari? Clearly the url bar obscures the 'safe area' in portrait mode...

+

I've made sure to add <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> to my head tag but this has no effect. Could someone please explain how I can ensure that my site doesn't go past the bottom URL bar on ios 15 Safari? I've attached screenshots from my phone showing the problem: + +

","

I think I made it work using -webkit-fill-available the other day which respects safe area.

+
body {
+    min-height: -webkit-fill-available;
+}
+
",css +"Animations of the bottom line from the center

I want to style the bottom line in the dropdown so that when I clicked it was the same color as the input, i.e. to focus on that color, but I read that focus doesn't work with a div, there were other options, but they don't work for me, also I want my dropdowns and inputs to have this animation in the bottom line on hover: https://jsfiddle.net/andrewphoenix228/v1spzha5/3/

+

+
+
/*******************************************************************************
+ *  Initialize the amount for the first currency
+ *******************************************************************************/
+function initializeAmount() {  
+  document.getElementById('amount-one').addEventListener('input', refreshAmount); 
+}
+
+/*******************************************************************************
+ *  Initialize the Swap trigger already existing in DOM
+ *******************************************************************************/
+function initializeSwap() {    
+  swap.addEventListener('click', () => {      
+    
+    const [selectOne, selectTwo] = document.querySelectorAll('.custom-select');
+    const amountOne = document.getElementById('amount-one');
+    const amountTwo = document.getElementById('amount-two');
+     
+    const [valueOne, valueTwo] = [selectOne, selectTwo].map(
+        select => select.querySelector('.custom-select__option--select').dataset.value
+      );
+    
+    //--------------------------------------------------------------------------
+    // Dirty trick to avoid problems when swapping currencies on the 2 DDs
+    // by finding the currencies not chosen by the two dropdowns
+    // and first selecting a third currency on the first dropdown
+    // before doing the actual swap
+    //--------------------------------------------------------------------------
+    const availableCurrencies = [];
+    const chosenCurrencies = [valueOne, valueTwo];
+    selectOne.querySelectorAll('.custom-select__list .custom-select__option-name').forEach((option)=>{
+      availableCurrencies.push( option.innerText );
+    });
+    const notChosenCurrencies = availableCurrencies.filter(chosen => !chosenCurrencies.includes(chosen));
+    
+    amountOne.value = amountTwo.value
+    selectOne.querySelector(`[data-value=""${notChosenCurrencies[0]}""]`).click();
+    selectTwo.querySelector(`[data-value=""${valueOne}""]`).click();
+    selectOne.querySelector(`[data-value=""${valueTwo}""]`).click();  
+    refreshConversionRatesAndAmount();
+  });
+}
+
+/*******************************************************************************
+ *  Initialize the Currency Dropdowns already defined in the DOM 
+ *******************************************************************************/
+function initializeCurrencyDropdowns() {
+  //given the array of all .custom-select
+  [...document.querySelectorAll("".custom-select"")]
+    //map()
+    .map(select => {
+      
+      //inits dropdown options
+      let selected = select.querySelector("".custom-select__option--select"");
+      if (selected) {
+        select.dataset.value = selected.dataset.value;
+        const placeholder = select.querySelector("".custom-select__placeholder"");
+        placeholder.innerHTML = """";
+        const pho = selected.cloneNode(true);
+        pho.classList.remove(""custom-select__option--select"");
+        placeholder.appendChild(pho);
+      }
+      
+      //adds click event listener to the list of options
+      select.querySelector("".custom-select__list"").addEventListener(""click"", e => {              
+        //--------------------------------------------------------------------------
+        // Logic to hide from the other DD the selected currency in this DD
+        //--------------------------------------------------------------------------
+        //fetches information about the currently selected dropdown
+        const thisDD = e.target.closest('.custom-select');
+        const currencyCurrentlySelected = e.target.closest('.custom-select__option').dataset.value;    
+       
+
+        //fetches information about the other dropdown
+        const otherDD_id = ((thisDD.id == 'curr-one' ? 'curr-two' : 'curr-one'));
+        const otherDD = document.getElementById(otherDD_id);
+
+        //removes the displaynone class to all the options in the other dropdown
+        otherDD.querySelectorAll('.custom-select__option').forEach((option)=>{
+          option.classList.remove('display-none');
+        });   
+        //adds the class displaynone to the currently selected currency in the second dropdown    
+        otherDD.querySelector(`.custom-select__option[data-value=""${currencyCurrentlySelected}""]`)
+          .classList.add('display-none');
+        
+        //-------------------------------------------------------------------------- 
+      
+        let target = e.target.closest("".custom-select__option"");
+        if (target) {
+          let parent = target.closest("".custom-select"");
+          parent
+            .querySelector("".custom-select__option--select"")
+            .classList.remove(""custom-select__option--select"");
+          target.classList.add(""custom-select__option--select"");
+          let selected = parent.querySelector("".custom-select__option--select"");
+          parent.dataset.value = selected.dataset.value;
+          const placeholder = parent.querySelector("".custom-select__placeholder"");
+          placeholder.innerHTML = """";
+          const pho = selected.cloneNode(true);
+          pho.classList.remove(""custom-select__option--select"");
+          placeholder.appendChild(pho);
+          target.closest("".custom-select"").classList.remove(""custom-select--drop"");
+        }
+        
+        //-------------------------------------------------------------------------- 
+        
+        refreshConversionRatesAndAmount();
+      });  
+      
+      //adds click event listener to the placeholder
+      select.querySelector("".custom-select__placeholder"").addEventListener(""click"", e => {
+        let target = e.target.closest("".custom-select__placeholder"");
+        if (target) {
+          target.closest("".custom-select"").classList.toggle(""custom-select--drop"");
+        }
+      });
+    });      
+}
+
+/*******************************************************************************
+ * Refresh the conversion rates and converted amount (and metadata)
+ * displayed in the respective labels
+ *******************************************************************************/
+async function refreshConversionRatesAndAmount() {
+
+  const rates = await fetchConversionRates();
+  
+  const currencyOne = getSelectedCurrencyOne();
+  const currencyTwo = getSelectedCurrencyTwo();
+  
+  const rateOne = rates[currencyOne];
+  const rateTwo = rates[currencyTwo];
+  
+  const amountOne = document.getElementById('amount-one');
+  const amountTwo = document.getElementById('amount-two');
+  
+  const rateLabel = document.getElementById('rate');
+  
+  const ratio = (1 * rateOne.rate / rateTwo.rate).toFixed(4);
+  rateLabel.innerText = `1 ${currencyOne} = ${ratio} ${currencyTwo}`;       
+  
+  amountTwo.ratio = ratio;
+  const newAmount = (amountOne.value * amountTwo.ratio).toFixed(2);
+  amountTwo.value = (amountOne.value !== '') ? newAmount : '';     
+    
+}
+/*******************************************************************************
+ * Refresh the amount only 
+ *******************************************************************************/
+function refreshAmount() {
+  const amountOne = document.getElementById('amount-one');
+  const amountTwo = document.getElementById('amount-two');  
+  const newAmount = (amountOne.value * amountTwo.ratio).toFixed(2);
+  amountTwo.value = (amountOne.value !== '') ? newAmount : '';      
+}
+
+/*******************************************************************************
+ * Fetch and return the conversion rates from a static url
+ *******************************************************************************/
+async function fetchConversionRates() {
+  const url = 'https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json';
+  const response = await fetch(url);   
+  const data = await response.json();  
+  data.unshift({
+    ""txt"": ""Українська гривня"",
+    ""rate"": 1,
+    ""cc"": ""UAH""
+  });
+  const ratesMapped = Object.assign({}, ...data.map((rate) => ({[rate.cc]: rate})));
+  return ratesMapped;
+}
+
+/*******************************************************************************
+ * Returns the Currency code selected on the first currency dropdown
+ *******************************************************************************/
+function getSelectedCurrencyOne() {
+  const curr_oneDD = document.querySelector('#curr-one.custom-select');
+  return curr_oneDD.textContent.trim().slice(0, 3);
+}
+
+/*******************************************************************************
+ * Returns the Currency code selected on the second currency dropdown
+ *******************************************************************************/
+function getSelectedCurrencyTwo() {
+  const curr_twoDD = document.querySelector('#curr-two.custom-select');
+  return curr_twoDD.textContent.trim().slice(0, 3);
+}
+
+initializeAmount();
+initializeSwap();
+initializeCurrencyDropdowns();
+refreshConversionRatesAndAmount();
+
body {
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  width: 100%;
+  min-height: 100vh;
+  margin: 0;
+}
+
+.custom-select {
+  display: block;
+  width: 150px;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+  position: relative;
+  -webkit-user-select: none;
+  -moz-user-select: none;
+  -ms-user-select: none;
+  user-select: none;
+  z-index: 1;
+  margin-bottom: 8.7px;
+}
+
+.custom-select:hover {
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54);
+}
+
+.custom-select__list {
+  display: block;
+  border-radius: 5px;
+  background-color: #fff;
+  padding: 5px 0;
+  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.15);
+  position: absolute;
+  z-index: 999;
+  left: 0;
+  top: calc(100% + 12px);
+  opacity: 0;
+  pointer-events: none;
+  transform: translateY(10px);
+  transition-property: transform, opacity;
+  transition-timing-function: ease-out;
+  transition-duration: 0.3s;
+  box-sizing: border-box;
+}
+
+.custom-select--drop .custom-select__list {
+  transform: translateY(0);
+  opacity: 1;
+  pointer-events: all;
+}
+
+.custom-select--drop .custom-select__placeholder::after {
+  transform: translateY(-80%) rotateX(360deg);
+}
+
+.custom-select__option {
+  display: flex;
+  justify-content: flex-start;
+  align-items: center;
+  padding: 0.5em 1.5em;
+  box-sizing: border-box;
+  cursor: pointer;
+  z-index: 0;
+}
+
+.custom-select__option-icon {
+  display: block;
+  flex-shrink: 0;
+  border-radius: 5px;
+  overflow: hidden;
+  margin-right: 10px;
+}
+
+.custom-select__option-icon img {
+  display: block;
+  width: 18px;
+  height: 15px;
+  max-height: 100%;
+  -o-object-fit: cover;
+  object-fit: cover;
+  margin: 0;
+}
+
+.custom-select__option-name {
+  display: block;
+  width: 100%;
+  text-transform: uppercase;
+  margin-right: 10px;
+}
+
+.custom-select__option-symbol {
+  display: block;
+  font-weight: bold;
+}
+
+.custom-select__option--select .custom-select__option-name {
+  color: #8dc641;
+}
+
+.custom-select__placeholder {
+  display: block;
+  width: 100%;
+}
+
+.custom-select__placeholder::after {
+  content: '';
+  display: block;
+  width: 0;
+  height: 0;
+  border: 6px solid transparent;
+  border-top-width: 6px;
+  border-bottom: 6px solid #616161;
+  position: absolute;
+  right: 0;
+  top: 50%;
+  transform: translateY(-30%) rotateX(180deg);
+  transition-property: transform;
+  transition-timing-function: ease-out;
+  transition-duration: 0.3s;
+}
+
+.custom-select__option {
+  padding-right: calc(1.5em + 10px);
+  position: relative;  
+}
+
+.custom-select {
+  display:inline-block;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+ }
+
+.custom-select:after {
+  display:block;
+  content: '';
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54); 
+  transform: scaleX(0);  
+  transition: transform 250ms ease-in-out;
+  position: relative;
+  bottom: -2px;
+}
+
+.custom-select:hover:after { transform: scaleX(1); 
+}
+
+.custom-select:focus {
+   border-bottom: 2px solid #8dc641;
+}
+
+/* .custom-select__placeholder .custom-select__option::before,
+.custom-select__placeholder .custom-select__option::after{
+  content: '';
+  position: absolute; bottom: -2px; 
+  width: 0;
+  height: 2px;
+  background-color: #8dc641;
+  transition: width .3s ease;
+}
+
+.custom-select__placeholder .custom-select__option::before {
+  left: 50%;
+}
+
+.custom-select__placeholder .custom-select__option::after {
+  right: 50%;
+}
+
+.custom-select--drop .custom-select__placeholder .custom-select__option::before,
+.custom-select--drop .custom-select__placeholder .custom-select__option::after {
+  width: 50%;
+}
+
+.custom-select__option:hover {
+  background-color: transparent;
+} */
+
+/* .container {
+  
+  border: solid 2px #212121;
+  border-radius: 10px;
+  background-color: white;
+  box-sizing: border-box;
+  -webkit-box-sizing: border-box;
+} */
+
+.header {
+  display: flex;
+  align-items: center;
+}
+
+.indent-right {
+  display: flex;
+  width: 24px;
+  height: 24px;
+  background-image: url(""https://cdn.privat24.ua/icons/file/ServiceCurrency.svg"");
+  background-repeat: no-repeat;
+  background-position: center center;
+  background-size: contain;
+  margin-right: 10px !important;
+}
+
+.btn {
+  display: inline-flex;
+  -webkit-box-align: center;
+  align-items: center;
+  -webkit-box-pack: center;
+  justify-content: center;
+  position: relative;
+  width: 57px;
+  height: 44px;
+  font-size: 16px;
+  line-height: 1.5;
+  font-family: 'Open Sans', sans-serif;
+  font-weight: 600;
+  padding: 8px 16px;
+  border-radius: 4px;
+  transition-duration: 450ms;
+  transition-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
+  word-break: normal;
+  color: rgba(0, 0, 0, 0.54);
+  background: rgb(255, 255, 255);
+  box-shadow: rgb(0 0 0 / 12%) 0px 2px 4px 0px, rgb(0 0 0 / 12%) 0px 0px 4px 0px;
+  white-space: nowrap;
+  border-style: none;
+  border-width: 0px;
+  border-color: rgb(255, 255, 255);
+  margin: 0px;
+  cursor: pointer;
+}
+
+.btn:hover {
+  background-color: #F5F5F5;
+  box-shadow: 1px 1px 3px 3px #E0E0E0;
+}
+
+.swap-rate-container .btn-arrows {
+  transform: rotate(90deg);
+  opacity: 0.54;
+  transition: opacity 450ms cubic-bezier(0.23, 1, 0.32, 1);
+  position: absolute;
+  z-index: 0;
+  font-family: 'Open Sans', sans-serif;
+}
+
+.currency {
+  padding: 40px 0;
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+}
+
+input::placeholder {
+  font-family: 'Open Sans', sans-serif;
+  font-size: 16px;
+}
+
+.currency input {
+  background: transparent;
+  font-size: 16px;
+  line-height: 1.5;
+  text-align: right;
+  font-weight: 400;
+  color: rgba(0, 0, 0, 0.87);
+  border-style: none;
+  border-width: 0px;
+  border-radius: 0px;
+  background: transparent;
+  box-shadow: none;
+  outline: none;
+  width: 65%;
+  font-family: 'Open Sans', sans-serif;
+  background: transparent;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+  margin-left: 15px
+}
+
+.currency input:hover {
+  display: block;
+  line-height: 1.5;
+  font-family: ""Open Sans"", sans-serif;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54);
+}
+
+.currency input:focus {
+  border-bottom: 2px solid #8dc641;
+  border-bottom-color: transparent;
+}
+
+.select-placeholder {
+  background: rgb(255, 255, 255);
+  color: rgba(0, 0, 0, 0.38);
+}
+
+.swap-rate-container {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+}
+
+.rate {
+  color: black;
+  font-size: 15px;
+  padding: 0 10px;
+  background: #E0E0E0;
+  line-height: var(--tl-small);
+  padding: 8px;
+  font-family: 'Open Sans', sans-serif;
+  border-radius: 2px;
+}
+
+input::-webkit-inner-spin-button {
+  display: none !important;
+}
+
+.input-container {
+  position: relative;
+  width: 65%;
+  margin-left: 15px;
+  bottom: -1px;
+}
+
+.input-container input {
+  width: 100%;
+  margin-left: 0;
+}
+
+.input-container input:focus {
+  border-bottom: 2px solid #8dc641;
+}
+
+.input-box:hover + .input-border {
+  transform: scaleX(1);
+}
+
+.input-border {
+  display: block;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54); 
+  transform: scaleX(0);
+  transition: transform 250ms ease-in-out;
+  position: absolute; bottom: 0; left: 0;
+  width: 102%;
+}
+
+@media (maz-width: 600px) {
+  .currency input {
+    width: 200px;
+  }
+}
+
+.display-none {
+  display: none;
+}
+
+
+
+/* for dropdown css*/
+
+/* for input border css */
+
+
+/* .input-container {
+  position: relative;
+  width: 65%;
+  margin-left: 15px;
+}
+
+.input-container input {
+  width: 100%;
+  margin-left: 0;
+}
+
+.input-border {
+  position: absolute; bottom: 0; left: 0;
+  width: 100%;
+  height: 2px;
+}
+
+.input-border::before,
+.input-border::after{
+  content: '';
+  position: absolute; top: 0; 
+  width: 0;
+  height: 100%;
+  background-color: #8dc641;
+  transition: width .3s ease;
+}
+
+.input-border::before {
+  left: 50%;
+}
+
+.input-border::after {
+  right: 50%;
+}
+
+.input-container input:focus + .input-border::before,
+.input-container input:focus + .input-border::after {
+  width: 50%;
+}  */
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+  <meta charset=""UTF-8"" />
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
+  <title>Currency Converter</title>
+  <link rel=""shortcut icon"" href=""currencies-icon-10.jpg"" type=""image/x-icon"">
+  <link rel=""stylesheet"" href=""style.css"" />
+</head>
+<body>
+  <div class=""container"">
+    <div class=""header"">
+      <div class=""indent-right""></div>
+      <b>Конвертор валют</b>
+    </div>
+    <div class=""currency"">
+      <div class=""custom-select"" id=""curr-one"">
+        <div class=""custom-select__placeholder""></div>        
+        <div class=""custom-select__list"">
+          <div class=""custom-select__option"" data-value=""EUR"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/EU.svg"">
+            </div>
+            <div class=""custom-select__option-name"">EUR</div>
+            <div class=""custom-select__option-symbol"">€</div>
+          </div>
+          <div class=""custom-select__option custom-select__option--select"" data-value=""USD"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/US.svg"">
+            </div>
+            <div class=""custom-select__option-name"">USD</div>
+            <div class=""custom-select__option-symbol"">$</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""GBP"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/GB.svg"">
+            </div>
+            <div class=""custom-select__option-name"">GBP</div>
+            <div class=""custom-select__option-symbol"">£</div>
+          </div>
+          <div class=""custom-select__option  display-none"" data-value=""UAH"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/UA.svg"" />
+            </div>
+            <div class=""custom-select__option-name"">UAH</div>
+            <div class=""custom-select__option-symbol"">₴</div>
+          </div>
+        </div>
+      </div>
+      <div class=""input-container"">
+        <input type=""number"" id=""amount-one"" class=""input-box"" placeholder=""200.00"" />
+        <span class=""input-border""></span>
+      </div>
+    </div>
+
+    <div class=""swap-rate-container"">
+      <button class=""btn"" id=""swap"">
+          <div class=""btn-arrows"">
+            <div style=""display: flex;"">
+              <svg
+                height=""24px"" width=""24px"" version=""1.1""
+                viewBox=""0 0 24 24"" xmlns=""http://www.w3.org/2000/svg"">
+                <g fill=""none"" fill-rule=""evenodd"" stroke=""none"" stroke-width=""1"">
+                  <path d=""M0 0h24v24H0z""></path>
+                  <path
+                    d=""M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z""
+                    fill=""#000""
+                    fill-rule=""nonzero""></path>
+                </g>
+              </svg>
+            </div>
+          </div>
+        </button>
+      <div class=""rate"" id=""rate""></div>
+    </div>
+
+    <div class=""currency"">
+      <div class=""custom-select"" id=""curr-two"">
+        <div class=""custom-select__placeholder""></div>
+        <div class=""custom-select__list"">
+          <div class=""custom-select__option custom-select__option--select"" data-value=""UAH"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/UA.svg"" />
+            </div>
+            <div class=""custom-select__option-name"">UAH</div>
+            <div class=""custom-select__option-symbol"">₴</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""GBP"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/GB.svg"">
+            </div>
+            <div class=""custom-select__option-name"">GBP</div>
+            <div class=""custom-select__option-symbol"">£</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""EUR"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/EU.svg"">
+            </div>
+            <div class=""custom-select__option-name"">EUR</div>
+            <div class=""custom-select__option-symbol"">€</div>
+          </div>
+          <div class=""custom-select__option display-none"" data-value=""USD"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/US.svg"">
+            </div>
+            <div class=""custom-select__option-name"">USD</div>
+            <div class=""custom-select__option-symbol"">$</div>
+          </div>
+        </div>
+      </div>
+      <div class=""input-container"">
+        <input type=""number"" id=""amount-two"" class=""input-box"" placeholder=""200.00"" />
+        <span class=""input-border""></span>
+      </div>
+    </div>
+  </div>
+  <script src=""script.js""></script>
+</body>
+
+</html>
+
+
+

","

i have shared code hover effect on Input & dropdown. please check

+

+
+
/*******************************************************************************
+ *  Initialize the amount for the first currency
+ *******************************************************************************/
+function initializeAmount() {  
+  document.getElementById('amount-one').addEventListener('input', refreshAmount); 
+}
+
+/*******************************************************************************
+ *  Initialize the Swap trigger already existing in DOM
+ *******************************************************************************/
+function initializeSwap() {    
+  swap.addEventListener('click', () => {      
+    
+    const [selectOne, selectTwo] = document.querySelectorAll('.custom-select');
+    const amountOne = document.getElementById('amount-one');
+    const amountTwo = document.getElementById('amount-two');
+     
+    const [valueOne, valueTwo] = [selectOne, selectTwo].map(
+        select => select.querySelector('.custom-select__option--select').dataset.value
+      );
+    
+    //--------------------------------------------------------------------------
+    // Dirty trick to avoid problems when swapping currencies on the 2 DDs
+    // by finding the currencies not chosen by the two dropdowns
+    // and first selecting a third currency on the first dropdown
+    // before doing the actual swap
+    //--------------------------------------------------------------------------
+    const availableCurrencies = [];
+    const chosenCurrencies = [valueOne, valueTwo];
+    selectOne.querySelectorAll('.custom-select__list .custom-select__option-name').forEach((option)=>{
+      availableCurrencies.push( option.innerText );
+    });
+    const notChosenCurrencies = availableCurrencies.filter(chosen => !chosenCurrencies.includes(chosen));
+    
+    amountOne.value = amountTwo.value
+    selectOne.querySelector(`[data-value=""${notChosenCurrencies[0]}""]`).click();
+    selectTwo.querySelector(`[data-value=""${valueOne}""]`).click();
+    selectOne.querySelector(`[data-value=""${valueTwo}""]`).click();  
+    refreshConversionRatesAndAmount();
+  });
+}
+
+/*******************************************************************************
+ *  Initialize the Currency Dropdowns already defined in the DOM 
+ *******************************************************************************/
+function initializeCurrencyDropdowns() {
+  //given the array of all .custom-select
+  [...document.querySelectorAll("".custom-select"")]
+    //map()
+    .map(select => {
+      
+      //inits dropdown options
+      let selected = select.querySelector("".custom-select__option--select"");
+      if (selected) {
+        select.dataset.value = selected.dataset.value;
+        const placeholder = select.querySelector("".custom-select__placeholder"");
+        placeholder.innerHTML = """";
+        const pho = selected.cloneNode(true);
+        pho.classList.remove(""custom-select__option--select"");
+        placeholder.appendChild(pho);
+      }
+      
+      //adds click event listener to the list of options
+      select.querySelector("".custom-select__list"").addEventListener(""click"", e => {              
+        //--------------------------------------------------------------------------
+        // Logic to hide from the other DD the selected currency in this DD
+        //--------------------------------------------------------------------------
+        //fetches information about the currently selected dropdown
+        const thisDD = e.target.closest('.custom-select');
+        const currencyCurrentlySelected = e.target.closest('.custom-select__option').dataset.value;    
+       
+
+        //fetches information about the other dropdown
+        const otherDD_id = ((thisDD.id == 'curr-one' ? 'curr-two' : 'curr-one'));
+        const otherDD = document.getElementById(otherDD_id);
+
+        //removes the displaynone class to all the options in the other dropdown
+        otherDD.querySelectorAll('.custom-select__option').forEach((option)=>{
+          option.classList.remove('display-none');
+        });   
+        //adds the class displaynone to the currently selected currency in the second dropdown    
+        otherDD.querySelector(`.custom-select__option[data-value=""${currencyCurrentlySelected}""]`)
+          .classList.add('display-none');
+        
+        //-------------------------------------------------------------------------- 
+      
+        let target = e.target.closest("".custom-select__option"");
+        if (target) {
+          let parent = target.closest("".custom-select"");
+          parent
+            .querySelector("".custom-select__option--select"")
+            .classList.remove(""custom-select__option--select"");
+          target.classList.add(""custom-select__option--select"");
+          let selected = parent.querySelector("".custom-select__option--select"");
+          parent.dataset.value = selected.dataset.value;
+          const placeholder = parent.querySelector("".custom-select__placeholder"");
+          placeholder.innerHTML = """";
+          const pho = selected.cloneNode(true);
+          pho.classList.remove(""custom-select__option--select"");
+          placeholder.appendChild(pho);
+          target.closest("".custom-select"").classList.remove(""custom-select--drop"");
+        }
+        
+        //-------------------------------------------------------------------------- 
+        
+        refreshConversionRatesAndAmount();
+      });  
+      
+      //adds click event listener to the placeholder
+      select.querySelector("".custom-select__placeholder"").addEventListener(""click"", e => {
+        let target = e.target.closest("".custom-select__placeholder"");
+        if (target) {
+          target.closest("".custom-select"").classList.toggle(""custom-select--drop"");
+        }
+      });
+    });      
+}
+
+/*******************************************************************************
+ * Refresh the conversion rates and converted amount (and metadata)
+ * displayed in the respective labels
+ *******************************************************************************/
+async function refreshConversionRatesAndAmount() {
+
+  const rates = await fetchConversionRates();
+  
+  const currencyOne = getSelectedCurrencyOne();
+  const currencyTwo = getSelectedCurrencyTwo();
+  
+  const rateOne = rates[currencyOne];
+  const rateTwo = rates[currencyTwo];
+  
+  const amountOne = document.getElementById('amount-one');
+  const amountTwo = document.getElementById('amount-two');
+  
+  const rateLabel = document.getElementById('rate');
+  
+  const ratio = (1 * rateOne.rate / rateTwo.rate).toFixed(4);
+  rateLabel.innerText = `1 ${currencyOne} = ${ratio} ${currencyTwo}`;       
+  
+  amountTwo.ratio = ratio;
+  const newAmount = (amountOne.value * amountTwo.ratio).toFixed(2);
+  amountTwo.value = (amountOne.value !== '') ? newAmount : '';     
+    
+}
+/*******************************************************************************
+ * Refresh the amount only 
+ *******************************************************************************/
+function refreshAmount() {
+  const amountOne = document.getElementById('amount-one');
+  const amountTwo = document.getElementById('amount-two');  
+  const newAmount = (amountOne.value * amountTwo.ratio).toFixed(2);
+  amountTwo.value = (amountOne.value !== '') ? newAmount : '';      
+}
+
+/*******************************************************************************
+ * Fetch and return the conversion rates from a static url
+ *******************************************************************************/
+async function fetchConversionRates() {
+  const url = 'https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json';
+  const response = await fetch(url);   
+  const data = await response.json();  
+  data.unshift({
+    ""txt"": ""Українська гривня"",
+    ""rate"": 1,
+    ""cc"": ""UAH""
+  });
+  const ratesMapped = Object.assign({}, ...data.map((rate) => ({[rate.cc]: rate})));
+  return ratesMapped;
+}
+
+/*******************************************************************************
+ * Returns the Currency code selected on the first currency dropdown
+ *******************************************************************************/
+function getSelectedCurrencyOne() {
+  const curr_oneDD = document.querySelector('#curr-one.custom-select');
+  return curr_oneDD.textContent.trim().slice(0, 3);
+}
+
+/*******************************************************************************
+ * Returns the Currency code selected on the second currency dropdown
+ *******************************************************************************/
+function getSelectedCurrencyTwo() {
+  const curr_twoDD = document.querySelector('#curr-two.custom-select');
+  return curr_twoDD.textContent.trim().slice(0, 3);
+}
+
+initializeAmount();
+initializeSwap();
+initializeCurrencyDropdowns();
+refreshConversionRatesAndAmount();
+
body {
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  width: 100%;
+  min-height: 100vh;
+  margin: 0;
+}
+
+.custom-select {
+  display: block;
+  width: 150px;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+  position: relative;
+  -webkit-user-select: none;
+  -moz-user-select: none;
+  -ms-user-select: none;
+  user-select: none;
+  z-index: 1;
+  margin-bottom: 8.7px;
+}
+
+/* .custom-select:hover {
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54);
+} */
+
+.custom-select__list {
+  display: block;
+  border-radius: 5px;
+  background-color: #fff;
+  padding: 5px 0;
+  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.15);
+  position: absolute;
+  z-index: 999;
+  left: 0;
+  top: calc(100% + 12px);
+  opacity: 0;
+  pointer-events: none;
+  transform: translateY(10px);
+  transition-property: transform, opacity;
+  transition-timing-function: ease-out;
+  transition-duration: 0.3s;
+  box-sizing: border-box;
+}
+
+.custom-select--drop .custom-select__list {
+  transform: translateY(0);
+  opacity: 1;
+  pointer-events: all;
+}
+
+.custom-select--drop .custom-select__placeholder::after {
+  transform: translateY(-80%) rotateX(360deg);
+}
+
+.custom-select__option {
+  display: flex;
+  justify-content: flex-start;
+  align-items: center;
+  padding: 0.5em 1.5em;
+  box-sizing: border-box;
+  cursor: pointer;
+  z-index: 0;
+}
+
+.custom-select__option-icon {
+  display: block;
+  flex-shrink: 0;
+  border-radius: 5px;
+  overflow: hidden;
+  margin-right: 10px;
+}
+
+.custom-select__option-icon img {
+  display: block;
+  width: 18px;
+  height: 15px;
+  max-height: 100%;
+  -o-object-fit: cover;
+  object-fit: cover;
+  margin: 0;
+}
+
+.custom-select__option-name {
+  display: block;
+  width: 100%;
+  text-transform: uppercase;
+  margin-right: 10px;
+}
+
+.custom-select__option-symbol {
+  display: block;
+  font-weight: bold;
+}
+
+.custom-select__option--select .custom-select__option-name {
+  color: #8dc641;
+}
+
+.custom-select__placeholder {
+  display: block;
+  width: 100%;
+}
+
+.custom-select__placeholder::after {
+  content: '';
+  display: block;
+  width: 0;
+  height: 0;
+  border: 6px solid transparent;
+  border-top-width: 6px;
+  border-bottom: 6px solid #616161;
+  position: absolute;
+  right: 0;
+  top: 50%;
+  transform: translateY(-30%) rotateX(180deg);
+  transition-property: transform;
+  transition-timing-function: ease-out;
+  transition-duration: 0.3s;
+}
+
+.custom-select__option {
+  padding-right: calc(1.5em + 10px);
+  position: relative;  
+}
+
+.custom-select {
+  display:inline-block;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+ }
+
+.custom-select:after {
+  display:block;
+  content: '';
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54); 
+  transform: scaleX(0);  
+  transition: transform 250ms ease-in-out;
+  position: relative;
+  bottom: -2px;
+}
+
+.custom-select:hover:after { transform: scaleX(1); 
+}
+
+.custom-select:focus {
+   border-bottom: 2px solid #8dc641;
+}
+
+.header {
+  display: flex;
+  align-items: center;
+}
+
+.indent-right {
+  display: flex;
+  width: 24px;
+  height: 24px;
+  background-image: url(""https://cdn.privat24.ua/icons/file/ServiceCurrency.svg"");
+  background-repeat: no-repeat;
+  background-position: center center;
+  background-size: contain;
+  margin-right: 10px !important;
+}
+
+.btn {
+  display: inline-flex;
+  -webkit-box-align: center;
+  align-items: center;
+  -webkit-box-pack: center;
+  justify-content: center;
+  position: relative;
+  width: 57px;
+  height: 44px;
+  font-size: 16px;
+  line-height: 1.5;
+  font-family: 'Open Sans', sans-serif;
+  font-weight: 600;
+  padding: 8px 16px;
+  border-radius: 4px;
+  transition-duration: 450ms;
+  transition-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
+  word-break: normal;
+  color: rgba(0, 0, 0, 0.54);
+  background: rgb(255, 255, 255);
+  box-shadow: rgb(0 0 0 / 12%) 0px 2px 4px 0px, rgb(0 0 0 / 12%) 0px 0px 4px 0px;
+  white-space: nowrap;
+  border-style: none;
+  border-width: 0px;
+  border-color: rgb(255, 255, 255);
+  margin: 0px;
+  cursor: pointer;
+}
+
+.btn:hover {
+  background-color: #F5F5F5;
+  box-shadow: 1px 1px 3px 3px #E0E0E0;
+}
+
+.swap-rate-container .btn-arrows {
+  transform: rotate(90deg);
+  opacity: 0.54;
+  transition: opacity 450ms cubic-bezier(0.23, 1, 0.32, 1);
+  position: absolute;
+  z-index: 0;
+  font-family: 'Open Sans', sans-serif;
+}
+
+.currency {
+  padding: 40px 0;
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+}
+
+input::placeholder {
+  font-family: 'Open Sans', sans-serif;
+  font-size: 16px;
+}
+
+.currency input {
+  background: transparent;
+  font-size: 16px;
+  line-height: 1.5;
+  text-align: right;
+  font-weight: 400;
+  color: rgba(0, 0, 0, 0.87);
+  border-style: none;
+  border-width: 0px;
+  border-radius: 0px;
+  background: transparent;
+  box-shadow: none;
+  outline: none;
+  width: 65%;
+  font-family: 'Open Sans', sans-serif;
+  background: transparent;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.12);
+  margin-left: 15px
+}
+
+.currency input:hover {
+  display: block;
+  line-height: 1.5;
+  font-family: ""Open Sans"", sans-serif;
+  /* border-bottom: 2px solid rgba(0, 0, 0, 0.54); */
+}
+
+.currency input:focus {
+  border-bottom: 2px solid #8dc641;
+  border-bottom-color: transparent;
+}
+
+.select-placeholder {
+  background: rgb(255, 255, 255);
+  color: rgba(0, 0, 0, 0.38);
+}
+
+.swap-rate-container {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+}
+
+.rate {
+  color: black;
+  font-size: 15px;
+  padding: 0 10px;
+  background: #E0E0E0;
+  line-height: var(--tl-small);
+  padding: 8px;
+  font-family: 'Open Sans', sans-serif;
+  border-radius: 2px;
+}
+
+input::-webkit-inner-spin-button {
+  display: none !important;
+}
+
+.input-container {
+  position: relative;
+  width: 65%;
+  margin-left: 15px;
+  bottom: -1px;
+}
+
+.input-container input {
+  width: 100%;
+  margin-left: 0;
+}
+
+ .input-box:hover + .input-border ,
+  .input-box:focus + .input-border , 
+  .input-box:active + .input-border {
+        transform: scaleX(1);
+    }
+
+.input-border {
+  display: block;
+  border-bottom: 2px solid rgba(0, 0, 0, 0.54); 
+  transform: scaleX(0);
+  transition: transform 250ms ease-in-out;
+  position: absolute; bottom: 0; left: 0;
+  width: 102%;
+}
+
+@media (maz-width: 600px) {
+  .currency input {
+    width: 200px;
+  }
+}
+
+.display-none {
+  display: none;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+<head>
+  <meta charset=""UTF-8"" />
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
+  <title>Currency Converter</title>
+  <link rel=""shortcut icon"" href=""currencies-icon-10.jpg"" type=""image/x-icon"">
+  <link rel=""stylesheet"" href=""style.css"" />
+</head>
+<body>
+  <div class=""container"">
+    <div class=""header"">
+      <div class=""indent-right""></div>
+      <b>Конвертор валют</b>
+    </div>
+    <div class=""currency"">
+      <div class=""custom-select"" id=""curr-one"">
+        <div class=""custom-select__placeholder""></div>        
+        <div class=""custom-select__list"">
+          <div class=""custom-select__option"" data-value=""EUR"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/EU.svg"">
+            </div>
+            <div class=""custom-select__option-name"">EUR</div>
+            <div class=""custom-select__option-symbol"">€</div>
+          </div>
+          <div class=""custom-select__option custom-select__option--select"" data-value=""USD"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/US.svg"">
+            </div>
+            <div class=""custom-select__option-name"">USD</div>
+            <div class=""custom-select__option-symbol"">$</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""GBP"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/GB.svg"">
+            </div>
+            <div class=""custom-select__option-name"">GBP</div>
+            <div class=""custom-select__option-symbol"">£</div>
+          </div>
+          <div class=""custom-select__option  display-none"" data-value=""UAH"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/UA.svg"" />
+            </div>
+            <div class=""custom-select__option-name"">UAH</div>
+            <div class=""custom-select__option-symbol"">₴</div>
+          </div>
+        </div>
+      </div>
+      <div class=""input-container"">
+        <input type=""number"" id=""amount-one"" class=""input-box"" placeholder=""200.00"" />
+        <span class=""input-border""></span>
+      </div>
+    </div>
+
+    <div class=""swap-rate-container"">
+      <button class=""btn"" id=""swap"">
+          <div class=""btn-arrows"">
+            <div style=""display: flex;"">
+              <svg
+                height=""24px"" width=""24px"" version=""1.1""
+                viewBox=""0 0 24 24"" xmlns=""http://www.w3.org/2000/svg"">
+                <g fill=""none"" fill-rule=""evenodd"" stroke=""none"" stroke-width=""1"">
+                  <path d=""M0 0h24v24H0z""></path>
+                  <path
+                    d=""M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z""
+                    fill=""#000""
+                    fill-rule=""nonzero""></path>
+                </g>
+              </svg>
+            </div>
+          </div>
+        </button>
+      <div class=""rate"" id=""rate""></div>
+    </div>
+
+    <div class=""currency"">
+      <div class=""custom-select"" id=""curr-two"">
+        <div class=""custom-select__placeholder""></div>
+        <div class=""custom-select__list"">
+          <div class=""custom-select__option custom-select__option--select"" data-value=""UAH"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/UA.svg"" />
+            </div>
+            <div class=""custom-select__option-name"">UAH</div>
+            <div class=""custom-select__option-symbol"">₴</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""GBP"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/GB.svg"">
+            </div>
+            <div class=""custom-select__option-name"">GBP</div>
+            <div class=""custom-select__option-symbol"">£</div>
+          </div>
+          <div class=""custom-select__option"" data-value=""EUR"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/EU.svg"">
+            </div>
+            <div class=""custom-select__option-name"">EUR</div>
+            <div class=""custom-select__option-symbol"">€</div>
+          </div>
+          <div class=""custom-select__option display-none"" data-value=""USD"">
+            <div class=""custom-select__option-icon"">
+              <img src=""https://cdn.privat24.ua/icons/file/US.svg"">
+            </div>
+            <div class=""custom-select__option-name"">USD</div>
+            <div class=""custom-select__option-symbol"">$</div>
+          </div>
+        </div>
+      </div>
+      <div class=""input-container"">
+        <input type=""number"" id=""amount-two"" class=""input-box"" placeholder=""200.00"" />
+        <span class=""input-border""></span>
+      </div>
+    </div>
+  </div>
+  <script src=""script.js""></script>
+</body>
+
+
+

",css +"How to remove zoomout content

i have a problem with my "website" whenever i zoom-out to max, below my Box 5"footer". +there's this huge amount of white space, which i don't want. +I think i need to size my website in some sort of a way, as in giving the page a horizontal and vertical max. Unsure if that works with grid. Another solution i believe could be having box2 and 4 horizontal max and having header and footer always on sticky, and having box 3 as auto. +I've been stuck on how to solve it. Saw another post on stackoverflow on how someone solved it, however it didn't work with mine.

+

After i solve this then my goal is to make box 1 2,4,and 5 sticky or something similar, so it scrolls with the page. and box 3 as content.

+

+
+
 .grid {
+ display: grid;
+ grid-template-columns: 1fr 4fr 1fr;
+ background-color: #8b9dc3;
+ height: 100vh;
+}
+
+.box1 {
+  background-color: #3b5998;
+  grid-column: 1/4;
+  grid-row: 1/2;
+  z-index: 2;
+}
+
+.box2 {
+  grid-column: 1;
+  /* grid-row: 2/12; */
+  grid-row-start: 2;
+  grid-row-end: 12;
+}
+
+.box3 {
+  background-color: #ffffff;
+  grid-row: 2/12;
+  grid-column: auto;
+}
+
+.box4 {
+  align-self: stretch;
+  grid-column: 3;
+  grid-row: 2/12;
+  grid-row: 2 / max;
+}
+
+.box5 {
+  background-color: #3b5998;
+  grid-column: 1/4;
+}
+
+html,
+body {
+  margin: 0;
+  padding: 0;
+  overflow: hidden;
+}
+
<!DOCTYPE html>
+<html lang=""en"">
+
+<head>
+  <link rel=""stylesheet"" href=""mystylesheet2.css"">
+  <meta charset=""UTF-8"">
+  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
+  <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
+  <title>Document</title>
+</head>
+
+<body>
+  <div class=""grid"">
+    <div class=""box box1"">box1</div>
+    <div class=""box box2"">box2</div>
+    <div class=""box box3"">box3</div>
+    <div class=""box box4"">box4</div>
+    <div class=""box box5""> box5</div>
+  </div>
+</body>
+
+
+</html>
+
+
+

","

Solved it.

+

Removed grid-auto-rows: minmax(100px, auto); +also added the height, as i was talking about to 100vh

+

Didn't really understand the auto function. I believe it maximize the entire screen with rows.

",css +"My navbar contents are merged within one another

The 3 center elements of my navbar have all merged within one another . I have tried giving margin between the contents but nothing seems to workthis is how it looks

+

+
+
@import url('https://fonts.googleapis.com/css2?family=Great+Vibes&display=swap');
+* {
+    margin: 0;
+    padding: 0;
+    box-sizing: border-box;
+}
+
+li {
+    list-style: none;
+}
+
+a {
+    text-decoration: none;
+}
+
+.nav-item {
+    margin-left: 10rem;
+}
+
+.nav-link {
+    font-size: 1.6rem;
+    font-weight: 400;
+    color: #475569;
+}
+
+.nav-link:hover {
+    color: #482ff7;
+}
+
+.topnav {
+    position: relative;
+    overflow: hidden;
+    background-color: #333;
+}
+
+.topnav a {
+    float: left;
+    color: #f2f2f2;
+    text-align: center;
+    padding: 14px 16px;
+    text-decoration: none;
+    font-size: 17px;
+}
+
+.topnav a:hover {
+    color: black;
+    text-decoration: none;
+}
+
+.topnav a.active {
+    color: white;
+}
+
+.topnav-centered a {
+    float: none;
+    position: absolute;
+    top: 50%;
+    left: 50%;
+    transform: translate(-50%, -50%);
+    display: flex;
+    justify-content: space-between;
+}
+
+.topnav-right {
+    float: right;
+}
+
+.nav-logo {
+    font-size: 4.1rem;
+    font-weight: 400;
+    color: #a9a9a9;
+    font-family: ""Great Vibes"", Georgia, serif, system-ui;
+    text-decoration: none;
+    padding-top: 2rem;
+    padding-bottom: 3rem;
+}
+
<!doctype html>
+<html lang=""en"">
+
+<head>
+    <title>Mercantilism Services LLP</title>
+    <!-- Required meta tags -->
+    <meta charset=""utf-8"">
+    <meta name=""viewport"" content=""width=device-width, initial-scale=1, shrink-to-fit=no"">
+    <link rel=""stylesheet"" href=""style.css"" type=""text/css"">
+    <!-- Bootstrap CSS -->
+    <link rel=""stylesheet"" href=""https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"" integrity=""sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"" crossorigin=""anonymous"">
+</head>
+
+<body>
+
+    <!-- Optional JavaScript -->
+    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
+    <script src=""https://code.jquery.com/jquery-3.3.1.slim.min.js"" integrity=""sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"" crossorigin=""anonymous""></script>
+    <script src=""https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"" integrity=""sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"" crossorigin=""anonymous""></script>
+    <script src=""https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"" integrity=""sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"" crossorigin=""anonymous""></script>
+
+    <div class=""topnav"">
+
+        <a href=""#"" class=""nav-logo"">Mercantilism Services LLP</a>
+        <div class=""topnav-centered"">
+            <li class=""nav-item""><a href=""#"" class=""nav-link"">Home</a></li>
+            <li class=""nav-item""><a href=""#"" class=""nav-link"">CONTACT Us</a></li>
+            <li class=""nav-item""><a href=""#"" class=""nav-link"">BLOG</a></li>
+        </div>
+        <div class=""topnav-right"">
+            <a href=""#""><svg xmlns=""http://www.w3.org/2000/svg"" width=""20"" height=""20"" fill=""currentColor"" class=""bi bi-cart"" viewBox=""0 0 16 16"">
+                <path d=""M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z""/>
+              </svg></a>
+            <a href=""#""><svg xmlns=""http://www.w3.org/2000/svg"" width=""20"" height=""20"" fill=""currentColor"" class=""bi bi-person"" viewBox=""0 0 16 16"">
+                <path d=""M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z""/>
+              </svg></a>
+        </div>
+        <div class=""hamburger"">
+            <span class=""bar""></span>
+            <span class=""bar""></span>
+            <span class=""bar""></span>
+        </div>
+
+    </div>
+
+
+</body>
+
+</html>
+
+
+

+

Any help would be appreciated. Also the font size dosent seem to chnage for the logo no matter how hard i try. Please if any one has any suggestions......

","

Here's the correct css. You can change it if you want to.

+
    @import url('https://fonts.googleapis.com/css2?family=Great+Vibes&display=swap');
+    *{
+      margin: 0;
+      padding: 0;
+      box-sizing: border-box;
+    }
+    
+    li {
+      list-style: none;
+    }
+    
+    a {
+      text-decoration: none;
+    }
+
+    .nav-link {
+      font-size: 1.6rem;
+      font-weight: 400;
+      color: #475569;
+    }
+    
+    .nav-link:hover {
+      color: #482ff7;
+    }
+    
+    .topnav {
+      background-color: #333;
+      display: flex;
+      justify-content: space-between;
+      align-items: center;
+      flex-direction: column;
+    }
+    
+    .topnav a {
+      float: left;
+      color: #f2f2f2;
+      text-align: center;
+      padding: 14px 16px;
+      text-decoration: none;
+      font-size: 17px;
+    }
+    
+    .topnav a:hover {
+      color: black;
+      text-decoration: none;
+    }
+    
+    .topnav a.active {
+      color: white;
+    }
+    
+    .topnav-centered li{
+      float:left;
+    }
+    
+    .nav-logo {
+      font-size: 4.1rem;
+      font-weight: 400;
+      color: #a9a9a9;
+      font-family: "Great Vibes", Georgia, serif, system-ui;
+      text-decoration: none;
+      padding-top: 2rem;
+      padding-bottom: 3rem;
+    }
+
+    @media only screen and (min-width: 480px){
+      .topnav{
+        flex-direction: row;
+      }
+    }
+
+

I removed the entire .topnav-centered a and .nav-item blocks and replaced it with

+
    .topnav-centered li{
+      float:left;
+    }
+
+

And changed .topnav into a flex container to align everything and with some minor tweaks your good to go.

",css +"Why is svg LogoMonniMobile not visible when the width is 736px?

This my code: codesandbox.io

+

CSS

+
@media (width > 736px) {
+  #LogoMonni-mobile {
+    display: none;
+  }
+}
+
+@media (max-width <= 736px) {
+  #LogoMonni-pc {
+    display: none;
+  }
+  #LogoMonni-mobile {
+    display: block;
+  }
+}
+
+

JSX

+
import { ReactComponent as LogoMonniPC } from "./logoMonniPC.svg";
+import { ReactComponent as LogoMonniMobile } from "./LogoMonniMobile.svg";
+
+import "./styles.css";
+
+export default function App() {
+  return (
+    <div className={"LogoMonni"}>
+      <LogoMonniPC />
+      <LogoMonniMobile />
+    </div>
+  );
+}
+
+

When the screen size is > 736px I show the computer version of the SVG, and when <= 736px I show the mobile version, but for some reason <LogoMonniMobile /> does not appear on the screen. What is the reason and how can this be fixed?

",

As i understand the id problem LogoMonni_0 LogoMonni_1 LogoMonni_2 ... if id sv1 are the same as scg2 I don’t know for some reason the browser thinks they should disappear

,css +"How to make a website start scrolling from the top but then stop at a certain point when scrolling up

I have a website that has a new splash screen and header at the top in its redesign that I want people to see when they load the page. From there, there's a button arrow they can click to jump down to the next section (or they can simply scroll, haven't figured out how to disable the scroll option or if I want to on that button). But once they scroll down to the main page and section, I don't want them to be able to scroll back up past a certain point to see it again (unless the page is refreshed). I came across this fiddle and coding and it seems to work, but it STARTS at the height I wanna stop it up after the initial scroll and am not sure how to get it to START at the top of the page, then stop at that point when scrolling up.

+
<div id="test"><div>
+
+
#test{
+    height: 3500px;
+    margin-top: 1000px;
+}
+
+
$(document).ready(function(){
+    var eTop = $("#test").offset().top;
+    $(document).scrollTop(eTop);
+    var eHeight = $("#test").height();
+    var eBottom = eTop + eHeight - $(window).height();
+    $(document).on("scroll", function(e){
+        var windowScrollTop = $(window).scrollTop();
+        if(windowScrollTop < eTop){
+            console.log("not allowed");
+            $(document).scrollTop(eTop);
+        }
+        else if(windowScrollTop > eBottom){
+            $(document).scrollTop(eBottom);
+        }
+        else{
+            console.log("allowed");
+        }
+    });
+});
+
+

Though I suppose another potential solution could be in the button itself. After its clicked, to have it scroll and essentially 'lock' the lower part of the page in place (in not letting it scroll back up beyond that point) though I'm not sure how to do that.

+

+
+
<nav role=""navigation"" class=""open"">
+  <a href=""#services"" class=""banner-btn""><img src=""https://pluspng.com/img-png/down-arrow-png-down-icon-1600.png"" alt="""" height=""100"" width=""100""></a>
+</nav>
+
+
+

","

It not very clear of what you are trying to achieve but in the below snippet added button to enable and disable the scrolling and one for to scroll to the bottom

+

+
+
function func() {
+  window.scrollTo({
+    top: 4500,
+    left: 0,
+    behavior: 'smooth'
+  });
+};
+
+  function disableScroll() {
+    // Get the current page scroll position
+    scrollTop =
+      window.pageYOffset || document.documentElement.scrollTop;
+    scrollLeft =
+      window.pageXOffset || document.documentElement.scrollLeft,
+
+      // if any scroll is attempted,
+      // set this to the previous value
+      window.onscroll = function() {
+        window.scrollTo(scrollLeft, scrollTop);
+      };
+  }
+
+function enableScroll() {
+  window.onscroll = function() {};
+}
+
#test {
+  height: 3500px;
+  padding-top: 1000px;
+}
+
+.btnScroll {
+  position: fixed;
+  top: 0;
+}
+.btnDisable {
+  position: fixed;
+  right: 0;
+  top:0;
+}
+.btnEnable {
+  position: fixed;
+  right: 0;
+  bottom: 0;
+}
+
<div id=""test"">Tester
+  <div>
+    <button onclick=""func()"" class=""btnScroll"">Scroll</button>
+    <button onclick=""disableScroll()"" class=""btnDisable"">Disable Scrolling</button>
+    <button onclick=""enableScroll()"" class=""btnEnable"">Enable Scrolling</button>
+
+
+

+

Update:

+

To prevent upper (or back or previous ...something) scrolling when reached on final destination of scroll

+

+
+
function func() {
+  window.scrollTo({
+    top: 750,
+    left: 0
+  });
+
+  var previousPosition = window.pageYOffset || document.documentElement.scrollTop;
+
+  window.onscroll = function() {
+    var currentPosition = window.pageYOffset || document.documentElement.scrollTop;
+
+    if (currentPosition < 750) {
+
+      window.scrollTo(0, 750);
+    }
+    previousPosition = currentPosition;
+
+  };
+};
+
#test {
+  height: 3500px;
+  padding-top: 1000px;
+}
+
+.btnScroll {
+  position: fixed;
+  bottom: 0;
+  right: 0;
+}
+
<div id=""test"">Tester
+  <div>
+    <button onclick=""func()"" class=""btnScroll""><img src=""https://pluspng.com/img-png/down-arrow-png-down-icon-1600.png"" alt="""" height=""20"" width=""20""></button>
+
+
+

",css +"Add outside stroke to the text with css

How to add outside stroke for the text. +I tried with -webkit-text-stroke: 10px black; and text-shadow but my text becomes thinner, I want to have font size 24px.

+

+
+
p {
+  color: #fff;
+  text-shadow: -1px -1px 0 #844733, 1px -1px 0 #844733, -1px 1px 0 #844733, 1px 1px 0 #844733;
+  
+  font-size: 24px;
+}
+
<p>my text</p>
+
+
+

+

here is the image -> [1]: https://i.stack.imgur.com/5xMgn.png

+

I wanted very thick stroke and only outlide

","

You can use a pseudo element with identical text content to the main text and give the pseudo element the text-stroke. It was shown on CSS Tricks.

+

+
+
p {
+  color: #fff;
+  font-size: 24px;
+  position: relative
+}
+p:after {
+  content: attr(data-text);
+  -webkit-text-stroke: 6px #844733;
+  color: #844733;
+  position: absolute;
+  left: 0;
+  z-index: -1
+}
+
<p data-text=""my text"">my text</p>
+
+
+

",css +"Using Javascript to drag-and-drop an image into an unordered list

So, I've been warned that some of my past questions have not been well-received, and I'm in danger of being blocked from asking any more. I hope that this question is well-received and that it doesn't result in me being blocked from asking more questions! I'll do my very best to formulate it as a clear and useful question.

+

What I'm trying to do is create javascript to click-and-drag images into nested lists. I've read HTML Drag and Drop between multiple Unordered Lists and How to drag and drop into an html unordered list, and neither addresses what I'm trying to do.

+

The images I want to click-and-drag represent items--some items can contain other items while others cannot. For instance, a Single-Barrel Shotgun can contain Shotgun Ammo, but Shotgun Ammo cannot contain anything.

+

I've created a jsfiddle, https://jsfiddle.net/pjamesnorris25/9f0y8edz/76/, to facilitate some javascript wizard helping me with this. And because I have, I'm not going to post the javascript here unless someone asks me to do so.

+

My javascript works if you click-and-drag the shotgun to the "Left Shoulder" in the image of the generic person below the "Shotgun Ammo" and "Single-Barrel Shotgun" images in the upper right-hand corner. That is, when you do so, the text "Single Barrel Shotgun" appears below the "Left Shoulder" in a of its own denoted by a box around the text--the box indicates that "Single Barrel Shotgun" is a container into which you can drag other items, in this case, "Shotgun Ammo".

+

Prior to dragging the "Single-Barrel Shotgun" graphic to the "Left Shoulder" container, my HTML looks like this:

+
<span id="leftshoulder-span" style="border:black solid 1px; left:387px; height:30px; width:173px; overflow:hidden; position:absolute; top:96px; " ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+<ul id="leftshoulder-ul" style="left:387px; position:absolute; top:126px; z-index:101; "></ul>
+
+

After dragging the "Single-Barrel Shotgun" to the "Left Shoulder", the HTML looks like this:

+
<ul id="leftshoulder-ul" style="left:387px; position:absolute; top:126px; z-index:101; ">
+  <li id="Single_Barrel_Shotgun_1-li" style="margin-top:2px;">
+    <span id="Single_Barrel_Shotgun_1-span" ondrop="drop(event)" ondragover="allowDrop(event)" style="border:1px solid black;">
+      <div class="tooltip">
+        Single Barrel Shotgun
+        <span class="tooltipimage">
+          <img src="https://i.postimg.cc/sGCvntKs/Single-Barrel-Shotgun.gif" id="Single_Barrel_Shotgun_1" class="zoom_small card" draggable="true" ondragstart="drag(event)">
+        </span>
+      </div>
+    </span>
+    <span id="Single_Barrel_Shotgun_1-contents-span" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+    <ul id="Single_Barrel_Shotgun_1-ul"></ul>
+  </li>
+</ul>
+
+

Which is exactly what I want. But when I drag the "Shotgun Ammo" image to the "Single Barrel Shotgun" text , I get:

+
<ul id="leftshoulder-ul" style="left:387px; position:absolute; top:126px; z-index:101; ">
+  <li id="Single_Barrel_Shotgun_1-li" style="margin-top:2px;">
+    <span id="Single_Barrel_Shotgun_1-span" ondrop="drop(event)" ondragover="allowDrop(event)" style="border:1px solid black;">
+      <div class="tooltip">
+        Single Barrel Shotgun
+        <span class="tooltipimage">
+          <img src="https://i.postimg.cc/sGCvntKs/Single-Barrel-Shotgun.gif" id="Single_Barrel_Shotgun_1" class="zoom_small card" draggable="true" ondragstart="drag(event)">
+        </span>
+      </div>
+    </span>
+    <img id="Shotgun_Shell_4" class="zoom_small card" src="https://i.postimg.cc/N28LZpPT/Shotgun-Shell.gif" draggable="true" ondragstart="drag(event)">
+    <span id="Single_Barrel_Shotgun_1-contents-span" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+    <ul id="Single_Barrel_Shotgun_1-ul">
+    </ul>
+  </li>
+</ul>
+
+

Note that the <img src="https://i.postimg.cc/sGCvntKs/Single-Barrel-Shotgun.gif" ... is after the </span> closing the <span class="tooltipimage"> and not in an <li> inside <ul id="Single_Barrel_Shotgun_1-ul"></ul>.

+

That is, what I want is:

+
<ul id="leftshoulder-ul" style="left:387px; position:absolute; top:126px; z-index:101; ">
+  <li id="Single_Barrel_Shotgun_1-li" style="margin-top:2px;">
+    <span id="Single_Barrel_Shotgun_1-span" ondrop="drop(event)" ondragover="allowDrop(event)" style="border:1px solid black;">
+      <div class="tooltip">
+        Single Barrel Shotgun
+        <span class="tooltipimage">
+          <img src="https://i.postimg.cc/sGCvntKs/Single-Barrel-Shotgun.gif" id="Single_Barrel_Shotgun_1" class="zoom_small card" draggable="true" ondragstart="drag(event)">
+        </span>
+      </div>
+    </span>
+    <span id="Single_Barrel_Shotgun_1-contents-span" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+    <ul id="Single_Barrel_Shotgun_1-ul">
+      <li id="Shotgun_Shell_4-li" style="margin-top:2px;">
+      <div class="tooltip">
+        Shotgun Shell
+        <span class="tooltipimage">
+          <img src="https://i.postimg.cc/sGCvntKs/Shotgun-Shell.gif" id="Shotgun_Shell_4" class="zoom_small card">
+        </span>
+      </div>
+    </ul>
+  </li>
+</ul>
+
+

What's got me flabbergasted is that the javascript that properly places the "Single-Barrel Shotgun" as an unordered list item under the "Left Shoulder" doesn't place the "Shotgun Shell" as an unordered list item under the "Single-Barrel Shotgun" when the HTML for the two has exactly the same structure. That is, the "Left Shoulder" has a uniquely id'd <span> followed by a uniquely id'd <ul>:

+
<span id="leftshoulder-span" style="border:black solid 1px; left:387px; height:30px; width:173px; overflow:hidden; position:absolute; top:96px; " ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+<ul id="leftshoulder-ul" style="left:387px; position:absolute; top:126px; z-index:101; "></ul>
+
+

and the "Single Barrel Shotgun" also has a uniquely id'd followed by a uniquely id'd :

+
    <span id="Single_Barrel_Shotgun_1-contents-span" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
+    <ul id="Single_Barrel_Shotgun_1-ul"></ul>
+
+

I have built in some error checking alerts--that don't work in jsfiddle for some reason; extra bonus point to anyone who can explain this to me. When I run the code on my machine, I get the following when I first click-and-drag the "Single-Barrel Shotgun" to the "Left Shoulder":

+

+

which tells me that the javascript is correctly identifying the <span> to which the "Single-Barrel Shotgun" is being dragged, i.e., the leftshoulder-span, the code knows the id of the "Single-Barrel Shotgun" being dropped into the leftshoulder <ul> is "Single_Barrel_Shotgun_1" (the "_1" indicates that this is the first of the "Single-Barrel Shotgun"'s that can be dragged, and that the item is a "Single Barrel Shotgun".

+

But when I click-and-drag the "Shotgun Ammo", the error checking alert I get is:

+

+

which, because the eve.target.id tells me that the code doesn't recognize that it should be putting the "Shotgun Ammo" as the first <li> in the <ul id="Single_Barrel_Shotgun_1-ul">.

+

So my question is: how do I modify my javascript so that when I click-and-drag the "Shotgun Ammo" to the "Single Barrel Shotgun" it appears as an unordered list item under the "Single Barrel Shotgun"? Or put differently, why is eve.target.id in my error checking alert blank when I click-and-drag the "Shotgun Ammo" to the "Single Barrel Shotgun"?

","

So, I'm not sure if my reasoning is correct here, but I think the reason my javascript wasn't working was that it was looking for the id for the inner-most span to which I was trying to drag the "Shotgun Shell", i.e.:

+

<span class="tooltipimage">

+

for which there was no id.

+

So, I wrote my javascript to add an id to every div and span daughter of id="Single_Barrel_Shotgun_1-span" like so:

+
    <span id="Single_Barrel_Shotgun_1-span" ondrop="drop(event)" ondragover="allowDrop(event)" style="border:1px solid black;">
+      <div id="Single_Barrel_Shotgun_1-tooltip" class="tooltip">
+        Single Barrel Shotgun
+        <span id="Single_Barrel_Shotgun_1-tooltipimage" class="tooltipimage">
+          <img src="https://i.postimg.cc/sGCvntKs/Single-Barrel-Shotgun.gif" id="Single_Barrel_Shotgun_1" class="zoom_small card" draggable="true" ondragstart="drag(event)">
+        </span>
+      </div>
+    </span>
+
+

And, lo and behold, the "Shotgun Shell" now appears as an unordered list item under the "Shotgun" the way I want it to.

+

The javascript that does the trick is:

+
        function addContentsSpan(str_possession)
+        {
+            var str_item = str_possession.replace(/[0-9]/g, "").replace(/_/g, " ").slice(0, -(" ".length));
+            var str_possession_li = str_possession + "-li";
+            var str_possession_span = str_possession + "-span";
+
+            var ele_span = document.getElementById(str_possession_span);
+            ele_span.setAttribute("id", str_possession_span);
+            ele_span.setAttribute("ondrop", "drop(event)");
+            ele_span.setAttribute("ondragover", "allowDrop(event)");
+            ele_span.setAttribute("style", "border:1px solid black;");
+            var ele_li = document.getElementById(str_possession_li);
+
+            var ele_ul = document.createElement("ul");
+            ele_ul.setAttribute("id", (str_possession + "-ul"));
+            ele_li.appendChild(ele_ul);
+            
+        } // function addContentsSpan(str_possession_li)
+
+        function allowDrop(eve) { eve.preventDefault(); }
+        
+        function drag(eve) 
+        { 
+            eve.dataTransfer.setData("text", eve.target.id);
+            console.log(eve.target.id);
+        }
+        
+        function drop(eve) 
+        {
+            bool_debug = false;
+
+            // identify the item being moved
+            var str_possession = eve.dataTransfer.getData("text");
+            var str_container = eve.dataTransfer.setData("text", eve.target.id);
+            var str_item = str_possession.replace(/_/g, " ").replace(/[0-9]/g, "").slice(0, -(" ".length));
+                
+            // drop the item in the container           
+            if (eve.target.id.slice(-("-tooltip").length) == "-tooltip") { eve.target.id = eve.target.id.slice(0, -("-tooltip").length) + "-span"; }
+
+            var str_item_parent = eve.target.id.slice(0, -("-span").length) + "-ul";
+            
+            var str_location = eve.target.id.slice(0, -("-span").length) + "-ul";
+            var ele_location = document.getElementById(str_location);
+
+            eve.preventDefault();
+            eve.target.appendChild(document.getElementById(str_possession));
+
+            var ele_li = document.createElement("li");
+            ele_li.setAttribute("id", (str_possession + "-li"));
+            ele_li.setAttribute("style", "margin-top:2px;");
+            ele_location.appendChild(ele_li);
+
+            var ele_divTooltip = document.createElement("div");
+            ele_divTooltip.setAttribute("class", "tooltip");
+            ele_divTooltip.setAttribute("id", (str_possession + "-tooltip"));
+
+            var ele_spanDrop = document.createElement("span");
+            ele_spanDrop.setAttribute("id", (str_possession + "-span"));
+            ele_li.appendChild(ele_spanDrop);
+
+            ele_divTooltip.textContent = str_item;
+            ele_spanDrop.appendChild(ele_divTooltip);
+
+            var ele_spanTooltipImage = document.createElement("span");
+            ele_spanTooltipImage.setAttribute("id", str_possession + "-tooltipimage");
+            ele_spanTooltipImage.setAttribute("class", "tooltipimage");
+            ele_divTooltip.appendChild(ele_spanTooltipImage);
+
+            var ele_image = document.createElement("img");
+            ele_image.setAttribute("src", ("img/cards/items/" + str_item + ".gif"));
+            ele_image.setAttribute("id", str_possession);
+            ele_image.setAttribute("class", "zoom_small card");
+            ele_image.setAttribute("draggable", "true");
+            ele_image.setAttribute("ondragstart", "drag(event)");
+            ele_spanTooltipImage.appendChild(ele_image);
+            
+            // remove the item from "Possessions"
+            document.getElementById(str_possession).remove()
+            
+            // remove item from previous container
+            if (bool_debug) { alert("line " + 1366 + ":\n" + "str_item_parent = " + str_item_parent + "\n" + "possession list element = " + str_possession + "-li"); }
+            if (str_item_parent.slice(-("-ul")) == "-ul") { document.getElementById(str_item_parent).removeChild(str_possession + "-li"); }
+                        
+            // update the Solo_Possession table with the new item
+            str_target_id = eve.target.id;
+            if (bool_debug) { alert("line " + 1371 +": str_target_id = \"" + str_target_id + "\"\n" + "str_possession = " + str_possession); }
+            
+            insertItem(str_possession);
+            
+            if (arr_space[str_item]['space'] > 0) { addContentsSpan(str_possession); }
+            
+            eve.dataTransfer.clearData();
+                    
+        } // function drop(eve)
+
",css +"JavaScript CheckBox Change Color Not Working

Hi I am trying to use this checkAll function.

+

If I click on the checkAll checkbox, then all of the row will be selected and the background color will change accordingly.

+

Here is my javascript:

+
function checkAll(objRef) {
+        var GridView = objRef.parentNode.parentNode.parentNode;
+        var inputList = GridView.getElementsByTagName("input");
+        for (var i = 0; i < inputList.length; i++) {
+            var row = inputList[i].parentNode.parentNode;
+            if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
+                if (objRef.checked) {
+                    row.style.backgroundColor = "aqua";
+                    inputList[i].checked = true;
+                }
+                else {
+                    if (row.rowIndex % 2 == 0) {
+                        row.style.backgroundColor = "#e4edfb";
+
+                    } else {
+                        row.style.backgroundColor = "white";
+                    }
+                    inputList[i].checked = false;
+                }
+            }
+        }
+    }
+
+

This is my code:

+
<asp:TemplateField>
+   <HeaderTemplate>
+      <asp:CheckBox ID="checkAll" runat="server" onclick="checkAll(this);" />
+   </HeaderTemplate>
+   <ItemStyle HorizontalAlign="Center" />
+   <ItemTemplate>
+      <asp:HiddenField ID="hidID" runat="server" Value='<%# Eval("Id") %>' />
+   <asp:CheckBox runat="server" ID="chkBoxMultipleSelect" CssClass="chkBoxMultipleSelect" OnClick="checkIfUnselected(this);" />
+   </ItemTemplate>
+</asp:TemplateField>
+
+

After click on the checkAll checkBox, I am only able to change the color of that checkbox column only, but not my other column.

+

Any help is apparated. Thanks.

","
function checkAll(spanChk) {
+        var IsChecked = spanChk.checked;
+        var Chk = spanChk;
+        Parent = document.getElementById('gvMessageReportShow');
+        var items = Parent.getElementsByTagName('input');
+        for (i = 0; i < items.length; i++) {
+            if (items[i].id != Chk && items[i].type == "checkbox") {
+                if (items[i].checked != IsChecked) {
+                    spanChk.parentElement.parentElement.style.backgroundColor = 'aqua';
+                    items[i].click();
+                }
+            }
+        }
+    }
+
+

I ended up finding my answer here

+

http://www.codedigest.com/Articles/ASPNET/132_GridView_with_CheckBox_%E2%80%93_Select_All_and_Highlight_Selected_Row.aspx

",css +"Use calc() function in makeStyles
const useStyles = makeStyles((theme) => ({
+  dialog: {
+    '& .MuiTextField-root': {
+      margin: theme.spacing(1),
+    }
+  },
+  address: {
+    width:"calc(24vw + 8px)"
+  },
+}));
+
+
<div>
+ <TextField id="contact-tel" style={{width:'10vw'}} label="联系电话" inputRef={tellRef} margin='none' />
+ <TextField id="contact-company" style={{width:'14vw'}} label="公司名称" inputRef={companyRef} margin='none' />
+</div>
+<div>
+  <TextField id="contact-address" className={classes.address} label="收件地址" inputRef={addressRef} margin='none' />
+</div>
+
+

Code as above, but I didn't the right thing, don't know where is the problem? not support vw + px?

","

Your styles has lower priority than the one from MUI, try adding a couple of ampersands to increase the CSS specificity.

+
address: {
+  width: "calc(24vw + 8px)",
+  "&&": {
+    width: "calc(24vw + 8px)" // same as the above but with higher priority
+  }
+}
+
+

References

+",css +"Opening only the pane below itself when the button is clicked

I have divs with max height. The property of these divs is overflow: hidden; When the read more button below is clicked, only the divin under itself is overflow:hidden; I want the feature removed. I tried but failed. How to do this?

+

MY HTML CODE:

+
 <div class="w-1/2 md:w-1/4 mr-4 md:mr-20 flex flex-col">
+                <h1
+                    class="border-b border-gray-400 font-bold text-base sm:text-2xl md:text-4xl lg:text--5xl xl:text-7xl font-akrobat pb-2 text-right">
+                    2019</h1>
+                <p class="read-text mt-4 max-h-16 overflow-hidden text-xs">Lorem ipsum dolor, sit amet consectetur
+                    adipisicing elit.
+                    Autem qui, aliquam voluptas quasi recusandae quidem possimus repellendus eos asperiores aut
+                    incidunt fuga necessitatibus ipsam doloribus vitae fugiat molestiae numquam quod quaerat
+                    dignissimos dolorum. .</p>
+
+                <a class=" w-full mt-2 text-right read-more text-blue-500 underline" href="#">Read More..</a>
+
+            </div>
+ <div class="w-1/2 md:w-1/4 mr-4 md:mr-20 flex flex-col">
+                <h1
+                    class="border-b border-gray-400 font-bold text-base sm:text-2xl md:text-4xl lg:text--5xl xl:text-7xl font-akrobat pb-2 text-right">
+                    2019</h1>
+                <p class="read-text mt-4 max-h-16 overflow-hidden text-xs">Lorem ipsum dolor, sit amet consectetur
+                    adipisicing elit.
+                    Autem qui, aliquam voluptas quasi recusandae quidem possimus repellendus eos asperiores aut
+                    incidunt fuga necessitatibus ipsam doloribus vitae fugiat molestiae numquam quod quaerat
+                    dignissimos dolorum. .</p>
+
+                <a class=" w-full mt-2 text-right read-more text-blue-500 underline" href="#">Read More..</a>
+
+            </div>
+ <div class="w-1/2 md:w-1/4 mr-4 md:mr-20 flex flex-col">
+                <h1
+                    class="border-b border-gray-400 font-bold text-base sm:text-2xl md:text-4xl lg:text--5xl xl:text-7xl font-akrobat pb-2 text-right">
+                    2019</h1>
+                <p class="read-text mt-4 max-h-16 overflow-hidden text-xs">Lorem ipsum dolor, sit amet consectetur
+                    adipisicing elit.
+                    Autem qui, aliquam voluptas quasi recusandae quidem possimus repellendus eos asperiores aut
+                    incidunt fuga necessitatibus ipsam doloribus vitae fugiat molestiae numquam quod quaerat
+                    dignissimos dolorum. .</p>
+
+                <a class=" w-full mt-2 text-right read-more text-blue-500 underline" href="#">Read More..</a>
+
+            </div>
+
+

MY JS CODE:

+
  $(".read-more").each("item", function () {
+        $("item".on("click", function () {
+            $(".read-text").removeClass("overflow-hidden");
+            $(".read-more").addClass("hidden")
+        }))
+    })
+
","

Let's take this small step to get started on removing jQuery from your codebase. Here's the vanilla JS solution:

+
function onclickReadMore(event) {
+  event.preventDefault();
+  const next = this.parentElement;
+  next?.querySelector('p.read-text')?.classList.remove('overflow-hidden');
+  next?.querySelector('a.read-more')?.classList.add('hidden');
+}
+
+const btnReadMore = document.querySelectorAll('a.read-more');
+
+for (const btn of btnReadMore) {
+  btn?.addEventListener('click', onclickReadMore.bind(btn));
+}
+
",css +"My sticky side bar is not sticky which is a child of flex, why?

I have a parent container which is flex and has 2 children. One of the is content and the other is sidebar which I want to be sticky. But it is not working. It's not sticky at all. Could you please tell me what I am doing wrong??

+

HTML

+
<div class="container">
+ <div class="side-bar">Side bar</div>
+ <div class="content">Content</div>
+</div>
+
+

CSS

+
 .container {
+  display: flex;
+}
+.side-bar {
+  box-shadow: 0 0 1px grey;
+  padding: 1rem 0.4rem;
+  align-self: start;
+  display: none;
+  flex-basis: 14rem;
+  margin-right: 0.7rem;
+  position:sticky;
+  top:1rem;
+}
+
","

if you are using flex in the parent element use align-self: flex-start for the element which you want to make sticky.

+

Apart from that, your element is hidden with display:none.

+
.side-bar {
+  box-shadow: 0 0 1px grey;
+  padding: 1rem 0.4rem;
+  align-self: flex-start;
+  display: none; // --->> remove this line to show the element
+  flex-basis: 14rem;
+  margin-right: 0.7rem;
+  position:sticky;
+  top:1rem;
+}
+
",css +"My CSS and JS external files are not working in my project

I have a simple project with that files structure:

+

+

But my CSS and JS files are not loading...

+
<link rel="stylesheet" href="./css/main.css">
+
+<script src="./js/main.js"></script>
+
","

It should be work

+
<link rel="stylesheet" href="/www/public/css/main.css" type="text/css">
+
+<script type="text/javascript" src="/www/public/js/main.js"></script>
+
",css +"Why does the top half of the span element cover the text and the bottom half does not

The following code states my problem.

+

+
+
span {
+    margin: 20px;
+    padding: 20px;
+    width: 80px;
+    height: 50px;
+    background-color: lightblue;
+    border: 2px solid blue;
+  }
+p {
+    width: 300px;
+}
+
<p>
+I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height.
+</p>
+
+
+

+

As we can see that the top half of the span element cover the text and the bottom half does not, specifically, the word 'paragraph' is obscured but 'span is an' is not

+

codepen url here

","

That's because of the line by line execution of the file. set position:relative for span it will be on top of other elements.

+

+
+
span {
+  margin: 20px;
+  padding: 20px;
+  width: 80px;
+  height: 50px;
+  background-color: red;
+  border: 2px solid blue;
+  position: relative;
+}
+p{
+  width:300px;
+}
+
<p>
+    I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height.
+</p>     
+
+
+

",css +"how to get value from the right class if class is included several times

How do I get the correct value of a class, if the class name is included several times? +I have this structure on a webpage and the value I need is always inside the div "auctionValue" and there in "curreny-coins value" ("5,500" in this example) but this class name ""curreny-coins value" is available 60 times on that page. And I only need the value from "auctionvalue" -> "currency-coins value":

+

+

How can I access this specific class value inside class "auctionValue" and not get all 60 values as a result for example from "auctionStartPrice"? +I tried this:

+
let currencyValues = [];
+function highlightDeal() {
+    let currentBid = document.getElementsByClassName('currency-coins value');
+    for (i = 0; i < currentBid.length; i++) {
+        currencyValues.push(currentBid[i].innerHTML);
+    }
+    console.log(currencyValues);
+}
+
+highlightDeal();
+
+

but it logs an array of all 60 values with that class name.

","

You can target the second child using nth-child selector:

+
document.querySelector(".auction > .auctionValue:nth-child(2) > .currency-coins.value")
+
+

Demo:

+

+
+
const bid = document.querySelector("".auction > .auctionValue:nth-child(2) > .currency-coins.value"").textContent;
+
+console.log(bid);
+
<div class=""auction"">
+
+  <div class=""auctionValue"">
+  </div>
+  
+  <div class=""auctionValue"">
+    <span class=""currency-coins value"">5,500</span>
+  </div>
+  
+  <div class=""auctionValue"">
+  </div>
+
+</div>
+
+
+

",css +"Why the SVG icon does not appear in heading?

I try to add a SVG icon in the h1 heading element:

+
<h1>
+            <svg class="my-svg-inline--fa my-fa-w-18">
+                <use href="https://www.datanumen.com/wp-content/themes/datanumen/images/icons/icons.svg#shopping-cart"></use>
+            </svg> Buy Full Version Now!
+        </h1>
+
+

But the SVG icon will not appear. THe original URL is https://www.datanumen.com/outlook-repair-order/?nowprocket and I create it in JSFiddle at https://jsfiddle.net/alanccw/871v6jke/3/ to demonstrate the issue. Both will not show the SVG icon.

+

Update

+

When test in JSFiddle, I get the following error:

+
fiddle.jshell.net/:140 Unsafe attempt to load URL https://www.datanumen.com/wp-content/themes/datanumen/images/icons/icons.svg from frame with URL https://fiddle.jshell.net/alanccw/871v6jke/3/show/?editor_console=. Domains, protocols and ports must match.
+
+

This issue is discussed in Unsafe attempt to load URL svg

+

But in the original URL, there is no such a problem but the icon still not show.

","

This clearly isn't an issue with your SVG, as you've identified: Your social icons (e.g .../icons.svg#facebook-f) are loading without any problems, and they're being loaded from the same SVG sprite.

+

The problem is your parent div: cta. You're hiding everything inside it with the following CSS:

+
single-wporder .hero-page-wporder .cta * {
+    display:none;
+}
+
+

And then overriding the style on cta's child elements, using the following:

+
.single-wporder .hero-page-wporder .cta h1, 
+.single-wporder .hero-page-wporder .cta h1 svg, 
+.single-wporder .hero-page-wporder .cta h1 path {
+    display: inline-block;
+}
+
+

The problem is the last line. The shopping-cart svg is set to display:none inside the sprite, so you just need to target it and all its children to display it.

+

Update your CSS to this:

+
.single-wporder .hero-page-wporder .cta h1, 
+.single-wporder .hero-page-wporder .cta h1 svg, 
+.single-wporder .hero-page-wporder .cta h1 svg * {
+    display: inline-block;
+}
+
+

The SVG is now visible, and your CTA elements are still hidden:

+

",css +"Why text pulse?

I wonder why this text, although it is the same, is pulsating. Any ideas? Looks like a font rendering issue.

+

+
+
setInterval(() => {
+  const elem =  document.querySelector('p');
+  
+  elem.style.display = elem.style.display === 'none' ? '' : 'none';
+}, 1000)
+
p {
+  position: absolute;
+  color: red;
+}
+
<p>Test</p>
+<p>Test</p>
+
+
+

","

The reason for this is that text normally is rendered anti-aliased, which means that you have pixels with different transparencies (and possibly also color) at the border of the font to get a smooth look:

+

+

The area around the font is therefore up to one pixel larger than it is perceived when you look at it. If you overlay the same text multiple times then it appears to be thicker because the pixels with transparencies overlay and thus reduce the amount of the background to be seen:

+

+

When no anti-aliasing (font smoothing) is active you don't see a difference between the reference text and the case where multiple elements overlay (that example might not work for every browser or os):

+

+
+
p {
+  position: absolute;
+}
+
+* {
+  font-smooth: never;
+  -webkit-font-smoothing: none;
+ }
+
<p>overlayed text</p>
+<p>overlayed text</p>
+<p>overlayed text</p>
+<p>overlayed text</p>
+<div>reference text</div>
+
+
+

+

With anti-aliasing (font smoothing) is active you can see that the overlayed text looks bolder then the reference text.

+

+
+
p {
+  position: absolute;
+}
+
<p>overlayed text</p>
+<p>overlayed text</p>
+<p>overlayed text</p>
+<p>overlayed text</p>
+<div>reference text</div>
+
+
+

",css +"Is it possible to customize radio button with react and styled-component?

I am trying to make a radio button using the radio type of the <input>. Instead of label, components are bundled together, and instead of using packages such as MUI, I try to use the <input> tag directly.

+

The functions I want are:

+
    +
  1. A circle exists inside regardless of whether it is checked or not. Instead, it is displayed in gray when it is unchecked and blue when it is checked.
  2. +
+

+
    +
  1. I can change the color of the radio button. However, when checked, the color of the border of the outer circle does not change (the default behavior is that the color of both the outer circle and the inner circle changes).
  2. +
+

I succeeded change the color using the accent-color property. However, the color of both the outer circle and the inner circle changes together. Is there a way to satisfy all of the above functions using <input type="radio"..>?

","

There's no way (as far as I know) to reliably exert full control over the appearance of the input itself.

+

However, there is a common trick to overcome this limitation: hide the actual input and render a pseudo-element in its place, as in the example below.

+

I've wrapped the inputs in a <label> here so that clicks still trigger the native inputs to check/uncheck.

+

Note that because inputs may be replaced elements it's possible that input::after won't work in every browser. If it's a problem you could use an actual span (or whatever) instead.

+

Also: I haven't needed to solve this problem in a long time, so my method may be outdated. There are several articles and demos to be found that may give you other solutions or better ideas.

+

+
+
.radio {
+  --size: 30px;
+  --padding: calc(var(--size) + 1em);
+  position: relative;
+  margin: .25em;
+  min-height: var(--size);
+  padding-left: var(--padding);
+  cursor: pointer;
+}
+
+.radio input {
+  visibility: hidden;
+  position: absolute;
+}
+
+input[type=radio]::after {
+  --color-border: lightgray;
+  --color-dot: var(--color-border);
+  content: '';
+  visibility: visible;
+  position: absolute;
+  top: 50%;
+  transform: translateY(-50%);
+  left: calc(var(--padding) * -1);
+  width: var(--size);
+  height: var(--size);
+  border-radius: 50%;
+  color: lightgray;
+  background: radial-gradient(var(--color-dot) 0%, var(--color-dot) 40%,  white 40%);
+  box-shadow: 0 0 0 2px var(--color-border);
+  pointer-events: none;
+}
+
+input[type=radio]:checked::after {
+  --color-dot: blue;
+}
+
<label class=""radio"">
+  <input type=""radio"" name=""demo"" value=""1"" checked />
+  One
+</label>
+<label class=""radio"">
+  <input type=""radio"" name=""demo"" value=""2"" />
+  Two
+</label>
+<label class=""radio"">
+  <input type=""radio"" name=""demo"" value=""3"" />
+  Three
+</label>
+
+
+

",css +"Precise text overlay on image (and responsive)

I would like to put text on a specific spot on a picture. This text must stay in the same place relative to the image. I made this simple example to illustrate the problem. The 60kg must stay next to the materials. If i resize the browser slightly the text moves and is not next to the materials anymore. This is how it is supposed to be (even when resizing): example

+

+
+
.background {
+  background-color: lightgrey;
+  position: relative;
+}
+
+.crane {
+  width: 30vw;
+  margin-left: 35vw;
+  position: absolute;
+}
+
+.overlay {
+  background-color: rgb(255, 0, 0, 0.5);
+  position: absolute;
+  margin-left: 43vw;
+  margin-top: 37vh;
+  width: auto;
+  font-size: 1em;
+  padding: 2px;
+}
+
<div class=""background"">
+  <img class=""crane"" src=""https://img.freepik.com/free-vector/isolated-tower-crane-cartoon-style_1308-104645.jpg?w=2000"" 
+    class=""img-responsive"">
+</div>
+<div class=""overlay"">
+    60kg
+</div>
+
+
+

","

Don't position the image, and use percentages to position the text rather than absolute values.

+

+
+
.background {
+  background-color: lightgrey;
+  position: relative;
+  display: inline-block;
+  height: 100vh;
+}
+
+.crane {
+  max-width: 100%;
+  height: 100%;
+}
+
+.overlay {
+  background-color: rgb(255, 0, 0, 0.5);
+  position: absolute;
+  left: 30%; /* adjust as required */
+  top: 52%; /* adjust as required */
+  width: auto;
+  font-size: 1em;
+  padding: 2px;
+}
+
<body>
+  <div class=""background"">
+    <img class=""crane"" src=""https://img.freepik.com/free-vector/isolated-tower-crane-cartoon-style_1308-104645.jpg?w=2000"" class=""img-responsive"">
+    <div class=""overlay"">
+      60kg
+    </div>
+</body>
+
+
+

",css +"Background-image CSS does not load

In an HTML webpage I created, a stylesheet is attached that, among other things, uses "background-image" to add an image from a CDN, using this code _

+
BODY{
+background-image: url(https://CDN/FILE.jpg);
+}
+
+

This seems to just create a blank background -- however, when I turn off the style on the Element Inspector and then turn it on again, it works perfectly fine. What am I doing wrong?

+

Thanks.

","

You probably forgot "" around the link. +Try background-image: url("https://CDN/FILE.jpg");

+

I'd suggest making an example in codepen if this isn't the case.

",css +"React prevent css animation restarting every state change

I have two child components, an image gallery and a hidden components which will display the clicked image of the gallery at full size.

+
    const [selectedIndex, setSelectedtIndex] = useState(0);
+    const [galleryVisible, setGalleryVisible] = useState(false);
+
+    const FirstComponent = () => {
+        return (
+           <div className={'gallery-container'}>
+               <div class='img fade-1' onClick={() => handleClick(1)}>Image 1</div>
+               <div class='img fade-2' onClick={() => handleClick(2)}>Image 2</div>
+               <div class='img fade-3' onClick={() => handleClick(3)}>Image 3</div>
+               [...]
+           </div>
+        )
+    }
+
+    const handleClick = (index) => {
+        setSelectedtIndex(index)
+        setGalleryVisible(true)
+    }
+
+    const SecondComponent = ({ index }) => {
+        return (
+            <div className={`selected-img`}>Selected : {index} (But the fading animation shouldn't restart è_é)</div>
+        )
+    }
+
+    return (
+        <>
+            <FirstComponent/>
+            {galleryVisible && 
+                <SecondComponent index={selectedIndex} />
+            }
+        </>
+    )
+
+

The issue is that I also have a fade-in animation on the first component, and every time I click on an image to display the second component, that animation resets due to the rerender of react on state change.

+
    &.fade-1 {
+      animation-delay: 0s
+    }
+    &.fade-2 {
+      animation-delay: 0.5s
+    }
+     &.fade-3 {
+      animation-delay: 1s
+    }
+
+

I don't know how can I only change the second component when the state is changed from a click on the first one... I tried to play with useMemo but couldn't get it to work.

+

Here is a codepen reproducing the issue : https://codepen.io/disgallion/pen/zYjqPBE

","

Move the first component outside of App and pass handleClick to its props:

+

+  const FirstComponent = ({handleClick}) => {
+    return (
+      <div className={'gallery-container'}>
+        <div class='img fade-1' onClick={() => handleClick(1)}>1</div>
+        <div class='img fade-2' onClick={() => handleClick(2)}>2</div>
+        <div class='img fade-3' onClick={() => handleClick(3)}>3</div>
+      </div>
+    )
+  }
+
+const App = () => {
+  const [selectedIndex, setSelectedtIndex] = useState(0);
+  const [galleryVisible, setGalleryVisible] = useState(false);
+
+  const handleClick = (index) => {
+    console.log('click')
+    setSelectedtIndex(index)
+    setGalleryVisible(true)
+  }
+
+
+  
+  const SecondComponent = ({ index }) => {
+    return (
+      <div className={`selected-img`}>Selected : {index} (But the fading animation shouldn't restart è_é)</div>
+    )
+  }
+  
+  return (
+    <>
+      Click on an image to open the fullsize gallery:
+      <FirstComponent handleClick={handleClick} />
+      {galleryVisible && 
+        <SecondComponent index={selectedIndex} />
+      }
+    </>
+  )
+}
+
+ReactDOM.render(<App />,
+document.getElementById("root"))
+
+

Now the state change of App will not trigger a re-render in FirstComponent

",css +"LI's with variable pixel/% widths not followed in full width of container

I'm working with the following code which creates a series of boxes as <UL><LI> tags. The splits are separate <LI>s with a background img containing the arrows. What needs to happen is that if you resize, the arrow-LI size must not change, but the data-LI size should accommodate and shrink accordingly. To accomplish this, the arrow-LI widths are specified in px, and the data-LI in %. At all times, the entire box bar must be 1-line.

+

+

This should work, but I see that if I resize, the last box is brought out to a 2nd line, and at some point later the next-to-last box will be lowered to a 2nd line too. The text does shrink, but it should auto-shrink even more to satisfy any reasonable browser width, while the arrow LIs are fixed.

+

+

Some text e.g. "Reference Letter Deadline" did shrink, but not enough to keep everything on 1 line.

+

+

Code:

+
    <ul class="arrowDateBoxes dateLists">
+        <li class="arrowDateBox1">
+            <div class="arrowDateBoxContent">Application Cycle Opens</div>
+        </li>
+        <li class="arrowDateBox1Arrow">
+        </li>
+        <li class="arrowDateBox2">
+            <div class="arrowDateBoxContent">Application Deadline</div>
+        </li>
+        <li class="arrowDateBox2Arrow">
+        </li>
+        <li class="arrowDateBox1">
+            <div class="arrowDateBoxContent">Reference Letter Deadline</div>
+        </li>   
+        <li class="arrowDateBox1Arrow">
+        </li>
+        <li class="arrowDateBox2">
+            <div class="arrowDateBoxContent">Selections for Program Interviews</div>
+        </li>
+        <li class="arrowDateBox2Arrow">
+        </li>   
+        <li class="arrowDateBox1">
+            <div class="arrowDateBoxContent">Interviews</div>
+        </li>       
+        <li class="arrowDateBox1Arrow">
+        </li>
+        <li class="arrowDateBox2">
+            <div class="arrowDateBoxContent">Offer Acceptance Deadline Date</div>
+        </li>
+        <li class="arrowDateBox2Arrow">
+        </li>
+        <li class="arrowDateBox1">
+            <div class="arrowDateBoxContent">ICRC Term Begins</div>
+        </li>   
+
+

CSS

+
/* Generally for all boxes */
+ul.arrowDateBoxes li { 
+    display: inline;
+    float:left;
+    font-size:14px;
+    font-weight: bold;
+}
+
+/* Bi-color: 
+   data boxes (arrowDateBoxN), width as % to be flexible, and 
+   arrow boxes (arrowDateBoxNArrow), width as px to be fixed */
+/* ----------------- */
+.arrowDateBox1 {
+    background-color: #E8E8E8;
+    color: #143A66;
+    width: 12.5%;
+    height: 57px;
+    padding-left: 15px;
+}
+.arrowDateBox1Arrow {
+    background-image: url('../images/menuarrow-split1.svg');
+    background-repeat: no-repeat;
+    width: 30.5px;
+    height: 57px;
+}   
+
+.arrowDateBox2 {
+    background-color: #A9CDF1;
+    color: #143A66;
+    width: 12.5%;
+    height: 57px;
+    padding-left: 15px;
+}
+.arrowDateBox2Arrow {
+    background-image: url('../images/menuarrow-split2.svg');
+    background-repeat: no-repeat;
+    width: 30.5px;
+    height: 57px;
+}   
+
+

Per request, the SVGs (bi-colored arrow splits):

+
<svg xmlns="http://www.w3.org/2000/svg" width="30.541" height="57.001" viewBox="0 0 30.541 57.001">
+  <g id="Group_225" data-name="Group 225" transform="translate(-312.858 -383.001)">
+    <path id="Polygon_30" data-name="Polygon 30" d="M28.5,0,57,18.143H0Z" transform="translate(331.001 383.002) rotate(90)" fill="#e8e8e8"/>
+    <path id="Subtraction_11" data-name="Subtraction 11" d="M18.4,57H0L18.142,28.5,0,0H18.4Z" transform="translate(325 383.001)" fill="#a9cdf1"/>
+  </g>
+</svg>
+
+
+<svg xmlns="http://www.w3.org/2000/svg" width="30.541" height="57.001" viewBox="0 0 30.541 57.001">
+  <g id="Group_225" data-name="Group 225" transform="translate(-312.858 -383.001)">
+    <path id="Polygon_30" data-name="Polygon 30" d="M28.5,0,57,18.143H0Z" transform="translate(331.001 383.002) rotate(90)" fill="#a9cdf1"/>
+    <path id="Subtraction_11" data-name="Subtraction 11" d="M18.4,57H0L18.142,28.5,0,0H18.4Z" transform="translate(325 383.001)" fill="#e8e8e8"/>
+  </g>
+</svg>
+
","

Change the ul to display:flex. It'll keep it all on one line. You can also probably cut out a fair amount of markup by using the ::after pseudo element for your arrows. Fire over the svg (or provide a link to it) and I'll have a look.

+
    ul.arrowDateBoxes {
+      display:flex;
+    }
+
+    /* Generally for all boxes */
+    ul.arrowDateBoxes li {
+      list-style-type: none;
+      font-size: 14px;
+      font-weight: bold;
+      overflow: hidden;
+    }
+
+    /* Bi-color: 
+   data boxes (arrowDateBoxN), width as % to be flexible, and 
+   arrow boxes (arrowDateBoxNArrow), width as px to be fixed */
+    /* ----------------- */
+    .arrowDateBox1 {
+      background-color: #E8E8E8;
+      color: #143A66;
+      width: 12.5%;
+      height: 57px;
+      padding-left: 15px;
+    }
+
+    .arrowDateBox1Arrow {
+      background-image: url('../images/menuarrow-split1.svg');
+      background-repeat: no-repeat;
+      width: 30.5px;
+      height: 57px;
+    }
+
+    .arrowDateBox2 {
+      background-color: #A9CDF1;
+      color: #143A66;
+      width: 12.5%;
+      height: 57px;
+      padding-left: 15px;
+    }
+
+    .arrowDateBox2Arrow {
+      background-image: url('../images/menuarrow-split2.svg');
+      background-repeat: no-repeat;
+      width: 30.5px;
+      height: 57px;
+    }
+
",css +"How to create a reusable component with many possibilities based on the screen size?

I'm making a blog website with a UI similar to https://atlas-demo.blogspot.com. A card component is used all over the main page, which has different layouts in different screen sizes. There is no specific pattern so I'm having difficulties creating a reusable component.

+

These are some of the possibilities for the card component:

+

Possibility #1

+
+ + + + + + + + + + + + + + + + + + + + + +
Screen sizeLayout
mobilefloat
tabletfloat
mobilefloat
+
+

Possibility #2

+
+ + + + + + + + + + + + + + + + + + + + + +
Screen sizeLayout
mobilefloat
tabletfloat
mobilehorizontal
+
+

Possibility #3

+
+ + + + + + + + + + + + + + + + + + + + + +
Screen sizeLayout
mobilehorizontal
tablethorizontal
mobilefloat
+
+

Possibility #4

+
+ + + + + + + + + + + + + + + + + + + + + +
Screen sizeLayout
mobilevertical
tabletvertical
mobilevertical
+
+

And by "float" and "horizontal" and "vertical" I mean

+

float:

+

+

horizontal:

+

+

vertical:

+

+

I can't find any pattern between these possibilities. My workaround is to pass a layout object to the component that defines the way it should look in different screen sizes. something like this:

+
const layout = {
+  mobile: "float",
+  tablet: "horizontal",
+  desktop: "horizontal"
+}
+
+

And I add different classes based on the layout object:

+
<div class={classnames(
+        layout.mobile === "float" && "mobile:relative",
+        layout.tablet === "float" && "tablet:relative",
+        layout.desktop === "float" && "desktop:relative",
+
+        layout.mobile === "horizontal" && "mobile:flex",
+        layout.tablet === "horizontal" && "tablet:flex",
+        layout.desktop === "horizontal" && "desktop:flex",
+
+        layout.mobile === "vertical" && "mobile:flex mobile:flex-col",
+        layout.tablet === "vertical" && "tablet:flex tablet:flex-col",
+        layout.desktop === "vertical" && "desktop:flex desktop:flex-col",
+
+     )}>
+</div>
+
+

BTW this is JSX syntax with tailwindcss classes.

+

As you can see, it's very messy and it gets worst as the complexity grows:

+
    +
  1. What if I want the image to be in a square shape when the layout is not "float"?
  2. +
  3. What if I want to add something to the card, like an icon, but it should be in the corner for "horizontal" and "vertical" layouts and in the center for the "float" layout?
  4. +
+

And so on.

+

So I like to hear your take on this. I don't want you to do my homework, I just need some ideas. Anything could be helpful. Maybe a design pattern that I don't know?

","

The areas are in my opinion still logically divided and each area can be given a unique css class.

+

eg top most slider can be ticker and the unique behavior is, the layout of each card doesn't change

+

the middle area with 5 cards can be featured and the unique behaviour is, except slider, all other cards change the layout at the different viewport, eg desktop and tablet = float and for mobile = horizontal

+

Similarly, the rest of the rules can be created based on the context.

+

It's hard to generalise and hence easy to hard code the configuration.

+

I am not a tailwind expert so can't give you an equivalent code. Hope you got my point.

",css +"Container size doesn't shrink with child scale

I'm trying to create a custom drop down menu in ReactJs. When a user clicks the heading, a list of items appears below it. This works but I want the div that contains both the heading and the list (.db-container) to in increase its height depending on if the list (.db-list) is visible or not. I can use display:none/block or position:absolute/relative with transform:scaleY(0)/scaleY(1) on .db-list but then I cannot animate it or use transitions. I've tried using visibility:hidden/visible which does hide the list but the container remains its full size.

+

I am using ReactJs and in the code snippet below, the handleClick() function just changes isVisible from true to false and vice versa.

+

+
+
.db-container {
+  display: flex;
+  flex-direction: column;
+  justify-content: flex-start;
+}
+
+.db-list {
+  transform: scaleY(0);
+  transform-origin: top center;
+  position: absolute;
+}
+
+.visible-true {
+  transform: scaleY(1) !important;
+  position: relative !important;
+}
+
<div className='db-container'>
+  <h3 className='db-name' onClick={handleClick}>Headinf</h3>
+  <ul className={`db-list visible-${isVisible}`}>
+    <li>One</li>
+    <li>Two</li>
+    <li>Three</li>
+    <li>Four</li>
+  </ul>
+</div>
+
+
+

+

Is there a way to get .db-container to change its height depending on the visibility of .db-list and use animations or transitions?

","

Use max-height and overflow:hidden. These are animatable. Needs a bit of tidying up but you'll get the general idea. Setting max-height means the element will just size itself to the content as long as you set it to a high enough value. (I've made it transform on :hover but you can change it to a click in react)

+
.db-container {
+    display: flex;
+    flex-direction: column;
+    justify-content: flex-start;
+}
+
+.db-list {
+    max-height:0px;
+    overflow: hidden;
+    transition: max-height 1s;
+}
+
+.db-name:hover + .db-list {
+  max-height:1000px;
+}
+
",css +"How to make CSS SVG files close together using Flex

This is my first post on here as it seems to be quite a weird problem.

+

I am very new to HTML and CSS but I seemed to have learnt the majority of it in a couple of days. +There is one thing which is very confusing to me regarding flex. It has been very simple when dealing with other elements, like the links in the Navigation at the top of the page. However when I have put flex on the Social Media SVG icons, they have this weird spacing between them.

+

Here is me hovering my mouse over the gaps when in F12 picker mode

+

The spacing isnt padding or margins or anything like that. All I have done is set the container they are in to have display:flex; and that is it. Any help will be appriciated!

+

The website I am building with the problem area circled in red

+

Side note: Sorry most of the site is blurred, it contains potentially sensitive information about a small organisation I wouldn't like to be shared :(

+

Here is the CSS Code:

+
.footer {
+  display: flex;
+  justify-content: space-around;
+}
+
+.social-icons ul {
+  display: flex;
+}
+
+.social-icons img {
+  width: 5em;
+}
+
+

Here is the questionable HTML:

+
<footer id="footer" class="padding-block-big text-primary-heading bg-main fw-regular fs-small">
+  <div class="footer">
+    <div class="social-icons">
+      <h3 class="fs-regular">
+        Follow Us:
+      </h3>
+      <ul role="list" aria-label="Social Media Links">
+        <li><a aria-label="Facebook" href=""><img src="Images\Facebook.svg" alt="Facebook"></a></li>
+        <li><a aria-label="Twitter" href=""><img src="Images\Twitter.svg" alt="Twitter"></a></li>
+        <li><a aria-label="Instagram" href=""><img src="Images\Instagram.svg" alt="Instagram"></a></li>
+        <li><a aria-label="YouTube" href=""><img src="Images\Youtube.svg" alt="Youtube"></a></li>
+      </ul>
+    </div>
+  </div>
+</footer>
+
","

You are using flex on a ul tag which has its own styles (like padding and list-style), so I reset those.

+

+
+
.footer {
+  display: flex;
+  justify-content: space-around;
+}
+
+.social-icons ul {
+  display: flex;
+  list-style: none;
+  padding: 0;
+  margin: 0;
+}
+
+.social-icons img {
+  width: 5em;
+}
+
<footer id=""footer"" class=""padding-block-big text-primary-heading bg-main fw-regular fs-small"">
+  <div class=""footer"">
+    <div class=""social-icons"">
+      <h3 class=""fs-regular"">
+        Follow Us:
+      </h3>
+      <ul role=""list"" aria-label=""Social Media Links"">
+        <li>
+          <a aria-label=""Facebook"" href=""""><img src=""Images\Facebook.svg"" alt=""Facebook""></a>
+        </li>
+        <li>
+          <a aria-label=""Twitter"" href=""""><img src=""Images\Twitter.svg"" alt=""Twitter""></a>
+        </li>
+        <li>
+          <a aria-label=""Instagram"" href=""""><img src=""Images\Instagram.svg"" alt=""Instagram""></a>
+        </li>
+        <li>
+          <a aria-label=""YouTube"" href=""""><img src=""Images\Youtube.svg"" alt=""Youtube""></a>
+        </li>
+      </ul>
+    </div>
+  </div>
+</footer>
+
+
+

",css +"Animation effect on SVG using ::after pseudo-element

I have been using ::after pseudo-element to create a shining effect on all of my divs, and I need to implement the same approach to an SVG icon. But with SVGs, I need the animation to be just within the SVG and not on its parent container. Can anyone please help?

+

+
+
.svg-icon {
+  position: relative;
+  background-color: black;
+  overflow: hidden;
+  max-width: 100px;
+}
+
+.svg-icon::after {
+  position: absolute;
+  width: 5px;
+  height: 150px;
+  left: -200px;
+
+  background: white;
+
+  animation: shimmer 5s ease-in-out 1s infinite;
+  content: '';
+}
+
+@keyframes shimmer {
+  100% {
+    left: 200px;
+  }
+}
+
<div class=""svg-icon"">
+<svg
+  version=""1.1""
+  id=""Layer_1""
+  xmlns=""http://www.w3.org/2000/svg""
+  xmlns:xlink=""http://www.w3.org/1999/xlink""
+  x=""0px""
+  y=""0px""
+  viewBox=""0 0 512.001 512.001""
+  style=""enable-background:new 0 0 512.001 512.001;""
+  xml:space=""preserve""
+>
+  <g>
+    <path
+      style=""fill:#FFC855;""
+      d=""M256.955,0.05l-71.56,458.945L12.069,482.63c-8.631,1.177-14.926-7.971-10.743-15.611L256.955,0.05z
+    ""
+    />
+    <path
+      style=""fill:#FFC855;""
+      d=""M256.955,0.05l78.48,458.945l164.43,23.49c8.639,1.235,14.992-7.906,10.825-15.573L256.955,0.05z""
+    />
+  </g>
+  <polygon
+    style=""fill:#FAAF50;""
+    points=""256.955,0.05 256.955,511.951 335.434,458.996 ""
+  />
+  <polygon
+    style=""fill:#FFE182;""
+    points=""256.955,0.05 185.394,458.996 256.955,511.951 ""
+  />
+</svg>
+</div>
+
+
+

+

Basically, I need the shining white line to not be visible on the black background. Thanks in advance.

","

css

+
.preloader {
+  position: fixed;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  width: 30%;
+  height: 25vh;
+  background: black;
+}
+
+
+.logo {
+  display: none;
+}
+
+.wrapper {
+  overflow: hidden;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  width: 60%;
+}
+
+/* Make the gradient visible only on hover*/
+linearGradient {
+  display: none;
+}
+path {
+  fill: #FFC855;
+}
+polygon {
+  fill: #FFC855;
+}
+svg linearGradient {
+  display: initial;
+}
+svg path {
+  fill: url(#linear-gradient);
+}
+svg g {
+  fill: url(#linear-gradient);
+}
+svg polygon {
+  fill: url(#linear-gradient);
+}
+/**/
+
+

html

+
<div class="preloader">
+  <span class="wrapper">
+    <svg
+      version="1.1"
+      id="Layer_1"
+      xmlns="http://www.w3.org/2000/svg"
+      xmlns:xlink="http://www.w3.org/1999/xlink"
+      x="0px"
+      y="0px"
+      viewBox="0 0 512.001 512.001"
+      style="enable-background:new 0 0 512.001 512.001;"
+      xml:space="preserve"
+    >
+      <defs>
+        <linearGradient
+          id="linear-gradient"
+          x1="-100%"
+          y1="100%"
+          x2="800%"
+          y2="0"
+        >
+          <stop offset="0" stop-color="#FFC855">
+            <animate
+              attributeName="offset"
+              values="0;0.8"
+              dur="1s"
+              repeatCount="indefinite"
+            />
+          </stop>
+          <stop offset="0" stop-color="#FFC855">
+            <animate
+              attributeName="offset"
+              values="0;0.8"
+              dur="2s"
+              repeatCount="indefinite"
+            />
+          </stop>
+          <stop offset="0.1" stop-color="white">
+            <animate
+              attributeName="offset"
+              values="0.1;1"
+              dur="2s"
+              repeatCount="indefinite"
+            />
+          </stop>
+          <stop offset="0.1" stop-color="#FFC855">
+            <animate
+              attributeName="offset"
+              values="0.1;1"
+              dur="2s"
+              repeatCount="indefinite"
+            />
+          </stop>
+        </linearGradient>
+      </defs>
+      <g fill="url(#linear-gradient)">
+        <path
+          d="M256.955,0.05l-71.56,458.945L12.069,482.63c-8.631,1.177-14.926-7.971-10.743-15.611L256.955,0.05z"
+        />
+        <path
+          d="M256.955,0.05l78.48,458.945l164.43,23.49c8.639,1.235,14.992-7.906,10.825-15.573L256.955,0.05z"
+        />
+
+        <polygon points="256.955,0.05 256.955,511.951 335.434,458.996 " />
+        <polygon points="256.955,0.05 185.394,458.996 256.955,511.951 " />
+      </g>
+    </svg>
+  </span>
+</div>
+
+

I hope it helps you

",css +"Change width of the Validation error message div

+

This is how the error message is getting displayed once the validations are added. It only takes the width of that div. How can I change the width so the error message fits a single line? If there's any other way to do front-end validations please suggest it.

+

+
+
.age {
+  width: 53px;
+  font-weight: 700;
+  font-size: 16px;
+  letter-spacing: 0.15px;
+  color: rgba(0, 0, 0, 0.6);
+}
+
+.input-group {
+  margin-bottom: 9px;
+  position: relative;
+}
+
+.input-group__label {
+  z-index: 5;
+  display: block;
+  position: absolute;
+  top: 0;
+  line-height: 40px;
+  color: #aaa;
+  left: 5px;
+  padding: 0 7px;
+  transition: line-height 200ms ease-in-out, font-size 200ms ease-in-out, top 200ms ease-in-out;
+  pointer-events: none;
+  font-weight: 700;
+  font-size: 16px;
+  letter-spacing: 0.15px;
+  color: rgba(0, 0, 0, 0.6);
+}
+
+.input-group__input {
+  width: 100%;
+  height: 40px;
+  border: 1px solid rgba(0, 0, 0, 0.3);
+  border-radius: 4px !important;
+  padding: 0 10px;
+}
+
+
+   
+
<div class=""input-group age"">
+                    <input class=""input-group__input form-control is-invalid""
+                           type=""text""
+                           placeholder=""&nbsp;""
+                           name=""age""
+                           id=""validationError""
+                           autocomplete=""off""
+                           required />
+                    <label class=""input-group__label"" for=""age"">Age</label>
+                    <div class=""invalid-feedback"">
+                      Please enter an age between 35-74
+                      years.
+                    </div>
+                  </div>
+
+
+

","

You can't really change the width of your invalid-feedback element because it's max width is being controlled by its parent input-group age. I'd suggest removing the age class and instead apply it to its first two children, minus its third child invalid-feedback.

+

Note: I also increased the max width of the age class, otherwise the validation icons' are obtruding the view of the validation text due to lack of space.

+

+
+
<script src=""https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js""></script>
+<link href=""https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css"" rel=""stylesheet""/>
+<style>
+    .age {
+        max-width: 96px;
+        font-weight: 700;
+        font-size: 16px;
+        letter-spacing: 0.15px;
+        color: rgba(0, 0, 0, 0.6);
+    }
+    .input-group {
+        margin-bottom: 9px;
+        position: relative;
+    }
+    .input-group__label {
+        z-index: 5;
+        display: block;
+        position: absolute;
+        top: 0;
+        line-height: 40px;
+        color: #aaa;
+        left: 5px;
+        padding: 0 7px;
+        transition: line-height 200ms ease-in-out, font-size 200ms ease-in-out, top 200ms ease-in-out;
+        pointer-events: none;
+        font-weight: 700;
+        font-size: 16px;
+        letter-spacing: 0.15px;
+        color: rgba(0, 0, 0, 0.6);
+    }
+    .input-group__input {
+        width: 100%;
+        height: 40px;
+        border: 1px solid rgba(0, 0, 0, 0.3);
+        border-radius: 4px !important;
+        padding: 0 10px;
+    }
+</style>
+<div class=""input-group"">
+  <input class=""age input-group__input form-control is-invalid""
+         type=""text""
+         placeholder=""&nbsp;""
+         name=""age""
+         id=""validationError""
+         autocomplete=""off""
+         required />
+  <label class=""age input-group__label"" for=""age"">Age</label>
+  <div class=""invalid-feedback"">
+    Please enter an age between 35-74 years.
+  </div>
+</div>
+
+
+

",css +"Why does clicking a button with two event handlers attached to it results in the page scrolling back to the top?

In a WordPress page with a CTA button, I attached two click event handlers one of which is to show an element that wraps an Hubspot form while the other one is to scroll to the beginning of the form.

+

HTML for the button:

+
<a id="btn" class="btn" role="button" href="javascript:void(0)" onclick="resetScrollpoint('#contact-form-wrap')" target="<?php echo $link['target']; ?>" title="<?php echo $link['title']; ?>">
+    <?php echo $link['title']; ?>
+</a>
+
+

Element that contains the hidden form. Form is by default hidden.

+
  <div id="contact-form-wrap" class="contact-form-wrap" style="display:none;"> <?php echo do_shortcode("$contact"); ?></div>
+
+

JS:

+
jQuery(document).ready(function ($) {
+    $("#btn").click(function () {
+        $("#contact-form-wrap").show();
+        return false;
+    });
+});
+
+function resetScrollpoint(selector) {
+  if(!selector) return false;
+  window.scroll(0,$(selector).offset().top - $('#header').height());
+}
+
+

Please see the image below to see where the problem is in the page here.

+

+

Please note this code works if I remove style="display:none; from the element that wraps the form.

","

Take the call to resetScrollPoint() out of the onclick attribute, and call it from the jQuery handler. That way you can call it after unhiding the element, so its position is known.

+
jQuery(document).ready(function ($) {
+    $("#btn").click(function () {
+        $("#contact-form-wrap").show();
+        resetScrollpoint('#contact-form-wrap');
+        return false;
+    });
+});
+
",css +"How to prevent icon position from changing in input when invalid feedback occur?

+

I was facing this problem when there is invalid feedback in the credential, it will cause the icon to move away from its original position. Hereby I attach my code with the relevant CSS. For Your information, I apply bootstrap & Bootstap icon in my design code.

+
<div class="form-group position-relative has-icon-left mb-3">
+     <input type="text" class="form-control form-control @error('username') is-invalid @enderror" id="username"  
+     name="username" placeholder="Username">
+     <div class="form-control-icon">
+         <i class="bi bi-person"></i>
+     </div>
+    @error('username')
+        <span class="invalid-feedback" role="alert">
+            <strong>{{ $message }}</strong>
+        </span>
+    @enderror
+</div>
+
+

CSS Part

+
.form-group[class*=has-icon-].has-icon-left .form-control-icon{left:0}
+.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}
+.form-group{margin-bottom:.7rem}
+.position-relative{position:relative!important}
+.form-control {
+      display: block;
+      width: 100%;
+      background-color: #f9f9f9;
+      padding: 12px;
+      border: 1px solid #ddd;
+      border-radius: 2.5px;
+      font-size: 14px;
+      -webkit-appearance: none;
+      -moz-appearance: none;
+           appearance: none;
+      margin-bottom: 24px;
+    }
+.form-group[class*=has-icon-].has-icon-left .form-control-icon{left:0}.
+
","

It may Help You!!!

+
.form-group[class*=has-icon-].has-icon-left .form-control-icon{ position: absolute;left:0px;top:0px}
+
",css +"Why can't I use flex with