text:
Q: Why does 'loadWindow' work here when 'window' doesn't? I was able to solve my problem with some trial and error, but I'm not really sure why it works. I have two main classes - AboutWindowController and MainView - and I was having trouble getting the AboutWindow nib to load.
Here's something that didn't work (in MainView.m):
#import "MainView.h"
#import "AboutWindowController"
...

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        AboutWindowController *aboutWindowController = [[AboutWindowController alloc] initWithWindowNibName: @"AboutWindowController"];
        [aboutWindowController window];
        ...
    }
return self;
}
...

However, this did work (using loadWindow instead of window)
#import "MainView.h"
#import "AboutWindowController"
...

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        AboutWindowController *aboutWindowController = [[AboutWindowController alloc] initWithWindowNibName: @"AboutWindowController"];
        [aboutWindowController loadWindow];
        ...
    }
return self;
}
...

The documentation says I shouldn't call loadWindow and that window calls it anyway, but the window did not appear. After playing around for a bit, I was able to fix the problem by adding a property to the implementation file, as follows:
#import "MainView.h"
#import "AboutWindowController.h"

@interface MainView
@property (strong, nonatomic) AboutWindowController *aboutWindowController;
@end

@implementation MainView

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        _aboutWindowController = [[AboutWindowController alloc] initWithWindowNibName: @"AboutWindowController"];
        [_aboutWindowController window];
    ...
    }
return self;
}
...

I'm wondering why adding the property fixed everything. Can someone shed light on this for me?

A: In the first two cases, the reference to your AboutWindowController object is held in a local variable. When that local variable goes out of scope, ARC releases the reference. If that's the last reference, the window controller is deallocated, at which point it releases the window. If that was the last reference to the window, then the window is deallocated and removed from the screen (probably before you ever got a chance to see it).
By assigning the reference to a strong instance variable, you ensure that the window controller sticks around long enough to see the window.
I'm not sure why it worked when you called -loadWindow. It could be that -loadWindow effectively leaks a reference to the window (or the controller) when it's called directly (which would be one reason that you're not supposed to do that).


text:
Q: Generate Excel from SQL through PHP I am using the following code to generate excel from sql through php.this is a modeifed verion of the working code ..
WORKING CODE (NO ERROR)
<?php
//documentation on the spreadsheet package is at:
//http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.php
chdir('phpxls');
require_once 'Writer.php';
chdir('..');

$sheet1 =  array(
  array('eventid','eventtitle'       ,'datetime'           ,'description'      ,'notes'      ),
  array('5'      ,'Education Seminar','2010-05-12 08:00:00','Increase your WPM',''           ),
  array('6'      ,'Work Party'       ,'2010-05-13 15:30:00','Boss\'s Bday'     ,'bring tacos'),
  array('7'      ,'Conference Call'  ,'2010-05-14 11:00:00','access code x4321',''           ),
  array('8'      ,'Day Off'          ,'2010-05-15'         ,'Go to Home Depot' ,''           ),
);

$sheet2 =  array(
  array('eventid','funny_name'   ),
  array('32'      ,'Adam Baum'    ),
  array('33'      ,'Anne Teak'    ),
  array('34'      ,'Ali Katt'     ),
  array('35'      ,'Anita Bath'   ),
  array('36'      ,'April Schauer'),
  array('37'      ,'Bill Board'   ),
);

$workbook = new Spreadsheet_Excel_Writer();

$format_und =& $workbook->addFormat();
$format_und->setBottom(2);//thick
$format_und->setBold();
$format_und->setColor('black');
$format_und->setFontFamily('Arial');
$format_und->setSize(8);

$format_reg =& $workbook->addFormat();
$format_reg->setColor('black');
$format_reg->setFontFamily('Arial');
$format_reg->setSize(8);

$arr = array(
      'Calendar'=>$sheet1,
      'Names'   =>$sheet2,
      );

foreach($arr as $wbname=>$rows)
{
    $rowcount = count($rows);
    $colcount = count($rows[0]);

    $worksheet =& $workbook->addWorksheet($wbname);

    $worksheet->setColumn(0,0, 6.14);//setColumn(startcol,endcol,float)
    $worksheet->setColumn(1,3,15.00);
    $worksheet->setColumn(4,4, 8.00);

    for( $j=0; $j<$rowcount; $j++ )
    {
        for($i=0; $i<$colcount;$i++)
        {
            $fmt  =& $format_reg;
            if ($j==0)
                $fmt =& $format_und;

            if (isset($rows[$j][$i]))
            {
                $data=$rows[$j][$i];
                $worksheet->write($j, $i, $data, $fmt);
            }
        }
    }
}

$workbook->send('test.xls');
$workbook->close();

//-----------------------------------------------------------------------------
?>

MODIFIED CODE TO RETRIEVE DATA FROM DATABASE (WHICH SHOWS ERROR)
<?php

    $numrow12 = mysql_query("SELECT * FROM mastertable WHERE pdfstatus = 1 ORDER BY tstamp DESC");

    mysql_select_db("brainoidultrafb", $link);
    chdir('phpxls');
    require_once 'Writer.php';
    chdir('..');

    while($row = mysql_fetch_array($numrow12)) {
        $sheet1 =  array(
      array('StudentID','Students Email' ,'Diagnosis','TimeStamp' ,),
      array($row['student_id'] ,$row['email_id'],$row['diagnosis'],$row['tstamp'],),
    );

    }

    $workbook = new Spreadsheet_Excel_Writer();

    $format_und =& $workbook->addFormat();
    $format_und->setBottom(2);//thick
    $format_und->setBold();
    $format_und->setColor('black');
    $format_und->setFontFamily('Arial');
    $format_und->setSize(8);

    $format_reg =& $workbook->addFormat();
    $format_reg->setColor('black');
    $format_reg->setFontFamily('Arial');
    $format_reg->setSize(8);

    $arr = array(
          'Calendar'=>$sheet1,
              );

    foreach($arr as $wbname=>$rows)
    {
        $rowcount = count($rows);
        $colcount = count($rows[0]);

        $worksheet =& $workbook->addWorksheet($wbname);

        $worksheet->setColumn(0,0, 6.14);//setColumn(startcol,endcol,float)
        $worksheet->setColumn(1,3,15.00);
        $worksheet->setColumn(4,4, 8.00);

        for( $j=0; $j<$rowcount; $j++ )
        {
            for($i=0; $i<$colcount;$i++)
            {
                $fmt  =& $format_reg;
                if ($j==0)
                    $fmt =& $format_und;

                if (isset($rows[$j][$i]))
                {
                    $data=$rows[$j][$i];
                    $worksheet->write($j, $i, $data, $fmt);
                }
            }
        }
    }

    $workbook->send('Submissions.xls');
    $workbook->close();

    //-----------------------------------------------------------------------------
    ?>

Its showing the following errors
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/content/58/9508458/html/psychiatric/subexcel.php on line 13
Warning: Cannot modify header information - headers already sent by (output started at /home/content/58/9508458/html/psychiatric/subexcel.php:13) in /home/content/58/9508458/html/psychiatric/phpxls/Writer.php on line 67
Warning: Cannot modify header information - headers already sent by (output started at /home/content/58/9508458/html/psychiatric/subexcel.php:13) in /home/content/58/9508458/html/psychiatric/phpxls/Writer.php on line 68
Warning: Cannot modify header information - headers already sent by (output started at /home/content/58/9508458/html/psychiatric/subexcel.php:13) in /home/content/58/9508458/html/psychiatric/phpxls/Writer.php on line 69
Warning: Cannot modify header information - headers already sent by (output started at /home/content/58/9508458/html/psychiatric/subexcel.php:13) in /home/content/58/9508458/html/psychiatric/phpxls/Writer.php on line 70
Warning: Cannot modify header information - headers already sent by (output started at /home/content/58/9508458/html/psychiatric/subexcel.php:13) in /home/content/58/9508458/html/psychiatric/phpxls/Writer.php on line 71

A: Right now, you're selecting the database after you try to query the database:
$numrow12 = mysql_query("SELECT * FROM mastertable WHERE pdfstatus = 1 ORDER BY tstamp DESC");

mysql_select_db("brainoidultrafb", $link);

That won't work. Just swap the order so you select the database, then query it:
mysql_select_db("brainoidultrafb", $link);

$numrow12 = mysql_query("SELECT * FROM mastertable WHERE pdfstatus = 1 ORDER BY tstamp DESC");

As for your second problem, you're overwriting $sheet1 on each iteration of the loop. Do this instead:
$sheet1 = array(
    array('StudentID','Students Email' ,'Diagnosis','TimeStamp' ,)
);

while($row = mysql_fetch_array($numrow12)) {
    $sheet1[] = array($row['student_id'], $row['email_id'], $row['diagnosis'], $row['tstamp'],);
}

A: For your second problem use:
$sheet1[] =
To append elements to the $sheet1 array. You're currently replacing it after every iteration of the loop.
You'll probably want to initialize $sheet1 outside of the while loop to avoid warnings as well. $sheet1 = array();

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Newbie question: ThreadProc I am just trying to understand some source code written in C++. I am a bit familiar
with C++, however, the following code sequence is absolutley new to me. A guess would be
that here I register some thread routine with the kernel, ptest->Run(). Could that be right?
static unsigned int __stdcall ThreadProc(void *lParameter)
{
CTest *ptest;

ptest= (Ctest *)lParameter;
ptest->Run();
return 0;
 }

CTest::CTest(int n)
{
...
}

A: A bit simplified but a thread is a function, in this case ThreadProc. When the thread starts, the function is called and when the function exits the thread dies.
In this case, someone has started a thread with CreateThread, begin_thread or something else and passed in a pointer to a class called CTest as an argument. The thread then casts it back to a CTest* (as you can see the argument is delivered by the CreateThread API as a more generic void*) and calls the CTest::Run method before exiting.
Edit: Also, except for the "__stdcall" declaration, this is not very Windows specific. Threads in C and C++ works more or less like this on all OSes.

A: This is a function signature that would be used to define a function that is exported from a DLL or used as a callback function.  In this case it is probably going to be used a the main loop of a worker thread.
the __stdcall keyword indicates that the function call is passed on the stack using the stdcall calling convention in Windows (same as used by methods exported from the Win32 API)
OOPS:  this link doesn't play nice with markdown http://msdn.microsoft.com/en-us/library/zxk0tw93(VS.80).aspx

A: Not quite. This is your thread function:
static unsigned int __stdcall ThreadProc(void *lParameter)

It will be executed an different thread than whatever caused it. Calling code creates an object of type CTest, creates a thread that runs ThreadProc, which in turn runs ptest->Run();
ThreadProc is just a convenience wrapper to launch ptest->Run(). (Because otherwise it is kinda hard to use pointers to member functions)

A: What OS? Looks like a Windows sample, if so begin_thread(), or CreateThread or...several

A: The code you show declares a pointer to a CTest class object, converts the input parameter into one of those, then calls its run method.
The why this is done is the tricky part. Normally you wouldn't write code like this, however, the profile of ThreadProc is that of a thread's main entry point. For one of those, Windows doesn't give you any choice for the parameter profile of it, and it can't be a class member.
What you have there is fairly standard code to convert a thread entry-point callback from the Windows' required form into a class method call.
For a full discussion of this, see my (accepted) answer for the question: Passing Function pointers in C++


text:
Q: How can I convert the timer from counting back in seconds to count back in minutes and seconds? I have numericUpDown1 that when I set its value it's saving the value in options text file:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            Options_DB.Set_Radar_Images_Time(numericUpDown1.Value);
        }

timer1 interval set to 1000ms in the form1 designer.
In timer1 tick event I have:
private void timer1_Tick(object sender, EventArgs e)
        {
           numbers_radar = Convert.ToInt64(numericUpDown1.Value);
        }

Now I want to assign the timer tick event to: label21.Text and display the minutes counting down.
If I set the numericUpDown1 to 10 so it will count down 10 minutes.
The format should be like: minutes:seconds (00:00).
And each time the timer get to 1 it should call this method: fileDownloadRadar();
Each time when it's get to 1 the timer should be reset to the numericUpDown1 value and start over again counting back and each time in the end to call the method fileDownloadRadar();
The numericUpDown1 is set to minimum 5 and maximum 60
EDIT
Now i tried this code but i don't see anything change on label21 when starting the timer.
And minutes is starting as 0 but should be in this case 29(value of numericUpDown1).
And should i check if minutes and seconds == 1 or == 0 ? What's more logic 1 or 0 ?
private void timer1_Tick(object sender, EventArgs e)
        {
            numOfMinutes = Convert.ToInt32(numericUpDown1.Value);
            int seconds = numOfMinutes % 60;
            int minutes = numOfMinutes / 60;
            seconds --;
            string time = minutes + ":" + seconds;
            label21.Text = time;
            if (seconds == 1)
            {
                minutes --;
            }
            if (minutes == 1 && seconds == 1)
            {
                numOfMinutes = Convert.ToInt32(numericUpDown1.Value);
                fileDownloadRadar();
            }
        }

A: I think you could better use a TimeSpan object and start as follows.
declare a TimeSpan variable in your object (thus a private field):
private TimeSpan span;

Just below the code where you start the timer, initialize the span variable:
timer1.Start(); // this should exist somewhere
TimeSpan span = new TimeSpan(0, numericUpDown1.Value, 0);

In your timer event handler, write this code:
private void timer1_Tick(object sender, EventArgs e)
{
    span = span.Subtract(new TimeSpan(0, 0, 1));
    label21.Text = span.ToString(@"mm\:ss");

    if (span.TotalSeconds < 1)
    {
        span = new TimeSpan(0, numericUpDown1.Value, 0);
        fileDownloadRadar();
    }
}

I'm not sure what you want in the if statement, but I hope this will help you further.


text:
Q: How to get SIM ip address for ipad I need to know the source IP for my iPad using my SIM network. Is there any way to get source IP address for SIM network

A: Go to a website like e.g. http://www.whatsmyip.org and there you can see your public IP address.


text:
Q: How to upload multiple projects in separate folders to the same repository? I have multiple projects in separate folders. It looks as following on the disk:

I already created remote repository and uploaded one project. It looks as following:

How to upload the second project in its separate folder to the same repository?

A: FIrst create subdirectory in local repo
mkdir png

then add files ( and move then into subdirectory)
git add *.png
git mv  *.png ./png

commit  and push
 git commit -m "move"
 git push -u origin main

If you already have folders then
git add /png/*.png
git commit -m "c"
git push -u origin main


text:
Q: Angular 5 - Promise vs Observable - performance context I have an Angular 5 site that receives data from a REST API, something like 1-4 requests to the API each page,
and what happens is that the requests sometimes take a long time(and sometimes not).
Now, all the requests are being performed in one function using Observable :
return this.http.post(url, {headers: this.header})
        .map(res => res.json())
        .catch(this.handleError)

my question is - could it be that the slow process is happening because an Observable is being used? Would Promises will be better for the performance?
Or is there no difference between an Observable and a Promise in performance context?

A: because you question intrigue me. i have create same testing which look like this :
console.time('observable');
for(let i = 0; i < 10000; i++) {
  let user$ = of({
    name: 'yanis-git'
  });

  user$.subscribe(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('observable');

console.time('promise');
for(let i = 0; i < 10000; i++) {
  new Promise((resolve) => {
    resolve({
      name: 'promise'
    });
  }).then(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('promise');

and result looks like this (can be different on your browser / setup but proportion should be the same :
observable: 34.060791015625ms
promise: 103.4609375ms

EDIT :
Another implementation with both async traitment inside :
console.time('observable');
for(let i = 0; i < 10000; i++) {
  let user$ = Observable.create((o) => {
    setTimeout(() => {
      o.next({
        name: 'observable'
      });
    });
  });

  user$.subscribe(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('observable');

console.time('promise');
for(let i = 0; i < 10000; i++) {
  new Promise((resolve) => {
    setTimeout(() => resolve({
      name: 'promise'
    }))
  }).then(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('promise');

Result are close but race are win by observable.
observable: 160.162353515625ms
promise: 213.40625ms

live sample
if you want to check on stackblitz, please use real browser console to see timer output

A: According to my tests, a Promise is more performant than an Observable.
I think Yanis-git test is a good start, but only shows part of the picture. It only calculates the starting of the Promise or Observable, but doesn't count the time for its resolution.
Here is the code I modified to take into account the resolution of the async functions as well:
https://stackblitz.com/edit/typescript-xhhseh?file=index.ts
import { of, Observable, zip } from 'rxjs';
console.clear();

function testPromise(){
  console.time('promise');
  const promiseAry = [];
  for(let i = 0; i < 10000; i++) {
    promiseAry[i] = new Promise((resolve) => {
      setTimeout(() => resolve({
        name: 'promise'
      }))
    }).then(user => {
      // do something. Prefer not console.log because is ressource consuming.
    });
  }
  Promise.all(promiseAry).then(() =>{
    console.timeEnd('promise');

    // test Observables after Promises have completed
    testObservable();
  })
}

function testObservable(){
  console.time('observable');
  const observeAry = [];
  for(let i = 0; i < 10000; i++) {
    observeAry[i] = Observable.create((o) => {
      setTimeout(() => {
        o.next({
          name: 'observable'
        });
      });
    });

    observeAry[i].subscribe(user => {
      // do something. Prefer not console.log because is ressource consuming.
    });
  }
  let source$ = zip(...observeAry);
  source$.subscribe(([weatherInfo, tweetInfo]) =>
    console.timeEnd('observable')
  );

}

testPromise();

When I run the test in Chrome (on Mac), by visiting this page directly and opening the console: https://typescript-xhhseh.stackblitz.io/ I get these results:
promise: 279.65185546875ms
observable: 552.891845703125ms

And a very similar result in Firefox:
promise: 232ms - timer ended
observable: 319ms - timer ended

Running them repeatedly, I always come up with Observable taking more time than Promise, which makes sense especially because Promises are now native to JavaScript, whereas Observables are not, so they wouldn't seem to be as performant.
Special thanks to Yanis-git for coming up with the original test that I forked.

A: It's not actually fair example by the last comment. More right usage RxJS in this scheme would be in this modified example:
https://stackblitz.com/edit/typescript-uajatd
Working browser performance: https://typescript-uajatd.stackblitz.io
And we can see RxJS mostly wins the race :)

A: The golden rule of performance troubleshooting is this: always measure; never jump to conclusions.
Start by reproducing a scenario where the page is running slowly. Check on the Network tab in your browser's developer console. How long does each network request take? Are the requests running in parallel, or is there a stair-step formation, where each request is not initiated until the previous one completes? Is there a long pause between requests, or does each one start immediately when the previous one finishes? Does the page appear loaded immediately when the last request is finished?
If you're unable to reproduce the problem, consider using a monitoring tool, like sentry.io, to help gather data. Analyze the data and find out what's taking so long. Is there a particular example of a record in your app that triggers this condition?
You should also look at application logs on the server side. How long is the server taking to respond to each request?
If you need to find out in detail what your rxjs code is doing, consider using this tool:
https://github.com/cartant/rxjs-spy
I found this very helpful for local development.
Note that rxjs-spy introduces a large performance overhead, and is NOT suitable for production use.


text:
Q: What is the antonym of "non-stop flight"? Indirect flight is the antonym of direct flight. However, direct flights and non-stop flights have a  different meaning.

A: A direct flight with a layover.
Apparently flight crew use the term "layover" differently from other travellers, and many people (including me 5 minutes ago) would not know the difference between a direct and a non-stop flight, or between a stopover and a layover.
You won't often see this being used, because the main reason to mention that a flight has a layover, is if you will need to change planes, of if you will have a stopover and spend the day in a hotel. If you have a short layover and don't even disembark then it's not very notable.
You could also say "...with a stop at ... to refuel."

A: I don't think there is a definitive phrase or word. However, I have seen the following used to convey your meaning: multi-city, multi-hop, and multi-destination.
Of those, I'd say the first is most common, even where the intermediate points aren't actually cities.


text:
Q: Import fixed width UTF-8 file into SQL 2008R2, variabel file names I have to import text files with different names (like the following) into SQL Server 2008.

*

*XYZ0000746263.txt

*XYZ0000746269.txt

*XYZ0000745860.txt

The filename always starts with XYZ, and the number is always higher than the file before.
The format of the file is fixed-width, with UTF-8 encoding.
SHINST 1020130613
SHINSD0745860182650  940PI67100000           dataw11     2012CH 01002601900100 848CRU
SHINSD0745860182650  940PI67066900           dataa12     9434CH 00701801400030 848CRU
SHINSD0745860182650  940PI67160300          adsfaf13     1205CH 04203601000160 848CRU
SHINSD0745860182650  940PI67171300           data 14     1205CH 01803501200120 848ND1
SHINSD0745860182650  940PI67079000           asdfs15     8400CH 00702601400040 848ND1
SHINSD0745860182620  940PI67053900           data 16     6877CH 01904101100130 848ND1
SHINSD0745860182620  940PI67156100          text  17     3003CH 08906202902460 848ND2
SHINSD0745860182650  940PI67110700         alskdjf18     1000CH 02603900900130 848ND2
SHINSD0745860182620  940PI67123900       asfasdffa19     8048CH 01502300900020 848ND2
SHINSD0745860182650  940PI67066300           data 20     8952CH 01002601900090 848ND2
SHINSF000012

The first line contains SHINST, then the number of records in the file, then a date in the format YYYYMMDD.
The records contain SHINSD, then a 13-digit number, then the fixed-width records.
The last line contains SHINSF, then a six-digit number with the total number of lines of the file.
I want to automatically import files in this format into an SQL table. How can that be done?

A: You can try with:
BULK INSERT tablename FROM 'c:\File.txt' WITH (FIELDTERMINATOR = ' ')

If the ' '(space) is your field delimiter.
Of course table table name columns must be the same as in file (count and length).
You can make a procedure and give it a filenamepath only, as in these exaples
The only problem is first and last row in file, cause they are different and I don;t know if you need to insert the mas well. If you need to ignore them, maybe you'll need a script to eliminate them.


text:
Q: Add visual elements (icons) to ggpplot labels I have code that creates a bar plot using ggplot:
library(tidyverse)

data <- data.frame(
    name=c("north","south","south-east","north-west","south-west","north-east","west","east"),
    val=sample(seq(1,10), 8 )
)

data %>%
    mutate(name = fct_reorder(name, val)) %>%
    ggplot( aes(x=name, y=val)) +
    geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
    coord_flip() +
    xlab("") +
    theme_bw()

Is it possible to add some visual elementos to the plot, say for example next to "south" adding a small icon and the same for the other regions?
It would look like the attached image...


text:
Q: PHP - Switch on a multi dimensional array I try to do a switch on a multidimensional array :
$types = array (
'type1' => array('value1', 'value2'),
'type2' => array('value3', 'value4');
...
);

$prefix = substr($number, 0, 4);

foreach ($types as $key => $values) {
    switch ($prefix) {
        case 'type1' :
            $type = 'TYPE1';
            break;
        case 'type2' :
            $type = 'TYPE2';
            break;
        ...
      }
}

Where the $prefix is equal to a value in $types array.
But it didn't works. I guess i'm close to the solution, but can't find it (googled gave me nothing more). Thanks (:

A: You have no $prefix in this code.
Try this:
$types = array (
    'type1' => array('value1', 'value2'),
    'type2' => array('value3', 'value4')
);

foreach ($types as $key => $values) {
    switch ($key) { // $prefix does not exist (at least not according to this code).
        case 'type1' :
            $type = 'TYPE1';
            break;
        case 'type2' :
            $type = 'TYPE2';
            break;
      }

}

A: I'm not sure to understand.
If $prefix = 'value1' or 'value2' or 'value3' .... you can try something like this:
foreach ($types as $key => $values) {
    if (in_array($prefix, $values) )
        $type = strtoupper($key);
}


text:
Q: Files that I download from an FTP server do not have the same length as the files on the server I am downloading files from a server using FTPClient in Java. When the file is downloaded, I would like to check it's integrity and then delete it.
I am doing this by comparing the size of both the downloaded file in bytes, and the file on the server in bytes, however the results are not as expected.
Below is an extract from my transfer directory:
for (int i = 0; i <= insideDirectory.length - 1; i++) {
                    FTPFile transferFile = insideDirectory[i];
                    LOGGER.info("Passing file" + folder.getName() + "/" + transferFile.getName());

                    File downloadFile = new File("/users/home/example" + i + ".mp4");
                    OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile));
                    System.out.println(transferFile.getSize());
                    ftpClient.enterLocalPassiveMode();
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    InputStream inputStream = ftpClient
                            .retrieveFileStream(folder.getName() + "/" + transferFile.getName());
                    byte[] bytesArray = new byte[4096];
                    int bytesRead = -1;
                    while ((bytesRead = inputStream.read(bytesArray)) != -1) {
                        outputStream2.write(bytesArray, 0, bytesRead);
                    }

                    Boolean success = ftpClient.completePendingCommand();
                    if (success) {
                        System.out.println("File #" + i + " has been downloaded successfully.");
                        checkIfExists(downloadFile, transferFile);
                    }

Below is my checkIfExists method
public void checkIfExists(File downloadedFile, FTPFile remoteFileToDelete) {
    Long downloadedLength = downloadedFile.length();
    Long remoteLength = remoteFileToDelete.getSize();
    if (downloadedFile.length() == remoteFileToDelete.getSize()) {
        LOGGER.info(downloadedLength + "exists and is the same length as " + remoteLength + ". Let's delete");
    } else {
        LOGGER.info(downloadedLength + "is not the same length as " + remoteLength + ". Let's not delete");
    }
}

Here is the output after running the loop twice, as you can see, the size of the downloaded file can vary:
     File #0 has been downloaded successfully.
     INFO: 7596008is not the same length as 7600840. Let's not delete
     File #1 has been downloaded successfully.
     INFO: 6873664is not the same length as 6878544. Let's not delete
     File #2 has been downloaded successfully.
     INFO: 7558112is not the same length as 7564744. Let's not delete
     File #3 has been downloaded successfully.
     INFO: 8662336is not the same length as 8665108. Let's not delete

     File #0 has been downloaded successfully.
     INFO: 7594312is not the same length as 7600840. Let's not delete
     File #1 has been downloaded successfully.
     INFO: 6870392is not the same length as 6878544. Let's not delete
     File #2 has been downloaded successfully.
     INFO: 7559184is not the same length as 7564744. Let's not delete
     File #3 has been downloaded successfully.
     INFO: 8660888is not the same length as 8665108. Let's not delete

A: .close() your BufferedOutputStream before you attempt to measure the size of the written file.
Without the .close() there's no guarantee (indeed quite the opposite) that all of the data that you have written to the stream will actually have been written to the underlying file that you access via the File object.


text:
Q: Workstation restarts automatically I have workstation with Asus Rog strix B450 F motherboard and got it replaced recently. I had 2 rams DDR4 where I found that one of the DIMM might be faulty as the workstation when powered on did not displayed anything on the monitor.
With one ram module, the workstation boots and displays properly, but sometimes it automatically turns off and restarts again. I see that there is white LED light blinking on the motherboard which I understood that this white LED light represent issue with display. I recently got new Nvidia GT 730 adapter fitted on the motherboard where the monitor is connected. I am curious to understand if the monitor has any problem / issue, will that cause any desktop to restart automatically? Monitor is dell. White LED light represents issue with VGA based on Asus Q LED signals.


text:
Q: Get keyboard height or top position when keyboard open How do I get keyboard height or top position when keyboard open? I found the following module but it's only for iOS. How do I get in Android?
react-native-keyboardevents

A: You can access keyboard details through the keyboard events.
Format of data:
Object {
  "height": 282,
  "screenX": 0,
  "screenY": 401.4285583496094,
  "width": 411.4285583496094,
}

You can call access them thus:
import { Keyboard } from 'react-native'

keyboardDidShow (e) {
    const { height, screenX, screenY, width } = e.endCoordinates
    console.log(height)
}


text:
Q: what is the difference between azure-sb and @azure/service-bus? I want to create a nodejs Azure Service Bus client to read from a topic, and I want my client to automatically register its subscription.
So @azure/service-bus allows to work with SB normally, yet does not allow to create a subscription. azure-sb does allow to create one and also operate on the bus.
Do I need to install both in my nodejs app? Both seem official package from Microsoft, however, I wonder what is the intended usage for both and intended future (will one replace the other?)

A: To put things simply, azure-sb is the old SDK for managing Service Bus while @azure/service-bus is the new one.
There are a few differences in the two packages:

*

*Protocol: azure-sb is a wrapper over Service Bus REST API (HTTP protocol) while @azure/service-bus makes use of AMQP protocol to communicate with Service Bus.

*Features: azure-sb enables you to work with entities (Queues, Topics and Subscriptions) by allowing them to perform CRUD operations on them. These features were removed from @azure/service-bus as Microsoft is moving these CRUD operations under control plane by enforcing RBAC on these operations. For performing these operations, you will need to use @azure/arm-servicebus. @azure/service-bus package is more geared towards sending and receiving messages. It also supports Websockets in case you need that.

Do I need to install both in my nodejs app? Both seem official package
  from Microsoft, however, I wonder what is the intended usage for both
  and intended future (will one replace the other?)

Considering your requirement, my answer is yes. You would need both of these packages. I'm not sure if that will cause any problems. In our project, we ended up implementing REST API directly (instead of using azure-sb package) for CRUD operations on entities and used @azure/service-bus for working with messages.
Regarding @azure/service-bus will eventually replace azure-sb package, I will be purely speculating but I don't think that will happen anytime soon. For this, Service Bus team will have to remove the REST API first which seems highly unlikely however Microsoft is pushing hard for RBAC at entities level so I would recommend that you use @azure/arm-servicebus along with @azure/service-bus if you're starting new.


text:
Q: UINavigationController transition animations triggered too fast I'm using a custom-made container view controller in my dictionary app. Basically, the container view controller contains a custom navigation bar on top (NOT a UINavigationBar--just a UIView with back and forward UIButtons, a UISearchBar, and a bookmark UIButton at the right), and a tab bar controller at the bottom.
My problem is this: I use the back and forward buttons to push and pop view controllers in one of the tabs (a UINavigationController) so the user can navigate through the dictionary browsing history. However, if I press the back or forward buttons too fast, I get this message in the log pane and some of the screens don't appear at all:

Unbalanced calls to begin/end appearance transitions for
  <DefinitionViewController: 0x8e5d230>.

Looking around StackOverflow, I understood that this is because clicking on the back or forward buttons too fast calls the push/pop methods of the UINavigatonController in the active tab, but it does not let the animation finish. https://stackoverflow.com/a/17440074/855680
Pushing or popping view controllers without the animations solves the problem, but I do want to keep the animations. How can I approach this problem? I looked at the UINavigationController class reference to see if there are any delegate methods or properties that indicate that it's in the middle of an animation, but there doesn't seem to be any.

A: Fixed it myself. The solution was to create a property in my container view controller which indicates whether the UINavigationController transition animations are still happening:
@property (nonatomic, getter = isStillAnimatingTransition) BOOL stillAnimatingTransition;

Now, for all the UIViewController classes that I push into the UINavigationController, I set this flag to YES or NO in each of the view controllers' viewWillDisappear and viewDidAppear methods, like this:
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.containerViewController.stillAnimatingTransition = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.containerViewController.stillAnimatingTransition = YES;
    [super viewWillDisappear:animated];
}

And my container view controller only ever allows the execution of the back and forward buttons if the animation flag is set to NO, like this:
- (void)backButtonClicked
{
    if (!self.isStillAnimatingTransition) {
        // Do whatever.
    }
}

- (void)forwardButtonClicked
{
    if (!self.isStillAnimatingTransition) {
        // Do whatever.
    }
}

A: Maybe you can take advantage of the UINavigationControllerDelegate class and handle the events there.
In your main class that holds the navigation controller, set the delegate to yourself and handle the interactions there.
i.e. in the .h file:
@interface yourClass : UIViewController <UINavigationControllerDelegate> {
     UINavigationController *content;
}

and then in the .m file:
  content = [[UINavigationController alloc] initWithRootViewController:yourRootViewController];
  content.delegate = self;

After that you can listen to the transition events via the following functions, and set your animation flags accordingly.
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    stillAnimatingTransition = NO;
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    stillAnimatingTransition = YES;
}

You can find more references about the delegate protocol from apple
https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationControllerDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UINavigationControllerDelegate/navigationController:willShowViewController:animated:


text:
Q: Index.html instead of client stuff on server side How can I get index.html for my app's client side?
The index page is defined in server.js like this
// load css styles
var css = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> ';
css = css + '<style type="text/css">' +require('fs').readFileSync('./style.css').toString() + '</style>'

http.createServer(function (req, res) {
  // send basic http headers to client
  res.writeHead(200, {
      "Content-Type": "text/html",
      "Transfer-Encoding": "chunked"
  });
  // setup simple html page:
  res.write("<html>\n<head>\n<title>Newsfeed</title>\n" +css +"</head>\n<body>");

But I want to get an index.html so I can use plain HTML for front-end.

A: This would explain the long.
Short answer is, you separate view, and use express middlewer for routing.
You must set view location:
app.set('views', __dirname + '/yourViewDirectory');

Put your index.html into /views folder
Then you can use res.render function:
res.render('index.html');

This is the base express server, which render index.html on localhost:3000/
var express = require('express');
var app = express();

app.set('views', __dirname + '/yourViewDirectory');
app.get('/', function (req, res) {
  res.render('index.html');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});


text:
Q: Making animated choropleth with ArcGIS Pro I want to make an animation that shows the changes in state shape and state population every ten years. My state data is all in one large feature class. I have a polygon for each state every ten years, along with the state's population.

I want the animation to start with something like this:
and end with something like this: I want the animation to cycle through the different years, with maybe a 2 second pause for each year.
I know how to use graduated colors in the symbology to make the choropleth maps, I just don't know how to use the animation tools in ArcGIS Pro to make the animation.
I tried to create key frames of the map using different Definition Queries (ie CensusYear=1900), but the key frames wouldn't change. Do I need to make separate maps for each key frame? What is the best way to do this with ArcGIS Pro?


text:
Q: Showing that composition can be represented by a map I want to prove proposition 5.6 in Lawvere and Rosebrugh.
The proposition goes like this.
Suppose $g:B \to Y_1$ and $\phi: Y_1 \to Y_2$ are arbitrary.
There exists a $\ulcorner c \urcorner: Y_2^{Y_1} \times Y_1^B \rightarrow Y_2^B$, such that $\ulcorner c\urcorner (\ulcorner \phi \urcorner,\ulcorner g \urcorner) = \ulcorner \phi g \urcorner$.
Now to start define $c: Y_2^{Y_1} \times Y_1^B \times B \to Y_2^B$ as the composite of $1 \times \text{eval}_1: Y_2^{Y_1} \times Y_1^B \times B \to Y_2^{Y_1} \times Y_1$ and $\text{eval}_2: Y_2^{Y_1} \times Y_1 \to Y_2$, where $1: Y_2^{Y_1} \rightarrow Y_2^{Y_1}$ is the identity. Then I wan't to invoke the universal property of one of the exponentials, in order to get $\ulcorner c \urcorner$ and then prove the equality in question, but I can't find the right one to use.

A: Since I don't know the book and since I can only guess what the notation is supposed to mean, I'll assume that this takes place in a cartesian closed category with terminal object $1$. If I interpret the question correctly, what we're trying to prove is the existence of the so-called internal composition. That is, the morphism $c\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ which makes the diagram
$$\require{AMScd}
\begin{CD}
Y_2^{Y_1}\times Y_1^{B}\times B @>{c\times \mathrm{id}_B}>> Y_2^{B}\times B\\
@V{\mathrm{id}\times\mathrm{ev}_{B,Y_1}}VV @VV{\mathrm{ev}_{B,Y_2}}V \\
Y_2^{Y_1}\times Y_1 @>{\mathrm{ev}_{Y_1,Y_2}}>> Y_2
\end{CD}$$
commute.
Since the adjunction map $\mathrm{hom}(Y_2^{Y_1}\times Y_1^{B},Y_2^{B})\to \mathrm{hom}(Y_2^{Y_1}\times Y_1^{B}\times B,Y_2)$ maps an arbitrary morphism $f\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ to the composition
$$Y_2^{Y_1}\times Y_1^{B}\times B\xrightarrow{f\times\mathrm{id}_B}Y_2^{B}\times B\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2,$$
we see that $c$ is just the unique element corresponding to $\mathrm{ev}_{Y_1,Y_2}\circ(\mathrm{id}_{Y_2^{Y_1}}\times\mathrm{ev}_{B,Y_1})$.
Finally, precompose the diagram with $1\times 1\times B\xrightarrow{([\phi],[g])\times\mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B$ and combine all the present adjunctions to conclude that $c([\phi],[g]) = [\phi\circ g]$.
Addendum: After having a look at the book in question and reading the question again, I realised that the above is not much more than the OP already knew. Here we go again, but using different words.
The universal (exponential) property of $Y^B\times B\xrightarrow{\mathrm{ev}_{B,Y}}Y$ is this: For every $X$ and each map $f\colon X\times B\to Y$ there exists a unique $[f]\colon X\to Y^B$ such that the composition
$$X\times B\xrightarrow{[f]\times\mathrm{id}_B}Y^B\times B\xrightarrow{\mathrm{ev}_{B,Y}}Y$$
equals $f$.
I'd rather conflict with the OP's notation than with mine above. Therefore, we define $f := \mathrm{ev}_{Y_1,Y_2}\circ(\mathrm{id}_{Y_2^{Y_1}}\times\mathrm{ev}_{B,Y_1})\colon Y_2^{Y_1}\times Y_1^{B}\times B\to Y_2$ and from the exponential property (where $X = Y_2^{Y_1}\times Y_1^{B}$ and $Y = Y_2$) we get $c := [f]$, the unique map $c\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ making the above square diagram commute.
It remains to show that $c([h],[g]) = [h\circ g]$ for every pair of maps $g\colon B\to Y_1$ and $h\colon Y_1\to Y_2$ where $[g]\colon 1\to Y_1^B$ and $[h]\colon 1\to Y_2^{Y_1}$ are the unique maps such that
$$B \xrightarrow{[g]\times \mathrm{id}_B}Y_1^B\times B\xrightarrow{\mathrm{ev}_{B,Y_1}}Y_1$$
equals $g$ and
$${Y_1} \xrightarrow{[h]\times\mathrm{id}_{Y_1}} Y_2^{Y_1}\times Y_1\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2$$
equals $h$. Thus, $h\circ g\colon B\to Y_2$ equals
$$
B\to 1\times 1\times B
\xrightarrow{1\times [g]\times \mathrm{id}_B}1\times Y_1^B\times B
\xrightarrow{1\times \mathrm{ev}_{B,Y_1}}1\times Y_1
\xrightarrow{[h]\times \mathrm{id}_{Y_1}}Y_2^{Y_1}\times Y_1\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2
$$
and substituting identities gives
\begin{align*}
h\circ g &= (B\to  1\times 1\times B
\xrightarrow{[h]\times [g]\times \mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B
\xrightarrow{\mathrm{id}_{Y_2^{Y_1}}\times \mathrm{ev}_{B,Y_1}}Y_2^{Y_1}\times Y_1
\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2)
\\&=
(B\to  1\times 1\times B
\xrightarrow{[h]\times [g]\times \mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B
\xrightarrow{c\times\mathrm{id}_B}Y_2^{B}\times B
\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2)
\\&=
(B\to 1\times B
\xrightarrow{c([h]\times [g])\times \mathrm{id}_B}Y_2^{B}\times B
\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2).
\end{align*}
But this implies $c([h], [g]) = [h\circ g]$.


text:
Q: Degraded volume on Synology NAS Today my Synology NAS's OS (DSM) told me that I have a degraded volume. The advice on their site is to replace the failed drive. I've gone ahead and bought the same drive model and capacity, and it has arrived.
However, I'm struggling to know which drive has failed. It may be my lack of HDD knowledge, but the two diagnostic screens in the DSM Storage Manager panel seem to conflict somewhat.
See these screenshots of Storage Pool and HDD/SSD tabs in the Storage Manager:

Although the Storage Pool tab seems to suggest that Disk 2 is degraded, the Disk 2 status is "Normal" and Disk 1 is "Initialized" in the HDD/SSD tab.
According to the instructions on the Synology website:

The status of the drive for replacement must be Initialized or Not Initialized.

Perhaps the GUI is the wrong thing to show here, but if anyone could provide any more insight as to which of my disks needs replacing that would be great. Time is of the essence as I'm on RAID 1 with only two drives.
Thanks in advance.

A: So it turns out the "Disk Info" listed in the Storage Pool tab are the disks currently contributing to the storage pool, not the disks with issues. The absence of Disk 1 here is the telling sign that Disk 1 is the HDD with the hardware failure, which would corroborate with the HDD/SSD tab's information.
From Synology's support response:

Both screenshots show that Disk 2 is part of the Storage Pool.
In the left screenshot, Disk 1 is missing and this means that it is
  not in the Storage Pool.
You may have noticed when adding a new HDD, they show up in three
  different states inside Storage Manager:

*

*Not Initialised = No system partition, HDD not used in a volume.

*Initialised = System partition correct, HDD not used in a volume.

*Normal = System partition correct, HDD used in a volume.

  As Disk 2 is normal, this indicates that it is in a Volume.
Where as Disk 1 is Initialised, so it means that it is not in a
  volume.

I have swapped out Disk 1 for a new drive, repaired the storage pool and the system is healthy again.


text:
Q: Determine job_id from within the code-block for a cron job in Rufus Scheduler (rails 3.2) When creating a cron job through the Rufus Scheduler, is there some way
within the code-block for the cron job to determine the job_id of the
cron job itself?
What I want to do is something like this:
scheduler.cron '0 0 0 * * * Etc/GMT+0' do
  # Nix existing jobs.
  scheduler.cron_jobs.values.map { |j| if j.job_id != self.job_id then j.unschedule end }
  ...
end

The problem is self.job_id.  Any suggestions on how to retrieve the
current job_id of the cron that is currently being triggered?
I know there is something like "triggered_threads", which returned
currently running jobs.  But I want something more specific:  the
job_id of the code-block I am currently within.
Is this possible?

A: I was able to resolve this issue by supplying the scheduler.cron method invocation with the an optional parameter that explicitly identified the new job's ID:
scheduler.cron '0 0 0 * * * Etc/GMT+0', {:job_id => explicit_job_id} do
  # Nix existing jobs.
  scheduler.cron_jobs.values.map { |j| if j.job_id != self.job_id then j.unschedule end }
  ...
end

where explicit_job_id is some variable defined before the scheduler.cron invocation is made.


text:
Q: Search for cell containing combination of words I am trying to find a way to search for a cell that contains multiple words in any order.
Example: In the input box I enter "search for words". I now want search for a cell containing these three words, although they don't have to come in that order or next to each other at all.
Hope you understand what I mean. I have this code, wich works fine to find one word, but I'm stuck and don't really have a clue how to solve this. I know the solution with five If statements isn't really neat but it works.
Sub Set_Hyper()

 '   Object variables
Dim wks As Excel.Worksheet
Dim rCell As Excel.Range
Dim fFirst As String
 '   {i} will act as our counter
Dim i As Long

Dim MyVal As String
 '   Search phrase
MyVal = ActiveSheet.Range("D9")

Application.ScreenUpdating = False
Application.DisplayAlerts = False

i = 19
 '       Begin looping:
 '       We are checking all the Worksheets in the Workbook
For Each wks In ActiveWorkbook.Worksheets
     If wks.Name <> "Start" Then

     '       We are checking all cells, we don't need the SpecialCells method
     '       the Find method is fast enough
        With wks.Range("A:E")
         '           Using the find method is faster:
         '           Here we are checking column "A" that only have {myVal} explicitly

            Set rCell = .Find(MyVal, , , xlPart, xlByColumns, xlNext, False)
         '           If something is found, then we keep going
            If Not rCell Is Nothing Then
             '               Store the first address
                fFirst = rCell.Address

                ' Where is the answer
                Do

                    If rCell.Column() = 1 Then
                    ' Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 4), "", "'" & wks.Name & "'!" & rCell.Address, TextToDisplay:=rCell.Value
                    rCell.Offset(0, 1).Copy Destination:=Cells(i, 5)
                    rCell.Offset(0, 2).Copy Destination:=Cells(i, 6)
                    rCell.Offset(0, 3).Copy Destination:=Cells(i, 7)
                    rCell.Offset(0, 4).Copy Destination:=Cells(i, 8)
                 '   wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 5)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter

                    End If

                    If rCell.Column() = 2 Then
                    ' Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 4), "", "'" & wks.Name & "'!" & rCell.Address, TextToDisplay:=rCell.Offset(0, -1).Value
                    rCell.Copy Destination:=Cells(i, 5)
                    rCell.Offset(0, 1).Copy Destination:=Cells(i, 6)
                    rCell.Offset(0, 2).Copy Destination:=Cells(i, 7)
                    rCell.Offset(0, 3).Copy Destination:=Cells(i, 8)
                 '   wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 5)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter

                    End If

                    If rCell.Column() = 3 Then
                    ' Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 4), "", "'" & wks.Name & "'!" & rCell.Address, TextToDisplay:=rCell.Offset(0, -2).Value
                    rCell.Offset(0, -1).Copy Destination:=Cells(i, 5)
                    rCell.Copy Destination:=Cells(i, 6)
                    rCell.Offset(0, 1).Copy Destination:=Cells(i, 7)
                    rCell.Offset(0, 2).Copy Destination:=Cells(i, 8)
                 '   wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 5)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter

                    End If

                    If rCell.Column() = 4 Then
                    ' Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 4), "", "'" & wks.Name & "'!" & rCell.Address, TextToDisplay:=rCell.Offset(0, -3).Value
                    rCell.Offset(0, -2).Copy Destination:=Cells(i, 5)
                    rCell.Offset(0, -1).Copy Destination:=Cells(i, 6)
                    rCell.Copy Destination:=Cells(i, 7)
                    rCell.Offset(0, 1).Copy Destination:=Cells(i, 8)
                 '   wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 5)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter

                    End If

                    If rCell.Column() = 5 Then
                    ' Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 4), "", "'" & wks.Name & "'!" & rCell.Address, TextToDisplay:=rCell.Offset(0, -4).Value
                    rCell.Offset(0, -3).Copy Destination:=Cells(i, 5)
                    rCell.Offset(0, -2).Copy Destination:=Cells(i, 6)
                    rCell.Offset(0, -1).Copy Destination:=Cells(i, 7)
                    rCell.Copy Destination:=Cells(i, 8)
                 '   wks.Range("B" & rCell.Row & ":R" & rCell.Row).Copy Destination:=Cells(i, 5)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter

                    End If

                    Loop While Not rCell Is Nothing And rCell.Address <> fFirst
            End If
        End With
     End If
Next wks
 '   Explicitly clear memory
Set rCell = Nothing
    '   Reset application settings
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

EDIT:
If all words searched for are found in one cell, the hyperlink to that row should be displayed, but if not there should be no match and nothing displayed. So I'm only looking for complete matches here.

A: The .Find method is not real good with complicated searches.
Here is a function using Regular Expressions to look at a string, and return TRUE or FALSE depending on whether or not all three words are found in the string. I would suggest testing, for speed, reading the cells you wish to check into a variant array, using a syntax such as:
V=wks.range("A:E")

or, preferably, code that limits the range to just the used range
Iterating through each item in the array, running this function to see if the words are present.  The function call might look like:
IsTrue = Function FindMultWords(StringToSearch,"search","for","words")

or
IsTrue = Function FindMultWords(Your_Array(I),"search","for","words")

The number of words you can search for can vary up to the maximum number of arguments for your version.
If you want, and this approach works for you, you could certainly incorporate this code into your macro, instead of having it as a standalone function. That would have the advantage of only needing to change .Pattern, instead of creating and initializing a regex object on each call, which should make it run faster.
Option Explicit
Function FindMultWords(sSearchString As String, ParamArray aWordList()) As Boolean
    Dim RE As Object
    Dim S As String
    Const sP1 As String = "(?=[\s\S]*\b"
    Const sP2 As String = "\b)"
    Const sP3 As String = "[\s\S]+"

    Dim I As Long
Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True
    .ignorecase = True

    S = "^"
    For I = LBound(aWordList) To UBound(aWordList)
        S = S & sP1 & aWordList(I) & sP2
    Next I
    S = S & sP3
    .Pattern = S

    FindMultWords = .test(sSearchString)
End With
End Function


text:
Q: My db records are not showing in sqlite browser I am working on an android app with DB operations. And for debugging purpose I have installed the SQLite browser from here enter link description here. My problem is that when I export my db file from the emulator and open it in the browser it only shows meta data but not my actual app data.enter image description here
And yes I have exported the db file from correct location using the Android Device Manager.enter image description here
And as you can see there are some other files also created in the database folder(journal & .file).
So I was wondering if anybody knows if there is any change in how the data is stored in the SQLite DB recently. I am using Android Studio 3.0.1.
Thanks in advance for the help.
Here is the new screenshot with the package name.enter image description here
Logs from the Common SQLite utility
D/SQLITE_CSU: logCursorColumns invoked. Cursor has the following 4 columns.

D/SQLITE_CSU: Column Name 1 is id

D/SQLITE_CSU: Column Name 2 is title

D/SQLITE_CSU: Column Name 3 is uid

D/SQLITE_CSU: Column Name 4 is address

D/SQLITE_CSU: logCursorData Cursor has 1 rows with 4 columns.

D/SQLITE_CSU: Information for row 1 offset=0
                For Column id Type is INTEGER value as String is 1 value as long is 1 value as double is 1.0

                For Column title Type is STRING value as String is BBC value as long is 0 value as double is 0.0

                For Column uid Type is STRING value as String is PajUFVIZvKbNWAHAgdJ9xpf6gi33 value as long is 0 value as double is 0.0

                For Column address Type is STRING value as String is http://feeds.bbci.co.uk/news/world/rss.xml value as long is 0 value as double is 0.0

Here is the logDatabaseInfo log "-
D/SQLITE_CSU: DatabaseList Row 1 Name=main File=/data/data/com.rss.feedster.rss_feedster/databases/rssFeeds
D/SQLITE_CSU: Database Version = 3
D/SQLITE_CSU: Table Name = android_metadata Created Using = CREATE TABLE android_metadata (locale TEXT)
D/SQLITE_CSU: Table = android_metadata ColumnName = locale ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table Name = feeds Created Using = CREATE TABLE feeds(id INTEGER PRIMARY KEY,title TEXT,uid TEXT,address TEXT)
D/SQLITE_CSU: Table = feeds ColumnName = id ColumnType = INTEGER Default Value = null PRIMARY KEY SEQUENCE = 1
D/SQLITE_CSU: Table = feeds ColumnName = title ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = feeds ColumnName = uid ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = feeds ColumnName = address ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table Name = user_info Created Using = CREATE TABLE user_info(id INTEGER PRIMARY KEY,uid TEXT,nickname TEXT,email TEXT,age TEXT,mobile TEXT,password TEXT,gender TEXT,photoURL TEXT)
D/SQLITE_CSU: Table = user_info ColumnName = id ColumnType = INTEGER Default Value = null PRIMARY KEY SEQUENCE = 1
D/SQLITE_CSU: Table = user_info ColumnName = uid ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = nickname ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = email ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = age ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = mobile ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = password ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = gender ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = user_info ColumnName = photoURL ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0

A: I believe that you are just looking in the wrong place, clicking the Browse Data Tab and then selecting the Messages table will show if there is any data.
The reasoning is that you are looking at the Database Structure, this shows you the tables and the SQL that will/was used to create them and additionally the columns and the SQL for the column definitions.
Having the table named android_metadata very likely shows that the database has come from and Android device rather than from another source i.e. you only find it on Android devices.
Your screenshot shows that there is a table called Messages, this isn't auto-generated nor is it created by SQLite. It has at least two columns according to the screenshot. One is named type and has a defined column-type of INTEGER along with a NOT NULL constraint the other column is named entry and has a column_type of BLOB.
Here's a similar DB that's been copied from an emulator showing how this (populated with 1 row) appears when you look at the Database Structure (Friends is the table and the columns have been expanded).

Note that the Browse Data table has been highlighted and has an arrow pointing to it. Clicking this will show something like :-

This is browsing the data for the android_metadata table (just 1 row with 1 column). To the right of the highlighted table there is a dropdown click this and select the Messages table. You data will be shown e.g (obviously this is for the Friends table):-

*

*The table has 1 row with 6 columns

*

*Column _id has a value of 1

*Column _name has a value of Test name

*and so on
Edit regards debugging information.
It is clear that the table you intend to copy/export from your emulator is not the database that you are looking at in DB Browser for SQLite. The database you have provided information for via the utilities provided is :-
/data/data/com.rss.feedster.rss_feedster/databases/rssFeeds
As such it is that file that you want to export copy and then open in DB Browser for SQLite.
It is not google_app_measurement_local.db
I think the issue is basically that you assumed that a database must have a .db file extension. The .db (file extension) does not affect the data it's used purely to indicate the type that the file may be.
I have little doubt that if you open the file indicated above then you will see that the data and structure are as you would expect. Note to see the file select All Files to the right of the File Name input.
As an example the following shows a file exported/copied as db1.rumplestiltskin and then opened in DB Browser for SQLite :-

The Fix
In the Device Monitor Export/Copy/Save the file /data/data/com.rss.feedster.rss_feedster/databases/rssFeeds and then open that in DB Browser for SQLite; noting that if it does not have a .db or .sqlite file extension then you will have to select All Files from the File Type selector to the right of the File Name input in order to be able to select the file from the file browser.
Perhaps have a read of Filename extension, which explains file extenstions in greater detail.


text:
Q: Error in SQL query in mapbasic I am writing below SQL query in mapbasic to insert columns from two tables t1 and t2 into table Sites but error is occuring "Variable or field t2.CELLID not defined"
Table Sites (Source integer, N integer, LAT float, LONG float)
Select t1.CELLID, t2.CELLID, t2.LATITUDE, t2.LONGITUDE from t1 left join t2 on t1.CELLID=t2.CELLID where t1.obj within zone into Sites
Can anyone tell me how to rectify it?

A: You can try this:
Table Sites (Source integer, N integer, LAT float, LONG float)
Select t1.CELLID "CellID1", t2.CELLID "CellID2", t2.LATITUDE, t2.LONGITUDE
  From t1, t2
  Where t1.CELLID = t2.CELLID
  And t1.obj within zone
  into __TO__INSERT
Insert Into Sites
   Select CellID1, CellID2, LATITUDE, LONGITUDE
   From __TO__INSERT

But notice that you will only insert the records where there is a match between the CellIDs in the two tables. As @Tom_Bacon mentioned, MapInfo SQL doesn't support outer joins.


text:
Q: How do I change content based on query string? I want to add some extra functionality to a WordPress (PHP) theme file.
I'm using a ref id, and adding this to the URL (as a query string). I would like the HTML to change depending on the string. Basic description:
if
/?ref=email1
echo 'This HTML'

or if
/?ref=email2
echo 'This other HTML'

or if neither
echo 'Default HTML'

The code I've come up with so far is below (however not working):
switch($_GET){
    case !empty($_GET['email1']):
        HTML here
    break;

    case !empty($_GET['email2']):
        This other HTML
    break;

    default:
        Default HTML
    break;
}

How can I fix my code?

A: You are doing it wrong way. $_GET is a array. You can't implement swicth this way. May be it would be like -
switch($_GET['ref']){
    case 'email1':
       HTML here
    break;

    case 'email2':
         This other HTML
    break;

    default:
         Default HTML
    break;

}

You can try this trick -
$contents = array(
  'email1' => 'HTML here',
  'email2' => 'This other HTML'
);

if(!empty($contents[$_GET['ref']])) {
    echo $contents[$_GET['ref']];
} else {
    Default HTML
}

A: You're getting the contents of email1 and email2, parameters that don't exist in $_GET. You need to use ref instead.
switch($_GET['ref']){
  case "email1":
    echo "HTML here";
    break;
  case "email2":
    echo "Other HTML here";
    break;
  default:
    echo "Default HTML here";
    break;
}


text:
Q: Digital signatures attached to the file I need to implement digital signatures to my web app. I followed this and this example, and have successfully signed and verified given file.
My questions are regarding the flow:

*

*I can export the signature, so what should I do with the signature? Save it in the database?

*If I attach signature to the file using BouncyCastle exported file is not readable. Should file with attached signature be readable?

*Is this the correct flow of digital signature: create the signature with user's certificate, store the signature, create endpoint for signature verification?

*If 3. is correct, does that mean if the file is sent outside an app, recipient wouldn't know if the file is signed? Should the signature be attached to the file? If yes, is there solution for all types of files (ie. I have found pdf based solutions).

Maybe the question is to broad, but I am open to any material regarding the subject.

A:
I can export the signature, so what should I do with the signature?

You have to distinguish between Private Key, Certificate and Signature.Private Key: User's private key, if created in cryptographic device, never comes out of the device.Certificate, in very brief, is a signed Public Key. Certifying Authority (CA) Signed it and Certificate is publicly available.Signature is Signed Content.  In fact, content to be signed is hashed and then this hash is signed, which is called Signature.

Is this the correct flow of digital signature: create the signature with user's certificate, store the signature, create endpoint for signature verification?

Private key is used to sign content (hash of content). The string produced is called Signature. Certificate (Public key) is used to verify signature.

is there solution for all types of files (ie. I have found pdf based solutions).

Any content can be signed.  Signing text files like CSV data, XML, Json, etc is used by web applications which accepts data from the users or members.  Example being eReturns, Signed Payment settlement data from banks, Tender Forms, etc.  PDF (and some other formats) supports signing and verifying signature and is format widely used to share document. Documents can display visible signature and hence pdf signatures are most discussed format of the Signatures.Otherwise, any application can define the signing requirement, users (client application or web browser) follow the required standard of signing and then the application can verify that signature is attached (along with data) as per pre-define format and standard.

I need to implement digital signatures to my web app.

Modern Browsers may need to use Browser Extensions to access Certificate stored on local machine. ex: Signer.Digital Browser Extension

A: A valid digital signature gives a recipient reason to believe that the message was created by a known sender (authentication), that the sender cannot deny having sent the message (non-repudiation), and that the message was not altered in transit (integrity)
More info : http://javaint4bytes.blogspot.com/2018/04/java-signature-certificates.html


text:
Q: Probability of paths to the boundary of a tree Let $G_n$ be the $4$-regular tree of depth $n$, that is to say the finite graph given by the ball of radius $n$ in the Cayley graph of the free group on two generators. By the root I mean the vertex at the center. If I choose vertices uniformly at random from $G_n$, what is the probability that when I choose the root it will be connected to the boundary of the graph by a path through vertices I have chosen already? Equivalently, if I take a random ordering of the vertices of $G_n$, what is the probability that the segment preceding the root will contain a path to the boundary? More precisely, I would like to know whether this probability approaches $0$ as $n$ goes to infinity.

A: It converges to a strictly positive limit.
Perhaps easiest to think about it in this way; assign every vertex an independent time which is uniform on $[0,1]$. If the vertices of $G_n$ are added in increasing order of their times, then this is equivalent to adding them one by one uniformly as you describe. But this way we can easily think about all the vertices in the infinite graph simultaneously.
Now condition on the time of the root. Given that this time is $p$, the set of vertices preceding the root contains each other vertex independently with probability $p$. Call this the set of open vertices. Effectively this is percolation with a random probability $p$ (itself chosen uniformly on $[0,1]$).
If we do percolation with probability $p$, then there exists an infinite open path starting from the root with positive probability iff $p>1/3$. This is almost the same as the probability of survival of a Galton-Watson branching process whose offspring distribution is Binomial($3,p$); the difference is that here the root has $4$ possible offspring, while each other vertex has only $3$. The probability (as a fuction of $p$) can be quite easily obtained as the solution of a recursive equation. To get the probability that the set of open vertices contains an infinite path from the root, integrate over $p$ from $1/3$ to $1$.
The limit as $n\to\infty$ of the probability that the set of open vertices contains a path from the root to distance $n$ is then just this probability that the set of open vertices contains an infinite path from the root.


text:
Q: USB retransmits SET_CONFIGURATION request I connected NanoPi Neo(Linux) as a USBProxy device between host(Windows) and printer. There is flow from the bootUp Wireshark flow
After that transmission stops. SET_CONFIGURATION config value is 1, printer responds with empty data. There is no single error response. Could someone say based on flow, is it correctly or not?
When printer and hosts are connected directly, communication works fine and printer is detected correctly. I also checked it with different hosts (Windows and Linux) and it also worked as expected.


text:
Q: Zend Db Where in I have the following table on MSSQL server:
Superheroes: id,name,real_name,power

And as Input I have the following array:
$heroes=["Superman","Batman","Wonder Woman"]

And I want to fetch their real names using Zend Framework 2.3.2.
Therefore on My model I have this function:
public function getHeroesRealNames(array $superHeroesNames)
{
  /**
  * @var Zend\Db\Adapter\AdapterInterface
  */
  $db=$this->db;
  $sql=new Sql($db);
  $qb=new Select('dbo.Superheroes');

  $qb->columns(['real_name'])->where('name IN (?)',$superHeroesNames);

  $query_string=$sql->getSqlStringForSqlObject($bq)
  var_dump($query_string);//Debug Output
}

But the var_dump for debugging purposes returns:

SELECT [dbo.Superheroes].[real_name] AS [real_name] FROM [dbo.Superheroes] WHERE name IN ('')"

Instead of the full query. How can I fix that? please keep in note that I DO NOT use var_dump in production.

A: I think you need to use the In Predicate as where method requires this but the method will also create the correct predicate for you if given the correct array or strings.
You can find the docs here .. https://framework.zend.com/apidoc/2.1/classes/Zend.Db.Sql.Predicate.In.html
You don't have to use the class directly, you can do ...
Basic example:
$select->from('Superheroes')->where(array(
    'name' =>$superHeroesNames,
));

You can find examples of this on the docs page too https://framework.zend.com/manual/2.2/en/modules/zend.db.sql.html#where-having
Please note the second argument of where method is the combination type, i.e AND or OR


text:
Q: View Flutter web on mobile I am building a flutter web app, but I want it to behave differently on mobile and desktop.
To test it, is it possible to run the web app on a phone's browser or in the browser of an emulator?
Thanks

A: The above answer is incorrect.  I test all my flutter web development in the mobile browser in the Simulator.  I use VS Code.  Your environment may be different.

*

*Run the project for Chrome (web).  This launches the local server and a Chrome Browser.  Copy the URL from the browser.  In my case, I have it to always be http://localhost:8686/#/

*Launch the Simulator.

*Launch Safari or any other browser on the Simulator.  Paste the URL in the browser.

You can even access the project from a real phone if it is on the same local network as your development machine.  Just replace localhost with the IP Address of your development machine.

A: *

*You need to start your flutter web-app on a specific port
flutter run -d web-server --web-port 5011

*Connect your device and verify if the device is connected properly
adb devices

*adb port-forwarding
adb reverse tcp:5011 tcp:5011
after that, you can able to access that port on a mobile broswer.

A: Yes, testing your code in a web browser while in production is possible. Here are steps to do that:

*

*Connect your devices (your laptop and phone) to the same internet

*Run the following code in the terminal of the opened project

t
flutter run -d web-server --web-port 8080 --web-hostname 0.0.0.0

Then, head to your mobile phone browser and type
HTTP://<your IP address>:8080

A: I working on a Macbook, and none of the answer from above help, but I found a pretty simple solution to test my webpage.

*

*The 1th you have to do is build your project with this command: flutter build web

*After that, get in the build/web folder and run this command: python3 -m http.server 8000
(For this you will need python 3.)

And that is, now you can see your webpage on both platform. On mobile you only your hosted platform's IP address. On mac, you can get with this command: ipconfig getifaddr en0
So, on your phone you can the webpage with this: your IP address:8000
Example.: 192.10.42.14:8000.
On your hosted platform it will be: 0.0.0.0:8000 (but this is only gonna work on your hosted platform)
I know, this is just a workaround, but for my situation it was very helpful.:)

A: No you cannot run a Flutter Web application in the mobile browser locally, if you want to test your application with a mobile format you can simulate it from a Google Chrome browser by enabling device toolbar from the developer tools Ctrl+Shift+M.


text:
Q: random forest variables importance with continuous and categorical variables and unbalanced output I am a bit lost in the literature regarding the random forest importance.
I am aware that there are different methods.
I have a binary output variables where elements labelled with 0 are much more than the ones labelled with 1.
5 variables are used as input. Some of them are continuous and some others are categorical.
Given a dataset of this type I am wondering what is the best method to asses variables importance with Random Forest and if this is available in any R or python library.
I know that the standard approach based the Gini impurity index is not suitable for this case due the presence of continuous and categorical input variables

A: Random forests for classification might use two kind of variable importance. See the original description of the RF here.

"I know that the standard approach based the Gini impurity index is not suitable for this case due the presence of continuos and categorical input variables"

This is plain wrong. The gini impurity is build using only the proportions of the target/dependent variable, when split by a test which involves either numerical or nominal independent variable. Note that the independent variable plays a role only for building the split test, the computation of gini index is based only on counts on dependent variable after split. Of course, the gini impurity index on each node is used further to compute gini importance.
I do not know if that would count, but my personal experiments revealed taht there are no big differences between gini variable importance and permutation value importance. And I usually prefered the former.
The second problem is the unbalance of the samples labeled with 1 and 0. I think this might play a role on variable importance, but to be honest I would verify if this is the case. Thus I would repeat many times various computations of variable importance with various sampels having different proportions varying gradually from 0.5 ratio to the actual ration. I expect that finding a stable variable importance no matter proportion to not be so unexpected.
[later edit]
It took me some time to compile the document provided by @Donbeo. I agree with the results from that paper and I hope that I would further experiment myself with that. The only think which I do not like about that study is that it does not state which number of trees were used and what would imply the variation of this parameter. The single note regarding that is that the number of trees affects the scaled version for permutation tests.

A: My current solution is a bootstrap on the samples such that the classes are balanced and the forest is trained using unbiased tree from the party package
sim = 100  #sim is the number of simulation. The larger the better and also the slower
s = 50 # s people with output 1 and s with output 0 are used in each iteration

    x1 = x[x$asthma3==1,]
        x0 = x[x$asthma3==0,]
    VI = data.frame(matrix(0, sim, ncol(x)-1))
    cont = cforest_unbiased(ntree=1000, mtry=2)

    for(i in 1:sim)
    {

      id1 = sample(x = nrow(x1), size = s, replace = F)
      z1 = x1[id1,]
      id0 = sample(x=nrow(x0), size = s, replace = F)
      z0 = x0[id0,]
      z = rbind(z0, z1)
      #reasign value to label
      cf = cforest(asthma3~., data=z, controls = cont)
      vi = varimp(object = cf)
      VI[i,] = as.numeric(vi)
    }

    names(VI) = names(x[,1:ncol(x)-1])
    b=boxplot(VI, outline=F)

A: In general, for deriving feature importance in datasets that include a mixture of categorical & continuous data I would consider alternative methods such as permutation_importance from sklearn (I'm sure there is an equivalent in R)
There are a number of interesting examples and discussions on the sklearn website such as this one here.


text:
Q: csrf token Follow up Hello and thank you in advance.  This is a follow up question from the following thread (not sure if I should have posted there or started a new thread...:
CSRF token missing or incorrect even though I have {% csrf_token %}
I am not sure what I need to do with the code to make csrfContext work.  I am trying to use ModelForm to collect data to a model and write it to a MYSQL table.  I am gettingthe error:
Reason given for failure:
    CSRF token missing or incorrect.
Here is the code:

    from django.shortcuts import render_to_response
    from djengo.template import RequestContext
    from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
    from acmetest.models import Player
    from acmetest.models import PickForm

    csrfContext = RequestContext(request)
    return render_to_response('makepick.html', csrfContext)

    def playerAdd(request, id=None):
        form = PickForm(request.POST or None,
                           instance=id and Player.objects.get(id=id))

        # Save new/edited pick
        if request.method == 'POST' and form.is_valid():
            form.save()
            return HttpResponseRedirect('/draft/')

        return render_to_response('makepick.html', {'form':form})

Again,
Thank you for your help!
dpbklyn

A: Update your code thusly:
from django.shortcuts import render
# from djengo.template import RequestContext <- this is not valid.

These two lines, as Yuji pointed out, are not valid python, and in addition they are not necessary if you use the render shortcut.
# csrfContext = RequestContext(request)
# return render_to_response('makepick.html', csrfContext)

Modify your return line:
 # return render_to_response('makepick.html', {'form':form})
   return render(request,'makepick.html',{'form':form})

A: I'm assuming we're talking about the playerAdd view - you need to pass RequestContext to the response there.
def playerAdd(request, id=None):
    form = PickForm(request.POST or None,
                       instance=id and Player.objects.get(id=id))
    # Save new/edited pick
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/draft/')

    return render_to_response('makepick.html', RequestContext(request, {'form':form}))

The first lines in your code are hard to understand and doesn't even appear to be valid python. You can't use return from outside a function block.


text:
Q: how do I update my old apps to iPhone 5?
Possible Duplicate:
How to develop or migrate apps for iPhone 5 screen resolution?

My apps use standard Apple controls. Some of them are really simple (UITableView nested in a UIView) and others are UITextView inside a UIScrollView inside a UIView
When I run the apps on my new iPhone 5, they are letterboxed. How do i update them to take advantage of the new iPhone 5 real estate?

A: First of all to remove the letter boxing, you let xcode know it should work on the iPhone 5 by adding an iPhone5 sized startup image which will be named Default-568h@2x.png
Straight away, your app will work without the letter box.
Then you need to move onto formatting your views to fit. From experience, every UITableView i've had has automatically resized to be longer, but most other views needed some tweaking of the Struts and Springs.


text:
Q: Android: Get recent location only, not getLastKnownLocation? I am developing an Android application in which current and precise location is key. After GPS fix is detected, it moves to the next activity.
The problem is that I tested it outdoors and found that sometimes it just uses a location from a previous fix.
So what I am asking; is there any other logic to get location from LocationManager other than  by getLastKnownLocation? I haven't yet found an example that wouldn't look something like
    Location location = locationManager.getLastKnownLocation(provider);

Thanx!

A: You can use LocationListener and then call locationManager.requestLocationUpdates() passing your own listener implementation.

A: Here's the sample code from the official guide (with little modifications):
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
         makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

In here, you just request updates from the GPS, and as soon as the location is received, you'll get a callback call.

A: Google has released new Location API, check this link out https://developer.android.com/training/location/index.html,
for you question, you need to implement location update callback to get current location.
https://developer.android.com/training/location/receive-location-updates.html


text:
Q: How to remove top space within a div tag I am placing a header text in a division. Fortunately i am getting unwanted space above that text. When i am trying to increasing the size of the text, the text is moving downwards. So here, I want to increase my text size and at the same time i want to move it upwards of division. Is it possible to remove the top space and move it upwards ?
I have tried padding-top: in negative pixels. But that didn't work.
HTML:
<div class="stylish">
    <h1> keep you stylish </h1>
</div>

CSS:
.stylish{
    font-family:"Brush Script MT", cursive;
    font-size:1.3em;
}

A: Your problem is not the div, it's the <h1> tag. Try this:
h1 {
    margin: 0px;
    padding: 0px;
}

Your can also try:
h1 {
    margin: 0;
    padding: 0;
}

A: I recommend a css reset in the inception of every css:
/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

Source

A: h1
{
    margin-top: 0px;
    padding-top: 0px;
}

or you may try this too
h1
{
    margin: 0px 0px 0px 0px;//top left bottom right
    padding: 0px 0px 0px 0px;
}

and .stylish must have padding:0px;  i.e;
.stylish
{
padding:0px;
}

Reason:
By default each tag like <H1>,<P>... Comes with minimum margin and padding So in order to reduce that gaps we need to give margin=0px;padding =0px externally
More about margin and padding refer
http://www.htmldog.com/guides/css/beginner/margins/
http://webdesign.about.com/od/faqsandhelp/f/bl_faq5_7a.htm
http://html.net/tutorials/css/lesson10.php

A: Try this
.stylish
{
    margin: 0px;
    padding: 0px;
}

you may require to set margin and padding to zero for its parent element too, if it doesn't work
But for u the white space is the margin of div's parent..
so set the parents margin to 0px;


text:
Q: Change the Icon in Phonegap Hi there I'm really having troubles changing the Icon in my Phonegap-App (Cordova 2.5.0)
I put my icons into the folder Projectname/Ressources/Icons.
Then I removed the icons there
But where in the Project do I change the name of the Icon.
I'm getting an error, that the icon-72.png isn't found - but I have no idea where to change the name of the icon from icon-72.png to myicon.png

A: First, you need to remove old icon references. To do that :
In your Xcode project settings to go Build Phases and find in Copy Bundle Resources these old icon references. Delete them. Then, in your nav bar, go to Product>Clean.
Now build your project. It should work.


text:
Q: jquery - How to resolve two jquery conflict I have a page which includes two jquerys one  for slider other for populate dropdawn.The problem is when I put both of them my jqueries are not working together.What should i do?
My index:
   <!-- JAVASCRIPTs for slider -->
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/comment-reply.js"></script>
    <script type="text/javascript" src="js/jquery.quicksand.js"></script>
    <script type="text/javascript" src="js/jquery.tipsy.js"></script>
    <script type="text/javascript" src="js/jquery.prettyPhoto.js"></script>
    <script type="text/javascript" src="js/jquery.cycle.min.js"></script>
    <script type="text/javascript" src="js/jquery.anythingslider.js"></script>
    <script type="text/javascript" src="js/jquery.eislideshow.js"></script>
    <script type="text/javascript" src="js/jquery.easing.js"></script>
    <script type="text/javascript" src="js/jquery.flexslider-min.js"></script>
    <script type="text/javascript" src="js/jquery.aw-showcase.js"></script>
    <script type="text/javascript" src="js/layerslider.kreaturamedia.jquery-min.js"></script>
    <script type="text/javascript" src="js/shortcodes.js"></script>
    <script type="text/javascript" src="js/jquery.colorbox-min.js"></script>
    <script type="text/javascript" src="js/jquery.tweetable.js"></script>
    <script type="text/javascript" src="js/slider-layer.js"></script>

    <!-- JAVASCRIPTs for dropdawn -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){

$(document).on('change','.productcategory',function(){
   console.log("hmm its change");

  var cat_id=$(this).val();

  var div=$('#d').parent();

  var op=" ";

  $.ajax({
    type:'get',
    url:'{!!URL::to('findProductName')!!}',
    data:{'id':cat_id},
    success:function(data){
      //console.log('success');

      //console.log(data);

      console.log(data.length);

      op+='<option value="0" selected disabled></option>';

      for(var i=0;i<data.length;i++){

           op+='<option value="'+data[i].id+'">'+data[i].model+'</option>';

     console.log(data[i].model);
       }

       div.find('.productname').html(" ");
       div.find('.productname').append(op);
    },
    error:function(){

    }
  });
});

  });
  </script>

I try to add
<script type="text/javascript">
   var jQuery = $.noConflict(true);
</script>

but when add this in the end of bouth script then slider work and dropdown not, and when not add this code for conflict works dropdown and slider doesn't work.
I use next links:
Can I use multiple versions of jQuery on the same page?
http://jsfiddle.net/PGLVs/
Any ideas of what I'm doing wrong?

A: a quick example:
in the head:
<script type="text/javascript" src="/jqueryV1.js"></script>
<script type="text/javascript">
    var $myJQ = jQuery.noConflict();
</script>
<script type="text/javascript" src="/jqueryV2.js"></script>
<!-- the version 2 in now in $ while the 1 is in $myJQ -->

code that uses version 2 can keep the global $.
Now in the rest of your code, you could simply replace all the $ by $myJQ where the version 1 is used, but it means rewriting all, what you can do instead is to use an argument that acts as a local var, to be able to keep $ in the code that uses version 1:
(function($){
    //inside this function, using $ means using the global $myJQ
    $('#selector')...
})($myJQ);

A: Basically you should release release $ or jQuery variable for newer versions     so add noConflict between both versions as below. This will make $ alias available for newer version.
<script src"olderversion"></script>

<script type="text/javascript">
     jQuery.noConflict();
</script>

<script src"newerversion"></script>

If in case you have to call any plugin with lot of lines using $ or jQuery using old versions you can folow below approach.
jQuery.noConflict();
(function( $ ) {// if you want to use $
  $(function() {
    // More code using $ as alias to jQuery
  });
})(jQuery);

// Other code using $ as an alias to the other library

jQuery.noConflict();
    (function( jQuery ) {// if you want to use $
      $(function() {
        // More code using jQuery  as alias to jQuery
      });
    })(jQuery);

Please mark it as answer if it meets your requirement.


text: Q: localhost won't open from WampSever menu Can't open localhost from WampSever menu, the error is "could not execute run action, the directory name is invalid", but when I type "localhost" directly in address bar in browser, it works fine. For phpMyAdmin as well. The icon in the taskbar is green, everything else works just fine. Any idea what could the problem?


text:
Q: Plotting factorial of x function in gnuplot? I'm trying to plot the x! function in gnuplot, I defined first the factorial function and then called it, but I'm always getting stack overflow, no matter what bounds I set to the graph.
This what I've tried:
gnuplot>  fac(n) = (n==0) ? 1 : n * fac(n-1)
gnuplot> plot [0:10][0:10] log(fac(x)), log(x**x)
stack overflow

A: I should define the fac function to be integer. Otherwise, when plotting all along the x-axis, it'll evaluate a long range of real numbers, a huge one actually, which will always cause the overflow.
So, the function should be defined:
fac(x) = (int(x)==0) ? 1.0 : int(x) * fac(int(x)-1.0)

A: Another soultion would be to use the Gamma function (intrinsic function in gnuplot).

N!=gamma(N+1)

gnuplot> plot [0:10][0:10] log(gamma(x+1)), log(x**x)


text:
Q: LPSolve C++ source library and IDE gives different LP task solution results I have LP task. The problem has appeared suddenly. I use automated code for create the objective function, equations and constrains, from two vectors of nodes and lines, also I use the method for create code of my tas in LPSolve format and write it in file.
For example:
/* Objective function */
max:  +y4 +y5 +y6;

/* Constraints */
n1: +x4 -y4 -z4_5_4 -z4_6_5 +z5_4_8 +z6_4_9 = 0;
n2: +x5 -y5 +z4_5_4 -z5_6_6 +z6_5_7 -z5_4_8 +z6_5_10 -z5_6_11 = 0;
n3: +x6 -y6 +z4_6_5 +z5_6_6 -z6_5_7 -z6_4_9 -z6_5_10 +z5_6_11 = 0;

/* Variable bounds */
x4 <= 16210;
x5 <= 16600;
x6 <= 17950;
y4 <= 15000;
y5 <= 15000;
y6 <= 15000;
z4_5_4 <= 2000;
z4_6_5 <= 2000;
z5_6_6 <= 1000;
z6_5_7 <= 1000;
z5_4_8 <= 2000;
z6_4_9 <= 2000;
z6_5_10 <= 1000;
z5_6_11 <= 1000;

After creating and writing equations in file I execute the solver:
int result = solve(lp);

Usualy for tasks with random values, I've got results like this:
Var-s    Result
         45000
x4       15000
x5       15000
x6       15000
y4       15000
y5       15000
y6       15000
z4_5_4   0
z4_6_5   0
z5_4_8   0
z5_6_11  0
z5_6_6   0
z6_4_9   0
z6_5_10  0
z6_5_7   0

But in the LPSolve IDE I've got results like this (and I think it's rigth results):
Var-s    Result
         45000
x4       16210
x5       16600
x6       12190
y4       15000
y5       15000
y6       15000
z4_5_4   400
z4_6_5   810
z5_4_8   0
z5_6_11  1000
z5_6_6   1000
z6_4_9   0
z6_5_10  0
z6_5_7   0

On some forum I read that's better to use "1E-5" instead "0" and "1000" instead "1.0" as coefficients in my objective function. I tried to do this  and i've got the same results in solver IDE and in my programm but the results was not changed for randome values in the task.

So, I need to get results like in LPSolve IDE (wroten in the end) but use my programm. If it's possible, please help me.

Used versions LPSolve v-5.5.2.3, v-5.5.2.0

A: So, I had conversation with some guy, which used LPSolve many time and knows some pitfalls. In my question I have equations and constraints, if we replace x,y,z unknown values to the resulting solution, the equations will satisfied.
/* Constraints */
n1: +x4 -y4 -z4_5_4 -z4_6_5 +z5_4_8 +z6_4_9 = 0;
n2: +x5 -y5 +z4_5_4 -z5_6_6 +z6_5_7 -z5_4_8 +z6_5_10 -z5_6_11 = 0;
n3: +x6 -y6 +z4_6_5 +z5_6_6 -z6_5_7 -z6_4_9 -z6_5_10 +z5_6_11 = 0;

/* satisfied equations */
n1: +15000 -15000 -0 -0 +0 +0 = 0;
n2: +15000 -15000 +0 -0 +0 -0 +0 -0 = 0;
n3: +15000 -15000 +0 +0 -0 -0 -0 +0 = 0;

LPSolve will find the optimal solution and will write several different solutions in IDE, programm etc.
In this situation when Y is load, X is generation, Z is flows and when less load generation, we needn't flows to balancing system and in programm I have solution like in example, but In IDE have right solution too.
So, before you will think that solver write wrong solution you need to check the model, objective function, equations and constrains, and try to replace result values with constrains to get satisfied equations or try to solve the dual problem.
Next time I try to find special constrians in objective function. May be it can help somebody.


text:
Q: Get text at top of screen during scroll? I'm looking for a way for javascript to tell how far a user has scrolled down the screen.
Instead of doing this through x, y coordinates is there a way to pull what's at the top of the viewport?
Either the text / line number or the current top element in the viewport?

A: Have a look at jQuerys scrollTop()
This should probably do it for you:
$("body").scrollTop()

A: No, you can't.
You have to set scroll events and update x and y values.
Then, with those values, you can get the element at this position.
https://developer.mozilla.org/en/DOM/document.elementFromPoint
http://msdn.microsoft.com/en-us/library/ms536417%28VS.85%29.aspx


text:
Q: Stopping / Killing a debug thread in IntelliJ I like to stop the execution of a debug thread that I run in IntelliJ Ultimate 2019.3.
I can stop the entire JVM process, but that will require to restart the web application that takes a lot of time to spin up.
I found this request for such a feature (back from 2015), but I see no new way to do it.

A: Following y.bedrov comment, the solution was indeed to get to the "Throw Exception" wizard and then to enter there
new RuntimeException("error")


text:
Q: Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable I want to import the sample project from the github. I have downloaded the whole package into zip , extracted the zip , and there are several folders in it. The one I want to import is sample app .
Now when Ever I tried to import it I get the following error

Error:(1, 0) SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

I have searched many link on stackoverflow. But got nothing. Please help me.