text:
Q: AS3 - addchild from stage to movieclip I just tried to add the movieclip "box" to the "container.holder". Both movieclips are on stage.
Nothing happends with this script.
container.holder.addChild(box);

What do I miss there?

A: Edit
Maybe you forgot to stage.removeChild(box)?
Old
When you add box in holder you have to convert its "global" (stage) position to a "local" (holder) position using the globalToLocal method.
var global : Point = new Point(box.x, box.y);
var local : Point = container.holder.globalToLocal(global);
container.holder.addChild(box);
box.x = local.x;
box.y = local.y;


text:
Q: How to backup a remote VPS machine? I am considering opting for a VPS solution, with the server running Ubuntu server. I am pretty new to this, and I need to come up with a backup policy for my server data.
Initial data is likely to be about 80Mb, and I expect the data to grow at approximately 5Mb to 10 Mb a day.
Can anyone recommend:

*

*A backup/restore policy (best
practises for a small startup)

*Which tools to use for backup?

Another thing that is not clear to me is - where are the files backed up to normally (in the case of remote servers). If the files are backed up to the same machine (or even to another machine but with the same host), there is potentially, a single point of failure).
How do people normally backup their server data, and is the probability of machine meltdown or the host company server farm "catching fire" so remote as not to be worth worrying about - especially for a small (read one man) startup like me?

A: My host (Slicehost) provides full-VM snapshot backups, which I can schedule to run daily. Slicehost staff are on record that these backups are stored on a separate host machine. This is by far the easiest way.
As a second level of backup, I push my /var/www directories up to Amazon S3 once a week, along with a database dump.

A: A backup/restore policy is something that is specific to an organisation due to differences in the value of the data and perceived risks. That said, given that you're a one-man startup, you would probably want to do something like:

*

*Start with daily backups of everything on the server and then only exclude files once you determine they are not needed;

*Keep all of your code in a revision control system. Git is a decent choice as you could then also store a copy on a free service like github, a copy on your workstation, and a copy on your server;

*Be sure to create cron jobs to perform database dumps using the database provided utilities.

For the tools, rdiff-backup works fairly well. Of course, don't forget to actually test that you can restore from your backups at least once. It is best to backup the data to another host or some other machine which is always online.
This is a good bare minimum to get you started. In future once you can justify the effort, you can worry about backup job monitoring, backup set size optimisation (date based log files, gzip --rsyncable rolling database dumps, exclude junk), having the backups go to a machine which is in a ready state to start serving, DR plans, higher frequency backups, daily automated restore testing, etc.

A: I'd suggest to choose a VPS provider that already has snapshot backups. Most providers perform redundant offsite backups - it is supposed to be better than you can setup yourself, especially if you are new to this.
Even some cheap (sub-$10/month) VPS hostings offer backups. If you pay $15+, then you will certainly find a major hosting company with well-organized backups included in the price.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I change the default date format? When I paste a date into Excel 2010 in the format "2012-12-07 00:00:00.000" I'd like it to be displayed by default as "2012-12-07", but it is actually displayed as "00:00.0".
I know I can work around this by prepending a ' or changing the cell format, but I'm interested in changing the default format.
An approach that almost works is going to Control Panel->Region and Language->Long Time format and changing it to something like "h". This results in Excel displaying the dates I paste in as "2012-12-07 00:00:00.000", but screws up times displayed outside of Excel.
The dates I'm pasting in are from SQL Server.

A: By default Excel starts all new workbooks without formatting. This means you have to tell Excel how you want the data formatted.
To achieve what you ask, you will need to format the column to the date format you want then save the file. You have to options to save the file:

*

*If you do not want this formatting applied to ALL new workbooks, save the formatted workbook as a template (xltx) or regular file. Each time you use this file it will be formatted for you to paste the data.

*If you want it to be the starting point for ALL new workbooks, then save the template as Book.xltx in the XLSTART folder. This folder is typically located at C:Program Files\Microsoft Office\Office14\XLSTART.
Now you have a formatted file to use. When you open the file and paste the data, paste only the values and it will format it the way you've chosen.

A: It completely depends on your system date and time format:

*

*Go to Control Panel.

*Click on "Region and Language".

*Click on "change date, time and number format".

*Set "short date", "long date", "short time" and "long time".


text:
Q: sql report each supplier, per wood type and grade I wanted to make a stock report for each supplier, group by wood type and grade.
My current SQL query:
    SELECT ll.supplier,
       obd.wood_type_output_breakdown                                AS
       wood_type,
       obp.grade_output_breakdown_panjang                            AS grade,
       (SELECT Sum(xobp.volume_breakdown_panjang)
        FROM   output_breakdown_panjang xobp
        WHERE  xobp.id_output_breakdown = obd.id_output_breakdown
               AND
       xobp.grade_output_breakdown_panjang = obp.grade_output_breakdown_panjang
               AND xobp.id_output_breakdown = ob.id_output_breakdown
               AND ob.id_output_breakdown = obd.id_output_breakdown) AS volume
FROM   loglist ll
       LEFT JOIN trimming t
              ON t.id_loglist = ll.id_loglist
       LEFT JOIN breakdown b
              ON b.id_trimming = t.id_trimming
       LEFT JOIN output_breakdown_detil det
              ON det.id_breakdown = b.id_breakdown
       LEFT JOIN output_breakdown ob
              ON ob.id_output_breakdown = det.id_output_breakdown,
       output_breakdown obd,
       output_breakdown_panjang obp
GROUP  BY Concat(ll.supplier, obd.wood_type_output_breakdown,
                    obp.grade_output_breakdown_panjang)
ORDER  BY ll.supplier,
          obd.wood_type_output_breakdown

but the result came out like this :

it should be like this :

here I attach the sql for you to help me out :http://s000.tinyupload.com/index.php?file_id=07777439563611215580
Can anyone help?

A: I finally found a solution :
> SELECT l.supplier, h.jenis_kayu_output_breakdown as jenis_kayu, g.grade_output_breakdown_panjang as grade,
SUM(distinct g.volume_breakdown_panjang) as volume
FROM output_breakdown_panjang as g
LEFT JOIN output_breakdown AS h ON h.id_output_breakdown = g.id_output_breakdown
LEFT JOIN output_breakdown_detil as i ON i.id_output_breakdown = g.id_output_breakdown
LEFT JOIN breakdown as j ON j.id_breakdown = i.id_breakdown
LEFT JOIN trimming as k ON k.id_trimming = j.id_trimming
LEFT JOIN loglist as l on l.id_loglist = k.id_loglist
group by CONCAT(l.supplier,h.jenis_kayu_output_breakdown,g.grade_output_breakdown_panjang)


text:
Q: How to avoid blocking the asyncio event loop with looping functions I'm using FastAPI with WebSockets to "push" SVGs to the client. The problem is: If iterations run continuously, they block the async event loop and the socket therefore can't listen to other messages.
Running the loop as a background task is not suitable because each iteration is CPU heavy and the data must be returned to the client.
Is there a different approach, or will I need to trigger each step from the client? I thought multiprocessing could work but not sure how this would work with asynchronous code like await websocket.send_text().
@app.websocket("/ws")
async def read_websocket(websocket: WebSocket) -> None:
    await websocket.accept()
    while True:
        data = await websocket.receive_text()

        async def run_continuous_iterations():
            #needed to run the steps until the user sends "stop"
            while True:
                svg_string = get_step_data()
                await websocket.send_text(svg_string)

        if data == "status":
            await run_continuous_iterations()
        #this code can't run if the event loop is blocked by run_continuous_iterations
        if data == "stop":
            is_running = False
            print("Stopping process")

A:
"...each iteration is CPU heavy and the data must be returned to the
client".

As described in this answer, a "coroutine suspends its execution only when it explicitly requests to be suspended", for example,  if there is an await call to an asynchronous operation/function; normally, to non-blocking I/O-bound tasks such as the ones described here (Note:  FastAPI/Starlette runs I/O-bound methods such as reading File contents in an external threadpool, using the async run_in_threadpool() function, and awaits them; hence, calling such File operations from your async def endpoint, e.g., await file.read() won't block the event loop—have a look at the linked answer above for more details). This, however, does not apply to blocking I/O-bound or CPU-bound operations, such as the ones mentioned here. Running such operations inside an async def endpoint will block the event loop; and hence, any further client requests will get blocked until the blocking operation is completed.
Additionally, from the code snippet your provided, it seems that you would like to be sending data back to the client, while at the same time listening for new messages (in order to check if the client sent a "stop" msg, in order to stop the process). Thus, awaiting for an operation to be completed is not the way to go, but rather executing that task in a separate thread or process (if this is a CPU-bound task)—as demonstrated in this answer, but without awaiting it—should be a more suitable way (Note: processes have their own memory, and hence, sharing websocket connections among multiple processes would not be natively feasible—have a look here and here for available options on that). Solutions on using a separate thread are given below.
Using asyncio's loop.run_in_executor() and ThreadPoolExecutor
Passing None as the executor argument loop.run_in_executor(), the default executor will be used; that is ThreadPoolExecutor.
import asyncio

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    is_running = True
    await websocket.accept()

    try:
        while True:
            data = await websocket.receive_text()

            async def run_continuous_iterations():
                while is_running:
                    svg_string = get_step_data()
                    await websocket.send_text(svg_string)

            if data == "status":
                is_running = True
                loop = asyncio.get_running_loop()
                loop.run_in_executor(None, lambda: asyncio.run(run_continuous_iterations()))

            if data == "stop":
                is_running = False
                print("Stopping process")

    except WebSocketDisconnect:
        is_running = False
        print("Client disconnected")

Using  asyncio's loop.run_in_executor() and custom ThreadPoolExecutor:
import concurrent.futures

#...  rest of the code is the same as above

@app.on_event("startup")
def startup_event():
    # instantiate the ThreadPool
    app.state.pool = concurrent.futures.ThreadPoolExecutor()

@app.on_event("shutdown")
def shutdown_event():
    # terminate the ThreadPool
    app.state.pool.shutdown()

#...  rest of the code is the same as above

if data == "status":
    is_running = True
    loop = asyncio.get_running_loop()
    loop.run_in_executor(app.state.pool, lambda: asyncio.run(run_continuous_iterations()))

#...  rest of the code is the same as above

Using threading's Thread:
#...  rest of the code is the same as above

if data == "status":
    is_running = True
    thread = threading.Thread(target=lambda: asyncio.run(run_continuous_iterations()))
    thread.start()

#...  rest of the code is the same as above


text:
Q: Python : why numba takes more time? I am using list comprehension to gather data from list of tuples. Code below:
data = [result[0] for result in results] #results is a list of tuples and i take first element from each tuple.

This works and all good.
Recently i came across numba module which will increase speed of loop execution ?
So i tried this to test timing:
import numba
from numba import literal_unroll
from datetime import datetime
import logging

numba_logger = logging.getLogger('numba')
numba_logger.setLevel(logging.WARNING)

@numba.jit(nopython=True)
def loop_faster(results):
    for result in literal_unroll(results):
        print(result)

tuples = (1.1, "Hello", 1, "World", "Tuple-1")

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

loop_faster(tuples)

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

for result in tuples:
        print(result)

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

i refereed this link for literal_unroll : https://numba.pydata.org/numba-doc/dev/reference/pysupported.html
However it seems for loop performs way better than numba method.
Results for above program :
2021-03-04 10:51:36.385
1.1
Hello
1
World
Tuple-1
2021-03-04 10:51:47.234
1.1
Hello
1
World
Tuple-1
2021-03-04 10:51:47.236

Why is this behavior ? numba took almost over 10-Seconds
For my case to form a list out of tuple's nth element , how can i implement using numba module ?

A: The reason is very simple, on first run of function a lot of time is spend in compiling Ayour code into C++ code and machine code, which is doing numba's JIT.
So you have to add param cache = True to you @numba.jit decorator to pre-cache compiled version. Also you have to call one time run before measuring time to ensure compilation. Also you have to run more loops iterations to mesure time more precisely, just 10 milliseconds run is not enough.
Following code does three things mentioned above. You can see that numba gives 5.5x times speedup.
Also I modified your code for a bit different logic, because printing logic will not measure time correctly. Numba is meant for very computational heavy code, not for printing to console. So I just created random integers array and computed this array +1. This is enough as an example code for you to see that Numba runs much faster.
Try it online!
import numba, logging, random
from datetime import datetime

numba_logger = logging.getLogger('numba')
numba_logger.setLevel(logging.WARNING)

@numba.njit(cache = True)
def loop_faster(results, n):
    for i in range(n):
        res = []
        for result in numba.literal_unroll(results):
            res.append(result + 1)

t = tuple(random.randrange(1 << 20) for i in range(100))

loop_faster(t, 10) # pre-compile numba

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

loop_faster(t, 1 << 16)

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

for i in range(1 << 16):
    res = []
    for result in t:
        res.append(result + 1)

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

Output:
2021-03-04 12:18:04.491
2021-03-04 12:18:04.840
2021-03-04 12:18:06.774


text:
Q: Jquery multiple choice quiz using clickable buttons I'm a beginner in Jquery.
I want to create a multiple choice quiz with over 30 questions. Each questions has four options assigned to 4 clickable CSS buttons - NOT radio buttons). The user clicks on just one button to make the choice. Each button would fire a script (in a click-function), and depending on the button clicked, (eg button A)  a point or no points is assigned to a variable in memory, then a new set of questions is automatically paged in to replace the former set. This goes on to the end of the bank of 30 questions, when total scores are then (and only then) displayed on screen.
I want the same buttons (A,B, C,D) to remain displayed on the screen throughout, without having CSS rewrite them, but each button be re-assigned a different correct or incorrect script (eg, this time question C is correct and, if clicked, awards 1 point) based on the next bank of questions and the correct button choice for the answer in that new bank.
It's easy to copy 30 banks of questions with their different questions into the html file, but there must be a more elegant way to switch the code from one button to the other, depending on the correct button to click, without having to use so many lines.

A: You can always use two arrays, one in which you put the correct and incorrect code, and then another 2D array, for each question and for each answer an index for the array with the code.
When you arrive at a certain question, loop through that part of the 2D array and attach the code to each answer.
For example:
var codeArray = [notCorrect, correct]; // your functions you have defined, that are called when the answer is correct or not correct.
var answerArray = [
  [1, 0, 0, 0],
  [0, 1, 0, 0],

  // ... etc ...

  [1, 0, 0, 0],
];

$('.button').click (function (event) {
  // get questionNumber and answerNumber
  codeArray[answerArray[questionNumber-1][answerNumber-1]](); // call the function, and mind the 0 indices!
}

EDIT, more info:
An array can be defined like this:
var myArray = [0, 1, 2, 3, 4, 5];

You can put any values in each 'slot'. In my example, I am only using 1's and 0's. To access these numbers in the array, use square brackets ([]).
You can also put functions into arrays (in my example, the codeArray. You can even give anonymous functions, like this:
var codeArray = [function () { alert("Not correct"); }, function () { alert("Correct!"); }];

The last few lines of code is the click handler for any .button click. If a user clicks a button with the class button, this function is triggered.
I hope this helped enough, if you don't understand any of this, please read some JavaScript books, and become a little more educated.

A: Another simple way would be to add a javascript property to the checkbox...
e.g.
element.answer = true;
...
elements.filter(function(cb, index){      return cb.answer === true && cb.checked; });


text:
Q: Twitter "Cancel and return to app " issue
This is the first page of twitter login, when i am clicking on cancel and return to app
My application get force close.
M using Twitter4J for this
Kindly suggest me what can be issue.
M using this code.
void OAuthLogin() {
        try {

            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(consumerKey, consumerSecret);
            requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
            String authUrl = requestToken.getAuthenticationURL();
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                    .parse(authUrl)));
        } catch (TwitterException ex) {
        Log.e("in Main.OAuthLogin", ex.getMessage());
        }
    }

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        if (uri != null && uri.toString().contains(CALLBACKURL)) {
            try {
                String verifier = uri.getQueryParameter("oauth_verifier");
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);
                String token = accessToken.getToken(), secret = accessToken
                        .getTokenSecret();
                twitter.setOAuthAccessToken(token, secret);

                twitter.updateStatus(base_link_url);
            this.displayTimeLine(token, secret); // after everything,
            } catch (TwitterException ex) {
                                }
        }
    }

My Manifest File:M using this code for my class
<activity android:name=".Test" android:configChanges="keyboard|keyboardHidden|orientation"
            android:screenOrientation="portrait" android:label="@string/app_name"
            android:launchMode="singleTask" android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="gauravmusic" android:host="twitt" />
            </intent-filter>
        </activity>

MY Callback Url:which m using in my code
private final String CALLBACKURL = "gauravmusic://twitt";

Now Suggest me where m going wrong.
After research i found that ,
            if (uri != null && uri.toString().contains(CALLBACKURL))
{

}

if i change this condition to
if (uri != null && uri.getScheme().toString().contains(CALLBACKURL_SCHEME)) {
}

Cancel,and return to app working fine now, but now i am unable to post tweet on my wall.
i add both condition together like that
   if (uri != null && uri.getScheme().toString().contains(CALLBACKURL_SCHEME) || uri.toString().contains(CALLBACKURL)) {

}

its also not working..
Kindly suggest me.
Hi i found answer. i find a pattern that when Cancel and Retun to app  link is clicked then this code is executed. In this case we are not login so we cant find value of String Verifier, and its gives NullPointer Exception.
if (uri != null && uri.toString().contains(CALLBACKURL)) {
            try {
                String verifier = uri.getQueryParameter("oauth_verifier");
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);
                String token = accessToken.getToken(), secret = accessToken
                        .getTokenSecret();
                twitter.setOAuthAccessToken(token, secret);

                twitter.updateStatus(base_link_url);
            this.displayTimeLine(token, secret); // after everything,
            } catch (TwitterException ex) {
                                }
        }

I change this line to
if (uri != null && uri.getScheme().toString().contains(CALLBACKURL_SCHEME)&& !uri.toString().contains("denied"))

After some research i found that when we click on Cancel and return to app link its uri is like that
DEBUG/URI!!!!!!!!!!!!!!!!!!!!!(5174): gauravmusic://twittdenied=FjgW7QQYpFDI03sDvIc5I1w6w2Xv67TFI9sKW1OyA

And when we are sucessully login then Uri is like that
08-17 10:31:19.182: DEBUG/URI(5278): gauravmusic://twitt?oauth_token=pm0E10vayzTViLGQpGZwwpIKhQ9aqwLrEBggiJ7vvPY&oauth_verifier=cHiWkuiQfygmlPeC7B6fNbiqv34gkPIdWctlavzGo80

Then i add condition
!uri.toString().contains("denied")(bcz when we are not login uri contains a word "denied")
Its work fine for me.
Now when i click on Cancel and Return to app  , it will not reach to this line or in this loop .
    String verifier = uri.getQueryParameter("oauth_verifier");
Now everything works fine. Suggest me if any better idea is for handle this.I dont want to depend on Uri's "denied" word.

A: Check this link for Twitter Integration in Android Application.
It works great and perfectly.
Ensure that you gave some Dummy Callback in the Field CallBack URL in the Settings page of your Application.
Integrating Twitter in Android Application
Edit :
I guessed what is happening in our your code , If you cancel the App from Authorization then there will be no value for below verifier
String verifier = uri.getQueryParameter("oauth_verifier");

Since there is no value it will throws NULL POINTER EXCEPTION and it will go from Try to Catch block, hence
 twitter.updateStatus(base_link_url);

will no reached
so the Tweet is not posted.
If you need to check this add come Log to Catch Block so that you can see what is happening.
`


text:
Q: Adding sass to the project - installation not working - cb.apply is not a function I'm trying to use sass in my project, but installing sass isn't working in my windows 10 machine by using the command npm i -g sass. and I getting the following error in npm-debug.log
    0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\Arun\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'i',
1 verbose cli   '-g',
1 verbose cli   'sass'
1 verbose cli ]
2 info using npm@3.10.10
3 info using node@v14.17.0
4 silly loadCurrentTree Starting
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 silly fetchPackageMetaData sass
8 silly fetchNamedPackageData sass
9 silly mapToRegistry name sass
10 silly mapToRegistry using default registry
11 silly mapToRegistry registry https://registry.npmjs.org/
12 silly mapToRegistry data Result {
12 silly mapToRegistry   raw: 'sass',
12 silly mapToRegistry   scope: null,
12 silly mapToRegistry   escapedName: 'sass',
12 silly mapToRegistry   name: 'sass',
12 silly mapToRegistry   rawSpec: '',
12 silly mapToRegistry   spec: 'latest',
12 silly mapToRegistry   type: 'tag'
12 silly mapToRegistry }
13 silly mapToRegistry uri https://registry.npmjs.org/sass
14 verbose request uri https://registry.npmjs.org/sass
15 verbose request no auth needed
16 info attempt registry request try #1 at 10:10:53 pm
17 verbose request id e008d98ed4542708
18 verbose etag W/"bf606690a2126312f5bf42d5684969d3"
19 verbose lastModified Sat, 22 May 2021 06:18:13 GMT
20 http request GET https://registry.npmjs.org/sass
21 http 304 https://registry.npmjs.org/sass
22 verbose headers {
22 verbose headers   date: 'Sun, 23 May 2021 16:40:56 GMT',
22 verbose headers   connection: 'keep-alive',
22 verbose headers   'cf-ray': '653fba911aca31a6-BOM',
22 verbose headers   'cache-control': 'public, max-age=300',
22 verbose headers   etag: '"bf606690a2126312f5bf42d5684969d3"',
22 verbose headers   'last-modified': 'Sat, 22 May 2021 06:18:13 GMT',
22 verbose headers   vary: 'Accept-Encoding',
22 verbose headers   'cf-cache-status': 'REVALIDATED',
22 verbose headers   'cf-request-id': '0a3bb2eead000031a669266000000001',
22 verbose headers   'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
22 verbose headers   server: 'cloudflare'
22 verbose headers }
23 silly get cb [
23 silly get   304,
23 silly get   {
23 silly get     date: 'Sun, 23 May 2021 16:40:56 GMT',
23 silly get     connection: 'keep-alive',
23 silly get     'cf-ray': '653fba911aca31a6-BOM',
23 silly get     'cache-control': 'public, max-age=300',
23 silly get     etag: '"bf606690a2126312f5bf42d5684969d3"',
23 silly get     'last-modified': 'Sat, 22 May 2021 06:18:13 GMT',
23 silly get     vary: 'Accept-Encoding',
23 silly get     'cf-cache-status': 'REVALIDATED',
23 silly get     'cf-request-id': '0a3bb2eead000031a669266000000001',
23 silly get     'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
23 silly get     server: 'cloudflare'
23 silly get   }
23 silly get ]
24 verbose etag https://registry.npmjs.org/sass from cache
25 verbose get saving sass to C:\Users\Arun\AppData\Roaming\npm-cache\registry.npmjs.org\sass\.cache.json
26 verbose correctMkdir C:\Users\Arun\AppData\Roaming\npm-cache correctMkdir not in flight; initializing
27 verbose stack TypeError: cb.apply is not a function
27 verbose stack     at C:\Users\Arun\AppData\Roaming\npm\node_modules\npm\node_modules\graceful-fs\polyfills.js:267:18
27 verbose stack     at FSReqCallback.oncomplete (fs.js:193:5)
28 verbose cwd C:\Users\Arun\Desktop\sass
29 error Windows_NT 10.0.19042
30 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Arun\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "i" "-g" "sass"
31 error node v14.17.0
32 error npm  v3.10.10
33 error cb.apply is not a function
34 error If you need help, you may report this error at:
34 error     <https://github.com/npm/npm/issues>
35 verbose exit [ 1, true ]

and in the console, I'm getting the following when installing sass
npm ERR! Windows_NT 10.0.19042
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Arun\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "i" "-g" "sass"
npm ERR! node v14.17.0
npm ERR! npm  v3.10.10

npm ERR! cb.apply is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\Arun\Desktop\sass\npm-debug.log

Any help really appriciated.

A: You have oddly old npm version. You should update it running
npm i -g npm

A: This is for anyone who comes across the same issue.
I'm finally able to fix the problem.
Note: I'm using a windows machine

*

*Go to C:\Users(your username)\AppData\Roaming

*Delete npm and npm_catche folders

*npm cache verify then

*npm cache clean --force
its worked.


text:
Q: How can I properly call any math related function in a class/controller? I tried to use the factorial php build in function gmp_fact() in one of my function in my class/controller.
I keep getting:
Call to undefined function App\Http\Controllers\gmp_fact()
Does anybody know why ? or How do I fix it ?
How's come I can use other functions like strlen, str_split, and so on ... ?
Do I need to include any kind of Math library or something ?

My Controller
<?php

namespace App\Http\Controllers;
use View, Input, Redirect;

class CodeController extends Controller {

    public function getFactorial($num)
    {
        $fact = 1;
        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;
        return $fact;
    }

    public function codingPuzzle()
    {
        return View::make('codes.puzzle');
    }

    public function codingPuzzleProcess()
    {

        $word     = strtoupper(Input::get('word'));
        $length   = strlen($word);
        $max_value = ($length * 26);
        $characters = str_split($word);

        $num = 1 ;
        $index = 1;

        sort($characters);

        //dd($characters);

        foreach ( $characters as $character) {
            $num += gmp_fact($index) * $index;
            $index ++;

        }

        return Redirect::to('/coding-puzzle')
            ->with('word', $word )
            ->with('num', $num )
            ->with('success','Submit successfully!');

    }

}


text:
Q: How to perform Code splitting with CommonsChunkPlugin This is my current bundle information which i got from bundle analyzer plugin,
Current bundle information
I want to move the jquery to a separate chunk and extract css into a separate single css bundle, is there any other optimization which i can do to reduce my bundle size?
My current webpack is this
webpack.base.js
   /**
 * COMMON WEBPACK CONFIGURATION
 */

    const path = require('path');
    const webpack = require('webpack');
   const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
   // const BundleAnalyzerPlugin = require('webpack-bundle-
   analyzer').BundleAnalyzerPlugin;
   const ExtractTextPlugin = require('extract-text-webpack-plugin');
   const autoprefixer = require('autoprefixer');
   // Remove this line once the following warning goes away (it was meant
   webpack loader authors not users):
   // 'DeprecationWarning: loaderUtils.parseQuery() received a non-string
   value which can be problematic,

   be replaced with getOptions()
   // in the next major version of loader-utils.'
   process.noDeprecation = true;
const environment = require('../../environments/environment');
let publicDeployPath = '/';
const loaderOptions = {};
if (!environment.isLocal) {
  publicDeployPath = environment.blobContainerPath;
  loaderOptions.root = environment.blobContainerPath;
  loaderOptions.minimize = true;
}

     module.exports = (options) => ({
    entry: options.entry,
    output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: publicDeployPath,
    }, options.output), // Merge with env dependent settings
    module: {
    rules: [
      {
        test: /\.js$/, // Transform all .js files required somewhere with
       Babel
        use: {
          loader: 'babel-loader',
          options: options.babelQuery,
        },
      },
      {
        test: /\.jsx$/, // Transform all .js files required somewhere with
           Babel
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: options.babelQuery,
        },
      },
      {
        // Preprocess our own .css files
        // This is the place to add your own loaders (e.g. sass/less etc.)

        test: /\.css$/,
        // exclude: /node_modules/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [{
            loader: 'css-loader',
            options: loaderOptions,
          }, {
            loader: 'postcss-loader',
            options: {
              plugins: () => [autoprefixer()],
            },
          },
          ] }, true),
      },
      // {
      //   // Preprocess 3rd party .css files located in node_modules
      //   test: /\.css$/,
      //   include: /node_modules/,
      //   loader: ExtractTextPlugin.extract({
      //     fallback: 'style-loader',
      //     use: [{
      //       loader: 'css-loader',
      //       options: loaderOptions,
      //     },
      //     ] }, true),
      // },
      {
        test: /\.mp3$/,
        loader: 'url-loader?limit=10000&mimetype=audio/mpeg',
        options: {
          publicPath: publicDeployPath,
        },
      },
      {
        test: /\.(eot|svg|otf|ttf|woff|woff2)$/,
        loader: 'file-loader',
        options: {
          publicPath: publicDeployPath,
        },
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              publicPath: publicDeployPath,
              progressive: true,
              optimizationLevel: 7,
              interlaced: false,
              pngquant: {
                quality: '65-90',
                speed: 4,
              },
            },
          },
        ],
      },
      {
        test: /\.html$/,
        use: 'html-loader',
      },
      {
        test: /\.json$/,
        use: 'json-loader',
      },
      {
        test: /\.(mp4|webm)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
          },
        },
      },
    ],
   },
   plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),
    // new BundleAnalyzerPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      'root.jQuery': 'jquery',
    }),
    // Always expose NODE_ENV to webpack, in order to use
       `process.env.NODE_ENV`
     // inside your code for any environment checks; UglifyJS will
     automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new AddAssetHtmlPlugin({ filepath: path.resolve(process.cwd(),
     'app/vendor/VidyoConnector.js'), hash: true }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    modules: ['app', 'node_modules'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
  node: {
    fs: 'empty',
      },
      });

webpack.production.js
    // Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const pathsToClean = [
  'build',
];
const cleanOptions = {
  root: path.resolve(__dirname, '..'),
  verbose: true,
  dry: false,
  allowExternal: true,
};
module.exports = require('./webpack.base.babel')({
  // In production, we skip all hot-reloading stuff
  entry: [
    path.join(process.cwd(), 'app/app.js'),
  ],
  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'reactjs',
      filename: 'reactjs.[chunkhash].js',
      minChunks: (module) => (
        // If module has a path, and inside of the path exists the name "somelib",
        // and it is used in 3 separate chunks/entries, then break it out into
        // a separate chunk with chunk keyname "my-single-lib-chunk", and filename "my-single-lib-chunk.js"
        module.resource && (/react/).test(module.resource)
      ),
    }),
    new CleanWebpackPlugin(pathsToClean, cleanOptions),
    new ExtractTextPlugin({ filename: 'style.[hash].css', disable: false, allChunks: true }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.[chunkhash].js',
      minChunks: (module) => (
        // If module has a path, and inside of the path exists the name "somelib",
        // and it is used in 3 separate chunks/entries, then break it out into
        // a separate chunk with chunk keyname "my-single-lib-chunk", and filename "my-single-lib-chunk.js"
        module.context && module.context.includes('node_modules')
      ),
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),
    new HtmlWebpackPlugin({  // Also generate a invalid page html
      filename: 'ppVideoInvalid.html',
      template: 'app/ppVideoInvalid.html',
    }),
    new HtmlWebpackPlugin({  // Generate a test client html
      filename: 'testClient.html',
      template: 'app/TestInterface/testClient.html',
    }),
  ],

  performance: {
    assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
  },
});


text:
Q: How can I find the value of inline margin-left using jquery I have the following code:
<div class="ongoing" style="width: +728px; margin-left: +12480px">

and I would like to use the value of margin-left for scrolling to a position.
I've used the below code to get the value of width, but it's not working for margin-left (because of the hyphen, I assume?):
$("div.ongoing")[0].style.margin-left

How can I get the margin-left value?
Thanks!

A: You need to use:
 $("div.ongoing")[0].style.marginLeft

or
 $("div.ongoing").css("marginLeft");//or .css("margin-left");

A: Try this
    $('div.ongoing').css('margin-left')


text:
Q: Variance as a function of parameters I am currently building a statistical model. According to data, the variance is non-constant, and it is likely based on a factor. Is there any statistical model with variance as a function of other parameters? What is its name, and can that model be fitted in R?

A: This looks like a standard heteroskedastic model, where we treat heteroskedasticity the "old-fashioned way", i.e. by explicitly modelling the error variance as a function of some other variables (which may be the regressors themselves or not). In its most simple form the model is Weighted Least Squares.
Various specifications have been examined in the literature, like for example
$$\sigma^2_i = (\mathbf z_i'\alpha)^2,\;\;\;\sigma^2_i = \exp\{\mathbf z_i'\alpha\}, \;\;\;\sigma^2_i = \sigma^2(\mathbf x_i'\beta)^2$$
The last case indicates that the variance is directly proportional to the conditional expected value of the dependent variable, while in the previous formulations, the $\mathbf z$ vector may contain the regressors or other variables.
The model can be estimated by a two-step least square procedure, or by maximum likelihood -note that the unknown parameter $\alpha$ is common for all $i$ and so we do not have an "incidental parameters" problem.
This approach always had the issue of misspecification that is almost certain to occur in specifying the functional form that characterizes the heteroskedasticity. After the arrival of White's standard errors and the "heteroskedasticity-robust" variance-covariance matrix, the main problem with using OLS regression was cleared away, and the "direct-modeling" approach is visibly less used than in the past, at least in Econometrics.

A: To me the question speaks of straight-up mixed models where the typical homogeneous (homoscedastic) error term is (possibly) decomposed into levels and (possibly) explained at each level using functions.
For example, suppose you have a model that looks like this:
(1) $y_{i} = \beta_{0} + \beta_{1}x_{1} + \beta_{2}x_{2} + \varepsilon_{i},$
where, say, $x_{1}$ is some continuous predictor, and $x_{2}$ is a nominal factor (for sake of simplicity).
Now suppose, as you suggest that the variance of $y$ depends on $x_{2}$. You might revise your model as in (2):
(2) $y_{i} = \beta_{0} + \beta_{1}x_{1} + \beta_{2}x_{2} + \varepsilon_{i0} + \varepsilon_{i2},$
where:
$\left[\begin{array}{c}\varepsilon_{0,i}\\
\varepsilon_{2,i}\end{array}\right] \sim \mathcal{N}\left(0,\Omega_{\varepsilon}\right):\Omega_{\varepsilon}=\left[\begin{array}{cc}\sigma^{2}_{\varepsilon 0} &  \\
0 & \sigma^{2}_{\varepsilon 2} \end{array}\right]$
(The covariance in $\Omega_{\varepsilon}$ is assumed zero here, since you've got factors with what I am assuming are mutually exclusive categories. If you are not comfortable with that assumption, and think you can estimate a covariance term, $\sigma_{\varepsilon02}$, go ahead and include that.)
You can even use this model if there is no fixed effect of $x_{2}$ on $y$ (i.e. if $x_{2}$ only contributes a random effect). This could be accomplished implicitly by letting a near zero estimate of $\beta_{2}$ be part of the model as in (2), or explicit as in (3):
(3) $y_{i} = \beta_{0} + \beta_{1}x_{1} + \varepsilon_{0,i} + \varepsilon_{2,i}.$


text:
Q: Place Icon at Top Left Corner in Multiline EditText How Do I place icon at top left corner in multiline EditText, here is what I am using :
<EditText
        android:id="@+id/editComments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="20dp"
        android:paddingRight="10dp"
        android:layout_margin="10dp"
        android:hint="Comments"
        android:inputType="textMultiLine"
        android:lines="4"
        android:drawablePadding="20dp"
        android:minLines="4"
        android:gravity="top|left"
        android:drawableLeft="@drawable/comment"
        android:maxLines="4" />

I am getting icon as left aligned but in center not at top

A: use this code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/left_drawer"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="#FFA500">
    <EditText
        android:id="@+id/editComments"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="Comments"
        android:inputType="textMultiLine"
        android:padding="20dp"
        android:lines="4"
        android:drawablePadding="20dp"
        android:minLines="4"
        android:gravity="top|left"
        android:maxLines="4" />
    <ImageButton
        android:layout_width="20dp"
        android:layout_gravity="left"
        android:src="@drawable/comment"
        android:layout_height="20dp" />

</FrameLayout>

A: *

*You have to understand what you are using. There is no such thing as android:setToTop in your editText options - that's why it does not align to the top; android:paddingTop is about something else.

*It depends on which layout are you using - the best one for your problem is RelativeLayout, which uses android:layout_alignTop.

I strongly suggest that you should read more about layouts which can help you understand how it works and what are you doing - copy & paste the code doesn't help every time!

A: Try this,
<LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_below="@+id/rlHeader"
        android:orientation="horizontal"
        android:padding="10dp">

        <ImageView
            android:id="@+id/imgIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_lock"
            android:layout_gravity="top"/>

        <EditText
            android:id="@+id/editComments"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Comments"
            android:inputType="textMultiLine"
            android:lines="4"
            android:textColor="@android:color/white"
            android:textColorHint="@android:color/white"
            android:layout_marginLeft="10dp"
            android:minLines="4"
            android:gravity="top|left"
            android:maxLines="4" />
    </LinearLayout>


text:
Q: Dynamically generate a checkbox group, loop through checked/unchecked values in pl/sql I'm using Oracle Apex version 22.2 and this is my first time working with a dynamic checkbox group. Each company has a list of "ParentID's" that they can do business under. The number of PIDs a company can have is from 1-20. I'm using a sql query LOV to display all of the PIDs via checkbox group
select
    ms.subid as ParentID,
    ms.keyid as KeyID
from
    memmgr.merchant_subid ms
join
    sandro.account_lookup al on
        ms.keyid = al.merchantkeyid
where
    orgkeyid = :P1_ORGKEYID
order by
    ms.subid;

My next objective is to create a process in which I loop through the selected checkboxes and insert the keyids into my other table named Portal_Parents . I'm fairly certain I can obtain this by using apex_string.split_numbers(:P10_CHECKBOX,':').
The part I'm not sure about is how to initialize these checkboxes after the initial insert, and what the best way to manage these updates would be. I still need for all of the checkboxes to appear as they would in the code above. But I need the ones that exist in my Portal_Parents table to be checked. If I can figure out how to initialize each checkbox as either checked or unchecked by using a query such as:
select 1
from portal_parents
where portalloginkeyid = :P10_PORTALLOGINKEYID
and merchantkeyid = {This checkboxes' keyid}`

For my update statement, I would basically have to loop through all of the checked values, use a query to see if they already exist in the portal_parents table, then either insert or do nothing depending on if they exist. I would also then have to loop through all of the unchecked boxes, use the same query to see whether they exist in portal_parents, then either delete or do nothing depending on whether they exist.
This seems like a plausible solution to me, but please let me know if I should change directions. If not my only real unknown is to figure out how to use the checkboxes keyid to determine whether it should be checked or not, and how to select for the checked and unchecked boxes into pl/sql variables to be used for processing. Appreciate your time.


text:
Q: pandasql is not working in a function python pandas I am using pandasql to do sql join on pandas dataframe. it's working well without putting them in a function. But after putting everything together in a function, it gave me an error said:
NameError: global name 'sqldf' is not defined
the code i am using is like:
import pandasql
def myfunction():
    pandasqldf=lambda q:sqldf(q,globals())
    df=pandasqldf("select * from table1 left join table2 on table1.id=table2.id")

I have tried to use locals() instead, but it's still not working.
it would be appreciated for any input or advice on how to solve this problem. Thanks!

A: You didn't include the right import.
I also found calling sqldf directly, instead of going through the lambda, to work better.
The code below seems to work for me.
from pandasql import sqldf
def select_sql(df_a):
    return sqldf("select * from df_a", locals())

df = pd.DataFrame(np.random.randn(10,10))
select_sql(df)


text:
Q: Numba and Numpy Random Number interaction I am trying to generate a bunch of random numbers quickly to do a MCMC.
I have the following benchmarks:
@njit
def getRandos(n):
    for i in prange(n):
        a = np.random.rand()

%timeit np.random.rand(1000000000)
13.1 s ± 287 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit getRandos(1000000000)
1.97 s ± 25.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Clearly the parallelization improves my runtime.  However, I don't know how the seeding of the random number generation works.  How can I ensure that these numbers are truly random?  Do I have to randomly choose a seed somehow?

A: You don't have an apples to apples comparison. The first call you make np.random.rand(1000000000) is spending a ton of time creating space and storing the random numbers, while the second call getRandos(1000000000) just generates values and drops them.
Here is the apples to apples comparison (which is about the same speed):
from numba import prange, njit
import numpy as np

@njit
def getRandos(n):
    a = np.zeros(n)
    for i in prange(n):
        a[i] = np.random.rand()
    return a

%timeit -n 100 getRandos(100000)
%timeit -n 100 np.random.rand(100000)

To answer your question however, reference the numba documentation here.
They don't allow you to create individual RandomState instances, but you can set the seed inside the definition.
@njit
def getRandos(n):
    np.random.seed(1111)
    a = np.zeros(n)
    for i in prange(n):
        a[i] = np.random.rand()
    return a

values = getRandos(100000)
values2 = getRandos(100000)
print(all(values == values2))  # True


text:
Q: Is y * (1 - x / y) better than y - x for computing the difference of two floating numbers in C++? Subtracting two floating point numbers in C++ can lead to catastrophic cancellation.
Is there any advantage to writing y * (1 - x / y) instead of y - x, in terms of numerical stability?

A: What you call "catastrophic cancellation" I call Sterbenz's theorem:  If a/2 <= b <= 2a, then the difference b-a is exactly representable.
The term "catastrophic cancellation" is something of a misnomer.  The subtraction is totally innocent; the catastrophe had already occurred when you rounded away the part of the number you wanted.

A: I'd think the the multiplication & division would give you more trouble, but nevertheless, in the long version, you are STILL subtracting two floating point numbers.

A: the error you get from x-y is y times the one you get from 1-(x/y), that you later multiply by y, having the same result.

A: Haha, no. Catastrophic cancellation occurs the moment you decide you want to find the difference between two numbers, if those two numbers are nearly equal and far from 0. It doesn't matter how wacky a formula you use to do it -- the information required for a precise difference calculation has already been discarded.
In order to avoid the situation, you need to calculate and store different numbers. That is, instead of calculating and storing x and y, say, you'd calculate a=x and b=y-x. Or a=(x+y)/2 and b=(x-y)/2. You wouldn't calculate them from x and y -- that would have exactly the same problem -- rather, you'd calculate and store them as the actual numbers, and calculate x and y as needed. (Obviously this requires a choice of a and b which can actually be calculated, given your use case.)


text:
Q: Squared button in Qt Designer I'm using Qt Creator with the 'Design' tool and I have grid of buttons, which, no matter how I resize them, should always be squares.
Any ideas?
This is what my grid looks like when resized differently:
Here it is perfectly squared, but if I make my window smaller...

...it looks like this:

That's the .ui:
<layout class="QGridLayout" name="gridLayout_5" rowstretch="0,0,0" columnstretch="0,0,0">
         <property name="sizeConstraint">
          <enum>QLayout::SetMinimumSize</enum>
         </property>
         <item row="2" column="1">
          <widget class="QPushButton" name="downButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="layoutDirection">
            <enum>Qt::LeftToRight</enum>
           </property>
           <property name="text">
            <string/>
           </property>
           <property name="icon">
            <iconset resource="grafics.qrc">
             <normaloff>:/grafics/grafics/pfeile/pfeil_unten.tga</normaloff>:/grafics/grafics/pfeile/pfeil_unten.tga</iconset>
           </property>
           <property name="iconSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
          </widget>
         </item>
         <item row="0" column="1">
          <widget class="QPushButton" name="upButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="sizeIncrement">
            <size>
             <width>0</width>
             <height>0</height>
            </size>
           </property>
           <property name="text">
            <string/>
           </property>
           <property name="icon">
            <iconset resource="grafics.qrc">
             <normaloff>:/grafics/grafics/pfeile/pfeil_oben.tga</normaloff>:/grafics/grafics/pfeile/pfeil_oben.tga</iconset>
           </property>
           <property name="iconSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
          </widget>
         </item>
         <item row="1" column="1">
          <widget class="QPushButton" name="waitButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="font">

             <family>MS Shell Dlg 2</family>
             <pointsize>15</pointsize>

           </property>
           <property name="contextMenuPolicy">
            <enum>Qt::DefaultContextMenu</enum>
           </property>
           <property name="text">
            <string>W</string>
           </property>
           <property name="icon">
            <iconset theme="&#9664"/>
           </property>
          </widget>
         </item>
         <item row="1" column="0">
          <widget class="QPushButton" name="leftButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="text">
            <string/>
           </property>
           <property name="icon">
            <iconset resource="grafics.qrc">
             <normaloff>:/grafics/grafics/pfeile/pfeil_links.tga</normaloff>:/grafics/grafics/pfeile/pfeil_links.tga</iconset>
           </property>
           <property name="iconSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
          </widget>
         </item>
         <item row="0" column="2">
          <widget class="QPushButton" name="deleteButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="font">

             <pointsize>15</pointsize>

           </property>
           <property name="text">
            <string><</string>
           </property>
          </widget>
         </item>
         <item row="1" column="2">
          <widget class="QPushButton" name="rightButton_3">
           <property name="minimumSize">
            <size>
             <width>30</width>
             <height>30</height>
            </size>
           </property>
           <property name="maximumSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
           <property name="sizeIncrement">
            <size>
             <width>0</width>
             <height>0</height>
            </size>
           </property>
           <property name="text">
            <string/>
           </property>
           <property name="icon">
            <iconset resource="grafics.qrc">
             <normaloff>:/grafics/grafics/pfeile/pfeil_rechts.tga</normaloff>:/grafics/grafics/pfeile/pfeil_rechts.tga</iconset>
           </property>
           <property name="iconSize">
            <size>
             <width>50</width>
             <height>50</height>
            </size>
           </property>
          </widget>
         </item>
        </layout>

A: Read about the Qt layouts https://doc.qt.io/qt-5/layout.html
It's a powerful way to have responsive UI and ensure your window will look good for many different sizes.
All Qt widgets have default behaviours about how to resize in the available space. You can see in your code (and in Qt Designer properties) that your buttons have min and max sizes, the layout will adapt your widget's size in this range when you resize your window, to make everything fit as much as possible.
So if your window is not squared, your content will not be squared, thanks to the top GridLayout you have.
About your question to have squared buttons, there is not straightforward property to do that, you have to code a little bit :

*

*How to maintain widgets aspect ratio in Qt?

*Qt layouts - Keep widget aspect ratio while resizing


text:
Q: C++ lightweight embedded itoa and fptoa implementation Backstory
I am developing a TFT LCD library (that I will open source once I finish) and came to the understanding I need a lightweight itoa and fptoa function to convert integral and floating point values to strings. After reading through quit a few posts here I didn't find a concrete implementation here so I decided to post it myself.
Limitation

*

*no dynamic allocations

*c++11 compatible.

The problem
The first approach was to look if there is a solution in the standard library and sadly itoa isn't part of the standard and fptoa doesn't exist. However, there is still sprintf right ? The problem is the overhead for all of the internal checks it does and the other c++ methods aren't much more appealing:

*

*std::string - heavy + dynamic memory usage (If number is too big for short string optimization).

*Streams - Too slow and heavy.

A: itoa solution
#include<algorithm>
#include<type_traits>
#include<cstdint>

static constexpr char digits[]{ "0123456789ABCDEF" };

enum class Base : uint8_t
{
    BIN = 2,
    OCT = 8,
    DEC = 10,
    HEX = 16
};

template<typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
char* itoa(T number, char* buf, const Base base) noexcept
{
    if (base < Base::BIN || base > Base::HEX) {
        *buf = '\0';
        return buf;
    }

    bool negative{ false };
    if (number < 0 && base == Base::DEC) {
        number = -number;
        negative = true;
    }

    typename std::make_unsigned<T>::type unsigned_number = number;
    uint8_t index{ 0 };
    do {
        buf[index++] = digits[unsigned_number % static_cast<decltype(unsigned_number)>(base)];
        unsigned_number /= static_cast<decltype(unsigned_number)>(base);
    } while (unsigned_number);

    if (negative) {
        buf[index++] = '-';
    }

    std::reverse(buf, buf + index);

    buf[index] = '\0';

    return &buf[index];
}

ftoa solution
This one was a bit more tricky as I had to create a type that ensures the precision value will be in bounds:
#include<cfloat>
#include<cstdint>

template<uint8_t v, uint8_t min, uint8_t max>
struct BoundIntegral
{
    static_assert(min < max, "min bound must be lower than max");
    static_assert(v >= min && v <= max, "value out of bounds");
    static constexpr uint8_t value{ v };
};

constexpr uint8_t MIN_PRECISION{ 1 };

template<typename T, uint8_t prec> struct Precision {};

template<uint8_t prec>
struct Precision<long double, prec> : BoundIntegral<prec, MIN_PRECISION, LDBL_DIG> {};

template<uint8_t prec>
struct Precision<double, prec> : BoundIntegral<prec, MIN_PRECISION, DBL_DIG> {};

template<uint8_t prec>
struct Precision<float, prec> : BoundIntegral<prec, MIN_PRECISION, FLT_DIG> {};

Next up was the actual fptoa implementation:
#include<cstdint>
#include<cmath>
#include<type_traits>

constexpr uint8_t ERR_LEN{ 3 };

template<typename T, uint8_t prec, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
char* fptoa(T number, char* buf) noexcept
{
    auto memcpy = [](char* dest, const char* const src, uint8_t length) noexcept {
        for (uint8_t index{}; index < length; ++index) {
            dest[index] = src[index];
        }
        return &dest[length];
    };

    if (std::isnan(number)) {
        buf = memcpy(buf, "NAN", ERR_LEN);
    }
    else if (std::isinf(number)) {
        buf = memcpy(buf, "INF", ERR_LEN);
    }
    else if (number > INT32_MAX) {
        buf = memcpy(buf, "OVF", ERR_LEN);
    }
    else if (number < INT32_MIN) {
        buf = memcpy(buf, "OVF", ERR_LEN);
    }
    else {
        T rounding = 0.5 / std::pow(10.0, Precision<T, prec>::value);
        if (number < 0.0) {
            number -= rounding;
        }
        else {
            number += rounding;
        }

        int32_t integral_part = static_cast<int32_t>(number);
        buf = itoa(integral_part, buf, Base::DEC);

        *buf++ = '.';

        T fractional_part = std::abs(number - static_cast<T>(integral_part));
        uint8_t precision = Precision<T, prec>::value;
        while (precision--) {
            fractional_part *= 10;
            *buf++ = digits[static_cast<uint8_t>(fractional_part)];
            fractional_part -= static_cast<uint8_t>(fractional_part);
        }
    }

    *buf = '\0';

    return buf;
}

Use case
For the use case itself I made a utility template that can deduce the buffer size I will need:
#include<climits>
#include<type_traits>
#include<cstdint>

template<typename T>
struct bits_constant : std::integral_constant<std::size_t, sizeof(T) * CHAR_BIT> {};

And use it as following:
#include<cstdio>

int main()
{
    char fpbuf[bits_constant<double>::value + 1];
    double d{ 3.123 };
    fptoa<double, 3>(3.123, fpbuf); //convert double value with 3 digits precision

    std::printf("%s", fpbuf);

    char ibuf[bits_constant<int32_t>::value + 1];
    int32_t i{-255};
    itoa(i, ibuf, Base::DEC);

    return 0;
}

Summary
Feel free to use the code in your project. And I would appreciate it if you could suggest improvements to the code, as the goal of this post is to help others use a portable solution to converting integral and floating point values to strings.
Godbolt link for assembly output: https://godbolt.org/z/PGiw7m


text:
Q: Malloc and realloc for union of structs linked to array of structs What's the best way to dinamically allocate memory to an array of structs with union included? I should malloc and then realloc to record_user or to data_user? Below I explain more of it, this is the sample code:
core.h
#define MAX_USER sizeof(record_user) / sizeof(record_user[0])
#define MAX_ARTIST sizeof(record_artist) / sizeof(record_artist[0])
/* all my other defines here */

typedef enum {
    admin = 1,
    basic = 0
} type;

typedef struct {
    int hour;
    int minute;
    int second;
} tm;

typedef struct {
    int day;
    int month;
    int year;
} date;

typedef struct {
    short id;
    char name[MAX_USER_NAME];
    char surname[MAX_USER_SURNAME];
    char email[MAX_USER_EMAIL];
    char password[MAX_PASSWORD_LENGTH];
    date birthday;
    date subscription_date;
    tm subscription_time;
    type role;
} user;

typedef struct {
    short id;
    char name[MAX_ARTIST_NAME];
    char genre[MAX_GENRE][MAX_GENRE_NAME];
    char producer[MAX_PRODUCER_NAME];
    char nationality[MAX_NATIONALITY_NAME];
    int starting_year;
} artist;

/* and other structs */

typedef struct {
    enum { USER, ARTIST } type;
    union {
        user *u_user;
        artist *u_artist;
    };
    int size;
} data;

data.h
#ifndef DATA_H
#define DATA_H

#include "core.h"

extern user record_user[];
extern artist record_artist[];

extern data data_user;
extern data data_artist;
/* etc */

#endif

data.c
#include "data.h"

// SOME PRESET DATA
user record_user[] = {
{ 1, "Name 1", "Surname 1", "name1.surname1@email.com", ",+o[oS", { 29, 9, 1996 }, { 7, 3, 2011 }, { 18, 25, 58 }, 0 },
/** The list goes on **/
}

artist record_artist[] = {
{ 1, "Coldplay", { "Pop", "Britpop", "Alternative Rock" }, "Parlophone", "United Kingdom", 1997 },
/** The list goes on **/
}

data data_user = { .type = USER,.u_user = record_user,.size = MAX_USER };
data data_artist = { .type = ARTIST,.u_artist = record_artist,.size = MAX_ARTIST };

As you can see, there is a union struct for artist and user. I decided to create a union struct in order to pass multiple array of structs to a generic function. In the full code, I have more unions, but that's not the point to list them all. I just really need to understand what's I'm going to further explain below.
record_user like record_artist has some preset data that I link to data_user and data_artist respectively in data.c. Now this data needs to be increased during the runtime. I mean if record_user has 100 preset data rows (same thing for record_artist) in it, I'd like to add more rows or even remove them. For that I know there's malloc and realloc. I tried to play with it, making some tests and I don't know what's the best way of doing that.
I tried to declare in my main.c file the following:
int main() {
    data_user.u_user = (user *)malloc(size * sizeof(user));
    /***/
}

but I also tried with this
int main() {
    record_user = (user *)malloc(size * sizeof(user));
    /***/
}

but as I already imagined I lose all the preset data delcared in data.c file.
MY GOAL
What I'd like to achieve is to malloc a temp size for my data (for starting 100) and then to link the array of structs (or the union struct), with the starting temp size, to my preset data in order for using them. Naturally, during runtime, I will add more rows, and for that I'll use realloc (or even remove them).
This is the sample code of my add function:
data *add_data(data *record_data) {
    date record_date;
    tm record_time;

    switch (record_data->type) {
    case USER:
    {
        /* SOMEWHERE HERE I should use realloc to my record_data */
        int ID = record_data->size;
        record_data->u_user[ID].id = ID;
        printf("\n\n\tNEW USER");
        printf("\n\tEnter name: ");
        strcpy(record_data->u_user[ID].name, inputString(MIN_USER_NAME, MAX_USER_NAME));
        printf("\tEnter surname: ");
        strcpy(record_data->u_user[ID].surname, inputString(MIN_USER_SURNAME, MAX_USER_SURNAME));
        printf("\tEnter email: ");
        strcpy(record_data->u_user[ID].email, inputString(MIN_USER_EMAIL, MAX_USER_EMAIL));
        printf("\tEnter password: ");
        strcpy(record_data->u_user[ID].password, inputString(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH));
        /* etc for birthday, subscription date */

        record_data->size += 1;

        printf("\n\tUser added!");
        return record_data;
    }
    case ARTIST:
        /* asking for input data */

        return record_data;
    }
}

this is how I call the function instead in the main.c file
int main() {
    /***/
    data_user = *add_data(&data_user);
    /***/
}

I don't know how to move here, if I should work with the struct record_user or the union struct data_user. If it's the same or not... if I work with the original struct (allocating memory), is the union capable of reading the new memory size or not? Or is it best to work with the union struct leaving the original struct untouched?
I hope someone clear my mind!


text:
Q: Kotlin new Thread is still running on main thread I am trying to make network calls on a background thread, so I am creating a thread like this:
private val networkThread = Thread("NetworkThread")

init {
    networkThread.start()
}

However when I try running something on the thread like this:
    networkThread.run {
        try {
            socket = Socket(ip, port)
        } catch (e: java.lang.Exception) {
            Log.e(TAG, "Network Error $e")
        }
    }

I get the following error: Network Error android.os.NetworkOnMainThreadException
Why is this still running on the MainThread? If I create the thread by using a runnable as the param it works, but I am just curious why doing it this way is still counting as the MainThread

A: private val networkThread = Thread("NetworkThread") creates a thread which does nothing as you haven't override its run method.
networkThread.run {
        ....
}

run method you are using on networkThread is not the run() method of the Thread class but is the scope function of Kotlin which gives the context object as the receiver and returns the lambda result, that is why you are getting Network Error android.os.NetworkOnMainThreadException
For a thread to execute something on the background thread, you've to override its run method or you can create a Runnable and use it to create thread object
val networkThread = object: Thread() {
        override fun run() {
            try {
                socket = Socket(ip, port)
            } catch (e: java.lang.Exception) {
                Log.e(TAG, "Network Error $e")
            }
        }
    }

networkThread.start()


text:
Q: Python: Convert complex dictionary of strings from Unicode to ASCII
Possible Duplicate:
How to get string Objects instead Unicode ones from JSON in Python?

I have a lot of input as multi-level dictionaries parsed from JSON API calls. The strings are all in unicode which means there is a lot of u'stuff like this'. I am using jq to play around with the results and need to convert these results to ASCII.
I know I can write a function to just convert it like that:
def convert(input):
    if isinstance(input, dict):
        ret = {}
        for stuff in input:
            ret = convert(stuff)
    elif isinstance(input, list):
        ret = []
        for i in range(len(input))
            ret = convert(input[i])
    elif isinstance(input, str):
        ret = input.encode('ascii')
    elif :
        ret = input
    return ret

Is this even correct? Not sure. That's not what I want to ask you though.
What I'm asking is, this is a typical brute-force solution to the problem. There must be a better way. A more pythonic way. I'm no expert on algorithms, but this one doesn't look particularly fast either.
So is there a better way? Or if not, can this function be improved...?

Post-answer edit
Mark Amery's answer is correct but I would like to post a modified version of it. His function works on Python 2.7+ and I'm on 2.6 so had to convert it:
def convert(input):
    if isinstance(input, dict):
        return dict((convert(key), convert(value)) for key, value in input.iteritems())
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

A: Recursion seems like the way to go here, but if you're on python 2.xx you want to be checking for unicode, not str (the str type represents a string of bytes, and the unicode type a string of unicode characters; neither inherits from the other and it is unicode-type strings that are displayed in the interpreter with a u in front of them).
There's also a little syntax error in your posted code (the trailing elif: should be an else), and you're not returning the same structure in the case where input is either a dictionary or a list. (In the case of a dictionary, you're returning the converted version of the final key; in the case of a list, you're returning the converted version of the final element. Neither is right!)
You can also make your code pretty and Pythonic by using comprehensions.
Here, then, is what I'd recommend:
def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

One final thing. I changed encode('ascii') to encode('utf-8'). My reasoning is as follows: any unicode string that contains only characters in the ASCII character set will be represented by the same byte string when encoded in ASCII as when encoded in utf-8, so using utf-8 instead of ASCII cannot break anything and the change will be invisible as long as the unicode strings you're dealing with use only ASCII characters. However, this change extends the scope of the function to be able to handle strings of characters from the entire unicode character set, rather than just ASCII ones, should such a thing ever be necessary.


text:
Q: GRASS i.landsat.toar returns empty raster I am trying to use the GRASS module i.landsat.toar.
Currently the files created are empty and it spits out:

So it seems that it is not picking up something?  The location is set to the extent of the landsat image.  Does anyone have an idea where I am going wrong?
Becky

A: The original question could have been more complete, if the exact command instructed would have been posted.  As well, the exact type of Landsat product, and the metadata file in question.
Anyhow, from the screenshot, one can conclude that the original poster tried to work on Landsat7 bands. Taking into account the date when the question was posted, it is likely that the version of GRASS used, was version 6.4.
Support for the "new" --at the time-- type of metadata files (MTL), was added:

*

*for GRASS 6.4, see revision 54844 on 02/02/13 (change details: Changes in  grass/branches/releasebranch_6_4/imagery/i.landsat.toar/landsat_met.c [53339:54844] -- note, this happened 1 day after the question was posted!

*for GRASS 7, around the time of revision 57936 (see also: Changes in grass/trunk/imagery/i.landsat.toar [57933:57936]) in the module's code for handling metadata. That was April 2014, which is about 2 months after the date when the question was posted.


text:
Q: Python Matplotlib: Create normal colorbar with white interval at specific values I have Sea Ice Concentration data around Antarctica that range between -40 and +40 (see attached Figure) but I would like for the values between +10 and -10 to appear white in my map and colorbar because they do not represent sea ice concentration (they appear light green and light blue in the current Figure).
I do not want to exclude them from my array but rather want to assign them a specific color (in this case, white) and keep the jet colorscale for the other values.

I have looked at multiple other questions (i.e. How to change colorbar's color (in some particular value interval)?; Python matplotlib change default color for values exceeding colorbar range; **Reset default matplotlib colormap values after using 'set_under' or 'set_over')
but have not managed to apply those to my case.
I have tried to use 'set under','set over', 'set.bad' but have not managed to get what I would like. I have also tried to create my own colormap but haven't been successful either.
Would anyone be able to help?
Thanks.

UPDATE:
I have adapted the code from 'stackoverflow.com/a/41815114/5103802' (see Updated Code below) but my colors are not white for values [+10 -10] and 'jet'
for above +10 and below -10 (see Figure below). The 'tmap' object seems to have messed up the colorscale. Any idea on how I could get the jet colorscale and leave the interval between -10 and +10 white?
Thanks for your help.

Updated code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
from mpl_toolkits.basemap import Basemap, cm, rcParams

HIGH_86 = a.variables['high_86'][:]

n=40
x = 10

lower = plt.cm.seismic(np.linspace(1-x, 0, n))
upper = plt.cm.seismic(np.linspace(0, x, n))

white1 = plt.cm.seismic(np.ones(10)*x)
white2 = plt.cm.seismic(np.ones(10)*-(x))

colors = np.vstack((lower, white1, white2, upper))
tmap = matplotlib.colors.LinearSegmentedColormap.from_list('terrain_map_white', colors)

x = HIGH_86

lats = a.variables['latitude'][:]
lons = a.variables['longitude'][:]

lons, lats = np.meshgrid(lons,lats)

fig, ax = plt.subplots()

m2 = Basemap(projection='spstere',boundinglat=-50,lon_0=180,resolution='l')

CS2 = m2.contourf(lons,lats,x,cmap=tmap,latlon=True)
cbar = m2.colorbar(CS2,location='right', pad="12%")

m2.drawparallels(np.arange(-90.,99.,60.),labels=[False,False,False,False])
m2.drawmeridians(np.arange(-180.,180.,90.),labels=[True,False,False,True])
m2.drawcoastlines()
m1.fillcontinents(color='grey')

plt.title('SIE Anomaly')

plt.show()

A: I assume you have read the linked question and it's answer.
It clearly states

Colormaps are always ranged between 0 and 1.

and further explains how to arrive at a suitable colormap. It thus makes no sense to supply values of 10 or -9 to the colormap.
While you could directly copy the code from the answer here and would receive a decent result, you may of course also refine it to match this specific case, where one may go for 80 colors, 30 from the lower part of the colormap, 30 from the upper part and the remaining 20 in the middle to be white.
n=30
x = 0.5
lower = plt.cm.seismic(np.linspace(0, x, n))
white = plt.cm.seismic(np.ones(80-2*n)*x)
upper = plt.cm.seismic(np.linspace(1-x, 1, n))
colors = np.vstack((lower, white, upper))
tmap = matplotlib.colors.LinearSegmentedColormap.from_list('map_white', colors)

In order to get the jet colormap, which does not have white in it, an array of ones may be used in the middle
n=30
x = 0.5
cmap = plt.cm.jet
lower = cmap(np.linspace(0, x, n))
white = np.ones((80-2*n,4))
upper = cmap(np.linspace(1-x, 1, n))
colors = np.vstack((lower, white, upper))
tmap = matplotlib.colors.LinearSegmentedColormap.from_list('map_white', colors)

Complete code to reproduce the image above:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

n=30
x = 0.5
cmap = plt.cm.jet
lower = cmap(np.linspace(0, x, n))
white = np.ones((80-2*n,4))
upper = cmap(np.linspace(1-x, 1, n))
colors = np.vstack((lower, white, upper))
tmap = matplotlib.colors.LinearSegmentedColormap.from_list('map_white', colors)

x = np.linspace(0,10)
X,Y = np.meshgrid(x,x)
z = np.sin(X) * np.cos(Y*0.4)*40

fig, ax = plt.subplots()
im = ax.contourf(z, cmap=tmap, vmin=-40, vmax=40)
plt.colorbar(im)

plt.show()


text:
Q: MySQL Query was killed, but caused mysql database to not accept new reads or writes This has happened a few times before and on all of those times I was not able to find an answer on the internet and I've had to completely uninstall MySQL and reimport the database from a backup. Although right now there's a little more than 1 billion rows so that's not something I see as an acceptable solution at this time.
In the processlist there are four queries showing as "sending data" and all of them are killed. Below that there are about 100 more listed as "statistics" which cannot be killed either.
Is there a way I could fix this without reinstalling MySQL?
Edit: Ubuntu 16, mysql newest

A: For future refference for myself and anyone else with this issue, run "pkill mysql", move "ibtmp1" (like 90G) inside of /var/lib/mysql to another location, then start mysql again.


text:
Q: SCardTransmit returns error 0x000005aa I am trying to connect and send command to smart Card through Windows smart Card api , below is the code i have from MSDN. Here the SCardTransmit function always Returns me 0x000005aa , can some one let me know what i am doing wrong.
int _tmain(int argc, _TCHAR* argv[])
{
SCARDCONTEXT    hContext;
LONG            lReturn;
SCARDHANDLE     hCardHandle;
DWORD           dwAP;
const DWORD BUF_LEN = 512;
DWORD dwRecv;
BYTE pbRecv[BUF_LEN];

BYTE sendCommand[]={0x00,0x0A4,0x00,0x00,0x02,0x3F,0x00};

lReturn = SCardEstablishContext(SCARD_SCOPE_USER, NULL,NULL,&hContext);
if ( SCARD_S_SUCCESS != lReturn )
{
    printf("Failed SCardEstablishContext\n");
    SCardReleaseContext(hContext);
    return 0;
}

lReturn = SCardConnect( hContext, "OMNIKEY CardMan 3x21 0",
    SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
    &hCardHandle, &dwAP );
if ( SCARD_S_SUCCESS != lReturn )
{
    printf("Failed SCardConnect\n");
    SCardReleaseContext(hContext);
    return 0;
}

switch ( dwAP )
{
case SCARD_PROTOCOL_T0:
    printf("Active protocol T0\n");
    break;

case SCARD_PROTOCOL_T1:
    printf("Active protocol T1\n");
    break;

case SCARD_PROTOCOL_UNDEFINED:
default:
    printf("Active protocol unnegotiated or unknown\n");
    break;
}

lReturn = SCardTransmit(hCardHandle,SCARD_PCI_T0,sendCommand,7,
    NULL,pbRecv,&dwRecv );
if ( SCARD_S_SUCCESS != lReturn )
{
    printf("Failed SCardTransmit\n");
}
lReturn = SCardReleaseContext(hContext);
return 0;
 }

A: As suggested in comments by Retired Ninja. the variable dwRecv needs to initialize, after initializing the variable the program works. thanks.


text:
Q: What is the solution to this problem (Geometric and Arithmetic progression)? Numbers $a , b,c , 64$ are consecutive members of a geometric progression.
Numbers $a,b,c$ are respectively the first, fourth, eighth members of an  arithmetic progression.

Calculate $a + b - c$

A: Set $a,b=aq,c=aq^2,64=aq^3$ consecutive members of the geometric progression. Clearly, $a,q\neq0$ because the sequence contains a non-zero term $64.$
If $r$ is the ratio of the arithmetic progression, then $$\begin{aligned}b&=a+3r=aq&\Rightarrow \quad3r&=a(q-1)\\c&=a+7r=aq^2&\Rightarrow \quad 7r&=a(q-1)(q+1)\end{aligned}$$
It is sure that $q\neq 1$ (from the given constraints).
From the two last equations we elliminate $r$ to get $$q+1={7\over 3}$$
I am sure you can finish the solution.

A: We can also work out the details from the requirements that
$$ a_1 \ = \ a \ \ , \ \ a_4 \ = \ a + (4 - 1)·d \ = \ b \ \ , \ \ a_8 \ = \ a + (8 - 1)·d \ = \ c \ \ , $$
where $ \ d \ $ is the difference between terms of the arithmetic progression, so $ \ a + b - c \ = \ a + (a + 3d) - (a + 7d) \ = \ a - 4d \ \ . $
That these numbers also form a geometric progression requires that the ratio between terms is given by
$$ r \ \ = \ \ \frac{b}{a} \ = \ \frac{c}{b} \ \ \Rightarrow \ \ \frac{a \ + \ 3d}{a} \ = \ \frac{a \ + \ 7d}{a \ + \ 3d} \ \ \Rightarrow \ \ a^2 \ + \ 7ad \ \ = \ \ a^2 \ + \ 6ad \ + \ 9d^2 $$ $$ 9d^2 \ - \ ad \ \ = \ \ d·(9d - a) \ \ = \ \ 0 \ \ ; $$
since $ \ d \neq 0 \ \ , $ we have $ \ a = 9d \ \ , $ indicating that $ \ a \neq 0 \ \ $ also.
Thus far, our geometric progression is then $ \ a \ \ , \ \ a \ + \ 3·\frac{a}{9} \ = \ \frac43 a \ \ , \ \ a \ + \ 7·\frac{a}{9} \ = \ \frac{16}{9} \ = \ \left(\frac43 \right)^2 a $ $ , \ \ 64 \ \ ; \  $ furthermore, $ \ a + b - c \ =  \ a \ - \ 4·\frac{a}{9} \ = \ \frac59·a \ \ . $
The terms in the geometric progression thus tell us that $$ \left(\frac43 \right)^3 · a \ \ = \ \ \frac{64}{27}·a \ \  = \ \ 64 \ \ \Rightarrow \ \ a \ \ = \ \ 27 \ \ \Rightarrow \ \ a + b - c \ =  \ \frac{5}{9}·27 \ \ = \ \ 15 \ \ . $$
[We can check this by calculating $$ \ d \ = \ \frac{27}{9} \ = \ 3 \ \ \Rightarrow \ \ b \ \ = \ \ 27 \ + \ 3·3 \ = \ \ 36 \ \ = \ \ \frac43·27 \ \ ,   $$ $$ c \ \ = \ \ 27 \ + \ 7·3 \ \ = \ \ 48 \ \ = \ \  \frac{16}{9}·27 \ \ \Rightarrow \ \ a + b - c \ \ = \ \ 27 + 36 - 48 \ \ = \ \ 15 \ \ . \ ]$$


text:
Q: Android Java String creation 'cheapest' way I have a runnable that is constantly updating a string value onscreen, there could be ten items in a list all updating their value every second. Its basically a list of stopwatches all running at the same time. The method I have below has three different ways of producing the string:
private void setTime() {

    long now = System.currentTimeMillis() / 1000L;
    long difference = now - startTime;

    // METHOD 1
    String conc = String.format("%02d:%02d:%02d", difference / 3600, (difference % 3600) / 60, difference % 60);

    // METHOD 2 (not finished)
    StringBuilder sb = new StringBuilder(8);
    sb.append(difference/3600).append((difference % 3600 /60)).append(difference % 60);

    // METHOD 3
    String timeAsText = new SimpleDateFormat("HH:mm:ss")
                .format(new Date(difference * 1000));
}

All of them work, but after watching the memory whilst performing the same test for each method and leaving it for 10 minutes the allocation continues to rise for each.
Method 1 - Allocated memory went up about 5MB-6MB.
Method 2 - Allocated memory went up about 3MB.
Method 3 - Allocated memory went up about 6MB.
After only 10 minutes this isn't ideal, I have tried to track the memory allocation and the issue is definitely with creating the String.
How best should I do this? What method can I employ to keep memory allocation to a minimum? Even better what can I do to stop the memory constantly rising? (This is definitely a new issue by the way, taking this out stops the leak)


text:
Q: What is the reason for failing to solve the following equation? I have a simple differential equation
$$
\frac{df(T)}{dT} = g(T)(f(T)-f_{\text{eq}}(T)),
$$
where $g,f_{\text{eq}}$ are some smooth functions, and $T$ is an analog of time, but the evolution corresponds to its decreasing. The initial condition is fixed at some large $T$.
As far as $g(T)$ is large, $f(T)$ tends to $f_{\text{eq}}(T)$.
The data and interpolations for $g, f_{\text{eq}}$ is given below:
datatable = {{0.001, -18.23707929395402, -3.4611075922132485*^51,
    0.06611490804695141},
     {0.0012589254117941675, -17.84461494544366, \
-1.731220410720289*^51, 0.06940434750265481},
     {0.001584893192461114, -17.431914718313582, \
-8.51731766948239*^50, 0.07237676798672106},
     {0.001995262314968879, -17.005104472877587, \
-4.3165099986682115*^50, 0.07395569051393182},
     {0.0025118864315095794, -16.557706734429065, \
-2.1593973167434227*^50, 0.07467984975288536},
     {0.0031622776601683794, -16.092497328595197, \
-1.074810138034652*^50, 0.07614210743368215},
     {0.003981071705534973, -15.612016450430032, \
-5.402227503991311*^49, 0.07670151429807713},
     {0.005011872336272725, -15.11979376331143, \
-2.7075274581505683*^49, 0.0770387920958333},
     {0.00630957344480193, -14.619694946405195, \
-1.3569781967203665*^49, 0.07725366322862573},
     {0.007943282347242814, -14.115080888527912, \
-6.801001485068046*^48, 0.07739012922334851},
     {0.01, -13.607560271569687, -3.3982958779998454*^48,
    0.0771018106537571},
     {0.012589254117941675, -13.095519359896302, \
-1.710097520600141*^48, 0.07686997193087373},
     {0.01584893192461114, -12.57502890910125, \
-8.690391178966214*^47, 0.0759855227210446},
     {0.0199526231496888, -12.044506899327656, \
-4.371902972077502*^47, 0.07282260228552294},
     {0.025118864315095808, -11.508867694748597, \
-2.1773382055232237*^47, 0.06994033587672496},
     {0.03162277660168379, -10.974125604097805, \
-1.0633537829077974*^47, 0.06503886133118436},
     {0.039810717055349734, -10.444363631208544, \
-5.112432708696619*^46, 0.06099002866348603},
     {0.05011872336272725, -9.921345251439233, \
-2.501552056154496*^46, 0.05697924054878366},
     {0.06309573444801933, -9.405008535108163, \
-1.1914528506215466*^46, 0.05377917472899783},
     {0.07943282347242818, -8.893455863058334, \
-5.952272541408941*^45, 0.05042561999840631},
     {0.1, -8.385806548209892, -2.914976254908381*^45,
    0.04632976895359},
     {0.12589254117941676, -7.880454160420435, \
-1.4737468497974092*^45, 0.039566117973202475},
     {0.15848931924611143, -7.138243474959937, \
-7.174174780329404*^44, 0.02942287460063761},
     {0.19952623149688808, -6.626336945176083, \
-2.965865068779192*^44, 0.017144010394089228},
     {0.25118864315095824, -6.108043591225297, \
-9.038610774285183*^43, 0.01313376026977404},
     {0.31622776601683794, -5.582083828910504, \
-4.548117030242562*^43, 0.012708083189742772},
     {0.3981071705534973, -5.052661452093368, \
-2.1806808000591704*^43, 0.012360362229429312},
     {0.5011872336272725, -4.524046758491513, -1.112629480001722*^43,
    0.01199402899466483},
     {0.6309573444801936, -3.9994743706180884, \
-5.3097114984886734*^42, 0.011537300885158159},
     {0.7943282347242822, -3.479883065855086, \
-2.6955468924524333*^42, 0.011267163642615846},
     {1., -2.965140354827245, -1.3165469387026805*^42,
    0.010824589365892487},
     {1.2589254117941675, -2.453828397690545, \
-6.4755820044992164*^41, 0.010584319966540402},
     {1.584893192461114, -1.9454167886779412, \
-3.2633903693694033*^41, 0.010215016118577763},
     {1.9952623149688808, -1.4391265773321897, \
-1.5547777621410808*^41, 0.010048630681173598},
     {2.5118864315095824, -0.9347011259099397, \
-7.989912520361756*^40, 0.009903098920860035},
     {3.1622776601683795, -0.4315440818394637, \
-3.8252581674440914*^40, 0.00972893547965847},
     {3.981071705534973,
    0.07068148630045823, -1.9247852842573809*^40,
    0.00971813690860107},
     {5.011872336272725, 0.5721584641714871, -9.626194155274167*^39,
    0.009606387739884165},
     {6.309573444801936, 1.0730475993443855, -4.7648846361866947*^39,
    0.00964133432146204},
     {7.943282347242821, 1.573490988036743, -2.3835091416492644*^39,
    0.009554013386705201},
     {10., 2.073808527167923, -1.1949012290701652*^39,
    0.009564214098470244},
     {12.589254117941687, 2.5742249035666016, -6.027369878562932*^38,
    0.00955817523693132},
     {15.848931924611142,
    3.0743680427736577, -3.0297492350947725*^38,
    0.009445529481161313},
     {19.952623149688787, 3.574441950151861, -1.4987904366966382*^38,
    0.009380697335597966},
     {25.11886431509582, 4.0744637940244415, -7.670096311434633*^37,
    0.009133085878059534},
     {31.622776601683793, 4.574453067816407, -3.7568252576901522*^37,
    0.009002785628402312},
     {39.81071705534978, 5.074525988991956, -1.898737042484131*^37,
    0.008740308444495148},
     {50.11872336272725, 5.574464995295442, -9.045965296413293*^36,
    0.008487702523222045},
     {63.09573444801943, 6.0745291537589585, -4.569314012352323*^36,
    0.008328828070587496},
     {79.43282347242821, 6.574382102294367, -2.2428280122531448*^36,
    0.008070902363797764}};

mass = 0.001;
Tini = 79;
Tfinal = 0.001;
rate[T_] =
  10^Interpolation[datatable[[All, {1, 2}]], InterpolationOrder -> 1][
    T];
jacobian[T_] =
  Interpolation[datatable[[All, {1, 3}]], InterpolationOrder -> 1][T];
feq[T_] =
  Interpolation[datatable[[All, {1, 4}]], InterpolationOrder -> 1][T];
fDynamics[f_, T_] = -rate[T]/(1 + 2.2*10^-7 T^6/mass^2)^2 (f - feq[T]);

When trying to solve the equation:
fsol = f /.
      NDSolve[{D[f[T], T] jacobian[T]^-1 == fDynamics[f[T], T],
         f[Tini] == 0}, f, {T, Tfinal, Tini}][[1]]

I get the error

NDSolve::ndsz: At T == 79., step size is effectively zero; singularity
or stiff system suspected.

Could you please tell me how to avoid it?

A: What you call  g[T] in your introduction seems to be equal to g[t]==-rate[t]/(1 + 2.2*10^-7 t^6/mass^2)^2 jacobian[t]. This values are of order 10^26!
You need to increase accuracy inside NDSolve dramatically.
Try
F = NDSolveValue[{D[f[T], T] jacobian[T]^-1 == fDynamics[f[T], T],
f[Tini] == 0}, f, {T, Tfinal, Tini}, WorkingPrecision -> 50] //Quiet

solution
Plot[{F[t], feq[t]}, {t, Tfinal, Tini}, PlotStyle -> {Automatic, Dashed}]

shows F[t]~ feq[t]as expected.

A: The problem is a combination of classic stiffness and weak singularities due to linear interpolation of the data.  The stiffness needs a stiff solver plus a higher working precision, as @Ulrich has observed previously and we will explain below. For the weak singularites, NIntegrate has a method "InterpolationPointsSubdivision" to deal with interpolating functions, but NDSolve does not. Such singularities are important because the error estimator assumes the underlying solution is smooth and well-approximated by its Taylor polynomial of the same degree as the order of the method.  However, "InterpolationPointsSubdivision" is a simple idea which is easy to implement manually.
First, we increase the precision of the system, which I did initially to avoid having to set and reset the precision; also, it is convenient to have the ODE and initial conditions in separate variables.
{ode, ic} = SetPrecision[
   Rationalize@{
     D[f[T], T] jacobian[T]^-1 == fDynamics[f[T], T],
     f[Tini] == 0},
   Infinity];

Stiffness and WorkingPrecision
The OP's NDSolve fails out of the gate and cannot even take one step.  If we examine the ode at the initial time we can see why.  We can also see that MachinePrecision is far from enough precision to handle the problem.
Plot[(f'[T] /. First@Solve[ode, f'[T]]) /. {f[T] -> f} /.
   Table[{T -> T0}, {T0, 79, 78, -0.25}] // Evaluate
 , {f, 0, 0.01}
 , Frame -> True, FrameLabel -> {f[T], f'[T]}
 , PlotLegends -> Table[T == T0, {T0, 79, 78, -0.25}]]

Since f[T] starts at 0 on the left and, remembering that we are integrating backwards, will rapidly approach but not reach the zero of f'[T] near f[T] == 0.008, the first step must take considerably less time than the following:
dT = 0.008/2.5*^19 (* df/f' *)
(*  3.2*10^-22  *)

dT/T /. T -> 79
(*  4.05063*10^-24  *)

The relative change in T shows that we need well over 24 digits of precision just to be able to take a step at all, but machine precision gives just under 16. It should also be clear that for standard explicit one-step integrators, the step sizes must be small while the derivative stays so large (i.e., the problem will be stiff for such methods).
Interpolation points subdivision for NDSolve
One can use NDSolve`ProcessEquations and NDSolve`Iterate to advance the integration from interpolation point to interpolation point.  This will stop the integration on one side of the singular point and restart it on the other.  This minimizes the error at the weak singularities.  Sometimes, depending on the precision settings and NDSolve method, I would get an error that normally causes NDSolve to abort. The Do loop below would bulldoze right through such errors and usually produce an accurate result.  I present settings that do not exhibit such problems.
{state} = NDSolve`ProcessEquations[
   {ode, ic},
   f, {T, Tfinal, Tini}
   , Method -> "LSODA"
   , PrecisionGoal -> 16, AccuracyGoal -> 25, WorkingPrecision -> 50,
   MaxSteps -> 100000, MaxStepFraction -> 1/3];

stops = SetPrecision[Rest@Reverse@datatable[[All, 1]],
   state@"WorkingPrecision"];

{newstate} = NDSolve`Reinitialize[state, ic];
Do[
  NDSolve`Iterate[newstate, tt],
  {tt, stops}] // AbsoluteTiming
solIPS = NDSolve`ProcessSolutions[newstate]
f@"Grid" /. solIPS // Dimensions

(*
{0.332851, Null}

{2156, 1}
*)

If we compare with a straight-through integration, we see that the piecewise approach above is faster and the solution has fewer steps:
{newstate} = NDSolve`Reinitialize[state, ic];
NDSolve`Iterate[newstate, Tfinal]; // AbsoluteTiming
solCont = NDSolve`ProcessSolutions[newstate]
f@"Grid" /. solCont // Dimensions

(*
{2.11116, Null}

{14124, 1}
*)

The quality of the solution
We can visualize the steps below (red dots).  The initial steps near T == 79 are very small. One can also see that restarting integration begins with small steps.
ListLinePlot[f /. solIPS, PlotRange -> All, Mesh -> All,
 MeshStyle -> {AbsolutePointSize[1.6], Red}, PlotStyle -> Black,
 FrameStyle -> Darker@Blue, Frame -> True, GridLines -> {stops, None}]

It is probably better to examine the solution with a log-scale on the horizontal axis (just add ScalingFunctions -> {"Log", Automatic}).  We will do that in our comparison with feq[T] below.  Note that as we have already observed at machine-precision, the first few steps occur at the same machine-precision value of T.  To see the whole plot, we must include and distinguish them, which we accomplish with WorkingPrecision -> 50, Method -> {"BoundaryOffset" -> False}:
Plot[{feq[T], f[T] /. solIPS} // Evaluate
 , Evaluate@Flatten@{T, f@"Domain" /. solIPS}
 , PlotPoints -> 100, ScalingFunctions -> {"Log", Automatic}
 , PlotStyle -> {Directive[AbsoluteThickness[3.], Red, Dashed],
   Black}, FrameStyle -> Darker@Blue, Frame -> True,
 GridLines -> {stops, None}
 , WorkingPrecision -> 50, Method -> {"BoundaryOffset" -> False},
 PlotRange -> All]