text:
Q: Recv or send in winsock2 are not sending data I am trying to learn how to build servers. When trying to send data from my client app to the server app, the server app does not receive any data. I assume it is just because of my lack of knowledge on the char buffer I'm sending. The client is able to join on the server and the server does register the client.
SERVER:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include<windows.h>
#include<winsock2.h>
#include<ws2tcpip.h>
#include<iphlpapi.h>

#include<iostream>
#include<fstream>
#include<string>

#pragma comment(lib, "ws2_32.lib")
#define PORT "69"
#define BUFFLEN 512

int main(int argc, char* argv[]) {
    bool active = true;

    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    struct addrinfo* result = NULL, * ptr = NULL, hints;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    std::cout << "which port should be initialized?\n>>>";
    std::string input;
    std::cin >> input;
    std::cout << "initializing..." << std::endl;
    getaddrinfo(NULL, input.c_str(), &hints, &result);

    SOCKET listenSocket = INVALID_SOCKET;
    listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    bind(listenSocket, result->ai_addr, (int)result->ai_addrlen);
    freeaddrinfo(result);

    listen(listenSocket, SOMAXCONN);
    std::cout << "initialized" << std::endl;

    //accept connection
    std::cout << "waiting for client..." << std::endl;
    SOCKET clientSocket = INVALID_SOCKET;
    clientSocket = accept(listenSocket, NULL, NULL);
    std::cout << "client connected" << std::endl;

    char recvBuf[100];
    int dataRes;
    std::cout << "TERMINAL:" << std::endl;
    while (active) {
        dataRes = recv(clientSocket, recvBuf, 100, 0);
        if (dataRes > 0) {
            if (recvBuf == "terminate")
                active = false;
            else
                std::cout << "CLIENT:" << recvBuf << std::endl;
        }
    }

    shutdown(clientSocket, SD_SEND);
    closesocket(clientSocket);
    WSACleanup();
}

CLIENT:
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <iostream>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "69"

int __cdecl main(int argc, char** argv)
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo* result = NULL,
    * ptr = NULL,
    hints;
    const char* sendbuf = "this is a test";
    char recvbuf[DEFAULT_BUFLEN];
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;
    std::cout << "enter ip address\n>>>";
    std::string input;
    std::cin >> input;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(input.c_str(), DEFAULT_PORT, &hints, &result);

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
             ptr->ai_protocol);

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);
    if (ConnectSocket == INVALID_SOCKET) {
         printf("Unable to connect to server!\n");
         WSACleanup();
         return 1;
    }

    //iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    iResult = shutdown(ConnectSocket, SD_SEND);

    // Receive until the peer closes the connection
    bool serverActive = true;
    while (serverActive) {
        char inp[100];
        std::cin >> inp;
        std::cout << "SENT:" << inp << std::endl;
        send(ConnectSocket, inp, (int)strlen(inp), 0);

        if (inp == "terminate")
            serverActive = false;
    }

   // cleanup
   closesocket(ConnectSocket);
   WSACleanup();

   return 0;
}


text:
Q: To merge address or not to merge addresses? Working on a sqlalchemy python flask postgresql project but not sure if I should merge my tables together. I first started off with company address in early development stages now I have another address table.
Should I keep these separate or should these be merged to a global Address table?
UserAddress
CompanyAddress

If I do merge them together to an Address Table it would be something like the following... however in the long run I still have more user_id than company_id and would mostly be blank.
Address
-user_id
-company_id

Companies and user can have multiple addresses... so this is why I'm thinking of using this approach but in the long run. Also I'm not sure if it is a good idea as for maintaining this. Or should I leave them as is and maintain them separately?
Thanks! And if possible, share your experience in dealing with similar situations?

A: It's pretty difficult to answer your question, there are some points to take care of:

*

*If UserAddress and CompanyAddress have exactly the same fields and they can be interchangeable between Users and Companies and you won't want to make queries like all of the UserAddress or all of the CompanyAddress, my advice would be to merge those in the same Address table, as they represent the same entity for you in the database model.

*If there are some user addresses that don't make sense as a company address or if you will add values for company address not present in user address, I recommend you to keep those tables separated, because they don't represent the same entity (a user address is not the same as a company address).

*If you will make operations like "all of the addresses", or searching for text inside all of the addresses, I think I'd make sense to use inheritance. You can accomplish this by saving common fields into one Address table and the specific ones in separated user/company address tables keeping a foreign key to the main Address table, then you reference User/Company Address tables in the User/Company tables respectively.
Your safe bet is to keep the tables separated, you can always merge them later if it makes sense, but if you feel really confident and the tables are (and you think they will be) exactly the same, and you won't be querying for user or company addresses (which will require a lot of joins), just merge them into one table.
Hope it helps,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern matching function gives error Why does the following haskell function gives error ?
The aim is to replicate the given element k number of times in a list and return the list.
Function:
--Replicate the element given number of times and return the list.
replicateElement :: (Integral k) => a -> k -> [a]
replicateElement x 0 = error "Cannot replicate Zero times"
replicateElement x 1 = [x]
replicateElement x k = [x] ++ replicateElement(x k-1)

Error:
Couldn't match expected type `[a]' with actual type `k0 -> [a0]'
    In the return type of a call of `replicateElement'
    Probable cause: `replicateElement' is applied to too few arguments
    In the second argument of `(++)', namely
      `replicateElement (x k - 1)'
    In the expression: [x] ++ replicateElement (x k - 1)
Failed, modules loaded: none.

A: When you write
replicateElement(x k-1)

you are passing just 1 argument to replicateElement, namely (x k-1), which also means ((x k) - 1), and you actually don't intend for x to be a function. Instead, what you should write is:
replicateElement x (k-1)

A: Your last line should be:
replicateElement x k = [x] ++ replicateElement x (k-1)

You don't need to put brackets around function arguments in Haskell.


text:
Q: How to unable and uncheck other checkbox if one is check using jquery?  <input type="checkbox" class="allCheck" />all
 <input type="checkbox" class="checks" />shoes
 <input type="checkbox" class="checks" />bag
 <input type="checkbox" class="checks" />car

how to unable and uncheck other checkbox if checkbox all is checked?
NOTE: I want to check multiple checkbox EXCEPT ALL if ALL is checked the others must be unchecked and disabled.

A: It's fairly straight-forward, but there are gotchas:

*

*If .allCheck is changed by the user, drive the .checks checkboxes from it

*If a .checks checkbox is changed by the user, drive the .allCheck checkbox based on whether all or none of .checks are (now) checked

// If `.allCheck` is changed by the user, drive the `.checks` checkboxes from it
$(".allCheck").on("change", function() {
  $(".checks").prop("checked", this.checked);
});
// If a `.checks` checkbox is changed by the user, drive the `.allCheck`
// checkbox based on whether all or none of `.checks` are (now) checked
$(".checks").on("change", function() {
  var all = $(".checks").get().every(function(cb) {
    return cb.checked;
  });
  $(".allCheck").prop("checked", all);
});
<input type="checkbox" class="allCheck" />all
<input type="checkbox" class="checks" />shoes
<input type="checkbox" class="checks" />bag
<input type="checkbox" class="checks" />car

Note in the above I have not done this

...and disabled

We can, but it's not the way these things are usually most useful. Instead, the above makes it easy to pick all but one (by ticking "all," then unticking the one).
But if you really want that disabled behavior, granted it's a bit simpler: You flag disabled via .prop("disabled", flag) and only have to handle changes to .allCheck.

$(".allCheck").on("change", function() {
  $(".checks")
      .prop("checked", this.checked)
      .prop("disabled", this.checked)
});
<input type="checkbox" class="allCheck" />all
<input type="checkbox" class="checks" />shoes
<input type="checkbox" class="checks" />bag
<input type="checkbox" class="checks" />car

A:

$('.allCheck').click(function(){
    $('.checks').prop('checked',$(this).prop('checked'));
    $('.checks').prop('disabled',$(this).prop('checked'));
});

<input type="checkbox" class="allCheck" />all
 <input type="checkbox" class="checks" />shoes
 <input type="checkbox" class="checks" />bag
 <input type="checkbox" class="checks" />car


text:
Q: use a created function within a function vba Im Making a VBA function to calculate an integral using the trapezoidal rule
but how can I apply a function that I created in VBA to Use in a another Function...heres My Code ( the worksheet.function did not work)
Option Explicit

Function funcion(x As Double) As Double
    funcion = 3 * (x ^ 3) + 5 * (x ^ 2) - 10 * x + 20
End Function

Function Sumatoria(a As Double, n As Double, h As Double) As Double
    Dim i As Integer
    Dim sum As Double

    i = 0
    sum = 0

    Do While (i <= n - 1)
        sum = sum + WorksheetFunction.funcion(a + i * h)
         i = i + 1
    Loop

    Sumatoria = sum

 End Function

A: This works :
Function Sumatoria(a As Double, n As Double, h As Double) As Double

    Dim i As Integer
    Dim sum As Double
    Dim temp As Double

    i = 0
    sum = 0

    Do While (i <= n - 1)
        temp = a + i * h
        sum = sum + funcion(temp)
         i = i + 1
    Loop

    Sumatoria = sum

 End Function


text:
Q: AS3 - Y Velocity 6.123031769111886E-17 When given 0,0 to 0,5, the y velocity becomes that number and breaks my code. I know I must have done something wrong as I just copy and pasted code (since I am horrible at maths)..
This is how I calculate the numbers:
var radian = Math.atan2(listOfNodes[j].y - listOfNodes[i].y,listOfNodes[j].x - listOfNodes[i].x);
var vy = Math.cos(radian);
var vx = Math.sin(radian);

Thanks

A: There i am assuming the velocity vector is FROM 0,0 TO 0,5. And 0,0 is i and 0,5 is j.
In that case the velocity vector is only along y and the y component should be 5 and x component 0. It is coming as opposite because,
cos(radian) whould be x velocity component and sin(radian) the y compunent.
And the number 6.123031769111886E-17 is actually returned in place of 0.
Look at the following figure:

Also as can be seen from the figure you do not need the trigonometric computations at all.
You can simply get the x and y components as follows:
// y2 - y1
var vy = listOfNodes[j].y - listOfNodes[i].y;
// x2 - x1
var vx = listOfNodes[j].x - listOfNodes[i].x;

This will avoid the floating point inaccuracy caused by the trig finctions due to which you are seeing 6.123031769111886E-17 instead of 0.
You only need to use atan2 if you actually need the angle θ in your code.
Update:
Well if you need only unit (normalized) vector's components you can divide the vx and vy with the length of the original vector. Like this:
// y2 - y1
var vy = listOfNodes[j].y - listOfNodes[i].y;
// x2 - x1
var vx = listOfNodes[j].x - listOfNodes[i].x;
// vector magnitude
var mag = Math.sqrt(vx * vx + vy * vy);

// get unit vector components
vy /= mag;
vx /= mag;

Using the above you will get the exactly the same results as you are getting from trig sin and cos functions.
But if you still need to use the original code and want to make 6.12...E-17 compare to 0, you can use the epsilon technique for comparing floats. So you can compare any value within epsilon's range from 0, using flllowing code:
function floatCompare(a:Number, b:Number, epsilon:Number):Boolean{
    return (a >= (b - epsilon) && a <= (b + epsilon));
}
// To check for zero use this code, here i'm using 0.0001 as epsilon
if(floatCompare(vx, 0, 0.0001)){
    // code here
}

So any deviation in the range of [b-epsilon, b+epsilon] would successfully compare to b. This is essential in case of floating point arithmetic.


text:
Q: Timers and counters I have to build a ladder diagram for a system which sounds the alarm if inside 60 seconds after pressing the start button,10 objects have passed.The alarm goes on until we press stop.In the system we have placed a sensor to identify the objects and the stop button to stop the alarm and to reset the system.Is my solution correct?

Edit : T1 is the timer,C1 is the counter,S is sensor,C is the output of C1 K10

A: For "Start",  you will need a "seal in contact", so that when start button is pressed,  the "start" contact will maintain.  (Also need to have "start" reset appropriately).  Right now, as soon as "start" pushbutton is released, the timer will stop.
As @Tut mentioned, you will need to reset T1 during reset.


text:
Q: Nested old-style form with Angular I'm facing a tricky problem: I have to make an old style form with action attribute inside a ng-form.
The reason I'm doing this is that the POST request from the old-style form goes to another website, and the user should be "redirected" (in a new page actually) to the result of the POST request (which makes kind of login).
I can simulate the old-style form from javascript but so the browser popup blocker will catch it and it has to be as easy as clicking a link.
I can't touch the outter ng-form because it comes from a framework.
So what I have is:
<div ng-form>
...
...
  <form action="old_website.com/index.php" method="post" target="_blank">
    <input type="hidden" name="field1" value="value1">
    <input type="submit" value="Submit">
  </form>
...
...
</div>

I can't find a way to make this work :) Hope you can help.
[edit] Ok I feel stupid. It seems you can have a button that calls a function to simulate and submit the form without having trouble with the browser popup blocker...
It also seems it does not work with Firefox.
What I'm doing is:
HTML:
<button ng-click="submitForm()">Submit</button>

JS:
$scope.submitForm = function() {
  var form = $('<form>', {
    action: 'old_website.com/index.php',
    type: 'post',
    target: '_blank'
  });
  form.append($('<input>', {name: 'field1', value: 'value1'}));
  form.submit();
}

A: Since the edit solved the first problem I had, I'll close this question and open another for the Firefox problem.
Thanks guys :)
[edit] This solved the problem with firefox.


text:
Q: host exception in .htaccess for http to https redirection I have defined the following code in my .htaccess file, how do I make an exception for http://mydomian.com to not be redirected to https ?
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

(Please note that somewhere on my site I'm loading http://mydomian.com via iFrame and on that website it doesn't have the https working properly).

A: To exclude www.mydomain.com you can use the following RewriteCondition :
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$

Try this :
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: How to get a responsive button in bootstrap 3 I am using bootstrap 3 and I have the following html:

    Create New Board

On a small screen, the text "Create New Board" is too long to fit on the button.  I would like the text to wrap on to another line and the height of the button to increase to fit the text.  Any tips on how to do this?

A: In Bootstrap, the .btn class has a white-space: nowrap; property, making it so that the button text won't wrap. So, after setting that to normal, and giving the button a width, the text should wrap to the next line if the text would exceed the set width.
#new-board-btn {
    white-space: normal;
}

http://jsfiddle.net/ADewB/

A: In some cases it's very useful to change font-size with relative font sizing units. For example:
.btn {font-size: 3vw;}

Demo:
http://www.bootply.com/7VN5OCVhhF
1vw is 1% of the viewport width. More info: http://www.sitepoint.com/new-css3-relative-font-size/

A: I know this already has a marked answer, but I feel I have an improvement to it.
The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.
One thing not mentioned here, is that the words may break in the middle of a word and look messed up.
My solution, forces the break to happen between words, a nice word wrap.
.btn-responsive {
    white-space: normal !important;
    word-wrap: break-word;
}

Click Here

A: <button type="button" class="btn btn-info btn-block regular-link"> Create New Board</button>

We can use btn-block for automatic responsive.

A: For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..
Demo: http://bootply.com/93706


text:
Q: WPF: Spacing in elements with the use of percent I am trying to create a grid, with some elements, but, I am seeing an space between them (My window is responsive), I create a simple example in WPF to show the problem:
    <Grid Background="Red">
        <Grid.RowDefinitions>
            <RowDefinition Height="0.20*" />
            <RowDefinition Height="0.80*" />
            <RowDefinition Height="0.20*" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="0" Background="Green" Margin="0">
            <TextBlock Text="Header"></TextBlock>
        </Grid>
        <Grid Grid.Row="1" Background="Green" Margin="0">
            <TextBlock Text="Body"></TextBlock>
        </Grid>
        <Grid Grid.Row="2" Background="Green" Margin="0">
            <TextBlock Text="Footer"></TextBlock>
        </Grid>
    </Grid>

And, let me show you the result:

As you can see, there is a space between the cells (The background is red), in my real scenario I can't set the background as green (In this example could be a solution).
Is there any way to fill the cells without those spaces (And responsive)?

A: I found out that this issue is due to some rendering problem. If you use SnapsToDevicePixels="True", it should solve your problem:
<Grid Background="Red" SnapsToDevicePixels="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="0.20*" />
        <RowDefinition Height="0.80*" />
        <RowDefinition Height="0.20*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Header"  Grid.Row="0" Background="Green"/>
    <TextBlock Text="Body"  Grid.Row="1" Background="Green" />
    <TextBlock Name="Box512" Text="Footer" Grid.Row="2" Background="Green"/>
</Grid>


text:
Q: Is there any way to make div vertically on middle whenever even has changes of height? im trying to make menu vertically on middle in header div. But this menu has  changes of height in Jquery because of  slideUp and slideDown.
So is there any way automatically on middle even if height changes with click event???

A: The two following options should work. The first is simpler, but the second is more foolproof.

OPTION 1

HTML:

CSS:
#center {
position: relative;
top: 50%;
bottom: 50%; }

OPTION 2

HTML

The Content

Once upon a midnight dreary...

CSS
.outer {
    display: table;
    position: absolute;
    height: 100%;
    width: 100%;
}

.middle {
    display: table-cell;
    vertical-align: middle;
}

.inner {
    margin-left: auto;
    margin-right: auto;
    width: /*whatever width you want*/;
}

A: You can try this, hope it will help you:-

        header{
            background-color: #ccc;
            width: 100%;
            margin: 0 auto;
        }
        ul {
            text-align: center;
            }
        ul li{
            height: 40px;
            list-style: none;
            display: inline-flex;
            align-items: center;
            padding:0 10px;
            }

navigation

navigation

navigation


text: Q: The 'Is Desired Intent' is returning a wrong value in Power Automate LUIS connector I am using the "Get Prediction" connector for LUIS in Power Automate. It seems that even though my desired intent has a high score (90+%) and is the highest scoring intent, the "Is Desired Intent" returns false when it should return true. How do I fix this?


text:
Q: PHPSpreadsheet to Read Passworded XLSX I've spent all day searching both the documentation and the web but there doesn't seem to be a way to programmatically open a passworded spreadsheet with phpspreadsheet; and spout library for that matter.
In Phpspreadsheet, I'm interested in the xlsx reader and have followed the inheritance chain to the root class but none have a "setpassword" type method (I notice writer class has though.)
Is this a true oversight in both libraries or have I missed something somehow? Is there any other way to do this in PHP? Or next best, strip the password off a set of xlsx files programmatically and then read it with either library?

A: Seeing no other solution, I solved this by writing VBA to open each file and save without the password. Then I could process with PHPSpreadsheet.


text:
Q: How can I encode a rule tree of multiple depths in Dhall? I'm trying to move some error prone YAML into Dhall to make some system configuration simpler. I have a tree that looks like:
composite:
  condition: And
  rules:
    - composite:
        condition: And
        rules:
          - leaf:
              static: true
          - leaf:
              exists: some-property-to-lookup
    - composite:
        condition: Or
        rules:
          - composite:
              condition: And
              rules:
                - leaf:
                    static: true
                - leaf:
                    exists: some-property-to-lookup

I'm trying to encode this in Dhall and I can't seem to provide the compiler the right information. My latest try looks like:
let Field
    : Type
    = < B : { static : Bool } | S : { exists : Text } >

let Condition
    : Type
    = < And | Or | Not >

let Node
    : Type
    = ∀(Node : Type) →
      ∀(Leaf : { leaf : Field }) →
      ∀(Branch : { composite : { condition : Condition, rules : List Node } }) →
        Node

let example
    : Node
    = ∀(Node : Type) →
      ∀(Leaf : { leaf : Field }) →
      ∀(Branch : { composite : { condition : Condition, rules : List Node } }) →
        Branch
          { composite =
            { condition = Condition.And
            , rules =
              [ Branch
                  { composite =
                    { condition = Condition.And
                    , rules = [ Leaf { leaf = Field.S { exists = "hi" } } ]
                    }
                  }
              , Branch
                  { composite =
                    { condition = Condition.Or
                    , rules = [ Leaf { leaf = Field.S { static = true } } ]
                    }
                  }
              , Branch
                  { composite =
                    { condition = Condition.And
                    , rules =
                      [ Branch
                          { composite =
                            { condition = Condition.And
                            , rules =
                              [ Leaf { leaf = Field.S { exists = "hi" } } ]
                            }
                          }
                      , Branch
                          { composite =
                            { condition = Condition.Or
                            , rules =
                              [ Leaf { leaf = Field.S { static = true } } ]
                            }
                          }
                      ]
                    }
                  }
              ]
            }
          }

in  example

But I get Error: Not a function. Any pointers would be appreciated.
I also tried w/ the Graph module, but I can't seem to convert that to YAML directly.

A: This works:
let Field
    : Type
    = < B : { static : Bool } | S : { exists : Text } >

let Condition
    : Type
    = < And | Or | Not >

let Node
    : Type
    = ∀(Node : Type) →
      ∀(Leaf : { leaf : Field } → Node) →
      ∀(Branch : { composite : { condition : Condition, rules : List Node } } → Node) →
        Node

let example
    : Node
    = λ(Node : Type) →
      λ(Leaf : { leaf : Field } → Node) →
      λ(Branch : { composite : { condition : Condition, rules : List Node } } → Node) →
        Branch
          { composite =
            { condition = Condition.And
            , rules =
              [ Branch
                  { composite =
                    { condition = Condition.And
                    , rules = [ Leaf { leaf = Field.S { exists = "hi" } } ]
                    }
                  }
              , Branch
                  { composite =
                    { condition = Condition.Or
                    , rules = [ Leaf { leaf = Field.B { static = True } } ]
                    }
                  }
              , Branch
                  { composite =
                    { condition = Condition.And
                    , rules =
                      [ Branch
                          { composite =
                            { condition = Condition.And
                            , rules =
                              [ Leaf { leaf = Field.S { exists = "hi" } } ]
                            }
                          }
                      , Branch
                          { composite =
                            { condition = Condition.Or
                            , rules =
                              [ Leaf { leaf = Field.B { static = True } } ]
                            }
                          }
                      ]
                    }
                  }
              ]
            }
          }

in  example

Here is the diff between the two:
12,13c12,13
<       ∀(Leaf : { leaf : Field }) →
<       ∀(Branch : { composite : { condition : Condition, rules : List Node } }) →
---
>       ∀(Leaf : { leaf : Field } → Node) →
>       ∀(Branch : { composite : { condition : Condition, rules : List Node } } → Node) →
18,20c18,20
<     = ∀(Node : Type) →
<       ∀(Leaf : { leaf : Field }) →
<       ∀(Branch : { composite : { condition : Condition, rules : List Node } }) →
---
>     = λ(Node : Type) →
>       λ(Leaf : { leaf : Field } → Node) →
>       λ(Branch : { composite : { condition : Condition, rules : List Node } } → Node) →
34c34
<                     , rules = [ Leaf { leaf = Field.S { static = true } } ]
---
>                     , rules = [ Leaf { leaf = Field.B { static = True } } ]
52c52
<                               [ Leaf { leaf = Field.S { static = true } } ]
---
>                               [ Leaf { leaf = Field.B { static = True } } ]


text:
Q: Patching GHOST Vulnerability # CVE-2015-0235 SLES 11 SP3 I need to upgrade a SLES 11 SP3 server for the new ghost vulnerability that has been discovered.
According to http://www.cyberciti.biz/faq/cve-2015-0235-patch-ghost-on-debian-ubuntu-fedora-centos-rhel-linux/ I should be able to run zypper although this doesn't work as it says there are no packages found.
However, Zypper isn't any good to me any as the server I need to upgrade doesn't have direct access to the internet, so I need an offline install, I guess an RPM would be best. I've had a look at the novel repos but it doesn't seem to have been updated.
Thanks for your help.

A: Do you have a Novel account?
Regarding this link you can download the files.


text:
Q: Google in-app updates api not updating latest version of app from play store I have implemented google In-app updates in my android project. There are two ways of implementing the in-app update.
1. Immediate and 2 Flexible.
I am using Flexible mode to update the app.
Now There is 1.0.7 version of my app exist in google play store which is updated one.I have retained version 1.0.3 in my app for testing purpose. Mean while There are five versions like 1.0.3, 1.0.4, 1.0.5, 1.0.6 and last 1.0.7 (which is latest version).
When I create signed apk and then it show alert to update the app in flexible mode, when I go for the update, after updating I restart the app and then it shows version 1.0.5 not the latest version which is on playstore (1.0.7).
Can anyone please tell me why it's not updating latest version(1.0.7).
Thanks in advance.


text:
Q: Trying to add users from Group A to Group C but not if they are members of Group B Long time reader first time poster... :)
I'm getting all confused. So, I'm trying to add users that are in GroupA and not in GroupC but also exempt them if they are in GroupB. I'm using this script:
$OUs = 'OU=TestOU,OU=Users,DC=domain,DC=local'
$ExemptGroups = (Get-AdGroup -filter * | Where {$_.name -like "Exempt Groups B and C wildcard"} | select name -expandproperty name)
get-aduser -filter * -searchbase $OUs | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -eq "Group A") -and ((get-aduser $_.samaccountname -properties memberof).memberof -eq $ExemptGroups)} | ForEach {add-adgroupmember -identity "Group C" -members $_.samaccountname}

Im not getting any errors with a test user in the test OU but its also not adding them to the desired Group C
Any ideas what I'm doing wrong?
Thanks

A: No need to query AD a bunch of times, we can query it once and then slice the results as we need it.
$OUs = 'OU=TestOU,OU=Users,DC=domain,DC=local'
$users =  Get-AdGroup -filter * -properties memberof

I think it would be easier to hit AD and cache the results, then filter the results to all the GroupB members and store that as GroupB members.
#gives an array of users in Group B
$GroupBMembers = $users | Where {$_.memberof -eq "Group B"} | select -expandproperty name

Then we look at the cache again and now filter it for anyone who IS NOT in GroupB members.
$NewGroupCMembers = $users | where {$_.Name -notin $GroupBMembers }

#...add NewGroupCMembers to Group C

Now all that's left is to add the people in $NewGroupCMembers to group C and you're done!

A: @FoxDeploy Ok this is what I have cobbled together with your help:
$OUs = 'OU=TestOU,OU=Users,DC=domain,DC=local'
#
# Query users of groups for membership
$users = Get-ADGroup -filter * -properties memberof
#gives an array of users in Group B
$GroupBMembers = $users | Where {$_.memberof -eq "GroupB"} | select -expandproperty name
#Filter users not in GroupB group
$NewGroupCMembers = $users | where {$_.Name -notin $GroupBMembers }
#Add new group members to GroupC
$OUs | ForEach {add-adgroupmember -identity "GroupC" -members $NewGroupCMembers -WhatIf}

Running with "WhatIf" the output seems ok:

What if: Performing the operation "Set" on target "GroupC".

Running without WhatIf, I get an error:

add-adgroupmember : A global group cannot have a universal group as a
member At line:20 char:17

*

*...  | ForEach {add-adgroupmember -identity "GroupC (I think because its cut off) ...

*
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*

*CategoryInfo          : NotSpecified: (GroupC:ADGroup) [Add-ADGroupMember], ADException

*FullyQualifiedErrorId : ActiveDirectoryServer:8517,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember


text:
Q: Is it possible to inspect a MS SQL Server dump (.dat-binary, exported with bcp)? I have issues importing a binary .dat-file that has been generated with the cmd-line tool bcp. Besides the unhelpful error messages I get (invalid field size for datatype ; but no mention of which column and or datatype) I have nothing to go with. I did not generate the bcp file, so there is that.
It's a large file and I have not encountered any means to see the contents!

*

*Is it somehow possible to convert the the binrary .dat file into a flat text .csv file?

*Is it possible to just extract the first couple of rows into clear text?

Thank you for any hints.


text:
Q: Expected number of rolls when removing all duplicate rolls Suppose we are playing a game where we start with six dice and we roll all the dice simultaneously. After the roll, if any of the dice is a duplicate of another we remove it entirely from the game. For example, if we roll 1 1 1 2 2 5, we would remove three dice: 1 1 and 2. After removing the applicable dice (or not removing any at all), we grab the remaining dice and roll again.
What is the expected number of rolls before we arrive at only one dice?


text:
Q: how to make multi module Ear project in eclipse and maven i am new to Ear kind project i can make a war project now i want to add my all war project in a Ear project by using maven but not able to get success my pom.xml file of Ear project gives me the error
and i am not able to get that, if any one has the solution please help.
thanks in adv.


text:
Q: Determine if a path within an NSString is to a directory, or a file? I have an NSString containing a path, but it could be either a file, or a directory.
Is there an equivalent to the Python os.path.isdir() and os.path.isfile() methods in Cocoa?

A: See the NSFileManager Class Reference
[[NSFileManager defaultManager] fileExistsAtPath:pathname
                                isDirectory:&directoryFlag];

For example:
NSString *file = @"/tmp/";
BOOL isDir = NO;
if([[NSFileManager defaultManager]
     fileExistsAtPath:file isDirectory:&isDir] && isDir){
    NSLog(@"Is directory");
}

A: if the solution from htw doesn't work, try this:
NSString *file = @"/tmp/";
BOOL isDir
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:file];
while ((file = [dirEnum nextObject])) {
   [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir];
   if(isDir){
      NSLog(@"%@ is a directory", file);
   }
}


text:
Q: View multiple animated gifs at the same time? I'm looking for a program/image viewer/gallery that I can point to a folder and see thumbnails of all the animated GIFs doing their animation.
Or something that make the GIFs animate without having to open each file.
Does such a thing exist?

A: Open notepad, put this text inside:
FOR /F %%G IN ('dir /B *.gif') DO echo ^<img src="%%G"^ width="40"^>^ %%G^<br^> >> gifs.html

Save it with name "whatever.bat" in folder where you have your gifs located, but choose "All files", not "Text file". Then navigate to your folder and doubleclick on whatever.bat. This will create another file called "gifs.html" in current directory. Doubleclick on it and you will see your gifs in web browser.


text:
Q: what file transfer mode should i use when transfering files from windows PC to linux server? I am using FileZilla for Upload/Download files from my windows PC to server and vise a versa
when i am uploading well formatted PHP file on server and then re-downloading it from server the code is mixed up the format
so can any one suggest me what file transfer mode should i use when transferring files from windows to linux server?

A: I think you can set your ftp client to use binary transfer mode all the time
Side note
maybe you need a good text-editor or IDE that can convert between
\r, \n and \r\n.


text:
Q: FileTransfer onprogress not working - PhoneGap 3.5.0 The onprogress event handler never seems to be called. The success callback comes through fine and the download works. Is there something I'm doing wrong here?
filesystem.root.getFile('/path/to/file', { create: true }, function (file) {

    var transfer = new FileTransfer();

    transfer.onprogress = function () {
        console.log(arguments);
    };

    transfer.download(
        'http://example.com/path/to/file',
        file.toURL(),
        function () { console.log('success'); },
        function () { console.log('error'); },
        true
    );

}, function () { console.log('error'); });

The app uses PhoneGap 3.5.0 with the newest file and file-transfer plugins. I'm testing on an iPad with iOS 8.

A: You seem to be missing the arguments variable on the onprogress function definition.
It should be:
transfer.onprogress = function (progressEvent) {
    console.log(progressEvent);
    console.log(progressEvent.loaded); //Loaded bytes
    console.log(progressEvent.total); //Total bytes
    console.log(progressEvent.lengthComputable); //TRUE if the destination server informs total file length
};

You can find the docs here: http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileTransfer
Hope it helps!


text:
Q: query string then insert in anchor using parse I am using Parse to retrieve values stored in a database. I can successfully retrieve image data and render it to the DOM, however, I am having trouble getting a string which consists of a web address and inserting it into an  tag. Currently, I get an "error loading page" message. I'm not sure what I've done wrong? Heres the main part of my code:
query.find({
    success:function(results) {
    var s = "";
    for(var i=0; i<results.length; i++) {
        //Lame - should be using a template
        s += "
";
        var pic = results[i].get("image");
        var address = results[i].get("address");

        if(pic) {
            s += "
";
        }
        s += "
";
    }
    $("#home2 div[data-role=content]").html(s);
}


text:
Q: @WithMockUser returning NoSuchMethodError I'm trying to run this test
@Test
@WithMockUser(username = "myUser", roles = ["USER"])
fun givenExistingFirstnames_whenGetRequest_thenReturnsFirstnameJsonWithStatus200() {
    every { firstnameService.findFirstnames() } returns firstnames

    mockMvc.perform(get("/api/v1/firstnames"))
        .andExpect(status().isOk)
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.firstname").value("Amadou"))
}

but when run, I get this error and I can't understand why:
java.lang.NoSuchMethodError: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken org.springframework.security.authentication.UsernamePasswordAuthenticationToken.authenticated(java.lang.Object, java.lang.Object, java.util.Collection)'

Here are my dependencies:
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa:2.7.3")
    implementation("org.springframework.boot:spring-boot-starter-data-rest:2.7.3")
    implementation("org.postgresql:postgresql:42.4.2")
    implementation("org.springframework.boot:spring-boot-starter-security:2.7.3")
    implementation("org.springframework.boot:spring-boot-starter-web:2.7.3")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3")
    implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.0")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0")
    implementation("com.sipios:spring-search:0.2.4")
    implementation("org.junit.jupiter:junit-jupiter:5.9.0")
    // https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui
    implementation("org.springdoc:springdoc-openapi-ui:1.6.10")
    // https://mvnrepository.com/artifact/com.opencsv/opencsv
    implementation("com.opencsv:opencsv:5.6")
    // https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt
    implementation("io.jsonwebtoken:jjwt:0.9.1")
    // https://mvnrepository.com/artifact/org.liquibase/liquibase-core
    //implementation("org.liquibase:liquibase-core:4.7.1")
    runtimeOnly("com.h2database:h2:2.1.214")
    testImplementation("org.springframework.boot:spring-boot-starter-test:2.7.3") {
        exclude(group = "org.mockito", module = "mockito-core")
    }
    testImplementation("org.springframework.security:spring-security-test:5.7.3")
    testImplementation("com.ninja-squad:springmockk:3.1.1")
}

It seems that all versions are aligned


text:
Q: Card Slider transform translate only working as expected on first click I am trying to get this card slider to transform cards on each click. Every time the user clicks on any of the cards, the last card in the array goes to the beginning, and all cards are moving as in a carousel, scaling and changing their zIndex. It works perfectly on the first click but then cards start translating differently.
After searching and searching, I read you have to keep track of translations therefore I am using distanceCounter0Elm and distanceCounterElse variables, but it does not seem to work. Also tried to reset all transforms and even a different approach by adding css classes but could not get it to work properly.
Where is my mistake? It might be something very simple but I am not being able to see it. I would really appreciate your help. Many thanks!

Nuestros trabajos

section{
    background-color: #021845;
    width: 98vw;
    height: 180vh;
    padding-top: 10vh;
    display: flex;
    flex-direction: column;
}
.tituloTrabajos{
    color: white;
    text-align: center;
    font-size: 2vw;
    margin-bottom: 25vh;
}
.sitesContainer{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    align-content: center;
    flex-wrap: wrap;
    row-gap: 8vh;
}
.siteDiv{
    background-color: #ddf1fc;
}
.sitePic{
    width: 38vw;
    border-radius: 20px;
}
.container{
    position: relative;
    height: 150vh;
    width: 98vw;
    display: flex;
    justify-content: center;
    overflow: hidden;
}
.eachCard{
    width: 38vw;
    height: 40vh;
    border-radius: 20px;
    box-shadow: -5px 0 6px #000, 10px 0 6px #000;
    transition: 0.4s ease-out;
    position: relative;
    border: 5px solid white;
    cursor: pointer;
    top: 5vh;
}
.eachCard:not(:first-child){
    margin-left: -30vw;
}
.originalzIndex2{
    z-index: 2;
}
.originalzIndex1{
    z-index: 1;
}
.originalScale{
    transform: scale(1.2);
}

var grasscoImgs = ["img/grassco2.png", "img/grassco3.png", "img/grassco.png", "img/grassco4.png", "img/grassco6.png"];
var grasscoContainer = document.getElementById("grasscoContainer");
var cards = document.getElementsByClassName("eachCard");

grasscoImgs.forEach(function(image){
    var img = document.createElement("img");
    img.src = image;
    img.classList.add("eachCard");
    grasscoContainer.appendChild(img);
    img.onclick = slideCards;
});

cards[2].classList.add("originalzIndex2", "originalScale");
cards[3].classList.add("originalzIndex1");

var cardsArr = Array.from(cards);

function slideCards(){

    var lastCard = cardsArr.pop();
    cardsArr.splice(0, 0, lastCard);
    var distanceCounter0Elm = " translate(-32vw)";
    var distanceCounterElse = " translate(2vw)";
    for (let i = 0; i < cardsArr.length; i++){
        if (i == 0){
            cardsArr[0].style.transform = distanceCounter0Elm + " scale(0.8)";
            cardsArr[0].style.zIndex = "0";
            distanceCounter0Elm += " translate(-32vw)";
        } else {
            cardsArr[1].style.transform = distanceCounterElse + " scale(1)";
            cardsArr[2].style.transform = distanceCounterElse + " scale(1.2)";
            cardsArr[3].style.transform = distanceCounterElse + " scale(1)";
            cardsArr[4].style.transform = distanceCounterElse + " scale(0.8)";
            cardsArr[1].style.zIndex = "1";
            cardsArr[2].style.zIndex = "2";
            cardsArr[3].style.zIndex = "1";
            cardsArr[4].style.zIndex = "0";
            distanceCounterElse += " translate(2vw)";
        };
    };
};


text:
Q: What distro allows you to create a folder and a file with the same exact name? I am trying to figure out which distro this script (scene_splitter.sh) was built for. Everytime I try to use it I get the following error.
x@x-pc:/media/x/WD_2TB_HDD/test$ ./scene_splitter.sh 001.mp4
==============================================================================
FILE START: 001.mp4
mkdir: cannot create directory './001.mp4': File exists
Finding Scene... this might take a while...
./scene_splitter.sh: line 12: ./001.mp4/ffout.tmp.txt: Not a directory
Filtering timestamp... this might take a while...
./scene_splitter.sh: line 15: ./001.mp4/timestamps.tmp.txt: Not a directory
grep: ./001.mp4/ffout.tmp.txt: Not a directory
./scene_splitter.sh: line 17: ./001.mp4/timestamps.tmp.txt: Not a directory
Found  scenes
./scene_splitter.sh: line 31: ./001.mp4/timestamps.tmp.txt: Not a directory
---------------------------------------------------------------------------
LAST SCENE START:0/ (0,end)
ffmpeg version 3.4.4-0ubuntu0.18.04.1 Copyright (c) 2000-2018 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.3.0-16ubuntu3)
  configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '001.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.20.100
  Duration: 00:04:17.77, start: 0.000000, bitrate: 4771 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 9:8 DAR 2:1], 4635 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
./001.mp4/001.mp4.(0 of ).mp4: Not a directory
LAST SCENE DONE:0/ (0,end)
---------------------------------------------------------------------------
FILE DONE: 001.mp4
==============================================================================

It seems it was built for using with a distro that allows a folder and a file to have the same exact name, only difference being one a folder and one a file... assuming that distro knows the difference and thus allows it.

Here is the code for scene_splitter.sh
#/bin/bash

start=0;
count=0;
in="$1"
bn="$(basename "$in")"
echo "=============================================================================="
echo "FILE START: $bn"
mkdir "./$bn"

echo "Finding Scene... this might take a while..."
ffmpeg -nostdin -i "$in" -filter:v "select='gt(scene,0.1)',showinfo" -f null - 2>"./$bn/ffout.tmp.txt"

echo "Filtering timestamp... this might take a while..."
grep showinfo "./$bn/ffout.tmp.txt" | grep pts_time:[0-9.]* -o | grep '[0-9]*\.[0-9]*' -o > "./$bn/timestamps.tmp.txt"

scenes=$(wc -l < "./$bn/timestamps.tmp.txt")
echo "Found $scenes scenes"
sleep 1

while IFS= read -r line; do
    echo "---------------------------------------------------------------------------"
    echo "SCENE START: $count/$scenes ($start,$line)"
    ffmpeg -i "$in" -ss "$start" -to "$line" -nostdin -y -vcodec libx264 -acodec aac -g 120 -s 1280x720 -r 30 "./$bn/$bn.($count of $scenes).mp4"
    echo "SCENE DONE:$count/$scenes ($start,$line)"
    echo "---------------------------------------------------------------------------"
    start=$line
    count=$(($count+1))
    sleep 1

done <"./$bn/timestamps.tmp.txt"
echo "---------------------------------------------------------------------------"
echo "LAST SCENE START:$count/$scenes ($start,end)"
ffmpeg -i "$in" -ss "$start" -nostdin -y -vcodec libx264 -acodec aac -g 120 -s 1280x720 -r 30 "./$bn/$bn.($count of $scenes).mp4"
echo "LAST SCENE DONE:$count/$scenes ($start,end)"
echo "---------------------------------------------------------------------------"

echo "FILE DONE: $bn"
echo "=============================================================================="

Does anyone know how to edit this script so that it doesn't want to create a directory with the exact same name as the file being inputted?

A: Creating a directory with the same name as a file is not really possible on any Linux or Unix (that I know of, at least.)
But that's not really what the script is trying to do.
If you look carefully, you'll notice it's creating a directory with the same basename of the input file, but on the current directory.
Look at this part:
bn="$(basename "$in")"
# ...
mkdir "./$bn"

So, if given an input file of /path/to/movies/001.mp4 or ../movies/001.mp4, then it will try to create the ./001.mp4 directory, which is different from the input file (assuming your in a directory other than /path/to/movies in the example I used.)
The script is expecting you're running it from the output directory, and that the input files live in a separate directory other than the current one.
For example, this usage should work fine for you:
x@x-pc:/media/x/WD_2TB_HDD/test$ mkdir output
x@x-pc:/media/x/WD_2TB_HDD/test$ cd output
x@x-pc:/media/x/WD_2TB_HDD/test/output$ ../scene_splitter.sh ../001.mp4

UPDATE: If you want to modify the script to avoid the name clash, simply changing how bn is defined should do the job. For instance, adding an out- prefix:
bn="out-$(basename "$in")"


text:
Q: How to run SQL(MYSQL) stored procedure in JAVA jdbc? I'm a MySQL user and I have been using following statements in MySQL Workbench :
(these statements are based on Select column names whose entries are not null)
SET group_concat_max_len = 4294967295;

SELECT GROUP_CONCAT(
 ' SELECT ',QUOTE(COLUMN_NAME),
 ' FROM   ( select * from table_name where s3_01 = ', coloumn1,' ) abc',
 ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL',
 ' HAVING COUNT(*)'
SEPARATOR ' UNION ALL ')
INTO   @sql
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA = DATABASE()
   AND TABLE_NAME = 'table_name';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Although it work in my workbench, I do not know how to make it work in java.
for example, I made following code:
String sql1 = "SET group_concat_max_len = 4294967295;";
String sql2 = " SELECT GROUP_CONCAT(' SELECT ',QUOTE(COLUMN_NAME), ' FROM   ( select * from ptc_weight where s3_01 = ',column1,' ) abc', ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL', ' HAVING COUNT(*)' SEPARATOR ' UNION ALL ') INTO   @sql FROM   INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'ptc_weight'; ";
String sql3 = " PREPARE stmt FROM @sql; ";
String sql4 = " EXECUTE stmt;";
String sql5 = " DEALLOCATE PREPARE stmt;";

String[] result = getResult(sql1+sql2+sql3+sql4+sql5);

public static String[][] getResult(String sql) {
        System.out.println(sql);
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String[][] resultTable = null;
        try {
            con = getCon();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData result = rs.getMetaData();
            int rowNum=0;
            // Go to the last row
            rs.last();
            rowNum = rs.getRow();
        // Reset row before iterating to get data
            rs.beforeFirst();
            int colNum = result.getColumnCount();

            resultTable = new String[rowNum][colNum];
            for(int itr1=0; itr1<rowNum; itr1++){
                rs.next();
                for(int itr2=0; itr2<colNum; itr2++){
                    resultTable[itr1][itr2] =     rs.getObject(itr2+1).toString();
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            dbclose(con, ps, rs);
        }// finally
        return resultTable;
    }

However, it does not work. I guess I made a wrong code for utilizing stored procedure, but I don't have any idea to deal with this problem.

A: CallableStatement callableStatement = null;

String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);

// execute getDBUSERByUserId store procedure
callableStatement.executeUpdate();

String userName = callableStatement.getString(2);
String createdBy = callableStatement.getString(3);
Date createdDate = callableStatement.getDate(4);

System.out.println("UserName : " + userName);
System.out.println("CreatedBy : " + createdBy);
System.out.println("CreatedDate : " + createdDate);

Here Is Full Example. You can modify your code as you need.
Simple one with less argument and with resultset :
CallableStatement cstmt = con.prepareCall("{call getEmployeeDetails(?, ?)}");
cstmt.setInt("employeeId", 123);
cstmt.setInt("companyId", 456);
ResultSet rs = cstmt.executeQuery();


text:
Q: How to format date by regions? I'm using ionic 2 with angular2. I'm trying to format date automatically for each country or language.
I format the date so:
{{dateVariable | date: 'dd/MM/y HH:mm'}}

But in the France the format is:
dd/mm/yyyy
in the Switzerland:
dd.mm.yyyy
In the US:
m/d/yyyy
And so for lot of countries.
How can I format automatically the date corresponding with the correct country or language?


text:
Q: Select Video from Library but Cannot Choose Swift I am trying to allow users to upload video to there profile. Users are able to choose videos from there phone but after clicking the choose button of the video, the app crashes and you get a fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb).
This is my code:
var objMoviePlayerController: MPMoviePlayerController = MPMoviePlayerController()
var urlVideo :NSURL = NSURL()

@IBOutlet weak var videoprofileView: UIImageView!
@IBOutlet weak var addvideoBtn: UIButton!

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
    urlVideo = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! NSURL
    self.dismissViewControllerAnimated(true, completion: nil)

    objMoviePlayerController = MPMoviePlayerController(contentURL: urlVideo)
    objMoviePlayerController.movieSourceType = MPMovieSourceType.Unknown
    objMoviePlayerController.view.frame = self.videoprofileView.bounds
    objMoviePlayerController.scalingMode = MPMovieScalingMode.AspectFill
    objMoviePlayerController.controlStyle = MPMovieControlStyle.Embedded
    objMoviePlayerController.shouldAutoplay = true

    videoprofileView.addSubview(objMoviePlayerController.view)

    objMoviePlayerController.prepareToPlay()
    objMoviePlayerController.play()
}

I receive a thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0) error from this line of code:
urlVideo = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! NSURL

Is there any way someone can help?
Thank you!


text:
Q: How to debug "Out of memory" from core? I got a core from g_ascii_strdown() which said it got error while doing malloc() and it crashed. So if the process hit out-of-memory case, is there a way to find out, from core and gdb, which part of program (caller, stack or thread) allocated memory ?
In other words, If I have the core file. What kind of information exist in core file that I can use to find out memory allocations ?

A: Generally speaking, malloc does not save any book-keeping information that would allow you to figure out what parts of your program allocated the memory. Since that information isn't in the live process, it won't be in the core-dump either.
If you want to figure that out, you'll need to use some malloc debug library/program instead. I'd normally recommend Valgrind for this, since it contains an excellent malloc debugger, but Valgrind only works on live processes. There might be some alternative malloc library that you can link against that keeps such information around in such a way that it would also be saved in core-dumps, but if there is, I can't say I know about it.

A: Smells like some memory leak. Use valgrind on some reproducible run exhibiting the issue (you'll need to start the program again under valgrind). You might not be able to find the issue post-mortem using the core dump alone
BTW, the glib running documentation also suggests calling g_mem_set_vtable (glib_mem_profiler_table) very early at startup (at the beginning of your main)
See also the Boehm conservative garbage collector
At last, it is not important to know which part of the memory exhausted. The available memory is a whole process thing. When running your program of pid 1234, use cat /proc/1234/maps & see proc(5)


text:
Q: Laravel File put permission denied on Windows I'm trying to save a file in windows and find a problem with File Class,
When I upload a file i get this error:

ErrorException in Filesystem.php line 111:
  file_put_contents(./upload/Bambui/2016): failed to open stream:
  Permission denied

and this is my function to save the file:
public function save()
    {
        $input = Input::only('empresa','tipo','data','data_pub','deliberacao','status','num_registro','publicacao','arquivo');

        $diretorio = $this->atas->checkAndCreateDirectory($input['empresa'], substr($input['data'], 6, 4));

        File::put($diretorio, $input['arquivo']);
   }

I give permission to all users in my wamp folder to write and read also.

A: Thx for help, I found myself the answer and change the File class to Storage and did this
Storage::putFileAs('pdf/'.substr($input['data'], 6, 4), $input['arquivo'], $filename);

and works


text:
Q: Resume my application on coming back from google maps i want to show one location in google map, for that i used the below code:
    String geo = maindata.getString("map");
    String uri = String.format(Locale.ENGLISH, geo, "", "");
    final Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    try {
       cordova.getActivity().runOnUiThread(new Runnable() {
         public void run() {
cordova.getActivity().startActivity(intent1);
}
     });
   }catch(Exception e){
        e.printStackTrace();
   }

The google map application is getting launched and it is showing proper location also,
BUT the problem is, when press back button then it is restarting my application.
whereas i want to resume from the lunching position

A: You can display particular location on google map  by using following code snippet:
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + lattitude+ ","
                            + longitude+ "+&mode=d");
                    Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                    if (isAppInstalled("com.google.android.apps.maps")) {

                        mapIntent.setClassName("com.google.android.apps.maps",
                                "com.google.android.maps.MapsActivity");
                    }
                    startActivity(mapIntent);

Here latitude and longitude belongs the location which you want to display on map.
 /**
 * helper function to check if Maps is installed
 **/

 private boolean isAppInstalled(String uri) {
        PackageManager pm = mActivity.getPackageManager();
        boolean app_installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        }
        return app_installed;
    }

And on back press from google map user will redirect to the same activity from which google map was launched.

A: You have to put your activity to the buttom of the stack and then launch the Google map app activity
do the following :
        String geo = maindata.getString("map");
String uri = String.format(Locale.ENGLISH, geo, "", "");
final Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
try {
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class); //Instead Of MainActivity you can add your Launching activity Name
    stackBuilder.addNextIntent(intent1);
   cordova.getActivity().runOnUiThread(new Runnable() {
     public void run() {
    startActivity(intent1);
 }
      });
    }catch(Exception e){
    e.printStackTrace();
   }


text:
Q: Why is my Java linked drop out stack not working? I am implementing a drop out stack using links in Java, but the last element is not dropping.
If the stack size is n, the bottom element should be lost when the n+1 element is pushed onto the top.
The last element (1) is being set to null, as I can see with the debugger, but not being removed from the stack (it is still printing).
Whats wrong?
       /**
        * DropOutStack represents a drop out stack
        * implementation using linked lists.
        */
       public class DropOutStack<T>
    {
        private int count; //counter var
        private LinearNode<T> top; //var for top of stack
        private int stackSize; //var for size of stack

       /**
        * Constructor for DropOutStack class. Sets the size
        * of stack initially.
        * @param stackSize
        */
        public DropOutStack(int stackSize)
        {
            count=0; //set count to 0.
            top=null; //top to null.
            this.stackSize=stackSize; //StackSize param set
        }
        /**
         * Pushes an element onto the stack.
         * @param element element to be pushed on stack.
         */
        public void push(T element)
        {
            LinearNode<T> node = new LinearNode<T>(element); //creates new LinearNode object.
            if(count==stackSize)
            {
                LinearNode<T> tempNode; //create obj ref null default
                tempNode=top;

                while(tempNode.getNext()!=null)
                {
                    tempNode=tempNode.getNext();
                }
                tempNode=null;
                count--;
                //stackSize=stackSize+1;
            }
            node.setNext(top);
            top=node;
            count++;
        }

       /**
        *Peek at the top element on the stack.
        *@return element element on the stack.
        */
        public T peek()
        {
            return top.getElement();
        }

       /**
        * Checks if the stack is empty.
        * @return true if stack is empty.
        */
        public boolean isEmpty()
        {
            return count<=0;
        }

       /**
        * Returns the size of the stack as an int.
        * @return count the var that counts elements.
        */
        public int size()
        {
            return count;
        }

       /**
        * Returns a string representation of the stack.
        * @return str string representing the stack elements.
        */
        public String toString()
        {
            String str ="";
            LinearNode<T> topTemp = top;
            while(topTemp!=null)
            {
                System.out.println(topTemp.getElement());
                topTemp = topTemp.getNext();
            }
            return str;
        }
    }

    /**
     * LinearNode class represents a node for a linked list.
     */
    public class LinearNode<T>
    {
        private LinearNode<T> next; //next obj ref null default
        private T element; // element var

       /**
        * Constructor for LinearNode. Empty node.
        */
        public LinearNode() //creates an empty node
        {
            element=null; //set element to null
            next=null; //set next to null

        }

       /**
        * Constructor overloaded for LinearNode.
        * @param element for node to store.
        */
        public LinearNode(T element)
        {
            this.element=element;
            next=null;

        }

      /**
       * Getter method. Gets the objects next ref.
       * @return next the node's next reference pointer.
       */
        public LinearNode<T> getNext()
        {
            return next;
        }

       /**
        * Setter method. Sets the next data for the node.
        *
        */
        public void setNext(LinearNode<T> node)
        {
            next=node;
        }

       /**
        * Gets the element.
        * @return element.
        */
        public T getElement()
        {
            return element;
        }

       /**
        * Sets the element.
        */
        public void setElement(T element)
        {
            this.element=element;
        }
    }

    /**
     * Main class, main method.
     */
    public class Main
    {
        public static void main(String[] args)
        {
            DropOutStack<Integer> stack = new DropOutStack<Integer>(5);
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);
            stack.push(5);
            stack.push(6);
            System.out.println(stack);
        }
    }
    //End of classes.

    ```

A: You have to revisit the push method of your DropOutStack.
At this codepart
LinearNode<T> tempNode; //create obj ref null default
tempNode=top;

while(tempNode.getNext()!=null)
{
    tempNode=tempNode.getNext();
}

you are iterating to the bottom of the stack and assign the object at the bottom of the stack to tempNode.
When setting tempNode to null, only tempNode is referring to null. The instance-variable next of the LinearNode next to the bottom is still referring to the bottom element.
Therefore, to achieve the bottom element to be "dropped", you have to find the next-to-bottom element and set next of this object to null.
To find the next-to-bottom element of the DropOutStack you can do something like this:
while(tempNode.getNext()!=null && tempNode.getNext().getNext() != null)
{
    tempNode=tempNode.getNext();
}

(I have insterted the first condition of the while loop to prevent a NullPointerException in case the size of the stack is only 1)
After this, you have to set next of this element to null:
tempNode.setNext(null);

I hope this explanation helps you to understand what is happening in your code.
Finally, here is a working push method for your DropOutStack:
  public void push(T element)
  {
    LinearNode<T> node = new LinearNode<T>(element); //creates new LinearNode object.
    if(count==stackSize)
    {
      LinearNode<T> tempNode; //create obj ref null default
      tempNode=top;

      while(tempNode.getNext()!=null && tempNode.getNext().getNext() != null)
      {
        tempNode=tempNode.getNext();
      }
      tempNode.setNext(null);
      count--;
    }
    node.setNext(top);
    top=node;
    count++;
  }

A: I believe you are making this much harder than necessary.  Here are a few suggestions.

*

*For your node class, make it a private, inner class. Inner classes are typically helper classes that are related in some way to the enclosing class.  So this is a perfect use for them.  It also allows you to use the type specifier T of the enclosing class without having to declare its own.  Using getters and setters is ok but not really necessary since this is a private class and you don't need to hide implementation details.

*When you are pushing a value onto the stack, there is no need to iterate over the stack if it has met its capacity. In fact, no iterations should be required anywhere except possibly in your toString method.  I would recommend two things:

*

*Don't update the count of items but still add one to the beginning for a push.

*maintain a tail node adjust this to point to the now next to last node. Set the reference to the last node to null for garbage collection.  This effectively removes an element and frees up a node.

*And probably most important is to design this on paper, showing nodes and forward (and backward if any) references.  It makes it easier to visualize how to modify the head and tail nodes and other ancillary fields.


text:
Q: tagging ec2 instances with python boto3 from argument list I got following script to tag ec2 instance from argument list
import string
import boto3
import sys
import argparse

instance_id = sys.argv[1]
tagname = sys.argv[2]
tagvalue = sys.argv[3]

ec2_client = boto3.client('ec2')

response = ec2_client.describe_instances()

#print(response)

instances = response['Reservations']

#print(instances)

#for instance in instances:
# print(instance['Instances'][0]['InstanceId'])

instance_ids = []
for instance in instances:
    instance_ids.append(instance['Instances'][0]['InstanceId'])
#     instance_ids.append(instance)
print(instance_ids)

tag_creation = ec2_client.create_tags(
    Resources =
        instance_ids,
   Tags = [
    {
        'Key': tagname,
        'Value': tagvalue
    }
    ]
)
#print(instance.InstanceId)
print(f'Tags successfully added to the instance {instance_id}')

I can run it like: python3 script.py instanceid1, instanceid2, tagname, tagvalue
but I want to print the output like this
Tags sucessfully added to the instance instanceid1
Tags sucessfully added to the instance instanceid2
etc....
right now the output is like this
Tags successfully added to the instance ['instanceid1', 'instanceid2']
ay idea


text:
Q: jQuery.ajax servlet return a file I'm pretty new to jQuery and ajax and i have a question.
In a jsp I call
function downloadDocument(documentId){
    var action = "attachment.do";
    var method = "downloadDocument";
    var url = action + "?actionType="+method+"&documentId=" + documentId;
    $.ajax({
          url: url,
          dataType: "json",
          type: 'POST',
          success: function(data){
              alert("downloaded!");
          },
          error: function (request, status, error) {
              alert(request.responseText);
            }
    });

then in the servlet I do
public void downloadDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException{

    AttachmentActionForm form = (AttachmentActionForm)actionForm;

    ServletOutputStream out = response.getOutputStream();

    try{
        // Get the downloadFileName, the name of the file when it will be downloaded by user
        String downloadFileName = "hello.txt";

        String  mimetype = "application/x-download"

        // Get the byte stream of the file
        FileInputStream in = new FileInputStream(Global.ATTACHMENTS_SHARED_FOLDER_PATH + downloadFileName);

        // Print out the byte stream
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
        }

        response.addHeader("Content-Disposition", "attachment; filename="+downloadFileName);
        response.setHeader("Content-Length", Integer.toString(length));
        response.setContentType(mimetype);

        in.close();
    }
    catch(Exception e){
        response.setContentType("text/text;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        System.out.println(e.getMessage());
        out.println(e.getMessage());
    }finally{
        out.flush();
    }
}

But in the ajax function, I never get a success, all the time I get the error message, even if the message is composed by the string inside of the file. What can I do?

A: Remove your dataType: "json", options and you will see some debug informations.
By the way, there is a jQuery option that meet you need:
$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); })

Taken from this answer: https://stackoverflow.com/a/9970672/1420186
EDIT:
Your JSP
function downloadDocument(documentId){
    var action = "attachment.do";
    var method = "downloadDocument";
    var url = action + "?actionType="+method+"&documentId=" + documentId;
    $.ajax({
          url: url,
          dataType: "text", // Change dataType to "text"
          type: 'POST',
          success: function(data){
              if (data == "FAIL") {
                  alert("File not found!");
              } else {
                  window.location.href = data; // Download the file
              }
          },
          error: function (request, status, error) {
              alert("The request failed: " + request.responseText);
          }
    });
}

In your Servlet, if the file is not exists, just return a "FAIL" string, else return the file URL.
Hope that helps.

A: dont use Ajax call use //use hidden form approach
<form action='../servletname' method='POST' id='formid'>
                <input type='hidden' value='' name='name' id='id'/>
                <input type='hidden' value=' ' name='name'  id='id' />
            </form>

on click of button submit form
$('#formid').submit();

in servlet
response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=filnemae.fileformat");

 ServletOutputStream out = res.getOutputStream();

write on ouput stream then close or flush
if you are sending large data through post update postsize in server.xml


text:
Q: jQuery validator and bootstrap.js - Notifications/Errors I'm exploring jQuery and bootstrap.js for a single page site. When not being strong in complex CSS and jQuery this can be a bit of a hassle. My goal is simple building on their hero-box example, which has a login form in the top right corner as seen here: http://twitter.github.com/bootstrap/examples/hero.html
I've got a working form for creating users, where i used this example: http://alittlecode.com/files/jQuery-Validate-Demo/
The goal is combining it with something like these notifications/alerts: http://www.w3resource.com/twitter-bootstrap/alerts-and-errors-tutorial.php
The relevant parts i have is:
$(document).ready(function(){
$.validator.addMethod('validChars', function (value) {

    var iChars = "!#$%^&*()+=-[]\\\';,/{}|\":<>?";

    for (var i = 0; i < value.length; i++) {
        if (iChars.indexOf(value.charAt(i)) != -1) {
         return false;
      }
    }

    return true;

    });

$('#login_form').validate(
        {
        rules: {
            login_email: {
            required: true,
            validChars:true,
            maxlength:50
            },
            login_password: {
            validChars:true,
            required: true
            }
        },
        highlight: function(input) {
            $(input).closest('.control-group').addClass('error');
        },
        unhighlight: function(input) {
            $(input).closest('.control-group').addClass('success');
        }
        });

});

And my form looks like this:
                        <form id="login_form" name="login_form"; class="navbar-form pull-right control-group" action="">

                        <input  class="span2 control-group"  placeholder="Email" name="login_email" id="login_email">

                        <input  class="span2 control-group"  placeholder="Password" name="login_password" id="login_password">

                        <button class="btn login" type="button" onclick="login();">Sign in</button>
                        <button class="btn requestor" type="button" onclick="createForm();" >Create new account</button>
                    </form>

Nothing at all happens, and I'm really out of ideas.
The ambition of notification or events are illustrative, my main concern is getting the validation connected to the form.
Thank you in advance!

A: The problem is that you are not giving the <input>'s a type. When they dont have a type, validate cannot address the input.
Validate evaluates the input-fields like this
 .validateDelegate("[type='text'], [type='password'], [type='file'], select, textarea, " +
                "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
                "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
                "[type='week'], [type='time'], [type='datetime-local'], " +
                "[type='range'], [type='color'] ",
                "focusin focusout keyup", delegate)

Input with no type does not get included. Therefore
<input type="text" class="span2 control-group"  placeholder="Email" name="login_email" id="login_email">

<input type="text" class="span2 control-group"  placeholder="Password" name="login_password" id="login_password">

will do the trick!


text:
Q: Measuring the divergence in centrality statistics for similar networks? I want to measure the similarity/divergence between the centrality of nodes in two publicly available word association networks.
In my analysis, we have a long list of nodes - 12,000 or so - and then we have (centrality measures) in-degree, betweenness, and PageRank data for (a) all of these nodes in Network A, and (b) only some of those nodes in Network B. Regarding only the nodes which have data available in both networks, I want to find out the divergence in the centrality of the nodes for each of the centrality measures.
I have considered using KL divergence, but I think that this is designed to be used for a probability distribution, so I'm not sure that it would work with my centrality measures.
I also wondered if simple correlation would be appropriate?
Extra points for suggesting an R package which can run your suggested method!


text:
Q: Facebook graph API to get statuses I'm using the Facebook graph API to get my most popular statuses as determined by the number of likes and comments that they have received. My code is as follows:
$feed = 'https://graph.facebook.com/me/statuses?access_token='.$access_token.'';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$numba = count($response);

print_r($response);

When I try to print out the contents of the array, it says that the array is empty. Does anyone have any ideas as to why this is returning an empty array?
Thanks,
Lance


text:
Q: Bootstrap Carousal is not working in my code I'm learning bootstrap these days. I am developing  a main page. But the carousal is not working. Please check the code and tell me which thing i'm missing in my code. I am just copy pasting the code of carousal from w3school. I don't know where i am missing. It'll be great if somebody can help me in this.
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap 101 Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="index.css" rel="stylesheet">

  Winston Churchill

“Success consists of going from failure to failure without loss of enthusiasm.”

A: You may not have downloaded the bootstrap stylesheet or javascript assets. The code is fine since you mentioned that you copy pasted the code directly from w3schools.
You need the following files downloaded and added to your folder:
css/bootstrap.min.css
js/bootstrap.min.js
OR
You can just paste the following in your  tag:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

And you can add the following at the end of your  tag:

Hope that helps!


text:
Q: Connecting MySQL DB to InfusionSoft Contacts We have a website (created using CodeIgnitor , which accepts users to signup using their Email or via LinkedIn. The data is stored in a MySQL backend. We also have incorporated InfusionSoft to work as a CRM and tracking of the users who signup.
My basic requirement thus is to create a trigger in PHP code, which allows a new contact to be created in InfusionSoft, after the user has registered.
(I want the contact information to be created in InfusionSoft, after the user has successfully signed up (registered) on the site and authenticated his Email ID. Else it will create too many false positives.)
Does anyone know of a API which allows me to automatically connect to InfusionSoft and transfer a selected set of fields into InfusionSoft from the MySQL DB Table?
I have looked up the InfusionSoft KB, but unable to come across any specific example which allows me to do this for selected fields:
https://novaksolutions.com/infusionsoft-api-gotchas/

https://developer.infusionsoft.com/code_samples

https://github.com/infusionsoft/API-Sample-Code/blob/master/PHP/ContactService-Sample.php

A: You should use the official InfusionSoft PHP-iSDK. It is the official wrapper for their API.
You should then read the developer documentation to get familiar with the API. Specifically, the Contact Service.
"Connecting" your MySQL database to your InfusionSoft database isn't how you should be thinking about it. Rather, you should be "firing" or running a function when an event happens.
When a user confirms their email in your application, simply fire a ContactService.addWithDupCheck function to add the user to the InfusionSoft database. This will vary, depending on your application; but should look something like the following:
<?php

$app->addWithDupCheck(
    array(
        'FirstName' => 'test', // Pulled from your MySQL Database
        'LastName' => 'test', // Pulled from your MySQL Database
        'Email' => 'test@test.com' // Pulled from your MySQL Database, or a $_GET variable
    ),
    'EmailAndName'
);

EDIT: The iSDK is being deprecated in about a month. You should use the new, official infusionsoft-php wrapper instead. It works in a similar fashion.


text:
Q: ValueError: Ciphertext with incorrect length. While implementing RSA with python I am trying to implement RSA in python to encrypt and then decrypt the text given in a file.
Here is the code I am trying to run:
from Crypto.PublicKey import RSA as rsa
from Crypto.Cipher import PKCS1_OAEP
import binascii

def encrypt(message, pukey):
    pukey = rsa.import_key(pukey)
    encryptor = PKCS1_OAEP.new(pukey)
    encmessage = encryptor.encrypt(message)
    encmessage = binascii.hexlify(encmessage)
    return encmessage

def decrypt(message, prkey):
    prkey = rsa.import_key(prkey)
    decryptor = PKCS1_OAEP.new(prkey)
    decmessage = decryptor.decrypt(message)
    return decmessage

def main():
    keypair = rsa.generate(1024)
    with open('abcd.txt', 'r') as f:
        mes = f.read().encode()
    pukey = keypair.publickey().exportKey()
    prkey = keypair.exportKey()
    enc = encrypt(mes, pukey)
    print(enc)
    dec = decrypt(enc, prkey)
    print(dec)
    input('')

if __name__ == '__main__':
    main()

This is the content of 'abcd.txt':
abcdef

And here is the error I am getting:
b'a53fd1fca73b07d5b18d77d4c95a8e40e002a34b53fcbbc3e1f7277721a7c2fa74be9a83cf6f273fcb98a6124905a40d8e6b34bc781ffdff7a09a68bdadf2eb5c5d4c56756c1249828dcb113fed832e7e5f50cd613f1d4458e8ebbc0d5f856669f9929cb8b70371ba657a74d1d41022c512a80c1d5ce492b852328de42be76e4'
Traceback (most recent call last):
  File "d:\STUDY\VIT MATERIAL\Semester 04\08 Project exhibition\Material\Temp_project\cryptRSA1.py", line 39, in <module>
    main()
  File "d:\STUDY\VIT MATERIAL\Semester 04\08 Project exhibition\Material\Temp_project\cryptRSA1.py", line 34, in main
    dec = decrypt(enc, prkey)
  File "d:\STUDY\VIT MATERIAL\Semester 04\08 Project exhibition\Material\Temp_project\cryptRSA1.py", line 23, in decrypt
    decmessage = decryptor.decrypt(message)
  File "C:\Users\dhruv\AppData\Roaming\Python\Python39\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 167, in decrypt
    raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.

I am very new to this module and cryptography in general. Please suggest the changes I need to do to make this work.


text:
Q: How to make a link show after a certain amount of clicks on a word? I am a beginner to javascript. I have a function where you click on a word and a series of other words follows after every time you click on the first word. I would like for a link to show once all the words in the string are shown (from clicking on the word exactly 25 times). I can't seem to figure out how to get the link to show after the word is clicked.
here is my code.

    click on this sentence to show the string of  words

I'm trying to learn more about this and any advice or explanation would be very appreciated! thank you so much.

A: Well, we where all beginners at one time.
I refactored your code, since it wasn't working the way it was written.

var e = { }; // Global variable for elements
var currentWord = -1; // Global variable indicating current word. (-1 = before first word)
// Global variable with words
var myWords =[
  "word1", "word2", "word3", "word4", "word5",
  "word6", "word7", "word8", "word9", "word10",
  "word11", "word12", "word13", "word14", "word15",
  "word16", "word17", "word18", "word19", "word20",
  "word21", "word22", "word23", "word24", "word25"
];
//function that adds the text after all words has been shown
function addText() {
  var text1 =document.createElement('div');
  var link = document.createElement('a');
  link.href = 'nightsky.html';
  link.textContent = 'a few million years in space  is like, how many years on earth?';
  text1.appendChild(link);
  text1.style.padding ="20px";
  e.container.appendChild(text1);
}

function update() {
  // First we must add one to the currentWord variable. There are
  // a couple of ways to do that:
  // pre-increment:  ++currentWord;
  // post-increment:  currentWord++;
  // assignment operator: currentWord += 1;
  // calculate and assign : currentWord = currentWord + 1;
  currentWord += 1;

  // Check if all words has been shown
  if (currentWord < myWords.length) {
    // Show next word
    var word = document.createTextNode( myWords[currentWord] + ' ' );
    e.words.appendChild(word);
  } else {
    // Add text
    // Only add the text is currentWord is identical to myWords.length
    if ( currentWord == myWords.length) addText();
  }
}

function loaded() {
  // Get relevant elements and store them in the variable e
  e.container = document.getElementById('container');
  e.words = document.getElementById('words');
  e.hot = document.getElementById('hot');
  // Add the click-handler to the hot element
  e.hot.addEventListener('click',update);
}

loaded(); // Should be called 'onload' or DOM-ready

  click on this sentence to show the string of words


text:
Q: How to check Postgres version compatibility with spring data jpa? I have been using Postgres version 10.6 in my spring-boot project but now we are going to upgrade the Postgres version from 10.6 to 13.6. how should I check the version compatibility of the Postgres 13.6 with my current code? I am using spring-data-jpa.

A: It comes down to the version of your spring-data-jpa dependency in your project.
As a quick reference, latest spring-data-jpa v2.7.x uses the following PostgreSQL jdbc version:
<postgresql>42.2.19</postgresql>

On another hand, recent pgjdbc versions are all compatible with PostgreSQL 8.2 and higher, and Java 8 (JDBC 4.2) and higher as per this link
Therefore, it is all about checking the version of spring-data-jpa you are using, and upgrading to PostgreSQL 13 should prove no issues when you do.


text:
Q: Criar um executável Bom dia, eu fiz uma aplicação em C# recentemente mas ainda só está na forma de código e precisava de criar um executável ! Mas nunca fiz isso, não sei como fazer.
Alguém pode ajudar ? Obrigado !

A: Clique em build -> publish
Uma tela aparecerá para você configurar como será feita a instalação no PC do cliente, configure da forma que te atenda e publique. Será criado um Setup, um Manifest e uma pasta com o nome Application files onde você configurou a saída. No PC do cliente é só você executar a forma de instalação que você configurou e seu programa será instalado automaticamente.
Se você precisa apenas do executável, pode também consegui-lo na pasta visualStudio20XX -> Projects ->  ->  -> bin -> release, mas ao executá-lo ele não será instalado

A: Compile seu projeto no visual studio:
BUILD > BUILD SOLUTION ou Tecla de atalho, F6
o Executável será gerado na pasta:
[Pasta do seu projeto]\bin\Debug


text:
Q: Save CvSeq to an array I am a bit lost in OpenCV docs, I would like to save CvSeq returned by cvFindContours to an array, from what I understand it will return a seq of CvContour s but i couldn't find what it contains? which parts of it should I save to that later I can later I can iterate through it and say call cvBoundingRect etc.

A: A CvContour is a struct with the same fields as a CvSeq, plus a few others, the most important of which is a CvRect rect (see include/opencv/cxtypes.h). So it really boils down to what a CvSeq is.
There is a file called opencv.pdf that comes with the OpenCV sources, and in p. 138 (for OpenCV 2.1) it says that CvSeq is defined as follows:
#define CV_SEQUENCE\_FIELDS()
    int flags; /* micsellaneous flags */ \
    int header_size; /* size of sequence header */ \
    struct CvSeq* h_prev; /* previous sequence */ \
    struct CvSeq* h_next; /* next sequence */ \
    struct CvSeq* v_prev; /* 2nd previous sequence */ \
    struct CvSeq* v_next; /* 2nd next sequence */ \
    int total; /* total number of elements */ \
    int elem_size;/* size of sequence element in bytes */ \
    char* block_max;/* maximal bound of the last block */ \
    char* ptr; /* current write pointer */ \
    int delta_elems; /* how many elements allocated when the sequence grows
    (sequence granularity) */ \
    CvMemStorage* storage; /* where the seq is stored */ \
    CvSeqBlock* free_blocks; /* free blocks list */ \
    CvSeqBlock* first; /* pointer to the first sequence block */

typedef struct CvSeq
{
    CV_SEQUENCE_FIELDS()
} CvSeq;

Let's say you call cvFindContours like this:
cvFindContours(img, storage, &contours, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

, where contours will be pointing to the first contour after calling cvFindContours. If you want to get its bounding rectangle, you simply pass it to cvBoundingRect. The next contour in the sequence can be accessed through contours->h_next. In the case of contour trees, that is, when a contour can be inside another contour in the image, you can access the first inner contour of the current contour through contours->v_next. The next inner contour, if it exists, would be contours->v_next->h_next, and so forth.
If you want to convert a sequence to an array you can use cvCvtSeqToArray.
You can also use the C++ interface starting from OpenCV 2.0 which seems to be nicer to use. For instance, the CvSeq** contours parameter to cvFindContours becomes vector<vector<Point> >& contours.


text:
Q: Vectorizing terms inside a column of strings in scikit-learn I have a table-like dataset with the following structure: each line has, as columns:
RecipeName: "Guacamole"
Ingredients: "Avocado, vinegar, tomato"
PreparationTime: 10

I want to convert this to a bag-of-words-type representation in a pandas DataFrame, so that this line becomes
(column names) RecipeName Avocado Broccoli Chocolate Tomato Vinegar Zucchini
               Guacamole      1       0        0        1      0        0
               WeirdCacao     0       0        1        1      0        0

(I'm obviously able to take a DataFrame with a single Ingredients column and convert it into a dict of lists:
 recipe_dict = {recipes.ix[m]['RecipeName']:recipes.ix[m]['Ingredients'].split(',') for m in recipes.index}

But I'm not able to use CountVectorizer on that. Maybe that's not even the best way to handle it. )

A: I brute-forced an answer to this specific problem; but I'd still like to know how to do this with scikit-learn, as I might want to switch to tf-idf later, for example.
Given the dict obtained by
recipe_dict = {recipes.ix[m]['RecipeName']:recipes.ix[m]['Ingredients'].split(',') for m in recipes.index}

We do the following:
from functools import reduce
ingredients = reduce(lambda x, y: x+y, recipe_dict.values())

to obtain a list of all ingredients and then loop
for j in ingredients:
    recipes[j] = recipes['RecipeName'].apply(lambda i: 1 if j in recipe_dict[i] else 0)


text:
Q: jinja2.exceptions.TemplateNotFound I have the following structure in my project :
\myapp
    application.py
    \include
       hello.html
so the folder myapp contains application.py and the folder include.
the folder include contains hello.html.
the following code :
application.py
#!/usr/bin/python 2.7.6
# -*- coding:utf-8 -*-
import os
import sys
from flask import Flask,render_template
import psycopg2
app = Flask(__name__)

@app.route('/')
def fihoum():
    conn = psycopg2.connect(database="carto", user="postgres",
           password="daed5Aemo", host="192.168.12.54")
    cur = conn.cursor()
    cur.execute("SELECT * FROM carto.\"BADGES_SFR\"")
    rows = cur.fetchall()
    return render_template('hello.html', titre="Données du client
   BADGES_SFR !",mots=rows)

if __name__=="__main__":
    app.run(host=os.getenv('IP', '0.0.0.0'),
            port=int(os.getenv('PORT',5000)),debug=True)

the following code hello.html :
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>{{ titre }}</title>

{{ titre }}

        {% for mot in mots %}

{{ mot }}

        {% endfor %}

THE PROBLEM: Whene I run the program application.py I have this mistake :
jinja2.exceptions.TemplateNotFound
TemplateNotFound: hello.html
thanks for your help

A: The template folder defaults to templates\; so you should rename include to templates.


text:
Q: cURL Scraping Wrong Webpage I am attempting to scrape a webpage that requires a login using curl in the Mac Terminal but can't seem to get it right. I have a cookies.txt file with my login info that I am reading into the command, but I can't get it to scrape the intended page. When I run
curl -b /Users/dwm8/Desktop/cookies.txt -o /Users/dwm8/Desktop/file.txt https://kenpom.com/team.php?team=Duke&y=2002
the contents of file.txt are the webpage data from https://kenpom.com/team.php?team=Duke instead of https://kenpom.com/team.php?team=Duke&y=2002. Is there a fix for this? Thanks for the help.

A: You need to wrap url part in quotes.

A: & is a shell metacharacter that separates commands and indicates the command before it should be run in the background. So, your command:
curl ... https://kenpom.com/team.php?team=Duke&y=2002

gets parsed as two separate commands:
curl ... https://kenpom.com/team.php?team=Duke &    # The & means run curl in the background
y=2002    # This just sets a shell variable

In order to get the shell to treat & as part of the argument to curl rather than a command separator, you need to quote it (either single- or double-quotes would work) or escape it with a backslash:
curl ... 'https://kenpom.com/team.php?team=Duke&y=2002'
curl ... "https://kenpom.com/team.php?team=Duke&y=2002"
curl ... https://kenpom.com/team.php\?team=Duke\&y=2002

Oh, and notice that I also escaped the ? in that last example? That's because ? is also a shell metacharacter (specifically, a wildcard). In this case it probably wouldn't cause any trouble, but it's safest to quote or escape it just in case. And since it's hard to keep track of exactly which characters can cause trouble, I'll recommend quoting instead of escaping, and just quoting everything that you're at all unsure about.