diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404/index.html b/404/index.html new file mode 100644 index 0000000..ebd5e48 --- /dev/null +++ b/404/index.html @@ -0,0 +1,12 @@ +
Dendron (the tool used to generate this site) lets authors selective publish content. You will see this page whenever you click on a link to an unpublished page
\n","noteIndex":{"id":"root","title":"Inicio","desc":"","updated":1685946892733,"created":1595961348801,"custom":{"nav_order":0,"permalink":"/"},"fname":"root","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"e61b300237deb393ece8248ab604975d","links":[{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"code","position":{"start":{"line":3,"column":3,"offset":4},"end":{"line":3,"column":11,"offset":12},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"code"}},{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"math","position":{"start":{"line":4,"column":3,"offset":15},"end":{"line":4,"column":11,"offset":23},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"math"}}],"anchors":{},"children":["631hw9oh0k8jhc0wlm0joyz","rzreoc67l24hzknyqbn3a9b"],"parent":null,"data":{},"body":"\n\n* [[code]]\n* [[math]]"},"collectionChildren":null,"customHeadContent":null,"config":{"version":5,"dev":{"enablePreviewV2":true,"enableSelfContainedVaults":true},"commands":{"lookup":{"note":{"selectionMode":"extract","confirmVaultOnCreate":true,"vaultSelectionModeOnCreate":"smart","leaveTrace":false,"bubbleUpCreateNew":true,"fuzzThreshold":0.2}},"randomNote":{},"insertNoteLink":{"aliasMode":"none","enableMultiSelect":false},"insertNoteIndex":{"enableMarker":false},"copyNoteLink":{"aliasMode":"title"},"templateHierarchy":"template"},"workspace":{"vaults":[{"fsPath":"dependencies/github.com/renegarcia/eleventa-db","remote":{"type":"git","url":"git@github.com:renegarcia/eleventa-db.git"},"selfContained":true,"name":"eleventa-db"},{"fsPath":".","selfContained":true,"name":"Dendron"}],"journal":{"dailyDomain":"daily","name":"journal","dateFormat":"y.MM.dd","addBehavior":"childOfDomain"},"scratch":{"name":"scratch","dateFormat":"y.MM.dd.HHmmss","addBehavior":"asOwnDomain"},"task":{"name":"task","dateFormat":"y.MM.dd","addBehavior":"asOwnDomain","statusSymbols":{"":" ","wip":"w","done":"x","assigned":"a","moved":"m","blocked":"b","delegated":"l","dropped":"d","pending":"y"},"taskCompleteStatus":["done","x"],"prioritySymbols":{"H":"high","M":"medium","L":"low"},"todoIntegration":false,"createTaskSelectionType":"selection2link"},"graph":{"zoomSpeed":1,"createStub":false},"enableAutoCreateOnDefinition":false,"enableXVaultWikiLink":false,"enableRemoteVaultInit":true,"enableUserTags":true,"enableHashTags":true,"workspaceVaultSyncMode":"noCommit","enableAutoFoldFrontmatter":false,"enableEditorDecorations":true,"maxPreviewsCached":10,"maxNoteLength":204800,"enableFullHierarchyNoteTitle":false},"preview":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enablePrettyRefs":true,"enableKatex":true,"automaticallyShowPreview":false},"publishing":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enablePrettyRefs":true,"enableKatex":true,"copyAssets":true,"siteHierarchies":["root"],"writeStubs":false,"siteRootDir":"docs","seo":{"title":"Notes","description":"Personal Knowledge Space or Rene Garcia"},"github":{"enableEditLink":true,"editLinkText":"Edit this page on GitHub","editBranch":"main","editViewMode":"tree"},"enableSiteLastModified":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enableRandomlyColoredTags":true,"enableTaskNotes":true,"enablePrettyLinks":true,"searchMode":"search","enableHierarchyDisplay":true,"hierarchyDisplayTitle":"Children","duplicateNoteBehavior":{"action":"useVault","payload":["eleventa-db","Dendron"]},"siteUrl":"https://renegarcia.github.io","assetsPrefix":"/dendron","siteFaviconPath":"favicon.ico","siteIndex":"root"}}},"__N_SSG":true} \ No newline at end of file diff --git a/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/4k7eb68p8o3ctljv6pl0g3q.json b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/4k7eb68p8o3ctljv6pl0g3q.json new file mode 100644 index 0000000..03674f2 --- /dev/null +++ b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/4k7eb68p8o3ctljv6pl0g3q.json @@ -0,0 +1 @@ +{"pageProps":{"note":{"id":"4k7eb68p8o3ctljv6pl0g3q","title":"Stats","desc":"","updated":1685946339689,"created":1685946339689,"custom":{},"fname":"math.stats","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"f54a190589d2bb0e96eec42c44f13e92","links":[],"anchors":{},"children":["zmvhm0w2tjs2njii7b7nrm5"],"parent":"rzreoc67l24hzknyqbn3a9b","data":{}},"body":"git remote set-url origin <new-url>\n\n
\n\nSolution. Make sure you are writing your tests wrapped in classes that inherit from TestCase
. Example:
from django.test import TestCase\n\n\nclass FooTest(TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_this_will(self):\n print 'Win'\n
\n\nConsultar la base de datos Eleventa.
\nPrimero instalamos el paquete sqlparse
. Desde pypy
:
pip install sqlparse\n
\nSi utlizamos poetry
:
poetry add sqlparse\n
\nUna vez instalado, en una sesión de python
lo podemos importar de la manera usual
from typing import Optional\nfrom sqlparse.sql import Statement\nfrom sqlparse.tokens import Keyword\nfrom dataclasses import dataclass\nimport sqlparse\n
\nVamos a utilizar el siguiente ejemplo de SQL
para aprender a extraer la información que necesitamos
TABLE = \"\"\"CREATE TABLE IF NOT EXISTS MY_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n\"\"\"\n
\nparsed = sqlparse.parse(TABLE) # Devuelve una tupla de statements sql contenidos en la cadena\nstatement = parsed[0]\n
\nprint(statement)\n
\nCREATE TABLE IF NOT EXISTS MY_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n
\nstatement
es una variable tipo Statement
que puede ser iterada por medio de índices o ciclos.
token = statement[0]\nprint(type(statement), type(token))\n
\n<class 'sqlparse.sql.Statement'> <class 'sqlparse.sql.Token'>\n
\nCada token define dos atributos: value
y ttype
, sin embargo el parser es flojo, al invocarlo evitará escanear recursivamente la cadena como se puede ver en los siguientes ejemplos.
# En este caso, el primer token tiene un valor definido y un tipo.\ntoken.value, token.ttype\n
\n('CREATE', Token.Keyword.DDL)\n
\n# En este ciclo se puede ver que los tokens 11 y 13 no fueron analizados por el parser.\nfor i, token in enumerate(statement):\n token_type = repr(token.ttype)\n print(f\"{i+1:2d}. {token.value:50} {token_type:50} {type(token)}\")\n\n
\n 1. CREATE Token.Keyword.DDL <class 'sqlparse.sql.Token'>\n 2. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 3. TABLE Token.Keyword <class 'sqlparse.sql.Token'>\n 4. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 5. IF Token.Keyword <class 'sqlparse.sql.Token'>\n 6. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 7. NOT Token.Keyword <class 'sqlparse.sql.Token'>\n 8. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 9. EXISTS Token.Keyword <class 'sqlparse.sql.Token'>\n10. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n11. MY_TABLE None <class 'sqlparse.sql.Identifier'>\n12. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n13. (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID)) None <class 'sqlparse.sql.Parenthesis'>\n14. ; Token.Punctuation <class 'sqlparse.sql.Token'>\n
\nEl método Statement.flatten
realizará el parseo de la cadena completa, devolviendo los tipos y valores de cada token encontrado.
for i, token in enumerate(statement.flatten()):\n token_type = repr(token.ttype)\n print(f\"{i+1:2d}. {token.value:50} {token_type:50} {type(token)}\")\n
\n 1. CREATE Token.Keyword.DDL <class 'sqlparse.sql.Token'>\n 2. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 3. TABLE Token.Keyword <class 'sqlparse.sql.Token'>\n 4. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 5. IF Token.Keyword <class 'sqlparse.sql.Token'>\n 6. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 7. NOT Token.Keyword <class 'sqlparse.sql.Token'>\n 8. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n 9. EXISTS Token.Keyword <class 'sqlparse.sql.Token'>\n10. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n11. MY_TABLE Token.Name <class 'sqlparse.sql.Token'>\n12. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n13. ( Token.Punctuation <class 'sqlparse.sql.Token'>\n14. ID Token.Name <class 'sqlparse.sql.Token'>\n15. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n16. TLLAVE Token.Name <class 'sqlparse.sql.Token'>\n17. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n18. NOT NULL Token.Keyword <class 'sqlparse.sql.Token'>\n19. , Token.Punctuation <class 'sqlparse.sql.Token'>\n20. \n Token.Text.Whitespace.Newline <class 'sqlparse.sql.Token'>\n21. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n22. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n23. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n24. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n25. CONSTRAINT Token.Keyword <class 'sqlparse.sql.Token'>\n26. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n27. PK_MY_TABLE Token.Name <class 'sqlparse.sql.Token'>\n28. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n29. PRIMARY Token.Keyword <class 'sqlparse.sql.Token'>\n30. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n31. KEY Token.Keyword <class 'sqlparse.sql.Token'>\n32. Token.Text.Whitespace <class 'sqlparse.sql.Token'>\n33. ( Token.Punctuation <class 'sqlparse.sql.Token'>\n34. ID Token.Name <class 'sqlparse.sql.Token'>\n35. ) Token.Punctuation <class 'sqlparse.sql.Token'>\n36. ) Token.Punctuation <class 'sqlparse.sql.Token'>\n37. ; Token.Punctuation <class 'sqlparse.sql.Token'>\n
\nLas tablas que nos interesa analizar todas tienen siempre la siguiente estructura
\nCREATE TABLE [IF NOT EXISTS] my_table_name ...\n
\npor lo que para encontrar el nombre de la tabla necesitamos encontrar el primer token de tipo Identifier
que encontnró el parser y extraer su valor, como se ve en el siguiente ejemplo:
for token in statement:\n if isinstance(token, sqlparse.sql.Identifier):\n print(token.get_name().upper())\n break\n
\nMY_TABLE\n
\nEl volcado SQL puede tener una mezcla de definiciones de estructuras de datos y otros tipos de código SQL, por ejemplo un query de búsqueda
\nCREATE TABLE IF NOT EXISTS MY_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n\nSELECT * FROM ANOTHER_TABLE;\n\nCREATE TABLE IF NOT EXISTS MY_OTHER_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n
\nlo que hacemos es utilizar sqlparse
para encontrar cada statement y determiar si es de tipo CREATE
de modo que para statements de este tipo aplicamos el algoritmo de la sección anterior para encontrar el nombre de la tabla.
SQLDUMP = \"\"\"CREATE TABLE IF NOT EXISTS MY_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n\nSELECT * FROM ANOTHER_TABLE;\n\nCREATE TABLE IF NOT EXISTS MY_OTHER_TABLE (ID TLLAVE NOT NULL,\n CONSTRAINT PK_MY_TABLE PRIMARY KEY (ID));\n\"\"\"\n\nparsed = sqlparse.parse(SQLDUMP)\nfor i, statement in enumerate(parsed):\n print(f\"{i}. {statement.get_type()}\")\n
\n0. CREATE\n1. SELECT\n2. CREATE\n
\ndef get_name(statement: Statement) -> Optional[str]:\n for token in statement:\n if isinstance(token, sqlparse.sql.Identifier):\n return token.value\n return None \n
\nfor i, statement in enumerate(parsed):\n statement_type = statement.get_type()\n if statement_type == \"CREATE\":\n name = get_name(statement)\n print(f\"{i}. {statement_type}: {name}\")\n
\n0. CREATE: MY_TABLE\n2. CREATE: MY_OTHER_TABLE\n
\nEn un caso más general, podemos tener volcados sql con varios tipos de objetos, por ejemplo
\nCREATE TABLE MY_TABLE (ID INTEGER NOT NULL);\n\nCREATE INDEX MY_INDEX ON MY_TABLE(ID);\n
\nanalizando los tokens de cada statement es posible determinar el tipo de objeto.
\nSQL = \"\"\"CREATE TABLE MY_TABLE (ID INTEGER NOT NULL);\n\nSELECT * FROM MY_OTHER_TABLE;\n\nCREATE INDEX MY_INDEX ON MY_TABLE(ID);\n\"\"\"\n\nparsed = sqlparse.parse(SQL)\nstatement = parsed[0]\n\n\n
\ntype_found = False \nname_found = False \nfor token in statement:\n if type_found and name_found:\n break\n elif token.ttype is Keyword and not type_found:\n type_found = True \n token_type = token.value\n elif isinstance(token, sqlparse.sql.Identifier) and not name_found:\n name_found = True \n token_name = token.value\nprint (f\"tipo: {token_type}, nombre: {token_name}\")\n
\ntipo: TABLE, nombre: MY_TABLE\n
\nEn el código anterior asumimos que todas las cláusulas son simples, es decir del estilo \"CREATE ....\", si estuvieran agrupadas, por ejemplo \"(CREATE ....)\" el algoritmo ya no es tan simple, pues debe de realizar el escaneo de manera recursiva, un ejemplo de este tipo de algoritmo se encuentra en el repositorio de sqlparse
:
https://github.com/andialbrecht/sqlparse/blob/master/examples/extract_table_names.py
\nSQL = \"\"\"CREATE TABLE MY_TABLE (ID INTEGER NOT NULL);\n\nSELECT * FROM MY_OTHER_TABLE;\n\nCREATE INDEX MY_INDEX ON MY_TABLE(ID);\n\"\"\"\n\n@dataclass\nclass Metadata:\n type: str\n name: str \n \ndef get_metadata(statement: Statement) -> Metadata:\n type_found = False \n name_found = False \n object_name = None \n object_type = None \n for token in statement:\n if type_found and name_found:\n break\n elif token.ttype is Keyword and not type_found:\n type_found = True \n object_type = token.value\n elif isinstance(token, sqlparse.sql.Identifier) and not name_found:\n name_found = True \n object_name = token.value\n return Metadata(name=object_name, type=object_type)\n\n\nparsed = sqlparse.parse(SQL)\n\nfor i, statement in enumerate(parsed):\n name_found = False \n if statement.get_type() != \"CREATE\":\n continue\n metadata = get_metadata(statement)\n print(i, metadata)\n
\n0 Metadata(type='TABLE', name='MY_TABLE')\n2 Metadata(type='INDEX', name='MY_INDEX')\n
\nSimple program that reads an url and prints the last part of the path as a title.
\n\nfrom urllib.parse import urlparse\n\ndef get_last_path(url:str) -> str:\n # Parse the URL\n parsed_url = urlparse(url)\n\n # Get the path from the parsed URL\n path = parsed_url.path\n\n # Split the path by slashes and get the last part\n path_parts = path.split('/')\n last_part = path_parts[-1]\n\n return last_part\n\ndef path_to_title(path:str) -> str:\n return path.replace(\"-\", \" \").title()\n\ndef main():\n url = input(\"Enter the URL: \")\n path = get_last_path(url)\n title = path_to_title(path)\n print(title)\n\nif __name__ == \"__main__\":\n while True:\n try:\n main()\n except KeyboardInterrupt:\n break\n
\nI use this to format references in my mardown documents. For example, given the url
\nhttps://stackoverflow.com/questions/76392847/flutter-firebase-to-python-firebase\n
\nThe program outputs
\nFlutter Firebas To Python Firebase\n
\nwhich I use to link to the question, like so:
\n[Flutter Firebas To Python Firebase](https://stackoverflow.com/questions/76392847/flutter-firebase-to-python-firebase)\n
\nTo use argparse
in Python for creating a program that asks for a filename and an output directory, you can follow these steps:
argparse
module:import argparse\n
\nargparse.ArgumentParser
class:parser = argparse.ArgumentParser(description='Process input file and output directory.')\n
\nparser.add_argument('filename', help='Input file name')\nparser.add_argument('output_dir', help='Output directory')\n
\nargs = parser.parse_args()\n
\nfilename = args.filename\noutput_dir = args.output_dir\n
\nHere's a complete example that puts it all together:
\nimport argparse\n\ndef main():\n # Step 2: Create an ArgumentParser instance\n parser = argparse.ArgumentParser(description='Process input file and output directory.')\n \n # Step 3: Define command-line arguments\n parser.add_argument('filename', help='Input file name')\n parser.add_argument('output_dir', help='Output directory')\n \n # Step 4: Parse the command-line arguments\n args = parser.parse_args()\n \n # Step 5: Access the values of the arguments\n filename = args.filename\n output_dir = args.output_dir\n \n # Step 6: Use the obtained values\n print(\"Input file:\", filename)\n print(\"Output directory:\", output_dir)\n\nif __name__ == '__main__':\n main()\n
\nTo run this program from the command line, you would provide the filename and output directory as arguments. For example:
\n$ python your_program.py input_file.txt /path/to/output/\n
\nMake sure to replace \"your_program.py\" with the actual filename of your Python script, \"input_file.txt\" with the desired filename, and \"/path/to/output/\" with the desired output directory.
\nRespueta generada automáticamente por ChatGPT4
","noteIndex":{"id":"root","title":"Inicio","desc":"","updated":1685946892733,"created":1595961348801,"custom":{"nav_order":0,"permalink":"/"},"fname":"root","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"e61b300237deb393ece8248ab604975d","links":[{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"code","position":{"start":{"line":3,"column":3,"offset":4},"end":{"line":3,"column":11,"offset":12},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"code"}},{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"math","position":{"start":{"line":4,"column":3,"offset":15},"end":{"line":4,"column":11,"offset":23},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"math"}}],"anchors":{},"children":["631hw9oh0k8jhc0wlm0joyz","rzreoc67l24hzknyqbn3a9b"],"parent":null,"data":{},"body":"\n\n* [[code]]\n* [[math]]"},"collectionChildren":null,"customHeadContent":null,"config":{"version":5,"dev":{"enablePreviewV2":true,"enableSelfContainedVaults":true},"commands":{"lookup":{"note":{"selectionMode":"extract","confirmVaultOnCreate":true,"vaultSelectionModeOnCreate":"smart","leaveTrace":false,"bubbleUpCreateNew":true,"fuzzThreshold":0.2}},"randomNote":{},"insertNoteLink":{"aliasMode":"none","enableMultiSelect":false},"insertNoteIndex":{"enableMarker":false},"copyNoteLink":{"aliasMode":"title"},"templateHierarchy":"template"},"workspace":{"vaults":[{"fsPath":"dependencies/github.com/renegarcia/eleventa-db","remote":{"type":"git","url":"git@github.com:renegarcia/eleventa-db.git"},"selfContained":true,"name":"eleventa-db"},{"fsPath":".","selfContained":true,"name":"Dendron"}],"journal":{"dailyDomain":"daily","name":"journal","dateFormat":"y.MM.dd","addBehavior":"childOfDomain"},"scratch":{"name":"scratch","dateFormat":"y.MM.dd.HHmmss","addBehavior":"asOwnDomain"},"task":{"name":"task","dateFormat":"y.MM.dd","addBehavior":"asOwnDomain","statusSymbols":{"":" ","wip":"w","done":"x","assigned":"a","moved":"m","blocked":"b","delegated":"l","dropped":"d","pending":"y"},"taskCompleteStatus":["done","x"],"prioritySymbols":{"H":"high","M":"medium","L":"low"},"todoIntegration":false,"createTaskSelectionType":"selection2link"},"graph":{"zoomSpeed":1,"createStub":false},"enableAutoCreateOnDefinition":false,"enableXVaultWikiLink":false,"enableRemoteVaultInit":true,"enableUserTags":true,"enableHashTags":true,"workspaceVaultSyncMode":"noCommit","enableAutoFoldFrontmatter":false,"enableEditorDecorations":true,"maxPreviewsCached":10,"maxNoteLength":204800,"enableFullHierarchyNoteTitle":false},"preview":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enablePrettyRefs":true,"enableKatex":true,"automaticallyShowPreview":false},"publishing":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enablePrettyRefs":true,"enableKatex":true,"copyAssets":true,"siteHierarchies":["root"],"writeStubs":false,"siteRootDir":"docs","seo":{"title":"Notes","description":"Personal Knowledge Space or Rene Garcia"},"github":{"enableEditLink":true,"editLinkText":"Edit this page on GitHub","editBranch":"main","editViewMode":"tree"},"enableSiteLastModified":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enableRandomlyColoredTags":true,"enableTaskNotes":true,"enablePrettyLinks":true,"searchMode":"search","enableHierarchyDisplay":true,"hierarchyDisplayTitle":"Children","duplicateNoteBehavior":{"action":"useVault","payload":["eleventa-db","Dendron"]},"siteUrl":"https://renegarcia.github.io","assetsPrefix":"/dendron","siteFaviconPath":"favicon.ico","siteIndex":"root"}}},"__N_SSG":true} \ No newline at end of file diff --git a/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/hwyvw05ski3srgkxy31ym7w.json b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/hwyvw05ski3srgkxy31ym7w.json new file mode 100644 index 0000000..dd3bb1e --- /dev/null +++ b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/hwyvw05ski3srgkxy31ym7w.json @@ -0,0 +1 @@ +{"pageProps":{"note":{"id":"hwyvw05ski3srgkxy31ym7w","title":"Python","desc":"","updated":1685476629841,"created":1685474715630,"custom":{},"fname":"code.python","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"588d5c5ace35f706fa1a0dddcafefdb8","links":[{"from":{"fname":"code","id":"631hw9oh0k8jhc0wlm0joyz","vaultName":"Dendron"},"type":"backlink","position":{"start":{"line":37,"column":1,"offset":597},"end":{"line":37,"column":16,"offset":612},"indent":[]},"value":"code.python"}],"anchors":{},"children":["gznvznjzcsize57jmnzk130","l0u48190oqzxwanw96fjofu","qpru2s8dnotjix9okh0haqe","xerksxa0wc8wxg4wymgrp0i","6zw1kq25fhhqug5i45y1srj","z2m9aey7liflnpmzo3gh61z","g4q8yp5c8b2h1nlehk01cxt"],"parent":"631hw9oh0k8jhc0wlm0joyz","data":{}},"body":"Difference between exec, system and backticks?
","noteIndex":{"id":"root","title":"Inicio","desc":"","updated":1685946892733,"created":1595961348801,"custom":{"nav_order":0,"permalink":"/"},"fname":"root","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"e61b300237deb393ece8248ab604975d","links":[{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"code","position":{"start":{"line":3,"column":3,"offset":4},"end":{"line":3,"column":11,"offset":12},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"code"}},{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"math","position":{"start":{"line":4,"column":3,"offset":15},"end":{"line":4,"column":11,"offset":23},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"math"}}],"anchors":{},"children":["631hw9oh0k8jhc0wlm0joyz","rzreoc67l24hzknyqbn3a9b"],"parent":null,"data":{},"body":"\n\n* [[code]]\n* [[math]]"},"collectionChildren":null,"customHeadContent":null,"config":{"version":5,"dev":{"enablePreviewV2":true,"enableSelfContainedVaults":true},"commands":{"lookup":{"note":{"selectionMode":"extract","confirmVaultOnCreate":true,"vaultSelectionModeOnCreate":"smart","leaveTrace":false,"bubbleUpCreateNew":true,"fuzzThreshold":0.2}},"randomNote":{},"insertNoteLink":{"aliasMode":"none","enableMultiSelect":false},"insertNoteIndex":{"enableMarker":false},"copyNoteLink":{"aliasMode":"title"},"templateHierarchy":"template"},"workspace":{"vaults":[{"fsPath":"dependencies/github.com/renegarcia/eleventa-db","remote":{"type":"git","url":"git@github.com:renegarcia/eleventa-db.git"},"selfContained":true,"name":"eleventa-db"},{"fsPath":".","selfContained":true,"name":"Dendron"}],"journal":{"dailyDomain":"daily","name":"journal","dateFormat":"y.MM.dd","addBehavior":"childOfDomain"},"scratch":{"name":"scratch","dateFormat":"y.MM.dd.HHmmss","addBehavior":"asOwnDomain"},"task":{"name":"task","dateFormat":"y.MM.dd","addBehavior":"asOwnDomain","statusSymbols":{"":" ","wip":"w","done":"x","assigned":"a","moved":"m","blocked":"b","delegated":"l","dropped":"d","pending":"y"},"taskCompleteStatus":["done","x"],"prioritySymbols":{"H":"high","M":"medium","L":"low"},"todoIntegration":false,"createTaskSelectionType":"selection2link"},"graph":{"zoomSpeed":1,"createStub":false},"enableAutoCreateOnDefinition":false,"enableXVaultWikiLink":false,"enableRemoteVaultInit":true,"enableUserTags":true,"enableHashTags":true,"workspaceVaultSyncMode":"noCommit","enableAutoFoldFrontmatter":false,"enableEditorDecorations":true,"maxPreviewsCached":10,"maxNoteLength":204800,"enableFullHierarchyNoteTitle":false},"preview":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enablePrettyRefs":true,"enableKatex":true,"automaticallyShowPreview":false},"publishing":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enablePrettyRefs":true,"enableKatex":true,"copyAssets":true,"siteHierarchies":["root"],"writeStubs":false,"siteRootDir":"docs","seo":{"title":"Notes","description":"Personal Knowledge Space or Rene Garcia"},"github":{"enableEditLink":true,"editLinkText":"Edit this page on GitHub","editBranch":"main","editViewMode":"tree"},"enableSiteLastModified":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enableRandomlyColoredTags":true,"enableTaskNotes":true,"enablePrettyLinks":true,"searchMode":"search","enableHierarchyDisplay":true,"hierarchyDisplayTitle":"Children","duplicateNoteBehavior":{"action":"useVault","payload":["eleventa-db","Dendron"]},"siteUrl":"https://renegarcia.github.io","assetsPrefix":"/dendron","siteFaviconPath":"favicon.ico","siteIndex":"root"}}},"__N_SSG":true} \ No newline at end of file diff --git a/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/l0u48190oqzxwanw96fjofu.json b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/l0u48190oqzxwanw96fjofu.json new file mode 100644 index 0000000..bc765ae --- /dev/null +++ b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/l0u48190oqzxwanw96fjofu.json @@ -0,0 +1 @@ +{"pageProps":{"note":{"id":"l0u48190oqzxwanw96fjofu","title":"Password generator","desc":"Como generar passwords","updated":1685387560892,"created":1685385500530,"custom":{},"fname":"code.python.password_generator","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"0de1e1a5b291543cce42965405a65fd4","links":[],"anchors":{"resultado":{"type":"header","text":"Resultado","value":"resultado","line":8,"column":0,"depth":3},"detalles":{"type":"header","text":"Detalles","value":"detalles","line":13,"column":0,"depth":3},"referencias":{"type":"header","text":"Referencias","value":"referencias","line":35,"column":0,"depth":3}},"children":[],"parent":"hwyvw05ski3srgkxy31ym7w","data":{}},"body":"Necesitamos utilizar los paquetes string
y secrets
.
from secrets import choice\nimport string\n
\nA continuación definimos el alfabeto y la función generadora.
\nALPHABET = string.ascii_letters + string.digits + string.punctuation\n\ndef password_generator(len:int =10, alphabet: list[str] = ALPHABET) -> str:\n return \"\".join(choice(alphabet) for i in range(len))\n
\nHow To Use Black Flake8 And Isort To Format Python Codes
","noteIndex":{"id":"root","title":"Inicio","desc":"","updated":1685946892733,"created":1595961348801,"custom":{"nav_order":0,"permalink":"/"},"fname":"root","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"e61b300237deb393ece8248ab604975d","links":[{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"code","position":{"start":{"line":3,"column":3,"offset":4},"end":{"line":3,"column":11,"offset":12},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"code"}},{"type":"wiki","from":{"fname":"root","id":"root","vaultName":"Dendron"},"value":"math","position":{"start":{"line":4,"column":3,"offset":15},"end":{"line":4,"column":11,"offset":23},"indent":[]},"xvault":false,"sameFile":false,"to":{"fname":"math"}}],"anchors":{},"children":["631hw9oh0k8jhc0wlm0joyz","rzreoc67l24hzknyqbn3a9b"],"parent":null,"data":{},"body":"\n\n* [[code]]\n* [[math]]"},"collectionChildren":null,"customHeadContent":null,"config":{"version":5,"dev":{"enablePreviewV2":true,"enableSelfContainedVaults":true},"commands":{"lookup":{"note":{"selectionMode":"extract","confirmVaultOnCreate":true,"vaultSelectionModeOnCreate":"smart","leaveTrace":false,"bubbleUpCreateNew":true,"fuzzThreshold":0.2}},"randomNote":{},"insertNoteLink":{"aliasMode":"none","enableMultiSelect":false},"insertNoteIndex":{"enableMarker":false},"copyNoteLink":{"aliasMode":"title"},"templateHierarchy":"template"},"workspace":{"vaults":[{"fsPath":"dependencies/github.com/renegarcia/eleventa-db","remote":{"type":"git","url":"git@github.com:renegarcia/eleventa-db.git"},"selfContained":true,"name":"eleventa-db"},{"fsPath":".","selfContained":true,"name":"Dendron"}],"journal":{"dailyDomain":"daily","name":"journal","dateFormat":"y.MM.dd","addBehavior":"childOfDomain"},"scratch":{"name":"scratch","dateFormat":"y.MM.dd.HHmmss","addBehavior":"asOwnDomain"},"task":{"name":"task","dateFormat":"y.MM.dd","addBehavior":"asOwnDomain","statusSymbols":{"":" ","wip":"w","done":"x","assigned":"a","moved":"m","blocked":"b","delegated":"l","dropped":"d","pending":"y"},"taskCompleteStatus":["done","x"],"prioritySymbols":{"H":"high","M":"medium","L":"low"},"todoIntegration":false,"createTaskSelectionType":"selection2link"},"graph":{"zoomSpeed":1,"createStub":false},"enableAutoCreateOnDefinition":false,"enableXVaultWikiLink":false,"enableRemoteVaultInit":true,"enableUserTags":true,"enableHashTags":true,"workspaceVaultSyncMode":"noCommit","enableAutoFoldFrontmatter":false,"enableEditorDecorations":true,"maxPreviewsCached":10,"maxNoteLength":204800,"enableFullHierarchyNoteTitle":false},"preview":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enablePrettyRefs":true,"enableKatex":true,"automaticallyShowPreview":false},"publishing":{"enableFMTitle":true,"enableNoteTitleForLink":true,"enablePrettyRefs":true,"enableKatex":true,"copyAssets":true,"siteHierarchies":["root"],"writeStubs":false,"siteRootDir":"docs","seo":{"title":"Notes","description":"Personal Knowledge Space or Rene Garcia"},"github":{"enableEditLink":true,"editLinkText":"Edit this page on GitHub","editBranch":"main","editViewMode":"tree"},"enableSiteLastModified":true,"enableFrontmatterTags":true,"enableHashesForFMTags":false,"enableRandomlyColoredTags":true,"enableTaskNotes":true,"enablePrettyLinks":true,"searchMode":"search","enableHierarchyDisplay":true,"hierarchyDisplayTitle":"Children","duplicateNoteBehavior":{"action":"useVault","payload":["eleventa-db","Dendron"]},"siteUrl":"https://renegarcia.github.io","assetsPrefix":"/dendron","siteFaviconPath":"favicon.ico","siteIndex":"root"}}},"__N_SSG":true} \ No newline at end of file diff --git a/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/rzreoc67l24hzknyqbn3a9b.json b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/rzreoc67l24hzknyqbn3a9b.json new file mode 100644 index 0000000..2ffd0d7 --- /dev/null +++ b/_next/data/X7YNYBEDa6SjIJUoyfWrn/notes/rzreoc67l24hzknyqbn3a9b.json @@ -0,0 +1 @@ +{"pageProps":{"note":{"id":"rzreoc67l24hzknyqbn3a9b","title":"Math","desc":"","updated":1685946339687,"created":1685946339687,"custom":{},"fname":"math","type":"note","vault":{"fsPath":".","selfContained":true,"name":"Dendron"},"contentHash":"c5ac822c67cde92807607d8ee7def615","links":[{"from":{"fname":"root","id":"root","vaultName":"Dendron"},"type":"backlink","position":{"start":{"line":4,"column":3,"offset":15},"end":{"line":4,"column":11,"offset":23},"indent":[]},"value":"math"}],"anchors":{},"children":["4k7eb68p8o3ctljv6pl0g3q"],"parent":"root","data":{}},"body":"If you use poetry, assuming your project is organized as in this example
\n[tool.poetry]\nname = \"packagename\"\nversion = \"0.1.0\"\ndescription = \"\"\nauthors = [\"finswimmer <finswimmer@example.org>\"]\n\n[tool.poetry.scripts]\ncli-script = \"packagename.cli:main\"\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^5.2\"\n\n[build-system]\nrequires = [\"poetry>=1.0\"]\nbuild-backend = \"poetry.masonry.api\"\n
\nSimply call
\npoetry install --only-root\n
\nWhere your project should be organized as
\npackagename\n├── packagename\n│ ├── __init__.py\n│ └── cli.py\n├── tests\n│ ├── __init__.py\n│ └── test_packagename.py\n└── pyproject.toml\n
\nAnd the content of the script should resemble this:
\n#!/usr/bin/env python\n\ndef main():\n print(\"Hello world\")\n\nif __name__ == '__main__':\n main()\n
\nIf your project is simple, for example like this,
\nyourprojectdir/\n setup.py\n scripts/\n myscript.sh\n
\nyou may only need to create or append to your setup.py
the following:
from setuptools import setup\n# you may need setuptools instead of distutils\n\nsetup(\n scripts = [\n 'scripts/myscript.sh'\n ]\n)\n
\nThen in the shell type
\npython setup.py install\n
\nSource: https://stackoverflow.com/questions/874521/python-install-script-to-system
\nHow To Organize A Python Project With Poetry For A Command Line Script.
\nOften a string with special characters like \"this \\\"string\\\"\"
shall be used as input of another program\nwith all the special characters removed. A case of use could be for example if the input string is to be used as\na filename in another program.
We create a translation table that maps any punctuation symbol into None
. Punctuation symbols in python are defined in the module string
.
import string\n\ndef remove_special_characters(input_string):\n # Create a translation table mapping special characters to None\n translation_table = str.maketrans(\"\", \"\", string.punctuation)\n\n # Remove special characters using the translation table\n cleaned_string = input_string.translate(translation_table)\n\n return cleaned_string\n\n# Example usage\ninput_string = 'Hello! \"How are you?\"'\ncleaned_string = remove_special_characters(input_string)\nprint(cleaned_string)\n
\nLet (Ω,B,P) be a measure space, with Borel σ-algebra B, and probability measure P.
\nDefinition A stochastic process is a parametrized collection of random variables:
\n{Xt∣t≥0},
\nsuch that each Xt is a random variable in the measure space.
\nLet {wt∣t≥0} be a stochastic process such that wt is continous in the weak sense with respect to t. wt is a Wiener process if:
\nNote: In general, wt is not differentiable in any point.
\nLet f(t,xt)=f(t), with xt an stochastic process, such that
\n∫abE(f(t))dt<∞.
\nWe will say that f(t) is a random function. Let\n{a=t1<⋯<tn+1=b}\nbe a partition of [a,b], with equally spaced points, and let Δt=(b−a)/n and Δwi=wti+1−wti. Then, Ito's integral is
\n∫abf(t)dwt=lim∑i=1nf(ti)Δwi.
\nlimn→∞E((sn−I)2)=0.
\nDefinition: xt is a solution of the stochastic differential equation,
\ndxt=α(xt,t)dt+β(xt,t)dwt,
\nif for any t>0, xt satisfies
\nxt=x0+∫0tα(xt,t)dt+∫0tβ(xt,t)dwt.
\nQ. Under which conditions can it be proved that the solution to this equation is unique?.
\nTeorem (chain rule) If xt is the solution of a stochastic differential equation, and F(x,t) is a real function such that the partial derivatives\n∂tF,∂xF,∂xxF\nare continous functions, then
\ndF(xt,t)=f(xt,t)dt+g(xt,t)dwt,
\nwhere
\nf(x,t)=∂tF+α(xt,t)∂xF+21β2(xt,t)∂xxF
\nand
\ng(xt,t)=β(xt,t)∂xF.
\nTheorem The solution to the stochastic differential equation\ndxt=rxtdt+cxtdwt\nis
\nxt=x0exp((r−c2/2)t+c⋅wt).
\nProof Let F=ln(x), by the chain rule:
\ndln(xt)=(rxt⋅xt1+21c2xt2(−xt21))dt+cxt⋅xt1dwt,
\nSimplifying the equation, we get
\ndln(xt)=(r−2c2)dt+c⋅dwt.
\nIt can be shown that the fundamental theorem of calculus is valid for the stochastic integral of a constant function, therefore, applying this result to the previous equation, we find,
\nln(x0xt)=(r−2c2)t+c⋅wt,
\nand the theorem follows.
\ndxi=Δxi,dwi=Δwi,
\nxi+1=xi+α(xi,ti)Δt+β(xi,ti)Δwi.
\nNote that in order to implement this method we should select Δwi randomly with distribution N(0,Δt).
\nModify the last equation into
\nxi+1=xi+α(xi,ti)Δt+β(xi,ti)Δwi+21β(xi,ti)∂x∂β(xi,ti)((Δwi)2−Δt).
\nThis last method resembles predictor-corrector methods in ordinary differential equations.
\nOriginally published by the author in http://ixxra.github.io/mathannotations/sdes/2014/05/21/stochastic-differential-equations/
\n{let{isMatch:h,score:m,indices:v}=B(e,t,r,{location:i+p,distance:o,threshold:a,findAllMatches:s,minMatchCharLength:u,includeMatches:n,ignoreLocation:c});h&&(d=!0),f+=m,h&&v&&(l=[...l,...v])});let p={isMatch:d,score:d?f/this.chunks.length:1};return d&&n&&(p.indices=l),p}}class V{constructor(e){this.pattern=e}static isMultiMatch(e){return z(e,this.multiRegex)}static isSingleMatch(e){return z(e,this.singleRegex)}search(){}}function z(e,t){let n=e.match(t);return n?n[1]:null}class H extends V{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){let t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}}class W extends V{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){let t=e.indexOf(this.pattern),n=-1===t;return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}}class $ extends V{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){let t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}}class G extends V{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){let t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}}class q extends V{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){let t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}}class K extends V{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){let t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}}class Y extends V{constructor(e,{location:t=T.location,threshold:n=T.threshold,distance:r=T.distance,includeMatches:i=T.includeMatches,findAllMatches:o=T.findAllMatches,minMatchCharLength:a=T.minMatchCharLength,isCaseSensitive:s=T.isCaseSensitive,ignoreLocation:u=T.ignoreLocation}={}){super(e),this._bitapSearch=new Z(e,{location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:o,minMatchCharLength:a,isCaseSensitive:s,ignoreLocation:u})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class X extends V{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t=0,n,r=[],i=this.pattern.length;for(;(n=e.indexOf(this.pattern,t))>-1;)t=n+i,r.push([n,t-1]);let o=!!r.length;return{isMatch:o,score:o?0:1,indices:r}}}let J=[H,X,$,G,K,q,W,Y],Q=J.length,ee=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,et="|";function en(e,t={}){return e.split(et).map(e=>{let n=e.trim().split(ee).filter(e=>e&&!!e.trim()),r=[];for(let i=0,o=n.length;i>1,l=-7,f=n?i-1:0,d=n?-1:1,p=e[t+f];for(f+=d,o=p&(1<<-l)-1,p>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=d,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=r;l>0;a=256*a+e[t+f],f+=d,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:(p?-1:1)*(1/0);a+=Math.pow(2,r),o-=c}return(p?-1:1)*a*Math.pow(2,o-r)},t.write=function(e,t,n,r,i,o){var a,s,u,c=8*o-i-1,l=(1<