text:
Q: How to detect when subprocess asks for input in Windows I have a subprocess that either quits with a returncode, or asks something and waits for user input.
I would like to detect when the process asks the question and quit immediately. The fact that the process asks the question or not is enough for me to decide the state of the system.
The problem is that I cannot read the question because the child process probably does not flush standard output. So I cannot rely on parsing subprocess.Popen().stdout: when trying to read it, well, it blocks because input is being read first.
A bit like this
# ask.py, just asks something without printing anything if a condition is met
# here, we'll say that the condition is always met
input()

Of course, the actual subprocess is a third party binary, and I cannot modify it easily to add the necessary flush calls, which would solve it.
I could also try the Windows equivalent of unbuffer (What is the equivalent of unbuffer program on Windows?) which is called winpty, which would (maybe) allow me to detect output and solve my current issue, but I'd like to keep it simple and I'd like to solve the standard input issue first...
I tried... well, lots of things that don't work, including trying to pass a fake file as stdin argument, which doesn't work because subprocess takes the fileno of the file, and we cannot feed it rubbish...
p = subprocess.Popen(["python","ask.py"],...)

Using communicate with a string doesn't work either, because you cannot control when the string is read to be fed to the subprocess (probably through a system pipe).
Those questions were promising but either relied on standard output, or only apply to Linux

*

*Detecting when a child process is waiting for input

*How can I know whether my subprocess is waiting for my input ?(in python3)
What I'm currently doing is running the process with a timeout, and if the timeout is reached, I then decide that the program is blocked. But it costs the timeout waiting time. If I could decide as soon as stdin is read by the subprocess, that would be better.
I'd like to know if there's a native python solution (possibly using ctypes and windows extensions) to detect read from stdin. But a native solution that doesn't use Python but a non-Microsoft proprietary language could do.

A: if we not want let to child process process user input, but simply kill it in this case, solution can be next:

*

*start child process with redirected stdin to pipe.

*pipe server end we create in asynchronous mode and main set pipe
buffer to 0 size

*before start child - write 1 byte to this pipe.

*because pipe buffer is 0 size - operation not complete, until another
side not read this byte

*after we write this 1 byte and operation in progress (pending) -
start child process.

*finally begin wait what complete first: write operation or child process ?

*if write complete first - this mean, that child process begin read
from stdin  - so kill it at this point

one possible implementation on c++:
struct ReadWriteContext : public OVERLAPPED
{
    enum OpType : char { e_write, e_read } _op;
    BOOLEAN _bCompleted;

    ReadWriteContext(OpType op) : _op(op), _bCompleted(false)
    {
    }
};

VOID WINAPI OnReadWrite(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, OVERLAPPED* lpOverlapped)
{
    static_cast<ReadWriteContext*>(lpOverlapped)->_bCompleted = TRUE;
    DbgPrint("%u:%x %p\n", static_cast<ReadWriteContext*>(lpOverlapped)->_op, dwErrorCode, dwNumberOfBytesTransfered);
}

void nul(PCWSTR lpApplicationName)
{
    ReadWriteContext wc(ReadWriteContext::e_write), rc(ReadWriteContext::e_read);

    static const WCHAR pipename[] = L"\\\\?\\pipe\\{221B9EC9-85E6-4b64-9B70-249026EFAEAF}";

    if (HANDLE hPipe = CreateNamedPipeW(pipename, PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
        PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, 1, 0, 0, 0, 0))
    {
        static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };
        PROCESS_INFORMATION pi;
        STARTUPINFOW si = { sizeof(si)};
        si.dwFlags = STARTF_USESTDHANDLES;
        si.hStdInput = CreateFileW(pipename, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);

        if (INVALID_HANDLE_VALUE != si.hStdInput)
        {
            char buf[256];

            if (WriteFileEx(hPipe, "\n", 1, &wc, OnReadWrite))
            {
                si.hStdError = si.hStdOutput = si.hStdInput;

                if (CreateProcessW(lpApplicationName, 0, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &si, &pi))
                {
                    CloseHandle(pi.hThread);

                    BOOLEAN bQuit = true;

                    goto __read;
                    do
                    {
                        bQuit = true;

                        switch (WaitForSingleObjectEx(pi.hProcess, INFINITE, TRUE))
                        {
                        case WAIT_OBJECT_0:
                            DbgPrint("child terminated\n");
                            break;
                        case WAIT_IO_COMPLETION:
                            if (wc._bCompleted)
                            {
                                DbgPrint("child read from hStdInput!\n");
                                TerminateProcess(pi.hProcess, 0);
                            }
                            else if (rc._bCompleted)
                            {
__read:
                                rc._bCompleted = false;
                                if (ReadFileEx(hPipe, buf, sizeof(buf), &rc, OnReadWrite))
                                {
                                    bQuit = false;
                                }
                            }
                            break;
                        default:
                            __debugbreak();
                        }
                    } while (!bQuit);

                    CloseHandle(pi.hProcess);
                }
            }

            CloseHandle(si.hStdInput);

            // let execute pending apc
            SleepEx(0, TRUE);
        }

        CloseHandle(hPipe);
    }
}

another variant of code - use event completion, instead apc. however this not affect final result. this variant of code give absolute the same result as first:
void nul(PCWSTR lpApplicationName)
{
    OVERLAPPED ovw = {}, ovr = {};

    if (ovr.hEvent = CreateEvent(0, 0, 0, 0))
    {
        if (ovw.hEvent = CreateEvent(0, 0, 0, 0))
        {
            static const WCHAR pipename[] = L"\\\\?\\pipe\\{221B9EC9-85E6-4b64-9B70-249026EFAEAF}";

            if (HANDLE hPipe = CreateNamedPipeW(pipename, PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
                PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, 1, 0, 0, 0, 0))
            {
                static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };
                PROCESS_INFORMATION pi;
                STARTUPINFOW si = { sizeof(si)};
                si.dwFlags = STARTF_USESTDHANDLES;
                si.hStdInput = CreateFileW(pipename, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);

                if (INVALID_HANDLE_VALUE != si.hStdInput)
                {
                    char buf[256];

                    if (!WriteFile(hPipe, "\n", 1, 0, &ovw) && GetLastError() == ERROR_IO_PENDING)
                    {
                        si.hStdError = si.hStdOutput = si.hStdInput;

                        if (CreateProcessW(lpApplicationName, 0, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &si, &pi))
                        {
                            CloseHandle(pi.hThread);

                            BOOLEAN bQuit = true;

                            HANDLE h[] = { ovr.hEvent, ovw.hEvent, pi.hProcess };

                            goto __read;
                            do
                            {
                                bQuit = true;

                                switch (WaitForMultipleObjects(3, h, false, INFINITE))
                                {
                                case WAIT_OBJECT_0 + 0://read completed
__read:
                                    if (ReadFile(hPipe, buf, sizeof(buf), 0, &ovr) || GetLastError() == ERROR_IO_PENDING)
                                    {
                                        bQuit = false;
                                    }
                                    break;
                                case WAIT_OBJECT_0 + 1://write completed
                                    DbgPrint("child read from hStdInput!\n");
                                    TerminateProcess(pi.hProcess, 0);
                                    break;
                                case WAIT_OBJECT_0 + 2://process terminated
                                    DbgPrint("child terminated\n");
                                    break;
                                default:
                                    __debugbreak();
                                }
                            } while (!bQuit);

                            CloseHandle(pi.hProcess);
                        }
                    }

                    CloseHandle(si.hStdInput);
                }

                CloseHandle(hPipe);
                // all pending operation completed here.
            }

            CloseHandle(ovw.hEvent);
        }

        CloseHandle(ovr.hEvent);
    }
}

A: My idea to find out if the subprocess reads user input is to (ab)use the fact that file objects are stateful: if the process reads data from its stdin, we should be able to detect a change in the stdin's state.
The procedure is as follows:

*

*Create a temporary file that'll be used as the subprocess's stdin

*Write some data to the file

*Start the process

*Wait a little while for the process to read the data (or not), then use the tell() method to find out if anything has been read from the file

This is the code:
import os
import time
import tempfile
import subprocess

# create a file that we can use as the stdin for the subprocess
with tempfile.TemporaryFile() as proc_stdin:
    # write some data to the file for the subprocess to read
    proc_stdin.write(b'whatever\r\n')
    proc_stdin.seek(0)

    # start the thing
    cmd = ["python","ask.py"]
    proc = subprocess.Popen(cmd, stdin=proc_stdin, stdout=subprocess.PIPE)

    # wait for it to start up and do its thing
    time.sleep(1)

    # now check if the subprocess read any data from the file
    if proc_stdin.tell() == 0:
        print("it didn't take input")
    else:
        print("it took input")

Ideally the temporary file could be replaced by some kind of pipe or something that doesn't write any data to disk, but unfortunately I couldn't find a way to make it work without a real on-disk file.


text:
Q: Developing an app for ios i'm supposed to support fast or slow connection? Strange question i know. I'm developing an app for ios for a target being the visitors of a commercial centre. The app provide an internal updating system, using an xml system, that for a long list of reasons works differently in the case of slow or fast response of the net. The difference stands in different type of malfunctioning of the ui, and i only can choose to have a better performance in the case the user have a slow connection OR a fast one, for the two solution (one for the problem on the fast case, one for the slow case) for the issue i have, involve one the presence of malfunctioning in the other case.
In this case, i'm supposed to favor users who belong a fast or slow connection and why?
Edit: I'll try to explain the problem. I have a view that need to be updated via xml. When i launch the view, the simple fact i try to access the xml to control if the update needs to be done, takes time. I added an activity indicator, but it doesn't work fine for, as the net gets slower, it seems to take more time to the activity indicator to show, with the result the user have to time to think the app is frozen, try to touch button he has not to touch (that will not work and make him think the app doesn't work) and so on. So i used performSelectorInBackground in order to add the activity indicator as fast i can and it works fine in the SLOW connection case. In the FAST connection case, the activity appear so fast that it appears even if the control if the update must be done, due to the speed of the connection, takes near no time, causing it to show the activity indicator for a picosecond, giving an awful graphical effect that is to be avoided. To avoid the problem in the FAST case i added a
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.000001 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{ code to add the activity indicator; });

and, in this way, i do not have the graphical problem of the FAST case, but in the SLOW case the execution of the dispatch_after (i guess) slow down the showing of the activity indicator too much causing the impression that the app freezed. So my hands are tied and i don't know what it's to prefer.

A: You can determine what type of connection user has (Edge/3G or Wi-Fi) and perform different methods for each type of connection. Sample code here. Usually wi-fi is faster and cheaper, so you can provide your "fast code" for it.
P.S. I am still not sure what are you talking about. Perfomance? Difficult to give proper advice without some details, but still:
1) You can download needed stuff in background.
2) If it's about menus with images/videos/music - start with downloading list with titles, after that download media files. (like android market does on slow connections).
EDIT:
First of all, don't mix views and network tasks. All downloading should be done outside of the ViewController, in another thread.
You can download new XML each N minutes (or use if-modified in your request) and show it next time user tries to see the view. How often do you get new XMLs? It's important, maybe you can avoid downloading it at the same moment with UI drawining. Good luck!

A: As the target is visitors of a commercial centre, you should always work with fast connection to give a better user experience .. user does not like to wait long time with a loading screen on the device .. but you should also tackle the negative scenario, i.e, slow connection. You need to determine an optimized time depending on requirement so that you need to show the loading screen for that particular time only and still, if the connection is slow, you can terminate the connection with a 'Try Again' message .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double com precisão de no máximo 40 dígitos Estou a precisar que meu programa retorne um valor alto de dígitos, na casa de no máximo 40 dígitos.
Vi que o tipo DOUBLE tem uma abrangência que vai de 1.7 X 10^-308 até 1.7X10^308, por isso devo pensar que ele atende, até demais, minhas necessidades.
Mas quando esse simples programa é iniciado:
int main()
{
  double p = 1234567890123456789012345678901234567890.0;

  printf("%.0lf", p);

  return 0;
}

Ver também no Ideone
O retorno obtido será: 1234567890123456780000000000000000
Como contornar o problema em questão?

A: Não é possível obter esta precisão com double.
Números em notação de ponto fluante como o double são excelentes para representar números muito pequenos ou números muito grandes, mas não uma mistura dos dois. Para números muito grandes, os valores de ordem de magnitude menores influenciam muito pouco no resultado das operações, sendo descartados sem grandes perdas.
Se quiser saber mais, veja sobre o padrão IEEE 754, que é o padrão que os processadores x86 implementam (acredito que ARM utiliza o mesmo padrão).
Para precisões arbitrárias é necessário utilizar uma biblioteca como a GMP (GNU Multi-Precision Library). Ela é capaz de manipular números tão grandes quanto sua memória, sejam estes números inteiros, fracionários ou de ponto flutuante.
O site da lib:
The GNU Multiple Precision Arithmetic Library
Ela suporta as principais plataformas (Windows, Mac, Linux, FreeBSD).


text:
Q: personal folder in outlook stored on network share available on iphone? I am looking to swap out a BlackBerry for an iPhone from Verizon. On the BlackBerry we use an older version of the desktop synchronization software and I can access personal folders (Outlook 2007 and Exchange Server 2007) stored on a network share. Can you do that from an iPhone?

A: It appears that this works while using a VPN. The iPhone talks to the Exchange group policies, and can use all the mail folders (although, IMAP may be necessary for this). For more info, see this Apple doc (page 9).


text:
Q: MongoDB Reduce Key with single value I want to count the number of orders by clients, and thus, on the last year, last month and last week.
I wrote a MapReduce program:
var mapOrders = function() {
    var v_order = {
        order_date : this.dt_order
        ...
    };

     emit(this.clientid, v_order);
};

var reduceOrders = function(p_clientid, p_orders) {
    // Initialization of the output format of the couters
    var r_result = { orders_count : {
        total: {
            1year: 0,
            1month: 0,
            7day: 0
        }
        ...
    }}

    for (var c_order = 0; c_order < p_orders.length; c_order++) {
        // Increment counters
    }

    return (r_result);
};

db.orders.mapReduce(
    mapOrders,
    reduceOrders,
    {
        out: { merge:  "tmp_orders_indicators" }
    }
)

In my output collection, I have 2 types of records
{
    "_id" : 80320,
    "value" : {
        "order_date" : ISODate("2015-10-30T11:09:51.000Z")
        ...
    }
}

{
    "_id" : 80306,
    "value" : {
        "orders_count" : {
            "total" : {
                "count_1year" : 18,
                "count_1month" : 6,
                "count_7day" : 1
            }
            ...
        }
}

The clients with only 1 order don't go through the reduce function.
I found this in the MongoDB doucmentation that explain that behaviour:

MongoDB will not call the reduce function for a key that has only a
  single value.

How can i do to have only 1 type of record in my output collection looking like this? Force all the record to go throught the reduce function?
{
    "_id" : 80306,
    "value" : {
        "orders_count" : {
            "total" : {
                "count_1year" : 18,
                "count_1month" : 6,
                "count_7day" : 1
            }
            ...
        }
}

A: You can achieve this seamlessly with aggregation. Consider the following pipeline:
var dateSevenDaysAgo = new Date();
dateSevenDaysAgo.setDate(dateSevenDaysAgo.getDate()-7);

var dateMonthAgo = new Date();
dateMonthAgo.setMonth(dateMonthAgo.getMonth()-1);

var dateYearAgo = new Date();
dateYearAgo.setFullYear(dateYearAgo.getFullYear()-1);

var pipeline = [
    { "$match": { "$dt_order": { "$gte": dateYearAgo } } },
    {
        "$group": {
            "_id": "$id_client",
            "count_1year": {
                "$sum": {
                    "$cond": [
                        { "$gte": [ "$dt_order", dateYearAgo ] },
                        1, 0
                    ]
                }
            },
            "count_1month": {
                "$sum": {
                    "$cond": [
                        { "$gte": [ "$dt_order", dateMonthAgo ] },
                        1, 0
                    ]
                }
            },
            "count_7day": {
                "$sum": {
                    "$cond": [
                        { "$gte": [ "$dt_order", dateSevenDaysAgo ] },
                        1, 0
                    ]
                }
            }
        }
    },
    { "$out": "tmp_indicators" }
];

db.orders.aggregate(pipeline);
db.tmp_indicators.find();

A: Found a solution using the finalize utility.
var mapOrders = function() {
    var v_order = {
        order_date : this.dt_order
        ...
    };

     emit(this.clientid, v_order);
};

var reduceOrders = function(p_clientid, p_orders) {
    // Initialization of the output format of the couters
    var r_result = { orders_count : {
        total: {
            1year: 0,
            1month: 0,
            7day: 0
        }
        ...
    }}

    for (var c_order = 0; c_order < p_orders.length; c_order++) {
        // Increment counters
    }

    return (r_result);
};

var finalizeOrders = function(p_clientid, p_ReducedDrders) {

    if (typeof p_ReducedDrders.orders_count === 'undefined' )
        // Initialization of the output format of the couters
        var r_result = { orders_count : {
            total: {
                1year: 0,
                1month: 0,
                7day: 0
            }
        ...
        }}

        // do the same stuff as the for loop in the reducer
    }
    else {
        r_result = p_ReducedDrders
    }

    return (r_result);
};

db.orders.mapReduce(
    mapOrders,
    reduceOrders,
    {
        out: { merge:  "tmp_orders_indicators" },
        finalize : finalizeOrders
    }
)


text:
Q: how to import csv file with current date store in database using php I am import csv file in mysql database without the date format.but i have to insert current data and time in separate column.how can I implement the code to store the date and time.
php code:

       include_once("includes/dbConnection.php");
       session_start();
         if(!isset($_SESSION['u_id']))
              {
             header("Location:membership_import_csvpage.php");
                }
               //$deleterecords = "TRUNCATE TABLE contacts";
            //empty the   table of its current records
          //mysql_query($deleterecords);

       if ($_FILES[csv][size] > 0) {

          $file = $_FILES[csv][tmp_name];
          $handle = fopen($file,"r");
         $date = date('Y-m-d');
           do {
             if ($data[0]) {
          mysql_query("INSERT INTO membership (mbid, name,identification_number,date,user_id) VALUES
            (
                '".addslashes($data[0])."',
                '".addslashes($data[1])."',
                '".addslashes($data[2])."',
                  '".addslashes($data  ['CURDATE()'])."',
                 '".addslashes($_SESSION['u_id'])."'
            ) ");
             }
        }                while ($data = fgetcsv($handle,1000,",","'"));
             //

              //redirect
           echo ("");

       die;

     }
     ?>

A: apply the default value constraint to that  column which is storing the date and time .  set the column to Not null and set it default= current_timestamp . it will auto fill the column with current date and time . and dont give the date and time from query i.e manually . it will auto fill that column
 +-------+-------------+------+-----+-------------------+-------+
 | Field | Type        | Null | Key | Default           | Extra |
 +-------+-------------+------+-----+-------------------+-------+
 | str   | varchar(32) | YES  |     | NULL              |       |
 | date  | timestamp   | NO   |     | CURRENT_TIMESTAMP |       |
 +-------+-------------+------+-----+-------------------+-------+

A: Try This its for csv files
<?php
    $connect = mysqli_connect("localhost", "root", "", "testing");
    if(isset($_POST["submit"]))
{
    if($_FILES['file']['name'])
    {
        $filename = explode(".", $_FILES['file']['name']);
        if($filename[1] == 'csv')
        {
            $handle = fopen($_FILES['file']['tmp_name'], "r");
            while($data = fgetcsv($handle))
            {
                $item1 = mysqli_real_escape_string($connect, $data[0]);
                $item2 = mysqli_real_escape_string($connect, $data[1]);
                $query = "INSERT into excel(excel_name, excel_phone) values('$item1','$item2')";
                mysqli_query($connect, $query);
            }
            fclose($handle);
            echo "";
        }
    }
}
?>
<!DOCTYPE html>

    <title></title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

    <form method="post" enctype="multipart/form-data">

            Select CSV File:
            <input type="file" name="file" />

            <input type="submit" name="submit" value="Import" class="btn btn-info" />

    </form>

            Id
            Name
            Phone_No
            <?php
            $conn = mysqli_connect("localhost", "root", "", "testing");
            // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $sql = "SELECT excel_id, excel_name, excel_phone FROM excel";
                $result = $conn->query($sql);
                if ($result->num_rows > 0) {
                    // output data of each row
                    while($row = $result->fetch_assoc()) {
                        echo "
" . $row["excel_id"]. "	" . $row["excel_name"] . "	"
                        . $row["excel_phone"]. "
";
                    }
                    echo "
";
                } else { echo ""; }
                $conn->close();
            ?>


text:
Q: spark streaming reducebywindow i have a batch size = 20 seconds , in each rdd i have scores i need to sum all scores  every 20 seconds so i did this :
JavaDStream<Double> res = scoreC.map(r -> r._2);
res.reduceByWindow((x,y) -> x+y,Durations.seconds(600),Durations.seconds(20)).print()

the result is empty
how can i get the sum of scores every 20 seconds including previous sum for, example :
t-1 = 0
t = 0
t+20 = 0 + 0 + 1.5
t+40 = 0 + 0 + 1.5 + 2
t+60 = 0 + 0 + 1.5 + 2 + ....
...
t+600 = sum(all) from t=0 to t=600


text:
Q: Splitting lines by multiple polygons, taking length of particular segment, using PostGIS I have a table of 100k+ non-overlapping POLYGON features, and a table of 50k+ simple LINESTRING features (each line has only 2 vertices). The below is a common arrangement of these features on a map, showing 1 line (red, going left to right) and 4 individual polygons (blue):

Imagine the above scenario, but in thousands of different locations. The lines and polygons do vary in length/size across the map (the above is just a simplified example).
I can split the line features by the polygon features by using ST_INTERSECTION(lines, polygons), so that the above example would have the line split into 4 segments.
After successfully splitting the line into 4, I want to obtain the length of only the second segment (this is the important measurement for my particular project).
I can ST_LENGTH the result of question 1, but how can I extract only the second measurement?
This is especially tricky as the ST_INTERSECTION does't output the line segments in order (left to right here).
Perhaps I could somehow add a column containing an identifier for each segment, with 'a' being the first, 'b' being the second (and the one I want to measure!), then 'c', 'd' and so on... Then: SELECT ST_LENGTH FROM line_segments WHERE label = 'b'. But I need to get the segments in order somehow first...
If you want to test, here's the geometries for the example above.
Polygons (the ids are random in the real dataset):
SELECT 'ogb1' as id, ST_GeomFromText('POLYGON((2 2, 2 4, 4 4, 4 2, 2 2))') as geom
UNION
SELECT 'ogb2' as id, ST_GeomFromText('POLYGON((4 2, 4 4, 5 4, 5 2, 4 2))') as geom
UNION
SELECT 'ogb3' as id, ST_GeomFromText('POLYGON((5 2, 5 4, 5.5 4, 5.5 2, 5 2))') as geom
UNION
SELECT 'ogb4' as id, ST_GeomFromText('POLYGON((5.5 2, 5.5 4, 7 4, 7 2, 5.5 2))') as geom

and the line:
SELECT 1234 as id, ST_GeomFromText('LINESTRING(3 3, 6 3)') as geom

A: The query below will:
1 - Intersect the lines and polygons,
2 - extract the startpoints of each intersect output line geometry,
3 - Use the startpoints as input to ST_LineLocatePoint to get a number between 0-1 of where on the input lines the point is located.
4 - Order by this number and select number 2 intersection line by each original line id:
with cte as (
select lineid, row_number() over(partition by lineid order by st_linelocatepoint(linegeom, st_startpoint(intergeom))) segmentnum, st_length(intergeom) length, intergeom from
    (select  p.id polyid,
            l.id lineid,
            l.geom as linegeom,
            (st_dump(st_intersection(p.geom, l.geom))).geom intergeom
    from public.poly99 p
    join public.line99 l
    on st_intersects(p.geom, l.geom)) sub
)
select * from cte
where segmentnum=2

This finishes in three seconds for 50k lines and 250k polygons:

( This is the code I used to generate the random 50k lines
import numpy as np
linenum = 50000 #The number of lines to create
e = iface.mapCanvas().extent() #Within current map extent
xMax, xMin, yMax, yMin = e.xMaximum(), e.xMinimum(), e.yMaximum(), e.yMinimum() #Find the areas coordinates

vl = QgsVectorLayer("LineString?crs=EPSG:3006&index=yes", "randomLines", "memory") #Create a temp line layer. Replace 3006 with a suitable crs
provider = vl.dataProvider()

def randomline(xmin, xmax, ymin, ymax):
    """A function to return a random line within an area"""
    global point1, point2
    randx = np.random.uniform(xmin, xmax) #Create one random x coordinate
    randy = np.random.uniform(ymin, ymax) #And y
    point1 = QgsPoint(randx, randy) #Create a point from them
    randx+=np.random.uniform(-300,300) #Create a second x coordinate within +/-300 meters from the first
    randy+=np.random.uniform(-300,300) #And y
    point2 = QgsPoint(randx, randy) #And a second point
    return QgsGeometry(QgsLineString([point1,point2])) #Use them to return a line geometry

for x in range(0,linenum):
    f = QgsFeature()
    f.setGeometry(randomline(xMin, xMax, yMin, yMax))
    provider.addFeature(f)

QgsProject.instance().addMapLayer(vl)

)

A: ST_Intersection does keep the inherent (vertex) order of the LINESTRING, if given a compound operational context; thus, with a collection of POLYGONs to operate on, you can simply extract segments in order of the (ST_Dump).path:
SELECT
  ln.id,
  its.path[1] AS seq,
  ST_Length(its.geom) AS len,
  its.geom
FROM
  lines AS ln
  CROSS JOIN LATERAL (
    SELECT
      (ST_Dump(ST_Intersection(ln.geom, ST_Collect(pl.geom)))).*
    FROM
      polys AS pl
    WHERE
      ST_Intersects(ln.geom, pl.geom)
  ) AS its
WHERE
  its.path[1] = 2
;


text:
Q: Detect which /dev/ttyACM is open Is their a command that returns what /dev/ttyACM* is open. At some stage in the script it disconnects the usb and reconnects but the ACM increments after this so the variable port = /dev/ttyACM0 now is /dev/ttyACM1. I want to detect which /dev/ttyACM* is open. So port = return (command  to find ACM)

A: Using glob and serial, this should do the trick:
import glob
import serial

def find_ports():
    ports = glob.glob('/dev/ttyACM[0-9]*')

    res = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            res.append(port)
        except:
            pass
    return res


text:
Q: debian 3.1 can be upgraded to lenny? yesterday I "inherited" an ancient debian 3.1 machine to which I am supposed to add a few functionalities (mail, among them)
is there a safe way to upgrade it to a superior version ? if not, is there a repository for its debs ?

A: Sarge is no longer receiving security updates.  There are security issues that will not have been patched on sarge.  If the machine is available on the Internet, you should strongly consider to upgrading to at least etch, and preferably lenny.  If it isn't obvious make a backup first.
You should be able to upgrade, but not directly. You'll need to go from sarge->etch->lenny.  Since it is remote you'll want to make sure they hardware will be supported in the newer OS.
You can use this in your /etc/apt/sources.list if you really want to continue to use sarge for right now.
deb http://archive.debian.org/debian/ sarge main
deb-src http://archive.debian.org/debian/ sarge main

A: There are some "archive" servers. You could of course dist-upgrade it to etch, then dist-upgrade etch to lenny, but it's a bit of a stretch. You'd better make a list of installed packages with
dpkg --get-selection > packlist
saving /etc and other data files, then install a new lenny and reinstall additional packages with
dpkg --set-selection && aptitude dselect-upgrade


text:
Q: Can someone explain negative frequencies when doing the Fourier transform? I apologize if this question has been asked before. I have looked and have not found a clear explanation.
When doing the discrete Fourier transform (e.g. fft in MATLAB) for a vector of discrete time signals $f(t)$ with length $N$ and sample rate $\Delta t$, the result is a vector of complex Fourier coefficients, $F(\omega )$ with length $N$. However, I get confused when trying to plot these Fourier coefficients with respect to frequency.
My understanding is that each frequency is defined as $$f_n=\frac{n}{N\Delta t},\;\;\;\;\;\;n=-N/2\;\;...\;\; -2,-1,0,1,2\;\;...\;\;N/2.$$
I have two problems:
1) This results in a frequency set with $N+1$ elements, but $F(\omega )$ only has $N$ elements. On which side of zero do we lose an element? Wouldn't this wreck the symmetry and thereby violate conservation of energy?
2) Negative frequencies seem non-physical to me. So, if I chop the Fourier transform such that $f\geq0$, then I lose half the spectrum. Where does this extra energy go? What does it mean to have a "negative" frequency?
Any help or explanations are greatly appreciated.


text:
Q: Slick 3.0.0 Delete all Entries From a Table The following query:
val resultValue = Await.result(db.run(MyTable.myTableItems.delete), 2.seconds)

Strangely, the above query when run gives me the max value for the Id that I have in that particular table. Why is that? What is the Slick equivalent of delete all entries from a Table?

A: The result from delete is the number of rows affected by the delete. If your id starts from 1, it could be a coincidence that the number of rows affected happens to be the same as largest id in the table.
Calling delete on a table query is the way to delete all entries from a table. For example, if you have
val coffees = TableQuery[Coffees]

...then coffees.delete is the action to remove all rows.
Useful link: Deleting, in the Slick Manual.


text:
Q: Logstash Grok pattern to cut split a string in the log line using regex Below is the field that is part of a log line from the application, where have client-id attributes value that I need to split, delimitter '#'.
client-id=ABC-SYNC_Foo#qrkmguv4p995b3kqk1jaupocl2

here is how i want
source=ABC-SYNC_Foo
id=qrkmguv4p995b3kqk1jaupocl2

I need help with regex on how to split it in within a single line.

A: I suggest using
client-id=(?<source>[^#]*)#(?<id>.*)

See the regex demo
The pattern matches:

*

*client-id= -  a literal character sequence client-id=

*(?<source>[^#]*) - Group "source" matching zero or more characters other than # up to the first...

*# - literal hash symbol followed with...

*(?<id>.*) - any 0 or more characters other than a newline (Group "id")

A: Thanks to Wiktor Stribiżew for the suggestion, following Regex worked for me:
client-id=(?<source>[^#]*)#(?<id>.*)


text:
Q: arm-angstrom-linux-gnueabi-gcc linker fails to link against uclibc I am trying to build an application for angstrom linux (that uses uclibc instead of libstdc++, in my case). I am using bitbake and openembedded. With a simple toolchain I am able to build successfully by adding only -muclibc flag. With bitbake my build command is the following
arm-angstrom-linux-gnueabi-gcc -march=armv7-a -mtune=cortex-a8 -mfpu=neon -mfloat-abi=softfp -mthumb-interwork -mno-thumb --sysroot=/home/hnsl/stuff/tmp/sysroots/armv7a-angstrom-linux-gnueabi -fexpensive-optimizations -fomit-frame-pointer -frename-registers -O2 -ggdb2 -Wl,-O1 -Wl,--hash-style=gnu -muclibc mainThread.cpp lib.cpp -lportaudio

where -muclibc mainThread.cpp lib.cpp -lportaudio is done by me. Portaudio (-lportaudio) is linked successfully. Uclibc (I think) fails to be linked; I get these errors:
 /tmp/ccW4SVb4.o: In function `main':
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/mainThread.cpp:68: undefined reference to `__cxa_end_cleanup'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/mainThread.cpp:68: undefined reference to `__cxa_begin_catch'
| /tmp/ccW4SVb4.o: In function `operator<< <std::char_traits<char> >':
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:513: undefined reference to `std::cerr'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:513: undefined reference to `std::cerr'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:513: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, int)'
| /tmp/ccW4SVb4.o: In function `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))':
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:113: undefined reference to `std::cerr'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:113: undefined reference to `std::cerr'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:113: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
| /tmp/ccW4SVb4.o: In function `main':
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/mainThread.cpp:68: undefined reference to `__cxa_end_catch'
| /tmp/ccW4SVb4.o: In function `operator<< <std::char_traits<char> >':
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:511: undefined reference to `std::cerr'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/ostream:511: undefined reference to `std::cerr'
| /tmp/ccW4SVb4.o: In function `std::basic_ios<char, std::char_traits<char> >::setstate(std::_Ios_Iostate)':
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/bits/basic_ios.h:148: undefined reference to `std::basic_ios<char, std::char_traits<char> >::clear(std::_Ios_Iostate)'
| /tmp/ccW4SVb4.o: In function `main':
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/mainThread.cpp:68: undefined reference to `__cxa_end_catch'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/mainThread.cpp:68: undefined reference to `__cxa_end_cleanup'
| /tmp/ccW4SVb4.o: In function `__static_initialization_and_destruction_0':
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/iostream:73: undefined reference to `std::ios_base::Init::Init()'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/iostream:73: undefined reference to `std::ios_base::Init::~Init()'
| /home/hnsl/stuff/tmp/sysroots/x86_64-linux/usr/armv7a/lib/gcc/arm-angstrom-linux-gnueabi/4.5.3/../../../../arm-angstrom-linux-gnueabi/include/c++/4.5.3/iostream:73: undefined reference to `std::ios_base::Init::~Init()'
| /tmp/ccW4SVb4.o:(.ARM.extab+0x0): undefined reference to `__gxx_personality_v0'
| /tmp/ccW4SVb4.o:(.ARM.extab+0x28): undefined reference to `typeinfo for char const*'
| /tmp/ccUEShoN.o: In function `endOnError(void*, int, char*)':
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:23: undefined reference to `__cxa_allocate_exception'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:23: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:23: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:23: undefined reference to `__cxa_throw'
| /tmp/ccUEShoN.o: In function `initFramework(char**, void**, PaStreamParameters*, PaStreamParameters*)':
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:32: undefined reference to `__cxa_allocate_exception'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:32: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:32: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:32: undefined reference to `__cxa_throw'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:37: undefined reference to `__cxa_allocate_exception'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:37: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:37: undefined reference to `typeinfo for char const*'
| /home/hnsl/stuff/tmp/work/armv7a-angstrom-linux-gnueabi/cphone-1.0.0-r1/lib.cpp:37: undefined reference to `__cxa_throw'
| collect2: ld returned 1 exit status

Thanks

A: You really should use g++ to compile and link C++ code. It will take care of adding the right include paths and linker options for the standard C++ library.
It is possible to do so with gcc, but always using g++ both for compile and link is much easier.


text:
Q: Unable to modify authentication credential using Jersey 2.x when the client has been already created I have followed the documentation of Jersey 2.x to authenticate any request and following is my code snippet.
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
    .nonPreemptive()
    .credentials("user", "password")
    .build();

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(feature) ;

Client client = ClientBuilder.newClient(clientConfig);

Now let say i want to update the username, even if i do the same register of features with new username, i am still getting the username which is set earlier. How can i update the value of a already registered commonconfig for jersey client 2.x?


text:
Q: Failed to connect to camera service (RunTimeException) on open() when app has been running for a while This one's been making me lose my mind for the last few days.
The app I am working on is designed as a time clock of sorts to allow employees at my company to clock in and out. Accepts their ID number and snaps a picture for verification purposes if there was reason to suspect a "buddy punch." The tablets we are using are Samsung Galaxy Tab 3's with the 7 inch screen. The tablets are locked down and basically run the app all day with the screen on a 5 minute timeout.
The way I handle the camera is to open it when the app is active (screen is on and the activity is in the foreground), but not start the preview until someone starts typing in a number. This is all well and good. The problem is that sometimes for no reason that I've been able to discern, the app cannot connect to the camera service and gets a runtimeexception. Exiting and reloading the activity doesn't seem to fix it.
I release the camera when the activity loses focus (onPause) and open it back up in onResume. On my dev tablet, I can make the camera misbehave by rapidly starting and stopping the preview a bunch of times and just flailing on the tablet in general. The error thrown there gets handled by the error callback on the camera object and it's able to fix itself afterwards. Below is a stack trace.
Everything is declared properly in the manifest, and it works the majority of the time. It seems that the high use ones tend to get this thrown more often and the only fix I've found is restarting the device. I can post code snippets if need be.
Does anyone have any idea what's causing this? Could there be someplace I'm missing a camerae.release() call?
2014-01-06T18:43:58.645Z -- [myDebugTag] - getCamera: RunTimeException class java.lang.RuntimeException
2014-01-06T18:43:58.647Z -- [myDebugTag] - Fail to connect to camera service
2014-01-06T18:43:59.213Z -- [myDebugTag] - android.hardware.Camera.native_setup(Native Method)
android.hardware.Camera.<init>(Camera.java:348)
android.hardware.Camera.open(Camera.java:307)
[mypackagename].fragments.CameraFrag.getCamera(CameraFrag.java:156)
[mypackagename].[myactivity].onResume([myactivity].java:1587)
android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1199)
android.app.Activity.performResume(Activity.java:5259)
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2648)
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2686)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2159)
android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3595)
android.app.ActivityThread.access$800(ActivityThread.java:146)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4949)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
dalvik.system.NativeStart.main(Native Method)

This is my camera preview class. Perhaps not the prettiest. This class is inside a fragment. The activity tells the fragment when to stop the preview by doing camera.stopPreview and then hiding the view temporarily. It restarts it by calling startPreview and displaying the view again.
The activity also decides when to release the camera. It tells the fragment to release it and dispose of the objects in onPause and then restarts the camera preview and view in onResume.
/**
 * Used to display the camera preview to the screen. Handles taking a picture and saving it
 *
 * @author [bagellord]
 */
private class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, ErrorCallback {
    /**
     * Reference to the camera (front facing)
     */
    private Camera          camera;
    /**
     * Used for displaying the preview
     */
    private SurfaceHolder   mHolder;
    /**
     * Camera id of the camera in use
     */
    private int             cameraId;

    /**
     * Constructor
     *
     * @param con
     *            Context
     * @param cam
     *            The camera to use
     */
    public CameraPreview(Context con, Camera cam, int camId) {
        super(con);

        // Reference to the camera
        camera = cam;
        // Store the camera id
        cameraId = camId;
        // Get the holder for the surface view
        mHolder = getHolder();
        // Tell it to use this class as the call back
        mHolder.addCallback(this);
        // Add the error callback for the camera
        camera.setErrorCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // Check to see if the surface exists
        if(mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }

        // Stop preview before making changes
        try {
            camera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        // Holds the camera info
        CameraInfo info = new CameraInfo();
        // Get the camera info
        Camera.getCameraInfo(cameraId, info);

        // Orientation of the device
        int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        // Degrees
        int degrees = 0;

        // Check to see which way the device is oriented
        switch(rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        // Used for setting the camera orientation
        int result;

        // Check to see if it is front or rear facing
        if(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }

        // Set the orientation
        camera.setDisplayOrientation(result);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if(cameraEnabled) {
            // Set the callback to null
            camera.setPreviewCallback(null);
            // Surface is gone, stop the preview
            camera.stopPreview();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Start the preview back up with the holder
        startPreview();
    }

    @Override
    public void onError(int error, Camera camera) {
        // Release the camera
        releaseCamera();
        // Log what happened
        TimeClockApp.logToFile(DEBUG_TAG, "CameraFrag.CameraPreview.onError error: " + error + " server died? "
                + (error == Camera.CAMERA_ERROR_SERVER_DIED));
        // Tell the parent that the camera failed and it will recreate it
        parent.camFailed();
    }

    /**
     * Start the preview
     */
    public void startPreview() {
        try {
            if(camera != null && mHolder != null) {
                // Tell the camera where to output the preview
                camera.setPreviewDisplay(mHolder);
                // Start the preview
                camera.startPreview();
            }
        } catch (IOException e) {
            TimeClockApp.logToFile(DEBUG_TAG, e.getMessage());
        }
    }

    /**
     * Stop the preview
     */
    public void stopPreview() {
        camera.stopPreview();
    }

    /**
     * Tell the camera to take a picture
     *
     * @param timeStamp
     *            The timestamp for when it is being taken
     */
    public void takePicture() {
        // Tell the camera to take a picture.
        // The null parameters are for the shutter and the fallback for RAW format.
        // Third parameter is the code to run after it takes the photo
        camera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                // Stores the picture
                File pictureFile = new File(
                        TimeClockApp.STORAGE_TEMP_IMG);
                // Make the parent directories
                pictureFile.getParentFile().mkdirs();
                // Delete the picture if it exists already for some reason
                pictureFile.delete();

                try {
                    // Output stream to write the file with
                    FileOutputStream fos = new FileOutputStream(
                            pictureFile);
                    // Write the picture to the sd card
                    fos.write(data);
                    // Close the stream
                    fos.close();
                } catch (Exception e) {
                    // Error
                    TimeClockApp.logStackTrace("CameraFrag.CameraPreview.takePicture exception", e);
                }

                // Log that the picture was taken
                TimeClockApp.logToFile(DEBUG_TAG, "Temp picture taken");

                // Have to start previewing in the callback
                camera.startPreview();

                // Notify the parent activity that the picture has been taken
                parent.pictureTaken();
            }
        });
    }

    /**
     * Release the camera so its resource is not locked up
     */
    private void releaseCamera() {
        // Make sure the camera object is not null
        if(camera != null) {
            // Workaround for a glitch
            camera.setPreviewCallback(null);
            // Release the camera
            camera.release();
            // Set the camera to null
            camera = null;
            cameraEnabled = false;
        }
    }
}


text:
Q: Issue in expanding and collapsing tableview cell using swift 3 with Xcode 8.2 I'm trying to expand and collapse the table view cell by clicking them. I followed the tutorial https://www.youtube.com/watch?v=LqHzHkuXRxQ&t=89s. Did all things exactly like in this video. It is successfully running without any error or warning. But i could not view the content in the table view cell. It just displays an empty table. I think it is Xcode version problem. In the tutorial, he used Xcode 7, i guess. And i'm using Xcode 8.2. I don't know what changes i should make, to view the content in the table view cell.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var selectedIndex = -1
    var dataArray : [[String:String]] = [["FirstName" : "Arun", "LastName" : "Gupta"],["FirstName" : "John", "LastName" : "Cena"],["FirstName" : "James" , "LastName" : "Bond"],["FirstName" : "Iron", "LastName" : "Man"]]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) ->CGFloat
    {
        if(selectedIndex == indexPath.row) {
            return 100;
        }
        else{
            return 40;
        }
    }
    func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
        let obj = dataArray[indexPath.row]
        cell.firstViewLabel.text = obj["FirstName"]
        cell.secondViewLabel.text = obj["LastName"]
        return cell;
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if(selectedIndex == indexPath.row) {
            selectedIndex = -1
        } else {
            selectedIndex = indexPath.row
        }
        self.tableView.beginUpdates()
        self.tableView.reloadRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
        self.tableView.endUpdates()
    }

}

import UIKit

class customCell: UITableViewCell {

    @IBOutlet weak var firstView: UIView!
    @IBOutlet weak var firstViewLabel: UILabel!
    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var secondViewLabel: UILabel!
    @IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    var showsDetails = false {
        didSet {
            secondHeightConstraint.priority = showsDetails ? 250 : 999
        }
    }
}

A: You haven't supply UITableViewDelegate and UITableViewDataSource
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

In your viewDidLoad():
tableView.dataSource = self
tableView.delegate = self

A: If i see it correctly you are missing the numberOfSections(in tableView: UITableView) -> Int method. So your TableView have 0 sections.


text:
Q: Ununtu 16.10 no internet, wi-fi or cable i just installed Ubuntu 16.10 on my laptop, but i can not connect to internet, wi-fi or cable, it just not working. i hope that you can help me, thanks!
the output of: lspci -knn | grep -EA2 'Eth|Net'

A: Use another computer to download these files:
http://mirrors.kernel.org/ubuntu/pool/main/d/dkms/dkms_2.2.0.3-2ubuntu14_all.deb
http://mirrors.kernel.org/ubuntu/pool/universe/r/r8168/r8168-dkms_8.042.00-2_all.deb
http://mirrors.kernel.org/ubuntu/pool/restricted/b/bcmwl/bcmwl-kernel-source_6.30.223.248+bdcom-0ubuntu11_amd64.deb
Copy the files to your Ubuntu Home folder and run in terminal:
sudo dpkg -i *.deb

Reboot. Both interfaces should work. If you have UEFI, you need to disable Secure Boot in BIOS first.


text:
Q: List.js Dropdown Filter - How to reset to initial state? I have the dropdown filter working properly but I'd like to offer an All value that refreshes the list items and shows the initial state (all list items being visible).
I have a button that does this onClick:
$('#filter-clear').click(function() {
  featureList.filter();
  return false;
});

The if statement in the dropdown code below isn't working as expected.
Basically, if the selection value is ALL I want to run the same function that the filter-clear button runs (showing all items). Otherwise return the items with the selected value.
Here's a codepen of the dropdown working without the below if statement: https://codepen.io/nolaandy/pen/Zryaoq
My Dropdown Code:
$('#positionChange').change(function () {
var selection = this.value;
var option=document.getElementById('positionChange').value;
console.log(selection);console.log(option);

featureList.filter(function (item) {
  if (selection='ALL') {
      featureList.filter();
      } else {
return (item.values().playerPosition == selection);
}
});

});

A: try this code
$('#positionChange').change(function () {
var selection = this.value;
var option=document.getElementById('positionChange').value;
console.log(selection);console.log(option);
if(selection != 'ALL')
    featureList.filter();
else
    featureList.filter(function (item) {
        return (item.values().playerPosition == selection);
    });

});

it is not good to have if/else inside the function filter is better to do it out side.


text:
Q: Pandas group by cumsum length of values does not match length of index As most of these help questions begin, I'm new to Python and Pandas. I've been learning by doing, especially when I have a particular task to complete. I have searched the help pages and could not find an answer that addressed by specific problem and I could not devise a solution based on answers to similar problems.
I have a data set with 50K+ entries. The general format is:
    code  value
0    101    0.0
1    102    0.0
2    103   23.2
3    104   10.3
4    105    0.2
5    106    0.0
6    107   22.6
7    108    0.0
8    109    0.0
9    110    2.2
10   111    3.8
11   112    0.0

My first task was to segregate consecutive non-zero values. Through trial and error, I managed to condense my script to one line that accomplished this.
df[df['value'] != 0].groupby((df['value'] == 0).cumsum())
for grp, val in df[df['value'] != 0].groupby((df['value'] == 0).cumsum()):
    print(f'[group {grp}]')
    print(val)

The output is:
[group 2]
   code  value
2   103   23.2
3   104   10.3
4   105    0.2
[group 3]
   code  value
6   107   22.6
[group 5]
    code  value
9    110    2.2
10   111    3.8

I have other manipulations and calculations to do on this data set and I think the easiest way to access these data would be to transform the groupby object into a column (if that is even the correct terminology?), like so:
   code  value  group
0   103   23.2      2
1   104   10.3      2
2   105    0.2      2
3   107   22.6      3
4   110    2.2      5
5   111    3.8      5

Obviously, I get a "Length of values does not match length of index" error. I searched the help pages and it seemed that I needed to do some type of reset_index method. I tried various syntax structures and many other coding solutions suggested in other threads the past day and a half without success. I finally decided to give up and ask for help when I returned from a short break and found my cat rolling on the keyboard, adding and deleting gobs of gibberish to the script snippets I had been testing.
If someone would be kind enough to help me with this script--to get the groupby object into a column, I would greatly appreciate it. Thanks.

A: This will give you the groups then drop the zero rows.
df = pd.DataFrame({'code': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112],
 'value': [0.0, 0.0, 23.2, 10.3, 0.2, 0.0, 22.6, 0.0, 0.0, 2.2, 3.8, 0.0]})

df['group'] = df.value.eq(0).cumsum()
df = df.loc[df.value.ne(0)]

Output
    code  value  group
2    103   23.2      2
3    104   10.3      2
4    105    0.2      2
6    107   22.6      3
9    110    2.2      5
10   111    3.8      5


text:
Q: Running TestCases (from Maven) when TestCases are in src? I have a project that itself is a set of test cases for an application. The test cases are tested itself using a mockup of the application to ensure the tests itself is correct. This is important to ensure the test cases justify some sort of specifications that are hard to follow and easy to mess up.
Now I want the final tests (those who are tested before) being in src in Maven. As expected mvn test just executes the test cases of the test cases not the test cases themself.
So basically how do I execute test cases that reside inside the 'src' folder using a maven goal?

A: Try this :
<testSourceDirectory>src</testSourceDirectory>


text:
Q: Using paging (Skip, Take) over multiple DbSets I have an Entity Framework DbContext with two different DbSets.
In my view I am combining these two sets into the same view model and listing them in the same table.
I want to support table paging to be able to query only a page of records at a time sorted by a particular column.  I can't see how to do this without reading all of the records from the database and then paging from memory.
For example, I want to be able to sort by date ascending since both tables have a date column.  I could simply take the page size from both tables and then sort in memory but the problem comes into play when I am skipping records.  I do not know how many to skip in each table since it depends on how many records are found in the other table.
Is there a way to manipulate Entity Framework to do this?

A: It is possible.

*

*JOin them in the database (can be done in EF).

*Project that (select new  {}) into the final object

*Order by, skip, take on that projection.

It will be crap performance wise but there is no way around that given you have a broken database model. It basically has to get a tempoary view of all rows for the SQL to find the first ones - that will be slow.

A: Your best bet is going to be to combine them with a stored procedure or view, and then map that sp/view into Entity Framework. Combing them on the client is going to kill performance - let the server do it for you; it is clearly a server side task.


text:
Q: How to add multiple legends in Seaborn Jointplot? How can we add multiple legends in Seaborn jointplot? I`m creating a hexbin jointplot with seaborn, and I want to have two legends, scaling in vertical direction instead of horizontal.
First, how can I have both legends as separate and legend for dates scaling vertically instead of horizontally.
I had a look at these links.
Correctly add a legend to a seaborn jointplot
and
Getting legend in seaborn jointplot
And would it also be possible to have the same background for Hexbins instead of white, which doesn`t match with Seaborn style? And can I also make grid square, instead of rectangular?
sns.set()

g = sns.jointplot(x=x,y=y, kind="hex",color="#4CB391", height=15)
ax = g.ax_joint

sns.regplot(x = new_x,y= new_y, ax=ax, scatter=False)
sns.regplot(x = y_true['fatigue_dem_1'],y= y_true['fatigue_dem_1'], color='red',ax=ax, scatter=False)

g.set_axis_labels('Estimated', 'Predicted', fontsize=20)
g.fig.suptitle("Fatigue Dem 1", fontsize=20)

# adjustment for colorbar
plt.subplots_adjust(left=0.2, right=0.8, top=0.95, bottom=0.2)
# make new ax object for the cbar
cbar_ax = g.fig.add_axes([.85, .2, .05, .6])  # x, y, width, height
plt.colorbar(cax=cbar_ax)

metric_legend, = g.ax_joint.plot([], [], linestyle="", alpha=0.5)
data_legend, = g.ax_joint.plot([], [], linestyle="", alpha=0.5)

g.ax_joint.legend([metric_legend],['rrmse={:f}, r2_score={:f}'.format(rrmse,r2)],  fontsize=14)
g.ax_joint.legend([data_legend],['Start Date: {0}, End Date: {1}, purpose: {2}'.format(start_date, end_date, 'Test')],  fontsize=14)


text:
Q: resume Rsnapshot to same drive Sometimes, on a large rsync using Rsnapshot, the NFS mount we are syncing to will drop.
Then when you run:
rnsapshot monthly

to resume it, it will behave as if this is a brand new, rotating the monthly.0 to monthly.1 and so on.
Is there a way to resume the rsync using rsnapshot monthly if something gets interrupted? That won't start a brand new backup?

A: The answer is no not really but sort of. rsnapshot runs as a batch job - generally triggered from a cron job. It does not keep any state between runs apart from the backups themselves. If your NFS mount goes away mid backup, after a while you'll get some sort of IO error, and rsnapshot will give up and die with an error. The backup will fail. Next time it is run after the failure, it will start the backup as if from scratch.
However, if you use the sync_first config option, and not the link_dest option, rsnapshot will do a better job of recovery. It will leave the files its already transferred in place and won't have to transfer them again, but it will have to check again that the source and destination are the same in the usual rsync way. The man page gives some detail on this.
This is not the case with the link_dest method which for most errors removes the work its done and starts again. Specifically, on error link_dest does a "rollback" like this:
ERROR: /usr/bin/rsync returned 255 while processing sam@localhost:..
WARNING: Rolling back "localhost/"
/bin/rm -rf /tmp/rs-test/backups/hourly.0/localhost/
/bin/cp -al /tmp/rs-test/backups/hourly.1/localhost \
    /tmp/rs-test/backups/hourly.0/localhost
touch /tmp/rs-test/backups/hourly.0/
rm -f /tmp/rs-test/rsnapshot-test.lock

If your not using it already, and you can use it (apparently some non UNIX systems can't), use the sync_first method.

A: I don't use rsnapshot, but I've written my own equivalent wrapper over rsync [in perl] and I do delta backups, so I've encountered similar problems.
To solve the problem of creating "false whole backups", the basic idea is to do:
while 1
    rsnapshot remote_whatever/tmp

    if (rsnapshot_was_okay) then
        mv remote_whatever/tmp remote_whatever/monthly_whatever
        break
    endif
end

The above mv should be atomic, even over NFS.
I just answered a similar question here: https://serverfault.com/questions/741346/rsync-directory-so-all-changes-appear-atomically/741420#741420 that has more details


text:
Q: Apache2 500 error trouble shooting I recently updated some code on a staging server and now one link in the app throws an Internal Server Error...
There have been no changes to the .htaccess in doc root, but to remove this from the equation, I removed the .htaccess to test and no go.
Apache2 logLevel has been changed to debug and nothing is being logged. (watching tail -f /var/log/apache2/error.log and loading the page does not append anything to the log).
This code is running perfectly well on our development server. I know thats not much to go by.
Without the logs, I am stumped. Ths is a fairly complex app and without logs I simply cannot work out what the issue is.
Any help is much appreciated. Thanks in advance.

A: Ok guys, looks like it was just IE throwing the 500.
Loading the page in Firefox shows a nice PHP parse error (the app is only supported in ie, so I had to switch my user agents to test).
For the record, I went through all my vhosts so make sure the logs were all correct, which they were, I'm still not sure why I was getting nothing logged.
Thanks for the help!

A: A 500 usually means that some CGI that you're calling is failing, so it's not always easy to get useful logs - if you know what CGIs are being called, you can try and get them to do their own logging and see what you find.
Having said that, you should definitely get some messages in the logs, because just by virtue of the fact that you are getting a 500 - that means that the web server has spotted the error and sending you a 500 message.  So you should also check that it's actually logging to what you think it is logging to.


text:
Q: \documentclass{book} + natbib I'm using \documentclass{book} and trying to get the natbib package generate the bibliography.
I have a root file, say, root.tex and different chapters are included using \include{}.
I'm having problems in getting the bibliography to work.
I have the following commands in my root.tex file:
\bibliographystyle{plainnat}
\bibliography{mybib}

Any suggestion/solution will be much appreciated!


text:
Q: Arrays.sort (Comparator) - Java 6 vs Java 7 import java.util.Comparator;
public class CompareTester {
int i;
public static class Inside implements Comparator<CompareTester> {
    @Override
    public int compare(CompareTester o1, CompareTester o2) {
        // TODO Auto-generated method stub
        System.out.println(o1.i - o2.i);
        return 0;
}}}

public class CompareTest {
public static void main(String[] args) {
    CompareTester j = new CompareTester();
    j.i = 3;
    CompareTester k = new CompareTester();
    k.i = 5;
    CompareTester l = new CompareTester();
    l.i = 7;
    CompareTester[] numbers = { j, k, l };
    Arrays.sort(numbers, new CompareTester.Inside());
}}

These are two classes that are giving two different results in CompareTester class when ran in Java 6  and Java 7.
Is there any different kind of implementation that has been introduced in Java7 for Comparator?

A: Java 7 uses TimSort, Java 6 used MergeSort. Your comparator always returns 0 which breaks the Comparable Contract and TimSort is picking up on that.
To fix the code you really need to address that. If you really want to use the old sort algorithm then compile with -Djava.util.Arrays.useLegacyMergeSort=true

A: Apart from a different sorting algorithm, which is only relevant internally, there are no difference between the final result of Array.sort(E, Comparator). So, no, there is not difference "introduced in Java7 for Comparator".
Just change your implementation to
import java.util.Comparator;
public class CompareTester {
    int i;
    public static class Inside implements Comparator<CompareTester> {
        @Override
        public int compare(CompareTester o1, CompareTester o2) {
            return o1.i - o2.i;
        }
    }
}

and compare the final resulting array instead and you'll see that there is no difference between Java 6 and 7.
Edit
If you want to avoid using a Comparator, then make your CompareTester class implement Comparable<T> instead (Java 7 doc here);
import java.lang.Comparable;
public class CompareTester implements Comparable<CompareTester> {
    int i;

    public int compareTo(CompareTester o) {
        return this.i - o.i;
    }
}

Then, you don't need anything special with Array.sort :
Arrays.sort(numbers);


text:
Q: How to group 2 udp clients? What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i don't know how to make it work like described above. Messages are send from client by typing something in console.
server:
public class Server extends Thread{

public final static int PORT = 7331;
private final static int BUFFER = 1024;

private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;

public Server() throws IOException {
    socket = new DatagramSocket(PORT);
    System.out.println("[SERVER] UDP server successfully launched on port " + PORT);

    clientAddresses = new ArrayList<InetAddress>();
    clientPorts = new ArrayList<Integer>();
    existingClients = new HashSet<String>();
}

public void run() {
    byte[] buf = new byte[BUFFER];
    while (true) {
        try {
            //resets buffer so only new messages get displayed
            Arrays.fill(buf, (byte) 0);

            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);

            String content = new String(buf, buf.length);

            InetAddress clientAddress = packet.getAddress();
            int clientPort = packet.getPort();

            String id = clientAddress.toString() + "," + clientPort;
            if (!existingClients.contains(id)) {
                existingClients.add(id);
                clientPorts.add(clientPort);
                clientAddresses.add(clientAddress);
            }

            System.out.println(id + " : " + content);
            byte[] data = (id + " : " + content).getBytes();
            for (int i = 0; i < clientAddresses.size(); i++) {
                InetAddress cl = clientAddresses.get(i);
                int cp = clientPorts.get(i);
                packet = new DatagramPacket(data, data.length, cl, cp);
                socket.send(packet);
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

public static void main(String args[]) throws Exception {
    Server s = new Server();
    s.start();
}
}

clients:
public class Client implements Runnable {

public static void main(String args[]) throws Exception {
    String host = "127.0.0.1";

    DatagramSocket socket = new DatagramSocket();

    //handles the receiving part for every client (incoming packets to clients)
    MessageReceiver r = new MessageReceiver(socket);

    Client s = new Client(socket, host);
    Thread rt = new Thread(r);
    Thread st = new Thread(s);
    rt.start();
    st.start();
}

public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;

Client(DatagramSocket s, String h) {
    sock = s;
    hostname = h;
}

//sending clients socket to server
private void sendMessage(String s) throws Exception {
    //getting bytes from message
    byte buf[] = s.getBytes();

    //getting hostname from server
    InetAddress address = InetAddress.getByName(hostname);

    //setting up packet
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);

    //sending packet to server
    sock.send(packet);
}

public void run() {
    //connected boolean is used to send a greetings message once for every new client that has joined
    boolean connected = false;

    do {
        try {
            sendMessage("GREETINGS");
            connected = true;
        } catch (Exception e) {

        }
    } while (!connected);

    //reads from the console
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
        try {
            while (!in.ready()) {
                Thread.sleep(100);
            }

            //sends message from console to server
            sendMessage(in.readLine());
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
}

//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];

MessageReceiver(DatagramSocket s) {
    sock = s;
    buf = new byte[1024];
}

public void run() {
    while (true) {
        try {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            sock.receive(packet);
            String received = new String(packet.getData(), 0,
            packet.getLength());
            System.out.println(received);
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
}

A: What youre trying is a message broadcast or a message-repeater-client.
broadcasting is implemented on network layer (using brodcast the local network broadcast adress).
And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)


text:
Q: Finding burn-date of a DVD An ISO file has been burned into a blank DVD (in a Linux OS). Is there any commands in Ubuntu to check when the DVD was burned?
I mean the date that the ISO file was burned, I do not mean the date ISO itself was created.

A: ISO 9660 ?
Try dd if=/dev/sr0 bs=1 skip=33581 count=17 | hexdump -C
Example output:
00000000  32 30 31 32 30 38 32 33  31 37 31 33 34 37 30 30  |2012082317134700|
00000010  00                                                |.|


text:
Q: AVFoundation - property declarations - basic question I'm fiddling around with the AVCamDemo from Apple. Apart from trying to get my head around all that, I ran into something I don't understand.
The properties are initialized in a very strange way and I didn't find any explanation for this.
In the header-file
AVCaptureSession *_session;

...

@property (nonatomic,readonly,retain) AVCaptureSession *session;

in the .m-file
@synthesize session = _session;

What's the story with the underscore???
Thanks for any clarification!

A: Basically, you have two things going on here.  an ivar (instance variable) and the property.

*

*The ivar is the actual variable.

*The property is syntactical sugar for getters and setters.

If you do
@synthesize session;

The ivar and the property are assumed to have the same name by the compiler.
if you do
@synthesize session = _session;

Then the property name is session and the ivar name is _session.
MY OPINION:
I've been doing Cocoa for over a decade. and @synthesize session = _session; is the safer way.  Every now and then, the compiler or the programmer get confused when the ivar and the property have the same name.

A: The underscore is a naming convention to distinguish properties from instance variables.
In particular, it helps to distinguish between assignment to the property (that automatically decreases and increases the reference count) and assignment ot the instance variable (without automatic reference count update).


text:
Q: How to run php file from other location? I have installed my XAMPP in C drive, normally, I save the file in this location C:\xampp\htdocs and run it as localhost/example.php. If I change my project folder to E:\project\example.php, what are the settings that need to be altered in XAMPP to run the file from other saved location other than C:\?.

A: You can relocate your project by editing the DocumentRoot entry in XAMPP\apache\conf\httpd.conf. There, you have to replace the line
    DocumentRoot C:\xampp\htdocs\
With:
DocumentRoot E:\Project\

A: This tutorial will guide step by step through this operation.
http://mattots.blogspot.com/2009/10/changing-document-root-in-xampp.html


text:
Q: Instantiate Generic Type in C# class Pretty basic question in C#,
class Data<T>
 {
    T obj;

    public Data()
    {
      // Allocate to obj from T here
      // Some Activator.CreateInstance() method ?
      obj =  ???
    }
 }

How do i do this?

A: If you want to create your own instance of T, then you need define a constraint new()
class Data<T> where T: new()
 {
    T obj;

    public Data()
    {
      obj =  new T();
    }
 }

If you want to pass in the obj then you need to allow it in the constructor
 class Data<T>
     {
        T obj;

        public Data(T val)
        {
          obj = val;
        }
     }

A: YOU can use the new constraint in your generic class definition to ensure T has a default constructor you can call. Constraints allow you to inform the compiler about certain behaviors (capabilities) that the generic parameter T must adhere to.
class Data<T> where T : new()
{
    T obj;

    public Data()
    {
        obj = new T();
    }
}

A: this may help: http://pooyakhamooshi.blogspot.com/2011/06/how-to-instantiate-generic-type-with.html


text:
Q: Installed program not visible to all users I am using wix setup to install some package. When I install it, it appears in "Programs and Features" in control panel. It is visible to some users not all, and they can uninstall it as well.
Problem is when the other user who can not see what I installed in control panel, when he installs something I can't see it. I can install the same package again and it won't complain that it already exists.

A: MSI packages are installed per-user or per-machine. Only per-machine products are accessible by all users.
Try making your installation per-machine by setting ALLUSERS property to:
1

A: InstallScope="perMachine" need to be set for the package node under product node.
<Product Id="51552DB5-AE93-44D0-87B1-0EB93B64182D" >
 <Package InstallerVersion="200"
          Compressed="yes"
          InstallScope="perMachine"
          InstallPrivileges="elevated" />
</Product>


text:
Q: How can I present a modal View Controller with the default segue animation of dismissing one? In my App I display a wizard the first time the app runs. At the end of the wizard it segues to the main screen. The default animation for this is that the main screen slides in from the bottom. However, I want the wizard view controller to slide down to reveal the main screen using the same animation as when a modal view controller is dismissed.
Is there a way to achieve this? Do I have to implement a custom segue for this or can I somehow use the animation style of dismissing a view controller?

A: Show your Main Screen with the Wizard screen on top of it (displayed as a modal) and then, when the user dismisses the Wizard, it will slide down and show the Main Screen.


text:
Q: How to prevent parameters from VB6 to Oracle using ADO being trimmed I have a VB6 app which calls an Oracle (12) PL/SQL stored procedure. It uses an ADODB connection object.
String parameters passed from the app may have trailing spaces. When Oracle receives them, any trailing spaces are gone.
I would like the trailing spaces to remain. I've searched everywhere and can't find any reference online to behaviour of VB, ADO or Oracle which says that trailing spaces are supposed to be trimmed in parameters.
In Oracle, the parameters to the stored procedure are defined as varchar2.
In VB6, I use CreateParameter() to add the params as adVarChar (I've tried other string types and it doesn't help). The call specifies the name, type, direction, size and value.
Just prior to the Execute call, I can check the Command.Parameters collection and verify that any trailing spaces are present.
Oracle references explicitly state that with the varchar2 datatype, trailing spaces are not ignored.
Can someone describe if there's an option either in VB or the database which is causing this, and can be turned off?

A: Does it work if you append a null, ie. chr(0) to the end of the string that has spaces?
Can you show your code that passes the parameters? What are you passing for length of the string - ie. are you doing a trim before doing len()?

A: Still not enough points to add a comment though now that I expanded this that it qualifies as a solution.
Oracle Objects for OLE (OO4O) is your best bet for compatibility with modern database versions. Add a reference to oip12.dll and try it out. My quick test case shows that if I send 'abc   ' (that was 3 spaces) as a parameter that the sproc does indeed keep the trailing spaces. I am actually using oip10.dll but the database is 12c. Quick Oracle sample I used.
CREATE TABLE TEMPTestTrailingSpace
 (F1  VARCHAR2(30) NOT NULL
 ,F2   NUMBER(12,0) NOT NULL
 ,DATEIN     DATE NOT NULL
 ) ;

create public synonym TEMPTestTrailingSpace for trace_owner.TEMPTestTrailingSpace;
grant SELECT on TEMPTestTrailingSpace to "TRACE_USER";

Insert into TEMPTestTrailingSpace values ('abc',1,sysdate);
Insert into TEMPTestTrailingSpace values ('abc      ',2,sysdate);
Insert into TEMPTestTrailingSpace values ('abc   ',3,sysdate);
Insert into TEMPTestTrailingSpace values ('abc     ',4,sysdate);
Insert into TEMPTestTrailingSpace values ('abd',5,sysdate);
Insert into TEMPTestTrailingSpace values ('abd   ',6,sysdate);
Insert into TEMPTestTrailingSpace values ('abd    ',7,sysdate);

Create or Replace Procedure getTestRecord
(
  P_PN IN VARCHAR2,
  p_rec OUT number
)
IS
BEGIN
     SELECT f2
     INTO   p_rec
     FROM  TEMPTestTrailingSpace
     WHERE  f1 = p_pn;
END;
/

create public synonym getTestRecord for trace_owner.getTestRecord;
grant execute on getTestRecord to "TRACE_USER";

I use a wrapper around the db access so it's not as easy to share an example. This gets you connected at least.
Public ooSession As Object
Public ooDB As Object

Dim ConnStr As String
Set ooSession = New OracleInProcServer.OraSessionClass
ConnStr = userID & "/" & password
Set ooDB = ooSession.OpenDatabase(dataSource, ConnStr, 0&) 'dataSource = Oracle SID or alias in TNSNames.ora file


text:
Q: JDA - How to get the user ID of the bot itself I'm making a JDA (Java Discord API) program that needs to check if a message was sent by the bot itself. How can I achieve this? I thought about checking if the user ID of the message sender equals the bot's user ID, but how can I get the user ID of the bot itself in the program?

A: If you use the MessageReceivedEvent, you can just check if the sender is a bot by using:
event.getAuthor.isBot().
You can access the user of the bot itself by accessing JDA and calling getSelfUser() as follows with the MessageReceivedEvent in mind:
event.getJDA().getSelfUser()
On the SelfUser you can call SelfUser#getId() or SelfUser#getIdLong() to access the ID.
Example Code
public class Listener extends ListenerAdapter {
  @Override
  public void onMessageReceived(MessageReceivedEvent event) {
    boolean isBot = event.getAuthor().isBot() //Check if the Message Sender is a bot

    long id = event.getJDA().getSelfUser().getIdLong() //the bot ID
  }
}


text:
Q: Automatic user log-in on a PHP-Website by button-clicking on a 3rd party .NET application Our customer is developing a C#.NET desktop software whilst we are hosting a website.
Our (PHP) website (no framework in use) has an user area for logged-in users.
The plan (yes, we are collecting ideas right now) is to let the user who is clicking on the button gets automatically logged in on our website and see their own user area on the web browser.
Our idea is to use OAuth 2.0, but I suppose that's not the right way since that one is commonly used for fetching resources from a protected resource server. And we got no clue which of the 4 flows we got to stick to, not even knowing what would be the client (role) in this scenery.
They might send some kind of code (json, curl, whatever...) with the LDAP information (Email? Username? First-/Lastname?) so we check in our database if the user is registered maybe? Would you recommend that we are writing our own solution by trying this, letting them in as if they used the login form on our site? Or is there any best-practice, technology, framework or anything we could take a look at first?

A: I think you need a sso (single sign on) authentication,
Different SSO protocols share session information in different ways, but the essential concept is the same:

there is a central domain, through which authentication is performed

and then the session is shared with other domains in some way. For instance, the central domain may generate a signed JSON Web Token (which may be encrypted using JWE).

ref:
https://auth0.com/blog/what-is-and-how-does-single-sign-on-work/


text:
Q: How can I improve this database design? I'm trying to design a data model for my current project, and I'm having trouble.  The product owner wants to have Users, Searches, Documents, and Tags.  Here's what seems to be well known thus far:

*

*Users have Searches - (these are not database searches, they are full-text searches that return a bunch of Documents)

*Searches have Documents <- However this need not be modeled. Search results will change over time.

*Users have Documents - any document that they have seen before from any search

*Tags are text strings

*User will be able to mark a Document with any number of Tags, but other Users will not be able to see their Tags

There are two issues I'm trying to manage here:

*

*Whenever a User makes a Search, I need to mark the returned Documents differently according to whether or not they've been seen before.  How? Is it reasonable to just collect the Documents from the Search (which will be returned 10 at a time) and then issue another SQL query for all Documents belonging to the User which have one of the doc_ids from the Search?  Seems clumbsy.

*Since a User can give a Document several Tags, and since other Users can't see them, how do I represent this in a database?  How do I query it reasonably?  I'm thinking that the Documents that belong to a User are represented by a join table - UserDocuments.  And then several Tags belongTo UserDocuments.  But then how do I present the Tags in-line with the Search results?  It seems to me that this involves me issuing a Search, finding which Documents I have seen before, and then finding which of those have Tags and then hitting the database again for each of these Documents and gathering their Tags.  This seems extreme, no?

One thing that's possibly confounding my understanding here is that I'm thinking through the Ruby on Rails ActiveRecord ORM.  I will eventually have to implement whatever solution I find within Rails.

A: One possible design:
   User
  1|  \1
   |   \
   \   N\
    \   Search                    Document
     \      \1                    1/    /1
      \      \                    /    /
       \     N\                  /M   /
        \   Search-Returns-Document  /
         \                          /
          \                        /
           \N                    M/
            User--Views--Document           Tag
                   1\                      1/
                     \                     /
                      \N                  /M
                   User-Marks-Document-With-Tag

A: Hopefully this will help:

*

*Have a Documents_Viewed table that contains the user_id, document_id, etc.. then when retrieving the search result join the viewed table on user and document which will let you know if they have read it.

*I would have another table Document_Tags that contain user_id, document_id, tag since you mentioned tags are user dependant
And example theoretical query would be:
SELECT * FROM Docuemnts d
         LEFT JOIN Document_Viewed dv ON (dv.document_id = d.id AND dv.user_id= ?)
         LEFT JOIN Document_Tags dt   ON (dv.document_id = d.id AND dv.user_id= ?)
         WHERE (search_criteria)

Not sure if that helps you at all


text:
Q: iOS using NSURLSessionUploadTask to upload file but didn't send httpbody I want to upload a big file using NSURLSessionUploadTask with the fileUrl API. The following code is what I wrote to upload a big file. I found these problems:

*

*Got a "time out" error in -URLSession:task:didCompleteWithError:.

*No http body found in the sent package (by using wireshark). Here is my code:
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

NSURL *url = [My URL];
fileName = [[DBList objectAtIndex:fileIndex] objectForKey:@"title"];
NSString *boundary = [self getBoundaryStr];

NSMutableData *dataSend = [[NSMutableData alloc] init];
[dataSend appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"target_path"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"/%@",[NSString stringWithFormat:@"%@/%@/%@",UploaderController.getDestination,APP_UPLOADER,[Functions getDateString]]] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_path\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
[request setValue:[@"authtok=" stringByAppendingString:[broker getNasAuthtok]] forHTTPHeaderField:@"Cookie"];
    [request setHTTPBody:dataSend];

NSString *tempFile = [NSTemporaryDirectory() stringByAppendingPathComponent:@"uploadFile"];
NSURL *uploadfileURL = [[NSURL alloc] initFileURLWithPath:tempFile];
NSURLSessionUploadTask *sessionUploadTask = [session uploadTaskWithRequest:request fromFile:uploadfileURL];
[sessionUploadTask resume];

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

anyone know where did I miss? Thank you very much!!
I am wondering about that the fileURL means a file including some post data and the uploaded file, am I right?
or just a file like an video for upload?

A: NSURLSessionUploadTask will ignore the http body.
You can add the file that you want to upload to your dataSend object along with the parameter that you already have. Then write dataSend to a local file. Finally create an uploadTask with the url of that local file.
The tricky part is to prepare that dataSend object. you can first try using NSURLConnection to send a post request. then migrate your code from NSURLConnection to NSURLSession using upload task.


text:
Q: Locating Extension Source Code in Firefox What folder in firefox is where the extension IDs or source code is located?
I want to query the content of this folder to determine what extensions are installed on the browser (with Tanium).
For example, in Chrome, you can find it in
%userprofile%\AppData\Local\Google\Chrome\User Data\Default\Extensions\


text:
Q: Why does my old commits re-appear every time I update the changelog? I am using the conventional-changelog-cli and I want to update my Changelog with my newest version (2.3.2).
But when I run the npm run changelog script, random old commits get added into the new version - why is that?
This is how my changelog should look after running npm run changelog:
2.3.2 (2019-07-19)
- Bug Fixes
- Customer info is now available and presented for new customers as well. (16ec727)
- Exclude return from new savings graph calculations (39e5a60)
- Policy is calculated more accurate in graph (15985fd)

Features
- Add build number to version number (in parentheses) under 'About app' (9ae985a)
- Build- and version number added to NINAA and Demo app (fff7962)

And this is how it actually looks:
2.3.2 (2019-07-19)
Bug Fixes
- Add condition for biometrics pop-up after NemID, if creating new user (0d226b6)
- Added native pop-up for enable biometrics in settings and onboarding (86d3773)
- Android splash screen is no longer stretched (28f9f4a)
- changed critical illness link and made error message better (a0d86fd)
- Changed new bonus features, to match new API (77e4c8e)
- changed rxjs & rxjs-combat to v6.2.1 (c38f216)
- Policy is calculated more accurate in graph (15985fd)
- Add build number to version number (in parentheses) under 'About app' (9ae985a)
- app version number is now visible under 'About app' in the menu (b46df6c)
- Bonus has been moved to disbursement page (50e92b0)
- Build- and version number added to NINAA and Demo app (fff7962)
- Change the welcome page and intro onboarding page with new text and design (3139790)
- Prompt user to activate biometrics login, if is not enabled, but the device supports it (7f4c5b3)
- SSL certificate error is now handled in the app with "update app" page (91c7329)
Reverts
- Contact-info notification removed (333e655)
- density removed from Android phones (c4ac51a)
- Face ID authentication is not yet supported on Android. Code reverted. (875771d)

All theese commits are OLD and are already represented further dwówn in their respected version. Why are they reappearing?
My script in package.json looks like this: "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r && git add CHANGELOG.md" and I also have a .npmrc file with git-tag-version = false.
I have searched the internet, but I cannot see what I am doing wrong?
I have tried to fetch my latest tags (using `git tag -l), and they look like this:
Build-v.-2.2.0.5
Build-v.-2.3.0.5
Build-v.2.2.0.4
Release-v.-2.2.0
Release-v.-2.3.0
Release-v.-2.3.0.5
Release-v.-2.3.1
v2.1.0-in-test-environments

My latest tag should therefore be 2.3.1, but when I run the changelog script, it compares the changes to v2.1.0-in-test-environments tag.
Anyone have any idea what I am doing wrong?

A: I think you need to remove the -r flag. If you look closely at the docs it says using this `WILL overwrite"
https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-cli#quick-start