text:
Q: How to filter out harmonics (DSP) using MATLAB? i have this code which adds the 3rd harmonic to the fundamental signal and then using a filter takes back the fundamental. I have to modify this code in order to add the 3rd, 5th and 7th harmonic and then filter them out, but i dont know how to make the filter do that.
t = [0:199];
A1 = 100;
s1 = A1*sin(2*pi*(1/40)*t); % fundamental
A3 = A1/3;
s3 = A3*sin(2*pi*(1/40)*3*t); %3rd harmonic
s13 = s1 + s3;
% A5 = A1/5;
% s5 = A5*sin(2*pi*(1/40)*5*t); 5th
% A7 = A1/7;
% s7 = A7*sin(2*pi*(1/40)*7*t); 7th

% filter
[b13, a13] = ellip(6,0.5,20,[5.7/40 6.3/40],'stop') %elliptic filter
h13 = impz(b13,a13,length(s13)); %impulse
y13 = filter(b13,a13,s13);

A: The easiest way of getting rid of those harmonics is to simply to a low-pass filter...which will get rid of ALL frequency content above your cutoff.  This is no longer a notch filter, like you showed, but it will certainly get rid of tall of those harmonics:
%% lowpass IIR filter example
fs_Hz = 1;  %your sample rate appears to be 1 Hz
fund_Hz = 1/40;  %this is your fundamental
cutoff_Hz = 1.5*fund_Hz;  %choose cutoff
[b,a] = butter(3,fund_Hz/(fs_Hz/2));  %lowpass by default
y = filter(b,a,s13);  %apply filter

If a lowpass filter is too much filtering, then it sounds like your problem is that you don't know how to do a multi-notch filter.  That's fine.  You can choose to notch our your harmonics by applying a series of notch filters one-after-the-other...
%% apply IIR notch filters in series
fs_Hz = 1;  %your sample rate
fund_Hz =1/40;  %your fundamental frequency
y = x;  %initialize your output
for Iharm = 3:2:7  %will do 3rd, 5th, 7th
    [b, a] = ellip(6,0.5,20,[(Iharm-0.3) (Iharm+0.3)]*fund_Hz/(fs_hz/2),'stop');
    y = filter(b,a,y);  %apply the filter onto the previous output
end

And, finally, if you want to do it all as one filter, you'll need a much more complicated filter.  You could design your own based on poles and zeros (which is probably what is intended, if this is a class project, which is what it sounds like).  Or, you could use one of the filter design commands that allows you to enter an arbitrary response.  If you want to use IIR filters (as opposed to FIR filters), look up the yulewalk command.  You'd use it something like this (I haven't used it in a while, so this might not be right...
%% yulewalk example
f_Hz = 1;  %your sample rate
f_fund_Hz = 1/40;  %your fundamental

%define desired response at different frequencies
w = 0.3;  %width of each notch
f_Hz = [3-w 3 3+w  5-w 5 5+w  7-w 7 7+w]*f_fund_Hz; %3rd, 5th, 7th harmonics
resp = [ 1  0  1    1  0  1    1  0  1 ];  %notch each harmonic
f_Hz = [0; f_Hz(:); fs/2];  %must start at 0 Hz and end at Nyquist
resp = [1; resp(:); 1];  %add start and end points

%create and apply the filter
N = 3*3; %filter order...play with this...N=3 per notch?
[b,a]=yulewalk(N,f_Hz/(fs_Hz/2),resp);  %create filter
y = filter(b,a,x);  %apply filter


text:
Q: CTRL +F Logic in java I want to search the specific word in the text file and store that word in the array list. I have done like this but it gives output like word exist in the text file or not. I want to store that text in the array list
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";

try {
    br = new BufferedReader(new FileReader(filePath));
    try {
        while ((line = br.readLine()) != null) {
            countLine++;
            //System.out.println(line);
            String[] words = line.split(" ");

            for (String word : words) {
                if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                }
            }

            if (countBuffer > 0) {
                countBuffer = 0;
                lineNumber += countLine + ",";
            }

        }
        br.close();
    } catch (IOException e) {

        e.printStackTrace();
    }
} catch (FileNotFoundException e) {

    e.printStackTrace();
}

A: double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
List<String> searchedWords = new ArrayList<>();

try {
    br = new BufferedReader(new FileReader(filePath));
    try {
        while ((line = br.readLine()) != null) {
            countLine++;
            //System.out.println(line);
            String[] words = line.split(" ");

            for (String word : words) {
                if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                    if(!searchedWords.contains(word)){
                        searchedWords.add(word);
                    }

                }
            }
            if (countBuffer > 0) {
                countBuffer = 0;
                lineNumber += countLine + ",";
            }
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

System.out.println("Words that you have searched and found:");
for(String word : searchedWords){
    System.out.println(word);
}

You will have an arraylist searchedWords which will keep track of the searched words, you will notice that the if statement will not allow duplicates in the arraylist, so if you want to allow duplicates just remove the if(!searchedWords.contains(word)) and just write searchedWords.add(word);.

A: You can define a String ArrayList with your other declarations using:
ArrayList<String> matches = new ArrayList<String>();
Then when you find a word that matches, add it to the ArrayList using:
matches.add(word);

Edit:
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
ArrayList<String> matches = new ArrayList<String>();

try {
    br = new BufferedReader(new FileReader(filePath));
    try {
        while ((line = br.readLine()) != null) {
            countLine++;
            //System.out.println(line);
            String[] words = line.split(" ");

            for (String word : words) {
                if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                    matches.add(word);
                }
            }

            if (countBuffer > 0) {
                countBuffer = 0;
                lineNumber += countLine + ",";
            }

        }
        br.close();
    } catch (IOException e) {

        e.printStackTrace();
    }
} catch (FileNotFoundException e) {

    e.printStackTrace();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript / remove hover after click close button Help me please!
Show me please how can I remove hover effect after click close button on the right corner?
I can't figure out how to turn off the effect when you click on the close button
Help me please. I just started to learn javascript, I would like for me to solve this problem, so that I can see how you solved it
I'm insert code snippet!

$(".close_help").click(function() {
  $('.close_help').removeClass(".product__element");
  setInterval(function() {
    $('.product__element').addClass('.product__element')
  }, 100);
});

// // $(".close-hover").click(function () {

// const resetClose = document.querySelector('.close-hover');

// $(".close-hover").click(function () {

//   resetClose.style.display = 'none';
// })

//   //    $('.product__element').removeClass("product__element");
// //    setInterval(function () { $('.product__element').addClass('product__element') }, 500);
// // });
.product__element {
  z-index: 9;
  background-color: #fbfbfb;
  width: 20%;
  margin: 2%;
  padding: 10px 10px 10px 20px;
  box-sizing: border-box;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
  border-radius: 5px;
  -webkit-transform: translateY(0);
  -webkit-transition: all .2s cubic-bezier(0.165, 0.84, 0.44, 1);
  transition: all .2s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.prodact_sezon {
  content: "";
  position: absolute;
  left: 0%;
  top: 0%;
  width: 100%;
  height: 100%;
  z-index: 9;
  background: rgba(196, 196, 196, 0.4);
}

.close_help {
  position: absolute;
  top: 4px;
  right: 10px;
  font-size: 20px;
  cursor: pointer;
}

.interact:hover .close_help {
  display: block;
}

/* .prodact_sezon .product__element:hover {
   transform: scale(02);
} */

.product__element:hover {
  background-color: white;
  transform: scale(1.02);
  box-shadow: 0px 15px 40px 5px rgba(0, 0, 0, .09);
  z-index: 10;
  margin-bottom: 0px;
}

.elem123 {
  margin-top: -1px;
  margin-bottom: 0px;
  display: none;
  position: absolute;
  box-shadow: 0 1px 12px 0 rgba(0, 0, 0, .09);
}

.product__element:hover .elem123 {
  display: block;
  background: #FFFFFF;
  left: 0%;
  right: 0%;
  margin-bottom: 0%;
  padding: 20px;
  box-shadow: 0px 10px 12px 0 rgba(0, 0, 0, .09);
  border-radius: 10px;
}

.product__img {
  max-width: 80%;
  height: auto;
  padding-top: -20px;
}

.product__name {
  width: 100%;
  padding: 1px 5px 10px 5px;
  text-align: center;
  font-weight: bold;
}

.product__name__two {
  width: 100%;
  font-size: 15px;
  padding: 0px 5px 7px 5px;
  text-align: center;
  font-weight: regular;
}

.product__description {
  width: 100%;
  font-size: 14px;
  padding: 10px 2px 2px 2px;
  text-align: center;
  font-weight: regular;
  text-rendering: auto;
}

.product__price {
  text-align: center;
  padding: 10px 5px;
  /*  border: 1px solid #e2e2e2;  */
  border-radius: 10px;
  margin-bottom: 0px;
  color: #edaf26;
  font-weight: bold;
  z-index: 330;
  font-size: 17px;
}

.product__size {
  display: flex;
  align-items: center;
  justify-content: space-between;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.product__size-element {
  width: 48%;
  border: 2px solid #e2e2e2;
  font-size: 14px;
  padding: 5px;
  text-align: center;
  cursor: pointer;
  box-sizing: border-box;
  margin-bottom: 0px;
  border-radius: 10px;
}

.product__size-element_active {
  border: 3px solid #76AA6F !important;
  border-radius: 10px;
}

.product__add-to-cart-button {
  width: 100%;
  height: 45px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  border: none;
  -webkit-appearance: none;
  border-radius: 10px;
  background: #76AA6F;
  color: #fff;
  cursor: pointer;
  margin: 15px 0 0;
  -webkit-transition: .3s;
  transition: .3s;
  font-size: 16px;
  outline: none;
}

.product__add-to-cart-button:hover {
  background: #63915D;
  -webkit-transition: .3s;
  transition: .3s;
}

  ×

    Манго Махачонок

    220 Грн

        1 шт.

        1 кг.

<button class="product__add-to-cart-button" data-sb-id-or-vendor-code="003" data-sb-product-img="images/shop/2-min.png" data-sb-product-name="Манго Махачонок" data-sb-product-price="220" data-sb-product-quantity="003" data-sb-product-size="1 шт."> В корзину</button>

      По вкусовым качествам Mango Махачонок идет на первом месте среди всех тайских сортов. У него самая не волокнистая мякоть. Он самый сладкий.

A: While mentioning the class in any of these functions(addClass() or removeClass()) you do not start it with . because these functions are all about classes and you just need to specify them.
And to turn off the hover, change your jQuery code to
$(".close_help").click(function() {
   $('div').removeClass("product__element");
   setInterval(function() {
   $('div').addClass('product__element')
   }, 1000);
});

Here is the working example of how it works.


text:
Q: AdventureWorks Query In AdventureWorks 2008, what are some other (better) ways of writing this query:
SELECT DISTINCT o.CustomerID,  c.CustomerType,
ISNULL(s.Name, p.FirstName + ' ' + p.LastName) AS Name

FROM Sales.SalesOrderHeader o

INNER JOIN Sales.Customer c
ON c.CustomerID = o.CustomerID

LEFT OUTER JOIN sales.Individual i
ON i.CustomerID = o.CustomerID

LEFT OUTER JOIN sales.Store s
ON s.CustomerID = o.CustomerID

LEFT OUTER JOIN Person.Contact p
ON p.ContactID = i.ContactID

ORDER BY CustomerID

Preferably with the ability to support additional CustomerTypes.
Results look like:
   CustomerID   CustomerType    Name
    697            S            Brakes and Gears
    698            S            Western Bike Supplies
    699            S            Sensational Discount Store
    700            S            Underglaze and Finish Company
    701            S            Future Bikes
    11000          I            Jon Yang
    11001          I            Eugene Huang
    11002          I            Ruben Torres
    11003          I            Christy Zhu


text:
Q: large n for factorials I am trying to solve a very simple task about finding nCk when 1<=n,k<=50. I can't seem to find a way of outputting the result for very large numbers like 50 in C++. My algorithm only works for small integer values.
I implemented a factorial function for the nCk formula, but I can't find a way to solve such task for bigger number, and in 1s.
#include <iostream>
using namespace std;
int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int i, n, k;
    long long res, num, den;
    res = num = den = 1;
    cin >> n >> k;
    if (n < k) {
        cout << 0;
        return 0;
    }
    if (n == k || k == 0) {
        cout << 1;
        return 0;
    }
    for (i = 1; i <= k; i++) {
        if ((n - i + 1) % i == 0) {
            res = res * ((n - i + 1) / i);
        }
        else {
            num *= (n - i + 1);
            den *= i;
        }
    }
    cout << (res*num)/den;
    return 0;
}

A: This solution requires some mathematics rather than programming (to solve the problem of overflow).
You have:
n! / (k! * (n - k)!)

You can eliminate common factors easily enough by expanding it. For example:
n = 8, k = 3
8*7*6*5*4*3*2*1 / ((3*2*1) * (5*4*3*2*1))

which expands to
8*7*6*5*4*3*2*1 / 3*2*1*5*4*3*2*1

notice how we can remove 5*4*3*2*1 from both by the rules of division? We then get
8*7*6 / 3*2*1

This will be a lot easier to calculate.
Eventually if you keep getting bigger you will run into issues anyways, so you may need to look into Boost's Multiprecision

A: Your current formula is
binom(n, k) = n! / (n - k)!k!

This formula is OK for mathematics, but not OK for computing.  Simplify it:
binom(n, k) = n(n - 1)(n - 2) ... (n - k + 1) / k!

which involves fewer terms.  Also note that
binom(n, k) = binom(n, n - k)

which can be used as an optimization if k > n / 2.
Also, if the numbers are too large, you need to use a multi-precision library like GMP.


text:
Q: Using php code to output the itemid in XML I am trying to get my php code to output the code in XML, however I'm unsure about how to get it to work properly. So far it outputs the code in php/html format.
This is my XML:
 <bookcollection>
 <items>
 <item id="483">
 <title>Database systems management and design/</title>
 <isbn>0877091153</isbn>
 <url>http://library.hud.ac.uk/catlink/bib/483</url>
 <borrowedcount>28</borrowedcount>
 <courses>
 <course>CC140</course>
 </courses>
 </item>
 </items>
 </bookcollection>

And the PHP:
<?php

$xmlassignDoc = new DOMDocument();
$xmlassignDoc->load("books.xml");

 $books = $xmlassignDoc->getElementsByTagName("item");

foreach($books as $list)
{
    $bookID = $list->getAttribute("id");

    //HERE is where the GET function will be
    if ($bookID == '483')
    {
        $id = $list->getAttribute("id");
        echo "Book ID:  $id
";

         $title = $list->getElementsByTagName("title");
         $title = $title->item(0)->nodeValue;
         echo "Title:  $title
";

         $isbn = $list->getElementsByTagName("isbn");
         $isbn = $isbn->item(0)->nodeValue;
         echo "ISBN:  $isbn
";

         $borrowed = $list->getElementsByTagName("borrowedcount");
         $borrowed = $borrowed->item(0)->nodeValue;
         echo "Borrowed Count:  $borrowed
";
         echo "
";

    }
}

?>

Any ideas would help me a lot.

A: From what i understand you want to pull out a xml element and save it as another xml file
if so use this
$xmlassignDoc = new DOMDocument();
$xmlassignDoc->load("book.xml");

$books = $xmlassignDoc->getElementsByTagName("item");

$singleBook = new DOMDocument('1.0', 'utf-8');
$singleBook->formatOutput = true;

foreach($books as $book) {
    $bookID = $book->getAttribute("id");

    //HERE is where the GET function will be
    if ($bookID == '483') {
        $singleBook->loadXML("<book></book>");
        $node = $singleBook->importNode($book, true);
        $singleBook->documentElement->appendChild($node);
        echo $singleBook->saveXML(); //do we need to save?!?!
    }
}

result:
<?xml version="1.0"?>
<book>
    <item id="483">
        <title>Database systems management and design 1</title>
        <isbn>0877091153</isbn>
        <url>http://library.hud.ac.uk/catlink/bib/483</url>
        <borrowedcount>28</borrowedcount>
        <courses>
            <course>CC140</course>
        </courses>
    </item>
</book>

or if you only want the id as a result
if ($bookID == '483') {
    $singleBook->loadXML("<book></book>");
    $node = $singleBook->createElement("id", $bookID); //<--- ID only
    $singleBook->documentElement->appendChild($node);
    echo $singleBook->saveXML();
}

result
<?xml version="1.0"?>
<book>
    <id>483</id>
</book>

In your case you want  the output to be
<results>
    <book id="1234" title="Interaction Design" isbn="968347337" borrowedcount="15"/>
</results>

use this
$xmlassignDoc = new DOMDocument();
$xmlassignDoc->load("books.xml");

$books = $xmlassignDoc->getElementsByTagName("item");

$singleBook = new DOMDocument('1.0', 'utf-8');
$singleBook->formatOutput = true;

foreach($books as $book)
{
    $bookID = $book->getAttribute("id");

    //HERE is where the GET function will be
    if ($bookID == '483') {
        $singleBook->loadXML("<results></results>");
        $element = $singleBook->createElement("book");

        //id attribute
        $attrId = $singleBook->createAttribute('id');
        $attrId->value = $bookID;

        //title attribute
        $title = $book->getElementsByTagName("title");
        $title = $title->item(0)->nodeValue;
        $attrTitle = $singleBook->createAttribute('title');
        $attrTitle->value = $title;

        //the rest of the attributes

        //add the attributes to the element
        $element->appendChild($attrId);
        $element->appendChild($attrTitle);

        //add the element to the dox
        $singleBook->documentElement->appendChild($element);

        //output the result (don't forget to save if needed :) )
        echo $singleBook->saveXML();
    }
}

A: Try this :
$xml = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
 <bookcollection>
 <items>
 <item id="483">
 <title>Database systems management and design/</title>
 <isbn>0877091153</isbn>
 <url>http://library.hud.ac.uk/catlink/bib/483</url>
 <borrowedcount>28</borrowedcount>
 <courses>
 <course>CC140</course>
 </courses>
 </item>
 </items>
 </bookcollection>';

$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);

echo "
";
print_r($array);

To get id :
echo $id  = $array['items']['item']['@attributes']['id'];
You will get the output as array, fetch the values from this array :
Array
(
    [items] => Array
        (
            [item] => Array
                (
                    [@attributes] => Array
                        (
                            [id] => 483
                        )

                    [title] => Database systems management and design/
                    [isbn] => 0877091153
                    [url] => http://library.hud.ac.uk/catlink/bib/483
                    [borrowedcount] => 28
                    [courses] => Array
                        (
                            [course] => CC140
                        )

                )

        )

)


text:
Q: how to resize an overlayed div depending on the img's size I used this css to overlay the two elements, the image is underneath the overlayed texts:
I need to make sure that the overlay-ed layer should be resized automatically depending on the image's size to ensure a good UI of the elements .

.overlay {
  position: relative;
  background: rgb(0, 0, 0);
  background: rgba(0, 0, 0, 0.5);
  /* Black see-through */
  color: #f1f1f1;
  opacity: 1;
  color: white;
  font-size: 20px;
  text-align: center;
  z-index: 2;
  display: flow-root;
}

.underneath {
  position: absolute;
  z-index: 1;
  height: 100%;
  width: 100%;
}

.container {
  position: relative;
}

.h1 h3 {
  color: rgb(255, 255, 255) !important;
}

      Let's see what to do today

 Check below how to contribute

A: How I'd do something like this is using inset: 0 on the overlay whilst adding postition: absolute to the overlay too and removing position: absolute; from the .underneath class. (Inset: 0 is basically shorthand for top:0; bottom: 0; right: 0; left: 0.).
So:
.container {
  max-width: fit-content;
}
.overlay {
  position: absolute;
  inset: 0;
}

If you need the image to bee 100% container width and potentially wider than the image's full width I'd use a background-image on the .underneath class instead of an img tag and give the .underneath div a set height and remove max-width: fit-content from the container.
.underneath {
  z-index: 1;
  height: 600px;
  width: 100%;
  background-image: url(./overviewBanner.webp);
  background-size: cover;
  background-repeat: no-repeat;
}

A: One approach, with two different image-sizes, is below; in each case the CSS remains exactly the same. To achieve this we take advantage of CSS grid, placing both the overlay and the underneath in the same cell, and placing the overlay 'above' (between the underneath and the viewer) due to its later position in the DOM.
The code for this is below, with explanatory comments in the CSS; please note: I removed the use of z-index and position: absolute, as they aren't necessary to achieve the end-result:

/* to allow for font-sizing across the page: */
:root {
  --fontBaseSize: 16px;
  --fontScale: 1;
}

/* a simple CSS reset to remove browser-default margins
   and padding, and specifying that all elements should
   be sized to include border-width and padding in their
   declared sizes; also sets the shared font-size, and
   font-family: */
*,
::before,
::after {
  box-sizing: border-box;
  font-family: system-ui;
  font-size: calc(var(--fontBaseSize) * var(--fontScale));
  margin: 0;
  padding: 0;
}

.container {
  /* using CSS grid: */
  display: grid;
  /* setting one column to take up all
     available space: */
  grid-template-columns: 1fr;
  /* using margin-block (CSS logical property)
     to place a 1em margin both before and after
     the element on its block axis: */
  margin-block: 1em;
}

.underneath {
  /* positioning the element in the first row
     and first column of the grid: */
  grid-area: 1 / 1;
}

.overlay {
  /* setting background-color and color properties: */
  background-color: rgb(0 0 0 / 0.5);
  color: rgb(235 235 235 / 1);
  display: grid;
  /* positioning the element in the first row
     and first column of the grid: */
  grid-area: 1 / 1;
  /* this places the grid-items in the center, on
     both inline and block axes: */
  place-content: center;
}

h1 {
  /* demonstrating the use of the --fontScale custom property,
     the font-size is calculated via the the CSS calc() function
     multiplying the --baseFontSize by the --fontScale; therefor
     changing the --fontScale property changes the  calculated
     result: */
  --fontScale: 2;
}

h3 {
  --fontScale: 1.2;
}

      Let's see what to do today

 Check below how to contribute

      Let's see what to do today

 Check below how to contribute

JS Fiddle demo.
References:

*

*background-color.

*box-sizing.

*calc().

*color.

*CSS Custom Properties.

*CSS Logical Properties.

*display.

*font-family.

*font-size.

*grid-area.

*grid-template-columns.

*margin.

*margin-block-end.

*margin-block-start.

*margin-inline-end.

*margin-inline-start.

*padding.

*padding-block-end.

*padding-block-start.

*padding-inline-end.

*padding-inline-start.

*place-content.


text:
Q: get value from input and pass it to controller and firebase query Hi guys I'm trying to query my database with the input from html. But data from input is not passed to query. What am I doing wrong? Any help would be appreciated.
Html:
<label class="item item-input">
<input type="text" placeholder="Student name" ng-model="input.studentName">
</label>

controller:
function ($scope, $stateParams, $firebaseObject, $ionicUser, $state, $ionicAuth) {

$scope.userData = $ionicUser.details;

$scope.input = { studentName:''}

var ref = firebase.database().ref().child('users/'+ $scope.input.studentName);
$scope.users = $firebaseObject(ref);

If I input name it doesnt query but if I I set input manually to
 $scope.input = { studentName:'Michael'}

it works fine.


text:
Q: MySQL - expanding a date range into individual dates I have a table with a start date and repeat counts (simplified):
CREATE TABLE tblSchedule (
  schedStart timestamp,
  schedRepeatMonth tinyint,
  schedRepeatDays  tinyint,
  schedOpen bit
);

So, in a simplifed example, "open every Tuesday" would have a start date on a Tuesday and repeat every 7 days. The third Friday would start on a Friday and repeat once a month and 21 days. Closed on Christmas would have a date of Dec. 25th, no repeats, closed.
There are two types of queries it has to handle - "are we open on this date" and "how many times are we open between these dates". If the table were populated without repeats, these would be totally mundane queries and what I would like to do is create a select that produces rows as if they had been entered long-hand without repeats ie:
SELECT * from (
    SELECT schedStart, schedEnd from tblSchedule
     where schedStart between ('2001-01-01', '2001-12-31')
     and *expand_ranges_into_non_repeating_rows_here*)
)

The trouble is that SQL is about filtering information out, not expanding it so creating several rows from a single one is not exactly normal. I could use a while loop to create a temporary table but this is the schedule for multiple items across the entire system so it's going to be commonly run a lot, albeit with some date ranges being more common than others.
Any ideas? Bonus if we can keep the solution as standard-sql as possible.
Edit:
I suppose the question could be further simplified and abstracted to "How can I create a sequence of rows without using a table."

A: Hmm. I think I withdraw the question. I've tried recursive views, some of which might be possible using the new cte feature of MySQL but the calculations involved were getting too time consuming (eg modulo on day-of-week making indexes useless). I've decided to go with expanding them into a temporary table at the start of the run.
I would delete the question but I think failed attempts are just as useful as successful ones. If anyone wants to continue this discussion, feel free.


text:
Q: Modify React Component's State using jQuery/Plain Javascript from Chrome Extension I am building a tiny Chrome Extension for my own personal use.
In Facebook's ads manager(Uses React) i want to change a textarea field's value to a value generated by my chrome extension.
i tried it doing the old fashion way like this
document.querySelector('textarea').value = myValue;

this changes the value on screen but in chrome's inspect element the value doesn't change and when i focus on the input element value resets.
Here is the picture of how react component looks like:

Here is the picture of this react components props & states:

In above component i want to change the state.displayValue to my value.
how it can be done?

A: @Bandal react needs to be notified that the inputs value has changed. You will need to dispatch a change event after you have updated the value.
    document.querySelector('textarea').value = myValue;
    const event = new Event('input', { bubbles: true })
    document.querySelector('textarea').dispatchEvent(event)

Original answer here

A: As mentioned previously, you need to notify react about your manual changes. However, with React 16 this is not so straightforward.
const element = document.querySelector('textarea')
const event = new Event('input', { bubbles: true })
const previousValue = element.value

element.value = 'next value'
element._valueTracker.setValue(previousValue)
element.dispatchEvent(event)

Here is a working codesandbox with source code.
To see demo only you can open this link and call window.triggerChange('new value') function directly from browser dev tools console.
You'll see React's onChange and then setState events being triggered!


text:
Q: mongodb java driver hide id field in aggregation/projection operation I'm performing an aggregation operation using the java mongodb driver, and I followed the example from the docs (pasted below). According to this, the _id field should be hidden. However, in my experience with my own code as well as the output of this example, the _id field doesn't hide even when setting the projection value to 0 (it works from the mongo shell). Does anyone know if this is a bug in the mongodb java driver? Or am I doing something incorrectly?
// create our pipeline operations, first with the $match
DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare") );

// build the $projection operation
DBObject fields = new BasicDBObject("department", 1);
fields.put("amount", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );

// Now the $group operation
DBObject groupFields = new BasicDBObject( "_id", "$department");
groupFields.put("average", new BasicDBObject( "$avg", "$amount"));
DBObject group = new BasicDBObject("$group", groupFields);

// run aggregation
AggregationOutput output = collection.aggregate( match, project, group );

A: The _id field you are getting at the end is from the $group operator.  If you want to rename it back to department, add another $project to the end of the pipeline and translate _id to department.


text:
Q: Password is failing to validate inside my login.php When I register, it hashes the password and then puts the username and the hashed password into my local database. Works fine. When I try to login, the username and password don't match any in the local database and it throws me the error message called login=error2 into the url, which I have written for the case if something is wrong in that part of the code. So you should look for error2 in login.php. I assume the problem lies there. I have been stuck on it the entire day and can't get it to work.
p.s. I am a front-end dev and the most complicated frameworks I use are jquery and react, so I am sorry if I may sound stupid regarding php/mysql. I started learning php 3 days ago.
I am using XAMPP localhost at port 80,
this is the phpmyadmin sql code I used (database name is pixl_users)
create table user_info (
    username varchar(12) not null,
    password varchar(30),
    email varchar(30),
    gender int(1),
    date datetime not null
);

$(document).ready(function () {
  //switch to login form
  $('#switch-to-login').click(function () {
    $('#form-register').hide();
    $('#form-login').show();
  });
  //switch to registration form
  $('#switch-to-signup').click(function () {
    $('#form-login').hide();
    $('#form-register').show();
  });
});

========================================

signup.php file

<?php

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

  include_once 'db-connect.php';

  $username = mysqli_real_escape_string($conn, $_POST['username']);
  $password = mysqli_real_escape_string($conn, $_POST['password']);

  if ((empty($username) || empty($password)) || $username == "admin" || $username == "Admin") {
    // if fields are empty, send back to index and say error msg
    header("Location: index.php?fields=empty");
    exit();
  } else {
    // check for characters which are not allowed in the registration fields
    if (!preg_match('/^[a-zA-Z0-9_.\s]+$/i', $username) || !preg_match('/^[a-zA-Z0-9_.!\s]+$/i', $password)) {
      header("Location: index.php?fields=invalidcharacters");
      exit();
    } else {
        //check if username is longer than 2 and shorter than 13 characters
        if (strlen($username) > 2 && strlen($username) < 13) {
          // check if username is taken
          $sql = "SELECT * FROM user_info WHERE username='$username'";
          $result = mysqli_query($conn, $sql);
          $resultCheck = mysqli_num_rows($result);

          if ($resultCheck > 0) {
            header("Location: index.php?fields=userTaken");
            exit();
          } else {
            //hashing the password
            $hashedPass = password_hash($password, PASSWORD_DEFAULT);
            //insert the user into the database
            $insert = "INSERT INTO user_info (username, password)
            VALUES ('$username', '$hashedPass')";
            //query it into the database
            mysqli_query($conn, $insert);
            //send user to the main website page
            header("Location: index.php");
          }

        } else {
          echo "Username can't be shorter than 3 characters and longer than 12 characters!";
        }

    }
  }

}
login.php file

<?php

session_start();

if (isset($_POST['login'])) {
  // connect to local database
  include 'db-connect.php';
  // get username and password from inputs
  $username = mysqli_real_escape_string($conn, $_POST['login-username']);
  $password = mysqli_real_escape_string($conn, $_POST['login-password']);

  //check if fields are empty
  if (empty($username) || empty($password)) {
    header("Location: index.php?fields=empty");
    exit();
  } else {
    // put usernames from table into array $resultCheck
    $sql = "SELECT * FROM user_info WHERE username='$username'";
    $result = mysqli_query($conn, $sql);
    $resultCheck = mysqli_num_rows($result);
    // if there is 0 usernames in database throw error
    if ($resultCheck < 1) {
      header("Location: index.php?login=error1");
      exit();
    } else {
      if ($row = mysqli_fetch_assoc($result)) {
        //De-hashing the password
        $hashedPassCheck = password_verify($password, $row['password']);
        if ($hashedPassCheck == false) {
          header("Location: index.php?login=error2");
          exit();
        } elseif ($hashedPassCheck == true) {
          // log in the user
          $_SESSION['user_name'] = $row['username'];
          header("Location: index.php?login=success");
          exit();
        }
      }
    }
  }

} else {
  header("Location: index.php?login=error");
  exit();
}
<?php session_start(); ?>

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>database test</title>

  <button id="switch-to-login">switch to login</button>
  <button id="switch-to-signup">switch to signup</button>

  <form id="form-register" action="signup.php" method="POST">
    <input id="inp-username" type="text" name="username" placeholder="choose a name" />

    <input id="inp-password" type="password" name="password" placeholder="choose a password" />
    <button id="btn-register" name="register" type="submit">Register</button>
  </form>

  <form id="form-login" action="login.php" method="POST">
    <input id="inp-username" type="text" name="login-username" placeholder="login name" />

    <input id="inp-password" type="password" name="login-password" placeholder="password" />
    <button id="btn-login" name="login" type="submit">Login</button>
  </form>

A: If you call $hash = password_hash($newRegistrantPassword, PASSWORD_DEFAULT) more than once, you'll get a different $hash every time even if the password you give it is the same. That's because the function generates a different random hash each time. (If you're curious about why, look up rainbow tables.)
If you store $hash in a database column that doesn't have enough characters in it, you'll truncate it.  That's bad.  Future proof your application by using VARCHAR(255) for the hashed password.
What do I mean by future proof? The php developers recognize that computers get faster and cybercreeps get smarter and passwords get easier to crack. So they added the password_needs_rehash() function . In future releases of php, they may change the PASSWORD_DEFAULT hash methodology, making hashes  harder to crack.
Good password verification code for an application expecting a long life might look like this.
  $valid = password_verify ( $passwordPresentedByUser, $storedHash );
  if ( $valid ) {
    if ( password_needs_rehash ( $storedHash, PASSWORD_DEFAULT ) {
      $newHash = password_hash( $passwordPresentedByUser, PASSWORD_DEFAULT );
      /* UPDATE the user's row in the database to store $newHash */
    }
    /* log the user in, have fun! */
  }
  else {
    /* tell the would-be user the username/password combo is invalid */
  }

To troubleshoot your hashing, try putting these lines of code in your php program, and see what happens:
 $myFakePassword = 'BompSheBomp!Wow';
 $hash = password_hash( $myFakePassword, PASSWORD_DEFAULT );
 var_dump( $hash );
 $valid = password_verify ( $myFakePassword, $hash );
 if ( $valid ) echo 'Hey! It worked!';
 else echo 'WTF? password verify didn't work.';

Then make sure you store the hashed password in your database when you register a new user. When a user tries to log in, make sure you use password_verify to check the stored, hashed, password against the one furnished by your user.
You can verify a hashed password. But you can't unhash it.


text:
Q: Cannot pick query string variable from code behind URL: http://localhost:11111/foldername/pagename.aspx#&&PORS=reactive&GridSortDirection=Ascending&GridPage=0&CJ=false&GridSortExpression=SiteReference&CN=na na
Variable in Question :  CN with value na na
When I try below code I am getting null reference exception
string test = Request.QueryString["CN"].ToString();

Am I missing anything?
Note: in the above URL I have tried all variables such as PORS, GridSortDirection etc none of them are working.

A: Querystring is the content after the '?' in the URL. You have '#' instead of '?'. '#' is used to jump to the anchor on the same page.
URL should be like:
URL= http://localhost:11111/foldername/pagename.aspx?PORS=reactive&GridSortDirection=Ascending&GridPage=0&CJ=false&GridSortExpression=SiteReference&CN=na na

A: Your URL contains a Page Fragment Identifier (#). The browser does not send anything to the right of the # back to the server  (including the # itself). So there is no way for the server to make use of that information, unless you do something nonstandard like send it via an ajax call with javascript.


text:
Q: Add level to column from Dictionary I have a dataframe on which I'd like to add a level of columns.
The correct new level of column can be found using my_dict.
df = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5)})
my_dict = {"B": "BB","A": "AA","C": "CC"}

This is what I expect:
Out[92]:
   A  B
   AA BB
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

Thanks

A: You can do df.columns.map then convert to Multiindex
df.columns = pd.MultiIndex.from_arrays((df.columns,df.columns.map(my_dict)))

   A  B
  AA BB
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

A: Use Index.map with assign back to columns names by nested lists - if no match get NaN:
df.columns = [df.columns, df.columns.map(my_dict)]
print (df)
   A  B
  AA BB
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

Solution with rename - if no match get original values:
df.columns = [df.columns, df.rename(columns=my_dict).columns]

df.columns = [df.columns, df.columns]

df = df.rename(columns=my_dict, level=1)

Test for not match:
df = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5), 'D': range(5)})
my_dict = {"B": "BB","A": "AA","C": "CC"}

df.columns = [df.columns, df.columns.map(my_dict)]
print (df)
   A  B   D
  AA BB NaN
a  0  0   0
b  1  1   1
c  2  2   2
d  3  3   3
e  4  4   4

df.columns = [df.columns, df.columns]
df = df.rename(columns=my_dict, level=1)

#df.columns = [df.columns, df.rename(columns=my_dict).columns]
print (df)
   A  B  D
  AA BB  D
a  0  0  0
b  1  1  1
c  2  2  2
d  3  3  3
e  4  4  4


text:
Q: How to View the Windows form application In Windows Service Application running as service I have a Windows Service Application which contains one Service.cs and one Windows Form Application.Now as per my requirement i have to make a setup installer of this application which i did using Visual Studio Setup project under Deployment Section.
Now if i will install my setup Windows Service file will be added as Service and we can see it and its working fine also but i am not seeing the windows form application.
In the control panel add/remove program my application has been added as i am seeing it but windows form application is not showing in All programs of start button.
Please help me .
Thanks in advance.

A: If this is urgent:
In the File System Editor for the setup project, it should show the target machine's file system. By default, the primary outputs you've specified will be set to install to the "Application Folder". But what you want to do is to look under the "User's Programs Menu" (I can't remember if this shows up by default - if not, right click "File System on Target Machine", "Add Special Folder" and select this folder).
Then, in the right-hand pane, right click and choose "Create New Shortcut", navigate down through "Application Folder", select the windows forms application and hit OK. Then give it a suitable name.
If this isn't urgent - go and find a better setup tool and learn how to do similar things to the above using that tool. Visual Studio 2010 was the last version to include the Setup project support, so spending time learning this tool now is wasted time. Better to find a tool that will continue to work as you upgrade VS versions. I'd normally suggest WiX since it comes at a great price (free) but it does have a learning curve (since you author the setup in XML).


text:
Q: Ant - Setting ClassPath Does Not Work For Batch Test I have this and works fine:
<target name="runjunit">
    <junit>
        <classpath>
            <pathelement path="${build}"/>
            <fileset dir="lib">
                <include name="*.jar"/>
            </fileset>
        </classpath>
        <test name="com.xyzcompany.abcproject.test.junit.CalculatorTest"/>
        <formatter type="brief" usefile="false"/>
    </junit>
</target>

However, I have multiple tests. So I do this:
<target name="runjunit">
    <junit>
        <classpath>
            <pathelement path="${build}"/> <---- this doesn't seem to work anymore
            <fileset dir="lib">
                <include name="*.jar"/>
            </fileset>
        </classpath>
        <batchtest>
            <fileset dir="com/xyzcompany/abcproject/test/junit">
                <include name="**/*.*"/>
            </fileset>
        </batchtest>
        <formatter type="brief" usefile="false"/>
    </junit>
</target>

However, that tells me the directory doesn't exist:
C:\Users\me\Desktop\repository\mainproj\trunk\com\xyzcompany\abcproject\test\junit does not exist.
The above should be:
C:\Users\me\Desktop\repository\mainproj\trunk\build\com\xyzcompany\abcproject\test\junit
As you see, the pathelement in classpath would set trunk/build/com in the single test, but doesn't in batchtest.
Directory and package names obfuscated for privacy.
Any idea how I can change the batchtest so pathelement in classpath actually works? Thanks!
EDIT:
This doesn't work:
<batchtest>
    <fileset dir="${build}/com/xyzcompany/abcproject/test/junit">
        <include name="**/*.*" />
    </fileset>
</batchtest>

It gives me:
java.lang.ClassNotFoundException: CalculatorTest
Setting it to <fileset dir="${build}/com/xyzcompany/abcproject/test/junit"> doesn't make any sense since the class doesn't know it is under build. Thus, setting the classpath is the correct option, but doesn't work for <batchtest>.
EDIT 2:
Now that I really think about it, it does make sense to do <fileset dir="${build}/com/xyzcompany/abcproject/test/junit">. However, when it spins up java for junit it doesn't run junit from the ${build} classpath.
EDIT 3:
<batchtest>
    <fileset dir="${build}">
        <include name="com/xyzcopmany/abcproject/test/junit/*"/>
    </fileset>
</batchtest>

Final answers. Ant should really have better documentation. It is a complex product...

A: set
<fileset dir="com/xyzcompany/abcproject/test/junit">

to
<batchtest>
    <fileset dir="${buildTests}">
        <include name="**/*Test*.class"/>
    </fileset>
</batchtest>

Do not include com/xyzcompany/abcproject/test/junit part in the ${buildTests}.

A: If you want to pick up the files for your batch test from ${build} directory, you should tell so
    <batchtest>
        <fileset dir="${build}/com/xyzcompany/abcproject/test/junit">
            <include name="**/*"/>
        </fileset>
    </batchtest>


text:
Q: C - Proper size for a buffer to be send via TCP I'm writing a C client-server application.
The two sides exchange char buffer in order to communicate.
What is the proper size for these buffers?
Does exist a limit of bytes readable (or writable) by a read() (or a write()) on a stream-oriented socket?

A: Provided you write the code correctly there is no limit as long the connection is maintained. That's what a stream connection means.
Just remember that write() and read() can both return before they have written/read all of the data you provided/asked for. In that case the return value tells you how much was written/read, and it's your responsibility to call the function again to write/read any more.

A: It depends if you are aiming for high throughput or low latency. Big buffers for high throughput and small buffers for low latency. Note also that when sending a buffer with x Bytes the read and write functions do not guarantee to send all the x bytes. Make sure to check the return value to see how many bytes was send/received continue sending/receiving the rest (this is often done with a while loop until you send/receive the whole buffer-size x).


text:
Q: Difference between encoding and encryption What is the difference between encoding and encryption?

A: Encoding:

*

*Purpose: The purpose of encoding is to transform data so that it can be properly (and safely) consumed by a different type of system.

*Used for: Maintaining data usability i.e., to ensure that it is able to be properly consumed.

*Data Retrieval Mechanism: No key and can be easily reversed provided we know what algorithm was used in encoding.

*Algorithms Used: ASCII, Unicode, URL Encoding, Base64.

*Example: Binary data being sent over email, or viewing special characters on a web page.
Encryption:

*

*Purpose: The purpose of encryption is to transform data in order to keep it secret from others.

*Used for: Maintaining data confidentiality i.e., to ensure the data cannot be consumed by anyone other than the intended recipient(s).

*Data Retrieval Mechanism: Original data can be obtained if we know the key and encryption algorithm used.

*Algorithms Used: AES, Blowfish, RSA.

*Example: Sending someone a secret letter that only they should be able to read, or securely sending a password over the Internet.
Reference URL: http://danielmiessler.com/study/encoding_vs_encryption/

A: Encoding is the process of transforming data so that it may be transmitted without danger over a communication channel or stored without danger on a storage medium. For instance, computer hardware does not manipulate text, it merely manipulates bytes, so a text encoding is a description of how text should be transformed into bytes. Similarly, HTTP does not allow all characters to be transmitted safely, so it may be necessary to encode data using base64 (uses only letters, numbers and two safe characters).
When encoding or decoding, the emphasis is placed on everyone having the same algorithm, and that algorithm is usually well-documented, widely distributed and fairly easily implemented. Anyone is eventually able to decode encoded data.
Encryption, on the other hand, applies a transformation to a piece of data that can only be reversed with specific (and secret) knowledge of how to decrypt it. The emphasis is on making it hard for anyone but the intended recipient to read the original data. An encoding algorithm that is kept secret is a form of encryption, but quite vulnerable (it takes skill and time to devise any kind of encryption, and by definition you can't have someone else create such an encoding algorithm for you - or you would have to kill them). Instead, the most used encryption method uses secret keys : the algorithm is well-known, but the encryption and decryption process requires having the same key for both operations, and the key is then kept secret. Decrypting encrypted data is only possible with the corresponding key.

A: See encoding as a way to store or communicate data between different systems. For example, if you want to store text on a hard drive, you're going to have to find a way to convert your characters to bits. Alternatively, if all you have is a flash light, you might want to encode your text using Morse. The result is always "readable", provided you know how it's stored.
Encryption means you want to make your data unreadable, by encrypting it using an algorithm. For example, Caesar did this by substituting each letter by another. The result here is unreadable, unless you know the secret "key" with which is was encrypted.

A: I'd say that both operations transform information from one form to another, the difference being:

*

*Encoding means transforming information from one form to another, in most cases it is easily reversible

*Encryption means that the original information is obscured and involves encryption keys which must be supplied to the encryption / decryption process to do the transformation.

So, if it involves (symmetric or asymmetric) keys (aka a "secret"), it's encryption, otherwise it's encoding.

A: Encoding -》  example data is 16
        Then encoding is 10000   means it's binary format or ASCII or UNCODED etc
Which can be read by any system eassily and eassy to understand it's real meaning
Encryption  -》  example data is 16
        Then encryprion is 3t57 or may be anything depend upon which algo is used to encryption
Which can be read by any system eassily BUT ony who can understand it's real meaning who has it's decryption key

A: Encoding transforms data into another format using a scheme that is publicly available so that it can easily be reversed.
Encryption transforms data into another format in such a way that only specific individual(s) can reverse the transformation.
For Summary -
Encoding is for maintaining data usability and uses schemes that are publicly available.
Encryption is for maintaining data confidentiality and thus the ability to reverse the transformation (keys) are limited to certain people.
More details in SOURCE

A: These are little bit different from each other. The encoding used when we want to convert text in a specific computer coding technique and in the encryption we hide data between a specific key or text.

A: Encoding is the process of putting a sequence of characters into a special format for transmission or storage purposes
Encryption is the process of translation of data into a secret code. Encryption is the most effective way to achieve data security. To read an encrypted file, you must have access to a secret key or password that enables you to decrypt it. Unencrypted data is called plain text ; encrypted data is referred to as cipher text

A: Encoding is for maintaining data usability and can be reversed by employing the same algorithm that encoded the content, i.e. no key is used.
Encryption is for maintaining data confidentiality and requires the use of a key (kept secret) in order to return to plaintext.
Also there are two major terms that brings confusion in the world of security Hashing and Obfuscation
Hashing is for validating the integrity of content by detecting all modification thereof via obvious changes to the hash output.
Obfuscation is used to prevent people from understanding the meaning of something, and is often used with computer code to help prevent successful reverse engineering and/or theft of a product's functionality.
Read more @ Danielmiessler article

A: Encoding is process of transforming given set of characters in relevant accepted format, take this question's URL,

*

*This is what we see -->
hhttps://stackoverflow.com/questions/4657416/difference-between-encoding-and-encryption

*Over transmission this will be transformed to -->
https%3A%2F%2Fstackoverflow.com%2Fquestions%2F4657416%2Fdifference-between-encoding-and-encryption
^ is example of URL encoding using ASCII char set where,

*

*: = %3A

*/ = %2F
The reverse of Encoding is Decoding to original form and with given ASCII  standard.

Encryption is process of converting plane text to cipher text so only authorized party can decipher it.

*

*For example a simple HELLO is encrypted into KHOOR if just 3 characters are shifted.

p.s. Encoding (to code in some form) is form of encryption. :)
what-is-encryption

A: Encryption converts data to non-readable format (Possibly containing special non-readable characters).
Encoding helps to convert that data to readable format (characters) so that it can be stored for future use i.e. possibly during decryption.


text:
Q: Can the verb inform be intransitive and used in the sense of making somebody aware of something? And is it colloquial?
She informed she had no idea who had committed that robbery.

A friend of mine said this. I'm not sure if it's correct usage of the verb inform because I think it should be followed by an object (inform somebody of something)
Can the verb inform be intransitive and used in the sense of making somebody aware of something? And is it colloquial?
What are the better options?

A: Your friend is right. It needs an object.
She informed me she had no idea of etc.
Only if it comes at the end of a sentence and the context is clear:

*

*We were informed [of it]. We know you had no idea about the accident.

*We were informed that you did not know. the object is the entire clause.


text:
Q: JSON response for empty params I need a specific o/p if i get empty params. But i was getting a "Cannot Get ... " .

*

*This is what i was doing:

   app.get("/api/timestamp/:date", function(req, res)

   {
     let dateString = req.params.date;

   ...(some code here)

   // empty params

   if(!req.params.date) {
    res.json({...});

   };});

*This seems to solve the issue"

   app.get("/api/timestamp/", function(req, res) {
     res.json({...});
   });

I dont understand why 1 didnt work.

A: Use optional param add ? after date ,this won't throw can't get this route error
app.get("/api/timestamp/:date?", function(req, res)

   {
     let dateString = req.params.date;

   ...(some code here)

   // empty params

   if(!req.params.date) {
    res.json({...});

   };});


text:
Q: IOS Parse is my nested query a good solution for comparing an object with a pointer? Currently, I am querying the database twice to achieve a list of all users nearby who are not already being followed by the current user. Here is my nested query:
// List of all users being followed by the current user
PFQuery *followingActivitiesQuery = [PFQuery queryWithClassName:kFTActivityClassKey];
[followingActivitiesQuery whereKey:kFTActivityTypeKey equalTo:kFTActivityTypeFollow];
[followingActivitiesQuery whereKey:kFTActivityFromUserKey equalTo:[PFUser currentUser]];
[followingActivitiesQuery setCachePolicy:kPFCachePolicyNetworkOnly];
[followingActivitiesQuery includeKey:kFTActivityToUserKey];
[followingActivitiesQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {

        NSMutableArray *followedUserIds = [[NSMutableArray alloc] init];

        // Obtain an array of object ids for all users being followed
        for (PFObject *object in objects) {
            PFUser *followedUser = [object objectForKey:kFTActivityToUserKey];
            [followedUserIds addObject:followedUser.objectId];
        }

        PFGeoPoint *geoPoint = [[PFUser currentUser] objectForKey:kFTUserLocationKey];

        // List of all users within 50 miles that are not already being followed
        PFQuery *followUsersByLocationQuery = [PFQuery queryWithClassName:kFTUserClassKey];
        [followUsersByLocationQuery whereKey:kFTUserObjectIdKey notEqualTo:[PFUser currentUser].objectId];
        [followUsersByLocationQuery whereKey:kFTUserLocationKey nearGeoPoint:geoPoint withinMiles:50];
        [followUsersByLocationQuery whereKeyExists:kFTUserLocationKey];
        [followUsersByLocationQuery whereKey:kFTUserObjectIdKey notContainedIn:followedUserIds];
        [followUsersByLocationQuery setLimit:100];
        [followUsersByLocationQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                self.objects = objects;
                [self.tableView reloadData];
            }
        }];
    }
}];

My question is, is this a viable solution? I feel guilty about having to query the server twice in order to achieve this, but I was not able to do it all in one query. I could not compare a parse pointer from the ActivityClass to the Users class, since the Users class is the class being pointed to, and because of this I couldn't think of a way to do it all in one query.

A: You're in luck - this can be done in a single query using the whereKey:doesNotMatchKey:inQuery: method of PFQuery.
Parse will treat this as a single, compound query against the database. Totally guilt-free :)
Try this instead:
// List of all users being followed by the current user
PFQuery *followingActivitiesQuery = [PFQuery queryWithClassName:kFTActivityClassKey];
[followingActivitiesQuery whereKey:kFTActivityTypeKey equalTo:kFTActivityTypeFollow];
[followingActivitiesQuery whereKey:kFTActivityFromUserKey equalTo:[PFUser currentUser]];
[followingActivitiesQuery setCachePolicy:kPFCachePolicyNetworkOnly];
[followingActivitiesQuery includeKey:kFTActivityToUserKey];

PFGeoPoint *geoPoint = [[PFUser currentUser] objectForKey:kFTUserLocationKey];

// List of all users within 50 miles that are not already being followed
PFQuery *followUsersByLocationQuery = [PFQuery queryWithClassName:kFTUserClassKey];
[followUsersByLocationQuery whereKey:kFTUserObjectIdKey notEqualTo:[PFUser currentUser].objectId];
[followUsersByLocationQuery whereKey:kFTUserLocationKey nearGeoPoint:geoPoint withinMiles:50];
[followUsersByLocationQuery whereKeyExists:kFTUserLocationKey];
//The next line is your new compound query
[followUsersByLocationQuery whereKey:kFTUserObjectIdKey doesNotMatchKey:@"objectId" inQuery:followingActivitiesQuery];
[followUsersByLocationQuery setLimit:100];
[followUsersByLocationQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        self.objects = objects;
        [self.tableView reloadData];
    }
}];


text:
Q: Rename a jquery function $('#up').click(function(){$('#fn').click();});

I was wondering if it is possible to rename/define the .click() to something else, like .xclick().

A: One way could be just defining a function that does what you want:
function xclick(selector, callback) {
  $(selector).click(callback);
}

xclick('#up', function(){ $('#fn').click(); });

But if you want to use jQuerys interface you can use it's prototype:
$.fn.xclick = $.fn.click

$('#up').xclick(function(){$('#fn').click();});

A: You can rename a function by assigning a new property and then deleting the old reference or reassigning the old reference.
However, in your example this concept would be a terrible one. I wouldn't make sense. By changing the very API of such a public library your entire page/site/app would be broken. Not only that but anyone using your code would no longer be able to rely on jQuery. Even jQuery could no longer rely on itself.
You would be better off making your own jQuery plugin and not attempt to change the expected behavior of the existing library. in otherwords, extend don't change.

A: You can use Event namespaces with .on:
$('#something').on('click.x', function(){
    //
});
$('#something').on('click.y', function(){
    //
});


text:
Q: Application openURL gets called a few seconds after didFinishLaunchingWithOptions I have a deep linking feature in my app that works fine beside one case.
I have a 3 different onboarding pages according to the url that opened the app.
So when the app is launched i need to know what link(if any) opened the app and then present the right onboarding page. The problem is that i need to know what screen to present in the method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

but i can only know if a deep link opened the app in
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation

which gets called 5 seconds after did didFinishLaunchingWithOptions is called(i counted the seconds). So i have 5 seconds that i see a wrong onboarding page untill openURL is called(if it will be called) .
So my question is: is there any way to know if the app was launched from a url before or during didFinishLaunchingWithOptions?
By the way launchOptions in didFinishLaunchingWithOptions is nil when the app opens from a deep link

A: I just had a similar problem in iOS 13, but things have changed in iOS 13 because the UIWindowSceneDelegate has been introduced and may now do some of the work previously done by UIApplicationDelegate (depending on your app settings).
The answer by @Olivier in this thread was still very useful to me because it points out the two scenarios in which the URL scheme gets handled; namely when the app is not in memory yet, which calls for application:didFinishLaunchingWithOptions:, and when the app has already been loaded and is in the background, which second case calls for application:openURL:options:.
So, as I'm mentioning above, things are a little different since iOS 13 if you are using the default application template generated by XCode 11. I won't get into the details here, so here's an informative tutorial on the topic: Understanding the iOS 13 Scene Delegate.
But the key methods to modify if you are using the new approach with scenes are scene(_:willConnectTo:options:) (docs here) and scene(_:openURLContexts:) (docs here). The former is where to act upon the URL scheme when the app was not already loaded (so it kind of replaces application:didFinishLaunchingWithOptions:), and the latter is where to get the URL when the app was already in the background when the URL scheme was called (so this one replaces application:openURL:options:).
With scene(_:willConnectTo:options:), you can look for the URL of the URL scheme (if any) doing something like this:
if let url = connectionOptions.urlContexts.first?.url {
    // handle
}

For scene(_:openURLContexts:), you can look inside the URLContexts set.
I hope this helps!

A: The launch option key your are looking for is UIApplicationLaunchOptionsURLKey (Objective-C) / UIApplicationLaunchOptionsKey.url (Swift).
If you're targeting iOS 9 and upwards you only have to intercept a launch URL from

*

*application:didFinishLaunchingWithOptions: (in case the app is not in memory yet)

*application:openURL:options: (in case the app is already in the background).

Here's a minimalistic implementation of UIApplicationDelegate that should cover both cases - please note that a lot unrelated logic has been omitted for clarity:
Objective-C:

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSURL *url = launchOptions[UIApplicationLaunchOptionsURLKey];
    if (url) {
        // TODO: handle URL from here
    }

    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    // TODO: handle URL from here

    return YES;
}

@end

Swift 5:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        if let url = launchOptions?[.url] as? URL {
            // TODO: handle URL from here
        }

        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {

        // TODO: handle URL from here

        return true
    }
}

A: nice idea from previous.
I made some tests..
I confirm iOS 13 odds and bugs.
Preamble:
I enabled all flags on plist:
(from  https://forums.developer.apple.com/thread/118932)
...
     UIFileSharingEnabled

     LSSupportsOpeningDocumentsInPlace

     UISupportsDocumentBrowser

..
And added ALL types in plist:
<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeIconFiles</key>
        <array/>
        <key>CFBundleTypeName</key>
        <string>abc File</string>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>LSHandlerRank</key>
        <string>Owner</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>org.example.app.document.abc</string>
        </array>
    </dict>
</array>

<key>UTExportedTypeDeclarations</key>
    <array>
        <dict>
            <key>UTTypeConformsTo</key>
            <array>
                <string>public.data</string>
            </array>
            <key>UTTypeDescription</key>
            <string>abc File</string>
            <key>UTTypeIconFiles</key>
            <array/>
            <key>UTTypeIdentifier</key>
            <string>org.example.app.document.abc</string>
            <key>UTTypeTagSpecification</key>
            <dict>
                <key>public.filename-extension</key>
                <array>
                    <string>abc</string>
                </array>
            </dict>
        </dict>
    </array>

I logged here:
1)
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        print(documentsDir())

        if let url = launchOptions?[.url] as? URL {
            // TODO: handle URL from here
            openWriteAndCloseLog(msg: "1 " + url.absoluteString, withTimestamp: true)
        }
        return true
    }

2)
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    // TODO: handle URL from here
    openWriteAndCloseLog(msg: "2 " + url.absoluteString, withTimestamp: true)
    return true
}

3)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let url = connectionOptions.urlContexts.first?.url {
        // handle
        openWriteAndCloseLog(msg: "3 " + url.absoluteString, withTimestamp: true)
    }
    guard let _ = (scene as? UIWindowScene) else { return }
}

seems we pass ONLY on 3 (as per my debug log I can see inside documents, as I shared via iTunes)
I made a small demo app to test it.
https://github.com/ingconti/DocumentBroswerSampleApp
You can open attachment from (mal for example..)
You will see:


text:
Q: android chat listview with user profile picture I have to implement a chat in android which should look like in the following image:

How to implement such a ui using listview and adapter?
The row_layout should contain only one message or all messages of one user including his avatar?
Think it should contain only one message, but where to inflate the profile picture for each user at the top of his messages?
Pease help with any suggestions.
Thanks in advance!

A: you need two layout for this,both consists from an ImageView and a ListView. The only difference between them will be the Gravity( one is Left the Other is Right). And in your out most ListView's getView method, return this two layout based on the data you have.


text:
Q: How to read XML in blue prism? How to get value from specific node in XML document in blue prism?
I have imported file management and strings file from VBO folder. But using that I am not able to get value from specific node.

A: There is already one inbuilt "XML VBO" provided by blue prism,you can download the VBO in Blue prism portal.By using that VBO you can achieve almost everything about xml.

A: Actually with the help of  file management and strings file from VBO folder, I got all xml data into text data item, after that using code(Regular c# code) I got value from specific node. It works..

A: Did you try to import the MS Excel VBO? Inside that VBO, theres a lot of Excel related objects that might help you.


text:
Q: How can I prepare effectively for this test? I live in Australia and I will be doing my final high school mathematics test in 5 months from today. The test is about the following topics:

*

*Differentiation and Integration and their applications (Maxima/minima problems, volumes, motion [simple harmonic, projectile, circular and resisted motion], conical pendulum and banked tracks)

*Complex numbers

*Polynomials

*Conic sections

*Series and sequences, mathematical induction and analysis

*Inequalities (similar to ones in IMO)

*Circle geometry

*Probability, combinatorics and binomial probability.
Here are some examples of past exam papers:

*

*http://www.boardofstudies.nsw.edu.au/hsc_exams/hsc2012exams/pdf_doc/2012-hsc-exam-maths-ext2.pdf

*http://www.boardofstudies.nsw.edu.au/hsc_exams/hsc2011exams/pdf_doc/2011-hsc-exam-mathematics-ext2.pdf

*http://www.boardofstudies.nsw.edu.au/hsc_exams/hsc2010exams/pdf_doc/2010-hsc-exam-mathematics-extension-2.pdf
The test starts of very easy then gradually gets harder. I'm confident that I can get most of the questions correct but timing is a problem as it is difficult to get the whole test done in the time allowed.
Many people, including my teacher, told me that the best way to prepare is to do as many of these papers as possible in timed conditions. Do you agree with that? The problem is that doing the same thing with slightly different questions over and over is very boring :(

A: Yes, it is the best way to get the highest mark on the test and yes it is very boring. At the very high percentiles, the ranks are decided by who did the most past papers, who saw the most familiar questions and who has practiced their speed - not necessarily by who has the most solid understanding of all the mathematical principles involved. With enough practice you should aim to get to the point where you don't even need to think about how to do the problems until Q8, everything before that is just writing down what comes to your mind as fast as you can.
Not saying is this the best way to learn or enjoy mathematics, but it is the best way to rank the highest on the tests. Unfortunately sometimes we all have to jump through some hoops.


text:
Q: How to aggregate tweets per minute I´ve done some for-fun twitter-mining. I used twitters streaming-APi and recorded the tweets before, while and after a football match. Now i want to do a ggplot2-graph that shows the frequency of tweets on the football match.
In the original dataframe i´ve one row per tweet and a variable "created_at" which contains a date like this: Sat Dec 13 13:04:34 +0000 2014
Then i changed the time-format like this

tweets$format<- as.POSIXct(tweets$created_at, format = "%a %b %d %H:%M:%S %z %Y", tz="")
  an

and got this 2014-12-13 14:04:34 CET. Because i don´t need the date, i thought, i could get rid of it

tweets$Uhrzeit <- sub(".* ", "", tweets$format)

With this i have only the time left 14:04:34.
My Problem is, that i want to analyse the tweet-frequency with an accuracy of of tweets per minute. How do i aggregate the tweets per minute? As i said earlier, every row is a tweet. I made a dataframe with just the time and a second variable containing "1". Now i want to count (aggregate, sum) the second variable for every minute. I tried to find a solution, read about the zoo-library and the chron-library, but it left my confused.
Hope, somebody can help me.

EDIT: Reproducible Data
The dataframe is a subset of this:  names(tweets)
 [1] "X"                         "text"                      "retweet_count"
 [4] "favorited"                 "truncated"                 "id_str"
 [7] "in_reply_to_screen_name"   "source"                    "retweeted"
[10] "created_at"                "in_reply_to_status_id_str" "in_reply_to_user_id_str"
[13] "lang"                      "listed_count"              "verified"
[16] "location"                  "user_id_str"               "description"
[19] "geo_enabled"               "user_created_at"           "statuses_count"
[22] "followers_count"           "favourites_count"          "protected"
[25] "user_url"                  "name"                      "time_zone"
[28] "user_lang"                 "utc_offset"                "friends_count"
[31] "screen_name"               "country_code"              "country"
[34] "place_type"                "full_name"                 "place_name"
[37] "place_id"                  "place_lat"                 "place_lon"
[40] "lat"                       "lon"                       "expanded_url"
[43] "url"                       "timeformat"

I transformed the "created_at" variable to the "timeformat" variable, which looks like this:
tweets.df<-as.data.frame(cbind(c("2014-12-13 14:04:34 CET","2014-12-13 14:04:37 CET","2014-12-13 14:04:45 CET","2014-12-13 14:05:23 CET","2014-12-13 14:05:53 CET","2014-12-13 14:05:58 CET","2014-12-13 14:06:33 CET","2014-12-13 14:06:38 CET","2014-12-13 14:06:59 CET","2014-12-13 14:08:16 CET","2014-12-13 14:09:12 CET","2014-12-13 14:09:34 CET","2014-12-13 14:10:05 CET","2014-12-13 14:10:16 CET","2014-12-13 14:10:17 CET","2014-12-13 14:11:13 CET","2014-12-13 14:11:16 CET","2014-12-13 14:12:01 CET","2014-12-13 14:12:30 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:05 CET","2014-12-13 14:14:05 CET","2014-12-13 14:14:07 CET","2014-12-13 14:14:07 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:11 CET","2014-12-13 14:14:11 CET","2014-12-13 14:14:22 CET","2014-12-13 14:14:48 CET","2014-12-13 14:15:02 CET","2014-12-13 14:15:03 CET","2014-12-13 14:16:20 CET","2014-12-13 14:16:26 CET","2014-12-13 14:17:14 CET","2014-12-13 14:17:24 CET","2014-12-13 14:17:45 CET","2014-12-13 14:17:49 CET","2014-12-13 14:18:05 CET","2014-12-13 14:18:30 CET","2014-12-13 14:19:38 CET"),1))
colnames(tweets.df)<-c("time","freq")

I just plotted the data. stat="bin" which defaults bins to 1/30 of the range of the data. It would be nicer to have it per minute.
ggplot(tweets,aes(x=timeformat)) + geom_line(stat="bin")

A: GIven your example dataset:
tweets.df<-as.data.frame(cbind(c("2014-12-13 14:04:34 CET","2014-12-13 14:04:37 CET","2014-12-13 14:04:45 CET","2014-12-13 14:05:23 CET","2014-12-13 14:05:53 CET","2014-12-13 14:05:58 CET","2014-12-13 14:06:33 CET","2014-12-13 14:06:38 CET","2014-12-13 14:06:59 CET","2014-12-13 14:08:16 CET","2014-12-13 14:09:12 CET","2014-12-13 14:09:34 CET","2014-12-13 14:10:05 CET","2014-12-13 14:10:16 CET","2014-12-13 14:10:17 CET","2014-12-13 14:11:13 CET","2014-12-13 14:11:16 CET","2014-12-13 14:12:01 CET","2014-12-13 14:12:30 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:02 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:03 CET","2014-12-13 14:14:05 CET","2014-12-13 14:14:05 CET","2014-12-13 14:14:07 CET","2014-12-13 14:14:07 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:08 CET","2014-12-13 14:14:11 CET","2014-12-13 14:14:11 CET","2014-12-13 14:14:22 CET","2014-12-13 14:14:48 CET","2014-12-13 14:15:02 CET","2014-12-13 14:15:03 CET","2014-12-13 14:16:20 CET","2014-12-13 14:16:26 CET","2014-12-13 14:17:14 CET","2014-12-13 14:17:24 CET","2014-12-13 14:17:45 CET","2014-12-13 14:17:49 CET","2014-12-13 14:18:05 CET","2014-12-13 14:18:30 CET","2014-12-13 14:19:38 CET"),1), stringsAsFactors=FALSE)
colnames(tweets.df)<-c("time","freq")

First, your time column as it stands contains text string, you want POSIXct objects:
tweets.df$time <- as.POSIXct(tweets.df$time)

Then, binning by minutes is done using function cut.POSIXt:
by.mins <- cut.POSIXt(tweets.df$time,"mins")

Then you want to split your dataframe using this, and sum the column freq on the subsets:
tweets.mins <- split(tweets.df, by.mins)
sapply(tweets.mins,function(x)sum(as.integer(x$freq)))
2014-12-13 14:04:00 2014-12-13 14:05:00 2014-12-13 14:06:00 2014-12-13 14:07:00 2014-12-13 14:08:00
                  3                   3                   3                   0                   1
2014-12-13 14:09:00 2014-12-13 14:10:00 2014-12-13 14:11:00 2014-12-13 14:12:00 2014-12-13 14:13:00
                  2                   3                   2                   2                   0
2014-12-13 14:14:00 2014-12-13 14:15:00 2014-12-13 14:16:00 2014-12-13 14:17:00 2014-12-13 14:18:00
                 20                   2                   2                   4                   2
2014-12-13 14:19:00
                  1

In this case, since freq is always equals to 1 it is equivalent of using table(by.mins).


text:
Q: Set of pointers to objects with custom comparator I have a set of pointers and I want the set to be sorted in a specific order.
I came up with this code and it works as expected:
#include <string>
#include <iostream>
#include <set>

class Data
{
public:
  std::string name;
  int data;
  bool operator < (const Data& other) const
  {
    return name < other.name;
  }

  bool operator < (const Data* other) const
  {
    std::cout << "never called ";
    return name < other->name;
  }
};

struct DataComparator
{
  bool operator()(const Data* lhs, const Data* rhs) const
  {
    return *lhs < *rhs;
  }
};

int main() {
  Data d1{ "bb", 1 };
  Data d2{ "cc", 2 };
  Data d3{ "aa", 3 };

  std::set<Data*, DataComparator> s;
  s.insert(&d1);
  s.insert(&d2);
  s.insert(&d3);

  // print set members sorted by "name" field
  for (auto& d : s)
    std::cout << d->name << "\n";

  return 0;
}

What bothers me is the fact that I need to use the DataComparator struct in order to implement a custom sort order. I'd like the comparator be part of the Data class. I tried to implement the bool operator < (const Data* other) const class member and declare the set as std::set<Data*> s;, but now the operator < function is (unsurprisingly) never called and the sort order is by pointer address.
Is there some way to implement the custom comparator directly in the Data class so I can just have this:
 std::set<Data*> s;
 ...
 // print set members sorted by "name" field
 for (auto& d : s)
   std::cout << d->name << "\n";

A:
Is there some way to implement the custom comparator directly in the Data class so I can just have [stuff]:

No. I'd write a template
template <typename T>
struct PointerLess
{
    bool operator()(const T * lhs, const T * rhs) const
    {
        return *lhs < *rhs;
    }
};

Then you'd have std::set<Data*, PointerLess<Data>> etc.


text:
Q: How to get extent from current resolution in OpenLayers 3 for printing I need to print a map with a fixed scale of 1:500 horizontally on a A4 paper (297x210mm). The map is done with Openlayers, the print request is sent to QGIS server using WMS getPrint function.
Till now I used a variable scale, printing the map in the actual visible resolution:
var dpi = 120;
var a4_width = 297;
var a4_height = 210;
var inch = 25.4;

var width = Math.round(a4_width * dpi / inch);
var height = Math.round(a4_height * dpi / inch);

var extent = map.getView().calculateExtent([width, height]);

window.open("http://localhost/cgi-bin/qgis_mapserv.fcgi?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetPrint&FORMAT=pdf&TRANSPARENT=true&LAYERS=all&CRS=EPSG:3857&map0:STYLES=&map0:extent="+extent+"&TEMPLATE=DIN_A4_horizontal (1:500)&DPI=120");

How can I calculate the extend of the printing area using the center part of the actual view?
Probably the solution is part of this answer, but I can't figure out how.


text:
Q: trying to setup cntlm on ubuntu for NTLM authentication I am trying to setup cntlm on ubuntu13 for NTLM authentication.  I used apt-get install to setup ctlm.  My cntlm.conf file in the etc directory is copied below - the username/domain and password are correct (I have tested them with a different application).
cntlm.conf
    # Cntlm Authentication Proxy Configuration

    Username        account
    Domain          xxxxxx.com
    Password        password

    # Workstation   netbios_hostname

   Proxy                xxx.xxx.xxx.xxx:3128
    ###Proxy                10.0.0.42:8080

    NoProxy         localhost, 127.0.0.*, 10.*, 192.168.*, 0.0.*

    Listen          3128

    #SOCKS5Proxy    8010
    #SOCKS5User     dave:password

    #Auth           NTLM2
    #Flags          0x06820000

    #Gateway        yes

    #Allow          127.0.0.1
    #Deny           0/0

    #ISAScannerSize     1024
    #ISAScannerAgent    Wget/
    #ISAScannerAgent    APT-HTTP/
    #ISAScannerAgent    Yum/

    #Header         User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)
    #Tunnel         11443:remote.com:443

Error Message in /var/log/syslog:
Proxy returning invalid challenge!

cntlm is running on port 3129 (squid running on port 3128).  I pointed IE to use the proxy on the IP address and port number for cntlm (I tried with squid as well) - however, the connection times out.  Any suggestions on troubleshooting this will be appreciated.

A: Sounds like your firewall is disallowing this connection. You can confirm by temporarily disabling it.
$ sudo ufw disable

To allow these ports access:
$ sudo ufw allow 3128/tcp
$ sudo ufs allow 3129/tcp

You can also see what's open using status:
$ sudo ufw status

Firewall loaded

To                         Action  From
--                         ------  ----
22:tcp                     DENY    192.168.0.1
22:udp                     DENY    192.168.0.1
22:tcp                     DENY    192.168.0.7
22:udp                     DENY    192.168.0.7
22:tcp                     ALLOW   192.168.0.0/24
22:udp                     ALLOW   192.168.0.0/24

If it's disabled:
$ sudo ufw status
Status: inactive

References

*

*UFW - Ubuntu's firewall


text:
Q: Partitioning the Table into .net - Creating columner database I am developing some tool for BI. There are terms like Fact, Dimensions and Measures. My application will connect to the normal database and read the data from that table. Now, I want to convert all this data into columnar database. That is all the columns from this table will be transfer into 3 tables each. Consider below table:
ID    Product
1      XYZ
2      ABC
3      ABC

Now, I want to convert the Product column i.e. dimension into 3 tables.
dim_product_table:-
ID      Product
1       XYZ
2       ABC

dim_product_fmk(fact map by key):- Where we will store key-value pair of
Key     Row
1       1
1       2
2       3

dim_product_fmr(fact map by row):- The above table will be reversed.
Row     Key
1        1
2        1
3        2

The another requirement is all above table should be generated dynamically and I should be able to JOIN all those.

A: I'm posting another answer so that I don't have to struggle with the comments interface, but this is a response to your request above.
If I understand you correctly, you'll need to determine the structure of the database, and generate scripts based on that. In Sql Server, that means reading from sysobjects, syscolumns, etc. You can determine the primary key dynamically, and build the fact tables above accordingly.
This should get you started:
--list tables
SELECT * FROM sysobjects where type = 'u' Order BY Name

--get columns for that table
SELECT * FROM syscolumns WHERE Id = @Id --from sysobjects

--get PK info
SELECT ColumnUsage.*
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TableConstraints
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ColumnUsage
ON TableConstraints.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TableConstraints.CONSTRAINT_NAME = ColumnUsage.CONSTRAINT_NAME
WHERE TableConstraints.TABLE_NAME = @TableName
ORDER BY ColumnUsage.TABLE_NAME, ColumnUsage.ORDINAL_POSITION

A: If I understand you correctly, you're trying to create an OLAP structure? I'm sure someone here will give you a direct answer to your question, but you might also consider looking at Analysis Services, which is Microsoft's platform for creating cubes and doing online analytical processing.
When you generate the cube in AS, there's a wizard that you walk through that will do at least some of what you're looking for here.


text:
Q: ng-repeat tag is deleting my div
I'm very new to Angular, so this question might have a simple solution.
I'm trying to create a side panel div filled with image-templates:
ANGULAR Code:
var app = angular.module('app', []);
        app.controller('ctrl', function ($scope) {
            $scope.thumbnails = [
                {source:'images/img1.jpg',alt:'birthday image', description:'some description'},
                {source:'images/img2.jpg',alt:'birthday image', description:'some description'},
                {source:'images/img3.jpg',alt:'birthday image', description:'some description'},
                {source:'images/img4.jpg',alt:'birthday image', description:'some description'},
                {source:'images/img5.jpg',alt:'birthday image', description:'some description'},
                {source:'images/img6.jpg',alt:'birthday image', description:'some description'}
            ];
        });

and HTML Code:

THUMBNAILS

{{x.description}}

and at the end, this is how the page looks like:

THUMBNAILS

A: Fixed it!

THUMBNAILS

{{x.description}}


text:
Q: Bokeh (Python) Figure.vbar() vs Bar() I'm just starting to take a look at Bokeh for data visualization and am wondering the advantage/disadvantage to using Figure.vbar() vs Bar() if someone could clarify.

A: bar is from the high level Charts interface.  It gives you quick, easy access to bar charts with limited control.
vbar is from the mid level Plotting interface and gives you more control over the layout of your bar chart.  Alternatives to vbar would be rect and quad, both from the Plotting interface.  They give a few distinctive options for bar shape, location, etc.

bar is much easier if you don't need to do anything fancy.  If you decide you want more control over your plot (like HoverTool etc) you will have to instantiate a Figure and use one of it's methods.

bar docs Here
and
vbar docs Here
I use both, depending on my needs.


text:
Q: Python - How do you use the tags from pos_tag (NLTK)? I have been trying to figure out how to use the 'tagged' results from part of speech tagging. Currently I have this test code:

When I run it, it returns with this:

This is all fine. But I want to be able to use this result and I don't know how to. How can I check if the 'test' variable contains the 'VBG' tag? Is there a way to check the values of 'test'? I tried doing something like this:
if 'VBG' in test:
   print ('success')
else:
    print('Nope')
    print(test)

But this doesn't do anything. How do you find if a word/ string/ attribute is in the result of 'test'? Thanks.

A: In your example, test returns a list so correct way to check if it contains 'VBG' or any other POS is to index the list. Again, in your case, you'd want to do if 'VBG' in test[0]. For a list of words, you can do something like this.
import nltk
words = ['doing','cat','blue']
tags = nltk.pos_tag(words)
for idx,word in enumerate(words):
    if 'VBG' in tags[idx]:
        print word + ' is a VBG'

PS: Please acquaint yourselves with the etiquette of stack overflow before posting a question.


text:
Q: converting uri to string in c# I have this code:
   public static string FindRelativePath(string basePatrh, string targetPath)
    {
        Func<FileSystemInfo, string> getFullName = delegate(FileSystemInfo path)
            {
                string fullName = path.FullName;

                if (path is DirectoryInfo)
                {
                    if (fullName[fullName.Length - 1] != Path.DirectorySeparatorChar)
                    {
                        fullName += Path.DirectorySeparatorChar;
                    }
                }

                return fullName;
            };

        string basePatrhFullName = getFullName(new DirectoryInfo(basePatrh));
        string targetPathFullName = getFullName(new DirectoryInfo(targetPath));

        Uri basePatrhUri = new Uri(basePatrhFullName);
        Uri targetPathUri = new Uri(targetPathFullName);
        Uri relativeUri = basePatrhUri.MakeRelativeUri(targetPathUri);

        return relativeUri.ToString().Replace('/', '\\');
    }

This code convert a path to a relative path compared to another path. For example:
   FindRelativePath("c:\test","C;\test\dir1\dir2")

would return
     dir1\dir2
The code works well but if there is space in path for example:
  FindRelativePath("c:\test","C;\test\dir1\dir 2")

it returns wrong string:
dir1\dir%202

How can I fix it?

A: You can use Uri.UnescapeDataString that is reverse function of Uri.EscapeDataString.

A: the string that is returned is not wrong %20 is representing the space between dir 2

A: public static string FindRelativePath(string basePath, string targetPath)
{
           return Uri.UnescapeDataString(
                basePath.MakeRelativeUri(targetPath)
                    .ToString()
                    .Replace('/', Path.DirectorySeparatorChar)
                );
}

A: "%20" is the escaped encoding for the US-ASCII space character
So you have to Unescape it like Uri.UnescapeDataString


text:
Q: Is "This is the only mammal that can fly" an independent clause? We were taught that an independent clause must have a complete thought/idea.

This is the only mammal that can fly.

How can "This is the only mammal" be treated as an independent clause?            It was a grammar lesson and there was no context there. In this situation how can I decide that it is an independent clause? Though for sure, there should be an independent clause in a correct sentence, and the clause starting with 'that' is not independent. But by this way, I can't fit it with the rule that every independent clause must have a complete thought. A simple sentence must have an independent clause. If the sentence has no independent clause how we can call it a sentence? Can even two dependent clauses form a sentence?

A: In the sentence: "This is the only mammal that can fly," "This is the only mammal" is indeed the main clause. The term "independent" may in fact be misleading because main clauses often contain elements that link them with subordinate or dependent clauses, and if we take the latter ones out, the main clause will appear to be incomplete.
In the sentence at issue, that word within the main clause establishing a liaison with the subordinate one is, oviously, the adjective "only".
In this other sentence:

*

*This bird is so strong that it can fly for hours,

the main clause is "This bird is so strong," but once again we find an element that links it with the dependent clause "that it can fly for hours." That element is the adverb "so."
The question is, then, how to spot the main clause in a sentence. You'd better forget about calling it independent. The main clause will be the one that is not introduced by a subordinating word, be it a relative pronoun or adverb or a conjunction.
Notice that the relative (dependent) clause "that can fly" is introduced by the relative (subordinating) pronoun "that": then, that is the dependent clause and whatever remains is the main clause.
In the other example I provided, the adverbial (dependent) clause of result "that it can fly for hours" is introduced by the subordinating conjunction "that": then, that is the dependent clause and whatever remains is the main clause.
The main clause may be even shorter. In a sentence like: "Whoever arrives first is the winner," the subject "Whoever arrives first" is a nominal (dependent) clause, so only the predicate "is the winner" is the main clause, with an implicit or tacit subject "he/she". In a sentence like: "Say what you think," the direct object "what you think" is a content (dependent) clause and only the verb "Say" (with the tacit subject "you") is the main clause.
The main clause is actually "independent" in what we call the "deep structure" of the sentence, and sticking to the words that appear "on the surface" will not help you detect it, nor will the concept of a standalone, independent clause always help. The best thing for you to do is discard all the dependent clauses (not phrases), that is, smaller embedded sentences consisting of subject and predicate, and the main clause will be what remains.

A: Ah, the lies that we tell children.   A sentence is a complete thought.   A noun is a person, place or thing.   Elves make all the toys for Santa Clause.   As far as I can tell, none of those things are true.   Santa often gets his presents from the same stores where we shop.   A noun is a word that follows certain grammatical rules, no matter what it represents.   The basic unit of thought is not the phrase or clause or sentence, but the paragraph.
When I call a clause independent, I mean that that clause is not a part of another clause.   When I call a clause dependent or subordinate, I mean that that clause is a part of another clause.   Your example sentence contains one independent clause and one subordinate clause.   The subordinate clause is obvious: "that can fly".   The independent clause is somewhat harder to describe.
The clause "that can fly" is part of the noun phrase "the only animal that can fly".   That entire noun phrase, including the subordinate clause, is a predicate nominative subject complement.   It is a part of the independent clause.   The independent clause also contains the subject "this" and the verb "is".

In other words, you're absolutely correct.   The words "this is the only mammal" do not represent the entire independent clause in your example sentence.   Instead, those are the words that belong only to the independent clause.   The words "that can fly" belong to both the independent clause and the subordinate clause.

{ [This] | [is] / [the only mammal { [that] | [can fly] }] }

Finally, consider my first sentence: "Ah, the lies that we tell children."   If it is a sentence, then it is a sentence that has no independent clause.   The subordinate clause "that we tell children" modifies "lies" in the same way that "that can fly" modifies "animal".   Is it a correct sentence?   Obviously I think so, or I wouldn't have used it.   However, it is an incomplete sentence -- a sentence fragment.
Fragments are not always errors.
In this case I consider "that we tell children" to be a subordinate clause even though it is not a part of any other clause.   It's merely a part of a phrase.