text:
Q: Making "Include" files, global scoping, and more work I have an AppleScript that needs to have a customized version to be run on hundreds of machines, each machine having a different version of the script.  My thought was to separate the customized details into one file, and then have a "codebase script" (CodeBaseTest.scpt) file that would be included on them. That way, I could maintain one codebase file more easily.
Because I don't know the version of macOS running (and it may be as far back as 10.13), I need to keep things super simple. Furthermore, because they won't have script libraries installed, I can't use that mechanism for a codebase lib. That also rules out the third party tools, I believe, that make it easier to produce scripts with includes (whether a library, or something like Script Debugger).
So, I've gone ahead and split it to 2 scripts:
first.last.scpt << customized for each machine
CodeBaseTest.scpt << is copied to the same folder as first.last.scpt so it's in the same folder
To make this work, and to make it easy to test new versions of code in the code base, I wanted to make the "on run" handler the same in both files -- but this isn't a must, just made it easier to do things.
Also to make it work, I had to remove all the properties and move to globals with declarations and then a set to make the defaults work.
The problem is that the scripts are not seeing variables that are clearly defined as globals.
There are two sets of these two files below -- a short set, and a set that has a ton of debug code in the two files here (which will make the errors very obvious if you run them).
Short set first
first.last-test.scpt here:
on run
    global myPath, myName, scriptFileExtension, myLibFilename, myLib
    set myPath to (path to me) as text
    set myName to ((name of me) as text)
    set scriptFileExtension to ".scpt"
    set myLibFilename to "CodeBaseTest" & scriptFileExtension

    if (myName & scriptFileExtension) is not myLibFilename then
        set myLib to load script (text 1 through ((length of myPath) - (length of (myName & scriptFileExtension))) of myPath & myLibFilename) as alias
    else if (myName & scriptFileExtension) is myLibFilename then
        set myLib to me
    else
        set fullErrorMsg to "Critical error assigning myLib or loading script. Script terminating. (main on run handler)" & return
        log fullErrorMsg
        display dialog fullErrorMsg
    end if

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Assumptions that need to be defined early on… and are done so in initializeGlobals()
        So that they can be used from either the user script (e.g., first.last.scpt) or test data
        within code base script (i.e., OutlookCodeBase.scpt). First a check which file we're in.
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)

    initializeGlobals() of myLib

    -- Account to copy to. If empty, defaults to first account in AcctsToAddList.
    global theDestAcctParams, theDestAcctParamNames
    set theDestAcctParams to {}
    set theDestAcctParamNames to {}

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Accounts to Add: Custom User Account Parameters -- defined for each user
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    global AcctsToAddList
    set AcctsToAddList to {¬
        {"Field1", "Field2", "Field3"}, ¬
        {"A", "B", "C"}, ¬
        {"D", "E", "F"}, ¬
        {EndOfListMarker}}

    -- Main Script, and supporting routines, are executed by a routine in the OutlookCodeBase.scpt file
    if (myName & scriptFileExtension) is not myLibFilename then
        mainScript() of myLib
    else
        mainScript()
    end if

end run

`
and CodeBaseTest.scpt (with debug code) here:
on initializeGlobals()
    -- Additional logging takes place with the debugFlag set to true
    global debugFlag
    set debugFlag to true as boolean

    global BlankUserPassword, EndOfListMarker
    set BlankUserPassword to "" -- should remain blank and not seen
    set EndOfListMarker to "ENDOFLIST"

end initializeGlobals

on mainScript()

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Log the time, so we know which run this is...
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    --if debugFlag then log "This run started at: " & (time string of (current date))

    -- if theDestAcctParams is empty, copy first account from AcctsToAddList
    if number of items in theDestAcctParams is 0 then
        if number of items in AcctsToAddList is greater than 1 then
            if debugFlag is true then log "theDestAcctParams is empty. copying 2nd item from AcctsToAddList"
            set theDestAcctParams to item 2 of AcctsToAddList
        else
            log "!!! ERROR: not enough items in AcctsToAddList to copy"
        end if
        if debugFlag is true then log "theDestAcctParams is not empty."
    end if

end mainScript

on run
    global myPath, myName, scriptFileExtension, myLibFilename, myLib
    set myPath to (path to me) as text
    set myName to ((name of me) as text)
    set scriptFileExtension to ".scpt"
    set myLibFilename to "CodeBaseTest" & scriptFileExtension

    if (myName & scriptFileExtension) is not myLibFilename then
        set myLib to load script (text 1 through ((length of myPath) - (length of (myName & scriptFileExtension))) of myPath & myLibFilename) as alias
    else if (myName & scriptFileExtension) is myLibFilename then
        set myLib to me
    else
        set fullErrorMsg to "Critical error assigning myLib or loading script. Script terminating. (main on run handler)" & return
        log fullErrorMsg
        display dialog fullErrorMsg
    end if

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Assumptions that need to be defined early on… and are done so in initializeGlobals()
        So that they can be used from either the user script (e.g., first.last.scpt) or test data
        within code base script (i.e., OutlookCodeBase.scpt). First a check which file we're in.
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)

    initializeGlobals() of myLib

    -- Account to copy to. If empty, defaults to first account in AcctsToAddList.
    global theDestAcctParams, theDestAcctParamNames
    set theDestAcctParams to {}
    set theDestAcctParamNames to {}

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Accounts to Add: Custom User Account Parameters -- defined for each user
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    global AcctsToAddList
    set AcctsToAddList to {¬
        {"Field1", "Field2", "Field3"}, ¬
        {"A", "B", "C"}, ¬
        {"D", "E", "F"}, ¬
        {EndOfListMarker}}

    -- Main Script, and supporting routines, are executed by a routine in the OutlookCodeBase.scpt file
    if (myName & scriptFileExtension) is not myLibFilename then
        mainScript() of myLib
    else
        mainScript()
    end if

end run

Anyone have any idea why this isn't working?  I'm sure (and hopeful) that I'm doing something stupid ... after all, I am coding during a migraine ... but I have to get this done today!
Thanks for reading (and even more if you can help)!
Neil
================================================================
The below is just the same scripts, but the set with all the extra debug code:
================================================================
first.last-test.scpt here:
on run
    global actionsHistory
    set actionsHistory to ""

    global myPath, myName, scriptFileExtension, myLibFilename, myLib
    set myPath to (path to me) as text
    set myName to ((name of me) as text)
    set scriptFileExtension to ".scpt"
    set myLibFilename to "CodeBaseTest" & scriptFileExtension

    set actionsHistory to actionsHistory & return & return & ¬
        "• " & ("hello world from " & myName)
    display dialog ("hello world from " & myName)

    if (myName & scriptFileExtension) is not myLibFilename then
        set myLib to load script (text 1 through ((length of myPath) - (length of (myName & scriptFileExtension))) of myPath & myLibFilename) as alias
    else if (myName & scriptFileExtension) is myLibFilename then
        set myLib to me
    else
        set fullErrorMsg to "Critical error assigning myLib or loading script. Script terminating. (main on run handler)" & return
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end if

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Assumptions that need to be defined early on… and are done so in initializeGlobals()
        So that they can be used from either the user script (e.g., first.last.scpt) or test data
        within code base script (i.e., OutlookCodeBase.scpt). First a check which file we're in.
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    try
        initializeGlobals() of myLib
        (*
        if (myName & scriptFileExtension) is not myLibFilename then
            initializeGlobals() of myLib
        else
            initializeGlobals()
        end if
    *)
    on error errorStr number errorNum partial result resultList
        set fullErrorMsg to ("Error is: " & errorStr & return & "Error number: " & errorNum & return & "Result List: " & resultList as text) ¬
            & return & "Critical error initializing globals. Script terminating. (attempt to call initializeGlobals() in " & myName & ")"
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end try

    -- Account to copy to. If empty, defaults to first account in AcctsToAddList.
    global theDestAcctParams, theDestAcctParamNames
    set theDestAcctParams to {}
    set theDestAcctParamNames to {}

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Accounts to Add: Custom User Account Parameters -- defined for each user
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    global AcctsToAddList
    set AcctsToAddList to {¬
        {"Field1", "Field2", "Field3"}, ¬
        {"A", "B", "C"}, ¬
        {"D", "E", "F"}, ¬
        {EndOfListMarker}}

    -- Main Script, and supporting routines, are executed by a routine in the CodeBaseTest.scpt file
    if (myName & scriptFileExtension) is not myLibFilename then
        mainScript() of myLib
    else
        mainScript()
    end if

    display dialog "Action history is: " & return & return & actionsHistory

end run

and CodeBaseTest.scpt (with debug code) here:
on initializeGlobals()
    display dialog ("hello world from initializeGlobals() in CodeBaseTest.scpt")
    try
        -- Additional logging takes place with the debugFlag set to true
        global debugFlag
        set debugFlag to true as boolean

        global BlankUserPassword, EndOfListMarker
        set BlankUserPassword to "" -- should remain blank and not seen
        set EndOfListMarker to "ENDOFLIST"

    on error errorStr number errorNum partial result resultList from badObject to expectedType
        set fullErrorMsg to (("Error is: " & errorStr & return * " Error number: " & errorNum & return ¬
            & "in script: " & myName & return ¬
            & "Result List: " & resultList as text) & return ¬
            & "badObject: " & badObject as text) & return ¬
            & "Coercion failure: " & expectedType
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end try

    display dialog ("In routine " & "initializeGlobals" & " (end)" & " in " & myName & " with debugFlag = " & debugFlag)
end initializeGlobals

on mainScript()
    display dialog ("hello world from mainScript() in CodeBaseTest.scpt")

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Log the time, so we know which run this is...
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    try
        display dialog ("In routine " & "mainScript" & " (start)" & " with debugFlag = " & debugFlag)
        if debugFlag then log "This run started at: " & (time string of (current date))
    on error errorStr number errorNum partial result resultList from badObject to expectedType
        set fullErrorMsg to ("Error is: " & errorStr & return & " Error number: " & errorNum & return ¬
            & "Result List: " & (resultList as text) & return ¬
            & "badObject: " & (badObject as text) & return ¬
            & "Coercion failure: " & expectedType)
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end try

    -- if theDestAcctParams is empty, copy first account from AcctsToAddList
    try
        if number of items in theDestAcctParams is 0 then
            if number of items in AcctsToAddList is greater than 1 then
                if debugFlag is true then log "theDestAcctParams is empty. copying 2nd item from AcctsToAddList"
                set theDestAcctParams to item 2 of AcctsToAddList
            else
                log "!!! ERROR: not enough items in AcctsToAddList to copy"
            end if
            if debugFlag is true then log "theDestAcctParams is not empty."
        end if
    on error errorStr number errorNum partial result resultList from badObject to expectedType
        set fullErrorMsg to ("Error is: " & errorStr & return & " Error number: " & errorNum & return ¬
            & "Result List: " & (resultList as text) & return ¬
            & "badObject: " & (badObject as text) & return ¬
            & "Coercion failure: " & expectedType)
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end try

end mainScript

on run
    global actionsHistory
    set actionsHistory to ""

    global myPath, myName, scriptFileExtension, myLibFilename, myLib
    set myPath to (path to me) as text
    set myName to ((name of me) as text)
    set scriptFileExtension to ".scpt"
    set myLibFilename to "CodeBaseTest" & scriptFileExtension

    set actionsHistory to actionsHistory & return & return & ¬
        "• " & ("hello world from " & myName)
    display dialog ("hello world from " & myName)

    if (myName & scriptFileExtension) is not myLibFilename then
        set myLib to load script (text 1 through ((length of myPath) - (length of (myName & scriptFileExtension))) of myPath & myLibFilename) as alias
    else if (myName & scriptFileExtension) is myLibFilename then
        set myLib to me
    else
        set fullErrorMsg to "Critical error assigning myLib or loading script. Script terminating. (main on run handler)" & return
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end if

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Assumptions that need to be defined early on… and are done so in initializeGlobals()
        So that they can be used from either the user script (e.g., first.last.scpt) or test data
        within code base script (i.e., OutlookCodeBase.scpt). First a check which file we're in.
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    try
        initializeGlobals() of myLib
        (*
        if (myName & scriptFileExtension) is not myLibFilename then
            initializeGlobals() of myLib
        else
            initializeGlobals()
        end if
    *)
    on error errorStr number errorNum partial result resultList
        set fullErrorMsg to ("Error is: " & errorStr & return & "Error number: " & errorNum & return & "Result List: " & resultList as text) ¬
            & return & "Critical error initializing globals. Script terminating. (attempt to call initializeGlobals() in " & myName & ")"
        log fullErrorMsg
        display dialog fullErrorMsg
        set actionsHistory to actionsHistory & return & return & ¬
            "• " & fullErrorMsg
    end try

    -- Account to copy to. If empty, defaults to first account in AcctsToAddList.
    global theDestAcctParams, theDestAcctParamNames
    set theDestAcctParams to {}
    set theDestAcctParamNames to {}

    (*  —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        Accounts to Add: Custom User Account Parameters -- defined for each user
        —-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-—-
        *)
    global AcctsToAddList
    set AcctsToAddList to {¬
        {"Field1", "Field2", "Field3"}, ¬
        {"A", "B", "C"}, ¬
        {"D", "E", "F"}, ¬
        {EndOfListMarker}}

    -- Main Script, and supporting routines, are executed by a routine in the CodeBaseTest.scpt file
    if (myName & scriptFileExtension) is not myLibFilename then
        mainScript() of myLib
    else
        mainScript()
    end if

    display dialog "Action history is: " & return & return & actionsHistory

end run

A: *

*AppleScript's global is an absolute menace; one of the language's (many) design flaws. Avoid. You will tie yourself in knots by using it. Instead, use property for all non-local variables. Properties are strictly scoped to the script that declares them. If script B needs to access properties and handlers from script A, script B should import script A and assign it to a property: use ALib : script "ALib" (or property ALib : load script (POSIX file "/path/to/ALib") if you're doing it old-style).

*You can use AppleScript's native library support. Here is the documentation. See #1 and #2. Save your customized scripts as either a Script Editor/Script Debugger .app applet or as a .scptd file, and put all its libraries inside that bundle. When the main app/script finds a use statement, it will search for those embedded libraries first. You don't have to install any libraries in /Library/Script Libraries or ~/Library/Script Libraries.

*Where you do need to share some properties/handlers between several scripts, put them into their own library and have the other scripts import that. You want to create a nice tree-shaped dependency structure, e.g. shared lib A is imported by libs B and C, which are imported by scripts D, E, and F. You want to avoid a cat's cradle of dependencies where every script imports every other script (e.g. A imports B and C; B imports A and C; C imports A and B) and each script manipulates the others ad-hoc. That will create an incomprehensible tangle that even you can't understand, never mind quickly and easily debug. (Especially avoid circular dependencies: e.g. A imports B, B imports C, C imports A again. Those are a nightmare to do right, and are generally a sign that you've divided up your program badly.)
…
Anyway, that's the techie bit summarizing How to structure your code. Read on if you want to understand the Why.

Programming is not about creating complexity. It's about minimizing and managing that complexity successfully. Handlers and libraries are two of the tools you use for that. Use them well, and you will smash the problem. Use them ineffectively, complexity will smash you.
I'm guessing you're a self-taught AppleScripter, not a college-trained Computer Science graduate (although plenty of those jokers can't program for toffee). Either way, your scripts have now reached a level of ambition, size, and complexity where your old "bodge it till it works" AppleScript hacking skills no longer succeed like they used to. Spaghetti hacking skills are great for quickly making simple automations that do the job, but once you get into hundreds and thousands of lines of code those same skills will bury you alive.
You need to go learn yourself a little bit of Computer Science now, because CS ran into and figured out techniques for managing code complexity 50 years ago.
Here's two words for you to start researching: "coupling" and "cohesion".
Good code has low coupling and high cohesion; bad code has the opposite.
BTW, I wrote a very brief intro to software design in ch 29 of Learn AppleScript, 3rd edition, which you might or might not find helpful. (Ignore the section about making libraries in the Script Objects chapter though: that's all obsolete since AS introduced native library support.)
Beyond that, I strongly recommend you buy a cheap copy of Steve McConnell's Code Complete, 1st edition off eBay. That book covers just about every Do and Don't of architecting software. However, don't read CC cover-to-cover (you will never take it in). Instead, put it on your bookshelf until you start struggling with some aspect of your program's design. When you do, take it down, read through the Table of Contents, and when you find a chapter topic that sounds like it might relate to your problem, go read just that chapter. You may need to hop back and forth a few times between your code and the book, but eventually what it's saying will start to make sense.
…
One more thing:
The real payoff to learning yourself some CS is not simply that your scripts work reliably and be a  relatively fast and pain-free pleasure to code. That is lovely to achieve, but it is not your killer USP.
What mastering CS stuff does is equip you to run circles around professional college-trained programmers who know lots about programming but possess none of your years of expert knowledge, insight, and experience inside your specialist profession (e.g. print industry). Being skilled in both is a force multiplier.
A programmer who understands their problem domain at a deep, expert level—who can talk to users in those users' own language, and treat them as full peers and collaborators in building their solutions—is like discovering a unicorn amongst a herd of donkeys. (Not all customers will appreciate this but for those who do you can blow their socks off.) Takes a few years to get up to this level, but as you do remember to increase your rates accordingly!

A: I so appreciate the explanations -- and it's clear that if I want to spend the next couple of days figuring out how to do something useful, I think at the end of the day, there's too much here to figure out.
Given this is a project that will live for no more than a month more, and that I need to start using today, I'm going to give up -- and not try to structure the files so that I can maintain it more easily.
Instead, I'll have one long script for each first.last.scpt ... and no "include" files at all.  I'll just maintain the code in FileMaker where I'll be creating the different "personalized" versions for each person.
Thank you SO much for the explanation -- it allowed me to make an informed decision.


text:
Q: How to find perfect numbers upto 10^18 in C? I have a C code off finding large perfect numbers below,
#include <stdio.h>

int main ()
{
    unsigned long long num,i,sum;

    while (scanf ("%llu",&num) != EOF && num)
    {
        sum = 1;

        for (i=2; i*i<=num; i++)
        {
            if (num % i == 0)
            {
                if (i*i == num)
                    sum += i;
                else
                    sum += (i + num/i);
            }
        }

        if (sum == num)
            printf ("Perfect\n");
        else if (sum > num)
            printf ("Abundant\n");
        else
            printf ("Deficient\n");
    }

    return 0;
}

I tried to find whether a number is perfect, abundant or deficient. I run a loop upto the square root of numto minimize the runtime. It works fine <= 10^15 but for the larger values it takes too long time to execute.
For example,for the following input sets,
8
6
18
1000000
1000000000000000
0

this code shows the following outputs,
Deficient
Perfect
Abundant
Abundant
Abundant

But, for 10^16 it doesn't respond quickly.
So, is there any better way to find a perfect number for too long values? Or is there any better algorithm to implement here??? :)

A: Yes, there is a better algorithm.
Your algorithm is basically the simple one--adding up the divisors of a number to find... the sum of the divisors of a number (excluding itself). But you can use the number-theoretic formula for finding the sum of the divisors of a number (including itself). If the prime numbers dividing n are p1, p2, ..., pk and the powers of those primes in the canonical decomposition of n are a1, a2, ..., ak, then the sum of the divisors of n is
(p1**(a1+1) - 1) / (p1 - 1) * (p2**(a2+1) - 1) / (p2 - 1) * ...
    * (pk**(ak+1) - 1) / (pk - 1)

You can find the prime divisors and their exponents more quickly than finding all the divisors of n. Subtract n from that expression above and you get the sum you want.
There are some tricks, of course, to find the pis and ais more efficiently: I'll leave that to you.

By the way, if your purpose is just to find the perfect numbers, as in your title, you would do better to use Euclid's formula for even prime numbers. Find the Mersenne prime numbers by examining all 2**p-1 for prime p to see if they are prime--there are shortcuts to doing this as well--then constructing a perfect number from that Mersenne prime. This would leave out any odd perfect numbers, though. If you find any, let the mathematical community know--that would make you world famous.
Of course, the fastest way of all to find perfect numbers is to use the lists already made of some of them.

A: It is a matter of factorization of numbers. You can read more here: https://en.wikipedia.org/wiki/Integer_factorization
Unfortunately no good news for you - the bigger the number gets, the longer it takes.
To start with your code, try not to multiply i*i each iteration.
Instead of:
    for (i=2; i*i<=num; i++)
calculate square root of num first, and then compare
 i <= square_root_of_num in the loop.

A: // Program to determine whether perfect or not

# include <bits/stdc++.h>
using namespace std;

map<long long int, int> mp;    // to store prime factors and there frequency

void primeFactors(long long int n)
{
// counting the number of 2s that divide n
while (n%2 == 0)
{
    mp[2] = mp[2]+1;
    n = n/2;
}

long long int root = sqrt(n);
// n must be odd at this point.  So we can skip every even numbers next
for (long long int i = 3; i <= root; i = i+2)
{
    // While i divides n, count frequency of i prime factor and divide n
    while (n%i == 0)
    {
        mp[i] = mp[i]+1;
        n = n/i;
    }
}

// This condition is to handle the case whien n is a prime number
    // greater than 2
    if (n > 2)
    {
        mp[n] = mp[n]+1;
    }
}

long long int pow(long long int base, long long int exp)
{
    long long int result = 1;
    base = base;
    while (exp>0)
    {
        if (exp & 1)
            result = (result*base);
        exp >>= 1;
        base = (base*base);
    }
    return result;
}

int main ()
{
    long long num, p, a, sum;

    while (scanf ("%lld",&num) != EOF && num)
    {
        primeFactors(num);
        sum = 1;

        map<long long int, int> :: iterator i;
        for(i=mp.begin(); i!=mp.end(); i++)
        {
            p = i->first;
            a = i->second;
            sum = sum*((pow(p,a+1)-1)/(p-1));
        }

        if (sum == 2*num)
            printf ("Perfect\n");
        else if (sum > num)
            printf ("Abundant\n");
        else
            printf ("Deficient\n");

        mp.clear();
    }

    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: uwsgi cannot work on a cloud server I have install uwsgi on a cloud server, with test I write a python script to test it, which is as follow:
# test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"] # python3

Then I run it as follows:
uwsgi --http :8001 --wsgi-file test.py

and I get some info like this :
pcre jit disabled
detected number of CPU cores: 1
current working directory: /root
detected binary path: /root/.pyenv/versions/2.7.6/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 7840
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8001 fd 4
spawned uWSGI http 1 (pid: 8524)
uwsgi socket 0 bound to TCP address 127.0.0.1:53307 (port auto-assigned) fd 3
Python version: 2.7.6 (default, May  6 2015, 18:35:37)  [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x1108510
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72768 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1108510 pid: 8491 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 8491, cores: 1)

But when I type the Ip address and port on a browser, it cannot echo "Hello World".

A: Check the firewall rules. Arbitrary ports like 8001 tend to be disabled from outside access out of the box. Should work just fine from the command line on the server, e.g. $ curl localhost:8001.


text:
Q: Unable to remove completely the vertical paddings inside  when using Bootstrap 5 i am trying to remove all paddings (top + bottom) for a text inside a  block using Bootstrap 5.
when using html without Bootstrap, setting padding: 0px does exactly what i expect:

no bootstrap
 // works!
however, the moment i use Bootstrap, the padding is never 0, even after setting class my-0. there is always extra padding that seems to be added regardless.

using bootstrap my-0
 // doesn't work
using style to override the padding to 0 also doesn't work when the Bootstrap css is included.

using bootstrap my-0
 // doesn't work
is there a solution here?

A: i figured out that there is a style property line-height that i should use to achieve this! setting it to 1 or 1.25 works exactly as i wanted. the default with bootstrap is 1.5, hence the additional unintended padding.

A: Add the class = "p-0". A bootstrap class that set padding to 0. For top and bottom use "py-0" and for left and right "py-0"

A:
Will remove all Paddings and margins (no extra space inside and outside div)

Will remove all Paddings (no extra space inside div)


text:
Q: No include path in which to find limits.h: GCC build limits.h (#include_next limits.h) I am building GCC for a foreign architecture on Ububtu trusty. I am on an i686 and building for i386. I am having the same problem as GCC build problem (#include_next limits.h).
From the discussion in the link I posted this comment struck me as being the best explanation however I am not sure what the poster means by (the toolsets copy)....I suspect he means I need some other tarballs apart from the gcc tarball. I believe I have libc6-dev-x32 and libc6-x32:i386 but these could be something wrong with their installation or something else might be needed?
Can anyone clarify what he means by the toolsets copy?

Consider using #include_next  (gcc extension) in order to
  force gcc to look at the next found limits.h in the include path
  (which should be the toolset's copy).

Additional Information:
Am I missing part of glibc? I have the packages previously mentioned.
The configure statement is: ./configure --prefix=/testing/gcc2953 --enable-languages=c --target=i486-pc-linux-gnulibc1 --without-headers
The error message is:
In file included from include/syslimits.h:7,
                 from include/limits.h:11,
                 from ./libgcc2.c:1105:
/src/gcc-2.95.3/gcc/include/limits.h:117: No include path in which to find limits.h

make[ 1]: *** [ libgcc2.a] Error 1

make[ 1]: Leaving directory `/src/gcc-2.95.3/gcc'

make: *** [ all-gcc] Error 2


text:
Q: How do i make the icon show correctly on the desktop icon I made a desktop link by creating a link in the desktop folder, which thin is displayed on the desktop. i selected the icon which then is correctly shown on the link in the folder but not on the desktop icon, even though the properties show it. (see pic)
what do i need to add / change?


text:
Q: Spring security whiltelist incoming service call In Spring security you can whitelist the incoming IP using hasIpAddress. Is it possible to have a whitelist for the incoming domain/url/servicename?
I have two services in a kubernates cluster, most of their endpoints can only be accessed with the accessed token (legacy filter can't be removed). However, I would like one service to call the other without a token for a particular endpoint (let's say service A call service B). Is it possible to specify the service name rather than the ip to be whitelisted in service B? I don't want to make the endpoint to be publicly accessible. Do I have to convert to IP like this
InetAddress ipaddress = InetAddress.getByName(service);
Is there something smart for Kubernetes services?

A: Maybe you can try to use the internal kubernetes dns link so you don't have to specify the ip address.


text:
Q: How to structure a many to many django model with unique key account-user combinations I have a issue with how to structure my django model.
I have a User model and an Account model.
The User can be in multiple accounts. Each User should have a key for each Account.
I want to be able to get the key associated with the account and user combination.
User 1 is in Account A and B. If I query for Account A and User 1 I should get key1 and if I query for B and 1 I should get key2.
keys = {AccountA: key1, AccountB: key2}
I'm just confused on how I can store this data. I know I could serialize json and store as a Text Field. But I think that will be messy. I want to be able to regenerate the keys if needed. What is the
class User(models.Model):
    accounts= models.ManyToManyField(Account)
    keys = models.TextField()

OR
class User(models.Model):
    accounts= models.ManyToManyField(Account)
    keys = models.ManyToManyField(AnotherModel?)

Something else? Caveats: I cant use hstore or jsonfield. I'm on django 1.7

A: What you need is related to database normalization. I would advice to read more on that topic. Now back to the concrete example.
If each user-account combination is unique I would set up a many-to-many through relation.
class User(models.Model):
    accounts= models.ManyToManyField(Account,
                                     through='UserAccount',
                                     related_name='user_accounts',
    )

class UserAccount(models.Model):
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    account = models.ForeignKey(User, on_delete=models.CASCADE)
    key = models.UUIDField()

After that you can get all keys simple by selecting all UserAccount instances which are related to the concrete user.


text:
Q: Get items on canvas Im working on a GUI for a board game. So I made some objects on the Canvas and I know they are somehow saved as integers because if I create it, it returns the int and if I canvas.delete(i) it gets removed. Summed up I have a mxn board and the squares are $i\in {1,__,m*n}$.
How can I configure the cells now, by only knowing the integers?
For all squares I set the tag: 'cells', therefore I can get the integers and change stuff:
items = canvas.find_withtag('cells')
canvas.itemconfig('cells', ...)

Do I have to set the (i,j) as a tag when I create the squares?
Thanks for reading and good evening.

A: I don't really often use Canvas quite often but this should be a workaround for what you have asking for:
import tkinter as tk

# Defining all of your constants
width = 10
height = 10
spacing = 2

countX = 20
countY = 10

# Dictionary which will contains all rectangles
_objects = {}

# Creating the window
root = tk.Tk()
root.geometry("200x100")
canvas = tk.Canvas(root, width = 200, height = 100, bg = "white")
canvas.pack()

# Creating all fields and naming than like coordinates
for y in range(countY):
    for x in range(countX):
        _objects["{0}/{1}".format(x,y)] = canvas.create_rectangle(0+(x*width),
                                                               0+(y*height),
                                                               width+(x*width) - spacing,
                                                               height+(y*height) - spacing)

# Call a ractangle [X/Y]
canvas.itemconfig(_objects["0/2"], fill = "red")
canvas.itemconfig(_objects["0/9"], fill = "yellow")
canvas.itemconfig(_objects["19/9"], fill = "green")

print(_objects)
root.mainloop()

So the idea is to use a simple Dictionary where you store the id corresponding to the correct coordinate. You can address a specific rectangle by using _objects[<X>/<Y>]. And if you need to know the coordinate you can simply iterate over the dic with:
def getCoordById(oid):
    # Search with id
    for pairs in _objects.items():
        if pairs[1] == oid:
            return pairs[0]

canvas.itemconfig(_objects[getCoordById(1)], fill = "purple")

Ps.: If you always use the ID to identfy a coordinate I would use the canvas.create(...) as key and the name as value.


text:
Q: Void methods can't return the value of a void method? I don't mind if I don't understand, but I want to know why this happens:
void something(String a) {
    return hi();
}
void hi() {
    return;
}

The odd thing here, is that hi() also has a return type of void. I get the syntax error in my IDE:
Void methods cannot return a value

Furthermore, the code doesn't compile:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Void methods cannot return a value

    at Resources.setSystemProperties(Resources.java:33)
    at Resources.main(Resources.java:49)

I would expect this to be happening:
hi() -> return nothing

return [nothing] -> hi() is nothing

So in the end, it returns nothing, just like a void method should.
Why does this behaviour happen? And why doesn't the code compile, when return the result of a void method?

A: This is defined in JLS 14.17:

A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:

*

*A method that is declared to return a value

*A lambda expression

A void method is not declared to return a value, so a return statement with an expression (like a function call) cannot happen in such a method.
Additionally, you can't return the result of a void method due to this language in JLS 15.12.3:

If the compile-time declaration is void, then the method invocation must be a top level expression (that is, the Expression in an expression statement or in the ForInit or ForUpdate part of a for statement), or a compile-time error occurs.

In other words, since a.notify() is void, you can use it in contexts where it looks like a statement (ie, all alone on a line) but not in contexts where it looks like an expression (ie, you can't assign its value to a variable, return it, etc).

A: A function declared as void cannot return anything, just like the error says. Your assumption that a.notify() returns anything is false, because a.notify() also cannot return anything (since it is void).

A: Because that's how the language works. You can't use the return keyword to return a value in a method that has a return type of void. void is not a real value that can be passed around:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Here's an article by James Iry comparing void in Java with Unit in Scala. (Unlike void, unit is an actual value that can be returned.) He demonstrates there are advantages to having a Unit type instead of void:

Java, C++, and C# programmers do solve this problem all the time. One common option is to not use Function but some other concept like "Action" to mean a function that takes a string, performs a side effect, and returns nothing useful. Then you essentially duplicate "map" into something called perhaps "foreach" that expects an Action and returns void. That probably makes sense in this case since a list of references to a meaningless value is perhaps silly, but it also means a great deal of code duplication if this kind of higher order programming is common. For instance, you can't write just one compose function that creates a function from two other functions, you also have to write a compose that takes an action and a function to create an action.

A: Java compiler will not go so much in depth. When it sees return keyword with some value following in void function it will throw compilation error. It is programmed so. As simple as that.

A: return  statements simply cannot be used with `Void` as it's Return type.

You can't change language rules!


text:
Q: Matlab: storing data from a file I am trying to read in data from a text file and do a 3D plot of it in Matlab. Currently, all I'm getting is a blank plot so my guess is the data is not being stored correctly or at all. Also, I don't want the 1.000000 at the end of every vector so how can I ignore that? Thanks.
Here is the file:

Blockquote

TechEdge4:<152.266724,173.189377,27.995975>  1.000000
<117.880638,156.116531,27.999983>  1.000000
<129.849899,59.195660,27.999983>  1.000000
<249.321121,60.605404,27.999983>  1.000000
<224.120361,139.072739,28.000668>  1.000000
<171.188950,143.490921,56.933430>  1.000000
<171.188950,143.490921,83.548088>  1.000000
<171.188950,143.490921,27.999985>  1.000000

Here is the code:
file = fopen('C:\Program Files (x86)\Notepad++\testFile.txt'); % open text file

tline = fgetl(file); % read line by line and remove new line characters

% declare empty arrays
CX = [];
CY = [];
CZ = [];

while ischar(tline) % true if tline is a character array

    temp = textscan(tline,'%n%n%n', 'delimiter',',');

    % convert all the cell fields to a matrix
    CX = vertcat(CX, cell2mat(temp));
    CY = vertcat(CY, cell2mat(temp));
    CZ = vertcat(CZ, cell2mat(temp));

    tline = fgetl(file);
end

fclose(file); % close the file

plot3(CX, CY, CZ) % plot the data and label the axises
xlabel('x')
ylabel('y')
zlabel('z')
grid on
axis square

A: The way your code is running now, your temp variables are blank in each iteration. Replace the textscan line with
temp = cell2mat(textscan(tline, '<%n,%n,%n>'));

and then the CX, CY, and CZ lines with
CX = vertcat(CX, temp(1));
CY = vertcat(CY, temp(2));
CZ = vertcat(CZ, temp(3));

That should make it work. Of course you will need to handle the first line separately because it has the TechEdge4: thing in it.
Also I suggest adding a check to make sure temp is non-empty before the vertcats.


text:
Q: CSV to sequence? "TypeError: Population must be a sequence or set". How to fix it. I am trying to follow this code http://alexminnaar.com/time-series-classification-and-clustering-with-python.html for doing time series clustering; when I try to follow the example in order to start understanding how it works, I get this error:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import random

def k_means_clust(data,num_clust,num_iter,w=5):
    centroids=random.sample(data,num_clust)
    counter=0
    for n in range(num_iter):
        counter+=1
        #print counter
        assignments={}
        #assign data points to clusters
        for ind,i in enumerate(data):
            min_dist=float('inf')
            closest_clust=None
            for c_ind,j in enumerate(centroids):
                if LB_Keogh(i,j,5)<min_dist:
                    cur_dist=DTWDistance(i,j,w)
                    if cur_dist<min_dist:
                        min_dist=cur_dist
                        closest_clust=c_ind
            if closest_clust in assignments:
                assignments[closest_clust].append(ind)
            else:
                assignments[closest_clust]=[]

        #recalculate centroids of clusters
        for key in assignments:
            clust_sum=0
            for k in assignments[key]:
                clust_sum=clust_sum+data[k]
            centroids[key]=[m/len(assignments[key]) for m in clust_sum]

    return centroids

train = np.genfromtxt('datasets/train.csv', delimiter='\t')
test = np.genfromtxt('datasets/test.csv', delimiter='\t')
data=np.vstack((train[:,:-1],test[:,:-1]))

import matplotlib.pylab as plt

centroids=k_means_clust(data,4,10,4)
for i in centroids:

    plt.plot(i)

plt.show()

--------------------------------------------------------------------------- TypeError                                 Traceback (most recent call
  last)  in ()
        5 import matplotlib.pylab as plt
        6
  ----> 7 centroids=k_means_clust(data,4,10,4)
        8 for i in centroids:
        9
 in k_means_clust(data, num_clust,
  num_iter, w)
        2
        3 def k_means_clust(data,num_clust,num_iter,w=5):
  ----> 4     centroids=random.sample(data,num_clust)
        5     counter=0
        6     for n in range(num_iter):
C:\Users\Luis\Anaconda3\lib\random.py in sample(self, population, k)
      309             population = tuple(population)
      310         if not isinstance(population, _Sequence):
  --> 311             raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
      312         randbelow = self._randbelow
      313         n = len(population)
> TypeError: Population must be a sequence or set.  For dicts, use
  list(d).

This is the data I am loading:

[[-0.37693558  1.2248643   0.34387438 ...,  0.91834602 -1.3117417
  -1.1971462 ]
 [ 0.64440621  0.41326914 -0.86227849 ...,  1.3981403   0.08574208
   0.02499741]
 [-0.97866735 -0.40623244  0.82242857 ...,  0.66612895  0.10699555
   0.08271546]
 ...,
 [ 0.8455511   0.05714152  1.2228095  ..., -0.51199761 -0.86978484
  -0.2057573 ]
 [ 1.9725294   0.41645028  1.6845052  ..., -1.3956278  -1.0317821
  -1.1345864 ]
 [ 1.5162553   1.1602023   1.2666022  ..., -0.85115838 -0.85573754
  -1.0178208 ]]

Should I convert that to a sequence? How should I fix it?

A: In the function:
   def k_means_clust(data,num_clust,num_iter,w=5):
       centroids=random.sample(data,num_clust)

you are using random on a numpy array:
The random library does not work with numpy arrays, so what you can do, is to convert the numpy array into a list:
   def k_means_clust(data,num_clust,num_iter,w=5):
       centroids=random.sample(list(data),num_clust)

A: [SciPy]: numpy.vstack returns an [SciPy]: numpy.ndarray, while [Python]: random.sample(population, k) expects a sequence ([Python]: class collections.abc.Sequence)
Example:

>>> import sys
>>> import random
>>> import numpy as np
>>>
>>> "Python {:s} on {:s}".format(sys.version, sys.platform)
'Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32'
>>>
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> data = np.vstack((a, b))
>>> data
array([[1],
       [2],
       [3],
       [2],
       [3],
       [4]])
>>> random.sample(data, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "e:\Work\Dev\VEnvs\py35x64_test\lib\random.py", line 320, in sample
    raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).
>>> random.sample(data.tolist(), 4)
[[3], [4], [2], [3]]

Fix:
Use numpy.ndarray.tolist(). In your code, replace
centroids=random.sample(data,num_clust)

by
centroids = random.sample(data.tolist(), num_clust)

or use list(data) (as the exception text instructs (for dicts)).


text:
Q: Implement transfer learning on niftynet I want to implement transfer learning using the Dense V-Net architecture. As I was searching on how to do this, I found that this feature is currently being worked on (How do I implement transfer learning in NiftyNet?).
Although from that answer it is quite clear that there is not a straight way to implement it, I was trying to:
1) Create the Dense V-Net
2) Restore weigths from the .ckpt file
3) Implement transfer learning on my own
To perform step 1, I thought I could use the niftynet.network.dense_vnet module. Therefore, I tried the following:
checkpoint = '/path_to_ckpt/model.ckpt-3000.index'
x = tf.placeholder(dtype=tf.float32, shape=[None,1,144,144,144])
architecture_parameters = dict(
    use_bdo=False,
    use_prior=False,
    use_dense_connections=True,
    use_coords=False)

hyperparameters = dict(
    prior_size=12,
    n_dense_channels=(4, 8, 16),
    n_seg_channels=(12, 24, 24),
    n_input_channels=(24, 24, 24),
    dilation_rates=([1] * 5, [1] * 10, [1] * 10),
    final_kernel=3,
    augmentation_scale=0)
model_instance = DenseVNet(num_classes=9,hyperparameters=hyperparameters,
                             architecture_parameters=architecture_parameters)

model_net = DenseVNet.layer_op(model_instance, x)

However, I get the following error:
TypeError: Failed to convert object of type <type 'list'> to Tensor. Contents: [None, 1, 72, 72, 24]. Consider casting elements to a supported type.

So, the question is:
Is there any way to implement this?

A: Transfer learning has been added been added to NiftyNet.
You can select which variables you want to restore through the vars_to_restore config parameter and which variables to freeze through the vars_to_freeze config parameter.
See here for more information.

A: A simple transfer learning can be achieved with restoring weights from existing model in the way that you set the parameter starting_iter in [TRAINING] section of your config file to the number of pretrained model. In your example starting_iter=3000.
This will restore the weights from your model and new iterations will start with this initialisation.
Here the architecture of your model has to be exactly the same, otherwise you will get an error.
For more sophisticated transfer learning or maybe also fine tuning where you can restore only a part of weights, there is a great implementation here. It will be probably merged with official niftynet repository very soon, but you can already use it.


text:
Q: Non V-bind part of the V-Model As we know v-model is two way binding. Which means it's combination of V-bind and maybe another attribute which I'm looking for and it updates the data. I have a input which it's value is sometimes custom and sometimes should be read from config based on another parameters.
What I need is an input with a v-bind:value/:value and another for update. I know I can do it with @change and a custom method But I'm looking for something easy, Bottom line is I want V-model without doing v-bind ! Thank You
EDIT: I did it with two input using v-if .
<input type="number" class="item-input"  v-if="setting.keto_program=='custom'" id="protein_per_kilo" v-model="setting.keto_program_protein_density">
 <input type="number" class="item-input"  v-else disabled id="protein_per_kilo" :value="config.keto_programs[setting.keto_program].protein_density">

Anyway doing this using just one input feels better. Thanks

A: May be you can use computed hook.
computed:{
  yourVariable(){
    return someVariable/computation
  }
}

you can use yourVariable inside your code that will act like v-model without doing v-bind.
yourVariable will be updated as soon as the variables of the return statement of this be changed or updated
Edited:
part of v-model for input tag
<input
   v-bind:value="variable"
   v-on:input="variable = $event.target.value"
>

or
<input
   :value="variable"
   @input="variable = $event.target.value"
>

found this via
Vue.js—Difference between v-model and v-bind


text:
Q: Problems rotating multiple cubes at the same time I'm drawing a Pyramid made out of 3 Cubes (two side to side then one on top), then I try to rotate this pyramid on X, Y or Z axis and scale it up and down.
Problem is the three cubes do not scale correctly (different sizes), also rotating produces very strange results.
I have defined an array for my Cube, using a glm vec3 array:
const glm::vec3 cube[] = {
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3( -1.0f,-1.0f, 1.0f),
    glm::vec3(-1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f, 1.0f,-1.0f),
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3(-1.0f, 1.0f,-1.0f),
    glm::vec3(1.0f,-1.0f, 1.0f),
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3(1.0f,-1.0f,-1.0f),
    glm::vec3(1.0f, 1.0f,-1.0f),
    glm::vec3(1.0f,-1.0f,-1.0f),
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3(-1.0f, 1.0f, 1.0f),
    glm::vec3(-1.0f, 1.0f,-1.0f),
    glm::vec3(1.0f,-1.0f, 1.0f),
    glm::vec3(-1.0f,-1.0f, 1.0f),
    glm::vec3(-1.0f,-1.0f,-1.0f),
    glm::vec3(-1.0f, 1.0f, 1.0f),
    glm::vec3(-1.0f,-1.0f, 1.0f),
    glm::vec3(1.0f,-1.0f, 1.0f),
    glm::vec3(1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f,-1.0f,-1.0f),
    glm::vec3(1.0f, 1.0f,-1.0f),
    glm::vec3(1.0f,-1.0f,-1.0f),
    glm::vec3(1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f,-1.0f, 1.0f),
    glm::vec3(1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f, 1.0f,-1.0f),
    glm::vec3(-1.0f, 1.0f,-1.0f),
    glm::vec3(1.0f, 1.0f, 1.0f),
    glm::vec3(-1.0f, 1.0f,-1.0f),
    glm::vec3(-1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f, 1.0f, 1.0f),
    glm::vec3(-1.0f, 1.0f, 1.0f),
    glm::vec3(1.0f,-1.0f, 1.0f)
};

I generate and link the buffers and the necessary stuff for OpenGL to work, then I draw the pyramid, which is made of the three cubes. I am almost certain this is the part of the code where it all goes wrong:
glm::mat4 P = glm::perspective(glm::radians(60.0f + zoom), float(width()) / height(), 0.01f, 1000.0f);

glm::mat4 V = glm::mat4(1);
V = glm::translate(V, glm::vec3(-3 + moveX, -1 + moveY, -6 + moveZ));

V = glm::rotate(V, glm::radians(rotateCamradX), glm::vec3(1.0, 0.0, 0.0));
V = glm::rotate(V, glm::radians(rotateCamradY), glm::vec3(0.0, 1.0, 0.0));
V = glm::rotate(V, glm::radians(rotateCamradZ), glm::vec3(0.0, 0.0, 1.0));

glm::mat4 M = glm::mat4(1);
M = glm::translate(M, glm::vec3(-1, 0, 0));

M = glm::rotate(M, glm::radians(rotateradX), glm::vec3(1.0, 0.0, 0.0));
M = glm::rotate(M, glm::radians(rotateradY), glm::vec3(0.0, 1.0, 0.0));
M = glm::rotate(M, glm::radians(rotateradZ), glm::vec3(0.0, 0.0, 1.0));

M = glm::scale(M, glm::vec3(scaleVar, scaleVar, scaleVar));

glm::mat4 M1 = glm::mat4(1);
M1 = glm::translate(M, glm::vec3(2, 0, 0));

M1 = glm::rotate(M1, glm::radians(rotateradX), glm::vec3(1.0, 0.0, 0.0));
M1 = glm::rotate(M1, glm::radians(rotateradY), glm::vec3(0.0, 1.0, 0.0));
M1 = glm::rotate(M1, glm::radians(rotateradZ), glm::vec3(0.0, 0.0, 1.0));

M1 = glm::scale(M1, glm::vec3(scaleVar, scaleVar, scaleVar));

glm::mat4 M2 = glm::mat4(1);
M2 = glm::translate(M, glm::vec3(1, 2, 0));

M2 = glm::rotate(M2, glm::radians(rotateradX), glm::vec3(1.0, 0.0, 0.0));
M2 = glm::rotate(M2, glm::radians(rotateradY), glm::vec3(0.0, 1.0, 0.0));
M2 = glm::rotate(M2, glm::radians(rotateradZ), glm::vec3(0.0, 0.0, 1.0));

M2 = glm::scale(M2, glm::vec3(scaleVar, scaleVar, scaleVar));

glm::mat4 PVM = P * V * M;
glm::mat4 PVM1 = P * V * M1;
glm::mat4 PVM2 = P * V * M2;

gl->glUniformMatrix4fv(id_shader_program_PVM_uniform, 1, GL_FALSE, glm::value_ptr(PVM));
gl->glUniform3f(id_shader_program_Color_uniform, 0.3f ,0.1f, 0.2f);
gl->glDrawArrays(GL_TRIANGLES, 0, 3*12);
gl->glUniformMatrix4fv(id_shader_program_PVM_uniform, 1, GL_FALSE, glm::value_ptr(PVM1));
gl->glUniform3f(id_shader_program_Color_uniform, 0.8f ,0.2f, 0.7f);
gl->glDrawArrays(GL_TRIANGLES, 0, 3*12);
gl->glUniformMatrix4fv(id_shader_program_PVM_uniform, 1, GL_FALSE, glm::value_ptr(PVM2));
gl->glUniform3f(id_shader_program_Color_uniform, 0.1f ,0.2f, 0.1f);
gl->glDrawArrays(GL_TRIANGLES, 0, 3*12);

The variables in V matrix are used for camera movement, which works, then in M, M1 and M2 are the scaling variables and rotation variables. All of the variables are type float, which I change using buttons in an UI app.

A: Try flipping the order of your transformations. Instead of [translate,rotate,scale] do [scale,rotate,translate].
As a side note, it's generally easier to use glm::lookAt to compute your V matrix then to use multiple steps.


text:
Q: Spring: Manually rollback a JPA transaction The problem:

*

*I want to clash an in-memory data set with one stored in a SQL table.

*The match is conducted on multiple columns.

*The in-memory set could be quite large ~10000 records.

*I don't want to persist the in-memory set.

*I'm using Spring and JPA

*Multiple requests may be made concurrently

My attempted solution

*

*Start transaction

*Write the requested records to a "temporary" table

*Select the desired results by joining the two tables

*Rollback the transaction

(or in SQL terms)
CREATE TABLE player_details (
  firstname VARCHAR2(10),
  surname VARCHAR2(10),
  position VARCHAR2(2)
);

CREATE TABLE player_request (
  firstname VARCHAR2(10),
  surname VARCHAR2(10)
);

INSERT INTO player_details (firstname, surname, position) VALUES ('Scottie', 'Pippen', 'SF');
INSERT INTO player_details (firstname, surname, position) VALUES ('Michael', 'Jordan', 'SG');
INSERT INTO player_details (firstname, surname, position) VALUES ('Dennis', 'Rodman', 'PF');

START TRANSACTION;

  INSERT INTO player_request (firstname, surname) VALUES ('Scottie', 'Pippen');
  INSERT INTO player_request (firstname, surname) VALUES ('Michael', 'Jordan');

  SELECT
    d.*
  FROM player_details d
  JOIN player_request r
    ON  d.firstname = r.firstname
    AND d.surname = r.surname;

ROLLBACK;

SELECT
  COUNT(*) AS player_requests
FROM family;

Gives:
FIRSTNAME  SURNAME    POSITION
---------- ---------- --------
Scottie    Pippen     SF
Michael    Jordan     SG

PLAYER_REQUESTS
---------------
              0

However, I can't find a way to get Spring to rollback the transaction.  I've tried several different annotations and approaches, but haven't found one that works.  Is there one?
(worst case scenario, I'll just give it a request id, commit then delete)

A: Got it.
This wasn't working:
@Transactional
public MatchResponse myMatcherMethod(MatchCriteria criteria) {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    transactionStatus.setRollbackOnly();
    saveMatchCriteria(criteria);

    MatchResponse matches = getMatches();
    return matches;
}

It was giving me no matches.  Tomas asked my to post my code (thanks! +1) so I decided that I'd add a couple of extra lines to show that the criteria weren't being saved:
@Transactional
public MatchResponse myMatcherMethod(MatchCriteria criteria) {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    transactionStatus.setRollbackOnly();
    saveMatchCriteria(criteria);

    //Added these lines:
    MatchCriteria savedCriteria = getMatchCriteria();
    System.out.println("# of criteria: " + savedCriteria.getIdentifiers().size());

    MatchResponse matches = getMatches();
    return matches;
}

..but at that point it started working!
So I guessed that my test query was causing a flush.  So I tried:
@Transactional
public MatchResponse myMatcherMethod(MatchCriteria criteria) {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    transactionStatus.setRollbackOnly();
    saveMatchCriteria(criteria);

    // Replaced with:
    transactionStatus.flush();

    MatchResponse matches = getMatches();
    return matches;
}

..and it worked.
It seems obvious in hindsight:

*

*Repository.save -> JVM memory

*flush() -> Runs insert statement

*End transaction -> Commit

Looks like I need to brush up on my JPA life-cycle!


text:
Q: Different ways of declaring a function When declaring a function, I've 3 different ways:
let f x = ...

let f = (fun x -> ...)

let f = function
    | ...  -> (pattern matching)

It's this last one that I don't fully understand how it works.
I was doing a function that, considering a list (we'll assume it has integers in it but could be anything), reverses it, pretty basic, but with a complexity of O(n). After struggling for an hour at least I check the answer, and it is written like this:
let reverse lst =
    let rec aux acc = function
          | [] -> acc
          | hd :: tl -> aux (hd :: acc) tl
    in
    aux [] lst

I thought that using the key word function was just another way of doing patter matching, but when I do this:
let reverse lst =
    let rec aux acc =
        match aux with
          | [] -> acc
          | hd :: tl -> aux (hd :: acc) tl
    in
    aux [] lst

It doesn't work, and idk why. On top of that, why can we add tl at the end of the first function? Isn't aux a single argument function?

A: There are a few problems with this question. First, the code you give as the solution for reverse is not valid OCaml. It matches aux (which is a function) against list patterns. Most likely aux was supposed to be acc. But even so it doesn't seem right because it should have two arguments (the accumulated result and the input that still needs to be processed).
Second, your two code examples are the same. You seem to be saying that one works and one doesn't work. That doesn't make sense since they're the same.
IMHO you need to rewrite the question if you want to get a helpful answer.

A: Ocaml uses currying, which means that a two-argument function is the same thing that a function whose return value is a function.
To define a two-argument function, you can combine all the ways you know of creating one-argument functions:
let f x y = x + y

let f x = (fun y -> x + y)

let f x = function
    | y -> x + y

let f = (fun x -> (fun y -> x + y))

let f = function
    | x -> function
        | y -> x + y

let f x = (let g y = x + y in g)

etc, etc.

All these definitions for f lead to the same result:
val f : int -> int -> int = <fun>

# f 3 4;;
- : int = 7

Note that the signature of f is:
val f : int -> int -> int = <fun>

If we added parentheses to better understand this signature, it would be this:
val f : int -> (int -> int) = <fun>

Meaning that f is a one-argument function whose return value is a one-argument function whose return value is an int.
Indeed, if we partially apply f:
# f 3;;
- : int -> int = <fun>

# let add_three = f 3;;
val add_three : int -> int = <fun>

# add_three 4;;
- : int = 7

The code you give at the end of your question is wrong. It's most likely intended to be this:
let reverse lst =
    let rec aux acc l =
        match l with
          | [] -> acc
          | hd :: tl -> aux (hd :: acc) tl
    in
    aux [] lst;;

val reverse : 'a list -> 'a list = <fun>

# reverse [1;2;3;4;5];;
- : int list = [5; 4; 3; 2; 1]


text:
Q: Auto select value in dropdown How do I set a value as the default selected value in the dropdown? I am using angular 8.
I have the following html

        Content Type
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType"  formControlName="contentType" name="contentType">
          <option   *ngFor="let contentType of contentTypes" [value]="contentType.name" >{{contentType.displayName}}</option>
        </select>

I have tried using [selected]="contentType.name=='TEXT'" but the dropdown still does not show the default selected value as "Text Only".

        Content Type
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType" formControlName="contentType" name="contentType">
          <option *ngFor="let contentType of contentTypes" [value]="contentType.name" [selected]="contentType.name=='TEXT'">{{contentType.displayName}}</option>
        </select>

contentTypes is an array of [{"name":"TEXT","displayName":"Text Only"},{"name":"AUDIO","displayName":"Audio"},{"name":"VIDEO","displayName":"Video"}]

A: Karu,
by default item.contentType should being inited with value coresponding with some option from your list of contentTypes. If you init item.contentType with value TEXT for example, option with value TEXT will be preselected by default.
Or, you can just put option with null value with text Select content (for example). And validate it, if it should be required. Something like:

   Content Type
   <select class="form-control form-control-sm" [(ngModel)]="item.contentType"
         name="contentType">
      <option [value]="null">Select content</option>
      <option *ngFor="let contentType of contentTypes" [value]="contentType.name">
          {{contentType.displayName}}
      </option>
    </select>

Anyway, deside which approach for building form you will use (Reactive forms or Template driven forms). Because you did a mistake in definition for select component. Use only [(ngModel)] definition and remove formControlName="contentType", if you would like to use template driven forms pattern. Study this first in link provided.

A: I could make it work by this example
template

   Content Type
   <select class="form-control form-control-sm" formControlName="contentType"
         name="contentType">
      <option *ngFor="let contentType of contentTypes" [value]="contentType.name">
          {{contentType.displayName}}
      </option>
    </select>

in ts
// if you will give the value to the contentType control it will be selected item
// something like this
export class ReleaseComponent implements OnInit {

   ngOnInit() {
      this.yourForm.get('contentType').patchValue('TEXT');
      // or
      this.yourForm.get('contentType').patchValue(this.contentTypes[0].name);
   }
}

I hope this can be helpfull

A: Use [selected] in option
like this. Your selected condition is wrong, i think
<select class="form-control" [(ngModel)]="item.contentType">
   <option *ngFor="let contentType of contentTypes" [value]="contentType.name" [selected]="contentType.name==item.contentType">{{contentType.displayName}}</option>
</select>


text:
Q: PrintWriter sends and DataInputStream reads it I got server-client application. On the client side, I am using this I/O stream to output data:
out = new PrintWriter(socket.getOutputStream(), true);
        out.println("yeah");

On the server side I am trying to read the product by this line:
DataInputStream din = new DataInputStream(s.getInputStream());
    String clientId = din.readUTF();

The server reaches the above statement and stops there. What's the problem? Are the two I/O streams not compatible with each other?
There are no exceptions thrown by either party, no output. I simply added System.out.println() before and after the above statement I=and I determined that the program does not cross this line:String clientId = din.readUTF();

A: You should use the DataOutputStream.writeUTF() method if you want to read from the other end of the socket with DataInputStream.readUTF(). See the Javadoc on DataInput for more detail on why. As an alternative, try using a buffered reader or scanner to read in your data.


text:
Q: Join tables in QGis 2.01. Dufour I performed a "join" going to the properties option in a shapefile (in this case is just a table), in order to join the attributes from another shapefile that has a field in common, specifically "OBJECT_ID".
Some features appear with the right numbers and others with "Null".
However, in the shapefile I wish to join the information is correct and there is no "Null" in the trable.
Any idea why this happens?


text:
Q: Triggering a system-wide garbage collection I would like to know whether it is possible to trigger a system-wide garbage collection from a privileged system service in the Android Framework? I was thinking of something like a specialized signal that once trapped by the process running the dalvik VM will do a garbage collection in-place. Another alternative would be an API for AcitivityManager (or some other system service).

A: There is certainly nothing documented or supported for this.
If anything, I would expect them to have logic to prevent GC from occurring on 2+ processes at once. Triggering an immediate GC in all Dalvik processes would grind the device to a halt, particularly on single-core devices, as a couple of dozen processes all try to do GC at once.
Of course, you are welcome to download the Android source code, modify it to suit, and deploy a ROM mod with your changes on devices that you control.


text:
Q: Possible to setup OpenVPN between two servers?  And how? Apologies if this is a FAQ but I did not find it in the answers, hence, I'm positing it here. I have a following scenario and I am curious how can I use OpenVPN-(AS) to solve my issue.

*

*I have two Application servers in two different LANs, separated by WAN, that need to communicate with each other over around 2500 different ports.

*Both of them have Static IP addressing and IP addresses cannot be changed on the fly.

*I only have SSL port open for me to communicate with over.

Questions:

*

*Can I build a SSL tunnel using OpenVPN to do what I need?

*will the following OpenVPN-AS scenario work?

Scenario:

*

*I setup a publicly visible VPN Server (vpnserver.somedomain.com)

*Make Application servers on both sides and connect to this publicly visible VPN server using the OpenVPN-Client.

*Connect from Application server 1 to Application Server 2 just like they can see each other.

Is this feasible with OpenVPN, and if so, are there any pointers on how to achieve this?

A: Yes you can do what's in your scenario. Read this and enable "client-to-client" in your config.
You only need to set up the config, generate the certs (easy-rsa, very simple), and start the processes. Just don't forget the "client-to-client" option in the config file.
The other possibility is to set up server on one of the servers, and client on another (if you have a free port visible from outside on one of them - if you only have tcp/443 it's not such a good idea, since tcp-over-tcp has alot of overhead, but will still work, if there is no better solution).


text:
Q: Spotlight effect with css, html, javascript I've designed a spotlight effect with css, html and java. This is the link to the page: https://civitonia.com/
The spotlight follows the cursor, but as you can see, when you refresh the page or when you open it, the spotlight is not center on the page but you can see it a the bottom right. I'd like to set a "center point" or something similar that send the spotlight effect at the center of the page every time I refresh it/open it. Is it possible?
CSS:
.spotlight {
    position: fixed;
    width: 100%;
    height: 100%;
    pointer-events: none;
    background-image: radial gradient(circle, transparent 160px, rgba(0, 0, 0, 0)
    200px);
    }

SCRIPT:

A: You can set spotlight to center by setting its radial gradient at half of window's innerWidth and innerHeight on "DOMContentLoaded".
window.addEventListener("DOMContentLoaded", () => {
        const spotlight = document.querySelector('.spotlight');
        let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
        spotlight.style.backgroundImage = `radial-gradient(circle at ${window.innerWidth/2}px ${window.innerHeight/2}px, ${spotlightSize}`;
        window.addEventListener('mousemove', e => updateSpotlight(e));
        function updateSpotlight(e) {
            spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
        }
    });

Snippet:

window.addEventListener("DOMContentLoaded", () => {
  const spotlight = document.querySelector('.spotlight');
  let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
  spotlight.style.backgroundImage = `radial-gradient(circle at ${window.innerWidth/2}px ${window.innerHeight/2}px, ${spotlightSize}`;
  window.addEventListener('mousemove', e => updateSpotlight(e));

  function updateSpotlight(e) {
    spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
  }
});
.spotlight {
  position: fixed;
  width: 100%;
  height: 100%;
  pointer-events: none;
  background-image: radial-gradient(circle, transparent 160px, rgba(0, 0, 0, 0) 200px);
}

To absolutely position the spotlight on mobile screen can use matchMedia method, to check the min width of the screen. Based on that, you can attach the mouse move event listener to it. In the code below, if min width is less than 800px, the spotlight is placed at center of screen else it will add the mousemove event listener to it.
Also, you might want to handle window resize i.e remove the mousemove event listener and reposition the spotlight if min width becomes < 800px and reattach the listener if becomes > 800px again (after becoming < 800px)

window.addEventListener("DOMContentLoaded", ()=>{
  const spotlight = document.querySelector('.spotlight');
  let spotlightSize = 'transparent 160px, rgba(0, 0, 0, 0.85) 200px)';
  //attach mousemove event listener if media query matches.
  if (matchMedia('only screen and (min-width: 800px)').matches) {
    window.addEventListener('mousemove', updateSpotlight);

    function updateSpotlight(e) {
      spotlight.style.backgroundImage = `radial-gradient(circle at ${e.pageX / window.innerWidth * 100}% ${e.pageY / window.innerHeight * 100}%, ${spotlightSize}`;
    }

  } else {
    spotlight.style.backgroundImage = `radial-gradient(circle at ${window.innerWidth/2}px ${window.innerHeight/2}px, ${spotlightSize}`;
  }
});
.spotlight {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
  background-image: radial-gradient(circle at 50% 50%, transparent 160px, rgba(0, 0, 0, 0.85) 200px);
}

@media only screen and (min-width: 800px) {
  .spotlight {
    position: fixed;
    background-image: radial-gradient(circle at 50% 50%, transparent 160px, rgba(0, 0, 0, 0) 200px);
  }
}


text:
Q: OnSelectedIndexChange not firing even with autopostback=true Ok I'm a little stumped here. I have an asp:Dropdownlist on the page. It gets populated via a web service call like this:
Ajax.GetSubDevelopments(developmentId, function (results) {
    var subDevelopments = $j("#<%=ddlMinorAssociation.ClientID %>");
    subDevelopments.empty();
    $j('<option />', { value: "-1", text: "Select a sub association" }).appendTo(subDevelopments);
        $j.each(results, function (index, value) {
            $j('<option />', { value: value.SubDevelopmentID, text: value.Name }).appendTo(subDevelopments);
        });
        subDevelopments.show();
    });

The actual control itself looks like this:
<asp:DropDownList ID="ddlMinorAssociation"
   OnSelectedIndexChanged="ddlMinorAssociation_SelectedIndexChanged"
   AutoPostBack="true" runat="server" CssClass="hidden">
</asp:DropDownList>

The intent is that when the user selects a subdevelopment, it will postback and then bind a datalist of results. Now the page is posting back, Page.Request.Params.Get("__EVENTTARGET") even says that it was posting back due to the drop down list. However, none of the code in my ddlMinorAssociation_SelectedIndexChanged function is being run. Here is that code:
protected void ddlMinorAssociation_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Write("hi");
}

Can anyone offer some insight as to what is going on???

A: Server-side, you dropdown list does not have any items. It cannot fire OnSelectedIndexChanged event because its index has not changed - it has no items to give it a meaningful current index value.

A: I believe the issue is related to the fact that when the page loaded, there were no elements in the dropdown list and ViewState didn't have any information of selected items; therefore, when it posts back, it determines that there hasn't been any IndexChanged event to fire.
The fact that it posts back is just because the Autoposback property is set to true which basically fires a normal form submit.
If you want this to work, change the AutoPostback property to false and hook code to the onchange event instead, then fire another Ajax request to whatever method you need to execute on the server side and bind the data on the client side.


text:
Q: Ionic 3 lazy loading with sub-page I just started to refactor my app trying to use the Ionic 3 Lazy Loading.
For instance I have a page EventPage which now has a EventPageModule.
Everything works fine went navigating to it with a string reference.
But what I can't manage to do is to open a sub-page from this exact page.
Sub-page is JoinersPage...
JoinersPage:
// JoinersPage
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-joiners',
  templateUrl: 'joiners.html',
})
export class JoinersPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad JoinersPage');
  }

}

JoinersPageModule:
// JoinersPageModule
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { JoinersPage } from './joinersbis';

@NgModule({
  declarations: [
    JoinersPage,
  ],
  imports: [
    IonicPageModule.forChild(JoinersPage),
  ],
})
export class JoinersPageModule {}

EventPageModule:
// EventPageModule
import { NgModule } from '@angular/core';
import { MomentModule } from 'angular2-moment';
import { IonicPageModule } from 'ionic-angular';
import { IonicImageLoader } from 'ionic-image-loader';

import { DirectivesModule } from '../../directives/directives.module';
import { PipesModule } from '../../pipes/pipes.module';

import { EventPage } from './event';
import { EventChatComponent } from './event-chat/event-chat.component';

@NgModule({
  declarations: [
    EventPage,
    EventChatComponent
  ],
  imports: [
    IonicPageModule.forChild(EventPage),
    IonicImageLoader.forRoot(),
    DirectivesModule,
    MomentModule,
    PipesModule
  ],
  entryComponents: []
})
export class EventPageModule {}

When I click the button that is supposed to open the JoinersPage with the following code this.navCtrl.push('JoinersPage');
I get the following error:
Error: No component factory found for JoinersPage. Did you add it to @NgModule.entryComponents?
Error: No component factory found for JoinersPage. Did you add it to @NgModule.entryComponents?

*

*I though that the all purpose of Ionic 3 Lazy Loading was to avoid importing the pages

*How could I solve my issue ?


text:
Q: Regex matching of incomplete strings "as-you-type" What would be a good practice to match strings while the user is typing them in?
I would like to take this regex for matching a time as an example:
/(\d\d?)(:\d\d?)?\s?(am|pm)?/ matches 12:30 am, 9 pm, 23:00 perfectly fine.
It only becomes tricky when you want to provide feedback while the user is typing in that string.
12: is not matched, neither would 12:30 p.
My solution would be to use a second, independend, regex for for the matching of incomplete strings that includes all input possibilities:
/(\d\d?)(:\d\d?|:)?\s?(|a|p|am|pm)?/ will match 12: and 12:30 p just fine.
Is there a better, more elegant way, to do this?


text:
Q: jQuery / Prototype conflict: only in webkit, in bookmarklet I most likely have the same problem as in this question:
Weird Chrome prototype/jQuery conflict
Basically it appears Prototype is conflicting with jQuery in Safari and Chrome. The solution in the question was to include prototype first, however I can't do that:  I'm using jQuery loaded in my bookmarklet, and so some sites it is used on will always have Prototype already loaded.  Now let's ignore for the moment the wisdom of using jQuery in the bookmarklet.  It seems to me there should be a solution here (though I can't find it), for these reasons:
1) This conflict does not appear to occur at all in Firefox.
2) Though the question linked to above cites a page stipulating that jQuery should be included first,  I no longer find that reference there.  So maybe it is not current?
Error Example: once jQuery is loaded (e.g. you can test it's version -1.4.4),  if you try in the firebug console:
jQuery('p:')
#yields =>  []
#or
jQuery('p:first')
# yields => TypeError: Object #<an Object> has no method 'find'

Some other notes:
-I have tried noConflict().  This does not seem to work at all.
-I never refer to '$' in my code, but only use 'jQuery'
-Using jQuery from the Google CDN
-Moving all the bookmarklet code into a frame would be very difficult, if possible at all, so I'd rather not go there.
Thanks for your help!

A: I had to do this for a client project, and ran into the exact same issue. After some research it looks like the conflict doesn't exist in 1.4.2, but does in 1.4.3 (I'm not sure about later versions). I downgraded to 1.4.2 and my bookmarklet now works on pages with Prototype.
Third comment here:
http://forum.jquery.com/topic/jquery-conflicts-with-prototype-and-the-fix

A: I believe that this is now fixed in jquery 1.5+ ....


text:
Q: Connect bitbucket project with Jenkins I tried adding a Bitbucket repository to Jenkins and it failed due to an error - see below. How Can I solve this issue?

A: Enter your BitBucket credentials in the window which opens when you click on the "add" button. After they have been added you will be able to select them in the screen you are showing and it should all be fine.


text:
Q: how to add sender into an HTML coded email? I need to send an email from my iPhone app but the name of the sender needs to be included within the body.
I do not know how to do that.

A: If you're using MFMailComposeViewController it takes the user's 'default' email account (as set up in Settings) and the email is sent from there. AFAIK, there's no way to obtain that email address (and the name that goes with it) programmatically.
But if your app can somehow get the user to associate their sender email account (via an addressbook picker) then you could use the standard AddressBook APIs to get the sender name and then insert that into the message.
[ It's not clear from your question if you're having problems with sending email, getting user names from contacts, or compositing HTML messages. Perhaps if you edited your question and explained what you're trying to do and what you've tried you'll get a better answer. ]


text:
Q: Ionic 2 android version fails My ionic 2 project is android. Application works android 5.x.x or higher version. But application not work older versions.
My project added plugin cordova-plugin-x5engine-webview. Project doesn't work.
Please help me
Thanks...

A: Add Crosswalk plugin to your project:
cordova plugin add cordova-plugin-crosswalk-webview
Find more details in pluign page: https://www.npmjs.com/package/cordova-plugin-crosswalk-webview


text:
Q: Ruby how to delegate module function of Namespace to Namespace::Base inner class I was confronted against choosing either #1 :
class Abstract
end
class Abstract::Foo < Abstract
end
class Abstract::Bar < Abstract
end

versus #2 :
module Abstract
  class Base
  end
  class Foo < Base
  end
  class Bar < Base
  end
end

I ended up choosing option #2, as my Abstract felt more like a namespace, and I could eventually add other things like
module Abstract # Instead of class if I had used option #1
  class SomeAbstractService
  end
end

However I feel that calling Abstract::Base.some_class_method is a bit weird. it possible to add a module function delegation ? For example if my Base is an ActiveRecord or Mongoid model (so Foo and Bar are like STI), i'd like to be able to query the collection/table with
Abstract.where(...) instead of Abstract::Base.where(...)
Is it possible to delegate the module function .where to the constant/class Base ?
Something like
module Abstract
  class Base
  end

  delegate_module_function :where, to: :Base
end

Or is there a different/better way to do that ?

A: You can use a standard Ruby library called Forwardable.
require 'forwardable'

module Abstract
  extend SingleForwardable
  class Base
    def self.where(p)
      "where from base : #{p}"
    end
  end

  delegate :where => Base
end

Abstract.where(id: 3)
# => "where from base : {:id=>3}"

For multiple methods, you can write :
delegate [:where, :another_method] => Base


text:
Q: Generalization of Moore graphs -- not geometries I was thinking about the following problem: Suppose you have a $k$-uniform hyper graph (simplicial complex of dimension $k$) with a complete $(k-1)$-skeleton, and some form of regularity (e.g. every vertex appears in $d$ facets, or every $(k-1)$-simplex appears in $m$ facets).  Suppose that the smallest cycle under the $\mathbb{Z}/2\mathbb{Z}$ boundary operator on the $k$-facets is of size D.  What can we say about the minimum number of vertices? Of facets?
This is a generalization of Moore graphs in a different direction than Moore geometries.  There a cycle is a closed path from vertex-to-facet-to-vertex; here it is a homological cycle (a more geometric interpretation, IMO).


text:
Q: Computing an Ito Integral using the Definition Let $B_t$ be a brownian motion adapted to $\mathcal F_t$. For general $\mathcal F_t$-adapted processes $X_t$ the Ito-integral could be defined as
$$
 \int_0^t X_s dB_s = \lim_{n\to \infty} \int_0^t X_s^{(n)} dB_s
$$
where the $X_t^{(n)}$ are simple processes approximating $X_t$ such that for each $0 = t_0 < t_1 < \ldots < t_k = t$ as the constant value on the interval $[t_i, t_{i+1})$ the left end point is choosen, i.e. $X_t^{(n)}(t) = X_{t_i}$ for $t_i \le t < t_{i+1}$ and such that
$$
 \lim_{n\to \infty} E\int_0^T | X_t^{(n)} - X_t |^2 dt = 0.
$$
Now I am looking for examples where this definition is used to compute the integral (and not Ito's Lemma). The only one I find in the literature are
$$
 \int_0^t B_s dB_s \quad \mbox{ and } \quad \int_0^t B_s^s dB_s
$$
For example, for the first we can choose
$$
 \int_0^1 B_s dB_s = \lim_n \sum_{i=0}^{n-1} B_{i/n} (B_{(i+1)/n} - B_{i/n})
$$
and by $\sum_{i=0}^{n-1} B_{i/n} (B_{(i+1)/n} - B_{i/n}) = \frac{1}{2} B_1^2 - \frac{1}{2} \sum_{i=0}^{n-1} (B_{(i+1)/n} - B_{i/n})^2$ we have
$$
  \int_0^t B_s dB_s. = \frac{1}{2} B_1^2 - \frac{1}{2}
$$
where the last term approaches $1$ as this is the quadratic variation of the Brownian motion. Another computation using the definition with the law of large numbers could be found on the german wikipedia.
Now I am looking for other examples where the definition is used, do you know any? For example for $\exp(B_t)$, by using Ito's Lemme we find
$$
 \int_0^t \exp(B_s) dB_s = \exp(B_t) - \frac{1}{2}\int_0^t B_s ds
$$
but I do not know how to derive this result using just the definition (i.e. finding an approximating series of simple processes).

A: Instead of using exp, I'll show how to derive $\int_0^t f(B_t)\,dB_t$, from the definition, assuming $\,f''$ exists and is continuous.
Let $F(x)=\int_0^xf(s)\,ds$. We of course start with a partition $0=t_0<t_1<\dots<t_m=t$, and setting $B_k=B_{t_k}$. Let $\mu=\sup_k t_{k+1}-t_k$ be the mesh of the partition.
Write
$$
F(B_{k+1})=F(B_k)+f(B_k)(B_{k+1}-B_k)+\frac12f'(B_k)(B_{k+1}-B_k)^2+R_k(B_{k+1})
$$
where $R_k(x)$ is the remainder term for the Taylor series centered at $B_k$. Rearranging, and letting $\Delta B_k=B_{k+1}-B_k$,
$$
f(B_k)\Delta B_k=F(B_{k+1})-F(B_{k})-\frac12 f'(B_k)(\Delta B_k)^2-R_k(B_{k+1})
$$
We then sum the above expression over $0\le k\le m-1$, and take the limit in probability as $\mu\to 0$ (meaning we are really using a sequence of partitions). The LHS of above becomes $\int f(B_t)dB_t$, by definition.
On the right, the $F(B_{k+1})-F(B_{k})$ part is telescoping, adding up to $F(t_n)-F(t_0)=F(t)$.
To evaluate the $f'(B_k)(\Delta B_k)^2$ part, we let $\Delta t_k=t_{k+1}-t_k$, and replace this with
$$
f'(B_k)\Delta t_k + f'(B_k)((\Delta B_k)^2 - \Delta t_k)
$$
Then $\sum_{k=0}^{m-1}f'(B_k)\Delta t_k \to \int_0^t f'(B_k)dt$, and $\sum_{k=0}^{m-1}f'(B_k)(\Delta B_k - \Delta t_k)\to 0$. You show the last limit approaches zero by computing its variance:
$$
Var\left(\sum_{k=0}^{m-1}f'(B_k)((\Delta B_k)^2 - \Delta t_k)\right)=\sum_{k=0}^{m-1}Var(f'(B_{k}))(\Delta t_k)^2 Var\left(\frac{\Delta (B_k)^2}{\Delta t_k}-1\right)$$
 $$\qquad \qquad \qquad\le Ct\cdot \mu\cdot \kappa\cdot \sum \Delta t_k=Ct\mu \kappa t\stackrel{\mu\to 0}\to 0$$
where $C=\sup_{s\in [0,t]} f'(s)$, so that $Var(f'(B_k))\le Var(CB_k)\le C^2 t_k\le C^2t$, and $\kappa$ is the variance of a $\chi^2$ random variable (note that $\frac{\Delta (B_k)^2}{\Delta t_k}$ are i.i.d. $\chi^2$). Since the variance $\to0$, and its mean is zero, the LHS $\to 0$ in $L_2$.
Finally, letting $K=\sup_{0\le s\le t}f''(t)$, the remainder term $R(B_{k+1})$ is uniformly bounded by $K(\Delta B_k)^3$, and a similar variance calculation shows that $\sum_{k=0}^{m-1} R_k(B_{k+1})\to 0$.
Putting this all together,
$$
\int_0^t f(B_k)\,d B_t=F(B_t)-\frac12\int_0^t f'(B_k)\,dt
$$


text:
Q: Android: Gridview going blank while scrolling fast the GridView is going blank in android if i scroll very fastly
please give me a solution for this..
Thanks in advance..
this is my code
gridView.setAdapter(new ImageAdapter(ChangedDashboard.this, stringarray));

this is my adapter class which is set on the gridview
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] menuvalues;

public ImageAdapter(Context context, String[] menuValues) {
    this.context = context;
    this.menuvalues = menuValues;
}
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View gridView;

    if (convertView == null) {

        gridView = new View(context);

        // get layout from mobile.xml
        gridView = inflater.inflate(R.layout.changedashboard, null);

    } else {
        gridView = (View) convertView;
    }

    TextView textView = (TextView) gridView
    .findViewById(R.id.textView1);
    textView.setText(menuvalues[position]);

    // set image based on selected text
    ImageView imageView = (ImageView) gridView
    .findViewById(R.id.imageView1);

    String mobile = menuvalues[position];

    if (mobile.equals("1")) {
        imageView.setImageResource(R.drawable.new1);
    } else if (mobile.equals("2")) {
        imageView.setImageResource(R.drawable.new2);
    } else if (mobile.equals("3")) {
        imageView.setImageResource(R.drawable.new3);
    }else if (mobile.equals("4")) {
        imageView.setImageResource(R.drawable.new4);
    } else if (mobile.equals("5")) {
        imageView.setImageResource(R.drawable.new5);
    }else if (mobile.equals("6")) {
        imageView.setImageResource(R.drawable.new6);
    }

    return gridView;
}

public int getCount() {
    return menuvalues.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

}
Please give me the solution for this
Updated code
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] menuvalues;

public ImageAdapter(Context context, String[] menuValues) {
    this.context = context;
    this.menuvalues = menuValues;
}
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View gridView;

    if (convertView == null) {

        gridView = new View(context);

        // get layout from mobile.xml
        gridView = inflater.inflate(R.layout.changedashboard, null);
        ViewHolder holder = new ViewHolder();
        holder.textView = (TextView) gridView
                .findViewById(R.id.textView1);
        holder.imageView = (ImageView) gridView
                .findViewById(R.id.imageView1);
        gridView.setTag(holder);

    } else {
        gridView = (View) convertView;
    }

    /*TextView textView = (TextView) gridView
    .findViewById(R.id.textView1);*/

    // set image based on selected text
    /*ImageView imageView = (ImageView) gridView
    .findViewById(R.id.imageView1);*/

    String mobile = menuvalues[position];

    ViewHolder holder = (ViewHolder)gridView.getTag();
    holder.textView.setText(mobile);
    if (mobile.equals("1")) {
        holder.imageView.setImageResource(R.drawable.new1);
    } else if (mobile.equals("2")) {
        holder.imageView.setImageResource(R.drawable.new2);
    } else if (mobile.equals("3")) {
        holder.imageView.setImageResource(R.drawable.new3);
    }else if (mobile.equals("4")) {
        holder.imageView.setImageResource(R.drawable.new4);
    } else if (mobile.equals("5")) {
        holder.imageView.setImageResource(R.drawable.new5);
    }

    return gridView;
}

public int getCount() {
    return menuvalues.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}
public static class ViewHolder {
    TextView textView;
    ImageView imageView;
}

}

A: User ViewHolder approach for re-using views. because, every time you scroll, you are finding  views by id, which take some processing and may cause very minor delay causing GridView to blink.
Here are some useful links to get idea of ViewHolder.

*

*why does the ViewHolder pattren work?

*ViewHolder pattern: caching effectively

*Commonsware:AdapterViews and Adapters see ViewHolder part specifically.

A: I face same issue May be problem with the height of TextView. So, make TextView single line like:
android:singleLine="true"
or, If u want 2 or 3 lines for some of the items, then make all the items have 2 or 3 lines like:
android:minLines="2"
refer: GridView breaks while scrolling


text:
Q: ImageMagick causing captcha to be black out I am having issues with ImageMagick. I downloaded ImageMagick through Homebrew and for some reason the captcha appears blacked out.
This is what I am getting:

Here is the ImageMagick version I am using:
Hamels-MacBook-Air:gitreports HD$ magick -version
Version: ImageMagick 7.0.5-4 Q16 x86_64 2017-03-25 http://www.imagemagick.org
Copyright: © 1999-2017 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC HDRI Modules
Delegates (built-in): bzlib freetype jng jpeg ltdl lzma png tiff xml zlib

Also this is what I am receiving in the console:
Started GET "/issue/hd719/Bloc-Jams" for ::1 at 2017-04-25 21:02:29 -0400
Processing by RepositoriesController#repository as HTML
  Parameters: {"username"=>"hd719", "repositoryname"=>"Bloc-Jams"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."username" = ? LIMIT 1  [["username", "hd719"]]
  Repository Load (0.3ms)  SELECT  "repositories".* FROM "repositories" INNER JOIN "repositories_users" ON "repositories"."id" = "repositories_users"."repository_id" WHERE "repositories_
users"."user_id" = ? AND "repositories"."name" = ?  ORDER BY name ASC LIMIT 1  [["user_id", 1], ["name", "Bloc-Jams"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."username" = ? LIMIT 1  [["username", "hd719"]]
  CACHE (0.1ms)  SELECT  "repositories".* FROM "repositories" INNER JOIN "repositories_users" ON "repositories"."id" = "repositories_users"."repository_id" WHERE "repositories_users"."us
er_id" = ? AND "repositories"."name" = ?  ORDER BY name ASC LIMIT 1  [["user_id", 1], ["name", "Bloc-Jams"]]
  SimpleCaptcha::SimpleCaptchaData Load (0.2ms)  SELECT  "simple_captcha_data".* FROM "simple_captcha_data" WHERE "simple_captcha_data"."key" = ?  ORDER BY "simple_captcha_data"."id" ASC
 LIMIT 1  [["key", "438f5570aeba7ef4658ee2505ced9112e7221fa6"]]
   (0.7ms)  begin transaction
  SQL (1.1ms)  UPDATE "simple_captcha_data" SET "value" = ?, "updated_at" = ? WHERE "simple_captcha_data"."id" = ?  [["value", "SJZSRC"], ["updated_at", "2017-04-26 01:02:29.640800"], ["
id", 1]]
   (1.1ms)  commit transaction
  Rendered simple_captcha/_simple_captcha.erb (0.8ms)
  Rendered repositories/repository.html.erb within layouts/application (42.4ms)
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
Completed 200 OK in 319ms (Views: 258.7ms | ActiveRecord: 4.9ms)

Started GET "/simple_captcha?code=438f5570aeba7ef4658ee2505ced9112e7221fa6&time=1493168549" for ::1 at 2017-04-25 21:02:30 -0400
  SimpleCaptcha::SimpleCaptchaData Load (0.2ms)  SELECT  "simple_captcha_data".* FROM "simple_captcha_data" WHERE "simple_captcha_data"."key" = ?  ORDER BY "simple_captcha_data"."id" ASC
 LIMIT 1  [["key", "438f5570aeba7ef4658ee2505ced9112e7221fa6"]]
  CACHE (0.0ms)  SELECT  "simple_captcha_data".* FROM "simple_captcha_data" WHERE "simple_captcha_data"."key" = ?  ORDER BY "simple_captcha_data"."id" ASC LIMIT 1  [["key", "438f5570aeba
7ef4658ee2505ced9112e7221fa6"]]

I can also provide any other information that is requested.
-Thank you!

A: As I said in my comments the code posted by @emcconville worked for me on a windows PC.
It failed when using magick and as I suspected magick ( V7 ) needs the operators in a different order as it is stricter than V6. So this worked again for me on my PC:
magick -size 100x28 -background white -gravity Center -fill darkblue -pointsize 22  label:12345 -wave 2x92  -implode 0.2 "E:\Pictures\temp.jpg"

I would guess SimpleCapture is not V7 compatible; have you a V6 version you could try?
I am using a V7 version but it also has a legacy V6 version built in but might not work on a mac?


text:
Q: Mercurial: diffs in a particular changeset? This is almost exactly a duplicate of Examining a single changeset in Mercurial, and without doubt a duplicate of another question I can't find on SO through Google alone.
I'm looking back through a Mercurial repo, and I want to see what exactly changed between two revisions (let's say 2580 and 2581):
hg log -v -r 2581

gives me all the files that changed.
How can I also see the diffs of these files?
Thanks.

A: Revision 2580 isn't necessasrily the parent revision of 2581.  It's easy to check if it is, of course, but easier yet is to just do:
hg log -p -r 2581

That compares 2581 to its (first) parent revision no matter what it is, and most clearly encompasses the answer to the question "what the hell did 2581 do?"

A: Try hg diff -r 2580 -r 2581.

A: hg diff -r 2580 -r 2581

This is a wrong example. The revision 2580 can be in another branch and you get diff between two branches.
Use
hg log -p -r 2581

or hg diff -c 2581
The difference between them in the first lines. Hg log also show information about changeset (parent, author, date, ...)
I prefer second variant hg diff -c ... because it can store to patch files.
hg diff -c 2581 > revision_2581.patch

A: Another solution is to use revset notation which IMO is a better solution as you can use it in more places consistently (ie you don't need to know about diff -c and log -p ).
hg diff -r 'last(ancestors(2581),2)'

Yes that is rather verbose compared to -c (for diff) and -p (for log).
However mercurial allows you to create revset aliases
In your .hgrc:
[revsetalias]

next(s) = descendants(s, 1)
prev(s) = last(ancestors(s),2)

Now you can do
hg diff -r 'prev(2581)'
hg log -r 'prev(2581)'