Wednesday, August 30, 2023

Python aiosqlite - async SQLITE

Install the aiosqlite package: aiosqlite is an async version of sqlite3 that works with Python's asyncio library. You can install it using pip:

 Import the necessary libraries: You need to import aiosqlite and asyncio for this task.

Create an async function to execute your query: This function will connect to a SQLite database, execute a query, and return the results. It uses the aiosqlite.connect() method to establish a connection to the database and the execute() method to run the SQL query.

Create tasks for each database: For each database you want to search, create a task using asyncio.create_task(). Each of these tasks will run the query_db function concurrently.

Execute the tasks: Use asyncio.gather() to run all the tasks concurrently and wait for all of them to finish. The results will be returned as a list of lists, with each sublist containing the results from one database.

Iterate through the results: You can now iterate through the results to process the data from each database.

import asyncio
import aiosqlite

async def query_db(database, query):
    async with aiosqlite.connect(database) as db:
        async with db.execute(query) as cursor:
            return await cursor.fetchall()

async def main():
    databases = ["database1.db", "database2.db", "database3.db"]
    query = "SELECT * FROM some_table"
    tasks = [asyncio.create_task(query_db(database, query)) for database in databases]

    results = await asyncio.gather(*tasks)

    for db_results in results:
        for row in db_results:
            # Process row
            pass

asyncio.run(main())

 

# This code will initiate connections to each of the specified databases concurrently and execute the same query on each. The results from each database are collected into a list of lists, which can then be processed as needed.Note: It's important to remember that although asyncio allows for concurrent execution of tasks, SQLite databases are stored on disk and therefore I/O bound. The actual speedup from using asyncio will depend on the speed of your disk and how large the databases are

Tuesday, August 29, 2023

JavaScript Learning in Progress

When JavaScript variables are declared, they have an initial value of undefined. If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a string of undefined.

MYVAR is not the same as MyVar nor myvar. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you do not use this language feature. Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.

Unlike var, when you use let, a variable with the same name can only be declared once.

const has all the awesome features that let has, with the added bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned. Note: It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).

You can easily increment or add one to a variable with the ++ operator. You can easily decrement or decrease a variable by one with the -- operator.

Decimal numbers are sometimes referred to as floating point numbers or floats. Note: when you compute numbers, they are computed with finite precision. Operations using floating points may lead to different results than the desired outcome.

The remainder operator % gives the remainder of the division of two numbers. In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2. Even numbers have a remainder of 0, while odd numbers a remainder of 1. Note: The remainder operator is sometimes incorrectly referred to as the modulus operator. It is very similar to modulus, but does not work properly with negative numbers.

In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash (\) in front of the quote. This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string.

Note that the backslash itself must be escaped in order to display as a backslash.

CodeOutput
\'single quote
\"double quote
\\backslash
\nnewline
\ttab
\rcarriage return
\bbackspace
\fform feed

Carriage return means to return to the beginning of the current line without advancing downward. The name comes from a printer's carriage, as monitors were rare when the name was coined. This is commonly escaped as "\r", abbreviated CR, and has ASCII value 13 or 0xD.

Linefeed means to advance downward to the next line; however, it has been repurposed and renamed. Used as "newline", it terminates lines (commonly confused with separating lines). This is commonly escaped as "\n", abbreviated LF or NL, and has ASCII value 10 or 0xA. CRLF (but not CRNL) is used for the pair "\r\n".

Form feed means advance downward to the next "page". It was commonly used as page separators, but now is also used as section separators. Text editors can use this character when you "insert a page break". This is commonly escaped as "\f", abbreviated FF, and has ASCII value 12 or 0xC.

\r is carriage return and moves the cursor back

printf("stackoverflow\rnine")
ninekoverflow

means it has shifted the cursor to the beginning of "stackoverflow" and overwrites the starting four characters since "nine" is four character long.

\n is new line character which changes the line and takes the cursor to the beginning of a new line like-

printf("stackoverflow\nnine")
stackoverflow
nine

\f is form feed, its use has become obsolete but it is used for giving indentation like

printf("stackoverflow\fnine")
stackoverflow
             nine

if i will write like-

printf("stackoverflow\fnine\fgreat")
stackoverflow
             nine
                 great

We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines. Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.

You can find the length of a String value by writing .length after the string variable or string literal. Note that the space character between "Alan" and "Peter" is also counted.

Bracket notation is a way to get a character at a specific index within a string. Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as Zero-based indexing. In JavaScript, String values are immutable, which means that they cannot be altered once created.

 In order to get the last letter of a string, you can subtract one from the string's length.

const lastLetter = somestring[somestring.length - 1];

You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.

For example, you can get the value of the third-to-last letter of the const firstName = "Leon" string by using firstName[firstName.length - 3]

 You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry.

You can also nest arrays within other arrays:

const teams = [["Bulls", 23], ["White Sox", 45]];

This is also called a multi-dimensional array. One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of brackets refers to the entries in the outermost (the first level) array, and each additional pair of brackets refers to the next level of entries inside. Note: There shouldn't be any spaces between the array name and the square brackets.

Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.

Unlike strings, the entries of arrays are mutable and can be changed freely, even if the array was declared with const. 

An easy way to append data to the end of an array is via the push() function. .push() takes one or more parameters and "pushes" them onto the end of the array.

 .pop() is used to pop a value off of the end of an array. We can store this popped off value by assigning it to a variable. In other words, .pop() removes the last element from an array and returns that element.

pop() always removes the last element of an array.  .shift() removes the first element.

Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the array.

.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.

Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed") into a function when it is called are known as arguments.

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

Variables which are declared without the let or const keywords are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with let or const. Variables which are declared within a function, as well as the function parameters, have local scope. That means they are only visible within that function. It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.

A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.

let sum = 0;
function addSum(num) {
  sum = sum + num;
}
addSum(3);

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined.

 The most basic operator is the equality operator ==. The equality operator compares two values and returns true if they're equivalent or false if they are not. Note that equality is different from assignment (=), which assigns the value on the right of the operator to a variable on the left.

Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.

Examples

3 ===  3  // true
3 === '3' // false

If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.

Examples

3 == '3' returns true because JavaScript performs type conversion from string to number. 3 === '3' returns false because the types are different and type conversion is not performed.

Note: In JavaScript, you can determine the type of a variable or a value with the typeof operator, as follows:

typeof 3
typeof '3'

typeof 3 returns the string number, and typeof '3' returns the string string.

The inequality operator (!=) is the opposite of the equality operator. It means not equal and returns false where equality would return true and vice versa. Like the equality operator, the inequality operator will convert data types of values while comparing.

The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns false where strict equality would return true and vice versa. The strict inequality operator will not convert data types.

Like the equality operator, the greater than operator and the greater than or equal to operator will convert data types of values while comparing.

 Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.

The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.

The logical or operator is composed of two pipe symbols: (||). This can typically be found between your Backspace and Enter keys.

 When a condition for an if statement is true, the block of code following it is executed. When that condition is false, normally nothing would happen. With an else statement, an alternate block of code can be executed.

If you have multiple conditions that need to be addressed, you can chain if statements together with else if statements. if/else statements can be chained together for complex logic.

If you need to match one value against many options, you can use a switch statement. A switch statement compares the value to the case statements which define various possible values. Any valid JavaScript statements can be executed inside a case block and will run from the first matched case value until a break is encountered. case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If the break is omitted, the next statement will be executed.

In a switch statement you may not be able to specify all possible values as case statements. Instead, you can add the default statement which will be executed if no matching case statements are found. Think of it like the final else statement in an if/else chain.

If the break statement is omitted from a switch statement's case, the following case statement(s) are executed until a break is encountered. Switch cases use strict comparison (===).

 When a return statement is reached, the execution of the current function stops and control returns to the calling location.

 Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties.

In this example, all the properties are stored as strings, such as name, legs, and tails. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:

const anotherObject = {
  make: "Ford",
  5: "five",
  "model": "focus"
};

However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array. Dot notation is what you use when you know the name of the property you're trying to access ahead of time.

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation. However, you can still use bracket notation on object properties without spaces. Note that property names with spaces in them must be in quotes (single or double).

Add properties to object: ourDog.bark = 'woof'; Delete properties from objects: delete ourDog.bark;

 Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to lookup values rather than a switch statement or an if/else chain. This is most useful when you know that your input data is limited to a certain range.

 To check if a property on a given object exists or not, you can use the .hasOwnProperty() method. someObject.hasOwnProperty(someProperty) returns true or false depending on if the property is found on the object or not.

Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.

The sub-properties of objects can be accessed by chaining together the dot or bracket notation.

For loops are declared with three optional expressions separated by semicolons:

for (a; b; c), where a is the initialization statement, b is the condition statement, and c is the final expression.

The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.

The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing. This means if the condition starts as false, your loop will never execute.

The final expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.

It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true. What makes the do...while different from other loops is how it behaves when the condition fails on the first check. Essentially, a do...while loop ensures that the code inside the loop will run at least once. Let's try getting a do...while loop to work by pushing values to an array.

JavaScript has a Math.random() function that generates a random decimal number between 0 (inclusive) and 1 (exclusive). Thus Math.random() can return a 0 but never return a 1. Note: Like Storing Values with the Assignment Operator, all function calls will be resolved before the return executes, so we can return the value of the Math.random() function. Use Math.floor() to round a number down to its nearest whole number. Math.random() can never quite return a 1.

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin

The parseInt() function parses a string and returns an integer.

The parseInt() function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36. The function call looks like: parseInt(string, radix); The radix variable says that string is in the binary system, or base 2.

The conditional operator, also called the ternary operator, can be used as a one line if-else expression.

The syntax is a ? b : c, where a is the condition, b is the code to run when the condition returns true, and c is the code to run when the condition returns false. One can also chain conditional (ternary) operators together to check for multiple conditions.

The following function uses if, else if, and else statements to check multiple conditions:

function findGreaterOrEqual(a, b) {
  if (a === b) {
    return "a and b are equal";
  }
  else if (a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}

The above function can be re-written using multiple conditional operators:

function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" 
    : (a > b) ? "a is greater" 
    : "b is greater";
}
It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read.

Wednesday, August 23, 2023

Swap SelectBox with JavaScript

 <!DOCTYPE html>
<html>
<head>
    <title>Swap Select Boxes</title>
</head>
<body>
    
    <select id="s1">
        <option value="EN">EN</option>
        <option value="DE" selected>DE</option>
        <option value="RO">RO</option>
    </select>

    <select id="s2">
        <option value="EN">EN</option>
        <option value="DE">DE</option>
        <option value="RO"selected>RO</option>
    </select>

<input type="button" onclick="
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
var temp = s1.value; s1.value = s2.value; s2.value = temp;" value="Swap Values" />

</body>
</html>

Or with function:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        button {
            background-color: #4CAF50;
            color: white;
            padding: 14px 20px;
            margin: 8px 0;
            border: none;
            cursor: pointer;
            width: 50%;
        }

        button:hover {
            opacity: 0.8;
        }

        select {
            width: 50%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
    </style>
    <title>Swap Select Boxes with JS</title>
    <script type="text/javascript">
        function swap() {
            var s1 = document.getElementById('s1');
            var s2 = document.getElementById('s2');
            var tmp = s1.value;
            s1.value = s2.value;
            s2.value = tmp;
        }
    </script>
</head>
<body>
    <select id="s1">
        <option value="EN">EN</option>
        <option value="DE" selected>DE</option>
        <option value="RO">RO</option>
    </select>

    <select id="s2">
        <option value="EN">EN</option>
        <option value="DE">DE</option>
        <option value="RO"selected>RO</option>
    </select>

    <button onclick="swap()">Swap Languages</button>
</body>
</html>

Word Macros to Set Selection Spelling Language

'  This is Word macro to set the spelling language of the selected text to a certain language, in this case German, English US and Romanian

Sub SelSpellDE()
    Selection.LanguageID = wdGerman
    Selection.NoProofing = False
    Application.CheckLanguage = False
End Sub
Sub SelSpellEN()
    Selection.LanguageID = wdEnglishUS
    Selection.NoProofing = False
    Application.CheckLanguage = False
End Sub
Sub SelSpellRO()
    Selection.LanguageID = wdRomanian
    Selection.NoProofing = False
    Application.CheckLanguage = False
End Sub

Tuesday, August 22, 2023

Python POST local access

 import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.7,ro;q=0.3',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'www.traduceri.pluto.ro',
    'DNT': '1',
    'Connection': 'keep-alive',
    'Referer': 'https://letconex.blogspot.com/',
    'Upgrade-Insecure-Requests': '1',
    'Sec-GPC': '1',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
}

data = {
    'sourcelanguagenames': 'DE',
    'targetlanguagenames': 'RO',
    'dictionaries': [
        'Hallo.ro',
        'Dict.cc',
        'IATE',
        'DWDS',
    ],
    'bimono': 'Include monolingual ressources',
    'searchformterm': 'Veredelung',
}

response = requests.post('http://192.168.2.100:5000/resultdic.html', headers=headers, data=data)

print(response.text)

Monday, August 14, 2023

Unicode character for Copy and Paste

Are there Unicode characters that represent Copy and Paste?

w3schools Arrows

https://www.key-shortcut.com

(there are scissor symbols that can be used fittingly to represent Cut (e.g. ✂ U+2702) but i could never find one to represent Copy or Paste.)

How about this: &#x2398; = ⎘ which looks kind of like a copy from clipboard.

that's a good one, but though that char's name is NEXT PAGE, which means relying on a particular font's rendering to represent clipboard will be unreliable. 
For Paste, the CLIPBOARD symbol (U+1F4CB) would be likely 📋
  • Use two 📄 emojis and layer them over each other like so:

<span style="font-size: .875em; margin-right: .125em; position: relative; top: -.25em; left: -.125em">
  📄<span style="position: absolute; top: .25em; left: .25em">📄</span>
</span>
The scissor ✂️ and clipboard 📋 emojis are then suitable cut/paste companions.

An (HTML-only) solution using emojis from the modern set

Concept HTML character code Literal Emoji
Copy = Camera &#128247; 📷
Cut = Scissors &#9986;&#65039; ✂️
Paste = Clipboard &#128203; 📋
  • Emojis vary in appearance depending on device and font in use

Unicode encodes characters used in texts, not ideas or concepts. So unless there is a character commonly used in texts to symbolize cut and paste, you shouldn’t expect to find such a symbol in Unicode.

U+2702 BLACK SCISSORS is in Unicode since it appears in older character codes, and it has been used in printed documents to indicate a cutting line, as a “cut here” indicator, rather than as a symbol of copying.

To summarize some great findings here with updated links:
&#8593; Arrow up
&#8595; Arrow down

 Copy: 🗐,

Paste: 📋

Cut: (✂️), ,

    <!-- <pre>&#128464;</pre> -->
    <!-- <pre>&#128203;</pre> -->

Monday, August 7, 2023

Privacy Policy for letconex.blogspot.com from https://www.privacypolicygenerator.org

Privacy Policy for letconex.blogspot.com

At letconex.blogspot.com, accessible from letconex.blogspot.com, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by letconex.blogspot.com and how we use it.

If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us.

Log Files

letconex.blogspot.com follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users' movement on the website, and gathering demographic information. Our Privacy Policy was created with the help of the Privacy Policy Generator.

Google DoubleClick DART Cookie

Google is one of a third-party vendor on our site. It also uses cookies, known as DART cookies, to serve ads to our site visitors based upon their visit to www.website.com and other sites on the internet. However, visitors may choose to decline the use of DART cookies by visiting the Google ad and content network Privacy Policy at the following URL – https://policies.google.com/technologies/ads

Our Advertising Partners

Some of advertisers on our site may use cookies and web beacons. Our advertising partners are listed below. Each of our advertising partners has their own Privacy Policy for their policies on user data. For easier access, we hyperlinked to their Privacy Policies below.

Privacy Policies

You may consult this list to find the Privacy Policy for each of the advertising partners of letconex.blogspot.com.

Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on letconex.blogspot.com, which are sent directly to users' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.

Note that letconex.blogspot.com has no access to or control over these cookies that are used by third-party advertisers.

Third Party Privacy Policies

letconex.blogspot.com's Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.

You can choose to disable cookies through your individual browser options. To know more detailed information about cookie management with specific web browsers, it can be found at the browsers' respective websites.

Children's Information

Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.

letconex.blogspot.com does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.

Online Privacy Policy Only

This Privacy Policy applies only to our online activities and is valid for visitors to our website with regards to the information that they shared and/or collect in letconex.blogspot.com. This policy is not applicable to any information collected offline or via channels other than this website.

Consent

By using our website, you hereby consent to our Privacy Policy and agree to its Terms and Conditions.

Word Macro to Clear Tags from Bilingual Wordfast and Leave Source Text Hidden and Marked Dark Red

 Sub CleanTags()
' CleanTags - Macro to clear tags from bilingual Wordfast and leave source text hidden and marked Dark Red

' Selection.ClearFormatting - clear all formatting


    Selection.Find.ClearFormatting
    Selection.Find.Font.Hidden = True
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "<}0{>"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.Find.ClearFormatting
    Selection.Find.Font.Hidden = True
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "{0>"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.Find.ClearFormatting
    Selection.Find.Font.Hidden = True
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "<0}"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.Find.ClearFormatting
    Selection.Find.Font.Hidden = True
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find.Replacement.Font
        .Hidden = True
        .Color = 192
    End With
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Thursday, August 3, 2023

Python Sqlite - Create Table With One Column and Unique and Not Null Rows, Insert List Into Column

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('your_database.db')

# Create a cursor object
c = conn.cursor()

# Create table
c.execute('''
    CREATE TABLE UniqueNotNullTable (
        UniqueNotNullColumn TEXT UNIQUE NOT NULL
    )
''')

# List of values to insert
values_to_insert = ['Value1', 'Value2', 'Value3']

# Insert each value from the list into the table
for value in values_to_insert:
    try:
        c.execute('''
            INSERT INTO UniqueNotNullTable (UniqueNotNullColumn) VALUES (?)
        ''', (value,))
    except sqlite3.IntegrityError:
        print(f'Value {value} already exists in the table or is null.')

# Commit the changes and close the connection
conn.commit()
conn.close()


Wednesday, August 2, 2023

Baza de date dexonline in format stardict (Dexonline Database in Stardict Format)

Acesta este un dictionar roman, bazat pe baza de date dexonline in format stardict. Formatul stardict este recunoscut de KoReader (singurul software open source pe care l-am gasit pentru e-reader-e).

Se descarcă baza de date de la dexonline si se transformă in format stardict.

TLDR

Ca sa obtineti un format stardict, trebuie mai intai obtinut un format gls din baza de date dexonline a datelor returnate de select-ul acesta:

select replace(l.form, "'", '') form, replace(d.htmlRep, "\n", "<br/>") html from Lexem l inner join EntryLexem el on l.id = el.lexemId
inner join Entry e on el.entryId = e.id
inner join EntryDefinition ed on e.id = ed.entryId
inner join Definition d on ed.definitionId = d.id where d.sourceId in (27, 21);

Formatul gls este destul de simplu. Pe prima linie se afla cuvantul cautat, apoi pe urmatoarea se afla definitia si dupa o linie libera. Deasupra datelor trebuie adaugat header-ul acesta (cu tot cu linii libere):


#bookname=dexonline.ro
#version=3.0.0
#stripmethod=keep
#sametypesequence=h
#date=2018-01-21
#description=Acesta este o adaptare a bazei de date DEX online sub licența GPL.

iar dupa aceea trebuie trecut prin stardict-editor pentru a obtine cele 3 fisiere stardict. Eu am folosit anumite software si anumite proceduri ca sa obtin formatul gls, dar evident, din moment ce se lucreaza cu soft-uri libere si formate text, puteti folosi orice software va e la indemana.

Cum sa-l folosesc

Cele 3 fisiere dex.* trebuie copiate in folderul de dictionare al koreader sau al oricarui alt cititor care cunoaste stardict. Daca doriti, puteti reincepe procesul pentru a obtine din nou baza de date si dictionarul.

Softuri folosite

Pasi

Instalati softurile necesare.

Atentie la stardict-tools. Pachetul este configurat sa depinda de libmysqlclient, care nu mai exista acum in Arch sau Artix Linux. Trebuie sa editati fisierul PKGBUILD si sa eliminati de acolo aceasta dependinta. Probabil libmysqlclient este folosit de alte softuri din pachet, stardict-editor (care ne trebuie noua) va merge.

Descarcati baza de date dexonline de

aici.   Instrucțiuni de instalare

Incarcati-o in mysql.

Un exemplu poate fi vazut aici

Folosind Sql Workbench/J, exportati datele in format CSV

In documentatia Sql Workbench/J sunt explicate anumite comenzi specifice, ca wbexport Le puteti gasi acolo. Eu am executat aceste comenzi:

wbexport -header=false -file=/tmp/rows.txt -delimiter=, -quoteChar="'" -quoteCharEscaping=none -quoteAlways=false -encoding=UTF-8;

select replace(l.form, "'", '') form, d.htmlRep html from Lexem l inner join EntryLexem el on l.id = el.lexemId
inner join Entry e on el.entryId = e.id
inner join EntryDefinition ed on e.id = ed.entryId
inner join Definition d on ed.definitionId = d.id

In urma acestei operatii, am obtinut datele in format text in fisierul /tmp/rows.txt.

Preparati fisierul text

Fisierul text obtinut trebuie transformat in format .gls. Puteti gasi informatii despre format aici.

Am editat fisierul cu vim si am facut urmatoarele schimbari:

  • :%s/\v'$//g (am eliminat ' de la sfarsitul fiecarei linii unde exista)
  • :%s/\v^([^,]+),'/\1, (am eliminat ' de dinaintea definitiilor)
  • :%s/\v^([^,]+),(.*)$/\1^M\2^M (am separat lexemele de definitii si am adaugat o linie noua dupa fiecare definitie)

Atentie la caracterele speciale: au fost obtinute apasand Ctrl si V si apoi Enter. Am inlocuit in principiu textele gasite cu linii noi.

Acum datele sunt in format .gls.

Creati fisierul dex.gls cu urmatorul continut:


#bookname=dexonline.ro
#version=3.0.0
#stripmethod=keep
#sametypesequence=h
#date=2018-01-21
#description=Acesta este o adaptare a bazei de date DEX online sub licența GPL.

-continut-rows.txt-modificat-

Atentie la liniile libere. Prima linie din fisier trebuie sa fie o linie libera si dupa definitia fisierului (linniile care incep cu #) trebuie inserat continutul modificat al rows.txt.

Salvati fisierul si inchideti vim.

Creati dictionarul

Deschideti stardict-editor. In interfata, selectati jos in stanga formatul Babylon file (nu Tab file, care este selectat initial). Apoi selectati fisierul creat dex.gls cu optiunea Browse in partea din stanga sus. Apoi apasati Compile in partea din dreapta jos. Daca totul a mers ok, ar trebui sa obtineti un mesaj de genul acesta:

Building...
Over
wordcount: &lt;n>
Done!

unde n este numarul de cuvinte din dictionar.

Acum ar trebui sa aveti langa fisierul dex.gls cele 3 fisiere stardict (dex.dict.dz, dex.idx, dex.ifo). Aceste 3 fisiere reprezinta dictionarul in format stardict. Trebuie sa le copiati in functie de e-reader-ul folosit in folderul indicat de documentatia KoReader

Sursa: https://github.com/cosminadrianpopescu/dexonline-stardict

Glosar de termeni lingvistici - DOOM

 accent pronunțare mai intensă a unei silabe↑/a unui cuvânt

accent fix accent↑ legat de poziția silabei↑ accentuate în cuvânt

accent liber accent↑ nelegat de poziția silabei↑ accentuate în cuvânt

acronim cuvânt format din prima literă a/primele litere ale cuvintelor dintr-o expresie/sintagmă, dintr-un titlu ș.a. 

afereză cădere accidentală/suprimare a unui sunet/grup de sunete la începutul unui cuvânt

afonizat (sunet) care și-a pierdut sonoritatea↑

analizabil (cuvânt) ale cărui componente pot fi puse de către vorbitori în legătură cu alte cuvinte existente și independent sau în alte formații

apocopă cădere accidentală/suprimare a unuia sau a mai multor sunete de la sfârșitul unui cuvânt

argotic (element) din limbajul convențional al unui anumit grup social

asilabic (sunet) care nu formează silabă↑

categorie gramaticală semnificație gramaticală cu expresie proprie și în funcție de care cuvintele variabile își schimbă forma în cursul flexiunii↑ (caz, comparație, determinare↑, gen, mod, număr, persoană, timp)

clasă lexico-gramaticală clasă de cuvinte cu trăsături semantice și gramaticale (categorii↑ gramaticale, posibilități de combinare) comune (corespunzând părții de vorbire din gramatica tradițională); pentru limba română se disting: adjectiv, adverb, articol3, conjuncție, interjecție, numeral, prepoziție, pronume, substantiv, verb

colocvial element specific conversației

compunere procedeu de formare a cuvintelor constând în combinarea unor cuvinte cu cuvinte independente sau cu elemente de compunere (prefixoide↑, sufixoide↑), dobândind împreună un sens global nou

compus cuvânt format prin combinarea mai multor cuvinte sau a unor cuvinte și a unor elemente de compunere (prefixoide↑, sufixoide↑), dobândind împreună un sens global nou

comun (gen ~) gen cuprinzând substantivele invariabile care desemnează ființe de sex fie femeiesc, fie bărbătesc

consoană sunet la a cărui emitere curentul de aer întâlnește un obstacol, care nu poate juca rolul de centru al unei silabe↑ și care nu primește accent↑

conversiune schimbare a clasei↑ lexico-gramaticale a unui cuvânt

corect conform cu normele↑ limbii literare↑ actuale

defectiv (cuvânt) cu distribuție limitată/flexiuneincompletă/paradigme incomplete

derivat (cuvânt) format de la un cuvânt de bază prin alipirea unor prefixe↑ sau a unor sufixe↑

desinență element final atașat în general radicalului↑ unui cuvânt flexibil↑, exprimând (adesea împreună) la substantive: numărul și cazul, la adjective: și genul, la verbe: numărul și persoana

desonorizat (sunet) care și-a pierdut sonoritatea↑

determinare funcție semantică de actualizare și de individualizare a substantivului sau categorie gramaticală↑ proprie acestuia, manifestată prin opoziția determinat hotărât/nehotărât

devocalizat (sunet) care și-a pierdut din trăsăturile de vocală (sonoritatea↑)

diacritic, -ă semn care distinge literele respective de altele cu formă identică; literă fără valoare fonetică proprie, care marchează valoarea în context a literei/grupului lângă/în care apare

diftong secvență formată dintr-o vocală↑ și o semivocală↑ pronunțate în aceeași silabă↑ (inclusiv în fonetică sintactică↑, atunci când fac parte din cuvinte diferite, alăturate în lanțul vorbirii)

diftong ascendent diftong↑ care prezintă ordinea semivocală↑ + vocală↑

diftong descendent diftong↑ care prezintă ordinea vocală↑ + semivocală↑

digraf succesiune de două litere care notează un singur sunet

domeniu sector de activitate reflectat în vocabular

element de compunere element asemănător cu prefixele↑ sau cu sufixele↑, dar cu sens relativ mai dezvoltat, originar în general din greaca veche sau din latină, care se atașează unui radical↑, dând naștere unor cuvinte noi; v. și prefixoid↑, sufixoid↑

eliziune cădere accidentală a vocalei↑ neaccentuate de la finala unui cuvânt în contact cu vocala inițială a cuvântului următor

encliză atașare a unui element la termenul precedent, cu care se grupează

etimologie populară modificare greșită a formei unui cuvânt/unei expresii, contrar etimologiei reale, prin apropieri bazate pe asemănări formale sau/și de sens

familiar (element) folosit în vorbirea obișnuită

flexibil (cuvânt) la care semnificațiile gramaticale se exprimă cu ajutorul unui element variabil atașat la partea lui finală

flexiune atașare, în cursul vorbirii, la partea (în general) invariabilă a unor cuvinte, a unor elemente care marchează diferitele categorii↑ gramaticale

fonetică sintactică fenomene fonetice care se produc în lanțul vorbirii

format” (cuvânt) compus↑ sudat sau derivat↑

greșit neconform cu normele↑ limbii literare↑ actuale

grup relativ stabil grup de cuvinte folosit relativ frecvent, ale cărui componente

de cuvinte își păstrează autonomia și sensul de bază și care corespund realității denumite

hiat succesiune de două vocale↑ alăturate pronunțate în silabe↑ diferite (în cuvinte simple sau compuse, inclusiv scrise cu cratimă)

hipercorect (element) la care se evită o falsă greșeală

hipercorectitudine evitare a unei false greșeli

i „șoptit” (afonizat↑,

asilabic↑, desonorizat↑,

devocalizat) i final de silabă sau de cuvânt care și-a pierdut sonoritatea↑ și nu formează silabă↑

invariabil (cuvânt) lipsit de flexiune↑ (care în cursul vorbirii își păstrează neschimbată forma)

învechit (element) din faze ale limbii anterioare celei actuale

latinism (în DOOM3) împrumut din latină, în general neadaptat, care apare ca un cuvânt străin în contexte în limba română

literară (limbă ~) varianta de cultură, cea mai îngrijită, a limbii unei comunități, codificată prin norme↑ supradialectale unice și consolidată în special prin scris

literă-consoană literă care notează sunete-consoane↑

literă diacritică literă fără valoare fonetică proprie, care modifică valoarea în cuvânt a literei în a cărei vecinătate apare

literă-vocală literă care notează (cu precădere) sunete-vocale↑ (și semivocale↑)

locuțiune grup de cuvinte cu sens global unitar și cu trăsături morfosintactice care atestă pierderea autonomiei gramaticale a cel puțin unei componente și funcționarea de ansamblu ca un cuvânt unic

morfologie schimbarea formei cuvintelor pentru marcarea valorilor gramaticale

neologism (în lingvistica românească) împrumut făcut de limba română modernă și contemporană cu precădere din limbile occidentale de circulație internațională și din limbile clasice

nonstandard (element) din afara limbii standard↑

norma (literară↑) expresia codificată a uzului↑ lingvistic dominant, respectată în scrisul și în vorbirea persoanelor cultivate, care arată „cum trebuie să se scrie/spună”

omofone (elemente) care se pronunță la fel

omografe (elemente) care se scriu la fel

omonime parțiale (construcții/cuvinte/morfeme) cu sensuri diferite care au unele forme identice și altele diferite sau prezente numai la unul dintre omonime

omonime totale (cuvinte) cu sensuri diferite, care au toate formele identice

ortoepie pronunțare corectă↑

ortografie scriere corectă↑

ortogramă model de scriere corectă↑

parasintetic (cuvânt) în același timp compus↑ și derivat↑

paronime cuvinte diferite ca sens, dar foarte asemănătoare ca formă și care se pot confunda

personal (gen ~) subclasă a substantivelor nume de persoană care se disting prin anumite particularități morfosintactice

plenisonă (vocală↑~), în opoziție cu semivocala↑ corespunzătoare

popular (element) supradialectal din limbajul curent al oamenilor obișnuiți, fără o instrucție superioară

prefix element antepus unei baze lexicale, cu ajutorul căruia se creează un cuvânt nou

prefixoid element de compunere↑ inițial din limbajul cult/specializat, în general fără existență independentă, având un sens mai dezvoltat decât prefixele↑, care, în limba din care provine (de multe ori indirect) – greaca veche, latina –, constituia un cuvânt autonom, cu sens deplin

procliză atașare a unui element la termenul următor, cu care se grupează

punctuație sistem de semne grafice convenționale care marchează segmentarea unui text în unități sintactice, intonația și pauzele

radical parte a unui cuvânt care poartă sensul lexical și la care se pot atașa desinențe↑, prefixe↑, sufixe↑

reduplicat (element) repetat întocmai

regional (element) specific unei regiuni

registru varietate a limbii în funcție de situația de comunicare

semianalizabil cuvânt „format”↑ din care o componentă poate fi pusă de către vorbitori, într-o măsură mai mare sau mai mică, în legătură cu alt element/alte elemente care există și independent sau în alte formații

semivocală sunet care din punctul de vedere al articulării seamănă cu o vocală↑, dar care nu poate primi accent↑ și nu poate forma singur o silabă↑

semn de punctuație semn grafic convențional care marchează segmentarea unui text în unități sintactice, pauzele sau/și intonația

semn diacritic semn grafic (în general subscris sau suprascris) care distinge litere cu forma de bază identică și cu valoare fonetică diferită

semn ortografic semn grafic convențional utilizat la nivelul cuvântului sau al mai multor cuvinte care formează o unitate

silabație descompunere a cuvintelor în conformitate cu structura lor silabică

silabă (fonetică/orală) secvență sonoră minimală caracterizată prin accent propriu unic, care are în centru o vocală↑, însoțită sau nu de una sau mai multe consoane↑ sau/și semivocale↑

sincopă cădere a unui sunet/grup de sunete din interiorul unui cuvânt.

sinereză pronunțare într-o singură silabă↑ a vocalei↑ finale a unui cuvânt și a vocalei inițiale a cuvântului următor (transformare, în fonetică sintactică↑, a unui hiat↑ în diftong↑)

sinonime (cuvinte/construcții) ale căror sensuri se află în relație de echivalență sau de identitate

sonante consoane↑ care se pronunță cu un zgomot mai slab decât majoritatea consoanelor (și care sunt întotdeauna sonore↑): l, m, n, r

sonor (sunet) produs cu vibrația regulată a coardelor vocale

sonoră (consoană↑) dotată cu sonoritate↑: b, d, g, g, ğ, j, v, z;

sonoritate trăsătură, atât a vocalelor↑, cât și a unor consoane↑, datorată vibrației regulate a coardelor vocale

standard (limbă ~) variantă a limbii care reunește elemente folosite de toți vorbitorii în condiții obișnuite și care nu sunt marcate de afectivitate sau de specializări profesionale

stil (~ funcțional) varietate funcțională a limbii

sufix (lexical) element postpus unei baze lexicale, cu ajutorul căruia se creează un cuvânt nou

sufixoid element de compunere↑ final din limbajul cult/specializat, în general fără existență independentă, având un sens mai dezvoltat decât sufixele↑ și care, în limba din care provine (de multe ori indirect) – greaca veche, latina – constituia un cuvânt autonom, cu sens deplin

sunet-consoană consoană↑

sunet-tip sunet reprezentând media variațiilor din pronunțarea unui sunet

sunet-vocală vocală↑

surdă (consoană↑) lipsită de sonoritate↑: č, f, h, k, k′, p, s, ș, t, ț

temă radicalul↑ și sufixul↑ lexical caracteristic, la care se atașează desinențele↑

triftong secvență formată din o vocală↑ și două semivocale↑ pronunțate în aceeași silabă↑ (inclusiv în fonetică sintactică↑, atunci când fac parte din cuvinte diferite, alăturate în lanțul vorbirii)

trigraf succesiune de trei litere care notează un singur sunet

trunchiere suprimare a silabelor↑ finale ale unui cuvânt

uz folosirea concretă, în condiții obișnuite, a elementelor lingvistice de către cei mai mulți vorbitori

variante literare libere forme care circulă în paralel în limba literară actuală și sunt acceptate de normă ca fiind corecte↑ (ordinea în care apar în DOOM3 indicând preferința); pot fi fonetice (inclusiv accentuale sau de silabație↑), lexicale, morfologice, ortografice

vocală sunet la a cărui emitere, prin vibrații ale coardelor vocale, curentul de aer nu întâlnește niciun obstacol, care poate primi accent↑ și poate forma singur o silabă↑

xenism neologism↑ foarte recent, neadaptat la sistemul limbii române, simțit și tratat de vorbitori ca străin

Sursa: https://doom.lingv.ro