text:
Q: ¿Cómo comprobar que un elemento de mi JSON es el primero? Necesito comprobar el primer elemento para poder hacer un if.
Ejemplo de JSON:
{"elementos": [
          {
              "elemento": [
                  {
                      "hora": "00:00:00.000"
                  },
                  {
                      "hora": "00:00:00.450"
                  }
              ]
            }
          ]
        }

Y lo estoy haciendo con un each y debo comprobarlo dentro de este mismo.
$.each(json.elementos.elemento, function(index_elementos, valores_elementos){
   /*En el caso que tuviera un elemento llamado hora*/

valores_elementos[0].hora == /*a el primer elemento*/;

)};

es un ejemplo burdo pero creo que se entiende.


text:
Q: Raspberrypi3 system calls - passing 64 bit arguments I created a system call for my raspberrypi3 in the kernel from github.com/raspberrypi/linux and with the RT patch applied.
Upon playing around, I notice I can't pass a 64 bit argument.  I created a user app that uses the syscall() function for testing.
Here is my system call:
asmlinkage long sys_testCall(const char __user* buf, unsigned long long testVal)
{
    unsigned long long val1 = 1000;
    unsigned long long val2 = 68719476735;
    unsigned long long retVal = 0;

    retVal = val1 + val1;
    printk("sum 1000 = %llu\n", retVal);

    retVal = val2 + val2;
    printk("sum Fs = %llu\n", retVal);

    printk("DEBUG: Entering %s %d \n", __FUNCTION__, __LINE__);
    printk("DEBUG: Buff: %s\n", buf);
    printk("DEBUG: testVal: %llu\n", testVal);
    printk("DEBUG: testVal: %llx\n", testVal);

    return 0;
}

and here is my user app:
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

// arm-linux-gnueabihf-gcc -o sysTest userSyscallTest.c

void main(int argc, char *argv[])
{
    int val = strtol(argv[1], NULL, 10);

    unsigned long long testVal = 100;
    char *mess = "MyMessage";

    printf("SYSCALL TEST: %d\n", val);
    if (397 == val)
    {
        long int test_call_ret = syscall(val, mess, testVal);
    }
    else
    {
        long int syscallRet = syscall(val);
    }
}

I compile on the target and execute ./sysTest 397 ... with that, I get:
SYSCALL TEST: 397[  595.650294] sum 1000 = 2000

[  595.654537] sum Fs = 137438953470
[  595.658007] DEBUG: Entering sys_testCall 53
[  595.662279] DEBUG: Buff: MyMessage
[  595.665682] DEBUG: testVal: 9137185598140841984
[  595.670214] DEBUG: testVal: 7ecdcde400000000

I'm not sure how to explain how the "math" handles 64bit values while the system call does not.  I assume both conditions are handled from some register loads, moves, swaps, etc.  But, I am not sure of those details.  I'm currently looking ...
While I continue searching through my code, I figured I would ask here as well.
Thoughts?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doubt related to rotational motion (rolling down an inclined plane) I have doubt regarding when an object ( sphere , ring , cylinder etc ) rolls down a FRICTIONLESS inclined plane.
Let us suppose the angle of inclination of inclined plane is θ.
Now the forces acting on it will be weight force (mg) and normal reaction. A component of mg perpendicular to incline mgcosθ will be balanced by the normal reaction. There will be another component of mg along the incline mgsinθ which will give the object acceleration gsinθ. There is no friction.
Now,
acceleration, a = radius ( r ) x angular acceleration (α)
Now as there is,  a = gsinθ so there must be nonzero value of α.
But force mg and normal reaction are forces whose line of action passes through the centre of the object ( ring etc ) ( passes through centre of mass). So net torque about centre should be zero and there should be no angular acceleration.
Also, will the angular momentum be conserved when it reaches the bottom of incline?
I'm confused please help me.

A:
Now, acceleration, a = radius ( r ) x angular acceleration (α) Now as there is, a = gsinθ so there must be nonzero value of α.

That is only true for rotational motion. As it stands there is nothing in your problem to suggest that any sort of rotational motion will happen. Since the plane is "FRICTIONLESS" (your words), it does not do the normal "rolling without slipping" motion but instead slips completely, sliding down without any rotation whatsoever.
This is why, as you say, the net torque about the center will be zero and angular acceleration will be zero.
Angular momentum will may or may not be conserved at the bottom of the incline; it depends on whether the new ground that it is rolling onto is frictionless (hence torquing the object) or not.


text:
Q: Facebook app with error I'm not a Facebook App expert. I grabbed this code from the FB website and I modified it to make it work with my app id (it is the only thing I changed. I added a couple of alerts too). Then I tried to use this code from a local webpage (that is: the page is on my desktop but my laptop is connected to the Internet).
Anytime I run this code I get a browser popup showing this error:
"An error occurred with MyAppName. Please try again later."
Can someone tell me what's going on here? It seems the FB.getLoginStatus never gets called too.
Any help is appreciated.
// initialize the library with the API key
FB.init({ appId: 'myAppID',frictionlessRequests:true });

// fetch the status on load
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
alert("1. not");
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
alert("2. alert");
// the user isn't logged in to Facebook.
}
});

$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});

$('#logout').bind('click', function() {
FB.logout(handleSessionResponse);
});

$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});

// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}

// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
alert("entered handleSessionResponse");
if (response.authResponse) {
alert('Welcome!  Fetching your information.... ');
FB.api('/me', function(response) {
alert('Good to see you, ' + response.name + '.');
});
} else {
alert('User cancelled login or did not fully authorize.');
}
if (!response.session) {
clearDisplay();
return;
}
}

A: Have you changed the property myAppID to the ID of the Facebook app you are using?
FB.init({ appId: 'myAppID',frictionlessRequests:true });

The myAppID should contain a unique Facebook App ID which you can fetch on the Facebook App page. Maybe you just copied the code without changing this.


text:
Q: POST to django from iOS app denied 403 i have written a django webservice that is suppose to be consumed by my iOS app.
i have manage to get GET requests to work with no particular problem, however the minute i start using POST i get 403.
I read that it might be the csrf so i tried
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt

and of course it works!
here is my django view code
questionAnswer = request.POST['questionAnswer']
facebookID = request.POST['facebookID']
if Question.objects.get(pk=int(question_id)).meaning == questionAnswer:
    u = User.objects.get(fbid = facebookID)
    u.questions_answered = u.questions_answered + 1
    u.save()
    dictForSend = {'didAnswerCorrect' : 'True'}
    jsonq = json.dumps(dictForSend)
    return HttpResponse(jsonq, content_type='application/json')
else:
    dictForSend = {'didAnswerCorrect' : 'False'}
    jsonq = json.dumps(dictForSend)
    return HttpResponse(jsonq, content_type='application/json')

and here is my objective c code
NSDictionary *postDict = @{ @"questionAnswer": questionAnswer, @"facebookID": facebookID};
NSString *myDictInJSON = [postDict JSONRepresentation];
NSData *postData = [myDictInJSON dataUsingEncoding:NSUTF8StringEncoding];

NSString *URLForSend = [NSString stringWithFormat:(@"http://127.0.0.1:8000/questions/checkanswer/%@/") , questionID ];
NSURL *url = [NSURL URLWithString:URLForSend];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"%@", JSON);
} failure:nil];
[operation start];

terminal line
"POST /questions/checkanswer/1/ HTTP/1.1" 403 2282

any idea how to incorporate csrf in my app?

A: Look at this question: CSRF Token in Django and iOS I don't think you really need csrf protection in your case.


text:
Q: Small Proof $\lim_{x\to x_0}f(x)\leq \lim_{x\to x_0}g(x)$ Can I get a quick check to see if I have done this correctly.
Limit proof
Assume By contradiction that $L_1>L_2$. Let $\epsilon = \frac{L_1-L_2}{2}$ then,
$\forall$ $\epsilon>0$ $\exists$ $\delta_1>0$ such that if $0<|x-x_0|<\delta_1$ then $|f(x)-L|<\epsilon$
$\forall$ $\epsilon>0$ $\exists$ $\delta_2>0$ such that if $0<|x-x_0|<\delta_2$ then $|g(x)-L|<\epsilon$
Therefore we get that,
$L_1-\frac{L_1-L_2}{2}<f(x)<L_1+\frac{L_1-L_2}{2}$ $\Rightarrow$ $\frac{L_1-L_2}{2}<f(x)<\frac{3L_1-L_2}{2}$
$L_2-\frac{L_1-L_2}{2}<g(x)<L_2\frac{L_1-L_2}{2}$ $\Rightarrow$ $\frac{-L_1-3L_2}{2}<g(x)<\frac{L_1-L_2}{2}$
which means that $g(x)<\frac{L_1-L_2}{2}<f(x)$ then $g(x)<f(x)$ which is a contradiction.
Thanks.

A: You should mention that the "wrong" inequality would hold for at least one $x$: just choose $x$ with $0<|x-x_0|<\min(\delta_1,\delta_2)$.
You can also do it without contradiction.

Suppose $f$ and $g$ are defined over $D=(x_0-k,x_0)\cup(x_0,x_0+k)$ (for some $k>0$) and that, for $x\in D$, $f(x)\le g(x)$.
Suppose also that $\lim_{x\to x_0}f(x)=L_1$ and $\lim_{x\to x_0}g(x)=L_2$ are finite. Then $L_1\le L_2$.

Let $\varepsilon>0$. There exists $\delta>0$ (and $\delta<k$) such that, for $0<|x-x_0|<\delta$,
$$
L_1-\varepsilon<f(x)<L_1+\varepsilon,
\qquad
L_2-\varepsilon<g(x)<L_2+\varepsilon,
$$
For such an $x$, we have
$$
L_1-\varepsilon<f(x)\le g(x)<L_2+\varepsilon
$$
which implies
$$
L_1-L_2<2\varepsilon
$$
Since $\varepsilon$ is arbitrary, we deduce $L_1-L_2\le 0$.


text:
Q: SQLite autoincrement primary key fields dont allow update I have got a database table with a column "id INTEGER PRIMARY KEY AUTOINCREMENT". When I try to update an existing row of this table with the primary key, the app exits saying "Unfortunately  is stopped."
public int updateUser(User user) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_FIRSTNAME, user.getUser_firstName()); // user first name
    values.put(KEY_LASTNAME, user.getUser_lastName()); // user first name
    values.put(KEY_USERNAME, user.getUsername());
    values.put(KEY_PASSWORD, user.getPassword());
    values.put(KEY_USERLEVEL, user.getUser_level());
    values.put(KEY_DESIGNATION, user.getDesignation());
    values.put(KEY_MOBILENO, user.getMobile_no());
    values.put(KEY_EMAIL, user.getEmail());
    values.put(KEY_NIC, user.getNIC());
    values.put(KEY_GENDER, user.getGender());
    values.put(KEY_DOB, user.getDOB());
    values.put(KEY_AVAILABILITY, user.getAvailability());

    db.close();

    // updating row
    return db.update(TABLE_USERS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(user.getUser_id()) });

Logcat :
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projectmanagementsys.com.sasith.project_management/com.projectmanagementsys.com.sasith.project_management.AddUser}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.projectmanagementsys.com.sasith.project_management/databases/ProjectManagement

There is no error in the whole thing and the code works well when I comment the update query. Can someone give a solution please ?
Thank you.

A: You have the line db.close() followed by db.update() and your error states that you are attempting to open an already-closed object. You haven't closed the db after you've added the data, you've closed it before. You'll need to update the row, close the database, then return your value.
// updating row
int result = db.update(TABLE_USERS, values, KEY_ID + " = ?",
        new String[] { String.valueOf(user.getUser_id()) });

db.close();
return result;


text:
Q: php regex combine repeated list with single occurrence and exclude whole words I fail with some regex task I need for replacing some text information.
The following task can be done also in not regex but if would be nice to have it in regex because there is much to replace.
However the question is:

*

*find characters in the set [\w\. \&\=\?\-\(\)\'\+] which can be occure 3-99 times, so write: [\w\. \&\=\?\-\(\)\'\+]{3-99}

*Within the list a newline can appear once, so write \n?

*after this characters a fixed string appears, so just write: <test@mail.se>

*but within the list of characters the word "for" should not appear

So if I use: ((?!for)[\w\. \&\=\?\-\(\)\'\+]{3,99}|(\n?))<test@mail\.se> the word 'for' will be matched even though. Do anyone has an idea?
So example:
Within this string:
    To: Lasse Erikson <test@mail.se>

I want to match the name and the mail.
Even here:
To: Lasse Erikson <test@mail.se>, Sara
    Larsson <mail@mail.se>

But here I want not fetch anything:
 for <test@mail.se>; Thu, 14 Dec 2017 21:18:22 +0100 (CET)

Because there is a "for" in the line.
I hope you understand this...
Thank you in advance

A: PHP (PCRE) provides some verbs to skip over or fail current matching process that you can use to skip over word for or fail whole match if you want:
((?(?=\bfor\b)for(*SKIP)(*F))[ \w.(&=?\-+)](?(2)|(\R)?)){3,99}<[^<>@]*@[^<>]*>

Live demo
Breakdown:
(   # Start of capturing group #1
    (?(?=\bfor\b)for(*SKIP)(*F))    # Skip over `for` if any
    [ \w.(&=?\-+)]  # Match whitelist characters
    (?(2)|(\R)?)    # One newline character between
){3,99} # Between 3 or 99 times, end of CG #1
<[^<>@]*@[^<>]*> # Match an email format


text:
Q: Modal solo cierra haciendo click afuera Necesito que mi popup modal cierre solo si le hago click en la imagen o bien en una x de "cerrar" en la imagen.
El codigo que tengo actualmente es:

A: Ah pues en el inicio donde empieza el html de tu modal checa que contenga lo siguiente:
class="modal fade" data-keyboard="false" data-backdrop="static"

Un ejemplo:

Y con eso cierras mediante el botoncito "x" del modal únicamente.
Para lo de hacer clic para cerrar el modal con la imagen asígnale un id, por ejemplo:

Y en tu javascript (y ya que estás usando jquery) pones lo siguiente:
$('#imgcerrar_bs_modal').click(function() {
    $('#idDeTuModal').modal('hide');
});


text:
Q: Weird results due to argument promotion when missing the prototype declaration in C I have encounter a problem which can be summarized as follows,
#include <stdio.h>
int main()
{
        float f=23.45;
        printf("main: %f\n", f);
        t1(f);
/*    the result would be
      main:23.450001
      t1:2.000000    */
}
void t1(float f)
{
        printf("t1: %f\n", f);
}

I know now that the weird behavior is due to missing of prototype declaration and the arguments are thus promoted,(float->double?),still i cannot figure out why the result is 2.000000,so can anyone give a more detailed explanation? I am using ubuntu10.04 gcc4.4.3

A: The behavior you are observing is specific to stack-based parameter passing. For people who compile 64-bit x86 code by default and are unable to reproduce it, you can try with "gcc -m32" instead of just "gcc".
With stack-based parameter passing, t1() read 32 bits from the stack, and these 32 bits happen to form the floating-point value 2.0.
At the call site, because t1 did not have a prototype, the argument f was promoted to double and it was a double that was written on the stack (C99 6.5.2.2:6 "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions").
There is no reason for t1 to recover the intended value from the stack since it does not read it properly with the same type and width it was written.

A: Because the compiler does not know that t1 takes a float, it promotes the float to a double. On your platform, t1 interprets the first four bytes of that double as a float.
2.0 is represented as 1 x 2^0, which in binary is three zero bytes followed by a 64 (on x86-64). As it happens, 23.45 as a double has the same first four bytes, 0, 0, 0, 64 (followed by 51, 115, 55, 64). So if you take the double 23.45 and interpret the first four bytes of it as a float, you get 2.0.

A: Remember that a missing prototype implies the function will later be declared with int arguments, and that appropriate conversions take place. So, I assume if you replace the float by int in the declaration of t1, you'll get a result of 23.


text:
Q: Android Intellij The device is not ready After installing new version of Windows and intellij again i get this error:
The device is not ready

my project build is Gradle and after remove .gradle from home folder and Invalidate Cache and Restart and try to change Target Device to USB or other options my problem don't resolve. how to resolve this problem?

A: It seems that ADB drivers for your device is either missing or not installed properly, Do a clean install of latest Android Studio from http://developer.android.com/sdk/index.html , if you are testing it on a physical device enable USB debugging in developer options, Developer Options is usually a hidden setting, you can enable it by tapping build number around 7 times in About Phone, If you want to test it on an Emulator create a new AVD and make sure that you have the images for the device installed from SDK manager. You need not remove any .gradle file or any other file, just import the project in Android Studio, it should work without any issue in the latest version of android studio. If you need further help you can reach out to me at my mail or skype. I can also help you out via teamviewer, if you need.

A: After change Android SDK location on files, problem solved


text:
Q: How to insert a vector with different length to a matrix in MATLAB? How to insert a vector with different length to a matrix? For example I have a randomly located nodes=10; After that I am finding who are the neighbours of this nodes for example for node: i = 2 neighbours are nodes: j = 5 and 6, so the vector which containts this value is neighb_i = [neighb_i j]; but maybe I have to add some zeros to fill the vector till the length of a matrix ( in this case nodes are 10, so the matrix will be 10x10 ) But I want to keep all the values of neighbours for all nodes in a matrix, because when I am using a vector after the next interation this value is replacing themselves so at the next iteration when i = 3 I don't have information about when i = 2. How can I store this in a matrix, which has length nodes x nodes ?
close all
clear all
clc

x = 2000;  %m

y = 2000;  %m

nodes = 8;

%% Random location and direction, calculating the distance;

loc_x = x*rand(1,nodes)

loc_y = y*rand(1,nodes)

loc = [loc_x' loc_y']

dist(loc_x);

dist(loc_y);

distance = sqrt(dist(loc_x).^2 + dist(loc_y).^2)   % = dist(loc')

distance(1:nodes+1:nodes^2) = inf;  % replace zero diagonal with infinity

%% Power:

noise_power_dBm = -90; %dBm

noise_power_w = 10^((noise_power_dBm - 30)/10); % W

% The channel is based on a path-loss model in which  is distance between    nodes i and j
% and 3 - is attenuation exponent considerd as 3 ( 1:6 )

channel_gain = (1)./(distance).^3;   %dB

channel_gain(1:nodes+1:nodes^2) = inf;  % replace zero diagonal with infinity

min_SNR_dB = 10; %dB, minimum required SNR at the receiving nodes

min_SNR = 10^(min_SNR_dB/10);

p_max_dBm = 10;   % dBm

p_max_w = 10^((p_max_dBm - 30)/10);  % W

p_uni = (min_SNR*noise_power_w)./(channel_gain); % unicast power between two nodes

p_uni(1:nodes+1:nodes^2) = inf;  % replace zero diagonal with infinity

plot(loc_x,loc_y,'r*');

change = 1;

cost = inf(1,nodes)   % at the beginning cost of all nodes are infinity

cost(1) = 0;          % except the cost of node 1 = 0 ( source node )

while change == 1   % change is when a child chooses parent node and change its parent node; if its a =1 its go again in for loops

change = 0;     % when i am coming inside while loop I change the change parameter to 0 and if some changes occurse

for i = 2:nodes %i - child node   first i = 2, then j is 1,2,3...8 it checks all the nodes starts from 1 because source node can be a neighbour of other node

neighb_i = [];

for j = 1:nodes  % j - parent node

if p_uni(i,j) < p_max_w

   neighb_i = [neighb_i j];  %Found who are the neighbours  ; to use a matrix not a vector ????????

end
% calculate the cost for every nodes First Dijkstra, later MC
% and choose the parent node for every node ; if we have some changes
% ---> change = 1

for k = [neighb_i j] % neighb_i

% cost(i,k) = 1:nodes;

end
end
keyboard
end
% At the end of this while - I have to know what is the parent node for
% every node and when I come out I can draw a graph.
end

%%
gplot(nodes,loc)

%plot(source,'b*');
plot(loc_x,loc_y,'rO');
axis([x y x y]);

hold on;
grid on;
grid on, xlabel('x'), ylabel('y');
title('Random nodes');


text:
Q: Using Python to login to a .aspx form I'm trying to log onto a website that uses aspx. I tried everything and all the solutions from Stackoverflow. I was trying with python requests and robobrowser but both failed.
Here is the form that I got from javascript, the problem here is that there is no button to submit the form, it's just a span tag.
0: form#frmDefaultMaster
0: input#rsmDefaultMaster_TSM
1: select.nav-select
2: input#ctl00_contDefaultMaster_rtbUserName.riTextBox.riEnabled
3: input#ctl00_contDefaultMaster_rtbUserName_ClientState
4: input#ctl00_contDefaultMaster_rtbPassword.riTextBox.riEnabled
5: input#ctl00_contDefaultMaster_rtbPassword_ClientState
6: input#ctl00_contDefaultMaster_rbLogin_ClientState
7: input#__LASTFOCUS
8: input#__EVENTTARGET
9: input#__EVENTARGUMENT
10: input#__VIEWSTATE
11: input#__VIEWSTATEGENERATOR
12: input#__EVENTVALIDATION

The response:
....
__VIEWSTATEGENERATOR: CD85D8D2
__EVENTVALIDATION: QKgKEA99vPpanZgU8X6PHAHp6NosVDjGbPeekexd8iwC9n+kKHZ554FzuWjeshUTg6ezi2F4dTJER3UO0ptPsluIGkdnkkqwdE13WSlRM99GijZKCw1S4NRNdARxkJB3tf/qD+i/IGVhYLIXe3n0ehDebns8xUBxy2S5+/LymGStS8//dES8XZPt48MsSHMoWCpRs2zyWE2m7AijL9sAVg==
ctl00$contDefaultMaster$rtbUserName: USERNAME
ctl00_contDefaultMaster_rtbUserName_ClientState: {"enabled":true,"emptyMessage":"","validationText":"USERNAME","valueAsString":"USERNAME","lastSetTextBoxValue":"USERNAME"}
ctl00$contDefaultMaster$rtbPassword: PASSWORD
ctl00_contDefaultMaster_rtbPassword_ClientState: {"enabled":true,"emptyMessage":"","validationText":"PASSWORD","valueAsString":"PASSWORD","lastSetTextBoxValue":"PASSWORD"}
ctl00_contDefaultMaster_rbLogin_ClientState:
__ASYNCPOST: true
RadAJAXControlID: ctl00_contDefaultMaster_rapLogin

And finally my python code:
    URL = 'URL'

    username = 'USERNAME'
    password = 'PASSWORD'

    browser = RoboBrowser(history=True)
    browser.open(URL)
    signin = browser.get_form(id='frmDefaultMaster')
    signin["ctl00$contDefaultMaster$rtbUserName"].value = username
    signin["ctl00_contDefaultMaster_rtbUserName_ClientState"].value = {"emptyMessage": "",
                                                                       "validationText": username,
                                                                       "valueAsString": username,
                                                                       "lastSetTextBoxValue": username}

    signin["ctl00$contDefaultMaster$rtbPassword"].value = password
    signin["ctl00_contDefaultMaster_rtbPassword_ClientState"].value = {"emptyMessage": "",
                                                                       "validationText": password,
                                                                       "valueAsString": password,
                                                                       "lastSetTextBoxValue": password}
    signin["ctl00_contDefaultMaster_rbLogin_ClientState"].value = ""
    browser.submit_form(signin)

    print(browser.url)

    print(signin)

Every time I run the browser redirects me to the error page.
Any help?


text:
Q: Selecting columns of Dataframe in Spark Scala If you want to select the first column of a dataframe this can be done:
df.select(df.columns(0))

df.columns(0) returns a string, so by giving the name of the column, the select is able to get the column correctly.
Now, suppose I want to select the first 3 columns of the dataset, this is what I would intuitively do:
df.select(df.columns.split(0,3):_*)

The _* operator would pass the array of strings as a varag to my understanding, and it would be the same as passing (df.column(1), df.column(2), df.column(3)) to the select statement. However this doesn't work and it is necessary to do this:
import org.apache.spark.sql.functions.col
df.select(sf.columns.split(0,3).map(i => col(i)):_*))

What is going on?

A: I think in the question you meant slice instead of split.
And as for your question,
df.columns.slice(0,3):_* is meant to be passed to functions with *-parameters (varargs), i.e. if you call select(columns:_*) then there must be a function defined with varargs, e.g. def select(cols: String*).
But there can only be one such function defined - no overloading here is possible.
Example on why it's not possible to define two different functions with same vararg-parameter declaration:
def select(cols: String*): String = "string"
select() // returns "string"
def select(cols: Column*): Int = 3
select() // now returns 3

And in Spark, that one function is defined not for Strings but for Columns:
def select(cols: Column*)

For Strings, the method is declared like this:
def select(col: String, cols: String*)

I suggest you to stick to Columns, like you do now, but with some syntax sugar:
df.select(df.columns.slice(0,3).map(col):_*))

Or if there's a need to pass column names as Strings, then you can use selectExpr:
df.selectExpr(df.columns.slice(0,3):_*)


text:
Q: Bind DataContext and not set in code behind I have a WPF application and I use Prism and Unity. I have also two custom user controls:

*

*PlotViewControl

*PlotViewReport
The second uses the first control in a DataTemplate.
If I want to call:
regionManager.RequestNavigate("RightRegion", "PlotViewControl", parameters);

The DataContext for PlotViewControl must be set in PlotViewControl.xamls.cs like so:
this.DataContext =  new PlotViewModel();

If I want to use the above UserControl in PlotViewReport in the following manner, I must remove the line above.
<ListView Name="PlotLista" SelectedIndex="{Binding SelectedValue}"
          ItemsSource="{Binding PlotReportModelList}"
          HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <!--<ItemsControl ItemsSource="{Binding }">-->
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding}"/>
                <pv:PlotViewControl DataContext="{Binding }"  />
            </StackPanel>
            <!--</ItemsControl>-->
        </DataTemplate>
    </ListView.ItemTemplate>

So, which is the solution to be able to use the both scenarios.

A: Taking into consideration that you set the DataContext as {Binding} inside the ItemTemplate, this will point to the current ListView item. So, you have to use a RelativeSource binding to get to the DataContext of the ListView.
Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.ViewModel}"


text:
Q: mysql sum column with same id I have orders table, order_details table
I join orders table with order_details table to make a temporary table that look like this
order_id | customer_id | Quantity |
      2  |          2  |    10    |
      2  |          2  |    25    |
      2  |          2  |    5     |
      2  |          2  |    15    |
      3  |          2  |    25    |

What I am trying to achieve is sum Quantity column where order_id is same.
so the end result look like this
order_id | customer_id | Quantity |
      2  |          2  |    55    |
      3  |          2  |    25    |

my sql statement to get to here look like this
SELECT
        orders.orders_id,
        orders.customer_id_fk,
        sum(order_detail.quantity)
        FROM orders
        LEFT  JOIN order_detail on orders.orders_id = order_detail.orders_id_fk
        WHERE customer_id_fk IN(2)  <-- this is needed because I only want to see customer 2.

how do I put a condition on the sum ?

A: Looks like you are very close!
You should be able to group by order_idto get a list of unique order_ids with the Quantity sum for each order_id
SELECT
 orders.orders_id,
 orders.customer_id_fk,
 sum(order_detail.quantity)
FROM orders
LEFT  JOIN order_detail on orders.orders_id = order_detail.orders_id_fk
WHERE customer_id_fk IN(2)
GROUP BY orders.orders_id,orders.customer_id_fk

A: use Group by
SELECT
        orders.orders_id,
        orders.customer_id_fk,
        sum(order_detail.quantity)
        FROM orders
        LEFT  JOIN order_detail on orders.orders_id = order_detail.orders_id_fk
        WHERE customer_id_fk IN(2) GROUP BY orders.orders_id,orders.customer_id_fk

A: Here is OP. Sorry I derped. I put GROUP BY after Order by and it didnt work. the below sovled it
SELECT
        orders.orders_id,
        orders.customer_id_fk,
        sum(order_detail.quantity)
        FROM orders
        LEFT  JOIN order_detail on orders.orders_id = order_detail.orders_id_fk
        WHERE customer_id_fk IN(2)
        GROUP BY orders_id
        ORDER BY customer_id


text:
Q: Should JSON API entities include a relationship for its parent? I haven't been able to find a clear answer, hoping someone can help.
If we have, say, a blog with posts, and each post can have comments, and each comment a related user. Is it against convention, if I request the comment, to include both the user and the post in the relationships?
data: {
  type: 'comments',
  id: '1',
  relationships: {
    post: {...}, //should this be here?
    user: {...},
  }
  attributes: {...},
},
included: {...}

A: As paulsm4 correctly stated: "it is up to you".
But I can give you some advice about that.
In such situations, you can give the caller of the API the choice of having such links or not via a querystring flag, like
?relationships=post,user
In this case, if you do not specify the relationship flag, you'll get the simple comment data or you can decide to give them all; in the second case, you can use relationships as a sort of filter.
In some APIs, I've seen also a more invasive approach: embed the related object directly in the returned JSON.
With the same technique as before:
?embed=post,user
This should produce an embedded JSON object in the current JSON reply including the original objects just as you were asking something like "GET /post/123" or "GET /user/456" separately. This can be handy in some situations.
Often this flag is named "expand" denoting same or similar behaviour.
For an example open this API documentation from Atlassian and search for "expand".
It does exist an old "standard" for your problem called HAL that speaks about linking and embedding in REST APIs.
Even the Wordpress API offers such features, give it a look in the official documentation.
An alternative to this is to rewrite the entire API in GraphQL leveraging the REST approach.

A: Q: Should JSON API entities include a relationship for its parent?
A: I assume that's entirely up to you!
If your JSON is defined by some third party, then you have to live with what they gave you.  Please post details on how the JSON is specified.
Otherwise, if you're "inventing" the format yourself:

*

*One possibility is to have a relationships: field with a link to the "parent".

*Perhaps a better solution might to invent a "container" (perhaps a simple array!) to hold your "records".

*If this were a database, I'd have a "posts" table, and a "comments" table.  The "comments" table would have a "Post ID" column as a foreign key into the "posts" table.
'Hope that helps ... at least a bit...

A: JSON API specification does not make any requirements on the attributes and relationships being included in a resource object. The specification is just saying how they must be formatted if they are included. If I did not missed anything, specification does not even require that all resource objects of the same type must have same attributes and relationships.
But I would argue that there isn't any value in not including the relationships. JSON API specification does not require a relationship object to include resource linkage data. On the contrary it's only talking about resource linkage data in context of a compound document, in which it's used "to link together all of the included resource objects without having to GET any URLs via links."
It's totally valid and could be considered best practice to only provide related resource link if the related resources are not included in the payload. Constructing such a link would not put any workload on your server since it does not require to query the database. It also does not make any relevant difference in payload size.
An example of a payload using both techniques would look like this. It assumes that the request explicitly asked to include related user using include query param.
// GET https://examples.com/api/v1/comments/1?include=user

{
  data: {
    type: 'comments',
    id: '1',
    relationships: {
      post: {
        links: {
          related: 'https://examples.com/api/v1/comments/1/post'
        }
      },
      user: {
        data: {
          type: 'users',
          id: '2'
        },
        links: {
          related: 'https://examples.com/api/v1/comments/1/user'
        }
      },
    }
  },
  included: [
    {
      type: 'users',
      id: '2',
      attributes: {
        name: 'John Doe'
      }
    }
  ]
}

You may also want to include a relationship link, which "allows the client to directly manipulate the relationship." Update relationships chapter of spec gives a deep dive into what you could accomplish using relationship links.


text:
Q: Exporting logs using journald / rsyslogd I am trying to export kernel logs (/var/log/messages) to remote Syslog servers.  Till now, most of the system logs are stored in journald currently and rsyslogd is disabled.
So, I am planning to use rsyslogd to export logs (By configuring the rsyslog.conf file). Firstly, I will pass those kernel logs from journald to rsyslogd and then export them.
Can someone suggest if this is the right path to proceed or I can use directly journald to achieve the same?

A: Systemd can collect and store logs, but it doesn't have a built-in method of logging to remote locations such as log management systems. Instead, it relies on the device's syslog service to relay messages between journald and a remote syslog server.

However, syslog is text-based and the journald uses a binary format,
so your logs need to be converted before they can be transferred. You
can do this by using either systemd's ForwardToSyslog configuration
setting, or by using rsyslog's imjournal module.

/etc/systemd/journald.conf has a ForwardToSyslog=yes option that would allow you to forward the logs to syslog, which seems like a pretty inelegant way to me.

In rsyslog you can add the module imjournal, to get the journal logs. To use it, add the following to your /etc/rsyslog.conf file. The mmjsonparse module lets ryslog parse journald messages:
module(load="imjournal")
module(load="mmjsonparse")

Kernel messages can be logged with the standard the imklog module. Just add: module(load="imklog") to the configuration file /etc/rsyslog.conf. With the standard rsyslog configuration, this should log kernel messages to /var/log/messages and /var/log/syslog.
The forwarding can be done over UDP or TCP.
Forwarding:
*.* action(type="omfwd" target="10.0.2.1" port="514" protocol="udp")         # UDP
*.* action(type="omfwd" target="10.0.2.1" port="10514" protocol="tcp")       # TCP

Obsolote Legacy Format
*.* @10.0.1.1:514        # UDP
*.* @@10.0.1.1:514       # TCP

After adding this (please not in legacy format), your rsyslog client should start forwarding the messages to your remote syslog server.
I only added the legacy format to the answer, because if you'll find a LOT of configurations written like this.


text:
Q: Git Issue : Newly added folders are showing untracked I have cloned a empty git repository. and I have put my whole xcode application. Now I want to push these project to server, then It's showing the folder untracked.
Please look the attached screenshot. This folder contains multiple files and sub-folders.

A: As mentioned, you would need to git add/git commit before pushing.
But if ECGame content is what you want, you would need to copy said content in your empty  cloned repository, not the folder itself.
As shown in your picture, if you add/commit/push, your remote repository would include the folder ECGame/, instead of directly their files.
If some files remains untracked even after a git add, then yes, core.precomposeUnicode might help:

When false, file names are handled fully transparent by Git, which is backward compatible with older versions of Git.

But it should not be needed with recent versions of Git.
As explained in "Git Tower / Untracked files with unicode names":

The default for this config setting on OS X is true and there should be no reason to override it.
  Note that the setting is also important when sharing repos between Macs.
Once a file name has been added in decomposed form to a Git repository, the only way of solving the problem is to remove these files from Git and re-add them with core.precomposeunicode set to true on Mac OS X or perform this action on Linux or Windows.
To recap, if you have problems with unicode file names showing up as untracked:

*

*Make sure core.precomposeunicode is globally set to true on OS X
 $ git config --global core.precomposeunicode
 => true

*All files still shown as untracked need to be removed from and re-added to Git.

A: I don't know what was the exact issue behind it But it has been resolved by below command
git config core.precomposeunicode false
Ref - http://oskarhane.com/untracked-files-in-newly-cloned-git-repo/


text:
Q: Excel Array Lookups I have an excel row with some id's. I want to look up the id's from the first table in the second table below and get the id with the max date. The output should only be from the id's that are in the row in table 1.
For reference, "ID1" is in cell A1 and "ID" is in cell A4.
I posted a similar question here but my requirements changed and wanted to post this again. @rwilson in the earlier post gave me a creative formula that worked but I did not indicate that there would be duplicates in table 2. In table 2 below, "b" appears twice but with different dates. The formula output for the sample row of data below should be "b" because it has the max date. I cannot sort the table in any way as I don't control it. I need to reference it to output the id with the latest date.
ID1    ID2    ID3    ID4    id of maxdate
b      a      c      #N/A   formula

ID  Date
b   1/26/2015
b   1/28/2015
a   1/26/2015
d   1/29/2015
c   1/27/2015

UPDATED SAMPLE DATA
This data sample uses @Marc's formula below. The output should be b but it shows as d. The reason is that the index is based off of the max date. Since the max date appears in d, index outputs d by default. Is there a way to tell the index/match to only index/match on id's that appear in table 1?
ID1 ID2 ID3 ID4     id of maxdate
b   a   c   #N/A    d (should be b)

ID  Date
b   1/26/2015
c   1/26/2015
a   1/26/2015
d   1/28/2015
b   1/28/2015

For reference, table 1 starts at cell A1 and table 2 starts at cell A4. Here is the formula in cell E2.
=INDEX($A$4:$A$9,MATCH(MAX(IF($A$4:$A$9=IFERROR(A2,""),$B$4:$B$9,0),IF($A$4:$A$9=IFERROR(B2,""),$B$4:$B$9,0),IF($A$4:$A$9=IFERROR(C2,""),$B$4:$B$9,0),IF($A$4:$A$9=IFERROR(D2,""),$B$4:$B$9,0)),$B$4:$B$9,0))
UPDATE #2
Here is the output based on @XOR's formula. Here is a case where it doesn't work.
ID1 ID2 ID3 ID4     id of maxdate
b   a   d   #N/A    b (should be a)

ID  Date
b   1/26/2015
c   2/26/2015
a   1/31/2015
d   1/29/2015
b   1/30/2015

A: =IF(SUMPRODUCT(COUNTIF(A2:C2,A5:A9)),LOOKUP(1,0/FREQUENCY(0,1/(1+(B5:B9=AGGREGATE(14,6,B5:B9/(COUNTIF(A2:C2,A5:A9)>0),1)))),A5:A9),"No Matching ID")
By the way, you don't specify which should be preferred if two or more IDs share the maximum date and also appear within Table1?
Regards

A: EDIT:
This should get you the answer, if entered as an Array Formula (Ctrl+Shift+Enter):
=INDEX($A$4:$A$8,MATCH(MAX(IF($A$4:$A$8=A2,$B$4:$B$8,0),IF($A$4:$A$8=B2,$B$4:$B$8,0),IF($A$4:$A$8=C2,$B$4:$B$8,0)),$B$4:$B$8,0))

It's based on repeating the following formula, which finds the max date for the entry in cell A2 (if entered as an array formula):
=MAX(IF($A$4:$A$8=A2,$B$4:$B$8,0))

Enter that with Ctrl+Shift+Enter (array formula).
Combine that a few times, and then do an INDEX()/MATCH() lookup, and you can get the ID.  You'll need to figure out how to handle equal max dates.

A: I always use what I call a MAXAIF function. You can add this into a VBA module and use it in your spreadsheet.
Function MAXAIF(ByVal id As Range, ByVal Criteria_Range As Range, ByVal Lookup_Range As Range)
    Dim max
    Dim ct As Integer
    For ct = 1 To Criteria_Range.Cells.Count
        If Criteria_Range.Cells(ct, 1).Value = id.Value Then
            If max = Empty Then
                max = Lookup_Range.Cells(ct, 1).Value
            Else
                If max < Lookup_Range.Cells(ct, 1).Value Then
                    max = Lookup_Range.Cells(ct, 1).Value
                End If
            End If
        End If
    Next
    MAXAIF = max
End Function

UPDATE
Per feedback, apparently the need here is to return the id with the greatest date attached along with the date. The following is a function that will accommodate that. If the last parameter is set to true, it returns the id, whereas if set to false it returns the greatest date.
Function IdWithGreatestDate(ByVal id As Range, ByVal Criteria_Range As Range, ByVal Lookup_Range As Range, return_id As Boolean)
    Dim max
    Dim max_index
    Dim ct As Integer
    For Each cell In id
        For ct = 1 To Criteria_Range.Cells.Count
            If max = Empty Then
                max_index = ct
                max = Lookup_Range.Cells(ct, 1).Value
            Else
                If max < Lookup_Range.Cells(ct, 1).Value Then
                    max_index = ct
                    max = Lookup_Range.Cells(ct, 1).Value
                End If
            End If
        Next
    Next
    If return_id Then
        IdWithGreatestDate = Criteria_Range(max_index, 1).Value
    Else
        IdWithGreatestDate = Lookup_Range(1, max_index).Value
    End If
End Function

A: You can use MAX() and IF() function to find the max_date for each ID in columns ID1, ID2, ID3, ID3 then use MAX() again to find max_date among the 4 values
SELECT max_date for each ID (enter using CTRL+SHIFT+ENTER):
{MAX(IF(A3:A100=H3,F3:F100))}

SELECT max_date among the 4 max_date:
{=MAX(MAX(IF(A3:A100=H3,F3:F100)),MAX(IF(A3:A100=I3,F3:F100)),MAX(IF(A3:A100=J3,F3:F100)),MAX(IF(A3:A100=K3,F3:F100)))}

Then use MATCH() | INDEX() function to find the ID that has the max_date
=INDEX(A:A,MATCH(L3,F:F,0))


text:
Q: SPFX 1.7.1 webpart is not working on IE11 I have created a new SharePoint web part (version 1.7.1). I'm using the react template. The web part is very basic, yet doesn't run on IE 11.
The error returned is
Object doesn't support property or method 'find'
I don't use find in any of my .ts files, so I found the .find method is being called by the .js files that were transpiled from my .ts files.
Can anybody confirm this to be a bug in SPFX v1.7.1?
If so, is there a solution.
I know this could be fixed by introducing a shim, but I don't know how to configure this for SPFX and can't find any documentation that explains how to do this.
Any help is welcome.

A: If I recall correctly, this is because IE 11 doesn't support Element.closest, which is used by the React engine.
I have personally used element-closest to polyfill it, although I'm sure other options exist.
// beginning of WebPart code file
import 'element-closest/browser';

import * as React from 'react';
import * as ReactDom from 'react-dom';
// rest of the code, etc.

A: With refer to this article, we can see that the Array.prototype.find() method not support IE browser. But, This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}

Besides, as far as I know, when we use React, by default, the generated react project supports all modern browsers. Support for Internet Explorer 9, 10, and 11 requires polyfills. You could check it and import related packages.

A: You can adjust your tsconfig.json file: set "target" to "es5" under "compilerOptions".
Typescript will create polyfills for you.

A: I had the same issue. Use this import in your webpart.ts file.
import 'core-js/modules/es6.array.find';


text:
Q: Launch SIRI from application I see apps on the store (application connected with a BLE button) that can launch SIRI when the BLE button is pressed.(By exemple flic button)
Any idea how this feature could be implemented ?
I did not see any API available to launch SIRI from an app
Did this application uses private APIs ?
This same application can:
- lock the screen when BLE button is pressed
- take screenshots when BLE button is pressed

A: It's called HID over GATT and is a BLE profile.


text:
Q: Low-level C I/O: When read from one file and write to another I'm hitting an infinite loop I am working on an assignment that only allows use of low-level I/O (read(), write(), lseek()) as well as perror().
I have been able to open the nessisary in and out files with correct permissions, but when I output I get an infinite loop of the in file contents to out. See snippet below...
void *buf = malloc(1024);
while((n = read(in, buf, 1024)) > 0){
    if(lseek(in, n, SEEK_CUR) == -1){
        perror("in file not seekable");
        exit(-1);
    }
    while((m = write(out, buf, n)) > 0){
        if(lseek(out, m, SEEK_CUR) == -1){
            perror("out file not seekable");
            exit(-1);
        }
    }
    if(m == -1){ perror("error writing out"); exit(-1); }
}
if(n == -1){ perror("error reading in"); exit(-1); }

I have removed some error trapping from my code and you can assume the variables are initialized and includes statements are there.

A: Problem is the inner loop:
while((m = write(out, buf, n)) > 0){

should really be
if((m = write(out, buf, n)) > 0){

You only want buf to be written once, not infinitely many times.  What you also need to handle is short writes, that is, when write returns with m < n && m > 0.
Also, the lseek() calls are wrong, but they don't lead to the loop. read() and write() already advance the current file offset.  You do not need to manually advance it, unless you want to skip bytes in the input or output file (note that in the output file case, on UNIX, skipping bytes may lead to so-called "holes" in files, regions which are zero but don't occupy disk space).

A: Why are you seeking on the input file after your read? Since you will, at most, read 1024 bytes (meaning n will be somewhere between 0 and 1024), you will be continuously seeking to somewhere beyond where you've left the input file pointer so that you'll lose data in the transfer (including probably beyond the end of the file when you get near the end).
This may be one cause why you have an infinite loop but the far more insidious one is the use of while for the write. Since this will return values greater than zero on success, you will continuously write the first chunk to the file over and over. At least until you run out of disk space or other resources.
You also don't need the seek on the write either. The read and write calls do what they have to do and advance the file pointer correctly for the next read or write - it's not something you have to do manually.
You can probably simplify the whole thing to:
while ((n = read (in, buf, 1024)) > 0) {
    if ((m = write (out, buf, n)) != n) {
        perror ("error writing out");
        exit (-1);
    }
}

which has the advantages of:

*

*getting rid of the seek calls;

*removing the 'infinite' loop;

*checking that you've written all the bytes requested.


text:
Q: how to send http POST with query params I want to send http POST via my java client.
Is there a way to send query params and a content in the body for a POST request?
here is my java http client:
@Override
public ResponseOrError sendPost(String url, String bodyContent) {
    url = urlUtils.getHttpUrl(url);

    ResponseOrError responseOrError = new ResponseOrError();
    final RetryListenerWithBooleanFlags listener = new RetryListenerWithBooleanFlags();
    try {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        Callable<ResponseOrError> callable = getCallable(httpPost);
        retryer = getRetryer(listener);
        responseOrError = retryer.call(callable);
        fillResponseOrError(responseOrError, listener);

    } catch (Exception e) {
        responseOrError.error = new Error();
        String errorMsg = getStatusCode(responseOrError, listener);
        responseOrError.error.errorMsg = e.getMessage() + errorMsg;
    }
    return responseOrError;
}

A: Be sure to check Java API.
This should work.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key", "value"));
post.setEntity(new UrlEncodedFormEntity(params));

A: Is there a reason to use HttpPost from org.apache.http.client?
Unfortunately I'm unfamiliar with that library / class, but if there is no specific reason to use this library an option would be to simply use HttpURLConnection
Example (not having a compiler at hand so it might have some mistakes in it):
URL url = new URL("http://..");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setRequestMethod("POST"); //it's a post request
httpCon.setDoInput(true); //read response
httpCon.setDoOutput(true); //send Post body
... = httpCon.getOutputStream(); //Here you go, do whatever you want with this stream

A: Just append the parameters to the URL, as easy as:
url = url + "?param=value&otherparam=othervalue";

Ensure you use:

*

*?: To start the query string

*=: To associate the parameter with its value

*&: To separate the parameter/value pairs

You will need to encode the parameter values if they include blank spaces, for example.
To do it, use the URLEncoder class:
String encoded = URLEncoder.encode(value, StandardCharsets.UTF_8);

With this, some value with blank spaces will become some%20value%20with%20blank%20spaces.


text:
Q: Is it correct to set up a variable inside a php try-catch? I know I can. I know it works. But, is it correct? I'm thinking that is like putting a div inside a span: you can but someone will hunt you, find you and destroy you.
// $value comes from $_POST no validation
try {
    $value = new DateTime($value);
} catch(Exception $e) {
    $value = new DateTime();
}

A: That's perfectly fine if doing so may result in an exception being thrown. Otherwise you are adding unnecessary overhead to whatever action is being performed.
In your case an exception will be thrown if $value is not a valid value. So your try/catch is necessary to catch the exception and react to it accordingly, which you do.


text:
Q: Ocaml function call, calling itself recursively Here is what I am trying to do, given z with the signature that 'a -> 'a,
let z(a)=
  if(a=0) then
    0
  else
    a * a;;

if I were to call repeat as, repeat(2, f, 2);;
then the answer should be too, since f should be called twice with 2, as in f(f(2) the answer should be 16.

A: I think the problem might be that when you are defining a recursive function you need to tell OCaml using the rec keyword.
Try changing the code to:
let f a =
  if a = 0 then
    0
  else
    a * a

let rec repeathelper n f answer accum =
  if n = accum then
    answer
  else
    repeathelper n f (f answer) (accum+1)

let repeat n f x = repeathelper n (f 0) 0 0


text:
Q: Making SVG Responsive in React I am working on a responsive utility component, to make a few D3 components responsive in react. However I deep SVG knowledge escapes me. I have based my responsive utility on this issue on github. However it isn't quite working, All it does is render the a chart, but not at the width or height passed in but rather at a really small width and height. It also doesn't resize.
import React from 'react';

class Responsive extends React.Component{
    constructor () {
      super();
      this.state = {
        size: {
          w: 0,
          h: 0
        }
      }
    }

    componentDidMount () {
        window.addEventListener('resize', this.fitToParentSize.bind(this));
        this.fitToParentSize();
    }

    componentWillReceiveProps () {
        this.fitToParentSize();
    }

    componentWillUnmount() {
      window.removeEventListener('resize', this.fitToParentSize.bind(this));
    }

    fitToParentSize () {
        let elem = this.findDOMNode(this);
        let w = elem.parentNode.offsetWidth;
        let h = elem.parentNode.offsetHeight;
        let currentSize = this.state.size;

        if (w !== currentSize.w || h !== currentSize.h) {
            this.setState({
                size: {
                    w: w,
                    h: h
                }
            });
        }
    }

    render () {

        let {width, height} = this.props;

        width = this.state.size.w || 100;
        height = this.state.size.h || 100;

        var Charts = React.cloneElement(this.props.children, { width, height});

        return Charts;
    }
};

export default Responsive;

Responsive width={400} height={500}>
  <XYAxis data={data3Check}
          xDataKey='x'
          yDataKey='y'
          grid={true}
          gridLines={'solid'}>
    <AreaChart dataKey='a'/>
    <LineChart dataKey='l' pointColor="#ffc952" pointBorderColor='#34314c'/>
  </XYAxis>
</Responsive>

A: disclaimer: I'm the author of vx a low-level react+d3 library full of visualization components.
You could use @vx/responsive or create your own higher-order component based on withParentSize() or withWindowSize() depending on what sizing you want to respond to (I've found most situations require withParentSize()).
The gist is you create a higher-order component that takes in your chart component and it attaches/removes event listeners for when the window resizes with a debounce time of 300ms by default (you can override this with a prop) and stores the dimensions in its state. The new parent dimensions will get passed in as props to your chart as parentWidth, parentHeight or screenWidth, screenHeight and you can set your svg's width and height attributes from there or calculate your chart dimensions based on those values.
Usage:
// MyChart.js
import { withParentSize } from '@vx/responsive';

function MyChart({ parentWidth, parentHeight }) {
  return (
    <svg width={parentWidth} height={parentHeight}>
      {/* stuff */}
    </svg>
  );
}

export default withParentSize(MyChart);


text:
Q: Get value from XML through linq So I was not at all willing to post it as already there are infinite documents about it. Its been 2years that I touched LINQ and now its taking a dig at me. After 3 hour of continuous try and failures, I decided to do what I was not willing to. Post it to SO.
I have this XML
<TopMost xmlns="http://abc.com/">
    <Mine>MyName</Mine>
    <Hello>
        <File>SIMPLE</File>
        <Book>20</Book>
        <Copy>0</Copy>
    </Hello>
</TopMost>

I just want to get values of "File", "Book", "Copy". and want to compare it with something in Unit Test.
I reached upto this:
string result = string.Empty;
const string path = @"C:\Library.xml";
XDocument xdoc = XDocument.Load(path);

var lv1s = from paper in xdoc.Descendants("Hello")
    select new
        {
            fileP = paper.Element("File").Value,
            bookP = paper.Element("Book").Value,
            copyP = paper.Element("Copy").Value,
        };
result += lv1s.fileP + lv1s.bookP + lv1s.copyP;  // Error
MessageBox.Show(result);

Error: Sequence contains no elements
I know there has to be a easy way around and I am far from it. I have many such code snippets that I have tried and failed.
EDIT
var lv1s = from paper in xdoc.Descendants(ns + "Hello")
    select new
        {
            fileP = paper.Element(ns + "File").Value,
            bookP = paper.Element(ns + "Book").Value,
            copyP = paper.Element(ns + "Copy").Value,
        };

I am getting Compilation error.
Error: The Name ns doex not exist in current context.

A: You need to specify the namespcae:
XNamespace ns = "http://abc.com/";  // or: doc.Root.GetDefaultNamespace()

var lv1s = from paper in xdoc.Descendants( ns + "Hello")
   select new
        {
            fileP = paper.Element(ns +"File").Value,
            bookP = paper.Element(ns +"Book").Value,
            copyP = paper.Element(ns +"Copy").Value,
        };

Don't be tempted to use string ns or var ns .


text:
Q: Javascript get date 30 days ago I am trying to populate two date input fields, one with today's date and one with the date 30 days ago(last month).
I am getting an error in my console: priordate.getDate is not a function
Here is my code, not sure what I am doing wrong:
//today's date

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;

//30 days ago

var beforedate = new Date();
var priordate = new Date().setDate(beforedate.getDate()-30);
var dd2 = priordate.getDate();
var mm2 = priordate.getMonth()+1;//January is 0, so always add + 1
var yyyy2 = priordate.getFullYear();
if(dd2<10){dd2='0'+dd2};
if(mm2<10){mm2='0'+mm2};
var datefrommonthago = yyyy2+'-'+mm2+'-'+dd2;

// Set inputs with the date variables:

$("#fromdate").val(datefrommonthago);
$("#todate").val(today);

A: You'll instead want to use:
var priordate = new Date(new Date().setDate(beforedate.getDate()-30));

if you want it on one line. By using:
new Date().setDate(beforedate.getDate()-30);

you're returning the time since epoch (a number, not a date) and assigning it to priordate, but it's not a Date anymore and so does not have the getDate function.

A: This is because setDate() returns a number, not a Date Object.
In any I case I'd strongly recommend using momentjs or date-fns as the internal Date object in JavaScript is broken in all kind of ways. See this talk: https://www.youtube.com/watch?v=aVuor-VAWTI

A: Change this:
var priordate = new Date().setDate(beforedate.getDate()-30);

to this:
var priordate = new Date();
priordate.setDate(beforedate.getDate()-30);


text:
Q: yarn workspace deploy into a docker image I am using yarn workspaces and I have this packages in my package.json:
"workspaces": ["packages/*"]
I am trying to create a docker image to deploy and I have the following Dockerfile:
# production dockerfile
FROM node:9.2

# add code
COPY ./packages/website/dist /cutting

WORKDIR /cutting

COPY package.json /cutting/
RUN yarn install --pure-lockfile && yarn cache clean --production

CMD npm run serve

But I get the following error:
error An unexpected error occurred:
"https://registry.yarnpkg.com/@cutting%2futil: Not found"
@cutting/util is the name of one of my workspace packages.
So the problem is that there is no source code in the docker image so it is trying to install it from yarnpkg.
what is the best way to handle workspaces when deploying to a docker image?
Say my structure is:
root
 |_node_modules
        -----|_ package_1
        -----|_package_2
        -----|_package_3
        -----|_deploy_pkg

I want to deploy deploy_pkg but I have no idea how to create a bundle I can just copy into the docker image


text:
Q: How do I make my ubuntu texlive environment available to the wine emulator? I wanted to give WinEdt a try, using the wine windows emulator on Ubuntu 14.04.  I have texlive 2015 installed and working with no issues.
The program installed fine, and seems to work well using the wine emulator, but fails to compile.  It appears that the problem is not being able to find the path to my texlive installation.  There may also be some other impediments that I am not yet aware. I assume one option would be to install another texlive into the wine environment.
However, I do not really want to install texlive into the wine environment, as it is rather large, and seems wasteful of system resources. Perhaps there is a solution using some kind of hard or soft links?
Does anybody know how to give wine access to my already installed texlive 2015 installation? Is it possible at all? Are there further pitfalls to watch out for?
The document I attempted to compile:
\documentclass{article}
\begin{document}
Hello World
\end{document}

The error:
Error Launching Console Application PDFTeXify ...
Command Line: pdflatex.exe --interaction=errorstopmode -- ...
File not found.

A: I am afraid the only way to properly (if possible) run TL inside Wine is to install the Windows binaries alongside with your Linux ones.
In summary, Linux binaries are not seen by Wine as executable files, nor Wine has the ability to run them through the host system, as it isolates the execution. A possible workaround is to have Cygwin installed inside Wine, but this would be quite a heavy workflow.
As I mentioned in my comments, Wine seems to get environment variables from your underlying Linux session, except some of them are omitted, specially PATH (which makes sense, for two reasons: (a) Wine doesn't bother about non-Windows executables, and (b) it would break the isolation/sandbox feature).
Let us see it in practice:
[paulo@nineveh ~] $ wine cmd
Microsoft Windows 5.2.3790 (1.9.12)

Z:\home\paulo>set
_=/usr/bin/wine
ALLUSERSPROFILE=C:\users\Public
APPDATA=C:\users\paulo\Application Data
BASH_FUNC_module()=() {  eval `/usr/bin/modulecmd bash $*`
}
BASH_FUNC_scl()=() {  local CMD=$1;
 if [ "$CMD" = "load" -o "$CMD" = "unload" ]; then
 eval "module $@";
 else
 /usr/bin/scl "$@";
 fi
}
CLIENTNAME=Console
COLORTERM=truecolor
CommonProgramFiles=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=nineveh
ComSpec=C:\windows\system32\cmd.exe
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
DESKTOP_SESSION=gnome
DISPLAY=:0
GDM_LANG=pt_BR.UTF-8
GDMSESSION=gnome
GJS_DEBUG_OUTPUT=stderr
GJS_DEBUG_TOPICS=JS ERROR;JS LOG
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
HISTCONTROL=ignoredups
HISTSIZE=1000
HOMEDRIVE=C:
HOMEPATH=\users\paulo
HOSTNAME=nineveh
KDEDIRS=/usr
LANG=pt_BR.UTF-8
LESSOPEN=||/usr/bin/lesspipe.sh %s
LOADEDMODULES=
LOCALAPPDATA=C:\users\paulo\Local Settings\Application Data
LOGNAME=paulo
LOGONSERVER=\\nineveh
LS_COLORS=rs=0:di=38;5;33:ln=38;5;51:mh=00:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=01;05;37;41:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;40:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.m4a=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.oga=38;5;45:*.opus=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:
MAIL=/var/spool/mail/paulo
MODULEPATH=/etc/scl/modulefiles:/etc/scl/modulefiles:/usr/share/Modules/modulefiles:/etc/modulefiles:/usr/share/modulefiles
MODULESHOME=/usr/share/Modules
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
PATH=C:\windows\system32;C:\windows;C:\windows\system32\wbem
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_ARCHITEW6432=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 6 Model 23 Stepping 10, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=170a
ProgramFiles=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
SESSION_MANAGER=local/unix:@/tmp/.ICE-unix/1279,unix/unix:/tmp/.ICE-unix/1279
SESSIONNAME=Console
SHELL=/bin/bash
SHLVL=2
SSH_AUTH_SOCK=/run/user/1000/keyring/ssh
SystemDrive=c:
SYSTEMROOT=C:\windows
TEMP=C:\users\paulo\Temp
TERM=xterm-256color
TMP=C:\users\paulo\Temp
USER=paulo
USERDOMAIN=nineveh
USERNAME=paulo
USERPROFILE=C:\users\paulo
VTE_VERSION=4402
windir=C:\windows
WINDOWID=27262982
WINDOWPATH=2
WINELOADERNOEXEC=1
winsysdir=C:\windows\system32
XAUTHORITY=/run/user/1000/gdm/Xauthority
XDG_CURRENT_DESKTOP=GNOME
XDG_MENU_PREFIX=gnome-
XDG_RUNTIME_DIR=/run/user/1000
XDG_SEAT=seat0
XDG_SESSION_DESKTOP=gnome
XDG_SESSION_ID=1
XDG_SESSION_TYPE=x11
XDG_VTNR=2
XMODIFIERS=@im=ibus

Z:\home\paulo>

Note that PATH only refers to Wine's system directories. If I try to export a random variable, say ZZZ:
[paulo@nineveh ~] $ ZZZ=quack wine cmd
Microsoft Windows 5.2.3790 (1.9.12)

Z:\home\paulo>set
_=/usr/bin/wine
ALLUSERSPROFILE=C:\users\Public
APPDATA=C:\users\paulo\Application Data
...
XDG_VTNR=2
XMODIFIERS=@im=ibus
ZZZ=quack

Z:\home\paulo>

Note that ZZZ was exported to Wine. Now let us check binaries and whatnot:
// quack.c
#include <stdio.h>

int main(void) {
  printf("quack!\n");
  return 0;
}

I will generate two binaries, quack1 (for Linux) and quack2.exe (for Windows):
[paulo@nineveh ~] $ gcc -Wall quack.c -o quack1
[paulo@nineveh ~] $ i686-w64-mingw32-gcc -Wall quack.c -o quack2.exe
[paulo@nineveh ~] $ ls -lha quack*
-rwxrwxr-x. 1 paulo paulo 8,5K Jul 11 08:57 quack1
-rwxrwxr-x. 1 paulo paulo  78K Jul 11 08:57 quack2.exe
-rw-rw-r--. 1 paulo paulo   84 Jul 11 08:56 quack.c

Now, let us inspect the generated executables:
[paulo@nineveh ~] $ file quack1
quack1: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=98adf48a7a9d9c2f0bdf5c96e62270e76e5c45a3, not stripped
[paulo@nineveh ~] $ file quack2.exe
quack2.exe: PE32 executable (console) Intel 80386, for MS Windows

Running both files:
[paulo@nineveh ~] $ ./quack1
quack!
[paulo@nineveh ~] $ ./quack2.exe
fixme:winediag:start_process Wine Staging 1.9.12 is a testing version containing experimental patches.
fixme:winediag:start_process Please mention your exact version when filing bug reports on winehq.org.
quack!

Note that the second file (quack2.exe) was executed by Wine under the hood, as it is not a native binary. Now, let us go to Wine:
[paulo@nineveh ~] $ wine cmd
Microsoft Windows 5.2.3790 (1.9.12)

Z:\home\paulo>dir quack*
O volume na unidade Z não tem rótulo.
Número de Série do Volume é 0000-0000

Directory of Z:\home\paulo

 11/7/2016     08:56            84  quack.c
 11/7/2016     08:57         8,624  quack1
 11/7/2016     08:57        79,150  quack2.exe
       3 files                   87,858 bytes
       0 directories    437,039,472,640 bytes free

Z:\home\paulo>

Now, let us run both files:
Z:\home\paulo>quack1
Não é possível reconhecer 'quack1' como um comando interno, externo ou arquivo de lotes.

Z:\home\paulo>quack2
quack!

(Sorry for the messages in Portuguese)
Observe that the Linux executable was not recognized, while the Windows one was correctly executed. Now, let us inspect the PATHEXT variable:
Z:\home\paulo>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

These are the file extensions recognized by Wine/Windows as executable files.
Out of curiosity, I decided to copy quack1 to quack3.exe and see what happens inside Wine. First things first:
[paulo@nineveh ~] $ file quack3.exe
quack3.exe: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=98adf48a7a9d9c2f0bdf5c96e62270e76e5c45a3, not stripped

Then:
[paulo@nineveh ~] $ wine cmd
Microsoft Windows 5.2.3790 (1.9.12)

Z:\home\paulo>quack3
quack!

The file was executed! Since Wine is an emulation layer, it looks like it also understands Linux binaries if faked as Windows ones, but this is of course a dirty maneuver and should never be used.
I have the following suggestions: (a) Try to install TL inside Wine (not sure if it works), (b) set up a virtual machine with a normal Windows install (Windows XP, perhaps) and install TL inside it, or (c) install Cygwin inside Wine and see what happens next. :)
Also, note that the executable example used above is very simple and does not use a lot of shared libraries, so what worked above might fail miserably with a real world executable. My tests were very naïve, as ducks are. :)
Hope this answer gives you some pointers on how to fix this issue. Personally, I wouldn't use Wine for this, as it's just an emulation layer. I'd rather prefer a robust solution, using a proper Windows install inside a VM. :)
Addendum: David mentioned in the chatroom that formats and configurations are cross-platform in TeX Live, so in theory you would only need the Windows binaries and share everything else, but it is probably not worth.


text:
Q: Converting Strings to Template Literals in ES6 Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);

But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);

This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);

This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!

A: Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:

"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));


text:
Q: ReferenceError: Vue is not defined while using shallowMount I am working on vue project and while doing unit testing using jest, I am getting following error for shallowMount:
ReferenceError: Vue is not defined

    > 1 | import { shallowMount } from '@vue/test-utils';
        | ^
      2 | import About from '@/views/About.vue';

Following are my devDependencies from package.json:
"devDependencies": {
    "@babel/core": "^7.18.5",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.4",
    "@vue/cli-plugin-e2e-cypress": "~5.0.4",
    "@vue/cli-plugin-eslint": "~5.0.4",
    "@vue/cli-plugin-pwa": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.4",
    "@vue/cli-plugin-unit-jest": "^5.0.6",
    "@vue/cli-plugin-vuex": "~5.0.4",
    "@vue/cli-service": "^5.0.4",
    "@vue/compiler-dom": "^3.2.37",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-airbnb": "^6.0.0",
    "@vue/test-utils": "^2.0.0",
    "@vue/vue3-jest": "^28.0.0",
    "babel-jest": "^28.1.1",
    "cypress": "^8.3.0",
    "eslint": "^8.17.0",
    "eslint-plugin-import": "^2.25.3",
    "eslint-plugin-vue": "^9.1.0",
    "eslint-plugin-vuejs-accessibility": "^1.1.0",
    "jest": "^28.1.1",
    "jest-environment-jsdom": "^28.1.1",
    "typescript": "~3.9.3",
    "vue-cli-plugin-i18n": "~2.3.1",
    "vue-cli-plugin-tailwind": "~3.0.0",
    "vue3-jest": "^27.0.0-alpha.1",
    "webpack": "^5.73.0"
  },

Following is my unit test code:
import { shallowMount } from '@vue/test-utils';
import About from '@/views/About.vue';

describe('About.vue', () => {
  test('renders inner text', () => {
    // eslint-disable-next-line no-bitwise
    const wrapper = shallowMount(About);

    expect(wrapper.text()).toContain('about');
  });
});

Following is my Component code:
<template>

This is an about page

</template>

Just wonder if I am doing something wrong with unit test or the component code or does the jest and other supporting libraries require version upgrade/downgrade?
based on comment 1:
Following are the dependencies:
"dependencies": {
    "@tailwindcss/postcss7-compat": "^2.0.2",
    "@vee-validate/rules": "^4.1.17",
    "autoprefixer": "^9",
    "core-js": "^3.6.5",
    "firebase": "^8.2.7",
    "howler": "^2.2.1",
    "lodash": "^4.17.21",
    "nprogress": "^0.2.0",
    "postcss": "^7",
    "register-service-worker": "^1.7.1",
    "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.0.2",
    "vee-validate": "^4.1.18",
    "vue": "^3.0.0",
    "vue-i18n": "^9.0.0-rc.2",
    "vue-router": "^4.0.0-0",
    "vuex": "^4.0.0-0"
  },


text:
Q: Django auth and Postman requests How do I authenticate a Django user, when making requests with Postman? I am not using Django Rest framework, just the standard dango.cont.auth system. In Postman you have the following options for authentication: Basic Auth, OAuth, and Custom. In custom I can add some headers.
How do I do this?

A: please try following image.
key   : Authorization
value : OAuth TOKEN


text:
Q: want to create cron job from the command line i have built a CMS website that replies upon the mysql records of a 3rd party. i intend to download the 3rd party records via CSV. i then want to use a Cron job via my command line to update my mysql records
i know how to manually upload to mysql via CSV i.e:
LOAD DATA INFILE 'c:/tmp/discounts_2.csv'INTO TABLE discountsFIELDS TERMINATED BY ',' ENCLOSED BY '"'LINES TERMINATED BY '\n'IGNORE 1 ROWS(title,@expired_date,amount)SET expired_date = STR_TO_DATE(@expired_date, '%m/%d/%Y');

however, i am not sure how to go about creating a cron job that will automtically link to the command line and then perform this function.
i guess that what i want is a pointer on how i can go about doing this.
UPDATE
@fancyPants asked the question "what do i want the cronJob to do?"
the answer is this. i want the cronJob job to access the CSV file (that i have previously downloaded)
and then upload all those values from the CSV file to the mysql database
i know the  command for doing the CSV conversion to mysql;

LOAD DATA INFILE 'c:/tmp/discounts_2.csv'INTO TABLE discountsFIELDS
  TERMINATED BY ',' ENCLOSED BY '"'LINES TERMINATED BY '\n'IGNORE 1
  ROWS(title,@expired_date,amount)SET expired_date =
  STR_TO_DATE(@expired_date, '%m/%d/%Y');

i am however stuck at the point of how to do a cron job to my command line and then how to execute the above command once the cron arrives at the command line

A: Create a MySQL event rather than a cronjob.
Enable the event scheduler with
SET GLOBAL event_scheduler = ON;

and create an event like this:
DELIMITER $
CREATE EVENT
ON SCHEDULE EVERY 1 DAY
STARTS '2015-10-11 00:00:00'
DO
BEGIN
TRUNCATE TABLE discounts;
LOAD DATA INFILE 'c:/tmp/discounts_2.csv'INTO TABLE discounts FIELDS TERMINATED BY ',' ENCLOSED BY '"'LINES TERMINATED BY '\n'IGNORE 1 ROWS(title,@expired_date,amount)SET expired_date = STR_TO_DATE(@expired_date, '%m/%d/%Y');
END $
DELIMITER ;

and that's it.
Read more about the syntax here and here is more general information about it.


text:
Q: Finding out the last digit of number $3a/4$ knowing the last two digits of $a$ Natural number $a$ ends with digits $16$. If $a$ is not divisible by $8$, what is the last digit of $3a/4$?
Solution:

 $$7$$

How do we arrive at that solution?

A: Note that $a = 100k + 16$ where $k$ is a positive integer.
Recall the divisibility criteria for $ 8$ : a number is divisible by $8$ if and only if its last three digits are.
Let $b$ be the last digit of $k$. Then, the last three digits of $a$ are  $\overline{b16}$.
When is $\overline{b16}$ divisible by $8$? It is not difficult to see that this is a multiple of $8$ if and only if $b$ is a multiple of $2$, since $\overline{b16}$ is a multiple of $8$, if and only if $\overline{b00}$ is a multiple of $8$, if and only if $b $ is even.
In  conclusion, $a = 100k + 16$ where the last digit of $k$ is odd. In other words, where $k$ is odd, since $a$ is not a multiple of $8$.
Now, $\frac a4 = 25k + 4$, and $\frac {3a}4 = 75k + 12$.
Note that $k $ is odd, so $75k$ is an odd multiple of $5$. Odd multiples of $5$ always end with $5$, so $75k + 12$ ends with $5+2 = 7$.


text:
Q: Grabbing columns with special characters and upper case letters I have a data frame and I'm trying to loop through the data frame to identify those columns which contain a special character or which are all capital letters.
I have tried a few things but nothing where I'm apple to catch the column names within the loop.
data = data.frame(one=c(1,3,5,1,3,5,1,3,5,1,3,5), two=c(1,3,5,1,3,5,1,3,5,1,3,5),
                thr=c("A","B","D","E","F","G","H","I","J","H","I","J"),
                fou=c("A","B","D","A","B","D","A","B","D","A","B","D"),
                fiv=c(1,3,5,1,3,5,1,3,5,1,3,5),
                six=c("A","B","D","E","F","G","H","I","J","H","I","J"),
                sev=c("A","B","D","A","B","D","A","B","D","A","B","D"),
                eig=c("A","B","D","A","B","D","A","B","D","A","B","D"),
                nin=c(1.24,3.52,5.33,1.44,3.11,5.33,1.55,3.66,5.33,1.32,3.54,5.77),
                ten=c(1:12),
                ele=rep(1,12),
                twe=c(1,2,1,2,1,2,1,2,1,2,1,2),
                thir=c("THiS","THAT34","T(&*(", "!!!","@$#","$Q%J","who","THIS","this","this","this","this"),
                stringsAsFactors = FALSE)
data

colls <- c()

    spec=c("$","%","&")
    for( col in names(data) ) {
      if( length(strings[stringr::str_detect(data[,col], spec)]) >= 1 ){
          print("HORRAY")
colls <- c(collls, col)
      }
      else print ("NOOOOOOOOOO")
    }

    for( col in names(data) ) {
      if( any(data[,col]) %in% spec ){
        print("HORRAY")
colls <- c(collls, col)
      }
      else print ("NOOOOOOOOOO")
    }

Can anyone shed light on a good way to tackle this problem.
EDIT:
The end goal is to have a vector with a name of column names which meet that criteria. Sorry for my poor SO question, but hopefully this will help with what I'm trying to do

A: I would use grep() to search for the pattern you are interested in. See here.
[:upper:] Matches any upper case letters.
Combining it with anchors (^,$) and match one or more times (+) gives ^[[:upper:]]+$ and should only match entries completely in capitals.
The following would match the special characters in your toy data set (but is not guaranteed to match all special characters in your real data set i.e form feeds, carriage returns)
[:punct:] #Matches punctuation - ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~.
Note that rather than use [:punct:] you could define your special characters manually.
We can try the resultant code on the first row of your data set:
#Using grepl() rather than grep() so that we return a list of logical values.
grepl(x= data[1,], pattern = "^[[:upper:]]+$|[[:punct:]]")
[1] FALSE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE

This gives us our expected response except for column nine which has the value 1.24.  Here the decimal point is being recognised as punctuation and is being flagged as a match.
We can add a "negative lookahead assertion" - (?!\\.)  -  to remove any periods from consideration, before they are even tested for being punctuation characters. Note we use \ to escape the period.
grepl(x= data[1,], perl = TRUE, pattern = "(?!\\.)(^[[:upper:]]+$|[[:punct:]])")
[1] FALSE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE

This returns a better response - it now no longer matches decimal places. NOTE: This might not be what you want as this pattern also won't match any fullstops in character fields.  You would need to refine the pattern further.
Rather than use a 'for loop' to reiterate this code across every row in your dataframe I would use vectorization instead which is 'more R like'.
To do this we must convert our script into a function which we will call with apply()
myFunction <- function(x){
      matches <- grepl(x= x, perl = TRUE, pattern = "(?!\\.)(^[[:upper:]]+$|[[:punct:]])")
  #Given a set of logical vectors 'matches', is at least one of the values true? using any()
  return(any(matches))
}

apply(X = data, 1, myFunction)

The 1 above instructs apply() to reiterate across rows rather than columns.
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

In your example data set all rows have an entry containing a special character or a string of all capital letters.  This is unsurprising as many columns in your example data set are a list of single capital letters.
If you are just interested in which values in column thirteen fit the stated criteria you can use:
matches <- grepl(x= data$thir, perl = TRUE, pattern = "(?!\\.)(^[[:upper:]]+$|[[:punct:]])")
matches
 [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE

To subset your dataframe on matching rows:
data[matches,]
  one two thr fou fiv six sev eig  nin ten ele twe  thir
3   5   5   D   D   5   D   D   D 5.33   3   1   1 T(&*(
4   1   1   E   A   1   E   A   A 1.44   4   1   2   !!!
5   3   3   F   B   3   F   B   B 3.11   5   1   1   @$#
6   5   5   G   D   5   G   D   D 5.33   6   1   2  $Q%J
8   3   3   I   B   3   I   B   B 3.66   8   1   2  THIS

To subset your dataframe on non-matching rows:
data[!matches,]
   one two thr fou fiv six sev eig  nin ten ele twe   thir
1    1   1   A   A   1   A   A   A 1.24   1   1   1   THiS
2    3   3   B   B   3   B   B   B 3.52   2   1   2 THAT34
7    1   1   H   A   1   H   A   A 1.55   7   1   1    who
9    5   5   J   D   5   J   D   D 5.33   9   1   1   this
10   1   1   H   A   1   H   A   A 1.32  10   1   2   this
11   3   3   I   B   3   I   B   B 3.54  11   1   1   this
12   5   5   J   D   5   J   D   D 5.77  12   1   2   this

Note that the regular expression used doesn't match THAT34 as it isn't composed wholly of capitalised letters, having the number 34 at the end.
EDIT:
To get a list of column names identifying columns that fulfill the criteria in your edit use myFunction described above with:
colnames(data)[apply(X = data, 2, myFunction)]
"thr"  "fou"  "six"  "sev"  "eig"  "thir"

The number in apply() changes from 1 to 2 to reiterate across columns rather than rows.  We pass the output from apply(), a list of logical matches (TRUE or FALSE), to colnames(data) - this returns the matching column names via subsetting.

A: I would collapse the data into strings (one string per row)
strings = apply(data, 1, paste, collapse = "")
contains_only_caps = strings == toupper(strings)
strings[contains_only_caps]
# [1] "33BB3BBB3.52 212THAT34" "55DD5DDD5.33 311T(&*("  "11EA1EAA1.44 412!!!"   "33FB3FBB3.11 511@$#"
# [5] "55GD5GDD5.33 612$Q%J"   "33IB3IBB3.66 812THIS"

# escaping special characters
spec=c("\\$","%","\\&")
contains_spec = stringr::str_detect(strings, pattern = paste(spec, collapse = "|"))

strings[contains_spec]
# [1] "55DD5DDD5.33 311T(&*(" "33FB3FBB3.11 511@$#"   "55GD5GDD5.33 612$Q%J"

You could also use which on contains_spec or contains_only_caps to get the corresponding row numbers for the original data frame. I think that using strings rather than row-wise data frame elements will by much faster - as long as you want to search the whole strings, not certain columns for certain conditions.


text:
Q: Logging SqlAlchemy to Database I'm coding a small application which is supposed to log everything to a database using sqlalchemy.
Inspired by this:
python logging to database
and this:
https://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/logging/sqlalchemy_logger.html
I came up with a solution that works fine for all log messages of all involved libraries besides those generated by sqlalchemy (!) itself.
Here is a minimal example, reproducing my problem:
import logging
import datetime
from sqlalchemy import Column, DateTime, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

 # define table
class TblLog(Base):
    __tablename__ = 'Tbl_Log'

    LOG_TIME = Column(DateTime, primary_key=True)
    LOG_NAME = Column(String(100))
    LOG_LEVEL = Column(String(100))
    LOG_MSG = Column(String(2000))

    def __init__(self, time, name, lvl, msg):
        self.LOG_TIME = time
        self.LOG_NAME = name
        self.LOG_LEVEL = lvl
        self.LOG_MSG = msg

# custom log handler that emits to the database
class DatabaseHandler(logging.Handler):

    def __init__(self, session):
        super().__init__()
        self.session = session
        self.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.setLevel(logging.DEBUG)

    def emit(self, record):

        self.format(record)

        log_time = datetime.datetime.strptime(record.__dict__['asctime'], "%Y-%m-%d %H:%M:%S,%f")

        log_record = TblLog(log_time, record.__dict__['name'], record.__dict__['levelname'], record.__dict__['message'])

        self.session.add(log_record)
        self.session.commit()

testing this with sqlalchemy (!) logs enabled:
if __name__ == '__main__':
    # simple logging config
    logging.basicConfig(
        format='%(asctime)s : %(name)s : %(levelname)s : %(message)s',
        level=logging.DEBUG,
    )
    logger_sqlalchemy = logging.getLogger('sqlalchemy')
    logger_sqlalchemy.setLevel(logging.INFO)

    # test with sqlite in memory database
    DB_STRING = 'sqlite:///:memory:'
    engine = create_engine(DB_STRING, echo=False)
    Base.metadata.create_all(engine)
    Session = sessionmaker()
    session = Session(bind=engine)

    # adding custom handler:
    logger_sqlalchemy.addHandler(DatabaseHandler(session))

    logger_sqlalchemy.info('this is a test message')

This raises

AttributeError: 'NoneType' object has no attribute 'set'

I can paste the whole traceback if necessary. I suspect that the issue arises
because the  TblLog(...) call produces a log record and thus the handler emits records to itself?!
What would be the best solution for this problem, i.e. can I write sqlalchemy log messages to a database using sqlalchemy in the handler??
I'm kind of stuck here, thanks for any help...

A:
I suspect that the issue arises because the TblLog(...) call produces
  a log record and thus the handler emits records to itself?!

That's not the immediate issue. The reason for the failure is that SQLAlchemy is emitting log messages while it is configuring the mapper, the first of those is sent before TblLog's mapper is fully configured and hence, your error.
If you add a StreamHandler to your logger_sqlalchemy instance before the DatabaseHandler you'll be able to see the log messages logger_sqlalchemy is receiving right up to the crash. The log message that's tripping it up is (TblLog|Tbl_Log) _post_configure_properties() started, which is coming from the _post_configure_properties() method. The docstring for that method includes:

This is a deferred configuration step which is intended to execute
  once all mappers have been constructed.

So that's a clue that the config of the mapper for TblLog isn't finished.
If you then, remove the DatabaseHandler from the logger and just leave the StreamHandler you'll see what that method goes on to do (I also removed your basicConfig() for clarity):
(TblLog|Tbl_Log) _post_configure_properties() started
# this is where your code crashed originally
(TblLog|Tbl_Log) initialize prop LOG_TIME
(TblLog|Tbl_Log) initialize prop LOG_NAME
(TblLog|Tbl_Log) initialize prop LOG_LEVEL
(TblLog|Tbl_Log) initialize prop LOG_MSG
(TblLog|Tbl_Log) _post_configure_properties() complete

So as you can see, some initialisation of the column descriptors seems to be happening after that first log message is emitted. Which is why you get the error, the ORM isn't ready by the time you're trying to use it.
You could instantiate a dummy TblLog instance to force the mapper to configure before you add the handler, e.g.:
# ensure TblLog mapper configured
TblLog(time=None, name=None, lvl=None, msg=None)
logger_sqlalchemy.addHandler(DatabaseHandler(session))
logger_sqlalchemy.info('this is a test message')

But you'll then encounter a new problem: SQLAlchemy emits logs throughout the flush/commit process. So then as the first log message is flushed to the datbase it generates a new log message which itself generates a new log message etc etc..... infinite recursion.
So my answer to:

What would be the best solution for this problem, i.e. can I write
  sqlalchemy log messages to a database using sqlalchemy in the
  handler??

The answer would be no, if you are trying to also capture sqlalchemy logging the logging.
Some possible solutions:

*

*Don't use SQLAlchemy to write the log messages to the database. Assuming that you use SQLAlchemy in other parts of your application, use the dpapi client direcly to write the logs to the db and explicitly don't write the client's log messages to the database (otherwise you'll end up with the same recursion issue).

*send your log messages to a webservice using a HTTPHandler which writes the log messages to a database.

*Have sqlalchemy log to a file, while everything else logs to the database. You could even setup a cron job to periodically write the sqlalchemy logs from the file to the database in a separate process.

*Logging as a service


text:
Q: find number of consecutive identical rows in python using pandas suppose I want to do something similar as rle for pandas data frame:
In [247]:  import pandas as pd

In [248]: df = pd.DataFrame([[1, 2],[3, 4],[3,4],[3,4],[5,6]])

In [249]: df
Out[249]:
   0  1
0  1  2
1  3  4
2  3  4
3  3  4
4  1  2

I would like to get an output which tells me that the first row is different to the second, the second is 3 times repeated and then the forth is again repeated only once. So an output like that
In [250]: (1, 3, 1)

What is a pythonic way to achieve this (and fast) in python 2.7?

A: This is one way. I would call this pythonic but not pandonic.
from itertools import groupby

dups = [sum(1 for _ in group) for _, group in groupby(zip(df[0], df[1]))]

A: Using join and value_counts
s=df.astype('str').apply(','.join,1).value_counts(sort=False)
s
Out[275]:
1,2    1
3,4    3
5,6    1
dtype: int64

With tuple
tuple(s.tolist())
Out[278]: (1, 3, 1)

A: I really wanted to keep it pandas so this is what you can do using pandas only:
values = df.apply(tuple, axis=1)
counts = values.value_counts()
result = values.drop_duplicates().map(counts)
tuple(result)
#(1, 3, 1)


text:
Q: mongo + java + too many open files I am using mongo-java2.4jar for communicating with the mongo server.
In my webapp i am using mongo=new Mongo("serverIp","port") where ever it is required and once the processing is complete, I am closing the mongo connection using mongo.close().
But after some time I am getting following exception :

java.net.SocketException: Too many open files

I think when I close the connection it is not closing the sockets.
Please help me out figuring this issue.
Thanks!

A: The Mongo class transparently does connection pooling and you should generally have only one instance per JVM process. Please look at http://api.mongodb.org/java/2.5-pre-/com/mongodb/Mongo.html
If you heavily create instances of this class i think you will acquire too many connections before they can be released. Just create a singleton on app startup for your whole application and place it in the application context. Call close only when your app stops.
Cheers,
Sven


text:
Q: EPGLTransitionView Most of you should know the the cool EPGLTransitionView for flip paging store in the github repository:
https://github.com/epatel/EPGLTransitionView
It is done in opengl but it only works in one landscape direction.
Anyone knows or can give me a tip how can I implement easily the rest of devitation orientations?
thank you,

A: The EPGLTransitionView uses FlipTransitions to make the animations. Here the orientation is hardcoded, you need to change this to your current orientation device.
Overwrite the setupTransition method of FlipForward and FlipBackward classes:
- (void)setupTransition {
NSUInteger rotationFactor = 0;
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
switch (orientation) {
    case UIInterfaceOrientationPortrait:
        rotationFactor = 0;
        break;
    case UIInterfaceOrientationLandscapeRight:
        rotationFactor = 90;
        break;
    case UIInterfaceOrientationPortraitUpsideDown:
        rotationFactor = 180;
        break;
    case UIInterfaceOrientationLandscapeLeft:
        rotationFactor = 270;
        break;
    default:
        break;
}
// Setup matrices
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glRotatef(rotationFactor, 0, 0, -1);
glFrustumf(-0.1, 0.1, -0.1333, 0.1333, 0.4, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_CULL_FACE);
f = 0;}


text:
Q: How do you find the local timezone offset in rust Rust's chrono::Local contains the local timezone information but does not seem to have any methods to get the value as a string or a number of seconds offset.
Any idea's how to get the correct local offset so that
DateTime::parse_from_rfc3339([iso8601 date] + [timezone]).unwrap().with_timezone(&Local)

will return a DateTime that is in the default current timezone of the computer the code is running on.

A: You can use
Local.timestamp(0, 0).offset().fix().local_minus_utc()

which returns the local offset to UTC in seconds (eg. it returns 3600 on my CET system).
(Permalink to the playground, which seems to use UTC and hence returns 0)

A: You can use the chrono crate and use the following snippet to get the timezone offset.
use chrono::Local;
let offset_in_sec = Local::now()
    .offset()
    .local_minus_utc();
eprintln!("offset: {:?}", offset_in_sec);

If you're using the time crate, then you can use the following snippet to get the
timezone offset from offset_in_sec above.
use time::UtcOffset;
let utc_offset_result = UtcOffset::from_whole_seconds(offset_in_sec);
eprintln!("utc_offset_result: {:?}", offset_in_sec);

*

*You can see a real example in r3bl_rs_utils crate here - https://github.com/r3bl-org/r3bl-rs-utils/blob/main/src/utils/file_logging.rs

*For more information, you can also checkout: https://developerlife.com/category/Rust/

A: For the moment I have a hacky solution that works on Linux only
/// returns local timezone "+01:00"
fn tz() -> String {
    let output = Command::new("date").arg("+%:z").output()
                 .expect("failed to fetch timezone");
    String::from(String::from_utf8_lossy(&output.stdout).trim())
}