text:
Q: What is the default font family of a Flutter app? How I can retrieve the current font family name for flutter app and what is the default one ?
I have tried
Theme.of(context).textTheme.

and
Theme.of(context).

but there is no attribute for the font family.

A: The default fonts depend on the operating system:

*

*Android uses the Roboto font.

*iOS uses the San Francisco font (specifically, SF Pro Display).

A: The default font of MaterialApp is described in
/flutter/packages/flutter/lib/src/material/typography.dart
on iOS, the default TextTheme is
  static const TextTheme whiteCupertino = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteCupertino display4',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteCupertino display3',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteCupertino display2',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteCupertino display1',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteCupertino headline',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteCupertino title',      fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteCupertino subhead',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteCupertino body2',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteCupertino body1',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteCupertino caption',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteCupertino button',     fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteCupertino subtitle',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteCupertino overline',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );

on Android, the default TextTheme is
 static const TextTheme whiteMountainView = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteMountainView display4',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteMountainView display3',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteMountainView display2',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteMountainView display1',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteMountainView headline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteMountainView title',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteMountainView subhead',    fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteMountainView body2',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteMountainView body1',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteMountainView caption',    fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteMountainView button',     fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteMountainView subtitle',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteMountainView overline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );

and you can retrieve the font family by the following code
DefaultTextStyle.of(context).style.fontFamily

A: The default font of MaterialApp is roboto, a Google font.
https://fonts.google.com/specimen/Roboto

A: The default font family for a Flutter app project is
Roboto - get it here:  https://fonts.google.com/specimen/Roboto#standard-styles
which by default shows on Andriod OS.

For iOS devices its
San Francisco font - get it here: https://developer.apple.com/fonts/

To use any of them by default(also depends on your theme settings) in your flutter project, you import either or both:
for Andriod - import package:flutter/material.dart.
for iOS - import package:flutter/cupertino.dart.

you can also use other fonts(add its folder to the root folder or create assets folder) and include the font definition in the pubspec.yaml

A: To get the current font family:
DefaultTextStyle.of(context).style.fontFamily
The default font family would be based on the device:
https://api.flutter.dev/flutter/material/Typography/Typography.material2021.html
Roboto for Android. https://api.flutter.dev/flutter/material/Typography/blackMountainView-constant.html
San Francisco for iOS. https://api.flutter.dev/flutter/material/Typography/blackCupertino-constant.html


text:
Q: how to link Youtube video in Lightbox v2.10.0 I am using Lightbox v2.10.0 by Lokesh Dhakar in Bootstrap 4, instead of image want to play Youtube video in the modal window, please help me how to do it.
here is what I tried, but i am unable to play Youtube link

App 1

App

A: Lightbox2 does not support videos.
Your best bet is to use an alternative 'lightbox' library that has video support. You could also modify Lightbox2 to have video support, using existing work as a starting point (https://github.com/lokesh/lightbox2/pull/564), but this would be substantially more challenging.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting Array of Strings by Character in Alphabetical or Numerical So I have an array of strings to be sorted out.
Let's say I have this array:
let array = ["8AD", "8AB", "8A6", "8BC", "86F", "835", "81D"];

Now, there two kinds of sorting that needs to be implemented:

*

*Alphabetical characters are prioritized over numerical characters

*Numerical characters are prioritized over alphabetical characters

Now, I needed to sort using either of these two for every character.
So, a Numerical-Numerical-Alphabetical order would give me:
"81D","835","86F","8AB","8AD","8A6","8BC"

While a Numerical-Alphabetical-Numerical order would give me:
"8A6","8AB","8AD","8BC","81D","835","86F"

I'm thinking of assigning every single digit number and all characters to a double-digit integer:
let alpha = {
    A= 11, B= 12 , C= 13 , D= 14 , E= 15 , F= 16 , G= 17 , H= 18 , I= 19 , J= 20 , K= 21,
    L= 22 , M= 23 , N= 24 , O= 25 , P= 26 , Q= 27 , R= 28 , S= 29 , T= 30 , U= 31 , V= 32,
    W= 33 , X= 34 , Y= 35 , Z= 36 , 0=37, 1= 38 , 2= 39 , 3= 40 , 4= 41 , 5= 42 , 6= 43 , 7= 44,
    8= 45 , 9= 46 };
let numeral = {
    0=11, 1=12, 2=13, 3=14, 4=15, 5=16, 6=17, 7=18, 8=19, 9=20, A=21,
    B=22, C=23, D=24, E=25, F=26, G=27, H=28, I=29, J=30, K=31, L=32,
    M=33, N=34, O=35, P=36, Q=37, R=38, S=39, T=40, U=41, V=42, W=43,
    X=44, Y=45, Z=46 }

And then replacing every characters to whichever order is needed.
Does anyone have a simpler or more efficient way to achieve what is needed to do?

A: Here's some generic/abstract stuff

// given a sequence and an array of "order" strings, create a comparable "key" string

let multiSortKey = (subject, orders) =>
    [...subject].map(
        (c, i) =>
            String(orders[i].indexOf(c)).padStart(16, '0')
    ).join();

// generic comparison function

let cmp = (a, b) => (a > b) - (a < b);

// generic sort-by-map, aka Schwartzian, function

let sortBy = (xs, key) => xs
    .map(x => [x, key(x)])
    .sort((x, y) => cmp(x[1], y[1]))
    .map(x => x[0]);

// applied to the task at hand:

data = ["8AD", "8AB", "8A6", "8BC", "86F", "835", "81D"]

N = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

console.log(sortBy(data, x => multiSortKey(x, [N, N, A])))
console.log(sortBy(data, x => multiSortKey(x, [N, A, N])))

A: An approach with looking at each letter and a pattern for sorting with map.

function sort(array, pattern) {
    return array
        .map((value, index) => ({ index, value: Array.from(value, c => pattern.map(fn => fn(c) ? c : ' ').join('')).join('') }))
        .sort(({ value: a }, { value: b }) => a.localeCompare(b))
        .map(({ index }) => array[index]);
}

const
    isDigit = c => /^\d$/.test(c),
    isNonDigit = c => /^\D$/.test(c),
    digitNonDigit = [isNonDigit, isDigit], // revers sorted
    nondigitDigit = [isDigit, isNonDigit], // revers sorted
    array = ["8AD", "8AB", "8A6", "8BC", "86F", "835", "81D"];

console.log(sort(array, digitNonDigit));
console.log(sort(array, nondigitDigit));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Try to use parseInt() function with radix argument for transfer your string to numeric value.
Also .sort() method to sorting your array.
Example:

let array = ["8AB", "8A6", "8BC", "86F", "835", "81D", "22", "33", "0"];
array.sort((x,y) => parseInt(x, 32) - parseInt(y, 32));
console.log(array);


text:
Q: Multiple autocomplete search fields I'm using the jQuery UI autocomplete widget on a text input. This text input is used to add a product to the database.
Here's my code:
HTML:

    <input type="text" class="form-control" placeholder="Termék kiválasztásához kezdjen el gépelni..." id="search">

JS:
$('#search').on('keypress', function () {
    $(this).autocomplete({
        appendTo: "#autocomplete",
        autoFocus: true,
        minLength: 0,
        source: "array - ommited for clarity"
    });
});

I would like to add a button which adds another input field, so the user can add another product to the database.
My problem would be, that if I duplicate the HTML I'm using, I'll have multiple elements with the same ID. Of course, the logical move would be to replace ID's with classes, but then again, if I'm correct the class selector for jQuery selects the first matched element, so the keypress event would fire on the original input.
How can I add another text input without duplicating my javascript code?

A: You can use class instead of the Id selector.
Please check this link : how-can-i-add-jquery-ui-autocomplete-to-a-dynamically-created-element
and this jsfiddle
<form id="myForm" name="myForm" method="post">
<input id="addButton" name="addButton" type="button" value="Add an input" />

$(function() {
var options = {
    source: [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
        ],
    minLength: 2
};

$("input.searchInput").live("keydown.autocomplete", function() {
    $(this).autocomplete(options);
});

var addInput = function() {
    var inputHTML = " <input name='search' value='' class='searchInput' maxlength='20' />";
    $(inputHTML).appendTo("form#myForm");
    $("input.searchInput:last").focus();
};

if (!$("form#myForm").find("input.searchInput").length) {
    addInput();
}

$("input#addButton").click(addInput);
});


text:
Q: Get data from database using php,ajax I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons  looks like this
When a user clicks one of the above buttons it displays this
So now  when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector  855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML

        Construction

        Power

        Oil

        All available industries

Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
    if( $(e.target).find("span.label").html()=="Confirm" ) {

        var selectedCountries = [];

        $('.video-btns .selected').each(function () {
            selectedCountries.push( $(this).parent().find("span.label").html() ) ;
        });

        if( selectedCountries.length>0 ) {
            if(selectedCountries.indexOf("All available countries")>-1) {
                selectedCountries = [];
            }

        } else {

            return;
        }

        var ajaxurl = "";
        if(selectedCountries.length>0) {
            ajaxurl = "data.php";
        } else {
            ajaxurl = "dataall.php";

        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                    countries: selectedCountries.join(","),
                    sector: selectedSector
            },
            success: function(result){
                console.log(result);
                result = JSON.parse(result);
                $(".video-btns").each(function () {
                    var getBtn = $(this).attr('buttonid');
                    if (getBtn == 106) {
                        var totalProjects = $(""+ result[0] + "");
                        $(this).append(totalProjects)
                    }else if(getBtn ==107){
                        var resultBudget = result[1]
                        var totalBudgets = $(""+ '&#36m' +" " + resultBudget +"");
                        $(this).append( totalBudgets)
                    }
                });
                return;
              }
        });
    }
});

Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
 $conn = mysqli_connect("localhost", "root", "", "love");
 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 {
    if($row['Sector']==$selectedSectorByUser ) {
     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];
    }
 }
 echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>

Here is data.php
<?php

$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);

//var_dump($countries);
 $conn = mysqli_connect("localhost", "root", "", "meedadb");
 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 {
    if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
    // array_push($data, $row);
     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];
    }
 }

 // array_push($wynik, $row);
 echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>

Now when the user clicks All available industries btn and selects a country I  get  [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,

A: in you dataAll.php
If you have select All available industries
you shold not check for sector  because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php

$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];

$wynik = [];
$totalProjects = 0;
$totalBudget = 0;

while ($row = mysqli_fetch_array($result)) {
    $totalProjects += $row['SumofNoOfProjects'];
    $totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);

A: You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");

You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");

In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.

A: The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...

But, rather than special casing the "all" in the client, do it in the server.  That is, the last button for industry will generate
    ?industry=all

and the PHP code will not include this in the WHERE clause:
    AND industry IN (...)

Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();

$industry = @$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
    $inds = array();
    foreach (explode(',', $industry) as $ind) {
        // .. should test validity here; left to user ...
        $inds[] = "'$ind'";
    }
    $wheres[] = "industry IN (" . implode(',', $inds) . )";
}

// ... repeat for country ...

$where_clause = '';
if (! empty($wheres)) {
    $where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)

// Build the SQL:

$sql = "SELECT ... FROM ...
           $where_clause
           ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)

Now, let's talk about using AJAX.  Or not.  There were 2 choices:

*

*you could have had the call to PHP be via a GET and have that PHP display a new page.  This means that PHP will be constructing the table of results.

*you could have used AJAX to request the data.  This means that Javascript will be constructing the data of results.

Which choice to pick probably depends on which language you are more comfortable in.


text:
Q: Python Turtle Drawing Assignment - Trouble with assigning variables I have an assignment due in a few hours and I'm stuck as to what to do.
I am using python 3.
I keep trying to run the code, but I get errors. At this point I figured I'd ask for help.
Thank you in Advance!
Instructions: http://people.uncw.edu/cferner/Classes/csc231/Assignment1.html
 import turtle
 import random

class myRectangle:

def __var__(self):
    self.__x
    self.__y
    self.__width
    self.__height
    self.__color

def __init__(self, x, y, width, height, color):
    self.__x = x
    self.__y = y
    self.__width = width
    self.__height = height
    self.__color = color

def getX(self):
    return self.__x

def setX(self, x):
    self.__x = x

def getY(self):
    return self.__y

def setY(self, y):
    self.__y = y

def getWidth(self):
    return self.__width

def setWidth(self, width):
    self.__width = width

def getHeight(self):
    return self.__height

def setHeight(self, height):
    self.__height = height

def getColor(self):
    return self.__color

def setColor(self, color):
    self.__color = color

def draw(self, turtle):
    turtle.penup()
    turtle.goto(self.getX(), self.getY())
    turtle.heading(0)
    turtle.pencolor("blue")
    turtle.pendown()
    turtle.begin_fill()
    turtle.forward(self.__width())
    turtle.left(90)
    turtle.forward(self.__height())
    turtle.left(90)
    turtle.forward(self.__width())
    turtle.left(90)
    turtle.forward(self.__height())
    turtle.left(90)
    turtle.end_fill()

def main():

wn = turtle.TurtleScreen
mr = myRectangle
phil = turtle.Turtle()
macie = turtle.Turtle()
sashi = turtle.Turtle()
roxie = turtle.Turtle()
darla = turtle.Turtle()
sammy = turtle.Turtle()

phil.pencolor("blue")
phil.pensize(7)

listofcolors = ("blue", "red", "yellow", "orange", "pink", "green")
c = random.choice(listofcolors)

xy = random.randrange(-200, 201)
wh = random.randrange(1, 151)

for i in [phil, macie, sashi, roxie, darla, sammy]:
    mr.setColor(c)
    mr.setX(xy)
    mr.setY(xy)
    mr.setWidth(wh)
    mr.setHeight(wh)

main()

Errors:
     /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
    "/Users/Desktop/OneDrive - UNC-Wilmington/UNCW Files/Summer
      2017/CSC 231/Assignment 1/turtleRectangle.py"
    Traceback (most recent call last):
    File "/Users/Desktop/OneDrive - UNC-Wilmington/UNCW Files/Summer
   2017/CSC 231/Assignment 1/turtleRectangle.py", line 102, in <module>
    main()
     File "/Users/Desktop/OneDrive - UNC-Wilmington/UNCW Files/Summer
  2017/CSC 231/Assignment 1/turtleRectangle.py", line 92, in main
   mr.setColor()
   TypeError: setColor() missing 2 required positional arguments:
  'self' and 'color'

   Process finished with exit code 1

Download link for Python file

A: Your testing code is a mess, you don't need multiple turtles, just one, something along the lines:
def main():

    listofcolors = ("blue", "red", "yellow", "orange", "pink", "green")
    wn = turtle.Screen()
    mr = myRectangle(0, 0, 100, 100, "blue")
    phil = turtle.Turtle()

    for _ in range(6):
        x = random.randint(-200, 200)
        print(x)
        y = random.randint(-200, 200)
        print(y)
        w = random.randint(1, 150)
        print(w)
        h = random.randint(1, 150)
        print(h)
        c = random.choice(listofcolors)
        print(c)

        mr.setX(x)
        mr.setY(y)
        mr.setWidth(w)
        mr.setHeight(h)
        mr.setColor(c)

        mr.draw(phil)

    wn.mainloop()

main()

This should bring you to step 7 in your instructions.
I don't know what your __var__() function is supposed to do, it seems like a lengthy no-op.  Your draw() function slightly tweaked:
    def draw(self, turtle):
        turtle.penup()
        turtle.goto(self.getX(), self.getY())
        turtle.setheading(0)
        turtle.color(self.getColor())  # set both pen & fill color
        turtle.pendown()
        turtle.begin_fill()
        turtle.forward(self.__width)
        turtle.left(90)
        turtle.forward(self.__height)
        turtle.left(90)
        turtle.forward(self.__width)
        turtle.left(90)
        turtle.forward(self.__height)
        turtle.left(90)
        turtle.end_fill()

A: The problem is the code you pasted in the post is not the same as in the file you list.  In the file you have an error on line 92 where you don't supply any args to setColor:
for i in [phil, macie, sashi, roxie, darla, sammy]:
    mr.setColor()
    mr.setX(xy)
    mr.setY(xy)
    mr.setWidth(wh)
    mr.setHeight(wh)


text:
Q: If I add more instances to my stack will they all get masked with the same Elastic IP or will they get new ones? If I add more instances to my stack will they all get masked with the same Elastic IP or will they get new ones?

A: An elastic IP is attached to a single EC2 instance. You can detach and reattach it to another instance, but only one.


text:
Q: jest enzyme testing a component with async fetch to api I'm using react, jest and enzyme with immutable. I'm trying to mount a component that fetching data from the API, and I'm having a little difficulties.
// FooListContainer.jsx

export default class FooListContainer extends Component {
    constructor(props) {
        super(props);

        this.state = {
           foos: List()
        }
    }

    componetWillMount() {
        manager.bringFooList()
        .then(lst => this.setState({ foos: fromJS(lst) }))
        .done();
    }

    render() {
        return <FooList foos={this.state.foos} />
    }
}

This is the ui component all it does is receive list and map them
// FooList.jsx

export default class FooList extends Component {
    render() {
        return (

               {this.props.foos.map(item =>
{item}
)}

        );
    }
}

Now I would like to test the data received from the fetch in FooListContainter is passed correctly to FooList.
// FooListContainer.test.jsx

describe('rendering', () => {
    it('Should passed the data from the fetch to the FooList', () => {
        const response = ['1', '2', '3'];

        manager.bringFooList = jest.fn(() => {
           return new Promise(resolve => {
               return resolve(response);
           });
        })

        const wrapper = mount(<FooListContainer />);

        const fooList = wrapper.find(FooList);

        expect(fooList.props().foos.size).toBe(3);
    });
});

But the test fails because it expects the length to be 3 and it actual length is 0 from some reason.
I think that it has something to do with the fact that the fetch inside the container is async - so the test is not 'waiting' to the response and render is happening before the state change for the first time and the FooList receive an empty list.
I have tried to receive in the 'it' function an async callback as an argument and call it after the mount, like this:
// FooListContainer.test.jsx

describe('rendering', () => {
    it('Should passed the data from the fetch to the FooList', (done) => {
        const response = ['1', '2', '3'];

        manager.bringFooList = jest.fn(() => {
           return new Promise(resolve => {
               return resolve(response);
           });
        })

        const wrapper = mount(<FooListContainer />);
        done();

        const fooList = wrapper.find(FooList);

        expect(fooList.props().foos.size).toBe(3);
    });
});

But the above example did not work.
I would really appreciate every help you could give me.


text:
Q: Get last inserted id of any table in mysql I'm importing a .sql file via php. My .sql file contains multiple tables and I want the last inserted id of a particular table.
So, how to get last inserted id of any table by table name?
Any idea how to get the id?
Please don't suggest, get id by select query to get MAX id.

A: We had.
id | value
1  |  10
3  |  20

Then we inserted 2 | 15, so it had become
id | value
1  |  10
2  |  15
3  |  20

(Remind, we have a .sql file, not a live connection)
And now you want to know, that the last one was 2? If so — it's impossible. .sql file doesn't keep that kind of information, only bare data and some meta.

A: This can be done in both mysql and mysqli.
 $conn = mysqli_connect($servername, $username, $password, $dbname);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('abc', 'xyz', 'abc@example.com')";
    if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);}

in mysql
       mysql_connect($servername, $username, $password);
       mysql_select_db($dbname);
        $sql = "INSERT INTO MyGuests (firstname, lastname, email)
        VALUES ('abc', 'xyz', 'abc@example.com')";
        if (mysql_query($sql)) {
            $last_id = mysql_insert_id();}

A: As long as auto_increment is defined, that last inserted auto increment id can be retrieved from information_schema.tables:
select IF(auto_increment = 1,
          'No row has been inserted',
          auto_increment - @@auto_increment_increment) As LastInsertedId
from information_schema.tables
where table_schema = 'DBName' and table_name = 'TableName';

A: Try these functions
If you're using PDO, use PDO::lastInsertId
If you're using Mysqli, use mysqli::$insert_id
But if you have to, use mysql_insert_id.


text:
Q: Inserting a very large integer array as standard input I want to be able to insert an array of integer as standard input which can has a length of 1000000.
I am trying to do that using this code but the array will be only a size of 254, (I read from an article that Console.ReadLine take only 254 charecter).
Note: Every character of the array is between 1 to 6
and the first line of the code numThrows represents the length of the array.
 int numThrows = Convert.ToInt32(Console.ReadLine()); // length of array
 string str = Console.ReadLine();
 int[] arr = new int[numThrows];
 arr = str.Select(c => Convert.ToInt32(c.ToString())).ToArray();

A: You can increase the limit by writing your own ReadLine function.
        const int BufferLimit = 10000;
        public static string ReadLine()
        {
            Stream s = Console.OpenStandardInput(BufferLimit);
            byte[] Buffer = new byte[BufferLimit];
            int Length = s.Read(Buffer, 0, BufferLimit);
            return new string(Encoding.UTF7.GetChars(Buffer, 0, Length));
        }


text:
Q: How to subtract two dates without sunday in php I want to subtract date with php or cakephp function,
example :
$date1 = '2016-05-19';
$date2 = '2016-05-23';

i want subtract dates without sunday, from example the result i want is 3, not 4, because 4 - 1 (sunday),
I already try with new Datetime php like this code,
$receipt_date   = new DateTime($air_way_bill['AirWayBill']['receive_date']);
$date           = new DateTime($air_way_bill['AirWayBill']['date']);
$difference     = $receipt_date->diff($date);

but the result is 4, how can i subtract with sunday between that range?
there is any step or way to doing what i mean?
thanks in advance...
[CASE CLOSED]:
True Answer :
// ============================= 1 ==================== //

$receipt_date   = new DateTime('2016-05-19');
$date           = new DateTime('2016-05-23');
$difference     = $receipt_date->diff($date);

$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);

$count = 0;

foreach($daterange as $date){
    if(!($date->format("w"))) {
        $count++;
    }
}

echo ($difference->days)-$count;

// ================================================ //
// ============================= 2 ==================== //

function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
    $days = $startDate->diff($endDate, true)->days;
    $sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);

    return intval($days)-Sundays;

}
// ======================================================== //
// ===================== This is my experiment =============== //
        $date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['date']));
        $receive_date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['receive_date']));

        $date_diff = round(abs(strtotime($receive_date) - strtotime($date)) / 86400);
        $weeks  = round(abs(strtotime($receive_date) - strtotime($date)) / (86400 * 7));

         echo $date_diff - $weeks;

// ======================================================== //
Thank you very much...

A: I wrote a function to do what you are asking for.
function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
    $days = $startDate->diff($endDate, true)->days;
    $sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);

    return intval($days)-$sundays;

}

A: You can find total days, and then find number of sundays in that range. Finally reduce those days from total days:
<?php
$receipt_date   = new DateTime('2016-05-19');
$date           = new DateTime('2016-05-23');
$difference     = $receipt_date->diff($date);

$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);

$count = 0;

foreach($daterange as $date){
    if(!($date->format("w"))) {
        $count++;
    }
}

echo ($difference->days)-$count;

Demo


text:
Q: Fraud messages were sent by my Twilio number I am a big fan of Twilio and I love to use Twilio
Since a month ago, some unexpected things occurred on my Twilio account,
Fraud messages were sent by my Twilio number around 4 times so far,
Every time, the fraud happened, Twilio suspended my account to ask me to investigate this fraud,
I tried to find something wrong with me, but I wasn't able to find what is wrong here
I never shared my credentials, but fraud messages were sent by my Twilio number.
Here is a number of things I want to mention

*

*Only one number was used for each time

*I released the numbers used for fraud when I found the fraud, but another number was used for the fraud again

*3,000 fraud messages were sent at once

*The fraud messages were related to some other services like Amazon ads, Apple ads, etc.

What I think

*

*I don't think someone hacked my account and send this fraud message using my Twilio number since only one number is used for this Fraud

*Maybe these numbers are shared by other VoIP services, meaning two services are using one number at the same time

I want to know

*

*if someone could send messages using my number without auth token and account sid on Twilio?

*if Twilio doesn't know how to prevent this fraud?

*if anyone else has this experience on Twilio?

*what is the best and secure service for SMS, I am considering Telnyx, any idea?

Thanks in advance


text:
Q: Exercise 6, Section 17 of Munkres' Topology
Let $A$, $B$, and $A_\alpha$ denote subsets of a space $X$. Prove the following:
(a) If$A\subseteq B$,then$\overline{A} \subseteq \overline{B}$. (b) $\overline{A\cup B}=\overline{A}\cup \overline{B}$.
(c) $\overline{ \bigcup A_{\alpha}} \supset \bigcup \overline{A_\alpha }$ ; give an example where equality fails.

My attempt: (a) $A\subseteq B \subseteq \overline{B}$. Since $\overline{B}$ is closed and $A\subseteq \overline{B}$, we have $\overline{A} \subseteq \overline{B}$. Is this  proof correct? If you think last step is bit of a jump, you can look at https://courses-archive.maths.ox.ac.uk/node/view_material/50743 lecture notes, page no. 6.

(b) Approach(1): We first show $(A\cup B)' = A' \cup B'$. Let $x\in (A\cup B)' \Rightarrow \forall U\in \mathcal{N}_x, (U-\{x\})\cap (A\cup B)\neq \phi$. By De Morgan's laws, $[(U-\{x\}) \cap A] \cup [(U-\{x\})\cap B]\neq \phi$. Which means $(U-\{x\}) \cap A$ or $(U-\{x\})\cap B$ or both is non empty. By definition of limit point, $x\in A'$ or $x\in B'$. So $x\in A' \cup B'$. Thus $(A\cup B)'\subseteq A'\cup B'$.
Conversely, $x\in A' \cup B'$. If $x\in A'$, then $\forall U\in \mathcal{N}_x, (U-\{x\})\cap A\neq \phi$. So $(U-\{x\})\cap (A\cup B)= [(U-\{x\}) \cap A] \cup [(U-\{x\})\cap B]\neq \phi$. Thus $x\in (A\cup B)'$. Similarly, if $x\in B'$, then $x\in (A\cup B)'$. Hence $(A\cup B)' = A' \cup B'$. So $\overline{A\cup B}= (A\cup B) \cup (A\cup B)'= (A\cup A') \cup (B\cup B')= \overline{A} \cup \overline{B}$. Is this proof correct? In proof of $(A\cup B)' \subseteq A' \cup B'$ what if, for one neighbourhood of $x$,$(U-\{x\}) \cap A$ is non empty and for some other neighbourhood it's empty?
Approach(2): let $x\in \overline{A\cup B}$. Then $\forall U\in \mathcal{N}_x, U\cap (A\cup B)\neq \phi$. So $(U\cap A)\cup (U\cap B)\neq \phi$. Rest of the proof is similar to approach(1). I'm facing the same problem as approach(1). Is this proof correct?
Approach(3): To show $\overline{A\cup B} \subseteq \overline{A}\cup \overline{B}$. $\overline{A}$ and $\overline{B}$ is closed in $X$. So $\overline{A}\cup \overline{B}$ is closed in $X$. $A\subseteq \overline{A}$ and $B\subseteq \overline{B}$. So $A\cup B\subseteq \overline{A}\cup \overline{B}$. Hence $\overline{A\cup B} \subseteq \overline{A}\cup \overline{B}$.
Approach(4): Since $A\cup B\subseteq \overline{A} \cup \overline{B}$, by part(a) $\overline{A\cup B} \subseteq \overline{ \overline{A} \cup \overline{B} }$. Since $\overline{A} \cup \overline{B}$ is closed, it's equal to it's closure. Thus $\overline{A\cup B} \subseteq \overline{A} \cup \overline{B}$.

(C) Let $x\in \bigcup \overline{A_\alpha}$. $x\in \overline{A}_j$. So $\forall U\in \mathcal{N}_x, U\cap A_j \neq \phi$. Since $A_j \subseteq  \bigcup A_\alpha$, we have $U\cap A_j \subseteq U\cap (\bigcup A_\alpha)$. Since $\exists p\in U\cap A_j$, $p\in U\cap (\bigcup A_\alpha)$. So $U\cap (\bigcup A_\alpha)\neq \phi$. Thus $x\in \overline{\bigcup A_\alpha}$. Hence $\overline{ \bigcup A_{\alpha}} \supset \bigcup \overline{A_\alpha }$.

A: So Munkres defines (or shows the equivalence of) three definitions of $\overline{A}$ that section.

*

*The original definition is $\overline{A}$ is the intersection of all closed sets containing $A$ (where closed=complement is open, and the topology is given).

*He then goes on to show that $x \in \overline{A}$ iff every neighbourhood of $x$ intersects $A$ which is a handy view to actually find the closure of specific sets in a space.

*Finally theorem 17.6 tells us $$\overline{A} =A \cup A'$$
which is added (I think) mainly for historical reasons, it's one of the oldest way of seeing the closure (as $A'$ was already defined way back by Cantor).
Your proof of the exercise alternates between these definitions, which is fine. The limit point one is often the least convenient for proofs though because you're often forced to make separate arguments for points in $A$ and in $A'$, and that's often more work.
(a): your way is fine: $\overline{B}$ is closed and contains $A$ so it's one of the sets in the defining intersection in def. 1 so $\overline{A} \subseteq \overline{B}$ then trivially holds. No "jump" at all: any intersection is trivially a subset of each of its intersectees (to coin a word), so of $\overline{B}$ in particular.
(b):approach 1 is messy, so avoid it; see my comments above though. An approach using def.1 could go:
$\overline{A} \subseteq \overline{A \cup B}$ by part (a). Likewise $\overline{B} \subseteq \overline{A \cup B}$. So for the union too:
$$\overline{A} \cup \overline{B}  \subseteq \overline{A \cup B}$$
and we have one inclusion. OTOH: $\overline{A} \cup \overline{B}$ is closed (finite union) and contains $A \cup B$ so by the same argument as before: $$\overline{A \cup B} \subseteq \overline{A} \cup \overline{B}$$ and we have the second inclusion and equality.
The point based approach using neighbourhoods and def 2:
Suppose $x \in \overline{A \cup B}$. Then $x \in \overline{A}\cup \overline{B}$: because if $x \notin \overline{A}$ and $x \notin \overline{B}$ we'd have $O_1 \in \mathcal N_x$ so that $O_1 \cap A = \emptyset$ and we'd also have $O_2 \in \mathcal N_x$ so that $O_2 \cap B = \emptyset$ (def 2 negated!). But then $O_1 \cap O_2 \in \mathcal N_x$ and moreover $$(O_1 \cap O_2) \cap (A \cup B) \subseteq (O_1 \cap A) \cup (O_2 \cap B)= \emptyset$$ contradicting that $x \in \overline{A \cup B}$, so the claimed inclusion holds. The other inclusion $\overline{A} \cup \overline{B} \subseteq \overline{A \cup B}$ again follows from (a) as before (a union is a superset of each of its unionees etc.).
For (c) use def 1 and note that for each fixed $a'$, $A_{a'} \subseteq \bigcup_{a \in A} A_a$ and so part (a) gives $\overline{A_{a'}} \subseteq \overline{\bigcup_{a \in A} A_a}$ and as this holds for all $a' \in A$ we get again $\bigcup_{a \in A} \overline{A_a} \subseteq \overline{\bigcup_{a \in A} A_a}$ as required.
The approach you do via def 2 is also possible: let $x \in \bigcup_{a \in A} \overline{A_a}$. Then for some $a' \in A$, $x \in \overline{A_{a'}}$. Now let $O \in \mathcal N_x$ be arbitrary. Then $O \cap A_{a'} \neq \emptyset$ and so trivially $O \cap (\bigcup_{a \in A} \overline{A_a}) \neq \emptyset$ too (as $A_{a'}$ is a subset of the union). As $O$ was arbitrary, $x \in \overline{\bigcup_{a \in A} A_a}$ and we're done.


text:
Q: Google Play Store Pre-registration sign up showing zero even though people have pre-registered my app So I have uploaded a game app on the google play store and currently, it's up for pre-registration. The problem is, even though I have ensured that quite a number of people have pre-registered but the play console dashboard is not updating and it's showing zero. I couldn't find any proper answer to this question. Can anyone kindly tell me why this might be happening and when it'll be updated?
[Pre-registration Date] [1]
[1]: https://i.stack.imgur.com/eJRGA.png

A: I had same problem so I asked google support and I got this reply.

Thanks for contacting the Google Play Developer Support team.

I understand that you have concerns regarding your app's statistics for pre-registration users.
Unfortunately, If pre-registration sign-ups have a low number of users, Google Play Console won't display pre-registration sign-up data. For privacy reasons, Google doesn't display pre-registration sign-up data when there are a low number of users. But rest assured, once you've reach or surpassed the threshold you will see the stats for your pre-registration

1 Week Later:
Now my registration crossed 50 and reached around 100. It started showing a 50 sign-up count in the play console. Maybe we have to cross 50 to show numbers, and it takes 3 to 4 days to update the last number.


text:
Q: Flex Mobile Android full screen application at startup I'm developing and Android application using the Flex 4.6 SDK version and AIR 4.0 SDK.
The application has the following manifest parameters (among others):
        <aspectRatio>landscape</aspectRatio>
        <autoOrients>true</autoOrients>
        <fullScreen>true</fullScreen>

and:
<application android:enabled="true">
        <activity android:excludeFromRecents="true">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.DEFAULT" />
                        <category android:name="android.intent.category.LAUNCHER" />
                        <category android:name="android.intent.category.HOME" />
                    </intent-filter>
        </activity>
</application>

So as you may see, the configuration is intended to launch the application as the HOME app, in landscape mode as soon as the device starts.
The application does in fact do everything it's supposed to but when the device boots up, the app does not starts in full screen because you can see the notification/status bar. Next you may see the problem.

What I need to do is to make the app start at full screen when the device boots. Now, the only way to make it start at full screen mode is to restart the application after the device finished booting up.
I hope you can help me solve this anoying problem.
EDIT 1
I also compiled the application using AIR 14 SDK and the behaiviour was exactly the same.
I must add that sometimes, the status bar appears and sometimes it doesn't. I thought it had something to do with the WIFI network connection but it doesn't, since on both cases, as soon as the application, if it has inmediate network connection or if it doesn't, the status bar will sometimes appear and sometimes not appear.
EDIT 2
Further testing make me realize that when the status bar was showing, it was exactly the same scenario as when the fullscreen parameter of the manifest was set to false. Could it be something related to a bug in that parameter or something like that?

A: just go into the manifest and use a full screen theme.
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >


text:
Q: Unit Testing in PHP Do you guys do any unit testing in PHP?  I'm not sure if I've ever done it... what exactly is it?  Can you provide a simple example?

A: Unit testing

Do you guys do any unit testing in PHP? I'm not sure if I've ever done
  it... what exactly is it?

Unit testing is the practice to test only one single unit(class). For unit test to be any good the should be allowed to run in isolation(alone) and be very fast or else you would probably not run your tests very often.
Integration tests
You could also write integration tests which test the system as a whole and most of the times are much slower to execute. These tests should be written after the unit tests!
TDD
In the past when I coded more (frequently) using PHP language I did not practice TDD(Test-Driven-Development) at all(looking back my code was NOT up the snuff). But now when I do have to do some code in PHP, I really like to test(unit testing) my code properly. In my opinion you should do too, because it makes your convinced of the quality of your code.

Over the years I have come to describe
  Test Driven Development in terms of
  three simple rules. They are:

*

*You are not allowed to write any production code unless it is to make a
  failing unit test pass.

*You are not allowed to write any more of a unit test than is sufficient
  to fail; and compilation failures are
  failures.

*You are not allowed to write any more production code than is
  sufficient to pass the one failing unit test.

  You must begin by writing a unit test
  for the functionality that you intend
  to write. But by rule 2, you can't
  write very much of that unit test. As
  soon as the unit test code fails to
  compile, or fails an assertion, you
  must stop and write production code.
  But by rule 3 you can only write the
  production code that makes the test
  compile or pass, and no more.
If you think about this you will
  realize that you simply cannot write
  very much code at all without
  compiling and executing something.
  Indeed, this is really the point. In
  everything we do, whether writing
  tests, writing production code, or
  refactoring, we keep the system
  executing at all times. The time
  between running tests is on the order
  of seconds, or minutes. Even 10
  minutes is too long

Example

Can you provide a simple example?

First a really simple example to get you started from the phpunit website.
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));

        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}
?>

As a more elaborate example I would like to point you out to a snippet of mine on github.
PHPUnit with code coverage
I like to practice something called TDD using a unit testing framework(in PHP that is phpunit).
What I also really like about phpunit is that it also offers code coverage via xdebug.
As you can see from the image below my class has 100% test coverage. That means that every line in from my Authentication class has been tested, which gives my the confidence that the code is doing what it should. Keep in mind that coverage does not always mean your code is well tested. You could have 100% coverage without testing a single line of production code.
Netbeans
Personally I like to test my code inside Netbeans(for PHP). with just a simple click(alt+f6) I can test all my code. This means I don't have to leave my IDE, which I really like and helps you save time switching between sessions.

A: Do you mean what is unit testing? Or how do i unit test effectively in PHP? If it is the former, then http://en.wikipedia.org/wiki/Unit_testing if it is the latter then https://phpunit.de/

A: I suggest you to have a look at phpunit. Some simple examples are also provided in the manual:
http://www.phpunit.de/manual/3.5/en/writing-tests-for-phpunit.html

A: I guess the best answer is to point to the most popular unit testing tool in PHP - PHPUnit: http://www.phpunit.de/manual/current/en/automating-tests.html
In the PHPUnit's manual you'll find everything you need to start.

A: There is another unit testing framework for PHP5 - SimpleTest. The name doesn't lie - you'll be up and running in minutes with it.
There is also a nice tutorial on Nettuts.

A: I think the manual phpunit (a php unit testing framework) has the adequate manual to get you started into unit testing.
You can start with the automatic testing chapter (which is a fine introduction) and move onward.

A: I'm not doing it yet, but will start probably next week. :)
Unit testing is, as the name implies, testing units of code. These tests are performed automatically. You will write a number of tests and write a job to run these tests on regular intervals (ie, when you check in new code, or just daily at midnight).
You write tests for isolated pieces of code. You provide the code with a fixed input and check the output. The test will know what the output should be and can test the results.
That way, when you change code and break existing functionality that has a unit test, the test will fail, and you will know you broke something.
It is a lot of effort to write these tests, and you shouldn't use them for everything, but they're especially useful for testing core functionality, framework, libraries etcetera.
It is important that your code is flexible and doesn't depend on a whole bunch of other code. If it does, all that code needs to be included in the test too, making it very hard to write and maintain those tests.
It is best to start writing unit tests for new code. You write the tests first and then the code. That will automatically force you to write independant code. :)

A: Unit testing is a simple way to make others believe your software works just as it must. Within unit testing you make sure that your add(2, 3) function, defined as function add($a, $b) { return $a + $b; } will return exactly 5. This is a very useful tool when you're developing complicated software - it helps you and other find minor (hidden, logic) errors. The benefits of unit testing software is to standardize and automatize testing processes so you would not have to write function assert($whatever) { return $whatever === true; } code and make possible human mistakes.

A: Since the other guys mentioned what unit testing is, i'll say why it's good :)
Unit testing (especially for dynamic languages like PHP) is good for several reasons and i'll point out few:

*

*Because PHP is dynamically typed, you can turn a boolean variable into string, array into integer and so on. If you have unit tests that covers your pre- and postconditions, you will avoid errors like that, which are not very pleasant to search for

*When you write tests (and it's good to do it after you've wrote the method) you think of how you are going to use this method in a early stage and by that - you can catch bugs or see design flaws very early in your project development.

*When you have your code covered by unit tests and you start making changes, adding features or refactoring your code, when you break something from the old code - the unit tests will tell you right away. Like that, you can be sure that all the new functionality is not breaking the old one (and bugs like that can show up later in time and can be very hard to find) and your code is in stable state.

I hope that my explanations will be useful :)


text:
Q: PHP: reasons to use GET and POST request at the same time? I am reviewing a system (an old system) in which in some cases, they send data in a form with POST method, but they also send parameters to the url, as if using get.
something like this:
echo "\n<FORM METHOD='POST' NAME='onegroup' ACTION='menu.php?sesion=".$sesion."' >
    <INPUT TYPE='HIDDEN'    NAME='sesion'   VALUE='".$sesion."'>
    <INPUT TYPE='HIDDEN'    NAME='index_login'   VALUE='1'>
[...]
</FORM>\n";

(note, sesion is not a typo, is just the word "session" in spanish)
What happens is that the "sesion" parameter gets sent both by url and by an input field, thus, the 'sesion' variable is then received both in the $_POST array and the $_GET array.
Why would this be necessary and should i leave it like that? or could i just take it off from the url and just rely on the $_POST data?
I have read in the comments for this answer that it is perfectly possible and valid to send data from both GET and POST (although the method itself is only either GET or POST (or others) in this case is POST, because that is the way the form defines). Now in this specific case, why would someone want to send the SAME sesionvariable (i.e. with the same value) by both get (by url) and post requests?
In my menu.php script can read both $_POST and $_GET and each will have its "version" of the variable, but it happens to be the same.
I've also played around and saw that if instead of $_POST or $_GET i read the $_REQUEST array, i get all the variables together, but in the case of the duplicated one (sesion), the post version gets precedence.
Another thing is that they rely on the "Register Globals" option, and thus, instead of explicitly using $_GET["sesion"] or $_POST["sesion"]  (or even $_REQUEST[]) they just use '$sesion' everywhere to use that information (and just the same for any other variable in the request). Again, playing around, i see that in that case, the POST version of the variable gets precedence also. But can I always rely on that?
Should I just use the post method and remove the parameter from the url?
Why would they want to do this instead of just sending everything by post? As I see it, there is no reason of using both, specially since both have the SAME value. If they didn't they could just choose which version to use, but that is not the case, and I can't think of anything other that it is just something they left there and never "fixed"
What are some "real-life" examples in which someone would need to use such scenario with both POST and GET requests, and specially with the same variable name in both?
thanks.

A: You should remove one of them (preferably GET) if the values are same. However, you also need to make sure that you make corresponding changes to your form processing logic so that the code gets the values it is expecting. It is better to use $_POST or $_GET in place of $_REQUEST since that way you are explicit about what values you are passing and what values is your code expecting. For example, if you are using $_REQUEST then your POST values can be overwritten by GET which might be a security issue. Also, it is not a good idea to rely on register globals as that could cause a security issue too plus the register global on/off setting might differ from server to server. As for why would someone do this, it could be an error or a lack of knowledge about the way PHP GET/POST works.
For a real life scenario:

For many of my applications, I use sessions and pass the php session_id as a GET parameter in the url from page to page. Each page also has a "verify.php" required which validates a session and checks if a user is logged in. If I am dealing with the forms, then I just creates forms and specify the action part as :
action="form_submit_page.php?SID=<?php echo Session_ID(); ?>"

The form passes the values from one page to another as POST while the action part passes session as GET.

A: I use query sting parameters (GET) to chose the active page and POST values to carry form data. There is a legitimate use-case for this.
If the data is a repeat, then kill the GET.


text:
Q: All users in a room join another room I would like that all users in a room (roomOne) join another room (roomTwo). I tried that code :
io.to('roomOne').join('roomTwo');

But it doesn't work. I got that error :
TypeError: io.to(...).join is not a function

How could I do ?

A: You can loop through the sockets connected to the room and ,one by one, join the new room
var clients = io.sockets.adapter.rooms[oldroom].sockets;

for (var clientId in clients ) {
  io.sockets.connected[clientId].join(newroom);
}

(socket.io version: 1.4.5)


text:
Q: Pool().map: modify the shared object Consider the following toy example. I am making a parallelization to compute the value of square function while making some modifications of the shared object A.
import multiprocessing

A = [1, 2]

def square(i):

    A[i] = 2 + A[i]

    return i * i

square(0)
square(1)

print(A)

A = [1, 2]

multiprocessing.Pool().map(square, [0, 1])

print(A)

The output is the following
[3, 4]
[1, 2]

But I expect it to be
[3, 4]
[3, 4]

As indicated above, the serial version of square function managed to change A from [1, 2] to [3, 4]. But the pool.map failed to modify A. So I am asking how to modify the shared object using pool().map. Thanks in advance!

A: If your startmethod is spawn or forkserver, then A is not a shared object in the first place. And if you're on Windows, spawn is the default, and only choice.
If your startmethod is fork, then A may be a shared object—but if it is, it isn't actually safe to mutate it without any locks.
As explained in Sharing state between processes, you should try as hard as possible to not need shared objects—it's kind of the whole point of multiprocessing that the processes are isolated from each other—but if you really do need them, you have to do something a bit more complicated.
The first option is using shared memory. In this case, you're using your list as a fixed-sized array of small ints, which you can simulate with an Array('i', [1, 2]), which you can use exactly as in the example in the docs. For more complicated cases, you often need to add a Lock or other synchronization mechanism to protect the shared memory. This is pretty efficient and simple, but it only works when your shared data is something that can be mapped to low-level types like this.
The second option is using a Manager.list([1, 2]), which you can use exactly as in the very next example in the docs. This is a lot less efficient—it works by creating a queue and passing messages back and forth that tell the main process to do the work whenever you want to access or mutate the list—but it has the advantage of being dead simple to use.

But again, it's usually better to not do either of these things, and instead rewrite your code to not need shared data in the first place. Usually this means returning more data from the pool tasks, and then having the main process assemble the returned values in some way. Of course this is tricky if, e.g., other tasks inherently need to see the mutated values.  (In such cases, you'd often have to build 80% of what Manager is doing, at which point you might as well just use Manager…). But in your toy example, that isn't the case. (And, in fact, when you think that's unavoidably necessary, it often means you haven't thought through how nondeterminism is going to affect your algorithm, and it wouldn't have worked anyway…)
Here's an example of how you could do this with your toy problem:
import multiprocessing

def square(i, aval):
    # actual return value, i, and value to set A[i] to
    return i*i, i, 2+aval

A = [1, 2]
# pass each A[i] into the function
for result, i, aval in multiprocessing.Pool().starmap(square, zip([0, 1], A)):
    # get the new A[i] out of the function and store it
    A[i] = aval
print(A)


text:
Q: Is it possible to send readed sqlite from php and send it via socket? Is it possible to me to read data from sqlite with php and send it with php script to another server?
Ex: I have a "Local sqlite" database, i have a web. Basically i want someone can see some prefered content at my "Local sqlite database" from my web.
is that possible to do it with php tcp socket script?
PHP Read Local sqlite -> send the data to server through socket -> server listened and received the data -> Php show received data.
I can't do it right for now so i ask my problem here.

A: Yes, it is possible to switch from MySQL to SQLite if you already have working code.
You have to use either SQLite extension or PDO.
Most queries do not need modification and can be used transparently between these databases.


text:
Q: Closed form expression for the series $\sum_{k=0}^\infty \frac{k^j}{k!}$ in terms of $j$ For my research I need to compute "approximate" moment generating function (we approximate exponential with the first $D$ elements of its Taylor series) of the number of fixed points of a permutation which involves the following sum:
\begin{equation}\sum_{k=0}^\infty \frac{k^j}{k!} \end{equation}
in terms of $j$. I am pretty sure this grows exponential in $j$ but I am interested in finding the exact exponent. With some elementary calculations I get the following recurrence relation
\begin{equation}\sum_{k=0}^\infty \frac{k^j}{k!}  = \sum_{m=0}^{j-1}{j-1\choose m} \sum_{k=0}^\infty \frac{k^{j-1-m}}{k!}  \end{equation}
but I couldn't proceed further.

A: This will be
$$
\lim_{x\to1}\left(x\frac d{dx}\right)^j e^x=\lim_{x\to1}e^x\sum_{k=1}^j{j\brace k}x^k=
B_je,
$$
where ${j\brace k}$ are the Stirling numbers of the second kind and $B_j=\sum_{k=1}^j{j\brace k}$ are the Bell (or exponential) numbers.

A: Note that we have
$$\sum_{k=0}^\infty \frac{k^j}{k!}=\left(\left.\left(x\frac{d}{dx}\right)^j\{e^x\}\right)\right|_{x=1}$$

LEMMA:
In general, if $f(x)$ is $n$ times differentiable, then we have
$$\left(x\frac{d}{dx}\right)^j\{f(x)\}=\sum_{k=1}^j  \begin{Bmatrix} j \\ k \end{Bmatrix}x^k\frac{d^k\,f(x)}{dx^k}$$
where $\begin{Bmatrix} j \\ k \end{Bmatrix}=\frac1{k!}\sum_{\ell=0}^k (-1)^{k-\ell}\binom{k}{\ell}\,\ell^j$ are the Stirling Numbers of the Second Kind.

PROOF:
We assume that we can write $\left(x\frac{d}{dx}\right)^j\{f(x)\}$ as
$$\left(x\frac{d}{dx}\right)^j\{f(x)\}=\sum_{k=1}^j s(j,k)x^k\frac{d^kf(x)}{dx^k}$$
for coefficients $s(j,k)$, where $s(j,1)=1$.  As an inductive base case, take $j=1$.  Then, we have
$$\begin{align}
\left(x\frac{d}{dx}\right)^{j+1}\{f(x)\}&=\left(x\frac{d}{dx}\right)\sum_{k=1}^j s(j,k)x^k\frac{d^kf(x)}{dx^k}\\\\
&=\sum_{k=1}^j s(j,k)\left(x^{k+1}\frac{d^{k+1}f(x)}{dx^{k+1}}+kx^k \frac{d^{k}f(x)}{dx^{k}}\right)\\\\
&=\sum_{k=1}^{j+1} \left(s(j,k-1)+k s(j,k)\right)x^{k}\frac{d^{k}f(x)}{dx^{k}}\\\\
&=\sum_{k=1}^{j+1} s(j+1,k)x^{k}\frac{d^{k}f(x)}{dx^{k}}
\end{align}$$
where $s(j,k)$ satisfies the relationship
$$s(j+1,k)=s(j,k-1)+ks(j,k)$$
along with the conditions $s(j,1)=s(j,j)=1$ and $s(j,k)=0$ for $k>j$.  Noting that  $S(j,k)$ and $\begin{Bmatrix} j \\ k \end{Bmatrix}$ satisfy the same recurrence relationship and initial conditions, the proof is complete.

If $f(x)=e^x$ then
$$\begin{align}
\left.\left(\left(x\frac{d}{dx}\right)^j\{e^x\}\right)\right|_{x=1}&=e\sum_{k=1}^j \begin{Bmatrix}j\\k\end{Bmatrix}\\\\
&=eB_j
\end{align}$$
where $B_j=\sum_{k=1}^j \begin{Bmatrix}j\\k\end{Bmatrix}$ are the Bell Numbers.

Alternatively, we could use the Faà_di_Bruno Formula to calculate the term $\left(x\frac{d}{dx}\right)^j \{e^x\}$.  To do this, we first make the substitution $x=e^y$.
Then, using the Bell Polynomials, $B_{n,k}(x_1,x_2,\dots,x_{n-k+1})$, we have
$$\begin{align}
\left(\left.\left(x\frac{d}{dx}\right)^j\{e^x\}\right)\right|_{x=1}&=\left(\left.\left(\frac{d}{dy}\right)^j\{e^{e^y}\}\right)\right|_{y=0}\\\\
&=\sum_{k=1}^j \left(\left.\left(e^{e^y}\right)^{(k)}B_{j,k}((e^y)^{(1)},(e^y)^{(2)},\dots,(e^y)^{(j-k+1)})\right)\right|_{y=0}\\\\
&=e\sum_{k=1}^j B_{j,k}(1,1\dots, 1)\tag1\\\\
&=B_j e\tag2
\end{align}$$
In going from $(1)$ to $(2)$ we used the relationship between the Bell Numbers, $B_n$, and the sum over the Stirling Numbers of the second kind:
$$B_n=\sum_{k=1}^n B_{n,k}(1,1,\dots,1)=\sum_{k=1}^n {n \brace k}$$

As a side note, it is interesting to observe that
$$\sum_{j=0}^\infty\frac1{j!} \left(\sum_{k=0}^\infty\frac{k^j}{k!}\right)=e^e$$

A: @user has already answered the question, and @MikeEarnest has noted how little we know about Bell numbers, but I'll chime in with an explanation of where these numbers come from.
In how many ways can we partition a size-$n+1$ set? Call the answer $B_n$. Fix one element $a$ and count the number of solutions in which all but $k$ of the remaining $n$ objects are grouped with $a$; we choose those $k$ in one of $\binom{n}{k}$ ways, so $B_{n+1}=\sum_{k=0}^n\binom{n}{k}B_k$.
It's not hard to show this implies the exponential generating function $B(x):=\sum_n\frac{B_nx^n}{n!}$ satisfies $B(0)=1,\,B^\prime(x)=B(x)\exp x$, so $B(x)=\exp(\exp x-1)$. If we write $B^{(n)}(x)=p_n(\exp x)B(x)$ the polynomials satisfy $p_0=1,\,p_{n+1}(x)=x(p_n(x)+p_n^\prime(x))$, the same recursion relation as the $p_n$ we can define from $\left(x\frac{d}{dx}\right)^n\exp x=p_n(x)\exp x$. This implies these definitions are equivalent, and $p_n(1)=\frac{B^{(n)}(0)}{B(0)}=B_n$, as already stated.


text:
Q: React Native Expo unable to access files above the root React Native Expo project is unable to access files above the root, I can't from the src dir go to import some module from  ../../SharedBusinessLogic
I need to do this as the RN is in a project with multiple projects needing to share the same non-framework specific business logic.
ie
repository:
/

    /SolidjsProject
    /CloudProject
    /ExpoProject
    /SharedBusinessLogic (no package.json)

I get people saying just move the /SharedBusinessLogic into ExpoProject, but that is non-sensical in 2022.


text:
Q: Why can't my Ansible server not communicate with my Windows XP machine? Ansible's official documentation says Windows XP is not a supported os, however, for every day that goes by I'm even more certain you could make it work.
The server is a CentOS 7 machine. I can establish a SSH connection to the Windows XP machine from my server and vice versa.
This is my Ansible hosts file entry for the Windows XP machine:
[winxp]
10.0.2.4

[winxp:vars]
ansible_user=nico
ansible_connection=ssh
ansible_port=22

This is the output when executing ansible winxp -m win_ping:

10.0.2.4 | UNREACHABLE! => {
      "changed": false,
      "msg": "Failed to connect to the host via ssh: ----USAGE WARNING---- This is a private computer system. This computer system,
including all related equipment, networks, and network devices
(specifically including Internet access) are provided only for
authorized use. This computer system may be monitored for all lawful
purposes, including to ensure that its use is authorized,   for
management of the system, to facilitate protection against
unauthorized access, and to verify security procedures, survivability,
and operational security. Monitoring includes active attacks by
authorized entities to test or verify the security of this system.
During monitoring, information may be  examined, recorded, copied and
used for authorizedpurposes. All information, including personal
information, placed or sent over this system may be monitored. Use of
this computer system, authorized or unauthorized, constitutes consent
to monitoring of this system. Unauthorized use may subject you to
criminal prosecution. Evidence of unauthorized use collected during
monitoring may be used for administrative, criminal, or other adverse
action. Use of this system constitutes consent to monitoring for these
purposes.
      Permission denied
(publickey,password,keyboard-interactive).",
"unreachable": true }

Why does it say "Failed to connect to the host via ssh:" when it can perfectly do so outside of Ansible?
Adding this line to the hosts file doesn't change anything:
ansible_ssh_server_cert_validation='ignore'

And adding the line ansible_password=xxxx and executing the same command shows the following output:

10.0.2.4 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ",
    "unreachable": true
}

Does anyone have any idea? Is it really impossible? Do I need a specific python version, powershell version, or anything else installed on the Windows XP machine?
EDIT: WORKAROUND FOR THIS
So, as mentioned on the answer, Ansible can't be used on Windows XP. However, there is a workaround for this. You can create a playbook that runs commands on the Windows XP machine using sshpass, and run that playbook on the same Ansible machine. Here is the playbook I used:
---
- hosts: ansible_server
  tasks:
    - name: Test
      shell: sshpass -p 'nico' ssh nico@10.0.2.4 "cmd.exe /c mkdir C:\it_works"

Hope this can help someone

A: Even if you manage to get ssh to connect successfully, Ansible requires PowerShell 3.0, which does not work on Windows XP. It needs 2008/Vista or later. You don't need to waste any more time with trying to make it work.


text:
Q: iCheck check boxes are not visible in print I am using iCheck check boxes, everything works fine in browser and coding,
But when i am trying to print page then checkbox are not at all visible,
<label>
   <input type="radio" name="ques_apti" class="icheck" data-radio="iradio_square-red" value="12">
</label>

Is there any way to print check boxes on paper?
Even if you just right click on this page http://icheck.fronteed.com/ and print, this page also doesn't show check boxes in print,
Any solution or workaround?
Thank you,

A: I added this to the print.css and it worked :
@media print {
    input[type=checkbox], input[type=radio] {
        opacity: 1 !important;
    }
}

A: I devised a quick fix. If you would like to print with the default styling of the checkboxes, you can simply change the opacity of the checkbox to 1 and back to 0. The iCheck plugin sets the opacity to 0. (I was using the print plugin to print a certain div on the page)
$('input.flat:checkbox').css('opacity', '1');
$('#myDiv').print();
$('input.flat:checkbox').css('opacity', '0');


text:
Q: Python Not Sending Email To Multiple Addresses I can't see where i'm going wrong with this, I hope someone can spot the problem. I'd like to send an email to multiple addresses; however, it only sends it to the first email address in the list and not both. Here's the code:
import smtplib
from smtplib import SMTP

recipients = ['example1@gmail.com', 'example2@example.com']

def send_email (message, status):
    fromaddr = 'from@gmail.com'
    toaddrs = ", ".join(recipients)
    server = SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('example_username', 'example_pw')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

 send_email("message","subject")

Has anyone came across this error before?
Thank you for your time.

A:    import smtplib

   from email.mime.text import MIMEText

   s = smtplib.SMTP('xxx.xx')

   msg = MIMEText("""body""")
   sender = 'xx.xx.com'

   recipients = ['example1@gmail.com', 'example2@example.com']

   msg['Subject'] = "test"
   msg['From'] = sender
   msg['To'] = ", ".join(recipients)
   s.sendmail(sender, recipients, msg.as_string())

A: Change
toaddrs = ", ".join(recipients)

to
toaddrs = recipients

since
server.sendmail(fromaddr, toaddrs, ...)

expects toaddrs to be a list of email addresses. (Or, of course, just use recipients in place of toaddrs.)

A: Try to use this code, without your join:
import smtplib
from smtplib import SMTP

recipients = ['example1@gmail.com', 'example2@example.com']

def send_email (message, status):
    fromaddr = 'from@gmail.com'
    server = SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('example_username', 'example_pw')
    server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

 send_email("message","subject")

Hope it helps!


text:
Q: Paypal Sandbox to run a function after payment is completed I got a total value that the user has to pay after making all their selections.
I used jquery to update the input value and add it dynamically into the html.
Once they click on 'pay now', a sandbox popup window opens where the user has to login into their paypal account and complete the payment.
How can I check that the payment is completed in php? Right now I have a form on my website that when all filled out, after the payment is verified, it should be submitted automatically (or show a button to complete the submission).

A: If you want to know the status of the payment once the transaction is complete, you would need to use either PDT or IPN.
I would recommend IPN which is more secure.

Instant Payment Notification (IPN) is a message service that
  automatically notifies merchants of events related to PayPal
  transactions. Merchants can use it to automate back-office and
  administrative functions, like fulfilling orders and providing
  customers with order status.

Simple Instruction for IPN:
Pre-requieste:
Enable IPN in your paypal profile.
1) Sample code:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="XXX@gmail.com">
<input type="hidden" name="item_name" value="test">
<input type="hidden" name="amount" value="1.00">
<input type="hidden" name="notify_url" value="https://XXX.com/ipn.php?email_address=vravichandran@paypal.com">
<input type="image" src="https://www.sandbox.paypal.com/en_GB/i/btn/btn_buynow_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

2) Check notify_url in above URL where your IPN listener file should reside.
3) Sample IPN listener file here can be downloaded here.
Just run the above code and check your IPN history in your paypal profile.


text:
Q: What is the window class name assigned by Visual Studio when creating .NET form? As in VC++ when creating a window we need to create a window class and use RegisterClass or RegisterClassEx to register. But in .NET we don't have this step.
So I wonder what the default window class name assigned by Visual Studio when creating a form?
As I've tracked out, the window class name assigned by Visual Studio is somewhat similar to this:
WindowsForms10.Window.8.app.0.1ca0192_r13_ad1
I want to change this default window class name, any idea?

A: Window class names are automatically generated.  You cannot change them, even though CreateParams lets you set the ClassName property.  Nor can an external program ever guess the auto-generated name correctly, part of it is generated from AppDomain.CurrentDomain.GetHashCode().
You'll need another way to identify the window.  Not much available, but you could pinvoke SetProp() to associate an arbitrary string to a window.  And test if it is present with GetProp().  The SDK article is here.


text:
Q: Sorting a List of Lists I have this list of lists:
data = [['john','1','2', 2.45434], ['jack','1.3','2.2', 4.45434],
        ['josh','2','3', 3.45434]]

I want to sort it by the very last decimal number in each inner list. How can I do this?

A: You can specify the key in the sorted function as the last element of the sub lists:
sorted(data, key = lambda x: x[-1])

# [['john', '1', '2', 2.45434],
#  ['josh', '2', '3', 3.45434],
#  ['jack', '1.3', '2.2', 4.45434]]

A: You may sort the existing "data" list by .sort() function of list using lambda function as:
data = [['john','1','2', 2.45434],['jack','1.3','2.2', 4.45434], ['josh','2','3', 3.45434]]
data.sort(key=lambda x: x[-1])
# data = [['john', '1', '2', 2.45434], ['josh', '2', '3', 3.45434], ['jack', '1.3', '2.2', 4.45434]]


text:
Q: How to configure azure-cli behind a corporate proxy on Windows I'm using Windows 10 behind a corporate proxy and az --version outputs the following:
azure-cli                          2.5.1

command-modules-nspkg              2.0.3
core                               2.5.1
nspkg                              3.0.4
telemetry                          1.0.4
...
Unable to check if your CLI is up-to-date. Check your internet connection.

Furthermore, az extension list-available throws:
Unable to get extension index.
Please ensure you have network connection. Error detail: HTTPSConnectionPool(host='aka.ms', port=443): Max retries exceeded with url: /azure-cli-extension-index-v1 (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',)))

How to configure azure-cli for the corporate proxy?

A: *

*Download local proxy configuration from http://wpad/wpad.dat

*At the beginning of the wpad.dat file there is a line similar to CWSProxy="PROXY proxy.corporation.com:8082";

*Enter the proxy server to environment variable HTTPS_PROXY, e.g. in bash: export HTTPS_PROXY="proxy.corporation.com:8082"
Now az extension list-available connects. However, for some reason, az --version is still giving Unable to check if your CLI is up-to-date. Check your internet connection. You can now anyway install extensions such as az extension add --name azure-devops.

A: From https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest&tabs=azure-cli#proxy-blocks-connection
For Windows 10, you could check the proxy settings in the Settings > Network & Internet > Proxy pane. Contact your system administrator for the required settings, or for situations where your machine may be configuration-managed or require advanced setup.


text:
Q: split dates column in R when there are no sperators I have a data set with date column with following format i.e. 19700101
How can I convert it as 1970-01-01 format
I tried zoo package in R but could not work it out. Can any one help me on this

A: library(anytime)
anydate(19700101)


text:
Q: When creating a vector of objects, how to pass arguments to Default or Copy Constructor to initialize values? For a program I'm writing for a project in my C++ class, one of the requirements is to use constructors to initialize data members in objects.
We also have to read from binary files.
The method I chose to accomplish this was:
// Loads invmast.dat or creates one if none exists
fstream invFile;
invFile.open("invmast.dat", std::fstream::in);
if (!invFile)
{
    cout << "File invmast.dat not found, creating a new one." << endl;
    invFile.open("invmast.dat", std::fstream::out | std::fstream::app | std::fstream::binary);
    if (!invFile)
    {
        cerr << "Unable to create or open file invmast.dat; exiting." << endl;
        exit (EXIT_FAILURE);
    }
}
cout << "File invmast.dat opened successfully." << endl;

vector <InventoryItem> invMast;
//vector <InventoryItem>::iterator invMastIterator;

InventoryItem invLoader;

while ( invFile && !invFile.eof())
{
    invFile.read(reinterpret_cast<char *>(&invLoader), sizeof(invLoader));
    invMast.insert(invMast.begin(), invLoader);
}

I'd prefer to create a vector of objects and pass the arguments to the copy or default constructor, but I can't seem to find a way to do this.
Is there a way, or do I need to rethink my approach?
Thanks!

A: If you were simply constructing an element, you could use emplace_back to construct it directly in the vector:
invMast.emplace_back(some, constructor, parameters);

But here, since you're initialising the InventoryItem from raw bytes, you probably just want to construct an object and move it into the vector:
invFile.read(reinterpret_cast<char *>(&invMast.back()), sizeof(invLoader));
invMast.push_back(std::move(invLoader));

Or default-construct an element and then fill it:
invMast.emplace_back();
invFile.read(reinterpret_cast<char *>(&invMast.back()), sizeof(InventoryItem));


text:
Q: How can I manually cut existing polylines at a point of my choosing in MapInfo? I want to edit polylines so that only the part of the polylines that fall within a certain area are remaining. SQL queries highlight the whole polyline if it falls within the desired area and hence does not achieve the goal. Thanks

A: *

*First select all polylines you want to cut

*then go to menu Objects and choose "Set target (ctrl+T)"

*Now select a polygon or area

*If you want to cut polylines which falls outside selected polygon/area choose "Objects/Erase Outside..."
Data Disaggregation window will show up and you will have to choose method.
After that, polylines will be sliced just at points where intersection with selected polygon occurred

A: With MapInfo Pro v2019 we added support for showing derived objects in queries instead of objects from the base table.
We introduced a new keyword that lets you specify that you want to see the derived object instead of the object from the base table. The keyword is Object.
You use this keyword by placing it after the expression that creates the derived spatial object in the SQL Select statement. Like this:
Select a.*, Buffer(a.obj, 20, 25, "m") Object
From Addresses As "a"
Into Selection

In the basic example above, I create a buffer around the input point dataset and using the Object keyword I specify that I want to see this derived spatial object when I show the query in a map.
Similar you can extract the part of a line that is within a polygon and show this:
Select r.*, c.NAME, Overlap(c.OBJ, r.OBJ) Object
From roads As "r", CityBoundaries As "c"
Where r.OBJ Intersects c.OBJ


text:
Q: Creating and using a Texture in DirectX I'm trying to create a texture using code, turn it into a shader resource view then apply it to a plane, however all I'm getting is a black square. I tried using the sample code on msdn to no avail, also tried using unsigned char and float (float is shown below as that is what I'll need to use for my end goal).
Here is the code trying to create the texture:
    bool TerrainClass::CreateTexture(ID3D11Device* _device)
{
    ID3D11Texture2D *texture;
    D3D11_TEXTURE2D_DESC tdesc;
    D3D11_SUBRESOURCE_DATA data;

    float *buf = (float *)malloc(m_terrainWidth * m_terrainHeight * 4 * sizeof(float));

    for(int i = 0; i < m_terrainWidth * m_terrainHeight * 4; i++)
        buf[i] = 1.0f;

    data.pSysMem = (void *)buf;
    data.SysMemPitch = m_terrainWidth * 4;
    data.SysMemSlicePitch = m_terrainWidth * m_terrainHeight * 4;

    tdesc.Width = m_terrainWidth;
    tdesc.Height = m_terrainHeight;
    tdesc.MipLevels = 1;
    tdesc.ArraySize = 1;
    tdesc.SampleDesc.Count = 1;
    tdesc.SampleDesc.Quality = 0;
    tdesc.Usage = D3D11_USAGE_DEFAULT;
    tdesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

    tdesc.CPUAccessFlags = 0;
    tdesc.MiscFlags = 0;

    //attempt to create the 2d texture
    if(FAILED(_device->CreateTexture2D(&tdesc,&data,&texture)))
        return false;

    //assign the texture made from fbm to one of the textures for the terrain
    if(!(m_Textures->ChangeTexture(_device, texture, 2)))
        return false;

    delete[] buf;

    return true;
}

Unless I'm misunderstanding that should be a white texture made. The texture is then passed into the texture array to this function:
bool TextureArrayClass::ChangeTexture(ID3D11Device* _device, ID3D11Texture2D* _texture, int _i)
{
        if(FAILED(_device->CreateShaderResourceView(_texture,NULL, &m_textures[_i])))
        {
            return false;
        }
        return true;
}

Which should set the shader resource view to be the texture I just created.
So I'm completely lost as to where I've gone wrong, any thoughts?

A: data.SysMemPitch should be in bytes, so m_terrainWidth * 4 * sizeof(float).  Same with SysMemSlicePitch but you can set that to zero since you only need that for a texture cube, volume, or array.  You should also verify that the D3D_FEATURE_LEVEL you're running on supports using R32G32B32A32 in the way you're using it (to Sample I assume).  Verify support by reviewing this page or calling CheckFormatSupport. If your hardware doesn't support the pattern you're using, switch to a more broadly supported format like B8G8R8A8_UNORM (and be sure to change your initial data as well to match the format layout).


text:
Q: how to map snps to ref gene file I have the following data set about the snps ID
  POS ID
    78599583    rs987435
    33395779    rs345783
    189807684   rs955894
    33907909    rs6088791
    75664046    rs11180435
    218890658   rs17571465
    127630276   rs17011450
    90919465    rs6919430

and a gene reference file
genename    name    chrom   strand  txstart txend
CDK1    NM_001786   chr10   +   62208217    62224616
CALB2   NM_001740   chr16   +   69950116    69981843
STK38   NM_007271   chr6    -   36569637    36623271
YWHAE   NM_006761   chr17   -   1194583 1250306
SYT1    NM_005639   chr12   +   77782579    78369919
ARHGAP22    NM_001347736    chr10   -   49452323    49534316
PRMT2   NM_001535   chr21   +   46879934    46909464
CELSR3  NM_001407   chr3    -   48648899    48675352

I'm trying to match the genes with the SNps location, so include the snps that has
POS >= txstart and POS<= txend
for example I want a data set that has the following columns
genename   SNPID   chrom   position   txstart   txend

A: As far as I can see, your sample files do not contain any matches of the kind you describe.
If we modify the first file to
CHROM  POS ID
chr7    78599583    rs987435
chr15   33395779    rs345783
chr1    189807684   rs955894
chr20   33907909    rs6088791
chrx    1234567     rsMadeUp
chr12   75664046    rs11180435
chr1    218890658   rs17571465
chr4    127630276   rs17011450
chr6    90919465    rs6919430
such that the made-up entry falls in the range
genename    name    chrom   strand  txstart txend
CDK1    NM_001786   chr10   +   62208217    62224616
CALB2   NM_001740   chr16   +   69950116    69981843
STK38   NM_007271   chr6    -   36569637    36623271
YWHAE   NM_006761   chr17   -   1194583 1250306
SYT1    NM_005639   chr12   +   77782579    78369919
ARHGAP22    NM_001347736    chr10   -   49452323    49534316
PRMT2   NM_001535   chr21   +   46879934    46909464
CELSR3  NM_001407   chr3    -   48648899    48675352
then
awk '
    NR == FNR && FNR > 1 {snp[$2]=$3; next}
    FNR > 1 {
      for (p in snp) {if (p>=$5 && p<=$6) print $1, snp[p], $3, p, $5, $6}
    }
  ' snpsid generef
YWHAE rsMadeUp chr17 1234567 1194583 1250306

A: You can use awk for this:
awk 'FNR==1 {next} FILENAME=="snipsid" {k++; POS[k]=$2; ID[k]=$2;} \
        FILENAME=="gene" {i++; if(POS[i]>=$5 && POS[i]<=$6) \
        print $1, ID[i], $3, POS[i], $5, $6} \
    ' snipsid gene >out_file


text:
Q: Running a standard .NET Console Application in docker container I am trying to run a very simple console application as a windows docker container. I have a docker file shown below using the "dotnet-framework:4.7.2-runtime-windowsservercore-1803" base image.
FROM microsoft/dotnet-framework:4.7.2-runtime-windowsservercore-1803
ARG source
WORKDIR /app
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT "DockerConsoleApp.exe"

The console application just outputs "Hello World" to a log file every 5 seconds"
static void Main(string[] args)
    {
        while (true)
        {
            try
            {
                Thread.Sleep(5000);
                _logger.Info("Hello Wolrd");
            }
            catch (Exception e)
            {
                //handle the exception
                Console.Error.WriteLine(e);
            }
        }

    }

I am using the following docker compose file
version: '3.4'

services:
  dockerconsoleapp:
    image: dockerconsoleapp:dev
    build:
      context: .\
      args:
        source: obj\Docker\publish
    volumes:
      - C:\Users\user\source\repos\DockerConsoleApp\DockerConsoleApp:C:\app
      - C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Remote Debugger:C:\remote_debugger:ro
      - C:\Users\user\source\repos\DockerConsoleApp\VolumeTest:C:\app\logs

The problem is that as soon as I manually build or run "docker-compose up -d" The container is created and then immediately dies. I would expect that the container should stay up given that the application is being called in the entrypoint and the application should just keep going unless manually stopped.

A: In the end, the fix was to change the ENTRYPOINT to a CMD in the dockerfile. See below.
FROM microsoft/dotnet-framework:4.7.2-runtime-windowsservercore-1803
ARG source
WORKDIR /app
COPY ${source:-obj/Docker/publish} .
CMD ["DockerConsoleApp.exe"]

I have let this run overnight and the container is now up 15 hours.

A: Your container died most likely as a result of exception in your ENTRYPOINT or ENTRYPOINT itself not being valid. You can examine docker logs to find out a reason.


text:
Q: Testing Qt application in Visual Studio - Qt files giving 'cannot open source file' error when including project files in test file I'm trying to write tests for a Qt application in visual studio.  I've added a new test project to the existing solution that has the project I'm wanting to test, and added a reference to said project as shown here.  When I try to run a test file, I get errors saying 'cannot open source file "x"' for a bunch of Qt and Qt generated files like QWidget and 'ui_x.h' (x is a placeholder).  I'm using Google Test, but the same issue occurs when using the 'Native Unit Test Project' option.
Image of problem

Settings.h
#pragma once

#include <string>
#include <QWidget>
#include <QSettings>
#include <QFileDialog>

#include "ui_Settings.h"

extern const std::string MODS_FOLDER_PATH;
extern const std::string  PROFILE_PATH;

class Settings : public QWidget
{
    Q_OBJECT

public:
    Settings(QWidget *parent = Q_NULLPTR, QString testHook = "");
    QString getModsFolderPath();

public slots:
    void browseProfilePath();
    void browseModsPath();
    void openSettingsWidget();

signals:
    void modsFolderPathChanged(const QString &newPath);
    void profilePathChanged();

private:
    Ui::Options ui;
    QString testHook;
    QString fileBrowser(QFileDialog::FileMode fileMode, const std::string  = "");
    bool changeFileSetting(QLineEdit * const settingInput, const std::string setting, const QString &fileName);
    void loadValuesFromSettings();
};

test.cpp
#include "pch.h"
#include "../FileOverwriteManager/Settings.h"

TEST(TestCaseName, TestName) {
  EXPECT_EQ(1, 1);
  EXPECT_TRUE(true);
}

A: I had to edit the 'Additional Include Directories' under 'C/C++' in the test project's properties as suggested by user vahancho.  If you only include the directories where the .h files are, i.e. C:\Qt\5.10.0\msvc2017_64\include\QtCore for qsettings.h, then it complains like so, so you have to also include one directory higher, i.e. C:\Qt\5.10.0\msvc2017_64\include\


text:
Q: React and Type script createContext initial data for functions I have a context that is used to create, update, list and delete a set of data.
It is created as follows with the following types to be returned.
type TDataContext = {
    loading: boolean,
    getDataList: () => TData[],
    addNewData : (data: TData) => Promise<boolean> ,
    editData: (dataId: string, data: TData) => Promise<boolean>,
    deleteData: (dataId: string) => Promise<boolean>,
}

const ADataContext = createContext<TGymClientDataContext>({
    // How to initialize these here ?
})

export const ADataProvider: FC<{}> = ({children}) => {

    const [loading, setLoading] = useState(true)
    const [snapshot, loading, error] = useCollection<TDataStore>(db.collection(FIRESTORE_COLLECTIONS.DATA_COLLECTION), {});

    const getDataList = async (): TData[] => {
        if(loading == true) {
            return []
        }
        if(typeof snapshot == "undefined"){
            return []
        }
        return snapshot?.docs.map((item) => {
            const fetched = item.data();

            return ({
                id: item.id,
                doj: fetched.doj.toDate(),
                firstName: fetched.firstName,
                lastName: fetched.lastName,
            })

        })
    }

    //    ... Function definitions

    const values = {
        loading,
        getDataList,
        addNewData,
        editData,
        deleteData,
    }

    return <ADataContext.Provider value={values}>
        {children}
    </ADataContext.Provider>

}

export const useDataHook = () => useContext(ADataContext)

*

*I would like to know what will be the good possible way to pass initial data to createContext ?

I'm creating this with the following usage to be expected
const {loading, getClientList, editClientData, addNewClient, deleteClientData} = useGymClient()

The functions are simply expected to return true or false depending on the operations being successful or not.
Another question is,

*The data has to be always caught via getDataList function.
is directly passing the snapshot variable down better approach ? In that case, what will be a better initializer for the create context


text:
Q: SaddlePoint Approximation Score Statistic My question will be very practical. Actually, I work in statistical genetics and I have 1000 Score statistics for which I want to compute the corresponding p-values. To be more specific, I suppose a conditional retrospective model:
$P(G|Y) = \frac{\exp{(\beta\sum_ig_{i}P(G_i))}} {\sum_{G^*}\exp{(\beta\sum_ig_{i*}P(G_i*))}}$
where  $g_i$ = {0, 1, 2}, is the number of minor alleles for one variant in an individual i and P(Gi) the corresponding probability to observe this variant. The denominator corresponding to the sum of all possible genotypic configurations. Here we can suppose a log-linear model of the variant effect.
Since I computed the Score statistic and the related Covariance matrix, I know that:
$Q = S^tV^{-1}S \sim \chi_{1}$ under the null.
However, asymptotic theory does not work very well in my tails (as expected due to rare variants i.e., lot of zero), providing inflation of Type I error. I read that Saddlepoint approximation might be a excellent solution to this problem since it uses the entire cumulant-generating function (CGF), while when we use normal approximation only the two first cumulants are used (mean and variance, respectively).
Some methods have been proposed to compute p-values (Lugannani and Rice, 1980) but it is not clear for me how to use it in my context.
To my current knowledge, here I may compute approximated distribution using the moment-generating function (MGF) of a poisson distribution. In this paper (https://www.biorxiv.org/content/10.1101/2020.10.31.358234v1.full.pdf) authors use closed approach.
If anyone have inputs it would be appreciated.


text:
Q: to_enum(:scan) vs scan alone with regular expression in ruby I dont understand why we use to_enum to make the string enumerable when the scan method would return an array of matches itself, what to_enum doing in this case?
this is the code with to_enum:
string = "The quick 12 brown foxes jumped over the 10 lazy dogs"

p string.to_enum(:scan, /\d+/).map {Regexp.last_match }

which return:
=> [#<MatchData "12">, #<MatchData "10">]

so why we use here to_enum to make the string enumerable when we can use scan which will return an array?
also I tried using scan alone but get weird result:
p string.scan(/\d+/).map { Regexp.last_match}
=>[#<MatchData "10">, #<MatchData "10">]

There is something I missing and not understanding here... can anyone explain it please?
thanks

A: to_enum isn't making the string enumerable, it's actually making String#scan a lazy enumerator. enum_for is an alias of to_enum and that might have helped clarify things here somewhat. map yields each result of the scan—one at a time (lazily)—to the block, which uses the last_match Regexp class method to return the last, most recent match. It's a really contrived example that you're not likely to see in the wild.


text:
Q: multiple iframes not loading in DOM Hi there I have the following iframes:

I have tried both ...
$(window).load(function (eventObject) {

});

and
$(document).ready(function (eventObject) {

});

but inside either one of these functions I can only access the first Iframe in this case IframeAuditLog in the DOM. If I change the HTML to be the following:

... Only DocumentManagerFrame is loaded in the DOM ... Any one have any idea whats going on?

A: You have to actually close the iframe, otherwise it stays open until the browser decides to fix it and add the closing tag, and when that is, is anyones guess ?


text:
Q: How does miro embed vlc I am sorry if this sounds like a dumb question, but I am looking at the code to see how VLC can be embedded in another program.
Some time ago, I read that Miro uses VLC library or source code.
However I cannot find any references to VLC in the Miro source code.
The question is: How does miro embed vlc?
Any help is greatly appreciated.

A: The best way to find out is to look at the Miro source code, which can be browsed on GitHub here: https://github.com/pculture/miro/
BTW, Miro says they use Gstreamer and Xine on Linux, not VLC.  The OSX version uses Quicktime.  Only the Windows version uses VLC, so that suggests focussing on this area of the code:
https://github.com/pculture/miro/tree/master/tv/windows
From there, a grep turns up this:
plat/xulhelper.py:pcfIDTVVLCRenderer = components.interfaces.pcfIDTVVLCRenderer

Looking a few lines above that, you'll see:
from xpcom import components

So, VLC is being used somehow via XPCom.  From there, you would have to figure out how XPCOM and VLC are talking together.  If you aren't already tied to XULRunner and XPCOM, I would suggest finding another way to do this.  If you goal to use VLC from inside your own Python program?  Inside your own C/C++ program?  What GUI toolset are you using?
Response to comment:
If you like java, http://caprica.github.io/vlcj/ is vlc java bindings that look ok, but warning I'm not really a Java guy.
For python, you could try pyqt and vlc-qt, but that could take some fiddling.
If you know a little C++, using Qt, and either libVLC directly or vlc-qt would probably be easiest.  If you don't already know C++ and Qt, then it wouldn't be.