text:
Q: Replace one delimiter with another in Spark data frame in Scala Here is my Spark data frame output of dfMainOutput.
4295858898,177,SelfSourcedPublic,INC,Cost of sales,Umsatzkosten,,ECOR,false,,,,,false,False,,,,505096,505074,505074,505096,505096,,505074,False,,3014830,,I|!|

Now i want to replace , with |^| and dropping one column DataPartition
This is what I am doing:
val dfMainOutputFinal = dfMainOutput.select($"DataPartition", $"StatementTypeCode",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

val headerColumn = df.columns.filter(v => (!v.contains("^") && !v.contains("_c"))).toSeq

val header = headerColumn.dropRight(1).mkString("", "|^|", "|!|")

val dfMainOutputFinalWithoutNull = dfMainOutputFinal.withColumn("concatenated", regexp_replace(col("concatenated"), "null", "")).withColumnRenamed("concatenated", header)

dfMainOutputFinalWithoutNull.repartition(1).write.partitionBy("DataPartition","StatementTypeCode")
  .format("csv")
  .option("nullValue", "")
  .option("header", "true")
  .option("codec", "gzip")
  .save("s3://trfsmallfffile/FinancialLineItem/output")

With this code the output below is generated:
4295858898|^|177|^|INC|^|Cost of sales|^|Umsatzkosten|^|ECOR|^|false|^|false|^|False|^|505096|^|505074|^|505074|^|505096|^|505096|^|505074|^|False|^|3014830|^|I|!|

Where empty elements are missing. I would like it to be:
4295858898|^|177|^|INC|^|Cost of sales|^|Umsatzkosten|^||^|ECOR|^|False|^||^||^||^||^|False|^|False|^||^||^||^|505096|^|505074|^|505074|^|505096|^|505096|^||^|505074|^|False|^||^|3014830|^||^|I|!|

Also in the data frame output i am getting false where as we want False
Please help me what II am missing ..
Here is my schema
root
 |-- LineItem_organizationId: long (nullable = true)
 |-- LineItem_lineItemId: integer (nullable = true)
 |-- DataPartition: string (nullable = true)
 |-- StatementTypeCode: string (nullable = true)
 |-- LineItemName: string (nullable = true)
 |-- LocalLanguageLabel: string (nullable = true)
 |-- FinancialConceptLocal: string (nullable = true)
 |-- FinancialConceptGlobal: string (nullable = true)
 |-- IsDimensional: boolean (nullable = true)
 |-- InstrumentId: string (nullable = true)
 |-- LineItemSequence: string (nullable = true)
 |-- PhysicalMeasureId: string (nullable = true)
 |-- FinancialConceptCodeGlobalSecondary: string (nullable = true)
 |-- IsRangeAllowed: boolean (nullable = true)
 |-- IsSegmentedByOrigin: string (nullable = true)
 |-- SegmentGroupDescription: string (nullable = true)
 |-- SegmentChildDescription: string (nullable = true)
 |-- SegmentChildLocalLanguageLabel: string (nullable = true)
 |-- LocalLanguageLabel_languageId: string (nullable = true)
 |-- LineItemName_languageId: string (nullable = true)
 |-- SegmentChildDescription_languageId: string (nullable = true)
 |-- SegmentChildLocalLanguageLabel_languageId: string (nullable = true)
 |-- SegmentGroupDescription_languageId: string (nullable = true)
 |-- SegmentMultipleFundbDescription: string (nullable = true)
 |-- SegmentMultipleFundbDescription_languageId: string (nullable = true)
 |-- IsCredit: string (nullable = true)
 |-- FinancialConceptLocalId: string (nullable = true)
 |-- FinancialConceptGlobalId: string (nullable = true)
 |-- FinancialConceptCodeGlobalSecondaryId: string (nullable = true)
 |-- FFAction: string (nullable = true)

In the data DataPartition=SelfSourcePublic and StatementTypeCode=INC
Output from dfMaainOutput
+-----------------------+-------------------+-----------------+-----------------+------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------+---------------------+----------------------+-------------+------------+----------------+-----------------+-----------------------------------+--------------+-------------------+-----------------------+-----------------------+------------------------------+-----------------------------+-----------------------+----------------------------------+-----------------------------------------+----------------------------------+-------------------------------+------------------------------------------+--------+-----------------------+------------------------+-------------------------------------+--------+
|LineItem_organizationId|LineItem_lineItemId|DataPartition    |StatementTypeCode|LineItemName                                                                              |LocalLanguageLabel                                                                                |FinancialConceptLocal|FinancialConceptGlobal|IsDimensional|InstrumentId|LineItemSequence|PhysicalMeasureId|FinancialConceptCodeGlobalSecondary|IsRangeAllowed|IsSegmentedByOrigin|SegmentGroupDescription|SegmentChildDescription|SegmentChildLocalLanguageLabel|LocalLanguageLabel_languageId|LineItemName_languageId|SegmentChildDescription_languageId|SegmentChildLocalLanguageLabel_languageId|SegmentGroupDescription_languageId|SegmentMultipleFundbDescription|SegmentMultipleFundbDescription_languageId|IsCredit|FinancialConceptLocalId|FinancialConceptGlobalId|FinancialConceptCodeGlobalSecondaryId|FFAction|
+-----------------------+-------------------+-----------------+-----------------+------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------+---------------------+----------------------+-------------+------------+----------------+-----------------+-----------------------------------+--------------+-------------------+-----------------------+-----------------------+------------------------------+-----------------------------+-----------------------+----------------------------------+-----------------------------------------+----------------------------------+-------------------------------+------------------------------------------+--------+-----------------------+------------------------+-------------------------------------+--------+
|4295858898             |707                |SelfSourcedPublic|INC              |Revenue from long-term construction contracts                                             |Erlöse aus langfristigen Fertigungsaufträgen                                                          |null                 |ROBR                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3015278                 |null                                 |I|!|    |
|4295858898             |3289               |SelfSourcedPublic|INC              |Balancing Item - Net Income available to Controlling Interest                             |null                                                                                |null                 |IIII                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3014960                 |null                                 |I|!|    |
|4295858922             |808                |SelfSourcedPublic|INC              |Income Taxes - Total                                                                      |Ertragsteuern                                                                                |null                 |XTAX                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |False   |null                   |3019589                 |null                                 |I|!|    |
|4295858922             |1507               |SelfSourcedPublic|INC              |Balancing Item - Operating Expenses                                                       |null                                                                                |null                 |IIII                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3014960                 |null                                 |I|!|    |
|4295858951             |1574               |SelfSourcedPublic|INC              |Admin/General Expenses                                                                    |null                                                                                |null                 |ESGA                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |False   |null                   |3018991                 |null                                 |I|!|    |
|4295859007             |1645               |SelfSourcedPublic|INC              |Exploration Expenses - Balancing value                                                    |null                                                                                |null                 |EEXP                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |False   |null                   |3018916                 |null                                 |I|!|    |
|4295859038             |954                |SelfSourcedPublic|INC              |Sale Investments                                                                          |null                                                                                |null                 |EGFA                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3018929                 |null                                 |I|!|    |
|4295859038             |1967               |SelfSourcedPublic|INC              |Restructuring Charges/Provisions                                                          |Ergebnis aus Umstrukturierungen                                                                       |null                 |ERES                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |False   |null                   |3018980                 |null                                 |I|!|    |
|4295859038             |1996               |SelfSourcedPublic|INC              |Diluted Weighted Average Shares on Instrument Level multiplied to its Participation Factor|null                                                                                |null                 |DWASEPFI              |false        |8590926849  |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |1002023919              |null                                 |I|!|    |
|4295859045             |864                |SelfSourcedPublic|INC              |Results of valuation gains/losses and disposals of non-current securities                 |Ergebnis aus Kursänderungen und Abgängen von Wertpapieren des langfristigen Finanzvermögens ("@FVTPL")|null                 |EGIT                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3018932                 |null                                 |I|!|    |
|4295859045             |1092               |SelfSourcedPublic|INC              |Excep. Depreciation                                                                       |null                                                                                |null                 |EGLO                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3018938                 |null                                 |I|!|    |
|4295859071             |1840               |SelfSourcedPublic|INC              |Other Operating Expense                                                                   |null                                                                                |null                 |EOOE                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |False   |null                   |3018974                 |null                                 |I|!|    |
|4295859078             |914                |SelfSourcedPublic|INC              |Balancing Item - Non Operating Income/(Expense), net                                      |null                                                                                |null                 |IIII                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505096                       |505074                 |505074                            |505096                                   |505096                            |null                           |505074                                    |True    |null                   |3014960                 |null                                 |I|!|    |
|4295859106             |514                |SelfSourcedPublic|INC              |Personnel Expenses                                                                        |null                                                                                |null                 |ELAS                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |False   |null                   |3018944                 |null                                 |I|!|    |
|4295859106             |903                |SelfSourcedPublic|INC              |Balancing Item - Non Operating Income/(Expense), net                                      |null                                                                                |null                 |IIII                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |True    |null                   |3014960                 |null                                 |I|!|    |
|4295859216             |499                |SelfSourcedPublic|INC              |BC - Depreciation of Fixed Assets                                                         |null                                                                                |null                 |BCDEP                 |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505084                       |505074                 |505074                            |505084                                   |505084                            |null                           |505074                                    |False   |null                   |1002023928              |null                                 |I|!|    |
|4295859236             |172                |SelfSourcedPublic|INC              |Total Revenue                                                                             |Ventes                                                                                |null                 |XTLR                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |True    |null                   |3016345                 |null                                 |I|!|    |
|4295859241             |492                |SelfSourcedPublic|INC              |Diluted Net Income excluding Extra Items applicable to Common - (Instrument Level)        |null                                                                                |null                 |XNCNDI                |false        |8589989623  |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |True    |null                   |1001214357              |null                                 |I|!|    |
|4295859279             |124                |SelfSourcedPublic|INC              |Income Available to Com Excl ExtraOrd                                                     |Toerekenbaar aan de aandeelhouders van de moederonderneming                                           |null                 |XNCN                  |false        |null        |null            |null             |null                               |false         |False              |null                   |null                   |null                          |505084                       |505074                 |505074                            |505084                                   |505084                            |null                           |505074                                    |True    |null                   |3016316                 |null                                 |I|!|    |
|4295859298             |488                |SelfSourcedPublic|INC              |Other operating income/expenses                                                           |Other operating expenses                                                                              |null                 |EOIE                  |false        |null        |null            |null             |null                               |false         |null               |null                   |null                   |null                          |505074                       |505074                 |505074                            |505074                                   |505074                            |null                           |505074                                    |True    |null                   |3018969                 |null                                 |I|!|    |
+-----------------------+-------------------+-----------------+-----------------+------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------+---------------------+----------------------+-------------+------------+----------------+-----------------+-----------------------------------+--------------+-------------------+-----------------------+-----------------------+------------------------------+-----------------------------+-----------------------+----------------------------------+-----------------------------------------+----------------------------------+-------------------------------+------------------------------------------+--------+-----------------------+------------------------+-------------------------------------+--------+

Output After Code
val dfMainOutputFinal = dfMainOutput.select($"DataPartition", $"StatementTypeCode",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

Here is output
+-----------------+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|DataPartition    |StatementTypeCode|concatenated                                                                                |
+-----------------+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|SelfSourcedPublic|INC              |4295858898|^|707|^|INC|^|Revenue from long-term construction contracts|^|Erlöse aus langfristigen Fertigungsaufträgen|^|ROBR|^|false|^|false|^|False|^|505096|^|505074|^|505074|^|505096|^|505096|^|505074|^|True|^|3015278|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295858898|^|3289|^|INC|^|Balancing Item - Net Income available to Controlling Interest|^|IIII|^|false|^|false|^|505096|^|505074|^|505074|^|505096|^|505096|^|505074|^|True|^|3014960|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295858922|^|808|^|INC|^|Income Taxes - Total|^|Ertragsteuern|^|XTAX|^|false|^|false|^|False|^|505096|^|505074|^|505074|^|505096|^|505096|^|505074|^|False|^|3019589|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295858922|^|1507|^|INC|^|Balancing Item - Operating Expenses|^|IIII|^|false|^|false|^|505096|^|505074|^|505074|^|505096|^|505096|^|505074|^|True|^|3014960|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295859236|^|172|^|INC|^|Total Revenue |^|Ventes|^|XTLR|^|false|^|false|^|False|^|505074|^|505074|^|505074|^|505074|^|505074|^|505074|^|True|^|3016345|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295859241|^|492|^|INC|^|Diluted Net Income excluding Extra Items applicable to Common - (Instrument Level) |^|XNCNDI|^|false|^|8589989623|^|false|^|505074|^|505074|^|505074|^|505074|^|505074|^|505074|^|True|^|1001214357|^|I|!|                                                                                |
|SelfSourcedPublic|INC              |4295859279|^|124|^|INC|^|Income Available to Com Excl ExtraOrd|^|Toerekenbaar aan de aandeelhouders van de moederonderneming|^|XNCN|^|false|^|false|^|False|^|505084|^|505074|^|505074|^|505084|^|505084|^|505074|^|True|^|3016316|^|I|!|                                                                               |
|SelfSourcedPublic|INC              |4295859298|^|488|^|INC|^|Other operating income/expenses|^|Other operating expenses|^|EOIE|^|false|^|false|^|505074|^|505074|^|505074|^|505074|^|505074|^|505074|^|True|^|3018969|^|I|!|                                                                                |
+-----------------+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

So just be make clear for example 4295858898             |3289 null value in the column LocalLanguageLabel is gone
I dont know how it is missed ...

A: Your main culprit is that you have null values in your dataframe and concat_ws is filtering out all the null values. So the solution is to replace all null values to "" which should solve your issue. It won't be a problem as you have all the null datatypes in schema as string.
So, replacing the following
val dfMainOutputFinal = dfMainOutput.select($"DataPartition", $"StatementTypeCode",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

with
val dfMainOutputFinal = dfMainOutput.na.fill("").select($"DataPartition", $"StatementTypeCode",concat_ws("|^|", dfMainOutput.schema.fieldNames.filter(_ != "DataPartition").map(c => col(c)): _*).as("concatenated"))

should solve your issue


text:
Q: Execute update command in MySql while overriding sql_safe_updates option I need to run a script with update commands which do not specify the record IDs, so I know I must turn the flag of sql_safe_updates to OFF.
Yet, I need to restore the flag to its previous state.
Is there a way to hold the flag's value in a temporary parameter, then run my updates and restore it to its initial value?
(I will need to keep the script for deployment procedure, so I cannot change the flag's value manually every time it runs)
UPDATE:
That is about the script I have:
SET SQL_SAFE_UPDATES = 0;
UPDATE offensedb.offenses set Status = 6 , ClosingReason = 1 WHERE Status = 1;
SET SQL_SAFE_UPDATES = 1;

A: After examining a dump file of mysql I came across these commands:
SET @OLD_SQL_MODE=@@SQL_MODE
-- some other sql commands there...
SET SQL_MODE=@OLD_SQL_MODE

So I figured out the answer to my question would be:
SET @SQL_SAFE_UPDATES=@@SQL_SAFE_UPDATES;
UPDATE offensedb.offenses set Status = 6 , ClosingReason = 1 WHERE Status = 1;
SET SQL_SAFE_UPDATES = @SQL_SAFE_UPDATES;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to prematurely stop a push notification sound when another push arrives? My scenario is i have 29 sec custom audio sound which is like a ringer.
So my scenario is like
push 1 arrives which is a 29 secs ringer
and continuous ringer starts
but when second push arrives i want this 29 ringer to stop and play the next push sound.
Is there anyway to achieve this?

A: It is not possible to stop the sound of one push notifications if user has enabled it from its global settings of iPhone.


text:
Q: Multiply list of lists with elements of multiplier list Python I want to multiply the lists below with the elements of a multiplier list. So that multiplier[0] multiplies the first list in list of lists, multiplier[1] multiplies the second list in list of lists etc.
Thank you!
I have tried this so far:
[a*b for a,b in zip(multiplier,list_of_lists)]

This is the list of lists:
[[0, 0, 1, 1],
[1, 0, 0, 0],
[1, 1, 1, 1],
[1, 2, 0, 1]]

Multiplier list:
[1.0, 2.0, 0.0, 0.41503749927884376]

A: If you'll convert your code from list comprehension into simple loop, you will see where problem is:
result = []
for a, b in zip(multiplier, list_of_lists):
    result.append(a * b)  # appends a copies of list b

It's definitely not what you're trying to do. You need nested loop to iterate over items of inner lists:
result = []
for multiplier, sub_list in zip(multipliers, list_of_lists):
    new_list = []
    for item in sub_list:
        new_list.append(multiplier * item)
    result.append(new_list)

Or you can write it shorter using nested list comprehension (you can give variables shorter names to look more "compact"):
result = [[multiplier * item for item in sub_list] for multiplier, sub_list in zip(multipliers, list_of_lists)]

A: Something like this (****edit: see caveats in comments**** )?
import numpy as np
a1 = np.array([[0, 0, 1, 1],
[1, 0, 0, 0],
[1, 1, 1, 1],
[1, 2, 0, 1]])
a2 = np.array([1.0, 2.0, 0.0, 0.41503749927884376])
res = (a1.T*a2).T

A: Use a list comprehension for a more compact implementation.
multi_list = [[0, 0, 1, 1],[1, 0, 0, 0],
        [1, 1, 1, 1],    [1, 2, 0, 1]]
mul = [1.0, 2.0, 0.0, 0.41503749927884376]

new_List = [[i * b for i in a] for a, b in zip(multi_list, mul)]

print(new_List)

A: Check something like this:
list_of_lists = [[0, 0, 1, 1],
[1, 0, 0, 0],
[1, 1, 1, 1],
[1, 2, 0, 1]]

multiplier_list =  [1.0, 2.0, 0.0, 0.41503749927884376]
output_list = [[x * multiplier_list[i] for x in list_] for i, list_ in enumerate(list_of_lists)]

print(output_list)
# [[0.0, 0.0, 1.0, 1.0],
#  [2.0, 0.0, 0.0, 0.0],
#  [0.0, 0.0, 0.0, 0.0],
#  [0.41503749927884376, 0.8300749985576875, 0.0, 0.41503749927884376]]


text:
Q: Wordpress redirect to referring page after logging in
Note: I already created the same question in Wordpress StackExchange, but I didn't receive any responses! Sorry about that!

I am not using any custom login plugins or any bespoke code. A few of my pages have got this bit of code in them at the very beginning.
<?php
    if(!is_user_logged_in())
        wp_redirect('/login/');
?>

So, this doesn't allow the users to view the page when not logged in. I have these pages bearing this bit of code:
/wp-content/my-theme/my-account/
/wp-content/my-theme/my-account/world.php
/wp-content/my-theme/my-account/subscription.php
/wp-content/my-theme/my-dashboard.php
/wp-content/my-theme/my-files.php

Now, when a user goes to any of the above pages, without logging in, it redirects to the login page, and when the user logs in, it lands them to the my-account/ page.
I want to change the current scenario to make the user redirect to the referring page, where he came from. I tried the following things, which never worked.
Using a HTTP_REFERRER
In the login/ form, I placed this bit of code:
<input type="hidden" name="redirect" value="<?php echo $_SERVER['HTTP_REFERER']; ?>" />

Hacking functions.php
In the functions.php, I placed this bit of code:
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
        add_filter('login_redirect', 'my_login_redirect', 10, 3);
        function my_login_redirect() {
                $location = $_SERVER['HTTP_REFERER'];
                wp_safe_redirect($location);
                exit();
        }
}

References:

*

*Redirect wordpress back to referring page after login

*WordPress Tip: Redirect to Previous Page After Login

I have also tried these and failed:

*

*Redirecting users to referrer page after logging in using custom login form

*Redirect user to original url after login?
Nothing was working out. I am happy to provide further details if needed. Thanks in advance. :)

My work so far...
I have modified the code this way:
<?php
    if(!is_user_logged_in())
        wp_redirect('/login/?redirect_to=' . $_SERVER["REQUEST_URI"]);
?>

This renders the login page this way:
/login.php?redirect_to=/my-account/subscription.php

This would be enough for me to authenticate and redirect. But I need to find the bit where the real redirection happens and I want to redirect it using the redirect_to parameter!

A: The login process is handled via AJAX. The function posting the values isn't considering redirect_to . The following code in the JS file always redirects to /my-account. So now when the AJAX function returns, you can get the value of redirect_to hidden field and then redirect the user there.
window.location = "/my-account/";


text:
Q: Short story about invaders being hampered by the flora, losing consciousness and transformed on awakening Hope you can help? I read this short story, possibly in a science fiction anthology from the 70's. Now I'm struggling to remember the author and the title of the story and I'd like to use it as reference as it is a great metaphor for immigration.
What I remember is a story about the character being a part of an invasion team where they struggle to reach the enemy. In fact never coming into contact, being hampered by poor visibility and having to constantly struggle against hedges and thickets of plant life that slowed down their progress. At some point they all lose consciousness and when recovering discover they have transformed into beings with a seal like pelt covering. They have been turned native by the environment itself.
There are other previous invaders but they too have been transformed in the same way.
Now, the planet is getting too crowded and they need to begin plans for invasion themselves.


text:
Q: I have a script that makes some manipulation with .xlsx file. How do i loop it with all files within folder? I have script that updates query in excel file
$filePath = "C:\Scripts\SheetToRefresh.xlsx"
$excelObj = New-Object -ComObject Excel.Application
$excelObj.Visible = $true
$workBook = $excelObj.Workbooks.Open($filePath)
$workSheet = $workBook.Sheets.Item("Data")
$workSheet.Select()

$workBook.RefreshAll()

$workBook.Save()

Original script comes from here
Now i need to loop it wihtin folder, i came up with:
$files = Get-ChildItem "C:\path" -Filter *.xlsx

foreach ($f in $files){

}

but struggling with changing filename for each file.(newbie with ps)

A: Let's break down what needs to happen:

*

*Before:

*

*Open Excel

*Enumerate files

*During, for each file:

*

*Open workbook

*Run the relevant part of your existing script

*Save and close workbook

*After:

*

*Close Excel

So, let's start by moving the "Before" actions to the top of your new script:
# Open Excel
$excelObj = New-Object -ComObject Excel.Application
$excelObj.Visible = $true

# Enumerate files
$files = Get-ChildItem "C:\path" -Filter *.xlsx

Now we need to move the relevant parts of the existing script into the new loop. To get the full path of the file object returned by Get-ChildItem, use the FullName property:
foreach($file in $files){
  # Open workbook from $file
  $workBook = $excelObj.Workbooks.Open($file.FullName)

  # Refresh query results
  $workSheet = $workBook.Sheets.Item("Data")
  $workSheet.Select()
  $workBook.RefreshAll()

  # Save updated workbook to file
  $workBook.Save()

  # Close workbook
  $workBook.Close()
}

And finally we just need to quit Excel:
$excelObj.Quit()


text:
Q: Area of region inside circle and Lemniscate? What is the area of the region inside the circle $r=1$ and inside the lemniscate $r^2=2\cos(2\theta)$?
I can't quite figure this one out. I was able to graph it easily and find the circle is one all the way around and the Lemniscate has tip petals on the x axis. How would you find the area if it is asking inside both figures? I know how to find out the answer if it is asking outside and inside. I found the integral range to be from $\pi/12$ to $\pi/4$. My answer after using the area for a region $1/2(f(\theta)^2-g(\theta)^2)$ is $\sqrt{3}-\pi/3$.

A: $ \theta = \frac{\pi}{12} \ $ is not the right value for their point of intersection in the first quadrant.
Equation of curves are $ \ r = 1$ and $r^2 = 2 \cos 2\theta$.

We need to find area that is inside the circle and the lemniscate (shaded area in the diagram). As you can see there is symmetry in all four quadrants so we can find area bound in first quadrant and multiply by $4$.
If we take intersection in first quadrant, $2 \cos2\theta = 1 \implies \theta = \frac{\pi}{6}$.
Also note that curve $r = \sqrt{2 \cos 2\theta}$ in first quadrant forms for $0 \leq \theta \leq \frac{\pi}{4}$.
For $0 \leq \theta \leq \frac{\pi}{6}$, $r$ is bound above by the circle and for $\frac{\pi}{6} \leq \theta \leq \frac{\pi}{4}, $ r is bound above by the lemniscate.
So the area should be,
$A = 4 \: \bigg[\displaystyle \int_0^{\pi/6} \int_0^1 \: r \ dr \ d\theta + \int_{\pi/6}^{\pi/4} \int_0^{\sqrt{2\cos2\theta}} \: r \ dr \ d\theta \ \bigg]$


text:
Q: Laravel 7 jQuery blocking submit button I have contact form for sending e-mails. When i adding jQuery no matters what version and i also tried downloaded jQuery and CDN  submit don't work in my contact form, nothing happens. In dev-tools don't have any errors. When i commenting out jQuery, everything works perfect. But i need both of them - contact form for site visitors and jQuery for my mobile menu. Maby there is another way to trigger action route with method=post?
Here is my blade
<form action="{{url('/sendmail')}}" method="post" id="contact">
    @csrf

            <fieldset>
                <input name="name" type="text" class="form-control" id="name" placeholder="Jūsu vārds..." required="">
            </fieldset>

            <fieldset>
                <input name="email" type="text" class="form-control" id="email" pattern="[^ @]*@[^ @]*"
                       placeholder="Jūsu e-pasts..." required="">
            </fieldset>

            <fieldset>
                <input name="subject" type="text" class="form-control" id="subject" placeholder="Temats..." required="">
            </fieldset>

            <fieldset>
                <textarea name="message" rows="6" class="form-control" id="message" placeholder="Jūsu ziņa..."
                          required=""></textarea>
            </fieldset>

            <fieldset>
                <button type="submit" id="form-submit" class="filled-button">Sūtīt ziņu</button>
            </fieldset>

</form>

And here is my route list
Route::get('/', 'PagesController@index');
Route::get('/kontakti', 'PagesController@contacts');
Route::post('/sendmail', 'MailController@sendMail')->name('send');

On other older Laravel versions this works fine, but in Laravel 7 it's not working.
UPDATE: here is script list for this template and seems that owl carousel is doing this error

A: Check in your browser if any request is being send. In Chrome of Firefox you can see this in developer tools network tab.
Also try to change your action to:
action="{{ route('send') }}"


text:
Q: TextEditor Keyboard Avoidance How can I shift the view upwards with TextEditor? When I use a TextField object, I have no problems with it, because keyboard avoidance is now provided by default. However, if I use a TextEditor, my view does not even react to the keyboard like TextField does.
I tried this solution here, but it did not fix my view.


text:
Q: Timer for Python 3.8.0 I need to create a timer that resets my slidingWindowSize variable without interrupting the application from running.
I have developed the server and client:
# Server
import socket
import sys
import config

MY_IP = config.myIP
OTHER_IP = config.otherIp
PORT_NUMBER = config.port_number

# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to the port
server_address = (MY_IP, PORT_NUMBER)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)

while True:
    print('\nwaiting to receive message')
    data, address = sock.recvfrom(4097)

    print('received {} bytes from {}'.format(
        len(data), address))
    print(data)

    if data:
        sent = sock.sendto(data, address)
        print('sent {} bytes back to {}'.format(
            sent, address))

# Client
import socket
import sys
import config # My computer IP
import sched
import time

from threading import Timer

MY_IP = config.myIP # My IP
PORT_NUMBER = config.port_number # Port Number

def timeout(slidingWindowSize):
    print('Window size value after:', time.time(), slidingWindowSize)
    exit()

scheduler = sched.scheduler(time.time, time.sleep)

# Create a UDP socket with my IP and Port
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (MY_IP, PORT_NUMBER)
slidingWindowSize = 1

while True:
    print("Window size value before: ", slidingWindowSize)
    if slidingWindowSize == 128:
        exit()
    for i in range(slidingWindowSize):
        packet = bytes([1])
        # send data
        print('sending {!r}'.format(packet))
        sent = sock.sendto(packet, server_address)

    # Here I would need the timer to start, but it interrupts my algorithm.
    # (I have tried sched, but it didn't work)
    print('START:', time.time())
    scheduler.enter(3, 1, timeout, (slidingWindowSize,))
    #scheduler.run() -> tried to use it but it interrupted the algorithm

    for j in range(slidingWindowSize):
        # Receive response
        print('waiting to receive')
        data, server = sock.recvfrom(4097)
        print('received {!r}'.format(data))

    slidingWindowSize = slidingWindowSize * 2
    time.sleep(2)

sock.close()

What should I change in my code so that the timer won't stop the application from working and when it reaches timeout it sets slidingWindowSize to 1 again?
I have to implement the AIMD protocol where I will send the quantity of packets of my sliding window to other server, and while I don't lose any packet in the communication between a client and a server or the timer doesn't run out I will be increasing my sliding window.
All timers that I have found stop the application, I need a timer that starts counting while the application is working and when it reaches timeout or the application loses packets, sets the sliding window to 1 again.
Yes it will run forever..., but that is the objective, to analize the packet loss.
Thanks!


text:
Q: How can I call gmail api's method without authentication everytime? I want to use access token instead of authorization. I have get my token and stored it in local storage. Now I am saying, if user has token then do not need of authorization. just call the required method. But it says "API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication". How can I use access token in every Gmail method calling. Like for adding label, getting email messages in my DOM and all this stuff.
In short, I wanna get rid of every time authentication.

A: Normally with authorization flow we use something called a refresh token to enable applications to request a new access token when the user is offline or the user returns after being away from the application.   This is not possible with implicit flow.
Implicit flow is defined in The OAuth 2.0 Authorization Framework

The implicit grant type is used to obtain access tokens (it does not
support the issuance of refresh tokens) and is optimized for public
clients known to operate a particular redirection URI.  These clients
are typically implemented in a browser using a scripting language
such as JavaScript.

Client side JavaScript uses implicit flow there is no other option, the user will need to authorize your application every time they want to use it.
Official example.
The official Gmail JavaScript quick start will walk you though how to access this api.  The client library handles all the interaction between your application and the authorization server for you so you wont need to worry about where to apply the access token.
<!DOCTYPE html>

    <title>Gmail API Quickstart</title>
    <meta charset="utf-8" />

Gmail API Quickstart

    <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
    <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>


text:
Q: Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions? For example,
If I have 2 modules try1.js and try2.js
try1.js
   module.exports.msg = "hello world";

try2.js
   try1 = require('./try1');
   try1.msg = "changed message";

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

A: There is no copy at all made.  module.exports is an object and that object is shared directly.  If you modify properties on that object, then all who have loaded that module will see those changes.

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

Yes, it does.  There are no copies.  The exports object is shared directly.  Any changes you make to that exported object will be seen by all who are using that module.
FYI, a module could use Object.freeze(module.exports) to prevent changes to that object after the desired properties are added.

A: Yes, it affects it. Try doing the following. Save this code to a file m1.js:
module.exports.msg = 'hello world';

module.exports.prn = function() {
    console.log( module.exports.msg );
}

Then run the node console and try the following:
> const m1 = require('./m1')
undefined
> m1.prn()
xxx
> m1.msg = 'changed'
'changed'
> m1.prn()
changed


text:
Q: MongoDB - filter condition and 3-deep objects I need to get all the docs where translations.proposedTranslation exists, but translations.proposedTranslation.translator doesn't, in at least one of the objects in the translations array.
These docs should be selected:
{
    translations: [{
        language: "spanish",
        proposedTranslation: {
            user: "123456789"
        }
    }]
}
//and
{
    translations: [{
        language: "spanish",
        proposedTranslation: {
            user: "123456789"
        }
    }, {
        language: "french",
        proposedTranslation: {
            user: "123456789",
            translator: "987654321"
        }
    }]
}

This one should not:
{
    translations: [{
        language: "spanish",
        proposedTranslation: {
            user: "123456789",
            translator: "987654321"
        }
    }]
}

Here's what I have so far:
$expr: {
    $gte: [
        {
            $size: {
                $filter: {
                    input: "$translations",
                    cond: {
                        $and: [
                            {
                                $ne: ["$$this.proposedTranslation", null]
                            },
                            {
                                $eq: ["$$this.proposedTranslation.translator", null]
                            }
                        ]
                    }
                }
            }
        },
        1
    ]
}

However, this returns no docs. I think it's because of $eq: ["$$this.proposedTranslation.translator", null], since it works as it should if I omit that line. Is there something I need to change since it's a 3-deep object?

A: Here's what fixed it for me, since I found out that the problem was actually the way I was checking if a field is null or not:
$expr: {
    $gte: [
        {
            $size: {
                $filter: {
                    input: "$translations",
                    cond: {
                        $and: [
                            {
                                $ifNull: ["$$this.proposedTranslation", false]
                            },
                            {
                                $not: [{ $ifNull: ["$$this.proposedTranslation.translator", false] }]
                            }
                        ]
                    }
                }
            }
        },
        1
    ]
}


text:
Q: mariadb cluster synced but one node shows size=0 I use mariadb 10.5 with galera 4. I have a 3 node cluster which worked perfectly for the past 6 months. Lately I have been having problems with very cpu intensive query and had to kill that process. One of the nodes (n1) went out of sync so I recreated it. Everything synced perfectly but since that day n1 shows wsrep_cluster_size=0 and the rest of them show wsrep_cluster_size=3.
After a couple of days I decided to stop n2 and n3 to recreate it from n1. Again everything went smoothly but now n3 shows wsrep_cluster_size=0 and n1,n2 show wsrep_cluster_size=3.
I have no idea what's going on. I've checked all the logs and manually checked all the tables and everything seems ok. Data is synced and database is working just fine.
Heres is my configuration
[mysqld]

binlog_format                       = ROW
bind-address                        = 0.0.0.0

# Galera Provider Configuration

wsrep_on                            = ON
wsrep_provider                      = /usr/lib/galera/libgalera_smm.so

# Galera Cluster Configuration
wsrep_cluster_name                  = cluser

wsrep_cluster_address               = gcomm://10.0.0.2,10.0.0.3,10.0.0.4
wsrep_node_address                  = 10.0.0.2
wsrep_node_name                     = n1

# Galera Synchronization Configuration

wsrep_sst_method                    = rsync

log_error                           = /var/lib/mysql/node.log

default_storage_engine              = InnoDB
innodb_autoinc_lock_mode            = 2
innodb_locks_unsafe_for_binlog      = 1
innodb_file_per_table               = 1
#innodb_thread_concurrency          = 0
innodb_buffer_pool_size             = 10G
#innodb_log_buffer_size             = 64M
innodb_flush_method                 = O_DIRECT
innodb_log_file_size                = 2G
innodb_log_files_in_group           = 2
wsrep_slave_threads                 = 5
innodb_locks_unsafe_for_binlog      = 1
innodb_autoinc_lock_mode            = 2

skip-name-resolve

lc-messages-dir                     = /usr/share/mysql
skip-external-locking
key_buffer_size                     = 16M
max_connections                     = 300
wait_timeout                = 20
max_allowed_packet                  = 16M
thread_stack                        = 192K
thread_cache_size                   = 8

# * Query Cache Configuration
#
query_cache_limit                   = 1M
query_cache_size                    = 16M

expire_logs_days                    = 10
max_binlog_size                     = 100M

Here is my SHOW STATUS LIKE 'wsrep%' for 3 nodes
https://pastebin.com/GXj0c38R
And logs
https://pastebin.com/YxJBcguK

A: This is definitely a bug. Please report it on MariaDB JIRA.
In addition to the wsrep_cluster_size=0 on n3, wsrep_cluster_conf_id is uninitialised (and not the 23 like other nodes) and wsrep_cluster_state_uuid is blank.
For a synced node I'd expect these to have consistent values on all nodes.


text:
Q: TFDMemTable and ListView I created a firemonkey (XE8) application.
My app reads data from XML file and populate a memTable from this. The memTable is binding a ´ListView´.
All works fine, but this process is very slow. I try using a progressbar, but when run the repeat loop, "freezes the application" and back to work when the ListView is completely filled.
How I can fix this?
Code:
procedure TForm2.layoutCatalogoClick(Sender: TObject);
var
Node: IXMLNode;
auxValor :Double;
begin
Label2.Visible := True;

mmtListaProdutos.Close;
mmtListaProdutos.CreateDataSet;
mmtListaProdutos.Open;

XMLDocument1.FileName := 'C:\dados\xml.xml';
XMLDocument1.Active := true;

Node := XMLDocument1.DocumentElement.ChildNodes.FindNode('produto');
Node.ChildNodes.First;

ProgressBar1.Max := node.ChildNodes.Count;
ProgressBar1.Value := 0;

repeat

  ProgressBar1.Value := ProgressBar1.Value + 1;
  auxValor := StrToFloat(Node.ChildNodes['valor_preco_a'].Text);

  mmtListaProdutos.Append;
  mmtListaProdutoscodigo.AsString := Node.ChildNodes['codigo'].Text;
  mmtListaProdutosdescricao.AsString := Node.ChildNodes['descricao'].Text;
  mmtListaProdutosreferencia.AsString := Node.ChildNodes['referencia'].Text;
  mmtListaProdutoscodigo_EAN.AsString := Node.ChildNodes['codigo_EAN'].Text;
  mmtListaProdutosgrupo.AsString := Node.ChildNodes['grupo'].Text;
  mmtListaProdutosfornecedor.AsString := Node.ChildNodes['fornecedor'].Text;
  mmtListaProdutosmarca.AsString := Node.ChildNodes['marca'].Text;
  mmtListaProdutosunidade.AsString := Node.ChildNodes['unidade'].Text;
  mmtListaProdutosvalidade.AsString := Node.ChildNodes['validade'].Text;
  mmtListaProdutosvalor_preco_a.AsString := Node.ChildNodes['valor_preco_a'].Text;
  mmtListaProdutosvalor_preco_b.AsString := Node.ChildNodes['valor_preco_b'].Text;
  mmtListaProdutosaltura.AsString := Node.ChildNodes['altura'].Text;
  mmtListaProdutoscomprimento.AsString := Node.ChildNodes['comprimento'].Text;
  mmtListaProdutoslargura.AsString := Node.ChildNodes['largura'].Text;
  mmtListaProdutoscodDesc.AsString := Node.ChildNodes['codigo'].Text + ' | ' + Node.ChildNodes['descricao'].Text;
  mmtListaProdutosvalorUnd.AsString := 'R$ ' + FormatFloat('#.00', auxValor) + ' / ' + Node.ChildNodes['unidade'].Text;
  mmtListaProdutosmarcaFornec.AsString := Node.ChildNodes['marca'].Text;
  mmtListaProdutos.Post;

  Node := Node.NextSibling;

until Node = nil;
mmtListaProdutos.First;

pnlListaProdutos.Visible := True;
pnlPrincipal.Visible := False;
end;

A: Live Binding is not quick, especially when a multi-row GUI component like a listview is involved. And loading the data into the dataset via the listview is a particularly inefficient way of doing it.
What I'd try is disconnecting the bindings (in code) from the FDMemTable, loading the data directly into the FDMemTable, rather than into the listview, and then re-connecting the bindings to the FDMemTable.


text:
Q: Create a drop down from values in a database with PHP in a WordPress page I multiple forms on various pages of a WordPress site that all have the same drop down menu.  Rather than update all the values in every select each time they change, I have created a table in my WordPress database that is populated with the source names.  I am attempting to use PHP in the WordPress pages in order to display the drop down, but am encountering issues.  Below is the code I am using for the drop down within the HTML form on the various pages.
<?php

echo "<select id=\"source\" style=\"max-width: 165px;\" name=\"source\">";
echo "<option value=\"\">Please select...</option>";
global $wpdb;
$wp_source = $wpdb->get_results("SELECT * FROM wp_source;");

foreach($wp_source as $table){
echo "<option value=\"" . $table->name . "\">" . $table->name . "</option>";
}

echo "<option id=\"other\" value=\"other\">Other</option>";
echo "</select>";

?>

The table name is wp_source and I am using a Plugin named Exec-PHP which allows a user to utilize PHP within WordPress posts/pages/widgets/etc.  What I am seeing in my drop down is the following text:  name."\">".$table->name."  Any assistance you might offer would be greatly appreciated.

A: I did something like this using Javascript. Pass your data into the function and create an array called wp_source.
list = document.getElementById("source");
for (i=0; i < wp_source.length; ++i)
  {
     option = document.createElement("option");
     option.text = numbers[i];
     list.add(option);
  }


text:
Q: asp-for in partial view does not generate proper id name I am working with a page calling a partial view and using a model that have child objects such as Model.Child1.Child2.
My issue is that when I am passing data using the model="Model.Child1" then the Id generated are only showing the Child1 Id without including the Id of the Father. Please see below the more detailed explanation.
@page
@model IndexModel

<partial name="_SelectGamesPartial.cshtml" model="Model.Input.SelectGamesViewModel" />

The IndexModel is a PageModel that contains an object to get the data on the page called Input which contains another ViewModel called SelectGamesViewModel.
public partial class IndexModel : PageModel
    {
        [BindProperty]
        public InputModel Input { get; set; }
        public class InputModel
        {
            [Required]
            public string NickName { get; set; }

            public SelectGamesViewModel SelectGamesViewModel { get; set; }
        }

The SelectGamesViewModel is as follow
public class SelectGamesViewModel
{
        public int? GameIdSelected { get; set; }

        public IList<int> GamesIdAdded { get; set; }
}

My issue is when i pass the second view model to the partial view it doesn't map the data to the Input view.
@page
@model IndexModel

<partial name="_SelectGamesPartial.cshtml" model="Model.Input.SelectGamesViewModel" />

I  think the id that should have been generated in the partial view with the asp-for should have been something like this (id=Input.SelectGamesViewModel.GameIdSelected) but instead it just write (id=GameIdSelected)
<input asp-for="Model.GameIdSelected" />

How do you pass the model to the partial view and make sure the id is properly generated ? so the binding is happening.

A:
I think the id that should have been generated in the partial view with the asp-for should have been something like this (id=Input.SelectGamesViewModel.GameIdSelected) but instead it just write (id=GameIdSelected)

Firstly, asp-for generated the id Input_SelectGamesViewModel_GameIdSelected and the name is Input.SelectGamesViewModel.GameIdSelected.
Refer to:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-5.0#navigating-child-properties
Then, you use asp-for="Model.GameIdSelected" which causes the id=GameIdSelected.So you need change your code like below:
Index.cshtml:
@page
@model IndexModel

<partial name="_SelectGamesPartial.cshtml" model="Model" />

_SelectGamesPartial.cshtml:
@model IndexModel
<input asp-for="@Model.Input.SelectGamesViewModel.GameIdSelected" />

Result:


text:
Q: Add syntax to JavaScript with Clojure I want to add new syntax to my JavaScript files much like Sweet.js, but using Clojure/ClojureScript to do the transformation.
Here is what I would like to do:
//original

specialFunction add(a, b) {
   return a + b;
}

//transformed

function add(a, b) {
   return a + b;
}
registerSpecialFunction({
   name: "add",
   args: ["a", "b"],
   func: add
});

Correct me if I'm wrong, but I think it would work best by:

*

*parse the JS file into an AST

*do the transformation

*print the resulting AST back out as JavaScript

Any idea on how to do parts 1 and 3? Do I even have the right idea here?

A: Just as a heads up, this may be a non-trivial task, but probably a great learning exercise.
You'll have to re-implement the concept or macros from Sweet.js or the idea of custom parser extensions from Babylon (parser for Babel) if you want the same control from Clojure.
Either way, you'll need to write a parser that understands a superset of JavaScript's syntax. You might want to look at parser generators such as instaparse (Clojure) and peg.js (JavaScript).
Then you need to decide whether you want to make a fixed number of additions to the language grammar (like Babel) or allow macros to define their own grammar extensions/replacement rules (like Sweet.js). At this point, you'll need to write some kind of engine for transforming the AST generated by your parser.
Macros can be implemented in a number of ways, everything from replacement rules like you'd find in C and C++ to full blown compile-time evaluated functions that work directly with the AST like you'd find in Clojure.
After parsing and transforming the AST with this new tool, you'll need to transform it into a valid JavaScript AST. It'll make things easier to maintain compatibility with the ESTree specification as this will allow you to use tools like escodegen to actually generate the JavaScript code from the AST itself.
Of course, piggybacking tools like peg.js and escodegen is only possible if you're writing your tool as ClojureScript and compiling and running it against NodeJS. The other option is to find compatible tools within the JVM ecosystem and use them with JVM compiled Clojure instead.
The JavaScript ecosystem has a range of good tools available for parsing, transforming and generating ES code (have a look through the Babel packages for example/inspiration) but you'll have to remember that if you are writing ClojureScript and running it under Node, you are in fact creating a JavaScript executable and it might have just been easier to start with JavaScript in the first place.


text:
Q: Unable to import tensorflow in Python Edit: This seems to be a problem in some versions of Windows. I tried the same in Linux OS and it finally worked.
Inside my virtual environment, I installed tensorflow. Then tried to import it into python, but ImportError.
I've tried ALL hacks available on the internet, but none of them seem to work for me. Please help.

*

*Tried downloading necessary DLLs (in system32 folder)

*Tried changing environment path variable

*Tried uninstalling and reinstalling Python and tensorflow in various ways

*Tried upgrading setup tools

Basic import command
E:\tensor1>myenv\Scripts\activate.bat

(myenv) E:\tensor1>python

>>> import tensorflow

Whatever I try, this error is relentlessly showing up:
Traceback (most recent call last):
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow.p
y", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow_i
nternal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow_i
nternal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\samiam\AppData\Local\Programs\Python\Python37\lib\imp.py", line
 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\samiam\AppData\Local\Programs\Python\Python37\lib\imp.py", line
 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\__init__.py", line 28, in
<module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\__init__.py", line
49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow.p
y", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow.p
y", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow_i
nternal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "E:\tensor1\myenv\lib\site-packages\tensorflow\python\pywrap_tensorflow_i
nternal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\samiam\AppData\Local\Programs\Python\Python37\lib\imp.py", line
 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\samiam\AppData\Local\Programs\Python\Python37\lib\imp.py", line
 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

Failed to load the native TensorFlow runtime.


text:
Q: How to add select_from_array in Backpack for Laravel page/create I want to add a dropdown field picking up an array from config file. I have tried this but getting an error.
In config/gallery.php:
return [
    'column_num' => [
         ''=>'-- Choose one --',
         'one' => 'Category: One column',
         'one-second'=> 'Category: Two columns',
         'one-third'=> 'Category: Three columns',
         'one-fourth'=> 'Category: Four columns',
         'one-fifth'=> 'Category: Five columns',
         'one-sixth'=> 'Category: Six columns',
    ],
];

In app/PageTemplates.php
...
    $this->crud->addField([
                    'name' => 'column_num',
                    'label' => 'Number of columns',
                    'type' => 'select_from_array',
                    'options' => config('gallery.column_num'),
                    'fake' => true,
                    'store_in' => 'extras',
                ]);

====== UPDATE =====
Error:

ErrorException in a1e88af9db4bb80b9055323bf64be621df2f9960.php line
  19: Undefined index: value (View:
  /Users/sokada/Code/backpack-ceci/vendor/backpack/crud/src/resources/views/fields/select_from_array.blade.php)
  (View:
  /Users/sokada/Code/backpack-ceci/vendor/backpack/crud/src/resources/views/fields/select_from_array.blade.php)
  (View:
  /Users/sokada/Code/backpack-
  ceci/vendor/backpack/crud/src/resources/views/fields/select_from_array.blade.php)
  in a1e88af9db4bb80b9055323bf64be621df2f9960.php line 19 at
  CompilerEngine->handleViewException(object(ErrorException), '1') in
  PhpEngine.php line 44 at

I tried this as in the doc, but it still gives an error.
$this->crud->addField([
    // select_from_array
    'name' => 'template',
    'label' => "Template",
    'type' => 'select_from_array',
    'options' => ['one' => 'One', 'two' => 'Two'],
    'allows_null' => false,
    // 'allows_multiple' => true, // OPTIONAL; needs you to cast this to array in your model;
]);

Error

ErrorException in PageTemplates.php line 114: Use of undefined
  constant 'one' - assumed ''one'' in PageTemplates.php line 114 at
  HandleExceptions->handleError('8', 'Use of undefined constant 'one' -
  assumed ''one''',
  '/Users/sokada/Code/backpack-ceci/app/PageTemplates.php', '114',
  array()) in PageTemplates.php line 114

It is something to do with this if statement.
 <option value="{{ $key }}"
    @if ((isset($field['value']) && $key==$field['value'])
       || ( ! is_null( old($field['name']) ) && old($field['name']) == $key)
       || (is_array($field['value']) && in_array($key, $field['value'])) )
        selected
    @endif
 >{{ $value }}</option>

A: For the moment I needed to modify @foreach statement in vendor/backpack/crud/src/resources/views/fields/select_from_array.blade.php to the following to avoid error.
        @if (count($field['options']))
            @foreach ($field['options'] as $key => $value)
                <option value="{{ $key }}"
                    @if ((isset($field['value']) && $key==$field['value'])
                        || ( ! is_null( old($field['name']) ) && old($field['name']) == $key)
                      )
                         selected
                    @endif
                >{{ $value }}</option>
            @endforeach
        @endif

I hope tabacitu will figure it out a better solution.

A: I know that this is an "old" question but I ran into the same error and solved it with this code:

'options' => [0 => "Blocked", 1 => "OK", 2 => "Proxy", 3 => "DNS"],


text:
Q: How to make a Non-scrollable ListView with dynamic number of rows based on the number of items The Problem
I have unknown number of square icons of the same size that should be displayed in a horizontal list however in case the number icons exceed a certain number the new icons should be displayed in the new row, and in case I have 1 item it should be displayed at the center it should be displayed at the center not at the left.
So this for example if I have 4 items.

If I have 5 items and the screen is already filled with 4, the 5th item should be displayed in the next row and centered.

A: There is no need to use ListView for that. If you can fix the number of items in a single row say 5, then you simply have a RelativeLayout and add your items to that dyanmically.For eg. like this.
RelativeLayout rl_attendingLayout=new RelativeLayout(yourActivity.this);

for (int i = 0; i < numberOfImages; i++) {
        ImageView temp = new ImageView(yourActivity.this);

        temp.setScaleType(ScaleType.CENTER_CROP);
        temp.setId(i + 1);
        temp.setTag(Integer.valueOf(i + 1));

        // set Image to ImageView

        RelativeLayout.LayoutParams attendingParams = new RelativeLayout.LayoutParams(
                imagewidth, imagewidth);
        if (i >= 5) {
            attendingParams.addRule(RelativeLayout.BELOW, (i % 5)
                    + (int) (5 * ((i / 5) - 1)) + 1);
            if (i % 5 > 0) {
                attendingParams.addRule(RelativeLayout.RIGHT_OF, i);
            }
        } else {
            if (i > 0) {
                attendingParams.addRule(RelativeLayout.RIGHT_OF, i);
            } else {
                attendingParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                attendingParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            }
        }

        attendingParams.setMargins(margin, 0, 0, margin);
        temp.setLayoutParams(attendingParams);

        rl_attendingLayout.addView(temp);
    }


text:
Q: Picard group of derived category of sheaves Let $X$ be a topological space and $R$ be a commutative ring with unit, $D(X,R)$ is the derived category of unbounded complexes of sheaves of $R$-modules. Moreover we suppose that $X$ is a stratified space and $D_c(X,R)\subset D(X,R)$ is the derived category of complexes of sheaves with constructible cohomology sheaves. The categories $D(X,R)$ and $D_c(X,R)$ are both closed symmetric monoidal categories, thus we can speak of their Picard groups as the group of isomorphism classes of invertible objects for the derived tensor product.
I was wondering if we know some computations of the Picard group of $D(X,R)$ or of $D_c(X,R)$?

A: Thanks to Drew Heard's comment I was able to find answers to my questions. In his paper "Picard groups of derived categories" H. Fausk proves the following theorem (see Theorem 4.2).
Theorem: Let $(\mathcal{E},\mathcal{O})$ be a commutative unital ringed Grothendieck topos with enough points such that for all points $p$
of $\mathcal{E}$ the ring $\mathcal{O}_p$ has a connected prime
ideal spectrum. Then there is a natural split short exact sequence:
$$0\rightarrow Pic(\mathcal{O}-Mod)\rightarrow Pic(D(\mathcal{O}-Mod))\rightarrow C(pt(\mathcal{E}))\rightarrow 0$$
Let us apply this theorem to the case of a connected and locally connected topological space $X$, together with the constant sheaf $\underline{R}$ (i.e. $\mathcal{O}=\underline{R}$) and let us suppose that $R$ is an integral domain (its prime ideal spectrum is connected), then we have the corollaries.
Corollary A: We have a split short exact sequence
$$0\rightarrow Pic(\underline{R}-Mod)\rightarrow Pic(D(X,R))\rightarrow \mathbb{Z}\rightarrow 0$$where the section is the morphism that sends the integer $n\in\mathbb{Z}$ to the constant sheaf $\underline{R}[n]$.
Corollary B: Moreover if $X$ is stratified then we have a split short exact sequence
$$0\rightarrow Pic(\underline{R}-Mod_c)\rightarrow Pic(D_c(X,R))\rightarrow \mathbb{Z}\rightarrow 0$$ where $\underline{R}-Mod_c$ is the category of constructible sheaves of $\underline{R}$-modules.
Let us look to the case of a point then we have a split short exact sequence (with the hypothesis that $Spec(R)$ connected):
$$0\rightarrow Pic(R)\rightarrow Pic(D(R)) \rightarrow \mathbb{Z}\rightarrow 0.$$


text:
Q: How do I navigate from Algolia search results to the specific page? How do I navigate to the search results shown by Algolia?
Do I have to give each item (in this instance 15 different articles) a different key?
I can only figure out how to make it navigate to a specific article, and not an article based on which search result that got clicked on.
import React from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity } from 'react-native';
import { connectInfiniteHits } from 'react-instantsearch-native';
import PropTypes from 'prop-types';
import { useNavigation } from '@react-navigation/native';

const InfiniteHits = ({ hits, hasMore, refineNext, }) => {

  const navigation = useNavigation()

 return(
    <View style={styles.container}>
      <FlatList
        data={hits}
        numColumns={2}
        keyExtractor={item => item.objectID}
        onEndReached={() => hasMore && refineNext()}
        renderItem={(({ item }, index) => (
            <TouchableOpacity
            onPress={() => navigation.navigate('Articles',{item})}
            style={styles.item}>
              <View style={TextBoxes.scrollcontainer}>
              <View style={TextBoxes.boxes} key={index} >
                <Text key={index} style={TextBoxes.style} hit={item}>
                  {item.title}
                </Text>
              </View>
            </View>
            </TouchableOpacity>
          ))}
      />
    </View>
  )
};

InfiniteHits.propTypes = {
  hits: PropTypes.arrayOf(PropTypes.object).isRequired,
  hasMore: PropTypes.bool.isRequired,
  refineNext: PropTypes.func.isRequired,
};

export default connectInfiniteHits(InfiniteHits);

A: Based on your code, the item.objectID of the article in your Algolia index record should be the unique ID needed by the Articles screen to retrieve and render the appropriate article.
If not, you may need to re-index with that value as the objectID or inject an additional attribute with the value you need to pass to the Articles screen for to render that article.


text:
Q: How to configure ELMAH to show log just for Sitecore user I added Elmah tool to my Sitecore Solution, actually I did it like here
http://newguid.net/sitecore/2011/using-elmah-for-error-logging-within-sitecore/
Just one rolls I have enabled is allowRemoteAccess property,
<elmah>
<security allowRemoteAccess="1" />
</elmah>

Now logs available for every one from any place, but I want to show it just for user who is login (authorized) to sitecore (sitecore users)
How I can mange it ?
Thanks.

A: Not sure what Elmah had built in now, but I used to do this:
<location path="elmah.axd">
    <system.web>
        <authorization>
            <allow roles="SITECORE_USERS"/> <!---put your role here-->
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

Securing Elmah RSS Feeds in ASP.NET website

A: I found solution after research of elmah source code and this article http://dotnetslackers.com/articles/aspnet/Securing-ELMAH-with-Independent-HTTP-Authentication.aspx. User can implement IRequestAuthorizationHandler for custom IHttpModule
I did next:
 public class SitecoreAuthModule :IHttpModule, IRequestAuthorizationHandler
{
    public bool Authorize(HttpContext context)
    {
        return SC.Context.User.IsAdministrator;
    }

    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += new EventHandler(ContextAuthenticateRequest); ;
    }

    void ContextAuthenticateRequest(object sender, EventArgs e)
    {
        var context = sender as HttpApplication;
        if (context.Request.Path.IndexOf("elmah.axd",
            StringComparison.InvariantCultureIgnoreCase) < 0)
            return;
    }

    public void Dispose()
    {

    }
}


text:
Q: How do I retrieve automatically generated ID values when adding rows to multiple tables using a stored procedure? I'm currently working on a database design for a Gym in SQL Server (ERD at following link: https://1drv.ms/u/s!ApYj_1gaRPZGgnjOj6VC_HgeaenU).
As part of this I need to be able to create a new member and their first program via a stored procedure. The issue I'm facing is that in order to create a new program, I first need the member number which is automatically generated when a row is added to the Member table, and in order to create a new member, I need to have a payment ID which is automatically generated when a row is added to the payment table.
How do I retrieve the automatically generated identity values in a single stored procedure? i.e. the only way I can see to do this at the moment is to first create a stored procedure to create a row in the Payment table, then manually look the PaymentID value up and then use this value in a separate stored procedure for inserting a row in the Member table (and same again for setting up a new Program).
See below the 3 separate stored procedures I have currently for this, any help would be greatly appreciated.
CREATE PROCEDURE NewPayment
    @PaymentType varchar(10),
    @LastPaymentDate date,
    @AmountPaid varchar(15),
    @NextPaymentDate date,
    @AmountDue varchar(15)
AS
    INSERT INTO Payment
    VALUES (@PaymentType, @LastPaymentDate, @AmountPaid, @NextPaymentDate, @AmountDue);

    IF @@ERROR <> 0
       RETURN -1
    ELSE
       RETURN 0
GO

CREATE PROCEDURE NewMember
    @Name varchar(100),
    @Address varchar(200),
    @ContactNo varchar(15),
    @Email varchar(50),
    @Photo image,
    @PaymentID int,
    @GDPRQ1 char(1),
    @GDPRQ2 char(1),
    @IsDeleted char(1)
AS
    INSERT INTO Members
    VALUES (@Name, @Address, @ContactNo, @Email, @Photo, @PaymentID, @GDPRQ1, @GDPRQ2, @IsDeleted);

    IF @@ERROR <> 0
       RETURN -1
    ELSE
       RETURN 0
GO

CREATE PROCEDURE NewProgram
    @MemberNumber int,
    @TrainerID int,
    @ProgramStartDate date,
    @TrainerReviewDate date,
    @Active char(1)
AS
    INSERT INTO Program
    VALUES (@MemberNumber, @TrainerID, @ProgramStartDate, @TrainerReviewDate, @Active);

  [1]: https://i.stack.imgur.com/ERuFS.png

A: You need to return the value from the stored procedure.  As a general rule, I recommend using the output clause for this:
create proc NewMember (
    @Name varchar(100),
    @Address varchar(200),
    @ContactNo varchar(15),
    @Email varchar(50),
    @Photo image,
    @PaymentID int,
    @GDPRQ1 char(1),
    @GDPRQ2 char(1),
    @IsDeleted char(1),
    @MemberId_out int output
) As
begin
    declare table @id (memberid int)
    Insert into Members
        output inserted.memberid into @id
        values (@Name, @Address, @ContactNo ,@Email, @Photo, @PaymentID, @GDPRQ1,@GDPRQ2, @IsDeleted);

    select @MemberId_out = memberid from @id;

    return 0
end;

The use of @@ERROR seems awkward to me (which is one reason I removed it).  If you really want to handle errors, then you want to be using TRY/CATCH blocks.
.


text:
Q: boot2docker: bootlocal.sh not executing I'm trying to do some customization on my boot2docker vm, and from what I can tell, I should be able to add a file: /var/lib/boot2docker/bootlocal.sh which should be executed when boot2docker starts, but it never seems to execute.
Here's my bootlocal.sh just to try to get it working:
!/bin/sh

echo 'testing bootlocal'
touch /var/lib/boot2docker/testfile

And I'm running boot2docker on OSX with this version info:
$ boot2docker version
Boot2Docker-cli version: v1.4.1
Git commit: 43241cb

I've also run chmod +x /var/lib/boot2docker/bootlocal.sh in case that script needs to be made executable.
I've tried both boot2docker restart and boot2docker down/up
Any idea what I may be missing?

A: You need to set up a persistence partition with the volume name boot2docker-data.

*

*Add a new virtual disk to your VM.

*Create a new partition on the virtual disk using fdisk.

*Format the partition as ext4 - mkfs.ext4 -L boot2docker-data /dev/sdX1

*Reboot boot2docker and it will pick up the persistence partition.

A: Adding to @Ben's answer and to clarify @jaycode's question on the comments
Its probably late, but here is my answer for windows 7.
To mount a folder from windows7 to the Docker-machine vm use the folowing command. Note that the docker machine shouldn't be running at this point.
You have to locate your installation of Oracle Virtual box that comes along with Docker-tools. Mine is at C:/Program Files/Oracle/VirtualBox/VBoxManage so replace it with your location.
 default is the name of the docker-machine to which the volume is mounted and E:/vm is the folder on the Windows7 machine that is to be shared with the docker-machine.
C:/Program Files/Oracle/VirtualBox/VBoxManage sharedfolder add default -name win_share -hostpath E:/vm

Now you can ssh into the docker-machine with:
docker-machine ssh default

Then perform the mount:
Make a folder inside the VM:
sudo mkdir /vm

Mount the Windows folder to it:
sudo mount -t vboxsf win_share /vm

After that, you can access E:/vm inside your Docker-machine:
You can refer
https://stackoverflow.com/a/30865500/4396129


text:
Q: jQuery HTML to JSON, including href attribute I have data in markup like this:

Lorem

     2:15
     3:17-19
     3:19

Ipsum

     10:18
     10:27
     10:28

I'd like to convert it to a JSON object like this:
{
    "Lorem": {
        "prin.v.ii.ii.html": "2:15",
        "prin.v.i.v.html": "3:17-19",
        "prin.v.v.html": "3:19"
    },
    "Ipsum": {
        "sec.vii.xxii.html": "10:18",
        "sec.vii.ix.html": "10:27",
        "sec.vii.xxiii.html": "10:28"
    }
}

I've seen some HTML to JSON solutions here but none that I can find that deal with attributes. I know it might be easier if the markup had ul's but it doesn't. How could I convert this?

A: Pretty easily, I should think. Here's some example code in jQuery-flavored Javascript, but you can adjust to taste with the DOM traverser and JSON library in your language of choice. (For example, in Perl, you'd use the HTML::TreeBuilder and JSON modules.)
var json_obj = {};
$('p.bbook').each(function(i,el) {
    var which = $(el).text();
    var refs = {};
    $(el).next('p.bref').find('a.ref').each(function(i,el) {
        var href = $(el).attr('href');
        var chapter_verse = $(el).text();
        refs[href] = chapter_verse;
    });
    json_obj[which] = refs;
});
var json_result = JSON.stringify(json_obj);

At this point, json_result contains a JSON string whose contents match what you describe in your question.

A: Use $.parseJSON() and $.each() from the jQuery framework. Here an exemple :
$(document).ready(function () {
    var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
    var lang = '';
    var obj = $.parseJSON(jsonp);
    $.each(obj, function () {
        lang += this['Lang'] + "
";
    });
    $('span').html(lang);
});

A: I think you should take a look at Beautiful Soup 4.
Start a Python script, feed the html to the soup, and you should be able to get whatever you want into a dictionary, and use json.dumps() at the end to get your JSON.
# import/install bs4, json (already included)
end_json = {}

soup = BeautifulSoup(html_string)
books = soup.findAll('p', class='bbook')
for book in books:
    # etc, etc

Edit: Don't know how I missed the JQuery in the question title, but BS4 is awesome.

A: http://jsfiddle.net/wDjhJ/
var result = {};
$('.bbook').each(function(a,b){
    var $this = $(b);
    result[$this.text()] = {};
    $this.next().find('a').each(function(k,v){
        var item = $(v);
        result[$this.text()][item.attr('href')] = item.text();
    });
});

$('body').append(JSON.stringify(result));

Traverse the dom with a couple of loops.

A: jsFiddle
$(document).ready(function() {
    var O = {}, el, key, a;
    $('.bbook').each(function(index, value) {
        el = $(value);
        key = el.text();
        O[key] = {};
        el.next().find('a').each(function(i, v) {
            a = $(v);
            O[key][a.attr('href')] = a.text();
        });
    });

    console.log(JSON.stringify(O));
});


text:
Q: Capturing SIGTERM signal Heroku So i finally found how to capture the signal from this site "https://pymotw.com/2/signal/" , I now can capture most of the kill signals like SIGINT, SIGUSR1, SIGUSR2.... all except the SIGTERM which heroku uses for some reason when I get a SIGTERM my script just exit instead of capturing the signal and do some work, Can Anyone tell me if I'm doing something wrong? I'm testing with the command "kill -INT $pid", i can capture every kill signals Except the SIGTERM, THANKS....
Code :
run = false
def receive_signal(signum, stack):
    print("Received:", signum)
    global run
    run = False

signal.signal(signal.SIGUSR1,receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)
signal.signal(signal.SIGINT, receive_signal)
signal.signal(signal.SIGTERM, receive_signal)

print("My PID is:", os.getpid())

while run:
      main()


text:
Q: Is every polynomial a limit of polynomials in quadratic variables? Let $d>0$ be even. Consider ${\mathbb{R}}[x_1,\ldots, x_n]_d$, i.e. polynomials of degree $d$.
Call a homogeneous polynomial $f$ of degree $d$ a polynomial in quadratic variables if it is of the form $f=p(y_1^2,\ldots, y_n^2)$ for some polynomial $p$. Here the $y_i=y_i(x_1,\ldots, x_n)$ are linear forms such that $\{y_1,\ldots, y_n\}$ is a basis of the degree 1 polynomials ${\mathbb{R}}[x_1,\ldots,x_n]_1$.
For example if we take $p(x,y)=5x^3y^4+(x-3y)^3$, and $x-y, x+y$ to be the linear polynomials, then this gives the example of $5(x-y)^6(x+y)^8+((x-y)^2-3(x+y)^2)^3$ $=5(x-y)^6(x+y)^8-(2x^2+8xy+2y^2)^3$ as an example of a polynomial in quadratic variables.
Is it true that polynomials in quadratic variables are dense in the vector space ${\mathbb{R}}[x_1,\ldots, x_n]_d$? In other words, it every polynomial of degree $d$ a limit of polynomials of degree $d$ in quadratic variables?
Edit: In response to Pete, Ewan's and Darij's comments, I will rephrase this question in terms of ring automorphisms. Firstly, let's ignore odd degree polynomials. In the language of linear change of variables, let $V$ be a real vector space space of dimension $n$. Consider the ring $\mathbb{R}[x_1^2,\ldots, x_n^2]$. Each choice of basis $\mathcal{B}=\{v_1,\ldots, v_n\}$ of the vector space $V$ induces a ring monomorphism $\mathcal{B}_*:\mathbb{R}[x_1^2,\ldots, x_n^2]\to Sym(V)$ to the symmetric algebra on $V$. This monomorphism is given by extending the map $x_i^2\mapsto v_i$.
Is every even degree element of $Sym(V)$ in the image of some induced monomorphism $\mathcal{B}_*$?

A: The dimension of the linear space of homogenous polynomials of degree $d$ is
$\binom{n+d-1}{d}$. The dimension of the space of homogenous polynomials of degree $d$ in squared linear variables is
$$\binom{n+d/2-1}{d/2} \cdot (n^2-1),$$
where $n^2-1 = \dim GL_n(\mathbb R)$. One easily see that if $d$ and $n$ are sufficiently large, then the dimension of the set of squared polynomials is too small to exhaust all homogenous polynomials of degree $d$. Indeed,
$$\binom{n+d/2-1}{d/2} \cdot (n^2-1) \leq \frac{(n-1)\cdot n \cdots (n+d/2-1)}{1 \cdot 2 \cdots d/2} \cdot n^2$$
$$< \frac{(n-1)\cdot n \cdots (n+d-1)}{1 \cdot 2 \cdots d} = \binom{n+d-1}{d}$$
if
$$n^2 < \frac{(n+d/2)\cdots (n+d-1)}{(d/2+1) \cdots d} = \prod_{k=1}^{d/2} \frac{n-1+d/2+k}{d/2+k}.$$
But the RHS equals
$$\prod_{k=1}^{d/2} \left( 1+\frac{n-1}{d/2+k} \right) \geq \left( 1+\frac{n-1}{d} \right)^{d/2} \sim \exp\left(\frac{n-1}2 \right)$$
for large $d$. So, if $n$ is large, we get $n^2 < \exp\left(\frac{n-1}2 \right) \leq \frac{(n+d/2)\cdots (n+d-1)}{(d/2+1) \cdots d}$ and this implies the claim.


text:
Q: How authenticate .net core app from angular client using identityserver4 My angular app is running on http://localhost:4200 and my .net core mvc app with integrated identityserver4 authentication is running on https://localhost:44312/
https://localhost:44312/connect/authorize?client_id=DocumentationGen&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fauthentication%2Flogin-callback&response_type=code&scope=DocumentationGenAPI%20openid%20profile&state=d9ecb6d546e147569672b85fb8239fc7&code_challenge=W78Reow6OnPtRs36FcieAc1-rUPfHSvE2rHWD9BpBYw&code_challenge_method=S256&prompt=none&response_mode=query

when I try to authenticate I am getting this below error
https://localhost:44312/home/error?errorId=CfDJ8B-i8u6rBkNAj3HnFY4JfcyXVNdYo37R9IxB3zFzX--WIeR89rnU7XNedmt_AHjo_HCw8Y04yrfDTxNnDud2_P2D_yNvqJyUhQrDp0iB_5njT13pYmY-a0N5jNdgMPYVHVY0hIF0aqx0KCkYJ9O_fga8djacA_78tizfFjWcN7mndsQxepe-Ox1UYdFHd_fuka86LaCL4JVeMA07r1NSG5LIOUv7RabIowsU0JHrbXR3NizS05-cdzsQDmFiVjl1DWfL0M3ba5y4ERSdbDFkLsay8xg4FiapvLCdcirWSkfzXnb3HPmgH9GYaBvMi0CVVQ1xn23ZRNcYTA5b4FO83kFwD-VVNi1u6YKc-PjUvFHw1InpFDXwtkl8zZWU_Iv6hg

A: After some research finally got the answer in this link
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-5.0

add this in your startup.cs file in order to authenticate from a different port
services.AddIdentityServer()
               .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
               {
                   options.Clients.AddSPA(
                       "client name", spa =>
                       spa.WithRedirectUri("http://localhost:4200/authentication/login-callback")
                          .WithLogoutRedirectUri(
                              "http://localhost:4200/authentication/logout-callback").WithClientId("ClientId"));
                });


text:
Q: nginx cannot connect to uwsgi in other container with docker-compose I use docker-compose and there are two containers, one for uwsgi and one for nginx. But it seems that nginx fails to connect uwsgi.
Here is the environment.
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.1 LTS
Release:        20.04
Codename:       focal
$ docker --version
Docker version 20.10.3, build 48d30b5
$ docker-compose --version
docker-compose version 1.24.0, build 0aa59064

Strangely, if I login to the nginx container and try to connect to the uwsgi manually, it succeeds as follows.
$ docker-compose ps --service
python
nginx
$ docker-compose exec nginx /bin/bash
# curl python:8001
success!

However, when I try to access uwsgi via nginx, it fails.
# curl localhost:8000/s

<title>404 Not Found</title>

404 Not Found

nginx/1.15.3

Here is my config. What is wrong with these? How can I fix this problem?
docker-compose.yml
version: '3'
services:
  nginx:
      image: nginx:1.15.3
      ports:
        - "80:8000"
      volumes:
        - ./nginx/nginx.conf:/etc/nginx/nginx.conf
        - ./python/uwsgi_params:/etc/nginx/uwsgi_params
        - .:/code
      depends_on:
        - python
  python:
      build: ./python
      ports:
        - "8001:8001"
      volumes:
        - ./proj:/code/proj
      command: bash -c "ls -l && cd proj && pwd && uwsgi --http :8001 --module fargate.wsgi --logto uwsgilog.txt"

nginx/nginx.conf
events {
        worker_connections 768;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
        gzip on;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

    upstream django {
        server python:8001;
    }
    server {
        listen       8000;
        server_name  localhost;
        root         /code/nginx/html;
        charset      utf-8;
        include /etc/nginx/default.d/*.conf;
        client_max_body_size 100M;

        location /static {
            alias /code/proj/static;
        }
        location ~ ^/s/(.*)$ {
        uwsgi_pass django;
        include /code/python/uwsgi_params;
        uwsgi_param SCRIPT_NAME /s;
        uwsgi_param PATH_INFO /$1;
        }
    }
}

python/Dockerfile
FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
RUN mkdir /code/python
WORKDIR /code
ADD . /code/python/
RUN pip install -r python/requirements.txt


text:
Q: Scala - how to pass Callback to a method I am trying to expose Java method via Scala (from Kafka: https://kafka.apache.org/10/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html). This is original Java method:
public void commitAsync(OffsetCommitCallback callback)

How to pass callback to a method in Scala? I have something like:
 def commitAsync() = {
    consumer.commitAsync(OffsetCommitCallback callback)
  }

Thanks.
Bonus points - how would look like a test for it e.g. using MockitoSugar?

A: You can handle the callback like this:
def commitAsync() = {
   consumer.commitAsync(new OffsetCommitCallback() {
      def onComplete(m: java.util.Map[TopicPartition, OffsetAndMetadata], e: Exception) {
        //...
      }
   })
}

OffsetCommitCallback is an interface, ("similar" as trait in Scala), so you can init an instance anonymously.
Here's is a quick apparition within Spark project.


text:
Q: Python - How do I get the window handle from my OWN application I am using win32gui.
With FindWindow and FindWindowEx I am able to get the handle of any window, resize, setpos etc. but how am I able to grab my own windows handle? I was not able to identify it using FindWindow and passing the class or title. Is there any other way?
In this example print will just print 0
(unrelated code removed)
import win32gui
import sys

class GUI(QMainWindow):
 def __init__(self, parent=None):

    super().__init__(parent)
    uic.loadUi('window.ui', self)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = GUI()
    win.show()

    mywindow = win32gui.FindWindow("QMainWindow",None)
    print ("My Window: ",mywindow)

    sys.exit(app.exec())

from my window.ui xml:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>My App</class>
<widget class="QMainWindow" name="QMainWindow">
[...]

EDIT: maybe winId()? But self.winId() and win.winId() return <PyQt6.sip.voidptr object at 0x000002B0[...]

A: I got it
[...]
winhandle = int(win.winId())
print("My Window: ",winhandle)

Still curious why it didn't work with FindWindow
edit: found out that PyQt Standart Window Class is MainWindow , without the Q.
So mywindow = win32gui.FindWindow("MainWindow",None) without the Q works.


text:
Q: How could Eratosthenes know the angle of the sun's rays in Alexandria? The measurement of the Earth's radius by Eratosthenes is famously the first of its kind. As I understand, it relies on the fact that the sun's rays are parallel. At noon, the light falls directly perpendicular to Earth's surface, which could easily be judged in the original experiment by checking the alignment of shadows in a deep well.
At the same time in Alexandria, a city several hundreds of kilometres away, it is not noon, but instead the sunlight falls at an angle from the normal. This angle is enough to calculate the Earth's diameter through some trigonometry.
My question is the following: before standardised clocks and fast communication was invented, how was it possible to tell the exact moment when the angle measurement was to be made? I'm imagining myself in Alexandria with a protractor. How do I know when it is noon in Syene and when I should make the measurement?

A:
How do I know when it is noon in Syene and when I should make the measurement?

They didn't need to know both the east-west and north-south angles at the two locations, either one of those would do.
So they simply measured the north-south angle at local noon in both locations. This is when the sun it at its maximum altitude, an easy measurement.
One can assume the line is close enough to north-south that local noon is the same anyway, or you could easily account for that by subtracting out the east-west difference in the measurement of the distance between the two.


text:
Q: Bound mismatch with dependent eclipse projects This is my minimal reproducible example:
I have 3 classes:
package a;

import b.B;
import c.C;

public class A {
    B<C> bc = new B<C>();
}

package b;

import c.C;

public class B<T extends C> {
}

package c;

public class C {
}

Class A is in eclipse project "project_a"
Class B is in eclipse project "project_b"
Class C is in eclipse project "project_c"
project_a has project_b and project_c in its Modulepath
project_b has project_c in its Modulepath
There is nothing else in my workspace.
I get this compile error:
Bound mismatch: The type C is not a valid substitute for the bounded parameter <T extends C> of the type B<T>
This doesn't make any sense. The C seen from project_a and the C seen from project_b should be the same!
Am I structuring the projects wrong?
If this is an issue in eclipse, what would be the best workaround without moving classes around?

A: When there are no module-info.java files, the dependent projects have to be on the Classpath, not on the Modulepath.