text:
Q: express debug module not working I'm on Windows trying to use the debug module https://www.npmjs.org/package/debug
I installed express-generator
var debug = require('debug')('MyApp');
debug('log'); // I don't see this on console

I tried to debug the variable
console.log(debug); // I get function disabled() {}

How to enable it? shouldn't be enabled by default?

A: In case you want to set it in your js code,
myapp-debug.js
#!/usr/bin/env node

process.env['DEBUG'] = 'myapp:server';
var debug = require('debug')('myapp:server');

// ...

*

*I find it useful when there's a single shebanged executable file (on windows you'l need to set node to open .js files)

A: Output from debug functions created by the debug module are only displayed when you set the appropriate environment variable when starting your script. That is what lets you selectively enable debug output so that it's not an all or nothing method of displaying debug information. This is similar to how node.js core works for showing internal debug information on the console.
So in your example you would need to execute this at your shell prompt: DEBUG=MyApp node foo.js, where foo.js is your script containing var debug = require('debug')('MyApp');.
For Windows you'd need to do set DEBUG=MyApp on the command line, followed by node foo.js.

A: On windows set DEBUG=* or your configured name for debug e.g. myApp. In all js files whenever I want debug I configured just like following statement.
var debug = require('debug')('MyApp');

require('debug')('MyApp');  //This is very imp. You should configured some name for debug
while executing on windows
D:>set DEBUG=MyApp

D:>node <your app file>.js

D:> node foo.js

A: I was also faces the same issue. Finally i get the solution that
In windows

set DEBUG=* & node index.js

above command has to work. But in my this is not working on VS code terminal. But if is you write this command in scripts section of your package.json then it will work.

"start": "set DEBUG=app & node app.js"

Now you just need to write

npm start

on terminal and there you go

A: Windows does not set environment variables the way Linux and others do.
The solution is:
set DEBUG=my-application
npm start

A: I was trying to figure this issue out as well and it seems to me (at least on my Windows 10 machine) that the way to do this (at least from a non-linux command line; I am using the WebStorm build-in command line) is to include the '&' operator. So write something like this:
set DEBUG=my-app & node index.js

A: Make sure that process.env.DEBUG has been set before you create the debug logger.

A: Just in case you cannot run the express debug in terminal using

set DEBUG=express:* & node index.js

on Windows, put

"this": "set DEBUG=express:* & node --experimental-json-modules index.js"

inside "scripts" in package.json, then type

npm run this

in terminal. Thanks for reading!


text:
Q: Navigation Drawer в фрагменте Можно ли создать Navigation Drawer в отдельном фрагменте, если да то как ?
А если нет то как правельнее сделать, просто говорят что подход с фрагментами правельнее.

A: Нельзя. А если и можно — не нужно. Я думаю, что Вы немного не так поняли то, что Вам сказали. Хорошей практикой является использовать NavigationDrawer в одной активности, помещая в нее любое кол-во фрагментов.

A: Если часть интерфейса должна содержать NavigationDrawer, а другая - нет, то самым правильным решением будет разделить интерфейс минимум на две активити, одна из которых реализует NavigationDrawer и хостит фрагменты, которые тоже должны реализовать этот дровер, вторая - не реализует его и, при необходимости, хостит фрагменты, которые тоже не должны реализовать дровер, но связаны цепочками переходов или же переходит на другие активити, которые тоже не реализуют дровер.
Так же, если дровер должен реализовать только один экран, то использование фрагментов вообще сомнительно. Еще стоит заметить, что есть решения с дровером и несколькими экранами, которые не используют фрагментов.
В конце мое мнение о том, как определиться, нужны ли вам в вашем приложении фрагменты вообще

redpajama_set_name: RedPajamaStackExchange


text:
Q: Encrypting in Eloquent Model with AES_ENCRYPT Laravel has a built in Crypt class that allows encryption. The key is associated to the app and can be changed per request using something like:
$key = env('DEV_CACHE_KEY', 'DEV_CHANGE');
Crypt::setKey($key); // sets to new key
$action->descr = Crypt::encrypt($request->descr);
Crypt::setKey(Config::get('app.key')); // resets key to app
$action->save()

We save our data using a Memcached key that is saved on a specific server. This is set to be retrieved through the Memcached class, but for now I am using a defined key that is saved to the app environment. The defined key is used in MySQLs AES_DECRYPT() to decrypt the data that is saved. We are trying to keep backwards compatibility so I need to be able to do something like MySQLs AES_ENCRYPT().
The above code doesn't work because when I go to decrypt with below it returns empty.
$ynak = env('DEV_CACHE_KEY', 'DEV_CHANGE');;

return DB::connection('action_table')
    ->table('action AS a')
    ->select('a.*', DB::raw('AES_DECRYPT(`descr`, "'.$ynak.'") as `descr`'), DB::raw('(status LIKE "%completed%" OR status LIKE "%closed%") as isClosed'));

The way the table is set up is a bit bad as I inherited it, but I'm not allowed to make changes.
Is there a way to use Crypt::encrypt to equal a MySQL AES_ENCRYPT?

A: I didn't find a successful way to do this the way I'm asking. If another user posts an answer that can I will accept it, but this is my workaround.
Create a new instance of the model in some way. All ways are acceptable. It should just create the model and save into the database.
At that point you'll have an id (you should have an autoincrement id to reference).
$action = new Action();
...
$action->save();

$id = $action->id;
$key = env('DEV_CACHE_KEY', 'DEV_CHANGE');
DB::connection('action_table')->table('action')->where('id', '=', $id)->update([
    'descr' => DB::raw('AES_ENCRYPT("'.$request->descr.'", "'.$key.'")')
]);

This will do the AES encrypt as required and will create the new action. The only problem is that you cannot use $action->descr to successfully display the saved text / encrypted text. I do not need that ability so that does not matter as much.


text:
Q: How to differentiate between noncontiguous ranges? I am trying to perform a few operations on a dynamic number of ranges that are also dynamically sized. Each time the program is run, the number of noncontiguous ranges may change, as well as the size of the ranges. I identify my ranges by finding the delimiter in Column A, which is the underscore. Right now, VBA is recognizing the ranges seen below as two different areas, but selects them both at the same time when called to find the strings containing the delimiter, which is correct. I am transposing my range areas from one page to the next. In the first column of each range, Column A, there is a name, and the rest of the row contains various numbers. In each range, the string names vary, but they all correspond to the string names in the other range(s). For instance, all the first string names in each range end with _1. The second string name in the range (or the cell in the row beneath the first string), ends in _2, for each range. Below is a picture:

I know I can remove the blank row in between each range, but I don't think it is the best solution for my desired output. I would like to take the first row of the first area (in this example, A5:E5), transpose it, and paste it on a new sheet from (in this example) B5:B9. I would then like to go to the next area and do the same thing (so, copy A9:E9), transpose it, and paste it on the same sheet in the next column (so, C5:C9). Then I'd like to go back to my first range, and take the next row (A6:E6), tranpose it, and paste to D5:D9, then go to the next area and take (A10:E10), and so on until all the ranges have been pasted to the new page. So, ideally, I'd like to alternate between ranges and paste each row into a column, continuously through each range. This is my desired output:

I am having a hard time getting the data the way I want it, and know that I may not have the option to alternate between ranges, so I am up to hearing any ideas. Again, the number of ranges (or areas) can change with each run, and so can the size of the ranges. For this example, I had two ranges with 3 string names, but next run, I could have three ranges with 4 string names, so I can't hard code anything. The string names will not always be the same (input_x, output_x) so I can't hard code these either, but I can search for the delimiter, the underscore in the string name, as it will always be formatted into the string name.
My current output DOES copy and paste by each cell in the area, but this is the best I have gotten with what I have tried:

Here is my code (comments are some things I have been trying):
Dim myRange as Range
Dim c as Range, a as Range
Dim t As Long, m as Long
Dim delimiterItem as Variant
Dim newSheetName as String

newSheetName = ActiveSheet.Name
delimiterItem = "_"
t = 2

    With Sheets.Add(After:=Sheets(Sheets.Count))
        .Name = "Final"

        If myRange Is Nothing Then
            MsgBox ("Value not present in this workbook.")
        Else
            For Each a In myRange.Areas

                For Each c In a.Rows
                    Worksheets(newSheetName).Activate
                    c.EntireRow.Copy
                    'For m = Cells(myRange.Rows.Count, 1).End(xlUp).Row To 2 Step -1
                    'If Split(InStrRev(myRange.Cells(m, 1).Text, delimiterItem))(0) = Split(InStrRev(myRange.Cells(m - 1, 1).Text, delimiterItem))(0) Then

                    Worksheets("Final").Activate
                    Cells(8, t).Select
                    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                          False, Transpose:=True

                    t = t + 1
                    'Sheets("Final").Range("B8").Offset(0, (t - 2) * 2).PasteSpecial xlPasteValues
                Next c
             Next a
        End If
    End With

Any help or pointers in the right direction would be much appreciated. Thank you!
Sorry for the length of this question.

A: Here is an alternative example that works using memory-based arrays for speed as well as helping with the transposition and correct sizing of the data.
This algorithm assumes:

*

*You'll always have data sets that start with _1

*The data set numbers always increase sequentially, e.g. _1, _2, _3 etc

*There will always be an equal number of data "groups" as there are data sets.

My sample data looks like this:

First, I move the data into a memory-based array
Dim inData As Variant
inData = Sheet1.UsedRange.Value

Then based on these assumptions, in order to properly sort the results you need to figure out how many data sets you have. So I created this function that takes advantage of the Split function to get the number value following the underscore:
Private Function DetermineNumberOfSets(ByRef data As Variant) As Long
    '--- runs through the labels in the first column and separates
    '    the number value following the underscore to find the maximum
    '    count of data sets
    Dim max As Long
    Dim i As Long
    For i = LBound(data, 1) To UBound(data, 1)
        Dim tokens As Variant
        tokens = Split(data(i, 1), "_")
        If UBound(tokens) > 0 Then
            If max < tokens(1) Then max = tokens(1)
        End If
    Next i
    DetermineNumberOfSets = max
End Function

So the main routine calls
Dim dataSetCount As Long
Dim columnCount As Long
dataSetCount = DetermineNumberOfSets(inData)

'--- this determines how many columns are in the output data
Dim allSetsCount As Long
allSetsCount = dataSetCount * dataSetCount

By calculating allSetsCount in this way, you're effectively skipping any blank rows in your input data.
Now create an array to hold all the transposed data
'--- this determines how many rows are in the output data
Dim maxDataPointsCount As Long
maxDataPointsCount = UBound(inData, 2)

Dim outData As Variant
ReDim outData(1 To maxDataPointsCount, 1 To allSetsCount)

And finally run through your data to collect the data sets in order and transpose the data to the output array.
Dim setNumber As Long
For setNumber = 1 To dataSetCount
    '--- run through the data and pick out the data for this set
    Dim i As Long
    For i = LBound(inData, 1) To UBound(inData, 1)
        Dim thisSetNumber As Long
        thisSetNumber = WhatsTheDataSet(inData(i, 1))
        If thisSetNumber = setNumber Then
            '--- copy this set to the output
            Dim j As Long
            For j = 1 To maxDataPointsCount
                outData(j, outputColumn) = inData(i, j)
            Next j
            outputColumn = outputColumn + 1
        End If
    Next i
Next setNumber

Here's the whole module for all the code
Option Explicit
Option Base 0

Public Sub CollateData()
    Dim inData As Variant
    inData = Sheet1.UsedRange.Value

    Dim dataSetCount As Long
    Dim columnCount As Long
    dataSetCount = DetermineNumberOfSets(inData)

    '--- this determines how many columns are in the output data
    Dim allSetsCount As Long
    allSetsCount = dataSetCount * dataSetCount

    '--- this determines how many rows are in the output data
    Dim maxDataPointsCount As Long
    maxDataPointsCount = UBound(inData, 2)

    Dim outData As Variant
    ReDim outData(1 To maxDataPointsCount, 1 To allSetsCount)

    Dim outputColumn As Long
    outputColumn = 1

    Dim setNumber As Long
    For setNumber = 1 To dataSetCount
        '--- run through the data and pick out the data for this set
        Dim i As Long
        For i = LBound(inData, 1) To UBound(inData, 1)
            Dim thisSetNumber As Long
            thisSetNumber = WhatsTheDataSet(inData(i, 1))
            If thisSetNumber = setNumber Then
                '--- copy this set to the output
                Dim j As Long
                For j = 1 To maxDataPointsCount
                    outData(j, outputColumn) = inData(i, j)
                Next j
                outputColumn = outputColumn + 1
            End If
        Next i
    Next setNumber

    Dim outRange As Range
    Set outRange = Sheet2.Range("A1").Resize(UBound(outData, 1), UBound(outData, 2))
    outRange.Value = outData

End Sub

Private Function DetermineNumberOfSets(ByRef data As Variant) As Long
    '--- runs through the labels in the first column and separates
    '    the number value following the underscore to find the maximum
    '    count of data sets
    Dim max As Long
    Dim i As Long
    For i = LBound(data, 1) To UBound(data, 1)
        Dim tokens As Variant
        tokens = Split(data(i, 1), "_")
        If UBound(tokens) > 0 Then
            If max < tokens(1) Then max = tokens(1)
        End If
    Next i
    DetermineNumberOfSets = max
End Function

Private Function WhatsTheDataSet(ByVal label As String) As Long
    Dim tokens As Variant
    tokens = Split(label, "_")
    If UBound(tokens) > 0 Then
        WhatsTheDataSet = tokens(1)
    End If
End Function

A: Please try this code. It works only in memory and is very fast. I will try to explain for some lines, which may be looking strange, what they do. It works no matter of any ("_") character of the strings in A:A column.
This is the starting sheet ("Areas"):

And this is the result ("Final") sheet:

    Sub testTransposeMyAreas()
      Dim sh As Worksheet, rngUR As Range, j As Long, ii As Long
      Dim rng As Range, usedR As Range, rA As Range, arVal As Variant
      Dim shFin As Worksheet, k As Long, i As Long, ArTr() As Variant
  Set sh = ActiveWorkbook.Worksheets("Areas") ' obviously the sheet keeping areas to be transposed
    If Sheets(Sheets.count).Name = "Final" Then
        Set shFin = ActiveWorkbook.Worksheets("Final")
        shFin.UsedRange.Clear' for testing reason only
    Else
        Set shFin = Sheets.Add(After:=Sheets(Sheets.count))
        shFin.Name = "Final"
    End If

  Set rngUR = sh.UsedRange

  'define all the (really used range) of the worksheet:
  Set usedR = sh.Range(rngUR.Cells(1, 1).Address & ":" & _
        rngUR.Cells(rngUR.Rows.count, rngUR.Columns.count).Address)

  'tricky way to separtate the areas...
  Set rng = usedR.SpecialCells(xlCellTypeConstants)

  k = 0
  For Each rA In rng.Areas
    ReDim ArTr(rA.Columns.count) 'redim the array used to transfer data to the "Final" one
    arVal = rA.Value 'load the area range in ArVal array

     For i = 1 To rA.Rows.count
        For ii = 0 To rA.Columns.count - 1
            ArTr(ii) = arVal(i, ii + 1) 'fill the transfer array (diferently for each area row)
        Next ii
            'create the paste range and make the transfer:
            'to optimize the code, it does what you explain, but not in that suggested order
            'I mean, it firstly fill column B:B, then the column situated at how manu areas exists (once for each iteration)
            shFin.Range(Cells(5, 2 + k + j).Address & ":" & Cells(rA.Columns.count + 4, 2 + k + j).Address).Value = _
                                                    Application.WorksheetFunction.Transpose(ArTr) ': Stop
            k = i * rng.Areas.count ' used to define position of the next column to be filled
    Next i
    j = j + 1: k = 0
  Next
End Sub

If something unclear, do  not hesitate to ask for clarifications.
This code start from the assumption that all rows and columns number in an area are equal.
In order to better see how it works, I would suggest to un-comment the Stop command after ...Transpose(ArTr), make VBE window smaller and see what is happening on the worksheet, pressing F5 after each stop.


text:
Q: bash: preventing a redirected function's errors from mixing with output Want to get user's input from a function. However, the prompt ("Please answer y or n." in this case) is also included in the return value.
#!/bin/bash

input() {
    while true; do
        read -p "input y/n: " yn
        case $yn in
            [Yy]* ) yn="y"; break;;
            [Nn]* ) yn="n"; break;;
            * ) echo "Please answer y or n.";;
        esac
    done

    echo $yn
}

val=$(input)
echo "val is: $val"

If input an error value first and here is the results:
input y/n: other
input y/n: y
val is: Please answer y or n.
y

Thanks.

A: Echo your error to stderr (FD 2), not stdout (the default, FD 1):
echo "Please answer y or n." >&2

A: Better use a common global variable to pass values between the function and the caller. It's more efficient than summoning subshells with command substitution.
#!/bin/bash

input() {
    while true; do
        read -p "input y/n: " __
        case "$__" in
            [Yy]* ) __="y"; break;;
            [Nn]* ) __="n"; break;;
            * ) echo "Please answer y or n.";;
        esac
    done
}

input; val=$__
echo "val is: $val"


text:
Q: Trying to get the data from database and load it into datatable got exception I am trying to get the database values and binding to data table by using the following query
sql = @"SELECT member_Id, 30*memberToMship_ChargePerPeriod  / DateDiff(memberToMship_EndDate,
         memberToMship_StartDate) As monthlyamount,
         PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'),
         DATE_FORMAT(memberToMship_StartDate,'%Y%m'))  + (DAY(memberToMship_StartDate) < memberToMship_DueDay)+ (DAY(now()) > memberToMship_DueDay)-1  AS ExpPayments,
         SUM(memberToMship_InductionFee+memberToMship_JoinFee+
             (IF(mshipOption_Period='year',
             TIMESTAMPDIFF (YEAR ,memberToMship_StartDate, memberToMship_EndDate),
             TIMESTAMPDIFF (MONTH ,memberToMship_StartDate, memberToMship_EndDate)) * memberToMship_ChargePerPeriod)) as value
        FROM membertomships
        INNER JOIN mshipoptions on membertomships.mshipOption_Id = mshipoptions.mshipoption_Id";

and this is my code for getting the data to datable from database
string memberid;
double value = 0.0;
double expectedpayment=0.0;
double monthlypayamount=0.0;
int dueday = 0;

dt = xxxxxx.GetData(sql, mf);
if (dt != null && dt.Rows.Count > 0)
{
      memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
      monthlypayamount = Convert.ToDouble(dt.Rows[1]["monthlyamount"]);
      expectedpayment = Convert.ToDouble(dt.Rows[2]["ExpPayments"]);
      value = Convert.ToDouble(dt.Rows[3]["value"]);
}

but I am getting an error

" index out of range exception"

and error like this

"there is no row at position 1"

Would any one please help on this...

A: You should use index [0] for Rows on every line of code if you want to get all the data from the first row that was returned.  If you use Rows[1] and Rows[2] etc., then you are looking at the second row, and third row, etc., which is invalid if your query only returned one row of data.

A: You're checking for
dt.Rows.Count > 0

And then accessing rows 0, 1, 2, and 3, without checking if all of these rows exist. I think you've confused row numbers with columns, and should try
  memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
  monthlypayamount = Convert.ToDouble(dt.Rows[0]["monthlyamount"]);
  expectedpayment = Convert.ToDouble(dt.Rows[0]["ExpPayments"]);
  value = Convert.ToDouble(dt.Rows[0]["value"]);

A: if (dt != null && dt.Rows.Count > 0)
{

  memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();

  monthlypayamount = Convert.ToDouble(dt.Rows[1]["monthlyamount"]);
  expectedpayment = Convert.ToDouble(dt.Rows[2]["ExpPayments"]);
  value = Convert.ToDouble(dt.Rows[3]["value"]);
}

Your if statement is only checking for the existence of 1 or more rows. However, when you set monthlypayamount you are assuming a second row (dt.Rows[1]["monthlyamount"]). I think you need to use a foreach loop to iterate the results
foreach(DataRow row in dt.Rows)
{
   memberid = Convert.ToInt32(row["member_Id"]).ToString();
   monthlypayamount = Convert.ToDouble(row["monthlyamount"]);
   expectedpayment = Convert.ToDouble(row["ExpPayments"]);
   value = Convert.ToDouble(row["value"]);

   //logic here to use variable values before moving to next row
}

This will make sure you get access to all rows

A: It seems that you are trying to access row 1 however, row 1 doesn't exist. So, it seems that your query is returning only one row that is row 0. Try
   if (dt != null && dt.Rows.Count > 0)
{
memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(dt.Rows[0]["monthlyamount"]);
expectedpayment = Convert.ToDouble(dt.Rows[0]["ExpPayments"]);
value = Convert.ToDouble(dt.Rows[0]["value"]);
}


text:
Q: How do I optimize my ul navigation for mobile I am using Gridset to create a dynamic website. So far, things are going great. When I hit my breakpoint, it gracefully transitions to its mobile counterpart. However, I noticed that when I tested this on my phone, the site was way larger then the viewing area of my phone, even though it was using the correct mobile grid.
Here are two screen shots of the layouts in both forms, viewed from my desktop
Desktop
Mobile
However, when I view on my phone, you have to scroll horizontally to view the whole thing. I tried to fix this by using
<meta name="viewport" content="width=device-width, initial-scale=1">

This did what I wanted it too. And I thought I fixed my issue. Until I viewed it on my phone in horizontal mode. It cuts off the last navigation option 'contact'
Here is a screenshot from my phone
phone Screenshot
It looks fine on any tablet in any orientation. Phones work when in landscape mode.
So what my question ultimately is, how can I prevent my ul navigation from being cut off when viewed on phones in horizontal mode.
Here is a link to the website if you want to view the source
link
Edit*
Because i want to center the log in and inquire icons I had to remove the float. This prevents them from being on the same line though.
/*center icons on mobile*/
@media all and (min-width: 0px) and (max-width: 989px){
    #headerIcons img{
        display:block;
        float:none;
        margin-left:auto;
        margin-right:auto;

    }
}

Is there a better way to do this? Or is there a different way to make sure the images stay on the same line?

A: Remove the height: 60px from #navigation ...
... and it's fixed. The LI elements inside are floating, so they drop down to another row when there's not enough width to display all on one. The problem was the fixed height: the container (#navigation) was unable to expand to contain them when they drop down.
EDIT
If you want the nav items to all fit on one line, you'll need to use media queries to adjust the layout. For example, add this to your stylesheet:
@media screen and (max-width: 320px) { /* increase this width until you see the desired results */
    #navigationPages li {
        font-size: 1em;
    }
    #navigationPages li a {
        padding: 0.75em 0.6em;
    }
}

This media query reduces the font size and link padding for windows that are 320px wide or less. You can adjust that width as needed. If you are new to media queries, it would be a good idea to google about them. They are instrumental in mobile responsive website development.


text:
Q: Static C++ variable, without default constructor, loses value I have a class with a static variable. Since I need a constructor that isn't the default, I'm getting a little confused, but I hope I did it well
Class
class Object3D{

    public:
        static Object3D ObjControl;

        Object3D(); //this is here just for the initialization of the static variable

        Object3D(Triangle *mesh);

        Triangle *mesh;

};

At this point I need to create an Object3D and I do as below
bool Engine::OnInit() {

    if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
            return false;
        }

        if((Surf_Display = SDL_SetVideoMode(WIDTH, HEIGTH, BBP, FLAGS)) == NULL) {
            return false;
        }

        arma::colvec::fixed<3> upDirection;
        upDirection << 0 << 1 << 0;

        Camera cam(0.0, 0.0, 10.0, 10.0, 200.0, 90.0, upDirection);
        Camera::CameraControl = cam;

        arma::colvec::fixed<3> vertexA;
        vertexA << -1 << 1 << 0;

        arma::colvec::fixed<3> vertexB;
        vertexB << 1 << 1 << 0;

        arma::colvec::fixed<3> vertexC;
        vertexC << 0 << -1 << 0;

        Triangle tri(vertexA, vertexB, vertexC);
        Triangle mesh[1];
        mesh[0] = tri;
        Object3D obj(mesh);

        Object3D::ObjControl = obj; // PROBLEM! -> when the function extis from the OnInit ObjControl doesn't have anything inside.. it is like cleaned at the exit

        return true;
    }

The problem is the one that is inserted in the comment before the return.
Then when I need to pass that object to the rendering function, as below; the application closes because I'm trying to access to a location of memory not initialized
void Engine::OnRender(){

    Rendering.WfRender(Object3D::ObjControl, Surf_Display, 1);

}

I think I'm doing something wrong with the static variable, but I did the same with a static variable for a Camera class, as you can see in the Engine::OnInit, and there everything works well. So I have no clue what's going on.

A: The main issue in your program is that you make a Triangle instance (mesh) in your function and that you pass a pointer to your static member variable ObjControl.  When you leave the function, mesh is no longer available, so ObjControl points to an invalid instance.  This could be solved by storing an actual Triangle instead of a pointer to a Triangle in Object3D or a container of Triangles if more are needed.

A: *

*Does your Object3D class only hold onto the pointer to the mesh or take a copy of it?

*Does it implement a deep-copy copy constructor?

I ask because your mesh is going out of scope after being assigned to obj, and obj is going out of scope after being assigned to the static variable.  You need to either assign the mesh on the heap and hand that pointer to the static variable, or ensure the actual data is copied by correctly implementing the right constructors.
EDIT: Or, as this looks like games development, get it done quick and nasty!  ;-)
Object3D::ObjControl.mesh = new Triangle(vertexA, vertexB, vertexC);

...and lose the local variables tri, mesh, and obj.


text:
Q: Ag grid infinite datasource - set sort/filter model after first load Short version: Using an infinite row model on Ag-grid I need a way to set the filter and sort model after the first getRows() request (I can't set the column definitions before the first request is completed). Does anyone have a way to do this without triggering more getRows?
Full Context:
I am using Ag-grid with the infinite row model for an Angular app. We're using it to view filter/sort large flat datasets. The grid correctly handles it so that when a user changes a filter or sort on the grid, the getRows request in the datasource is triggered with the new filter/sort model.
I also need to have routing on the app. If a user opens a grid of a certain dataset, adds a filter/sort this should be reflected in the url. The idea being that a user can then share the link of the page and if opened in a new window the page will automatically load the data that the first user was looking at. I have the routing working as well. It's also worth noting that we will never know exactly what the column definitions will be when loading a new grid.
Issue:
When the second user opens the link the grid loads and sends a request to the server with the correct filters. However the grid's sort/filter state doesn't reflect this, which is fair enough since we've just initialised a new grid and haven't set the sort/filter model, but it needs to be set otherwise when the user scrolls the original filters will no longer be applied.
However I am having trouble actually setting the sort/filter model as well as struggling to not trigger additional requests to the server.
We are generating the column definitions after the first load of data, so what I have tried is after generating the column definitions calling gridApi.setSortModel(sortModel) and gridApi.setFilterModel(filterModel) as well as setting a global variable to tell the grid not to ask for rows again after setting the models.
This is not working. The getRows() request is triggered again, but for some reason the filter and sort models are still empty. Here is a rough idea of the datasource I'm using:
createDatasource(grid): IDatasource {
  return {
    getRows: params => {
         if (grid.ignoreRequest) {
            grid.ignoreRequest = false;
            params.failCallback();
            return;
         } else {
             const query = generateQuery(params);
             this.api.getData(query).then(response => {
                 if (!grid.columnDefs.length) {
                     const sortModel = generateSortModel(query);
                     grid.ignoreRequest = true;
                     grid.columnDefs = grid.generateColumnDefs(response[0]);
                     grid.gridApi.setSortModel(sortModel);
                 }
                 params.successCallback(response, response.length);
             } handleErr);
         }
    }
  };
}

(Note the above code is slightly simplified, but the structure is the same).
When configured as above the grid will load the data once, correctly create column definitions, then hit the getRows() request again, which will correctly handle the ignoreRequest param but the sortModel isn't set correctly. Also despite the first request working correctly and setting rows, after the second request is ignored there is no row data in the grid, just the column definitions.
I found someone asking a similar thing on git hub, but the examples haven't helped me as I need to set column definitions after the first request, not before: https://github.com/ag-grid/ag-grid/issues/1785
Any help would be appreciated.

A: There are 2 things wrong with the code in the question.

*

*The column definitions need to be set using the grid api, not just setting a variable. Setting the variable on the grid means the columns will be displayed correctly, but unless gridApi.setColumnDefs(columnDefs) is called, then the subsequent call to set the sort or filter model won't work. Once this change is made the sortModel will be correctly reflected.

*In other examples I had seen, failCallback() was being used when we want to ignore the request. For me this was just setting the rows blank, perhaps that method has been updated to do that since those other solutions were posted. Instead it should be changed to successCallback. This method requires the row data, so before setting the filter/sort model the rowData needs to be persisted in some way.
Here is an updated (basic) version of the getRows() function.
createDatasource(grid): IDatasource {
  return {
    getRows: params => {
         if (_.get(grid, 'ignoreRequestount', 0) > 0) {
            grid.ignoreRequestCount--;
            params.successCallback(grid.rowData);
         } else {
             const query = generateQuery(params);
             this.api.getData(query).then(response => {
                 grid.ignoreRequestCount = 0;
                 const sortModel = this.ODataQueryToSortModel(query);
                 const filterModel = this.ODataQueryToFilterModel(query);
                 grid.columnDefs = gridTab.generateColumnDefs(response[0]);
                 grid.gridApi.setColumnDefs(grid.columnDefs);
                 if (_.keys(filterModel).length) {
                     grid.ignoreRequestCount += 1;
                     grid.gridApi.setFilterModel(filterModel);
                 }
                 if (sortModel.length) {
                     grid.ignoreRequestCount += 1;
                     grid.gridApi.setSortModel(sortModel);
                 }
                 params.successCallback(response, response.length);
             } handleErr);
         }
    }
  };
}

Again this is simplified, but covers it mostly. I had to adjust the check if it should ignore the request as in some cases the filterModel and sortModel could be being set, which would cause multiple triggers. It's a bit hacky, but it will have to do unless someone has a better solution...


text:
Q: MIPS:what's instruction lui $1,4097 for? Original:

After Compact:

So how is the process of this? What is lui here for?

A: lui is "Load upper immediate" and puts the the 16 bit immediate in the upper half of a register. In C-like notation $r = imm16 << 16. The register $1 is used as an assembler temporary. In this case the lw got divided into a lui and lw to load a full 32 bit address.
The instructions li and la are pseudo instructions (see Wikipedia) and they get replaced by a lui followed by a ori, addiu or andi.
Your assembler optimized the lui instructions away because the pseudo instructions and loads only need 16 bit values and addresses and not the full 32 bit values. Without optimization the assembler must assume that the full 32 bit values are needed.


text:
Q: Github: Define that only Beta branch can be merged into master branch? I want to set som restrictions or somehow define that only the beta branch, and poitentially any "hotfix" branch, can be merged into the master branch. Is this possible in GitHub?
The reason is to avoid accidental pull requests from a feature or development branch into the master branch.
Also, is it possible to have pull requests default to merge into a development branch, rather than default to merge into master?


text:
Q: How can I construct a bar chart with two drop downs menus How do I construct a bar chart in dash with two drop down menus? In my example the data is stored as follows, which makes it different than other examples:
table example
I understand how to do it with one dropdown and have tried a few things for the second. However, I cant figure out how the function would need to look like with the second input.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

df = pd.read_excel('cities.xlsx',engine='openpyxl')

app = dash.Dash()

app.layout = html.Div([
        html.Div([
            dcc.Dropdown(
            id= "selected_statistic",
            options=[
            {'label': 'Population', 'value': 'pop'},
            {'label': 'Area', 'value': 'a'},
            {'label': 'Density', 'value': 'dens'}
        ],
            value='pop')
],          style={'width': '48%', 'display': 'inline-block'}),

        html.Div([
            dcc.Dropdown(
            id= "year",
            options=[
            {'label': '1990', 'value': '1990'},
            {'label': '2000', 'value': '2000'},
            {'label': '2010', 'value': '2010'},
            {'label': '2020', 'value': '2020'}
        ],
        value='1990'),

],          style = {'width': '48%', 'float': 'right', 'display': 'inline-block'}),
        dcc.Graph(id='graph')
])

@app.callback(Output('graph', 'figure'),
              [Input('selected_statistic', 'value'),
               Input('year', 'value')])

def update_figure(selected_statistic,year):
    df2 = df[df["statistic"] == selected_statistic]
    fig = px.bar(df2[df2],
                x="city",
                y="value",
                color="city")
    return fig

if __name__ == '__main__':
    app.run_server()

A: I think you want something like this:
df2 = df[df["statistic"].eq(selected_statistic) && df["year"].eq(year)]

assuming that your df has a year column.


text:
Q: Javascript replace string with 8 and 9 doesn't work...but other numbers do...? Check out this script... run and see the oddity..
http://jsfiddle.net/BjJTc/
From jsfiddle
var m = 'Jan07';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));

var m = 'Jan08';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));

var m = 'Jan09';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));

var m = 'Jan10';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));

A: You are running into a problem with the radix.  Javascript is interpreting 07, 08, 09 as octal numbers.  Decimal 7 and Octal 07 evaluate to the same number, while 8 & 9 do not.
Include the base 10 radix as the second param to all of your parseInt() calls:
var m = 'Jan08';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, ''), 10));
// ------------------------------^^^^^^

A: This is an Octal issue: try parseInt(val, 10). The leading zero makes it believe it's octal. parseInt takes a second optional parameter radix:

radix  An integer that represents the radix of the above mentioned
  string. While this parameter is optional, always specify it to
  eliminate reader confusion and to guarantee predictable behavior.
  Different implementations produce different results when a radix is
  not specified.

So:
parseInt('09') // 0
parseInt('09', 10); // 9

A: If you are trying to get the year from the string you have, you could attempt to parse it as a date then extract the number of years...
var m = 'Jan07';
var d = Date.parse('01' + m); // Parse the 1st of the month
var y=Math.floor(d/(1000*60*60*24*365.24)) + 1970; // Convert to years since 1970, then add 1970
alert(y);

Not to most elegant of solutions, but will get you the year from your MMMyy format.

A: Or just lose the leading letters and any leading 0-
m='Jan08';
mm=/^\D+0?/,'');
alert(m.replace(mm, ''));


text:
Q: Index for a table with multiple JOIN varchar conditions I'm trying to do sort of a matching query to match recording from table A to table B using multiple columns. But for some reason the query is running very slow. I tried to experiment with different index combinations for the joined table but they are not being used, which is why it's always doing a full table scan.
SELECT
    nc.id, nc.firstName, nc.lastName,
    nc.firmName, nc.location,
    nc.city AS city, nc.state AS state,
    ac.id, ac.lastName, ac.firstName, ac.middleName,
    IFNULL(ac.suffixName, '') AS suffixName, ac.firmName, ac.city, ac.state
FROM
    NormalContacts AS nc
JOIN
    AllContacts AS ac ON ((nc.firstName = ac.firstName AND nc.lastName = fa.lastName) OR (nc.firstName = fa.middleName AND nc.lastName = ac.lastName))
        AND (ac.city = nc.city AND ac.state = nc.state)
JOIN
    FirmInputTable AS fit ON (fit.firmName = fa.firmName AND fit.otherFirmName = nc.firmName)
WHERE
    nc.crdNumber IS NULL AND nc.city IS NOT NULL AND nc.state IS NOT NULL AND nc.firmName IS NOT NULL

NormalContacts is 1,000 records while AllContacts is 337,250 records. All fields in the JOIN condition are varchar.
Here is the EXPLAIN result:

*fa in the screenshot AllContacts, sorry for the typo.
Hope anyone can suggest a way to optimize this query or tell me what I'm doing wrong. Thanks in advance!

A: The Optimizer will look at indexes and statistics to decide what order to do the the tables.
In the following, I will assume that ON says only how the tables relate to each other and WHERE is only for filtering.
The "first" table will probably (but not necessarily) be the one with the most selective WHERE condition(s).  So, it's INDEX needs to focus on the columns in WHERE.  (Sometimes GROUP BY or ORDER BY come into play.)
The other tables in the JOIN sequence will be reached into via "Nested Loop Join".  This is where "for each row in the previous table(s), fetch the row(s) in the current table".  To do this fetch it will use any WHERE clauses relevant to the table and any thing in the ON that mentions this table (and probably previous tables).  So, think about the INDEX for this table from the WHERE and ON conditions.
Since you cannot always predict what order the Optimizer will walk through the tables, it is best to add index(es) to accommodate each possible order.
A typical shortcut is when WHERE mentions only one table.  That table is almost certain to be picked first.
How to build a good index for a particular table, given the WHERE/ON things leading into it?  See my cookbook
For your case...
You seem to have properly split the ONs and WHEREs -- Good.
nc seems to be the  only table mentioned in WHERE, so we can probably assume that the Optimizer will start with it.
IS NULL is similar to = constant, but IS NOT NULL is like a range, not not as easy to optimize.  I recommend
nc:  INDEX(crdNumber, state)

(Here, I am guessing at which nc column is most/least likely to be NULL.)
After nc, only ac (aka fa???) could come:
ON    ((...) OR (...))
  AND ac.city = nc...
  AND ac.state = nc...

OR is usually not possible to index or optimize, so we are left with
ac:  INDEX(city, state)  -- in either order

Possibly lastName could be pulled out (after fixing ac/fa) of the OR, thereby leading to
ac:  INDEX(city, state, firstName)  -- in any order

Finally, fit:
ON    fit.firmName = ...
  AND fit.otherFirmName = ...

leads to
fit:  INDEX(firmName, otherFirmName)  -- in either order

Please fix the fa in the query; then I will modify my answer if needed.
Note:  INDEX(a,b) is better than INDEX(a), INDEX(b) in cases like these.


text:
Q: Positioning a 3d object in the corners of the canvas - three.js I have a 3d object that I want to be able to automatically position in either corner of my canvas regardless of the canvas's size.

I came across this stackoverflow solution:

and applied the following code to my object:
mesh.position.set(-(window.innerWidth), (window.innerHeight), 0)

which results in this:

As you can see it is only part of the object and I would like to have it positioned in full view, like this, but it would need to look consistent on different canvas sizes (maybe for mobile use):

I have also attached an example of my setup

I just need some pointers on how I can achieve this, so any help would be most appreciated.
Thanks.

A: You can use THREE.Raycaster() with THREE.Plane():

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.set(0, 5, 10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var box = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshLambertMaterial({
  color: "green"
}));
scene.add(box);

var plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0, 1));

btnMove.addEventListener("click", onClick, false);

var raycaster = new THREE.Raycaster();
var corner = new THREE.Vector2();
var cornerPoint = new THREE.Vector3();

function onClick() {
  corner.set(-1, -1); // NDC of the bottom-left corner
  raycaster.setFromCamera(corner, camera);
  raycaster.ray.intersectPlane(plane, cornerPoint);
  box.position.copy(cornerPoint)
    .add(new THREE.Vector3(1, 1, -1)); // align the position of the box
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}

#btnMove {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<button id="btnMove">Move bottom-left</button>


text:
Q: Baseball card problem A young baseball fan wants to collect a complete set of 262 baseball cards.
The baseball cards are available in a completely random fashion, one per package of chewing gum.
How many boxes of chewing gum does the fan need to buy in order to have a full set with
probability ≥ $0.99$?
I was told I need more info to solve this problem. However, this is all the info given. Is this missing data?

A: As lulu noted in a commented, this is the coupon collector's problem. The probability of having a complete set of $m$ coupons after drawing $n$ coupons is
$$
\def\stir#1#2{\left\{#1\atop#2\right\}}
\frac{m!}{m^n}\stir nm\;,
$$
where $\stir nm$ is a Stirling number of the second kind. For a derivation of this probability, see Probability distribution in the coupon collector's problem.
You have $m=262$ and want the probability to be at least $0.99$. Since we can't easily solve for $m$, we should try to get a good estimate so we don't have to compute too many Stirling numbers. The number of coupons you need to draw to have all coupons with probability $0.99$ should be close to the number you need to draw to make the expected number of undrawn coupons $0.01$. So
$$
m\left(1-\frac1m\right)^n\approx0.01\;,
$$
and solving for $n$ yields
$$
n\approx\frac{\log0.01-\log m}{\log\left(1-\frac1m\right)}\approx2660.37\;,
$$
and indeed calculating the exact probability for the values adjacent to $n=2660$ shows that, as Byron found, the probability $0.99$ is first reached at this value.

A: I answered a similar problem here: Birthday-coverage problem
Setting $n=262$ there, I calculate that with $2659$ packages the chance of getting a complete collection is $0.9899956985$,
while with $2660$ packages the chance is $0.9900336992$.
So the answer to your question is $2660$.

A: Technically, you need to know how many boxes of chewing gum were produced.  For example, if they only manufactured a total of $262$ boxes, and "random" meant simply that you don't know which card is in which package, then obviously you just need to buy all $262$ boxes, in which case you are assured, with $100$% probability, that you have a complete set.  So the one piece of information that's missing, I'd say, is whether the problem is making the tacit assumption that there is, in effect, an infinite supply of boxes of chewing gum.


text:
Q: C# ReactiveUI MessageBus from Process not updating ListBox until process ends I have a .NET 5 ReactiveUI application that launches a process. I am trying to get real time logs from the process to a ListBox. I have had some success getting the logs, but only after the process ends; then I get all of the logs at one time. I have observed that the MessageBus listener I created is called in realtime, but the UI is not reflecting the update until after the process ends. Below are some code snippets.
Any help will be appreciated. Thank you in advance!
Process Code:
public void Execute(Payload payload)
{
    using Process process = new()
    {
        StartInfo = CreateStartInfo(payload)
    };

    process.ErrorDataReceived += delegate(object sender,
                                            DataReceivedEventArgs e)
    {
        MessageBus.Current.SendMessage(new LogEventArgs(e.Data));
    };
    process.OutputDataReceived += delegate(object sender,
                                            DataReceivedEventArgs e)
    {
        MessageBus.Current.SendMessage(new LogEventArgs(e.Data));
    };

    MessageBus.Current.SendMessage(new LogEventArgs("Starting Process."));
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    StreamWriter myStreamWriter = process.StandardInput;
    CancellationTokenSource tokenSource = new();
    CancellationToken token = tokenSource.Token;

    Task.Run(() =>
                {
                    while (true)
                    {
                        myStreamWriter.WriteLine();
                        Thread.Sleep(250);
                        if (token.IsCancellationRequested)
                        {
                            break;
                        }
                    }
                },
                tokenSource.Token);

    process.WaitForExit();
    MessageBus.Current.SendMessage(new LogEventArgs("Process Finished."));
    tokenSource.CancelAfter(500);
}

private static ProcessStartInfo CreateStartInfo(Payload payload)
{
    string applicationPath = Path.Combine(payload.Directory,
                                            "Application");
    return new ProcessStartInfo
    {
        FileName = $"{applicationPath}.exe",
        WindowStyle = ProcessWindowStyle.Hidden,
        UseShellExecute = false,
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        RedirectStandardInput = true
    };
}

ViewModel Code:
public class LogPaneViewModel : ReactiveObject
    {
        public ListBox LogListBox { get; set; }

        [Reactive]
        public ObservableCollection<string> LogsList { get; set; } = new();

        [Reactive]
        public ReactiveCommand<Unit, Unit> ClearLogs { get; set; }

        public LogPaneViewModel()
        {
            MessageBus.Current.Listen<LogEventArgs>()
                      .Subscribe(OnLogMessageReceived);

            ClearLogs = ReactiveCommand.Create(OnClearLogClicked);
        }

        private void OnLogMessageReceived(LogEventArgs args)
        {
            // *** This is called in real time by the process.
            // But the ListBox is not updating until the process ends.
            LogsList.Add(args.Text);
            LogListBox.ScrollIntoView(args.Text);
        }

        private void OnClearLogClicked()
        {
            LogsList.Clear();
        }
    }

Code Behind Code:
    public partial class LogPane : ReactiveUserControl<LogPaneViewModel>
    {
        public LogPane()
        {
            InitializeComponent();

            ViewModel = App.ServiceProvider.GetRequiredService<LogPaneViewModel>();
            ViewModel.LogListBox = LogsList;

            this.WhenActivated(disposableRegistration =>
            {
                this.OneWayBind(ViewModel,
                                vm => vm.LogsList,
                                view => view.LogsList.ItemsSource,
                                s => s)
                    .DisposeWith(disposableRegistration);

                this.BindCommand(ViewModel,
                                 vm => vm.ClearLogs,
                                 view => view.ClearButton)
                    .DisposeWith(disposableRegistration);
            });
        }
    }

A: My process code waits until the process was finished. This led to the thread blocking the UI thread. As GlennWatson suggested and mm8 hinted, this was solved by wrapping the launching of that class in Task.Run(). Thank you for the help!


text:
Q: How to Call Python from R in a Windows OS? I'm looking for a way to call python within R on a Windows operating system. Since there appears to be no readily available R package for this (at least no package that's been updated recently), I'm looking for leads on how to write a set of commands in an R script that can then be sent in batch mode to python.
In short, how can I call python from R in a Windows OS?
Edit: To clarify, I am not asking about calling R from python; rather I am asking about calling python from R.
Update: Based on what I've gathered so far, here's a basic set of commands on running python from R in a Windows OS:
# (1) basic python commands called from R
system('python -c "a = 2 + 2; print a"')
system('python -c "a = \'hello world\' ; print a; import pandas"')

# (2) if you have a python file you've already created (which I've referred to as "my.py"), then you can run it in R as follows:
system("python C:\\Users\\Name\\Desktop\\my.py")

# or alternatively:
system('python -c "import sys; sys.path.append(\'C:\\Users\\Name\\Desktop\'); import my;"')

Neither of these approaches is at the level of interactivity needed for fluid data analysis using python in R on a Windows OS. The most straightforward solution might be to write a simple R function that (1) exports a specified R data frame to python, (2) parses python syntax written in R (using stringr and system('python -c')), and then (3) optionally exports the data back to R. It'd be a pseudo-interactivity in R based on updating a temporary python file through the R console.

A: You can use this package PythonInR

A: Make a python file....
# -*- coding: utf-8 -*-
"""
Created on Wed Mar  9 09:55:46 2016

@author: Subhash Jaini
"""

import pandas as pd
d = {'First' : [1., 2., 3.],'Second' : [1,2,3]}

AA = pd.DataFrame(d)
print(AA)

save it to a place (I used c:/deleteme/pythonRun.py)
In R, run this code.
#calls the python script to run in shell
BlobReturnedFromPython = shell('python c:/deleteme/pythonRun.py',intern=TRUE)
#get the first line and turn it to your header
HEADER = gsub(" ","",unlist(strsplit(as.character(BlobReturnedFromPython[1]),"  ")))[-1]
#all the rest of the data is non header data
NONHEADER = BlobReturnedFromPython[2:(length(BlobReturnedFromPython)-1)]
#turnthat blob (which is seperated by about 4 spaces )
DATA = data.frame(sapply(NONHEADER,function(x){unlist(strsplit(x,"    "))}))
#brings those names into the data set
names(DATA) <- HEADER
DATA

A: I have found a solution that might actually work on a Windows OS:
http://gallery.rcpp.org/articles/rcpp-python/
The article describes a setup for Ubuntu, where Rcpp is used as an intermediate layer between R and Python. Although I have not tried that yet, I currently see no reason why this solution should not work on Windows as well.

A: If you are looking for calling python from R then try rPython but it isn't for windows OS.
Or try RSPython has a weak support for windows. An other useful link.
At last you can try to use something like Cygwin to execute linux application on your windows OS. More work load will be to use some virtual environments like VMware or VirtualBox on windows and install linux and carry out your work.


text:
Q: Replacing last 6 digits from a number with 6 random digits I am looking to replace the last 6 digits from a number with 6 random numbers. How do I do that in Notepad++ or TextCrawler Pro?
I have a bunch of text files and I want to make the software scan for all the 9 digits combinations and replace the last 6 ones randomly.

A: Neither of the two programs appears to support variables in the "replacement" field (other than capture groups from the original matched text). So they cannot produce random replacements; at best, they can reorder the existing digits in some fixed manner (e.g. 123456789 → 123496857 every time).
However, I feel obligated to suggest a Perl oneliner instead:
perl -p -e 's/\b(\d{3})\d{6}\b/$1.sprintf("%06d", int(rand(1000000)))/ge'

The regex \b(\d{3})\d{6}\b works the same as in Notepad++ (which uses PCRE); it matches 9 digits and captures the first 3 for later use.
In Perl's s///, the /e flag indicates that the replacement is to be interpreted as actual Perl code, so it can call functions and generate random numbers. You can also achieve the same in other languages which support a replacement callback (e.g. in Python or Ruby).
Usage:
perl -p -e '...' < file.txt > file_new.txt        (create a new file)
perl -i -p -e '...' file.txt                      (update in-place)

A: I am looking to replace the last 6 digits from a number with 6 random numbers.
You cannot do this directly in Notepad++.
However, you could install the python script plugin and write some code to do so.

Python Script for Notepad++

*

*Full programmatic access to Notepad++ features and menus

*Full programmatic access to all of Scintilla features

*Call other plugin menu items

*Assign menu items, shortcuts and toolbar icons to scripts

*Process Notepad++ and Scintilla events, direct from a Python script

*Python console built-in

*Full regular expression support for search and replace - script Python regular expression replaces

*Start external programs and pipe the output direct to a Notepad++ document, or filter it, or simply to the console window

*Full documentation for all the objects and methods

Source Python Script - Plugin for Notepad++

A: You can run a python script within the PythonScript plugin.
If it is not yet installed, follow this guide
Create a script (Plugins >> PythonScript >> New Script)
Copy this code and save the file (for example random.py):
import re
def calculate(match):
    # generate a random integer in range 0-999999, cast to string and fill with 0 to the left
    return str(random.randint(0,999999)).zfill(6)
editor.rereplace(r'(?<=\b\d{3})\d{6}\b', calculate)

*

*Open the file you want to change

*Run the script (Plugins >> PythonScript >> Scripts >> random)

*Done

Regex explanation:
(?<=        # positive lookbehind, zero-length assertion that makes sure we have before
    \b      # a word boundary
    \d{3}   # 3 digits
)           # end lookbehind
\d{6}       # 6 digits
\b          # word boundary

Given:
abc 123456789 xyz
def 987654321 tuv
ghi 111111111 opq
klm 222222222 rst
123456789123465
111111111111111

Result for given example:
abc 123535410 xyz
def 987865493 tuv
ghi 111414834 opq
klm 222382724 rst
123456789123465
111111111111111


text:
Q: php не загружает несколько файлов Есть вот такой код:
<?php
foreach ($_POST as $index => $value) {
    $$index = $value;
}

$uploaddir = './files/';

for ($i=0; $i<=count($_FILES); $i++) {
    $uploadFile = $uploadDir.basename($_FILES['userFile']['name'][$i]);
    if (copy($_FILES['userFile']['tmp_name'][$i], $uploadFile))
    {
    echo "
Файл успешно загружен на сервер
";
    }
    else { echo "
Ошибка! Не удалось загрузить файл на сервер!
";}
}
?>

<form action="mce.php" method="post" enctype="multipart/form-data">
    <input name="userFile[]" type="file" multiple>

    <input type="submit" value="Загрузить">
</form>

По идее должно загружать много файлов, но больше двух файлов не грузит. Я понимаю, что какая то ошибка в цикле, но что то не могу сообразить как исправить. Что не так?

A: В вашем примере count($_FILES) всегда будет единичкой, так как $_FILES['userfile'] будет содержать подмассив информации о нескольких файлах, а не сам $_FILES.
Также ошибка в этой строке $i < count($_FILES['userFile']['name'], у вас стояло <=, но надо ставить просто знак меньше, так как отчет от нуля.
Ну и применяйте move_uploaded_file, по крайней мере по этому пути пошли разработчики.
<form action="uploadfiles.php" enctype="multipart/form-data" method="post">
    <input type="file" name="userFile[]" multiple>
    <input type="submit" name="submit">
</form>
<?php

if (isset($_POST['submit'])) {

    $uploaddir = __DIR__ . '/files/';

    for ($i = 0; $i < count($_FILES['userFile']['name']); $i++) {
        $uploadFile = $uploaddir . basename($_FILES['userFile']['name'][$i]);

        echo $uploaddir . basename($_FILES['userFile']['name'][$i]);

        if (move_uploaded_file($_FILES['userFile']['tmp_name'][$i], $uploadFile)) {
            echo "
Файл успешно загружен на сервер
";
        } else {
            echo "
Ошибка! Не удалось загрузить файл на сервер!
";
        }
    }
}


text:
Q: Duplicates in accessing address book For some reason, I keep getting duplicates on a lot of the contacts that I'm able to access with my code. Any reason why?
var error: Unmanaged<CFError>?
addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

   if let people = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(self.addressBook, nil, ABPersonSortOrdering(kABPersonSortByFirstName)).takeRetainedValue() as? NSArray {
        for record in people {
            //var contactPerson: ABRecordRef = record
            var contactName: String = ABRecordCopyCompositeName(record).takeRetainedValue() as String

            var number = ""

            var phones: ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue()

            for j in 0..<ABMultiValueGetCount(phones) {
                number = ABMultiValueCopyValueAtIndex(phones, j).takeRetainedValue() as! String
                break
            }

            if (number != "") {
                var newPerson = personInfo(name: contactName, number: number)
                allContacts.append(newPerson)
            }

           self.tableView.reloadData()
        }
    }

A: James Richards Please Use the Contacts frame work instead of using address book.
First you shoud add Contacts framework through Build Phases->Link Binary with Libraries->add(click +)->choose contacts framework
import Contacts

Then
let status = CNContactStore.authorizationStatusForEntityType(.Contacts)
if status == .Denied || status == .Restricted {
        // user previously denied, so tell them to fix that in settings
        return
}

// open it

let store = CNContactStore()
store.requestAccessForEntityType(.Contacts) { granted, error in
        guard granted else {
            dispatch_async(dispatch_get_main_queue()) {
                // user didn't grant authorization, so tell them to fix that in settings
                print(error)
            }
            return
}

// get the contacts

var contacts = [CNContact]()
let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])
   do {
      try store.enumerateContactsWithFetchRequest(request) { contact, stop in
                contacts.append(contact)
         }
   }
   catch {
            print(error)
         }

        // do something with the contacts array (e.g. print the names)

        let formatter = CNContactFormatter()
        formatter.style = .FullName
        for contact in contacts {
            print(formatter.stringFromContact(contact))
        }
 }

The Output Results
Optional("John Appleseed")
Optional("Kate Bell")
Optional("Anna Haro")
Optional("Daniel Higgins Jr.")
Optional("David Taylor")
Optional("Hank M. Zakroff")

Link 1
Apple Document
Contacts


text:
Q: PostgreSQL function returning multiple DIFFERENT datasets I have a seemingly simple question, but can't find an answer for it. So far, I've been working with MSSQL, but recently a new project came up which uses PostgreSQL for all DB related stuff, and I don't have as much experience with postgre as I'd like to have. The thing is I need to write a simple function which returns, let's say N different datasets. In MSSQL this simply would look like
-- Stored procedure creation statements
SELECT * FROM dbo.Table1

SELECT * FROM dbo.Table2

...
-- End stored procedure

Keep in mind, that all tables are different in structure (column count, names and etc.)
So far, all I've found that could help me, is SETOF, but it seems that by using it, I can only return results of same rowtype.
Any kind of help would be appreciated.


text:
Q: LU decomposition with PartialPivLU I have the following code in MATLAB that does an LU decomposition before trying to calculate lamb which I've included to give some context.
P=[1,2,3;4,5,6;7,8,9];
U=[0;1;2];
[F,J]=lu(P);
Jlamda=F\U;
lamb=J\Jlamda;

F is:
0.142857142857143   1                   0
0.571428571428571   0.500000000000000   1
1                   0                   0

U is:
7                   8                   9
0                   0.857142857142857   1.71428571428571
0                   0                   1.11022302462516e-16

When I try to replicate this in Eigen with the following code:
MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << F << endl;
cout << endl;
cout << J << endl;

Which prints:
1                    0                  0
0.142857             1                  0
0.571429             0.5                1

7                    8                  9
0                    0.857143           1.71429
0                    0                  1.11022e-16

Whilst I can obviously handcraft a matrix to transform the rows of F in C++ to that of the F from MATLAB I am not sure how to do that dynamically.
Is PartialPivLU the best way to go about this, or am I missing something more trivial?

A: By calling [F,J]=lu(P), the resulting matrix F is a permuted lower triangular matrix. You can call the function as [F,J,perm]=lu(P) to receive F as a truly lower triangle matrix and P as the separate permutation matrix so that F*J = perm*P. By default, the line
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();
using Eigen returns the true lower triangular matrix. If you want the permuted lower triangular matrix like Matlab returns, then you can store the permutation matrix in Eigen by calling permutationP and then multiplying this matrix by F.

A: The answer by DCSmith is pretty close, however it seems that you must also call transpose() on the permutation matrix in order to get the correct result:
MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();
MatrixXd perm = lu.permutationP().transpose();
MatrixXd F1 = perm * F;

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << perm << endl;
cout << endl;
cout << F1 << endl;

Prints:

0 1 0
0 0 1
1 0 0

0.142857 1   0
0.571429 0.5 1
1        0   0

Which is the same as the MatLab example


text:
Q: iOS: Type occasional straight quotes with smart quotes turned on The question Type straight quotes (",') when smart quotes is turned on answers this quite well for macOS, but the solution (using a text replacement with the straight quote as the replacement phrase) does not appear to work in iOS:

I like to use the typographically correct smart quotes, but when I need to edit text in a markup or programming language, it's frequently the case that I need to enter straight single and double quotes.
These text replacements pictured (and more such as exactly the ones mentioned in the macOS solution above) don't get replaced at all if they contain quotes (either straight or curly) in the shortcut. On the other hand, if I use a text replacement like the ^^s at the bottom here:

I get a ' character, even though the replacement's phrase is the ' character. (Note that the examples above that one also beginning with double-carets, such as ^^1 → ¹, ^^9 → ⁹, etc., work just fine—I used them in this sentence to type those superscript digits.)
I'm looking for a way to set a global hotkey to toggle smart quotes, a macro to insert a single or double straight quote, or anything easier than my current two methods:

*

*Go to Settings → Keyboard and toggle the smart quotes, type the straight quote, and go back to Settings → Keyboard and toggle them back (this is what I do when I need to only type straight quotes for a period of time); or

*Find a single quote or double quote somewhere and copy/paste it. (This is what I do when I must mix the two in ongoing text editing.)

Both are painful. I'd appreciate any trick to make it less so!

A: The smart replacement function is called after the user defined replacement function. You can't win if you
keep the smart replacement sabotaging what you define.
I suggest you my plain stupid approach:
I removed the smart replacement function in MacOS and iOS because
it's too smart for me to use it in a brain efficient way.
I feel it's really smart for the "racing typist", but not at all for me who type in many foreign languages, programming, math, physics, graphics…
I must admit I am far from the mass market ideal racing typist
which Apple is targeting.
Then I trained to use the Apple ergonomic shortcuts ( these were introduced 30 years ago by Apple, around 1986 if my memory is still OK ) to enter the curly quotes or quotation marks I need within the different languages I have to type correctly:
⌥+\ → «
⌥+⇧+\ → »
⌥+⇧+] → '
⌥+] → '
...
and on iOS I simply use the popup of
" to get the « or the "
...
This way I am able to type french, german, spanish, US, shell, C,
Perl, math, physics without too much pain in the fingers and in the brain.

A: I've the same problem. I recently filed a Feedback ticket (iOS 15.2 is the current version) to request Apple consider making toggling this switch easier via shortcut or adding an option to select the setting on an app level instead of globally. Let's hope they take my suggestion.


text:
Q: Unable to connect boost library to my project "symbol lookup error" I have the following situation:
I've created dynamic library lib.so. This library uses another static library lib.a. Both of them use Boost library (I link them in CMake file). (I use this dynamic library in Java project)
This is code of file.cpp in lib.so, which calls getFilesFromDirectory() from lib.a
#include "DrawingDetector.h"
#include "../../DrawingDetection.h"
#include <vector>

#include <boost/filesystem/operations.hpp>

using namespace std;

JNIEXPORT void JNICALL Java_DrawingDetector_detectImage( JNIEnv * env, jobject, jstring jMsg)
{
    const char* msg = env->GetStringUTFChars(jMsg,0);
    vector<File> filesPic = getFilesFromDirectory(msg,0);
    env->ReleaseStringUTFChars(jMsg, msg);
}

This is code of  getFilesFromDirectory() from lib.a:
#include <string.h>
#include <iostream>

#include <boost/filesystem/operations.hpp>

#include "DrawingDetection.h"

using namespace std;

using namespace boost;
using namespace boost::filesystem;

vector<File> getFilesFromDirectory(string dir, int status)
{
    vector<File> files;
    path directoty = path(dir);
    directory_iterator end;
    if (!exists(directoty))
    {
        cout<<"There is no such directory or file!"<<endl;
}
for (directory_iterator itr(directoty); itr != end; ++itr)
{
     if ( is_regular_file((*itr).path()))
     {
    //some code
     }
}
return files;
 }

But when my project invokes lib.so library, it raises the following message:
 java: symbol lookup error: /home/orlova/workspace/kmsearch/Images/branches/DrawingDetection/jni/bin/lib.so: undefined symbol:_ZN5boost11filesystem34path21wchar_t_codecvt_facetEv

As I found out it crushes in lib.a, when  it tries to invoke boost method "path".
But I declared all boost headers, and linked them in CMake file.
Can you explain, why it doesn't recognize boost methods?
EDIT:
The version of my compiler gcc 4.6. And if I use 4.5 everything is fine!
Also if I use some boost methods directly in file.cpp in lib.so everything works fine, for example:
 JNIEXPORT void JNICALL Java_DrawingDetector_detectImage( JNIEnv * env, jobject, jstring jMsg)
 {
    const char* msg = env->GetStringUTFChars(jMsg,0);
    path directoty = path("/home/orlova");//if I use boost method here
    vector<File> filesPic = getFilesFromDirectory(msg,0);// then everything works fine
    env->ReleaseStringUTFChars(jMsg, msg);
 }

BUT
JNIEXPORT void JNICALL Java_DrawingDetector_detectImage( JNIEnv * env, jobject, jstring jMsg)
{
   const char* msg = env->GetStringUTFChars(jMsg,0);
   //path directoty = path("/home/orlova");//if I don't use boost method here
   vector<File> filesPic = getFilesFromDirectory(msg,0);// then this method causes before-mentioned error!!
   env->ReleaseStringUTFChars(jMsg, msg);

}
How can you explain this behavior of compiler?
Note, that error occurs in runtime.
SOLVED
The problem was in order of libraries in *target_link_libraries* in CMake file.
WRONG:
find_library( LIBRARY_MAIN
        NAMES lib.a
        PATHS ../bin
          )

set ( LIB_JNI
      jpeg
      ${OpenCV_LIBS}
      ${BOOST_LIB}
      ${LIBRARY_MAIN}//static library is the last in the list of libraries and after boost!
    )
target_link_libraries( ${PROJECT} ${LIB_JNI} )

RIGHT:
find_library( LIBRARY_MAIN
        NAMES lib.a
        PATHS ../bin
          )

set ( LIB_JNI
      ${LIBRARY_MAIN}
      jpeg
      ${OpenCV_LIBS}
      ${BOOST_LIB}//boost library is the last in the list and after static library!

    )
target_link_libraries( ${PROJECT} ${LIB_JNI} )

A: It seems that you link Boost.Filesystem dynamically - if so, you have to ensure that this library gets loaded. You can do this either by adding it to LOCAL_LDLIBS line in Android.mk, or by pre-loading it manually before you load lib.so in Java code.
Alternatively, just link Boost (and everything else) statically to lib.so and forget about all this dynamic mess. :)
UPDATE1: with regards to the update you posted -- try putting boost_filesystem.a as the last object in the linker line.


text:
Q: Unity scene objects missing from hierarchy whilst running a play-mode test I'm having some issues with my scene and objects not loading as I'd expect during a play-mode test in Unity, and I'm hoping that somebody could help me diagnose this.
I have a simple scene with some objects such as Text and InputField, and after clicking play manually, these can be interacted with, and seen in all their glory via the hierarchy like so:
Hierarchy after clicking Play manually
However, if I then go and run my play-mode test, the same scene doesn't appear to be loaded, instead the hierarchy pane shows "InitTestScene[LongStringOfNumbers]" with just one object called "Code-based tests runner", like so:
Hierarchy during play-mode test
This is then causing NullReferenceExceptions during my tests, because I'm attempting to find objects called "InputField (TMP)", which doesn't exist in the hierarchy, and my test is blowing up as a result.
At first I thought maybe I had to load this scene as part of the setup of the test, so I tried SceneManager.LoadScene("MyScene", LoadSceneMode.Single); but to no avail.
Any ideas how to overcome this, so that my play-mode tests are utilising a hierarchy representative of the first screenshot I posted, as opposed to the second screenshot which is missing all the objects?
Thanks

A: The Unity unit tests do not test the scene, it tests units of your code. The test runner creates a new scene every time it starts and runs the tests in this scene. As far as I know, you will have to recreate what you are testing inside the test and test that.
There are also limitations on creating objects to add to the hierarchy. This link here explains how to create the objects in the test scene


text:
Q: OnItemSelectedListener in Dialog I have a spinner in a dialog and I am trying to get the value from the selected item in spinner and pass it to a String variable. The method that I have found was spinner.setOnItemSelectedListener().
However, this method requires another method to be set up outside the dialog. Code attached below.
This is the code of the dialog
private void recordDialog() {
    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
    View subView = inflater.inflate(R.layout.record, null);

    //get current date
    Calendar calendar = Calendar.getInstance();
    String pattern = "dd-MMM-yy";
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    final String currentDate = dateFormat.format(calendar.getTime());

    //get category
    final Spinner spinner = subView.findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);
    ...
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

And the part outside the dialog
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedCategory = parent.getItemAtPosition(position).toString();
}

Is there anyway to complete everything within the dialog?

A: Well you could just implement the onItemSelectedListener inside your recordDialogfunction:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
         // Do your stuff here
      }

      public void onNothingSelected(AdapterView<?> parent) {
         // Do your stuff here
      }
  });
}


text:
Q: Using hashing to safely store user passwords
Please try to search StackOverflow before asking a question.  Many questions are already answered.  For example:

*

*PHP & MySQL compare password

*how do I create a mySQL user with hash('sha256', $salt . $password)?

*Secure hash and salt for PHP passwords

*User Login with a single query and per-user password salt

*Non-random salt for password hashes

Hi
I want that nobody can see my password even in database..
So i used hash function like this
$passowrd_hash=hash('shal',$_POST['password']);

Now easily I can store this password_hash value into database. It will be something like in encrypted form.
Now user know its original password he don't know this encrypted password.
Now if he try to login through this original password..He is not able to login.
So is there any method so that it can be decrypted and user can make log in. So he can achieve both security of password as well as login again.
How to do this?

A: you need to hash the user input password and compare hashes.

A: All you need to do is encrypt the password you type in and compare the two; the hash in the database and the one you just encrypted. If they match then the password entered is the right one. I am assuming you are using an algorithm like SHA1.

A: Before comparing the posted password by the user with the one in the database, encrypt the posted password the same way as the stored password.

A: You dont need to decrypt it. You cannot convert back a hash to a plain text, its a one way function. So, basically you hash the input password and compare the two hash:
E.g (pseudo code):-

if hash(password entered by user) == password stored in databse Then
    //logged in successfully
else
    //login failed
end if

A: As already answered, you need to hash the password every time they re-enter it and compare the hash to what is in your database.
You ALSO should look into using salt in your hashing algorithm. There is a good deal of discussion in this question:
Secure hash and salt for PHP passwords

A: I highly recommend using md5() http://php.net/manual/en/function.md5.php.
When the user signs up, you store:
$password = md5($_POST['password']);

And when the user logs in you check:
if($_POST['password_entered'] == $passwordFromDB) :
    // Log user in
else :
    // Show error to user
endif;


text:
Q: Exception when calling Autodesk forge API I am using web application with forge viewer.When uploading 1GB file in forge viewer its throwing exception.
This error is getting from below line of coding.
 newObject = Await objectsApi.UploadObjectAsync(bucketKey, m_strFileName,
                     Convert.ToInt32(fileStream.BaseStream.Length), fileStream.BaseStream,
                       "application/octet-stream")

Exception message : Error calling UploadObject
at Autodesk.Forge.ObjectsApi.d__57.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Autodesk.Forge.ObjectsApi.d__56.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CommonGUI.mtequipments.VB$StateMachine_2279_btn_bimfile_Click.MoveNext() in D:\Projects
Could you please help me for this. I need to upload large size files in forge viewer.

A: There is a great possibility that the upload has timeouted.
For large model file, please consider using the resumable endpoint PUT buckets/:bucketKey/objects/:objectName/resumable. In C# SDK, it's uploadchunk.
Here is an example: https://github.com/yiskang/ForgeResumableUploadProgressDemo/blob/master/ForgeResumableUploadProgressDemo/Program.cs


text:
Q: .htaccess: force www including subfolder I have this code in the .htaccess-file of my root:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

This changes mysite.com into www.mysite.com .
I've put the same .htaccess-file inside a folder named "v2". I want mysite.com/v2/start.php to change to www.mysite.com/v2/start.php . This doesn't happen, although other resources claim it should work.
Anyone has any idea what I am doing wrong?

A: Try this:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: Generate function from no initilized object or get keys from type and create functions by key const myFunctions = {
  data1 : <number | undefined>undefined,
  data2 : <string[] | undefined>undefined,
  data3 : <string | undefined>undefined,
  data4 : <undefined | undefined>undefined,
}

type TFunctions<Obj> = {
  [Prop in keyof Obj]: (
    value: NonNullable<Obj[Prop]>
  ) => void
}
const functionGenerator = <T>(fObj:T):TFunctions<T> => {
  const funObj:any = {}
  for(const key in fObj){
    funObj[key] = (payload : any) :void => { console.log(payload)}
  }
  return funObj;
}
const f = functionGenerator(myFunctions)
f.data1(1) //good
f.data2(['a','b']) //good
f.data3('test') //good
f.data4() // error try run empty function

is there some option make this code cleaner remove all undefined
and make data4 available run as function that receive nothing
i try find how get keys from type and create function on this but its look impassible as type is TypeScript declaration and no Variable

Webstorm its give me error on f.data4() as its 'Expected 1 arguments, but got 0'

A: Consider this example:
interface Data {
    data1: number,
    data2: string[]
    data3: string
    data4: undefined
}

type MakeUndefined<T> = {
    [Prop in keyof T]: T[Prop] | undefined
}

const myFunctions: MakeUndefined<Data> = {
    data1: undefined,
    data2: undefined,
    data3: undefined,
    data4: undefined,
}

type TFunctions<Obj> = {
    [Prop in keyof Obj]:
    NonNullable<Obj[Prop]> extends undefined // if data4 is undefined - no arguments
    ? () => void
    : (value: NonNullable<Obj[Prop]>) => void
}
const functionGenerator = <T,>(fObj: T): TFunctions<T> =>
    (Object.keys(fObj) as Array<keyof T>)
        .reduce((acc, elem) => ({
            ...acc,
            [elem]: (payload: any): void => { }
        }), {} as TFunctions<T>
        )

const f = functionGenerator(myFunctions)

f.data1(1) //good
f.data2(['a', 'b']) //good
f.data3('test') //good
f.data4() // ok

Playground
I mad small update in TFunctions since all keys should exists


text:
Q: Get annotations for enum type variable I have some nonnull variable (e.g. en1) of Enum type. The question is: how to get annotations related to enumeration constant referenced by en1 variable?

A: I just read from your comment that you already found the answer. I just wanted to remark for other people interested that, in order for that to work, those annotations must have been declared with the correct retention policy, like this:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Anno1 {
   // ...
}

Without this, they will not be accessible at runtime.
Further reading:

*

*JavaDoc: RetentionPolicy

*Wikipedia: Java annotation

A: If you are using an obfuscator such as Proguard, you might find that the enum fields have been renamed, while .name() still returns the original name of the field. For example, this enum...
enum En {
    FOO,
    BAR
}

...would become this after ProGuarding...
enum En {
    a,
    b
}

...but En.FOO.name() will still return "FOO", causing getField(En.FOO.name()) to fail because it expects the field to be named "a".
If you want to get the Field for a specific enum field from obfuscated code, you can do this:
for (Field field : En.class.getDeclaredFields()) {
    if (field.isEnumConstant()) {
        try {
            if (en1 == field.get(null)) {
                Annotation[] annotations = field.getAnnotations();
            }
        } catch (IllegalAccessException e) {
            //
        }
    }
}

A: Try this (java reflection):
String field = En.AAA.name();
En.class.getField(field).getAnnotations();

It should get you the annotations from AAA.
EDIT:
As the author supposed:
en1.getClass().getField(((Enum)en1).name()).getAnnotations();

Works for him :)

A: As I've already offered:
en1.getClass().getField(((Enum)en1).name()).getAnnotations();

To be clearer:
String name = e.name(); // Enum method to get name of presented enum constant
Annotation[] annos = e.getClass().getField(name).getAnnotations(); // Classical reflection technique

In this case we have no need to know real class of en1.
See also: remark about obfuscated case.

A: Further to the existing answers, if you are in control of the enum class (can edit it), you could simply add a method to the enum to fetch the required annotation i.e.
AnnotationClass getAnnotation(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotation(AnnotationClass.class);
}

or all it's annotations:
Annotation[] getAnnotations(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotations();
}

Adjust the code above to handle exceptions (NoSuchFieldException and  SecurityException).


text:
Q: how to display the Twitter's Bootstrap 2.x typeahead on demand? Hi I need to trigger the show with jquery bootstrap typeahead, and tried to simulate a key press but no way of showing the typeahead. Typeahead there any event that triggers the same effect as pressing a key?
Any suggestions?

A: Also read Definitive way to trigger keypress events with jQuery. The problem seems you first have to focus, so try to use this function:
function triggertypeahead(element,value,empty)
{
    empty = typeof empty !== 'undefined' ? false : true;
    element.focus();
    element.val(value);
    element.trigger(jQuery.Event('keyup'));
    if(empty)element.val('');
}

example:
<input id="typeaheadinput" type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source='["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="bootstrap-master/js/bootstrap-typeahead.js"></script>
<script>

function triggertypeahead(element,value,empty)
{
    empty = typeof empty !== 'undefined' ? false : true;
    element.focus();
    element.val(value);
    element.trigger(jQuery.Event('keyup'));
    if(empty)element.val('');
}

triggertypeahead($('#typeaheadinput'),'al');

</script>

See also: http://bootply.com/65987


text:
Q: Optimize an if/else statement code with lambda in C# ? Try to use only one Frame instead of parentIFrame and insurancedata I have the following lines of code which I want to shorten using a lambda statement or anything more elegant.
 HtmlControl parentIFrame = null;
 HtmlControl insurancedata = null;

if (!Resource.ControlType.ToLower().Equals("getactivityid"))
{
    parentIFrame = new HtmlControl(Resource.ProjectBrowserWindow);
       if (Resource.ControlType.ToLower().Equals("hyperlink"))
           parentIFrame.SearchProperties.Add(HtmlControl.PropertyNames.Id, "bike-insurance");
       else
           parentIFrame.SearchProperties.Add(HtmlControl.PropertyNames.Id, "section_wise_container");
}

if (Resource.ControlGenricName.ToLower().Contains("finalsubmitbutton"))
{
    insurancedata = new HtmlControl(parentIFrame);
    insurancedata.SearchProperties.Add(HtmlControl.PropertyNames.Id,
    "ResultButton");
}

A: I don't see anywhere to use a lambda in this code.
You can shorten the code by

*

*Declaring variables when you use them instead of before

*Using object initializer and collection initializer syntax to add the property

*Choosing the property value to set rather than choosing a logic branch to set it

Example:
if (!Resource.ControlType.ToLower().Equals("getactivityid"))
{
    var parentIFrame = new HtmlControl(Resource.ProjectBrowserWindow)
    {
        SearchProperties =
        {
            HtmlControl.PropertyNames.Id,
            (Resource.ControlType.ToLower().Equals("hyperlink")) ? "bike-insurance" : "section_wise_container"
        }
    };
}

A: No matter how much I look, it really doesn't seem appropriate to me to use lambda here. Try and encapsulate your code into functions, this way you will hide the ugly part.
Something like:
HtmlControl parentIFrame = GetParentIFrame();
HtmlControl insurancedata = GetInsuranceData(parentIFrame);

And then:
HtmlControl GetParentIFrame()
{
    HtmlControl parentIFrame = null;
    if (!Resource.ControlType.ToLower().Equals("getactivityid"))
    {
        parentIFrame = new HtmlControl(Resource.ProjectBrowserWindow);
        if (Resource.ControlType.ToLower().Equals("hyperlink"))
           parentIFrame.SearchProperties.Add(HtmlControl.PropertyNames.Id, "bike-insurance");
        else
           parentIFrame.SearchProperties.Add(HtmlControl.PropertyNames.Id, "section_wise_container");
        return parentIFrame;
   }
   return parentIFrame;
}

HtmlControl GetInsuranceData(HtmlControl parentIFrame)
{
    HtmlControl insurancedata = null;
    if (Resource.ControlGenricName.ToLower().Contains("finalsubmitbutton"))
    {
        HtmlControl insurancedata = new HtmlControl(parentIFrame);
        insurancedata.SearchProperties.Add(HtmlControl.PropertyNames.Id,
        "ResultButton");
    }
    return insurancedata;
}

A: Using an extension method, you can simplify the code by using a Fluent philosophy:
public static class HtmlControlExt {
    public static HtmlControl AddIdSearch(this HtmlControl ctrl, string name) {
        ctrl.SearchProperties.Add(HtmlControl.PropertyNames.Id, name);
        return ctrl;
    }
}

Now your code would be:
if (!Resource.ControlType.ToLower().Equals("getactivityid"))
{
    parentIFrame = new HtmlControl(Resource.ProjectBrowserWindow)
                        .AddIdSearch(Resource.ControlType.ToLower().Equals("hyperlink") ? "bike-insurance" : "section_wise_container");
}

if (Resource.ControlGenericName.ToLower().Contains("finalsubmitbutton"))
{
    insurancedata = new HtmlControl(parentIFrame)
                        .AddIdSearch("ResultButton");
}

NOTE: I would eliminate braces from single statement if and compare strings with ==, so the code would be even shorter:
if (!Resource.ControlType.ToLower() == "getactivityid")
    parentIFrame = new HtmlControl(Resource.ProjectBrowserWindow)
                        .AddIdSearch(Resource.ControlType.ToLower() == "hyperlink" ? "bike-insurance" : "section_wise_container");

if (Resource.ControlGenericName.ToLower().Contains("finalsubmitbutton"))
    insurancedata = new HtmlControl(parentIFrame)
                        .AddIdSearch("ResultButton");


text:
Q: Python and OpenCV - How can I understand this bitwise operator? I am a still beginner in programming, pordon me if this question is too trivial. Let say I have this code:
camera = cv2.VideoCapture('path_to_video_file')
while True:
    #reading frames of video
    ret, frame = camera.read()
    cv2.imshow("Video", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

So, from my understanding, at the instance when the frame is shown (in the "Video" window), if at the same time, the q key is pressed, the loop would break. But I don't really understand how the if cv2.waitKey(1) & 0xFF == ord('q') line works.
I do know this is an AND bitwise operation in which output is 1 only if both of the two inputs is also 1. But that is all abut it. So, I really want to know what is exactly happening.
And also, what is actually the 0xFF == ord('q') means?

A: Python operator precedence gives us:
(cv2.waitKey(1) & 0xFF) == ord('q')

In binary, this is:
(cv2.waitKey(1) & 0b11111111) == ord('q')

So, what this does is select the low 8 bits of the result cv2.waitKey and test if that's equal to ord('q'), which is the ASCII value for 'q'.


text:
Q: TIGER schema information I've recently pulled some of the TIGER data onto my local machine but, I'm at a loss about what it all means. I'm hoping to find some technical documentation on what all the tables and columns mean.
For example, what does the column tlid in the table addrfeat represent?
Specifically, I'm trying to pull up address information by area, i.e, what are all the possible addresses in downtown Albany, NY?
I have it sort of working but I don't feel confident about the results since I just pulled data without regard to the meaning of the columns or tables.

A: There are several products of US TIGER data.  The TIGER/Line Shapefiles and Files are the most extensive data set...  information can be found here.
Once on that page there are different years of data sets to choose from along with general information.  Each year has its own "Technical Documentation" which contains information that explains every aspect of the data.