text:
Q: How to sort a mysql table in a specific way I have the following table as a result of a query:
    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4

The table is sorted by
ORDER BY fullpath ASC, name ASC

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?
id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s

A: Since you want to refrain from stored functions, you need to rebuild the path using names instead of ids, using a MySQL 8.0 recursive query.
WITH RECURSIVE cte AS (
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CAST(f.name AS CHAR(50)) AS namepath
    FROM folders f
   WHERE f.id = 'fs-3'
  UNION ALL
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CONCAT(cte.namepath, '/', f.name) AS namepath
    FROM cte
    JOIN folders f ON f.parent_id = cte.id
)
SELECT id, parent_id, name, fullpath
  FROM cte
 ORDER BY namepath

See DB Fiddle for demo.

A: If you have MySql 8.0 or greater than:
WITH RECURSIVE folders_path (id, name, path) AS
(
  SELECT id, name, name as path
    FROM folders
    WHERE parent_id IS NULL
  UNION ALL
  SELECT f.id, f.name, CONCAT(fp.path, '/', f.name)
    FROM folders_path fp JOIN folders AS f
      ON fp.id = f.parent_id
)
SELECT f.id, f.parent_id, f.name, fp.path
    FROM folders f JOIN folders_path fp on f.id = fp.id
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fp.path;

See DB Fiddle
Note: In the above DB Fiddle I did not bother to add the fullpath column since as the sample data added already satisfied the WHERE clause.

A: You can do it with conditional sorting:
select f.*
from folders f
where fullpath like concat("%", 'fs-3', "%")
order by
  case
    when exists (
      select 1 from folders
      where name = 'test2'
      and f.fullpath like concat(fullpath, '%')
    ) then 1
    when exists (
      select 1 from folders
      where name = 'test3'
      and f.fullpath like concat(fullpath, '%')
    ) then 2
  end,
  f.fullpath,
  f.name

See the demo.
Results:
| id   | parent_id | name  | fullpath            |
| ---- | --------- | ----- | ------------------- |
| fs-3 | null      | root  | fs-3                |
| fs-d | fs-3      | test  | fs-3/fs-d           |
| fs-5 | fs-d      | test  | fs-3/fs-d/fs-5      |
| fs-y | fs-3      | test2 | fs-3/fs-y           |
| fs-4 | fs-y      | test  | fs-3/fs-y/fs-4      |
| fs-g | fs-3      | test3 | fs-3/fs-g           |
| fs-2 | fs-g      | test  | fs-3/fs-g/fs-2      |
| fs-s | fs-2      | test  | fs-3/fs-g/fs-2/fs-s |


text:
Q: react-native Redux updating state when returning MY OBJECT
const initialState = {
1: {
    id: 1,
   price: 280
},
2: {
    id: 2,
    price: 200
}

}
ACTION
I want to take away $100 for the item user has clicked on. The console log works fine when I click on first Item it gives me 180. But how can I do that In my return function. I tried many times but nothing updated.
switch (action.type) {
  case 'BUY_ITEM':
    const getId = state[action.index]['price']
    console.log(getId - 100)
    //this console.log works fine
        return {

        }
   }
   return state
}

 <FlatList
 style={{ flex: 1 }}
 data={Object.values(this.props.data)}
 keyExtractor={(item, index) => index.toString()
 }
   renderItem={({ item }) => {
     return (
        <Card style={styles.itemcontainer}>
             <Text style={[styles.text, { fontSize: 20,}]}>${item.price}</Text>
           <Button style={styles.buyItem} bordered onPress={() => this.props.boughtItem(item.id)}>
        <Text style={{ fontSize: 17, paddingHorizontal: 25, color: '#333945', textAlign: 'center' }}>
         <FontAwesome name="cart-plus" style={styles.buyIcon} />
                                {'  '}Add to cart
                                </Text>
                        </Button>
                    </Card >
                )
            }}>
        </FlatList>

A: Don't directly change state. Check below code,
switch (action.type) {
  case "BUY_ITEM":
    return {
      ...state,
      [action.index]: {
        ...state[action.index],
        price: state[action.index]["price"] - 100,
      },
    };
}

Hope this helps you. Feel free for doubts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery add CSS instead of replace? or set multiple? I wanted to do
$('.place').css('background', 'url(open.png) left top no-repeat, url(close.png) bottom right no-repeat');

However jquery doesnt like the ','. Making it two lines has the 2nd css replace the css on the first line. How do i set the css so it will have both open and close background image?

A: I think it would be easiest to use the addClass(). Since your using css3 i think that would be the only way for you to add it. and just create a css class to add.

A: Having two background images on the same element in CSS is not possible. It is possible with CSS3, but I expect jquery doesn't allow for that yet.

A: Use plain javascript instead.
$('.place').get(0).style.background = 'url(open.png) left top no-repeat, url(close.png) bottom right no-repeat'

A: For your given CSS, jQuery does not do any extra processing. It basically sets:
element.style['background'] = ...;

See lines 33 and 77 in jQuery's source.
A working example of setting 2 backgrounds.


text:
Q: Cofinality of functions $\mathbb N\to\mathbb N$ under eventual domination As the question suggests, I'm interested in the cofinality of functions $\mathbb N\to\mathbb N$ under eventual domination, i.e.
$$f\prec g \quad\Longleftrightarrow\quad\exists N,\ \forall n>N,\ f(n)<g(n)$$
Obviously, the cofinality of this set lies in $[\omega,\mathfrak c]$. Moreover, the cofinality must be at least $\omega_1$, since for any denumerable set of functions $\{f_1,f_2,\ldots\}$, one can define
$$f(n)=\max\{f_m(n):m\le n\}+1,$$ which will eventually dominate all functions in the set.
Without assuming the Continuum Hypothesis, can these bounds be made any stricter?

A: This is the dominating number $\mathfrak{d}$. Basically $\omega<\mathfrak{d}\le 2^{\omega}$ is all that can be said in $\mathsf{ZFC}$ alone. For example, it is consistent with $\mathsf{ZFC}$ that $\mathfrak{d}=\aleph_{17}$ and $2^\omega=\aleph_{42}$. Meanwhile, $\mathsf{MA}$ (which is compatible with $\neg\mathsf{CH}$) implies $\mathfrak{d}=2^{\aleph_0}$.
As a hopefully-useful bit of context, $\mathfrak{d}$ is an example of a cardinal characteristic of the continuum; I've written a bit about these here, and Blass' survey paper is excellent. The really interesting questions about CCCs are usually around their relations to one another. For example,  a related cardinal is the bounding number $\mathfrak{b}$, the smallest size of a set $F$ of functions $\mathbb{N}\rightarrow\mathbb{N}$ such that no single $g:\mathbb{N}\rightarrow\mathbb{N}$ eventually dominates every $f\in F$; we trivially have $\mathfrak{b}\le\mathfrak{d}$, and it's consistent with $\mathsf{ZFC}$ that in fact $\mathfrak{b}<\mathfrak{d}$. Until relatively recently it was largely unknown how to prove the consistency of a separation of three or more cardinal characteristics; see this old MO post of mine.


text:
Q: C++ Visual Studio : Debug Assertion Failed! Expression: c >= -1 && c <= 255 I'm trying to do a basic C++ score / grade system.  I want to validate the users input.  If the data is not a number, I want it to display an error message.  If it is, I want it to carry on.
However, if the user enters a letter, say for example 'a' or 'A'. It spits out this error :
Debug Assertion Failed!
Program:
...ers\Alex\source\repos\worksheet_1.2a\Debug\worksheet_1.2a.exe
File: minkernel\crts\ucrt\appcrt\convert\isctype.cpp
Line: 36

Expression: c >= -1 && c <= 255

This is the code:
#include "stdafx.h"
#include <iostream>
#include <cctype>

using namespace std;

int main()
{
    int score;

    // Recieve user input of score between 0-100. Stores input in score var
    cout << "\nWhat score did you get?\n" << endl;
    cin >> score;

    // Validating input

    if (!isdigit(score)) {
        if (score <= 59)
            cout << "Your grade is F" << endl;
        else if (score > 59 && score < 70)
            cout << "Your grade is D" << endl;
        else if (score > 69 && score < 80)
            cout << "Your grade is C" << endl;
        else if (score > 79 && score < 90)
            cout << "Your grade is B" << endl;
        else if (score > 89)
            cout << "Your grade is A" << endl;
    }
    else {
        cout << "Sorry, that is not a number. Please try again." << endl;
    }

    return 0;
}

It works fine if a number is entered, but not at all if a letter is.
I have looked at several other answers and videos based on 'Debug Assertion Failed' but cannot find one for this particular error.
Thanks for reading and help given!

A: It is rather strange that isdigit takes an int not a char, because thats what it is for (from here, emphazise mine):

Checks if the given character is one of the 10 decimal digits:
  0123456789.
The behavior is undefined if the value of ch is not representable as
  unsigned char and is not equal to EOF.

Seems like isdigit is quite some trap and you were lucky to get assertion fired. Anyhow, even though it takes an int you should pass a char:
 std::string s = "12asbc";
 std::cout << isdigit(s[0]);         // prints 1
 std::cout << isdigit(s[3]);         // prints 0

Anyhow your check isnt that meaningful. If it worked as you expected, you would only know that the number isnt a single digit, but your code would still fail if the user entered abcd or anything that is not a number. To check if the input was correct, you could do
int score;
if (std::cin >> score && 0 <= score && score <= 100) {
     // ok input
} else {
     // invalid input
}

A: why did you type !isdigit(score) instead of isdigit(score)?
Don't put ! in front of isdigit(score).
isdigit() returns True when the argument is number.


text:
Q: Question on distance and a closed, convex set Let $D\subset \mathbb{R}^n$ be closed and convex and let $D\subset B$ where $B$ is some open ball.
Let $x\in \partial D$ then $\exists y \in \partial B$ s.t. $\operatorname{dist}(x, \partial B)=|y-x|$. Is it true that also $|y-x|= \operatorname{dist}(y,D)$? (From picture it looks true)

A: No. In $R^2$ let $D$ be the convex region bounded by $\partial D=E\cup F\cup G$ where $E=\{(u,u+1): u\in [-1,0], F=\{(u,-u+1): u\in [0,1]\}, G=[-1,1]\times \{0\}.$
Let $B=\{(u,v)\in R^2:u^2+v^2=4\}.$ So $\partial B=\{(u,v)\in R^2:u^2+v^2=4\}.$
If $(1/2,1/2)\ne x=(a,1-a)\in G$  then $y$ is the intersection of $B$ with the half-line  $L=\{(ua,u(1-u)):u\geq 1\}.$
But $L$ is not perpendicular to the line-segment $F.$ And when $x$ is sufficiently close to, but not equal to $(1/2,1/2),$ the foot $x^*$ of the perpendicular from $y$ to the line that includes $F$ will satisfy $x^*\in F,$ and $d(y,x^*)<d(y,x).$


text:
Q: Указать условия для класса Можно ли сразу указать условия для класса ?
:class="{ white : 20 == 20 }">

Иначе добавить класс grey

A: Можно. Например вот так:
v-bind:class="false ? 'first-class' : 'second-class'"

Также можно вызывать метод, тоже работает.


text:
Q: How to divide my area into adjacent polygons containing 80 points each? I have a couple of thousand points in my dataset. I need to create clusters that each consists of 80 points. The specific selection of which points to put into a cluster is not critical - only the proximity. From these 80-point clusters I need to create 1 polygon pr. cluster, so I end up with dividing my area into adjacent polygons containing 80 polygons each.
A solution usable in QGIS and other open source tools would be great!


text:
Q: Invalid IL code error in Unity3D I'm trying to use perlin noise to generate terain using Unity3D (version 5.0.2f1) but I  get this error:
InvalidProgramException: Invalid IL code in TerrainGenerator:GenerateFloor (): IL_0045: call      0x0a00000c

TerrainGenerator.Generate () (at Assets/TerrainGenerator.js:36)
TerrainGenerator.Start () (at Assets/TerrainGenerator.js:23)

Code:
function GenerateFloor(){
    print("The function was called");
    if(!(seed > 0)){
        Debug.LogError("Seed not valid. Seed: " + seed + " .");
        seed = Random.Range(0, 1000000000000000);
        Debug.LogError("Generated new seed. Seed: " + seed + ".");
    }
    for(var i = 0; i < heightMap.length; i++){
        if(currentX == Math.Sqrt(size)){
            currentX = 0;
            currentZ++;
        }
        else if(currentX > Math.Sqrt(size)) Debug.LogError("How did this happen?! currentX = " + currentX + " size = " + size + " .");
        var height = Mathf.PerlinNoise(currentX, currentZ);
        heightMap[currentX * currentZ] = new Vector3(currentX, height, currentZ);
        print("For loop worked");
        //yield;
    }
}

A: Your param 1000000000000000 in Random.Range is excessively beyond maximum. Maybe you want int.MaxValue ? which would be 2147483647
Interesting it caused such a compiler error with IL2CPP !


text:
Q: Drag image javascript here is two events. With first event:drag gets element id.
Second event: drop must move picture where is cursor, but not doing it...
Please help me to correct that drop event.. I know I can use jquery, but I just have little time.
I just somehow need in drop event where is if((parseInt(id, 10) > 0) || (id==0)) change picture cords, but i dont know what to use.
part of code is here:
   function drop(ev)
{
ev.preventDefault();
var id=ev.dataTransfer.getData("id");
var CursorY=ev.pageY;
var CursorX=ev.pageX;
var posx = 0;
var posy = 0;
if (ev.pageX || ev.pageY)     {
    posx = ev.pageX;
    posy = ev.pageY;
}
else if (ev.clientX || ev.clientY)    {
    posx = ev.clientX + document.body.scrollLeft
        + document.documentElement.scrollLeft;
    posy = ev.clientY + document.body.scrollTop
        + document.documentElement.scrollTop;
}
var element = document.getElementById(id);
var element2 = document.getElementById("insert_box");
var name = element.getAttribute("name");
var w=document.getElementById(id).offsetWidth;
var h=document.getElementById(id).offsetHeight;

//alert(w+" "+h )

if((parseInt(id, 10) > 0) || (id==0))
{
   //element.style.top=posy;
   //element.style.left=posx;
}else
{
    element2.innerHTML = element2.innerHTML + "

";
    var element_ID = document.getElementById(i);
    i++;
}
}

All code here:
http://pastebin.com/MwaVpzL5
Here is picture:

where is left you can drag image into box in right and when creates new image and when I need to move created image

A: if your able to use jquery then it will make you life an aweful lot easier as jqueryui has several methodsof use
jqueryui draggable will do your dragging and droppable will do your targets


text:
Q: jqgrid and jqPivot: How to remove grouping when xDimension have multi value? I'm using free-jqgrid with jqPivot.
I want to change display of xDimension in pivot grid.
In document:

These values are the cells from source data that appear as rows in the
  grid. When more that one object element is set a grouping appear
  automatically.

and I want to make it not grouping.

Any way to do this?
Thanks in advance.

A: The last parameter of jqPivot is the object, where you can include almost any jqGrid option. You can add grouping: false option in the last parameter to switch the grouping off.
If you use xDimension with more as one element and you want to the number of grouping you can add skipGrouping: true property in the last elements of xDimension. The grouping of at least one (first) column will be hold in the way.


text:
Q: How is determining body length by closing connection reliable (RFC 2616 4.4.5) I can't get one thing straight. The RFC 2616 in 4.4.5 states that Message Length can be determined "By the server closing the connection.".
This implies, that it is valid for a server to respond (e.g. returning a large image) with a response, that has no Content-Length in the header, but the client is supposed to keep fetching till the connection is closed and then assume all data has been downloaded.
But how is a client to know for sure that the connection was closed intentionally by the server? A server app could have crashed in the middle of sending the data and the server's OS would most likely send FIN packet to gracefully close the TCP connection with the client.

A: You are absolutely right, that mechanism is totally unreliable. This is covered in RFC 7230:

Since there is no way to distinguish a successfully completed,
     close-delimited message from a partially received message interrupted
     by network failure, a server SHOULD generate encoding or
     length-delimited messages whenever possible.  The close-delimiting
     feature exists primarily for backwards compatibility with HTTP/1.0.

Fortunately most of HTTP traffic today are HTTP/1.1, with Content-Length or "Transfer-Encoding" to explicitly define the end of message.
The lesson is that, a message must have it own way of termination; we cannot repurpose the underlying transport layer's EOF as the message's EOF.
On that note, a (well-formed) html document, or a .gif, .avi etc, does define its own termination; we will know if we received an incomplete document. Therefore it is not so much of a problem to transmit it over HTTP/1.0 without Content-Length.
However, for plain text document, javascript, css etc. EOF is used to marked the end of the document, therefore it's problematic over HTTP/1.0.


text:
Q: Cancel repeated subscription in mergeMap How to combine the distinct, switchMap and mergeMap operators, so that when the source emits repeated values (detected by distinct.keySelector), the previous subscription is canceled (as in the switchMap), but if the value is not repeated follow the behavior of mergeMap?
Example:
source = from(1, 2, 1, 2, 3) // 'abcde'
result = source.pipe(delay(), combination() // '--cde'

I'm currently doing something like:
const activeSubscriptions = new Map();
source$.pipe(
  mergeMap((value) => {
    const pendingSubscription = activeSubscriptions.get(value);
    if (pendingSubscription) {
      pendingSubscription.unsubscribe();
      activeSubscriptions.delete(value);
    }
    const request$ = new Subject();
    const subscription = this.service.get(value).subscribe({
      complete: () => request$.complete(),
      error: (err) => request$.error(err),
      next: (value) => request$.next(value),
    });
    activeSubscriptions.set(value, subscription);
    return request$;
  })
);

But looking for a better way to do that.
Thank you in advance

A: I think you can use the windowToggle operator for this:
src$ = src$.pipe(shareReplay(1));

src$.pipe(
  ignoreElements(),
  windowToggle(src$.pipe(observeOn(asyncScheduler)), openValue => src$.pipe(skip(1), filter(v => v === openValue))),
  mergeMap(
    window => window.pipe(
      startWith(null),
      withLatestFrom(src$.pipe(take(1))),
      map(([, windowVal]) => windowVal),
    )
  ),
)

A replacement for observeOn(asyncScheduler) could also be delay(0), the important thing is to make sure the order in which the src$'s subscribers receive the value is correct. In this case, we want to make sure that when src$ emits, the clean-up takes place first, so that's why we're using src$.pipe(observeOn(asyncScheduler)).
ignoreElements() is used because each window is paired to only one value, the one which has created the window. The first argument(s) passed to windowToggle will describe the observable(s) which can create the windows. So, we only need those, since we're able to get the last value with the help of
window => window.pipe(
  startWith(null),
  withLatestFrom(src$.pipe(take(1))),
  map(([, windowVal]) => windowVal),
)

By the way, a window is nothing but a Subject.
Lastly, if you want to perform async operations inside the window's pipe, you'll have to make sure that everything is unsubscribed when the window is completed(closed). To do that, you could try this:
window => window.pipe(
  startWith(null),
  withLatestFrom(src$.pipe(take(1))),
  map(([, windowVal]) => windowVal),
  switchMap(val => /* some async action which uses `val` */),
  takeUntil(window.pipe(isEmpty()))
)

where isEmpty will emit either true or false when the source(in this case, the window) completes. false means that the source had emitted at least one value before emitting a complete notification, and true otherwise. In this case, I'd say it's irrelevant whether it's true or false, since the window will not emit any values by itself(because we have used ignoreElements, which ignores everything except error and complete notifications).


text:
Q: Encoding text to file / reading encoded text correctly to eradicate the  symbol? Basically in my student data I am having an issue where by I am getting weird sumbols in my data as you can see: MAIN £1.00when it should show MAIN £1.00
Below is a snippet of my code what scrapes a website for certain student information for their student discounts and eventually writes it to file.
# -*- coding: utf-8 -*-
totals = main.find_all('p')
for total in totals:
    if total .find(text=re.compile("Main:")):
        total = total.get_text()
        if u"Main £" in total:
            pull1 = re.search(r'(MAIN) (\D\w+\D\d+)', total)
            pull2 = re.search(r'(MAINER) (\D\w+\D\d+)', total)
            if pull1:
                rpr_data.append(pull1.group(0).title())
                print pull1.group(0).title()
            if pull2:
                rpr_data.append(pull2.group(0).title())
                print pull2.group(0).title()
with open('RPR.txt','w') as rpr_file:
    rpr_file.write('\n'.join(rpr_data).encode("UTF-8"))

When I try and re-use this data in the script Matching three variables from textfile to csv and writing variables to the csv on matched rows even though the data in the text file has no weird  symbol when it writes to CSV the symbol comes back...
How can I permanently eradicate this  symbol correctly?

A: Getting extra  characters before various western-european characters is almost always a sign of interpreting UTF-8 as Latin-1 (or cp1252 or some other "extended Latin-1" charset).*
That could be you receiving UTF-8 input and trying to process it as Latin-1, or you generating UTF-8 output that someone else is trying to process as Latin-1.

If you're seeing these in the output file, the most likely possibility is that your code is doing everything right every step of the way, and generating a perfectly good UTF-8 file… and then you're trying to view that file on a Windows machine whose OEM code page is 1252 in a program like Notepad that defaults to the OEM code page.
If that's it, there are two possibilities:

*

*Don't do that. View the file as UTF-8. You can tell Notepad to open a file as UTF-8 instead of the default. Or you can use a different editor/viewer.

*If you want the file to be viewable as cp1252, or as "whatever the OEM code page is on this machine", save it that way—e.g., change the last line to use encode("cp1252").

If you're seeing them in the print statements, the most likely possibility is that your code is doing everything right, but your terminal is a Windows DOS prompt that's again set to code page 1252. See Python, Unicode, and the Windows console and Windows cmd encoding change causes Python crash for all the different things that can be wrong here and how to work around them.

* You can see this from a quick line of Python: u'\u00a3'.encode('utf-8').decode('latin-1') == u'\u00c2\u00a3'. That u'\u00c2' is Â. Going the other way can never cause this problem: u'\u00a3'.encode('latin-1').decode('utf-8') will instead raise a UnicodeDecodeError.


text:
Q: How do I queue up more buildings/units for a city's production? I can't seem to tell a city that I would like to produce thing #2 after it is done with thing #1. Shift + Click doesn't work.

A: Nevermind, figured it out; there's a checkbox near the center of the screen, along the bottom. You have to click on it to enable Production Queue.


text:
Q: Eposh time not converting date/format in c program I have been working on this code where I read a binary file and convert it into readable texts. I pretty much got it done for the most part except the epoch time. I tried playing around with some coding but I still can't get it to work. Right now with the way I have the program coded, the first line would print like this
YV2827 kCLT KSRQ 1389396780 (Eposh time)
wed dec 31 19:00:00 1969 (which is NOT 1389396780). Can some one help me out why it's not printing out the proper date/time?
 <i>#include <stdio.h>
  #include <stdlib.h>
 #include <time.h>

 typedef struct {

 char flightNum[7]; // +1 due to null
 char originAirport[5];
 char destAirport[5];
 long time;
}FLIGHTDATA;

// function for flight number
void fofflightNum(FLIGHTDATA*);

int main() {
int i = 0;
time_t c;

FLIGHTDATA flights[30000];

FILE* binfile;

binfile = fopen("acars.bin", "rb");

if(binfile == NULL) {
    printf("sorry, can't open!\n");
    exit(-1);
    }

while (!feof(binfile))  {
fgets(&flights[i].flightNum, 7, binfile);
fseek(binfile, 1, SEEK_CUR);
fgets(&flights[i].originAirport, 5, binfile);
fseek(binfile, 1, SEEK_CUR);
fgets(&flights[i].destAirport, 5, binfile);
fseek(binfile, 4, SEEK_CUR);
fread(&flights[i].time, 1, sizeof(long), binfile);

c = strtoul( "flights[i].time", NULL, 0 );
ctime( &c );

printf("%s %s %s %ld\n", flights[i].flightNum, flights[i].originAirport,
flights[i].destAirport, flights[i].time);
i++;
printf("%s", ctime( &c ));

system("Pause");
}

fclose(binfile);
 return 0;
}

A: I was able to finally solve it, the correct coding is
c = flights[i].time;
ctime( &c );


text:
Q: Metric tensor's relation to gravitation potential I am trying to figure out the role of gravitation potential and its generalization to the metric tensor.
I know how we can relate the gravitation potential and the metric by looking at the geodesic equation and using some weak field, low speeds approximations along with the equation $a = -\text{grad} \,\,\phi$, we can get the coefficent of $dt$ as $\left(1+\frac{2\phi}{c^2}\right)$.
What I want to do is derive this relation in a more intuitive way. What I tried to do is look at a free-falling particle in a uniform gravitation field at a certain point. Then in a frame in its instantaneous velocity, the particle travels $d\tau$ in time and approximately $-\frac{1}{2}g \, d\tau^2$ in space. Then we can use Lorentz transformation under the instantaneous velocity to calculate $dt$ and $dx$ in the stationary frame. From here I am stuck because I think the Lorentz transformation used needs to have some second-order terms in order to result in the coefficient $\left(1+\frac{2\phi}{c^2}\right)$.
Alternatively, is there a direct way to get that coefficient from Rindler coordinates?
Any help is welcome.

A: why not just assume the metric:
$$ds^{2} = -\left(c^{2} + 2\phi\right)dt^{2} + d^{3}x$$
, and then work out the geodesic equations, and show that they have the properties you want, rather than try to derive it the other way around?

A: So I figured out what I would consider a more intuitive solution, which is a slightly modified version of the red shift argument. Basically when in a falling elevator, starting from rest, a light signal is emitted from the top of the elevator x' = 0 to the bottom in time $d\tau$ and the length of the elevator is $dx'=cd\tau$. So $ds^2 = c^2d\tau^2 - dx'^2 = 0$.
When looking at it from outside the elevator, the light signal is emitted from $x=0$ and reaches the bottom which is $dx'+\frac{1}{2}gdt^2$ away using kinematics in the frame at $x=0$. The problem is that since the lift is accelerating, every $x$ is a different frame and we need to look at the frame at $x=dx'+\frac{1}{2}gdt^2$.
What we can reason is that given light is wave, the number of periods $N$ this light signal goes through from the top to bottom would be preserved in both frames. Inside the falling elevator, $N \lambda_0 = dx'$. Outside, the light frequency and wavelength changes at each $x$ between $0$ and $dx'+\frac{1}{2}gdt^2$, but as the distance is infinitesimally small, we can approximate the change in wavelength linearly with respect to the period travelled by the light wave, i.e., $\lambda = \lambda_0 + \alpha n$, $n$ being the period travelled by the light signal. Integrating with respect to period will give the total distance travelled, which we have already calculated before to be $dx'+\frac{1}{2}gdt^2$.
So $\int^N_0\lambda dn = N\lambda_0 + \alpha \frac{N^2}{2} = dx'+\frac{1}{2}gdt^2$. Solving this equation gives $\alpha = \frac{gdt^2}{N^2}$ and we can then calculate the wavelength at the bottom of the lift to be $\lambda = \lambda_0 + \frac{gdt^2\lambda_0}{dx'}$. Using the fact that the instantaneous frame at the point of the light signal emitting, the velocity between inside and outside of the elevator is $0$, we can use $dt$ and $d\tau$ interchangeably and $\frac{dx'}{dt} = c$. This equation becomes $\frac{\lambda}{\lambda_0} = 1+\frac{gdx'}{c^2}$, which is the time conversion factor from the time at bottom of elevator to top of elevator. This shows time on top of elevator is more than the bottom (gravitational time dilation). It also means that while at the top of the lift $c^2dt^2-dx^2=0$, using $(t_b,x_b)$ to denote the spacetime coordinates at the bottom of the elevator, the equation becomes $c^2(1+\frac{gdx'}{c^2})^2dt_b^2 - dx_b^2 = 0$.
And since we've been using low velocity assumption, the equation becomes $c^2(1+\frac{2gdx'}{c^2})dt_b^2 - dx_b^2 = 0$.


text:
Q: Validate Public Google calendar url using javascript I have an application accesed by mulitple users that runs FullCalender.
I am giving users the option to sync their FullCalender with their Google Calendar.
If they choose to sync with Google, I ask the user to input their Public Google Calendar Url.
I'd like to validate the google calendar Url using javascipt once the user submits the form.
If the url the user entered does not exist or if the url is not public, I'd like to alert the user the url they provided is invalid or private.
What would the javascript code be for the validation function?
Thank you..


text:
Q: iOS - Customize Navigation Bar for only some UIViewController I have to add new screens to an existing app, that will use a different navigation bar style than the one that already exists and will be accessed from different screens. The idea would be to show the new Navigation Bar style only for those screens, so when the user finishes that flow or goes back to the screen that started the navigation, it should show again the navigation bar style it was previously using.
I have tried 2 things but didn't work as expected:

*

*I thought of wrapping the new screens in a new UINavigationController, so I could change its navigation bar style and it would be consistent for the new screens. It works but the problem is that I am not able to customize the initial UINavigationController transition to make it not look like a modal (i.e I want to show that UINavigationController with the same animation as if I were pushing a UIViewController). Is there a way to do that? By the way, I am managing the navigations with storyboards segues.

*I also thought of using
self.navigationController?.navigationBar.isHidden = true

But doesn't seem clean because I would have to show it again when the flow is finished (it is a bit long) or cancelled. This makes a lot of combinations and it would be easy to miss one of them, so this doesn't seem a practical solution. Is there a better way to do this?

A: The presenting view controller is where you want to change the nav bar for the controller to be presented. So you'd make any changes to the navbar just before you call push(viewController:animated:).
And then in viewWillAppear of still the presenting view controller you would reset the navbar to what it was initially.
NOTE: Keep in mind that depending on the kind of changes you're doing to the navbar, the transition might no longer be smooth. The user might see some flickering of sorts on the navbar, which would be poor UI/UX.
Edit: Another alternative
Alternatively, you could get rid of the navbar and instead implement your own header view that you can style however you want, to represent the navbar.

*

*You can style it as a simple navbar with a title + back button.

*You can style it to look like a navbar with large title

*You can style it as a navbar with back button + background image + title + right bar buttons

As you can see, this second alternative offers you more freedom in what you can do.


text:
Q: Join multiple collections using Aggregations with conditions i have 3 collections like this
  ModelA :

  {
      _id :ObjectId("60d2cd964200b320e7dc5c04"),
      name : 'Item 1'
  }

  ModelB :

  {
      _id :ObjectId("60e3c8e0748d2a18476ceb6f"),
      modelA : ObjectId("60d2cd964200b320e7dc5c04"),
      field1 : 'field1 item A',
      field2 : 'field2 item B',
  }

  ModelC :

  {
      _id :ObjectId("60e3c8e0748d2a18476ceb70"),
      modelB : ObjectId("60e3c8e0748d2a18476ceb6f"),
      status : 'finish'
  }

i want to fetch data all these collections where the ModelA name is 'Item 1' and ModelC status is equal 'Finish',
how can i join these 3 collections using Aggregations ?

A: You can put multiple $lookup stages to join multiple collections, so you could use a query like this:
db.ModelA.aggregate([
   {
      $lookup:{
         from:"ModelB",
         localField:"_id",
         foreignField:"modelA",
         as:"modelB"
      }
   },
   {
      $unwind:"$modelB"
   },
   {
      $lookup:{
         from:"modelC",
         localField:"ModelB._id",
         foreignField:"modelB",
         as:"modelC"
      }
   },
   {
      $unwind:"$modelC"
   },
   {
      $match: {
         name: "Item 1",
         "modelC.status": "finish"
      }
   },
   { // disable this stage if you want to get all fields of 3 collections or modify it with the output that you want
      $project:{
         "name": 1,
         "status": "$modelC.status"
      }
   }
]);


text:
Q: Using a Perl regex to print multi-line patterns from an HTML file I have an HTML file.  Here is a sample

              You searched for:
        Individual: A*

        JAMES BOND A'MONEYPENNY  (LIC# 1111111)

Alternate Names: BOND JAMES

          GREY TIDE LLC (LIC# 2222)

        FRANK WHITE A'SMALLS  (LIC# 1111111)

Alternate Names: JAMES SMALLS

          WEST RIVER CORP LLC (LIC# 3333)

Broker

        Details »

I'm trying to extract everything between  and 	. The data is stored in a file testFile.txt.
This is the Perl code I used
 system("perl -pi.bak -e '/^.+<\\/td>/mg' testFile.txt";

A: Your below code isn't actually doing anything:
system("perl -pi.bak -e '/^.+<\\/td>/mg' testFile.txt");

*

*You're matching m// in a void context with no captures, so the executed statement is meaningless.

*Your pattern will never match your content because:
a. You're using the any character ., but it won't match newlines unless you use the /s Modifier.
b.  You're using -p for line by line processing of the file, but your pattern would need to span lines in order to match.
The following demonstrates both a regex solution (not recommended) and using an actual HTML Parser, in this case Mojo::DOM.  For a helpful 8 minute introductory video, check out Mojocast Episode 5
use strict;
use warnings;

use Mojo::DOM;

my $data = do { local $/; <DATA> };

# Regex Solution:
if ( $data =~ m{(.*?)	}s ) {
    print "Regex Solution:\n$1";
} else {
    warn "No pattern match found";
}

# Parser Solution:
my $dom = Mojo::DOM->new($data);

my $yourtd = $dom->at(q{td[style="width:50%"]})->content;

print "\nMojo::DOM:\n", $yourtd;

__DATA__

<title>Hello World</title>

              You searched for:
            Individual: A*

                JAMES BOND A'MONEYPENNY  (LIC# 1111111)

Alternate Names: BOND JAMES

                GREY TIDE LLC (LIC# 2222)

Broker

            Details »

Outputs:
Regex Solution:

                JAMES BOND A'MONEYPENNY  (LIC# 1111111)

Alternate Names: BOND JAMES

                GREY TIDE LLC (LIC# 2222)

Mojo::DOM:

                JAMES BOND A'MONEYPENNY  (LIC# 1111111)

Alternate Names: BOND JAMES

                GREY TIDE LLC (LIC# 2222)

A:   .*?(((?!<\/td>).)*?<\/td>)

See demo.Use gs flags.
See demo.
http://regex101.com/r/oC3nN4/15

A: As said in the comments, remove the ^ in your regexp.
Also, use /s instead of /mg if you want to treat the file content as a single line string which allows '.' pattern to allow match new line characters '\n'.
/.+?<\\/td>/s

.+? while stop the matching at the first occurrence of 	, not the last

A: I hope you've seen previous advice to avoid regexes to process HTML? It's really true! The only excuse I can think of for avoiding one of the several excellent HTML modules is that your data is so malformed that nothing else will process it.
Your "sample" of your HTML file is particularly unhelpful. Before I fixed the indentation the lines were scattered all over the place. After I looked at it I saw that it was the end of one table element followed by the start of another, so it left several elements unbalanced and either closed but not opened or vice-versa. Please don't do that to us.
I built a well-formed HTML file that contains your extract, and this is a program that will process it that uses HTML::TreeBuilder
use strict;
use warnings;

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new_from_file('html.html');
my @td50 = $tree->look_down(_tag => 'td', style => 'width:50%');
print $_->as_HTML('<>&', '  '), "\n\n" for @td50;

output

JAMES BOND A'MONEYPENNY  (LIC# 1111111)
Alternate Names: BOND JAMES

 GREY TIDE LLC (LIC# 2222)

In case you or others need it, here's the HTML input document that I used

              You searched for:
            Individual: A*

            JAMES BOND A'MONEYPENNY  (LIC# 1111111)

Alternate Names: BOND JAMES

              GREY TIDE LLC (LIC# 2222)

Broker

            Details »


text:
Q: How to change a job schedule (date/time) in Rundeck from another application? Does Rundeck have an API to dynamically change schedule? If not is there any other way to do the same?
a. POST .../api/21/job/[ID]/run
{
    "runAtTime":"new-date/time"
}

*

*Schedules the job at new-date/time and runs the job but old schedule does not change.

b. POST /api/21/job/[ID]/execution/enable
- Only enables scheduling
Rundeck API page: https://rundeck.org/docs/api/
Thanks

A: Think I have found an API:
POST  .../api/14/project/[PROJECT-NAME]/jobs/import?dupeOption=update
Add a block for new schedule:
<schedule>
    <month month='...'>
    <time hour='12' minute='45' seconds='15'>
    <weekday day='...' />
    <year year='...' />
 </schedule>

To get current details of the job call
GET ...api/14/project/[PROJECT-NAME]/jobs/export
This will return all jobs under PROJECT. We will have to extract block for our job.

Points to note:
- content-type must be application/xml
- uuid must be specified in POST
- dupeOption=update must be specified a parameter; else Rundeck will create a duplicate job instead of updating our job


text:
Q: Binding Command lost I have a control (a) that needs to show / hide another control (b) in it
(a) Has:
1- A reference to (b)
2- A dependency property for (b) viewmodel
(b) Has a Dependency property for its viewmodel Named ViewModel.
Here is the code:
For (a)
If I create that way All mi binds works pretty well, my problem is if I have many instances of (a), each one works as b is the same instance for all of them because it is a static property.
public partial class a : UserControl
{
    public a()
    {

    }

    public bVM b
    {
        get { return (bVM)GetValue(bProperty); }
        set { SetValue(bProperty, value); }
    }

    public static readonly DependencyProperty bProperty =
        DependencyProperty.Register("b", typeof(bVM), typeof(a)), new PropertyMetadata(new bVM()));
}

now if I create a bVM instance into (a) constructor, all my binds work fine except for command bindings.
public partial class a : UserControl
{
    public a()
    {
        b = new bVM();
    }

    public bVM b
    {
        get { return (bVM)GetValue(bProperty); }
        set { SetValue(bProperty, value); }
    }

    public static readonly DependencyProperty bProperty =
        DependencyProperty.Register("b", typeof(bVM), typeof(a));
}

And here is my bind for (b) at (a) xaml:
<local:b
    x:Name="bName"
    ViewModel="{Binding ElementName=ThisAControl,Path=b}"/>

And this is my bind for command lost
<Button Content="Test"
   Command="{BindingElementName=ThisBControl,Path=ViewModel.ExitCommand }" />

Why my command binds are lost second way?
What I'm doing wrong?

A: I agree with @dymanoid comment, that normally you should not have a dependency property for VM. Aside of this strange implementation, technically the reason why binding is lost is because in constructor you are breaking it with:
b = new bVM();
To set value for a dependency property inside dependency object you should you SetCurrentValue method, that will not break any binding.
SetCurrentValue(a.bProperty, new bVM());

MSDN:
  The SetCurrentValue method changes the effective value of the property, but existing triggers, data bindings, and styles will continue to work.


text:
Q: How to reference a Qt Application? In order to test some functions of a Qt application (named qtapp), I build the Qt application as lib/dll library. The ctor and dtor have been correctly exported in the library. However compiling the test project (a Qt console project named consoleTest) is always running to the following link errors:

Link:
  1>     Bibliothek "C:\Users\gmbh\test\x64\Debug\consoleTest.lib" und Objekt C:\Users\gmbh\test\x64\Debug\consoleTest.exp" werden erstellt.
  1>moc_testFour.obj : error LNK2001: Nicht aufgelöstes externes Symbol ""public: static struct QMetaObject const qtapp::staticMetaObject" (?staticMetaObject@qtapp@@2UQMetaObject@@B)".
  1>testFour.obj : error LNK2001: Nicht aufgelöstes externes Symbol ""public: static struct QMetaObject const qtapp::staticMetaObject" (?staticMetaObject@qtapp@@2UQMetaObject@@B)".
  1>C:\Users\gmbh\test\x64\Debug\consoleTest.exe : fatal error LNK1120: 1 nicht aufgelöste Externe

The Qt application is quite simple:
#ifndef QTAPP_H
#define QTAPP_H

#include <QtWidgets/QMainWindow>
#include "ui_qtapp.h"

class __declspec(dllexport) qtapp : public QMainWindow
{
    Q_OBJECT

public:
    qtapp(QWidget* parent = 0);
    ~qtapp();

private:
    Ui::qtappClass ui;
};

#endif // QTAPP_H

Implementation:
#include "qtapp.h"

__declspec(dllexport) qtapp::qtapp(QWidget* parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
}

__declspec(dllexport) qtapp::~qtapp()
{

}

If I simply include #include "qtapp.h" in the test project, the compiler yields the above error.
My questions:

*

*What are the causes for the errors?

*How to correctly deploy a Qt
application as lib?

My compiler is visual studio 2013, qt has the version of 5.4.2

A: That's actually a question independent of Qt. When linking an application against the library you need to have __declspec(dllimport) instead of __declspec(dllexport).
To achieve that, one usually uses defines that change when linking the library vs linking the application against the library. Microsoft has a help page on that "Importing into an Application Using __declspec(dllimport)".
The Qt documentation provides another one. The one thing where Qt can help, is replacing the __declspec by a cross-platform Q_DECL_IMPORT.


text:
Q: R knitr Add linebreak in table header kable() I am using knitr to generate some reports. I use kable to generate an HTML table in the document. In the headers I want to use linebreaks (or other html tags) to enhance the table

As you can see I am trying different options without much success.
In my result linebreaks (\n) are just translated in a linebreak in the HTML source.  tags are translated to HTML special characters.
Any suggestions?

A: There is a way to limit column width which you could use to help achieve this in kable. use column_spec() where you can specify which columns, and the width in different units like cm,in,em.

A: So it appears that kable converts the <> to HTML equivalents, i.e. "<" and ">", so I have a quick fix that will work as long as you don't actually require the <> anywhere else. This has allowed me to get a line break in the column headings in my table.
Essentially once your table is complete just substitute the "<" and ">" in the HTML for < and > and then save it as HTML file. Like so:
tbl_output <- gsub("<", "<", tbl_output)
tbl_output <- gsub(">", ">", tbl_output)

write(tbl_output, "TableOutput.html")

where tbl_output is the output from kable.
Alternatively, and in particular if you need to use <> elsewhere in your table, you could create your own string for a newline and then gsub it for
 at the end.

A: As far as I know, the pipe table syntax does not support line breaks in the cells, so if using pandoc to convert markdown to HTML (this is what RStudio uses), then you'd better choose some more feature-rich table syntax, e.g. multiline or grid. Not sure how to do that with kable, but pander supports those:
> library(pander)
> colnames(s) <- c("Try Newline\nn","Try HTML break
%","Past 6 months\nn","\n%")
> pander(s, keep.line.breaks = TRUE)

-------------------------------------------------------
 Try Newline   Try HTML break
%   Past 6 months   %
      n                                    n
------------- --------------------- --------------- ---
      1                 2                  3         4

      1                 2                  3         4

      1                 2                  3         4
-------------------------------------------------------

But this is not enough, as line breaks are automatically removed by pandoc, so you have to put hard line-breaks ("a backslash followed by a newline") there based on the related docs. E.g. the following code converts to HTML as expected:
> colnames(s) <- c("Try Newline\\\nn","Try HTML break\\\n%","Past 6 months\\\nn","\\\n%")
> pander(s, keep.line.breaks = TRUE)

-----------------------------------------------------
 Try Newline\   Try HTML break\   Past 6 months\   \
      n                %                n          %
-------------- ----------------- ---------------- ---
      1                2                3          4

      1                2                3          4

      1                2                3          4
-----------------------------------------------------


text:
Q: Utilizar um Function JS para vários INPUTS Boa tarde a todos,
Sou novo aqui e espero conseguir explicar meu problema.
Tenho um cadastro de filiais, das quais fiz um button para adicionar novas linhas conforme código.
Porém tenho uma function onde ele encontra o CEP e coloca os dados em seus devidos campos.
Gostaria que essa function funcionasse para todos os novos inputs em que vou adicionando.

                                <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ">
                                <input type="text"  name="filial2[]" id="cep1" placeholder="CEP">
                                <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO">
                                <input type="text" name="filial4[]" id="cidade1" placeholder="CIDADE/UF">
                                <input type="number" name="filial5[]" id="colab" Placeholder="Nº ¹">
                                <input type="number" name="filial6[]" id="colab" Placeholder="Nº ²">
                                <input type="button" id="add-campo" class="bt-vd" value="+" >

E este é o código em que adiciono a nova linha
        $( '#add-campo' ).click(function() {

          $( "#filiais" ).append( '<input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ"> <input type="text"  name="filial2[]" id="cep1" placeholder="CEP">\
           <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO"> <input type="text" name="filial4[]" id="cidade1" placeholder="CIDADE/UF">\
           <input type="number" name="filial5[]" id="colab" Placeholder="Nº ¹"> <input type="number" name="filial6[]" id="colab" Placeholder="Nº ²">' );
        });

e o código do CEP
$(document).ready(function(){
$(document).on('change','input#cep1', function() {

    //Nova variável "cep" somente com dígitos.

    var cep1 = $(this).val();
    var cep = cep1.replace("-" , "")

    //Verifica se campo cep possui valor informado.
    if (cep != "") {
        var validacep = /^[0-9]{8}$/;
        if(validacep.test(cep)) {
            $.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {

                if (!("erro" in dados)) {
                    //Atualiza os campos com os valores da consulta.
                    $("input#bairro1").val(dados.bairro);
                    $("input#cidade1").val(dados.localidade + "/" + dados.uf)

                } //end if.
                else {
                    limpa_formulário_cep();
                    alert("CEP não encontrado.");
                }
            });
        } //end if.
        else {
            alert("Formato de CEP inválido.");
        }
    } //end if.
    else {
    }
});
});
Obrigado.

A: Olá, tudo bom?
Está acontecendo o seguite, quando você acrescenta os inputs pela função, todos os inputs tem o mesmo ID, então são vários inputs com o id="bairro1". Depois a segunda função tenta selecionar o id="bairro1", mas como tem vários ids com o mesmo nome, ele seleciona o primeiro e muda sempre o valor do primeiro. Diferente do que você espera.
Pra resolver isso você tem que colocar o listener onchange na própria tag do input CEP, aí sim você vai conseguir passar para a função os atributos do input em questão e de seus parentes, para ajudar nessa missão eu agrupei os inputs com um fieldset.
Veja como ficou:

$('#add-campo').click(function() {
  $("#filiais").append('<fieldset style="border: none"> <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ"> <input type="text"  name="filial2[]" id="cep" placeholder="CEP" onchange="fillInfos(this)"> <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO"> <input type="text" name="filial4[]" id="cidade" placeholder="CIDADE/UF"> <input type="number" name="filial5[]" id="colab1" Placeholder="Nº ¹"> <input type="number" name="filial6[]" id="colab2" Placeholder="Nº ²"> </fieldset>');
});

function fillInfos(input) {
  var cep = input.value.replace("-", "");
  var validacep = /^[0-9]{8}$/;
  if (validacep.test(cep)) {
    $.getJSON("https://viacep.com.br/ws/" + cep + "/json/?callback=?", function(dados) {
      if (!("erro" in dados)) {
        input.parentElement.childNodes[5].value = dados.bairro;
        input.parentElement.childNodes[7].value = dados.localidade + "/" + dados.uf;
      } else {
        limpa_formulário_cep();
        alert("CEP não encontrado.");
      }
    })
  } else {
    alert("Formato de CEP inválido.")
  }
}

  <fieldset style="border: none">
    <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ">
    <input type="text" name="filial2[]" id="cep" placeholder="CEP" onchange="fillInfos(this)">
    <input type="text" name="filial3[]" id="bairro" placeholder="BAIRRO">
    <input type="text" name="filial4[]" id="cidade" placeholder="CIDADE/UF">
    <input type="number" name="filial5[]" id="colab1" Placeholder="Nº ¹">
    <input type="number" name="filial6[]" id="colab2" Placeholder="Nº ²">
    <input type="button" id="add-campo" class="bt-vd" value="+">
  </fieldset>


text:
Q: Is Theodore Roosevelt's writing ungrammatical? Here is an excerpt from chapter 8 of Theodore Rex by Edmund Morris. Morris quotes some of Roosevelt's writing and calls it ungrammatical. Can you explain what is ungrammatical about the passage?

Musing on the behavior of screech owls, he produced one extraordinary, if ungrammatical, image:

They come up to the house after dark, and are fond of sitting in the elk-antlers over the gable. When the moon is up, by changing one's position, the little owl appears in sharp outline against the bright disk, seated on his many-tined perch

A: Reading through the comments on your question, one could conclude that the word ungrammatical has a rather technical meaning. Perhaps it would be useful to ponder whether Roosevelt's statement is as clear as it could be, or could be improved. Consider the potentially confusing part of his statement: "by changing one's position, the little owl appears..." Although the reader can probably guess at what Roosevelt means, this kind of construct can be confusing in other contexts. For example, "by pulling out one's hairs, the little owl builds a nest." Interpreted in the same way that we interpreted Roosevelt's statement, this could, at least at first glance, suggest that a person pulling out his own hair can have some effect on the owl's nest-building endeavors.
Perhaps the question of whether the statement qualifies as ungrammatical is not as important as the question of whether the statement is as clear as it could be.


text:
Q: Find $F'(x)$ if $F(x) = \displaystyle \int_{0}^x xf(t)dt$.
Find $F'(x)$ if $F(x) = \displaystyle \int_{0}^x xf(t)dt$.

I tried performing integration by parts to get $\displaystyle F(x) = xtf(t)-\int f'(t)f(x)xt dt$, but I am not sure how that helps. Also, are we assuming $x(f(t))$ to be integrable because otherwise the integral doesn't exist?
(This problem appears in Calculus by Michael Spivak, 3rd Ed., Chapter 14, Problem 11.)

A: Note that $x$ is a constant with respect to the variable of integration, so
$$\int_{0}^{x}xf(t)\text{ d}t = x\int_{0}^{x}f(t)\text{ d}t\text{.}$$
Notice that $F$ is a product of two functions of $x$: $x$, and $\int_{0}^{x}f(t)\text{ d}t$. So, we need to use the product rule.
$$F^{\prime}(x) =(x)^{\prime} \int_{0}^{x}f(t)\text{ d}t+x\left[\int_{0}^{x}f(t)\text{ d}t \right]^{\prime} = \int_{0}^{x}f(t)\text{ d}t+xf(x)\text{.}$$
Note that I used the Fundamental Theorem of Calculus for computing $\int_{0}^{x}f(t)\text{ d}t$. One of the assumptions here, as you can see, is that $f$ needs to be continuous.

A: Write $$F(x) = x \int_0^x f(t) \, dt$$ and use the product rule: $$F'(x) = x f(x) + \int_0^x f(t) \, dt.$$


text:
Q: Mypy complains about TestCase attributes set in setUpTestCase I have a project written in Django (Django 3.0, Python 3.8), using django-stubs to handle type annotations. Everything went fine until I wrote some tests:
from django.test import TestCase

class TestSomething(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.some_value = 'foo'
        cls.another_value = 'bar'

    def test_me(self):
        self.assertNotEqual(self.some_value, self.another_value)

When I run mypy, it raises '[attr-defined]' errors about the TestCase class attributes defined in setUpTestData:
 $ mypy --show-error-codes .
my_app/tests/test_something.py:6: error: "Type[TestSomething]" has no attribute "some_value"  [attr-defined]
my_app/tests/test_something.py:7: error: "Type[TestSomething]" has no attribute "another_value"  [attr-defined]
my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "some_value"  [attr-defined]
my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "another_value"  [attr-defined]

I cannot find any advice about type annotations in tests (even tests in general, not to mention Django or unittest tests specifically). I don't think I am using setUpTestData to do anything it is not supposed to do, so I wonder why nobody reported such issues before.
My main question is:
How can I annotate this code to make mypy satisfied?
A corollary question:
Does it even make sense to add type annotations in tests? Maybe I should just configure mypy to ignore test modules?
Here's the mypy.ini file - I would rather not change the settings to be more lenient:
[mypy]
plugins = mypy_django_plugin.main
python_version = 3.8
ignore_missing_imports = True
strict_optional = True
disallow_subclassing_any = False
disallow_any_generics = True
disallow_untyped_calls = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_ignores = true
warn_return_any = True

[mypy.plugins.django-stubs]
django_settings_module = studio.settings

[mypy-*.migrations.*]
ignore_errors = True

A: I guess that the problem is that the class does not declare those attributes "statically", so something like:
from django.test import TestCase

class TestSomething(TestCase):
    some_value = None
    another_value = None

    @classmethod
    def setUpTestData(cls):
        cls.some_value = 'foo'
        cls.another_value = 'bar'

    def test_me(self):
        self.assertNotEqual(self.some_value, self.another_value)

should make the static code analyzer happy


text:
Q: On the default/fill value for *multi-key* outer joins NB: The post below is the "multi-key" counterpart of an earlier question of mine.  The solutions to that earlier question work only for the case where the join is on a single key, and it is not clear to me how to generalize those solutions to the multi-key case presented below.  Since, IME, modifying an already-answered question in a way that disqualifies the answers it has received is frowned upon in SO, I'm posting this variant separately.  I have also posted a question to Meta SO on whether I should delete this post and instead modify the original question, at the expense of invalidating its current answers.

Below are teeny/toy versions of much larger/complex dataframes I'm working with:
>>> A
  key1 key2         u         v         w         x
0    a    G  0.757954  0.258917  0.404934  0.303313
1    b    H  0.583382  0.504687       NaN  0.618369
2    c    I       NaN  0.982785  0.902166       NaN
3    d    J  0.898838  0.472143       NaN  0.610887
4    e    K  0.966606  0.865310       NaN  0.548699
5    f    L       NaN  0.398824  0.668153       NaN

  key1 key2         y         z
0    a    G  0.867603       NaN
1    b    H       NaN  0.191067
2    c    I  0.238616  0.803179
3    d    G  0.080446       NaN
4    e    H  0.932834       NaN
5    f    I  0.706561  0.814467

(FWIW, at the end of this post, I provide code to generate these dataframes.)
I want to produce an outer join of these dataframes on the key1 and key2 columns, in such a way that the new positions induced by the outer join get default value 0.0.  IOW, the desired result looks like this
  key1 key2         u         v         w         x          y         z
0    a    G  0.757954  0.258917  0.404934  0.303313   0.867603       NaN
1    b    H  0.583382  0.504687       NaN  0.618369        NaN  0.191067
2    c    I       NaN  0.982785  0.902166       NaN   0.238616  0.803179
3    d    J  0.898838  0.472143       NaN  0.610887   0.000000  0.000000
4    e    K  0.966606   0.86531       NaN  0.548699   0.000000  0.000000
5    f    L       NaN  0.398824  0.668153       NaN   0.000000  0.000000
6    d    G  0.000000  0.000000  0.000000  0.000000   0.080446       NaN
7    e    H  0.000000  0.000000  0.000000  0.000000   0.932834       NaN
8    f    I  0.000000  0.000000  0.000000  0.000000   0.706561  0.814467

(Note that this desired output contains some NaNs, namely those that were already present in A or B.)
The merge method gets me part-way there, but the filled-in default values are NaN's, not 0.0's:
>>> C = pandas.DataFrame.merge(A, B, how='outer', on=('key1', 'key2'))
>>> C
  key1 key2         u         v         w         x         y         z
0    a    G  0.757954  0.258917  0.404934  0.303313  0.867603       NaN
1    b    H  0.583382  0.504687       NaN  0.618369       NaN  0.191067
2    c    I       NaN  0.982785  0.902166       NaN  0.238616  0.803179
3    d    J  0.898838  0.472143       NaN  0.610887       NaN       NaN
4    e    K  0.966606  0.865310       NaN  0.548699       NaN       NaN
5    f    L       NaN  0.398824  0.668153       NaN       NaN       NaN
6    d    G       NaN       NaN       NaN       NaN  0.080446       NaN
7    e    H       NaN       NaN       NaN       NaN  0.932834       NaN
8    f    I       NaN       NaN       NaN       NaN  0.706561  0.814467

The fillna method fails to produce the desired output, because it modifies some positions that should be left unchanged:
>>> C.fillna(0.0)
  key1 key2         u         v         w         x         y         z
0    a    G  0.757954  0.258917  0.404934  0.303313  0.867603  0.000000
1    b    H  0.583382  0.504687  0.000000  0.618369  0.000000  0.191067
2    c    I  0.000000  0.982785  0.902166  0.000000  0.238616  0.803179
3    d    J  0.898838  0.472143  0.000000  0.610887  0.000000  0.000000
4    e    K  0.966606  0.865310  0.000000  0.548699  0.000000  0.000000
5    f    L  0.000000  0.398824  0.668153  0.000000  0.000000  0.000000
6    d    G  0.000000  0.000000  0.000000  0.000000  0.080446  0.000000
7    e    H  0.000000  0.000000  0.000000  0.000000  0.932834  0.000000
8    f    I  0.000000  0.000000  0.000000  0.000000  0.706561  0.814467

How can I achieve the desired output efficiently?  (Performance matters here, because I intend to perform this operation on much larger dataframes than those shown here.)

IMPORTANT: In order to keep the example minimal, I made the multikey consist of only two columns; in practice the number of keys in a multi-key may be significantly greater.  Proposed answers should be suitable for multi-keys consisting of at least half-dozen columns.

FWIW, below is the code to generate the example dataframes A and B.
from pandas import DataFrame
from collections import OrderedDict
from random import random, seed

def make_dataframe(rows, colnames):
    return DataFrame(OrderedDict([(n, [row[i] for row in rows])
                                 for i, n in enumerate(colnames)]))

maybe_nan = lambda: float('nan') if random() < 0.4 else random()

seed(0)

A = make_dataframe([['A', 'g', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()],
                    ['B', 'h', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()],
                    ['C', 'i', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()],
                    ['D', 'j', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()],
                    ['E', 'k', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()],
                    ['F', 'l', maybe_nan(), maybe_nan(), maybe_nan(), maybe_nan()]],
                   ('key1', 'key2', 'u', 'v', 'w', 'x'))

B = make_dataframe([['A', 'g', maybe_nan(), maybe_nan()],
                    ['B', 'h', maybe_nan(), maybe_nan()],
                    ['C', 'i', maybe_nan(), maybe_nan()],
                    ['D', 'g', maybe_nan(), maybe_nan()],
                    ['E', 'h', maybe_nan(), maybe_nan()],
                    ['F', 'i', maybe_nan(), maybe_nan()]],
                   ('key1', 'key2', 'y', 'z'))

A: Set the keys to be the index of the two DF's:
def index_set(frame, keys=['key1', 'key2']):
    frame.set_index(keys, inplace=True)
    return frame

Subset the DF's containing NaN values:
def nulls(frame):
    nulls_in_frame = frame[frame.isnull().any(axis=1)].reset_index()
    return nulls_in_frame

Join the two Df's. Concatenate the joined DF with each of the subset of NaN containing DF's and drop the duplicated values filling the remaining NaN left with 0's.
Then, using combine_first to patch the values using chaining operation with the joined DF.
def perform_join(fr_1, fr_2, keys=['key1', 'key2']):
    fr_1 = index_set(fr_1); frame_2 = index_set(fr_2)
    frame = fr_1.join(fr_2, how='outer').reset_index()
    cat_fr_1 = pd.concat([frame, nulls(fr_1)]).drop_duplicates(keys, keep=False).fillna(0)
    cat_fr_2 = pd.concat([frame, nulls(fr_2)]).drop_duplicates(keys, keep=False).fillna(0)
    fr_1_join = frame.combine_first(frame.fillna(cat_fr_1[fr_1.columns]))
    joined_frame = fr_1_join.combine_first(frame.fillna(cat_fr_2[fr_2.columns]))
    return joined_frame

Finally,
perform_join(A, B)


text:
Q: Meteor/React Router: error message "there is no route defined" Unfortunately, I can't get React Router to work in my custom meteor boilerplate and I really can't figure out why. Here's all the files that could potentially be relevant to the problem:
\client\main.js:
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { renderRoutes } from '../imports/startup/client/routes.jsx';

Meteor.startup(() => {
  render(renderRoutes(), document.getElementById('app'));
});

\imports\startup\client\routes.jsx:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

// route components
import App from '../../ui/App.jsx';

export const renderRoutes = () => (
  <Router>

      <Route path="/" component={App} />

  </Router>
);

\imports\ui\App.jsx
import React from 'react';
import { withTracker } from 'meteor/react-meteor-data';

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (

Hey!

    );
  }
}

export default withTracker(() => {
  return {
  };
})(App);

Any idea why the error message might occur? Thanks!

A: Not sure what version of meteor and react you are using but tha's how i did it on the last project i had.
Try this changes:
import {Router, Route, browserHistory} from 'react-router';

export const renderRoutes = () => (
  <Router history={browserHistory}>

      <Route path="/" component={App} />

  </Router>
);


text:
Q: Фильтр для ListView из CheckBox В активности присутствует ListView с CheckBox-ами, часть из которых отмечена, также есть EditText для фильтрации списка по буквам.

MainActivity.java

package ru.test.listview_checkbox_getfilter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView listViewCgoicePair;
    private ArrayList<String> arrayListPair = new ArrayList<String>();
    private ArrayList<String> arrayListVisiblePair = new ArrayList<String>();
    private ArrayAdapter<String> adapterChocePair;
    private EditText filterText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arrayListPair.add("11");
        arrayListPair.add("12");
        arrayListPair.add("13");
        arrayListPair.add("21");
        arrayListPair.add("22");
        arrayListPair.add("23");

        arrayListVisiblePair.add("11");
        arrayListVisiblePair.add("12");
        arrayListVisiblePair.add("23");

        listViewCgoicePair = findViewById(R.id.listViewChoicePair);
        listViewCgoicePair.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        adapterChocePair = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, arrayListPair);

        listViewCgoicePair.setAdapter(adapterChocePair);
        for (String checkedPair:arrayListVisiblePair){
            listViewCgoicePair.setItemChecked(arrayListPair.indexOf(checkedPair), true);
        }
        filterText = findViewById(R.id.editTextChicePair);
        filterText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapterChocePair.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true">

    <EditText
        android:id="@+id/editTextChicePair"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        />
    <ListView
        android:id="@+id/listViewChoicePair"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

Проблема состоит в том, что когда применяется фильтр, не подходящие значения удаляются, но отмеченные CheckBox-ы остаются на своих местах и уже соответствуют другим записям.

A: Нашел такой же вопрос с ответом.
Но разобраться до конца не смог, по этому решил изобрести велосипед и написал свой метод фильтрации. Пишите критику, буду рад, учусь.

MainActivity.java

package ru.test.listview_checkbox_getfilter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView listViewCgoicePair;
    private ArrayList<String> arrayListPair = new ArrayList<String>();
    private ArrayList<String> arrayListVisiblePair = new ArrayList<String>();
    private ArrayAdapter<String> adapterChocePair;
    private EditText filterText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arrayListPair.add("Ab");
        arrayListPair.add("ab");
        arrayListPair.add("aB");
        arrayListPair.add("bA");
        arrayListPair.add("ba");
        arrayListPair.add("Ba");

        arrayListVisiblePair.add("Ab");
        arrayListVisiblePair.add("ab");
        arrayListVisiblePair.add("Ba");

        listViewCgoicePair = findViewById(R.id.listViewChoicePair);
        listViewCgoicePair.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        adapterChocePair = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, arrayListPair);

        listViewCgoicePair.setAdapter(adapterChocePair);
        updateCheckedBox(arrayListPair);

        filterText = findViewById(R.id.editTextChicePair);
        filterText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void filter(CharSequence s) {
        ArrayList<String> arrayPair = new ArrayList<String>();
        for (String pair : arrayListPair) {
            if (pair.toLowerCase().contains(s.toString().toLowerCase())) {
                arrayPair.add(pair);
            }
        }
        adapterChocePair = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, arrayPair);
        listViewCgoicePair.setAdapter(adapterChocePair);
        updateCheckedBox(arrayPair);
    }

    private void updateCheckedBox(ArrayList<String> arrayCheckBox) {
        for (String checkedPair : arrayListVisiblePair) {
            listViewCgoicePair.setItemChecked(arrayCheckBox.indexOf(checkedPair), true);
        }
    }
}


text:
Q: Database 'wss_content_1' cannot be opened. It is in the middle of a restore This is the scenario:
I am testing redundancy and fail over in my dev machine by creating two SQL Servers.
I have created two SQL Servers. One with an extra instance:
-SQL1 : primary server
-SQL2 : mirror server
-SQL2\wtn : witness instance

First I made a full backup of the database and transaction log in my primary server, then I restored the database and transaction log file.
I used option "Restore with no recovery".
In the database node "restoring" is being shown. I believe this is normal when you would like to keep pulling data.
Then in the primary server, I tried to create mirroring on the database. After the wizard completed, I clicked on start Mirroring, but now I am getting the following error:
An error occurred while starting mirroring.

------------------------------
ADDITIONAL INFORMATION:

Alter failed for Database 'WSS_Content_1'.  (Microsoft.SqlServer.Smo)

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

------------------------------

Database 'wss_content_1' cannot be opened. It is in the middle of a restore. (Microsoft SQL Server, Error: 927)

I see there is another post here on stack overflow, but that does not have much information. I have been waiting more than 10 minutes.
Update
I am using SQL Enterprise 2016 by the way. Perhaps there is a difference in 2016 version.
I was watching this youtube video and my steps were exactly as this guy's.
Update 2:
I followed this as well but did not help.
How to: Prepare a Mirror Database for Mirroring (Transact-SQL)


text:
Q: How to detect the winner I'm trying to make a minigame I already mentioned in other questions of mine. I think I got all the commands except one. I need a command block to return true when there is only one player left and that'll end the game.
I haven't tried anything yet because I have no idea how to do this. I have also tried researching this but I never get any info. Also, I'm on 1.7.10.
Is this possible in 1.7.10 and if so, how do I do it?

A: Try giving all player an objective with the command scoring system, when someone loses give them a point and make a clock running with a command to detect if any players has 1 point on the objective, if they do you can teleport them away or kill them.
Then have a clock running to the side checking in a certain radius if there is one player with the score of 0, when all players have 1 point and are taken away there will that one player left the score of 0 and you can make him win with teleporting him the winner room or ssimply say in the chat, "you are the winner!"
You can probably find all the commands you need for this on the YouTuber channel of "Dragnoz".
He does a lot of this kind of stuff.

A: You can't test if there is only one player left, but instead you can test if there aren't more players left in an area, use this command:
/testfor @a[c=2,x=X,y=Y,z=Z,r=R]

Unfolded:
 /testfor       | testfor
      @a[]      | players
        c=2     | which are one of the 2 closest players
 x=X,y=Y,z=Z    | at the coordinates X, Y, Z
          r=R   | or R blocks away from them

That means you should replace X, Y, Z with the approximate center coordinates of your minigame area, and R with half the minigame area length.
Now you should stick a comparator out of the command block, and invert it's output, so if the command returns false (eg. that there are less then 2 players in the specified area), your output is true.


text:
Q: How to link javascript in html I am creating browser based video editing tool. I want a user to first download a ~70mb javascript file and store it somewhere on his computer. I want to link that file when my website is opened. How can I achieve that.
EDIT
What i meant is that there are various files like js1.js,js2.js... all sums upto 70mb . So i will offer a zip folder to download and only link js1 or js2 file etc depending on the effects user wish to apply

A: That is actually done automatically. Once you add a <script> tag with a link to a local js file (also stored on the server) the file is loaded automatically.
See HTML <script> src Attribute for more information on that.
You can only reference to js files on the server. Files on the server could look like this:

*

*index.html

*somefancyjsfile.js

You can then reference from inside your html file to the js file via the <script> tag.
I'm not sure though if the size is not a bit too much...

A: i am sorry to inform you but i think there is something really wrong with what you are trying to do.
A "solution" would be to just cache the javascript on the user's browser so any subsequent requests parse the cache instead of requesting the resource again from the server.
You should know however that if you are in need to download ~70mb of a javascript file you are doing something wrong. I have a whole web app project that when published the total size is around 60mb, all files required to properly run included, and its a damn big codebase in there.
I find it very hard to believe there is ever a need for a single javascript file to be that big, in any case maybe a simple caching should do the trick


text:
Q: setState not updating the array in react I am working on a react app where I have to change keys of objects in an array.Here's my code:
getInterfaces(){
    //assign a array to interfaceOption state
    let interfaceOptions=[
      {
        "interface_name": "ORU",
        "interface_id": "1"
      },
      {
        "interface_name": "MLM",
        "interface_id": "2"
      },
    ]

    //change interfaceOptions keys to title and value
    let interfaceOptionsWithTitle = interfaceOptions.map(function(item){
      return {
        title: item.interface_name,
        value: item.interface_id
      }
    })
    console.log(interfaceOptionsWithTitle)
    this.setState({
      interfaceOptions: interfaceOptionsWithTitle
    })

    //print updated interfaceOptions
    console.log(this.state.interfaceOptions)

  }

Here I initially assign a array,then I change its keys and print it using console.log and it prints the updated array but when I then setState the array and console log it again,it returns a empty array.Can someone help me to understand this?
Will this work if I want to update interfaceOptions?
this.state.interfaceOptions = this.state.interfaceOptions.map(item => {
      return {
        title: item.interface_name,
        value: item.interface_id
      };
    });

Thanks

A: Becasue state only has new value when component re-render. So just put  console.log to outside function getInterfaces to see the new value
getInterfaces(){
...
}
console.log(this.state.interfaceOptions)

A: setState is asynchronous in nature, you are trying to update the value and printing it in next line which will always give you the old state value because at the time when the browser tries to print the value the state is not updated, it takes some time to update the value.
If you want to print the updated state value you have pass a callback function  to setState and print the value
e.g
    this.setState({
      interfaceOptions: interfaceOptionsWithTitle
    },() => {
     console.log(this.state.interfaceOptions)
    })

Note: The callback function in the above setState will be executed after the rendering is completed.


text:
Q: T-SQL Skip cte Table and Union when Variable Is Null I've got a query that captures all shipments and costs from our factory. Sample data and desired output on Google Drive here:
https://drive.google.com/open?id=0B4xdnV0LFZI1VndEaGgxNDVpU2M
The issue is we've got 2 different ways of selling things.  One is 'Regluar' where we make it and the other one is a 'buy/sell' where we buy and sell it.
To capture the costs I've had to write two queries, one for each scenario.  The end users of this query can enter in a date range and the query works well then, but I'm stuck when it comes to the variable @Job_No.
All work that goes through our factory (cteRegularJobs) has a Job Number associated with it and I've declared a variable so users can use it to search.  The cteBuyandSell has a value of 'NULL' for Job_No declared in the SELECT statement so I can do a UNION of these two tables at the end.  However, no buy/sell jobs have Job Numbers assigned to them, they are always NULL.
Initially @Job_No is declared as '' and when it's left '' I want the results from both cte tables returned. If there is an entry by the user, i.e. '001' then I want results for cteRegularJobs.
If it makes it easier I am open to declaring the cteBuyandSell.Job_No something else besides NULL, like "Buy and Sell".
The real query is complicated so here's a simplified example of the structure:
DELCARE @Job_No AS varchar(10) = '';
SET @Job_No = {User Input or leave as ''};

WITH
    cteBuyandSell AS ( NULL AS 'Job_No',
      ...),
    cteRegularJobs AS (tblJobs.Job_No AS 'Job_No',
      ...
        WHERE tblJobs.Job_No LIKE @Job_No)

SELECT *
FROM
(cteBuyandSell
 UNION
 cteRegularJobs)

A: You can logically break this up with an IF statement to check the value of your variable. I'd suggest NULL over white space though. Here's an example procedure... with the limited code you provided.
CREATE PROCEDURE getData(@Job_No varchar(10) = NULL)
AS

IF @Job_No IS NULL
    BEGIN

        WITH
            cteBuyandSell AS ( NULL AS 'Job_No',
              ...),
            cteRegularJobs AS (tblJobs.Job_No AS 'Job_No',
              ...
                WHERE tblJobs.Job_No LIKE @Job_No)

        SELECT *
        FROM
        (cteBuyandSell
         UNION
         cteRegularJobs)
    END

ELSE
    BEGIN
        WITH
            cteRegularJobs AS (tblJobs.Job_No AS 'Job_No',
              ...
                WHERE tblJobs.Job_No LIKE @Job_No)

        SELECT * FROM cteRetularJobs

    END


text:
Q: ASP.Net MVC Chart Control - Create Multiple Charts I would like to create multiple charts dynamically within my controller. When I instantiate a new Chart control in my for each it renders a blank chart. I am wondering what can be done to allow me to create and populate multiple charts on one page with the code below.
 public ActionResult BuildChart()
    {
        var chart = new System.Web.UI.DataVisualization.Charting.Chart()
        {
            Width = 576,
            Height = 100,
            BackColor = System.Drawing.Color.White,
        };

        GetPersonas();
        GetSenarioVoting();
        List<CIEToolRole.Models.ScenarioModel> scenarios = GetSenarioVotingResults();

        int i = 0;

       foreach (ScenarioModel scenario in scenarios)
       {
           chart = new System.Web.UI.DataVisualization.Charting.Chart()
           {
               Width = 576,
               Height = 100,
               BackColor = System.Drawing.Color.White,
           };

           chart.ID = "Chart" + i;

           Series mySeries = new Series();
           mySeries.ChartType = SeriesChartType.Column;

           mySeries.BorderWidth = 1;
           mySeries.Palette = ChartColorPalette.Chocolate;
           mySeries.Name = "series" + i;

               List<int> voteVal = scenario.Votes.Select(p => p.Value).ToList();

               foreach (int vote in voteVal)
               {
                   DataPoint point = new DataPoint();
                   point.YValues = new double[] { vote };
                   mySeries.Points.Add(point);
               }

           chart.Series.Add(mySeries);

           i++;
       }

        ChartArea ca1 = new ChartArea("ca1");
        ca1.BackColor = System.Drawing.Color.LightGray;
        ca1.AxisY.LineColor = System.Drawing.Color.LightBlue;
        chart.ChartAreas.Add(ca1);

        var imgStream = new System.IO.MemoryStream();
        chart.SaveImage(imgStream, ChartImageFormat.Png);
        imgStream.Seek(0, System.IO.SeekOrigin.Begin);

        return File(imgStream, "image/png");
    }

A: After some trial and error I was able to come up with a solution that did not require a partial view.
Controller
 public ActionResult BuildChart(int scenarioID)
    {
        var chart = new System.Web.UI.DataVisualization.Charting.Chart()
        {
            Width = 576,
            Height = 100,
            BackColor = System.Drawing.Color.White,
        };

        GetPersonas();
        GetSenarioVoting();
        List<modelstuff.Models.ScenarioModel> scenarios = GetSenarioVotingResults();

        int x = 0;

        var scenarioById = scenarios.FirstOrDefault(p => p.ID == scenarioID).Votes;

        Series mySeries = new Series();
        mySeries.ChartType = SeriesChartType.Column;

        mySeries.BorderWidth = 1;
        mySeries.Palette = ChartColorPalette.Chocolate;
        // Making a unqiue series ID
        Guid guido = new Guid();
        mySeries.Name = guido.ToString();

        foreach (int vote in scenarioById.Values)
        {
            DataPoint point = new DataPoint();

            point.YValues = new double[] { vote };
            mySeries.Points.Add(point);
        }

        chart.Series.Add(mySeries);

        ChartArea ca1 = new ChartArea("ca1");
        ca1.AxisX.LabelStyle.Enabled = false;
        ca1.AxisY.LabelStyle.Enabled = false;
        ca1.BackColor = System.Drawing.Color.LightGray;
        ca1.AxisY.LineColor = System.Drawing.Color.LightBlue;
        chart.ChartAreas.Add(ca1);

        var imgStream = new System.IO.MemoryStream();
        chart.SaveImage(imgStream, ChartImageFormat.Png);
        imgStream.Seek(0, System.IO.SeekOrigin.Begin);

        return File(imgStream, "image/png");
    }

View
 foreach (modelstuff.Models.ScenarioModel scenario in ViewBag.Scenarios)
               { %>
               <li class="<%= i % 2 == 0 ? "row" : "altRow" %>" data-       rowid="<%= "scenario" + scenario.ID%>">

                    <%= scenario.Name%>

                    <%= Html.Chart(
                    "BuildChart",
                    "Home",
                    new
                    {
                        scenarioID = scenario.ID
                    },
                    new
                    {

                        style = "width: 576px; height:100px;",

                    }) %>


text:
Q: WP Rest API returns all results when not logged in I have a very strange issue for which I could not find the reason. I've created a WP REST API endpoint for posts and some custom post types which returns all posts and can be filtered. Everything works fine locally but in a test environment, while not logged in the endpoint returns all posts no matter the categories or search or sorting I provide to the URL, as soon as I log in everything works fine.
Examples:
wp-json/wp/v2/style?per_page=100&style_category=112

Should return only 1 post. When the user is logged it does return 1 but as soon as the user logs out it returns all posts. I ran out of ideas so please help :))

A: For those interested the issue was server cache. Thanks, guys.


text:
Q: Merging two Irregular data frames in Python I have two data frames df1 and df2
    ID      Range(US)            Count(US)          Mean(US)
0   690      1-3                 266                4.0
1            4-7                 277                NaN
2   354      1-3                 233                2.0
3            4-7                 85                 NaN
4   947      1-3                 156                4.0

and
    ID   Range(UK)           Count(UK)          Mean(UK)
0   690      1-3                 186                4.0
1            4-7                 25                 NaN
2   354      1-3                 44                 1.0
3   947      1-3                 213                3.0
4            4-7                 33                 NaN

I merged using the code:
In:df=df1.merge(df2, left_on='deviceid',right_on='deviceid', how='left')
    df
 ID  Range(US)   Count(US)    Mean(US)   Range(UK)  Count(UK)    Mean(UK)
 0  690    1-3      266         4.0        1-3        186         4.0
 1         4-7      277         NaN        4-7        25          NaN
 2         4-7      277         NaN        4-7        33          NaN
 3  354    1-3      233         2.0        1-3        44          1.0
 4         4-7      85          NaN        4-7        25          NaN
 5         4-7      85          NaN        4-7        33          NaN
 6  947    1-3      156         4.0        1-3        213         3.0

From the above we see that the values are repeated again for some values if not present
But the expected output is
   ID  Range(US)   Count(US)  Mean(US)   Range(UK)  Count(UK)    Mean(UK)
 0  690    1-3      266         4.0        1-3        186         4.0
 1         4-7      277         NaN        4-7        25          NaN
 2  354    1-3      233         2.0        1-3        44          1.0
 3         4-7      85          NaN        Nan        NaN         NaN
 4  947    1-3      156         4.0        1-3        213         3.0
 5         4-7      Nan         Nan        4-7        33          Nan

A: First remove replacing duplicated ID in both DataFrames:
#df1['ID'] = df1['ID'].mask(df['ID'].duplicated(), '')
#df2['ID'] = df2['ID'].mask(df['ID'].duplicated(), '')

print (df1)
    ID Range(US)  Count(US)  Mean(US)
0  690       1-3        266       4.0
1  690       4-7        277       NaN
2  354       1-3        233       2.0
3  354       4-7         85       NaN
4  947       1-3        156       4.0

print (df2)
    ID Range(UK)  Count(UK)  Mean(UK)
0  690       1-3        186       4.0
1  690       4-7         25       NaN
2  354       1-3         44       1.0
3  947       1-3        213       3.0
4  947       4-7         33       NaN

And then merge by both columns with outer join:
df = df1.merge(df2, left_on=['ID', 'Range(US)'], right_on=['ID', 'Range(UK)'], how='outer')
print (df)
    ID Range(US)  Count(US)  Mean(US) Range(UK)  Count(UK)  Mean(UK)
0  690       1-3      266.0       4.0       1-3      186.0       4.0
1  690       4-7      277.0       NaN       4-7       25.0       NaN
2  354       1-3      233.0       2.0       1-3       44.0       1.0
3  354       4-7       85.0       NaN       NaN        NaN       NaN
4  947       1-3      156.0       4.0       1-3      213.0       3.0
5  947       NaN        NaN       NaN       4-7       33.0       NaN


text:
Q: Term for menu that appears at the top of many webpages What is the term for the menu that appears at the top right of many webpages? Here are two examples:

A: Maybe: Header, Topbar, Navbar, Topmenu

A: While I'm not entirely sure if there is any specific name for it. It could be referred to as a "Fixed Menu" or a "Navigation Menu".
As far as a name based on its position. It really depends. To me I would say its a Fixed Navigation Menu because it retains its location between pages and does offer navigation. It is not on the side of the webpage, so it would not be a Side Menu, and its not on the footer, so its not a Footer Navigation Menu.


text:
Q: Failing example with LWN's "Namespaces in operation, part 4: more on PID namespaces" The final example from this article fails to work as intended. This is the code:

*

*simple_init.c

*ns_child_exec.c

*orphan.c

*ns_run.c
My environment is Fedora 24, and this is the output I should receive:

*

*# ./ns_child_exec -p ./simple_init -v
    init: my PID is 1
init$
    init: SIGCHLD handler: PID 3 terminated

*# ps -C sleep -C simple_init
  PID TTY          TIME CMD
 9147 pts/8    00:00:00 simple_init
# ./ns_run -f -n /proc/9147/ns/pid ./orphan
Parent (PID=2) created child with PID 3
Parent (PID=2; PPID=0) terminating
#
Child  (PID=3) now an orphan (parent PID=1)
Child  (PID=3) terminating

However, this is the output I receive:

*

*# sudo ./ns_child_exec -p ./simple_init -v
    init: my PID is 1
init$

*# sudo ps -C sleep -C simple_init
  PID TTY          TIME CMD
 2665 pts/2    00:00:00 simple_init
# sudo ./ns_run -f -n /proc/2665/ns/pid ./orphan
Parent (PID=2) created child with PID 3
Parent (PID=2; PPID=0) terminating
# sudo ./ns_run -f -n /proc/2665/ns/pid ./orphan
Parent (PID=4) created child with PID 5
Parent (PID=4; PPID=0) terminating
# sudo ./ns_run -f -n /proc/2665/ns/pid ./orphan
Parent (PID=6) created child with PID 7
Parent (PID=6; PPID=0) terminating
# sudo ./ns_run -f -n /proc/2665/ns/pid ./orphan
Parent (PID=8) created child with PID 9
Parent (PID=8; PPID=0) terminating

It's as if orphan's child does nothing, and is never re-parented. However, running orphan via simple_init's shell (without ns_run) works as expected.


text:
Q: Change output variable PHP fputcsv I'm outputting SQL data into a CSV file and want to make the data more user readable. Currently field terminal_id returns various integers and I want to translate it into more user readable data.
In the different rows I have integers from 1-10 in this field. I essentially want it to output as a simple text string in the CSV file dependent on what the integer is. So for instance, instead of outputting 3 in the CSV file (just a random example), I need it to output New York.
I have a separate table called terminal that has columns id and name. name is what I actually want outputting to the CSV file rather than terminal_id.
The column in table terminalcashcollectionrecord that has the 3 in it is terminal_id. This is the correlating data in table terminal that also has column name in it.
Here's the code a snippet of that specific code:
//query the database
$query = 'SELECT terminaltime, terminal_id, amount, terminaltime FROM terminalcashcollectionrecord';

if ($rows = mysqli_query($link, $query))
{
    // loop over the rows, outputting them
    while ($row = mysqli_fetch_assoc($rows))
    {
        fputcsv($output, $row);
    }

A: This should select terminaltime and amount from terminalcashcollectionrecord and name from terminal where terminal_id equals id. You had terminaltime listed twice so I removed the second one:
SELECT a.terminaltime, b.name, a.amount
    FROM terminalcashcollectionrecord a
    LEFT JOIN terminal b
    ON a.terminal_id = b.id

See MySQL JOIN Syntax.


text:
Q: How to match 2nd instance in regex get_by_my_column
If I only want to match the get_by portion of the above string, how can I do this?  I keep reading on this regex cheatsheet that I should use \n but I can't figure out how to implement it properly...
I've tried variations of the following...
/((_){2})/
/(_+){2}/

A: Do you need to use a regex for this? You could use explode() and just grab the first two elements of the resulting array.

A: Try
preg_match('/(^[a-z]+[_][a-z]+)/', $string, $results);
This matches a string that starts with a group of letters followed by an underscore followed by another set of letters.
Edit: (lowercase letters)

A: /(\w+?_\w+?)_\w+/ (use non greedy quantifiers, your substring should be in capture group 1)
or just /\w+?_\w+?/ <---(edit: won't work, you do need that second underscore as regex structure to force the non greedy \w up to it :])

A: try /^get_by. ^ for the condition that g must be the starting character.


text:
Q: Video.js poster frame too big on iPod Touch 5G I embedded a video on my 'responsive' web page built with RapidWeaver, and my video plays OK on both desktop Safari and Firefox.
But on my iPod Touch 4G the poster image does not shrink enough for the play arrow to be visible, I just see the lefthand half of the poster image. After repeated tapping, the video plays, but the initial impression does not look good and inconvenient to use.
I used to have this problem with older versions of JWPlayer, where the poster size was specified in pixels HxW, but the latest version of that player uses a script that just says that the poster image width is 100%, and now the poster image fits nicely across the width of the iPod Touch screen.

A: I was building a Drupal site, where I had a video on the front page with the same problem. This is how I fixed it:
@media (max-width: 320px) {
    .video-js {
    zoom: .7;
    margin-left: auto;
    margin-right: auto;
    }
}
@media (max-width: 460px) {
  .video-js {
    zoom: .73 !important;
    margin-left: auto;
    margin-right: auto;
  }
}

change .7 and .73 to whatever numbers make your video fit best with trial and error.


text:
Q: Is OpenXML SDK required to be installed in every computer that will run my program? Is there a way to deploy my application (which uses ClosedXML) and not be required to install OpenXMLSDKv2.msi on each computer?
If I uninstall the sdk I get this error at runtime:

I already referenced DocumentFormat.OpenXml (copy local = true) and WindowsBase (also copy local true, despite being not necessary.
DocumentFormat.OpenXml.dll and ClosedXML.dll are both on the bin folder.

A:
DocumentFormat.OpenXml.dll and ClosedXML.dll are both on the bin folder.

This should be enough, no installation required.
See this question for other takes on this error (for all dlls, not just ClosedXML / OpenXml).