text:
Q: JS: Add easing to moving element I'm working on a site with one central element and I would like for this element to interact with the cursor. This is what I have so far:

var hello = document.getElementsByClassName("hello");
document.onmousemove = function() {
  var x = event.clientX * 100 / window.innerWidth + "%";
  var y = event.clientY * 100 / window.innerHeight + "%";

  for(var i=0;i<hello.length;i++) {
    hello[i].style.left = x;
    hello[i].style.top = y;
    hello[i].style.transform = "translate(-" + x + ",-" + y + ")";
  }
}
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: black;
}

.hello_wrapper_wrapper {
  position: absolute;
  background-color: none;
  /* background-color: blue */
  width: 35vw;
  /* This object has to be larger than: width: 300px; height: 150px; */
  height: 35vh;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.hello_wrapper {
  position: relative;
  background-color: none;
  width: 35vw;
  height: 35vh;
}

.hello {
  position: absolute;
  background-color: white;
  width: 300px;
  height: 150px;
  text-align: center;
  line-height: 150px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<!doctype html>

  <meta charset="UTF-8">
  <title> 0 </title>
  <link rel="stylesheet" href="style.css">

        Hello World!

Note: The main element is inside of a: wrapper (width: 35vw; height: 35vh;), the main element, called: hello has the following dimensions: hello (width: 300px; height: 150px;). – hello has to be bigger than the wrapper for this to work, so I would change the size of the preview-window, when looking at the fiddle.
I would like to add some sort of easing to the element, I don't want it to jump around or move too quickly, I would like for it to be a bit sluggish, follow the curser, but drag a little bit behind. Also, when the curser is not hovering over the page, the page is reloaded and the curser then enters the page, the box jumps and, again, I'd just like to make this more smooth.
I would very much appreciate it, if someone could help me with this. Thank you!
Credits: https://www.youtube.com/watch?v=AixAmLWzXYg (This is a tutorial I followed.)

A: You can use CSS transition properties to make sure it is smooth.
I tried adding transition-delay: 10ms, transition-timing-function: ease to the hello element CSS. More info here: https://css-tricks.com/ease-out-in-ease-in-out/ and here https://www.w3schools.com/css/css3_transitions.asp
   * {
    padding: 0;
    margin: 0;
}

body {
    background-color: black;
}

.hello_wrapper_wrapper {
    position: absolute;

    background-color: none; /* background-color: blue */
    width: 35vw; /* This object has to be larger than: width: 300px; height: 150px; */
    height: 35vh;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.hello_wrapper {
    position: relative;

    background-color: none;
    width: 35vw;
    height: 35vh;
}

.hello {
    position: absolute;

    background-color: white;
    width: 300px;
    height: 150px;
    text-align: center;
    line-height: 150px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transition-delay: 10ms;
    transition-timing-function: ease;

    }

Now to make sure the box doesn't move you can try with onmouseout event listener on the body.
Try this javascript code to make the transition smooth when the mouse leaves the window:
var hello = document.getElementsByClassName("hello");

document.onmouseleave = function(){
for(var i=0;i<2;i++){
    hello[i].style.left = '50%';
    hello[i].style.top = '50%';
    hello[i].style.transform = "translate(-50%,-50%)";
  }
  document.removeEventListener('onmousemove')

}

document.onmouseenter = function(){
    setTimeout(function(){
  document.onmousemove = function(){
    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";

    for(var i=0;i<2;i++){
        hello[i].style.left = x;
        hello[i].style.top = y;
        hello[i].style.transform = "translate(-"+x+",-"+y+")";
    }
}
  },1000)

}

A: We can just use CSS transitions!.
Added as example transition: transform 0.6s cubic-bezier(0.32, 0, 0.67, 0) to your css. This one will bring back the element in the center 0.6s after a mouse move.
See https://easings.net/ for many examples of transitions.
Similar answer

var hello = document.getElementsByClassName("hello")[0];
document.onmousemove = function() {
  var x = event.clientX * 100 / window.innerWidth + "%";
  var y = event.clientY * 100 / window.innerHeight + "%";
  hello.style.left = x;
  hello.style.top = y;
  hello.style.transform = "translate(-" + x + ",-" + y + ")";
}
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: black;
}

.hello_wrapper_wrapper {
  position: absolute;
  background-color: none;
  /* background-color: blue */
  width: 35vw;
  /* This object has to be larger than: width: 300px; height: 150px; */
  height: 35vh;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.hello_wrapper {
  position: relative;
  background-color: none;
  width: 35vw;
  height: 35vh;
}

.hello {
  position: absolute;
  background-color: white;
  width: 300px;
  height: 150px;
  text-align: center;
  line-height: 150px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: transform 0.6s cubic-bezier(0.32, 0, 0.67, 0)
}
<!doctype html>

  <meta charset="UTF-8">
  <title> 0 </title>
  <link rel="stylesheet" href="style.css">

        Hello World!


text:
Q: php guzzle request file upload and send body I want to send file and body HTTP request with guzzle but API not responding gets bad request error
ı had an error from response
have two ,
response for status 400
response getReasonPhrase()  ı get bad request
<?php

require_once "vendor/autoload.php";

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Psr7\Request;

$file="yeni.zip";
$hash=md5_file($file);

$binary=file_get_contents($file);

$soapbody='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:get="http://fitcons.com/earchive/invoice">
         <soapenv:Header/>
         <soapenv:Body>
         <get:sendInvoiceRequestType>
         <senderID>6310700163</senderID>
         <receiverID>53077224954</receiverID>
         <docType>XML</docType>
         <fileName>newarsiv.xml</fileName>
         <hash>'.$hash.'</hash>
         <binaryData>'.$binary.'</binaryData>
         </get:sendInvoiceRequestType>
         </soapenv:Body>
</soapenv:Envelope>';

$client=new Client();

$url="https://earsivwstest.fitbulut.com/ClientEArsivServicesPort.svc";

$options=[
    'auth' => ['blabla', 'blabla'],
    'headers' => ['Content-Type' => 'text/xml','cache-control'=>'no-control'],
    'SOAPAction'=>'sendInvoice',
    'body' => $soapbody,
    'http_errors'=>false,
    'multipart' => [
        [
            'name'  =>"yeni.zip",
            'Filename'  => "yeni.zip",
            'contents'      => fopen($file, 'r'),
            'headers'       =>  [
                'Content-Type' => 'application/zip',
                'Content-Disposition'   => 'form-data; name="yeni.zip"; filename="yeni.zip"'
                ]

            ]

]

];

$response = $client->request('POST', $url,$options);

echo $response->getReasonPhrase()."\n".$response->getStatusCode();

var_dump($response->getBody()->getContents());

result

,Internal Server Error 500string(698) "a:ActionNotSupportedThe message with Action '' cannot be processed at the
  receiver, due to a ContractFilter mismatch at the EndpointDispatcher.
  This may be because of either a contract mismatch (mismatched Actions
  between sender and receiver) or a binding/security mismatch between
  the sender and the receiver.  Check that sender and receiver have the
  same contract and the same binding (including security requirements,
  e.g. Message, Transport,
  None)."
  NKolayOfiss-MacBook-Pro:soapguzzle nkolayofis$ php index.php  ,Bad
  Request 400string(0) ""

A: You cannot use body and multipart in the same time. multipart internally forms the body, and body is the option to set the body of your HTTP request directly. It just doesn't make any sense to mix them together.
In your example you should read the API's documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The set of $\Delta_1$ indices Is the set of Godel numbers of $\Delta_1$ formulae itself $\Delta_1$ definable (i.e., computable)?

A: The answer is no, in either of the cases Trevor outlined.
For example, for a fixed $e$, consider the formulas $p(x)\equiv$"There is some $n$ such that $\Phi_e(x)[n]\downarrow=1$" and $q(x)\equiv$"There is some $n$ such that $\Phi_e(x)[n]\downarrow=0$." These formulas are both $\Sigma^0_1$, and they define complementary sets if and only if $\Phi_e$ is a total $\lbrace 0, 1\rbrace$-valued function. So if the set of indices for pairs of $\Sigma^0_1$-formulas defining complementary sets was $\Delta^0_1$, we'd have that the set of indices for total $\lbrace 0, 1\rbrace$-valued functions is computable, which is a clear contradiction.
Something similar will work in the other case Trevor described. The basic idea is that the set of indices of pairs of $\Sigma^0_1$-formulas which PA (say) proves are complementary is c.e. (just search through proofs) but not computable. To flesh that out, for $e$ a natural number, consider the $\Sigma^0_1$-formulas $p_e(x)\equiv$"$x\not=x$" (defining $\emptyset$) and $q_e(x)\equiv$"$\exists s(e\in W_{e, s}\vee x=2)$." These formulas are complementary iff $e\in W_e$, and moreover are complementary iff PA proves that they are complementary (I guess I'm assuming soundness of PA here, but that's not a huge assumption to make). But if the indices for PA-provably complementary $\Sigma^0_1$-formulas were $\Delta^0_1$, we could use the above setup to compute the set of $e$ such that $e\in W_e$ - i.e., the Halting Problem. So the answer is again no. (Note that the only properties of PA that are being used here are soundness, and the fact that it is sufficiently strong to express and prove basic facts about c.e. sets.)


text:
Q: Prolog define orthogonal constaint I am quite new in the Prolog magical universe, but it seems to be very powerful to solve my problem.
I have two basis [i0,j0,k0] and [i1,j1,k1]. Then we have an orthogonal constraint between all elements of the same basis (i0 is orthogonal to j0, j0 is orthogonal to k0, and k0 is orthogonal to i0).
I would like to find the set of new orthogonal constraint to add between elements of the first basis and the second one such that the two basis are aligned/equal. Then it could be interesting to find the minimal number of constraints (which seems to be 3 when you think about it).
I have working a start of code (but you can give me tips and tricks to have a more efficient code) but then I'm stuck when I need to express the goal of my problem ...
Let's define define ortho/1 such that all the elements in the list given to ortho are ortho one to another. Then we could define our two basis:
ortho([i0,j0,k0]).
ortho([i1,j1,k1]).

I add then the following rule to deduce ortho([X,Y]) from ortho([X,Y,Z]) predicates:
ortho(L) :- ortho(B), unique(L), unordered_subset(B,L).

This could be explained as we need to find an existing basis B such that L is a sublist of B and all elements of L are distinct. Some tests are leading to:
?- ortho([i0,j0]).
true.
?- ortho([k0,i0]).
true.
?- ortho([i0,i0]).
false.

Here is the implementation of unique/1, subset/2 and unordered_subset/2 I used in my program (Found on StackOverflow, don't know if there is better but it seems to work).
% unique/1 detect list formed by unique elements
unique([]).
unique([X|Xs]) :- \+ memberchk(X, Xs), unique(Xs).

% subset/2 (set, subset) true if subset is a subset of set in the same order
subset([], []).
subset([E|Tail], [E|NTail]):-
    subset(Tail, NTail).
subset([_|Tail], NTail):-
    subset(Tail, NTail).

% unordered_subset/2 (set, subset) true if subset is a subset of set
unordered_subset(Set, SubSet):-
    length(Set, LSet),
    between(0,LSet, LSubSet),
    length(NSubSet, LSubSet),
    permutation(SubSet, NSubSet),
    subset(Set, NSubSet).

The finality is to see if the two basis are equal. To do so, I defined equal/2 and collin/2 such that:
% collin/2 check the collinearity of two vectors
collin(A,B) :-
    ortho([X,Y,A]), ortho([X,B]), ortho([Y,B]).

% equal/2 check basis equals
equal([],[]).
equal([H1|T1],[H2|T2]) :-
    collin(H1,H2),
    equal(T1,T2).

collin/2 is based on the fact that two vectors A and B are collinear if it exists X and Y such that [X,Y,A] is a basis and X and Y are both orthogonal to B. And equal/2 is the fact that two basis are equal if the vectors taken in the good order are collinear. (By commutativity Prolog should be able to find this good order).
To find a solution to my problem, I think there is something about finding a list of pairs T of length N, with N as low as possible, such that for all pair P=X-Y in T, ortho(X,Y) implies equal([i0,j0,k0], [i1,j1,k1]).
Could you help me to express this rule ? (And eventually to have a better code :) )

A: Your unique/1 only works when the list has been fully populated - which violates the "fail fast" principle of performant code. Should check at the point that the individual list elements become instantiated - which can be done using freeze.
The most correct unique definition that I've seen is all_dif in https://stackoverflow.com/a/31724022/ (because it works when the list's tail is later extended).


text:
Q: Using VLOOKUP with two lookup values while using IMPORTRANGE to merge three Google Sheets I have created three google sheets wherein one google sheet is designed as the Masterfile for the data present on the two other google sheets.
I was able to merge two google sheets data into the Masterfile using the formula below:
=QUERY({IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs","Sheet1!A2:H");IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0","Sheet1!A2:H")},"WHERE Col2 IS NOT NULL ORDER BY Col1 ASC")

However, what I want to do right now is to import data in another using IMPORTRANGE while using VLOOKUP based on two lookup values. Here's the formula I've used on that specific column and it returns me an error of "VLOOKUP evaluates to an out of bounds range":
=ARRAYFORMULA(VLOOKUP(A2&" "&B2, {IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", {Sheet1!$A$2:$A&" "&Sheet1!$B$2:$B,Sheet1!$F$2:$F});IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0", {Sheet1!$A$2:$A&" "&Sheet1!$B$2:$B,Sheet1!$F$2:$F})},5,false))

I was able to test the same formula while only using one lookup value please see the working formula below for only one lookup value:
=ARRAYFORMULA(VLOOKUP(A2, {IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!A2:F");IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0", "Sheet1!A2:F")},6,false))

A: multiranges are not supported within importrange. use:
=ARRAYFORMULA(IFNA(VLOOKUP(A2&" "&B2, {
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!A2:A")&" "&
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!B2:B"),
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!F2:F")}, 2, )))

for two importranges it would be:
=ARRAYFORMULA(IFNA(VLOOKUP(A2&" "&B2, {
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!A2:A")&" "&
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!B2:B"),
 IMPORTRANGE("1JY2OMkBa926_P_PJABMxFqctfnRQAPAknkvMzFn7lFs", "Sheet1!F2:F");
 IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0", "Sheet1!A2:A")&" "&
 IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0", "Sheet1!B2:B"),
 IMPORTRANGE("12I5uRLkS_YjgWPdf_Kx5orQxX876XruW9Q9kDrECJi0", "Sheet1!F2:F")}, 2, )))

also make sure that you run each unique importrange first to connect your sheets by allowing access before you use any of above formulae


text:
Q: Which recommendation algorithm should be used? Favorite data of multiple users (no more than 10000) are as follows:
user1:  url_ 1, url_ 5, url_ 13, url_ 104, ....
user2:  url_ 3, url_ 20, url_ 104, url_ 638, ....
user3:  url_ 11, url_ 13, url_ 57, url_ 104, ....
....
userN: url_ 3, url_ 310, url_ 517, url_ 638, ....

The number of favorite url for each user is generally tens to hundreds, and at most not more than 1000, but the possibility of url is unlimited.
All user are filtered by conditions in advance. So the repeatability of each user's favorite url is estimated to be between 3% and 20%.
What algorithm is most suitable for calculating the similarity between users? Thanks.

A: You are looking for the similarity between two unordered subsets (no duplicates) from the same universe. The most common distance measure for this use case is the Jaccard similarity coefficient.


text:
Q: Database not being updated with 'Edit user form' I have an administrator page that allows admins to edit details of the users who have just registered. Everyone's 'access levels' are defaulted to 4 and it is up to the admin to change their access level to '2' for a tutor or '3' for a student.
adminpage.php

 New Members

                    <?php

                    $query = "Select * FROM users WHERE accessLevel = '4'";

                    $result = mysqli_query($conn, $query);
                    if (mysqli_num_rows($result) > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            $userID = $row['userID'];
                            $firstName = $row['firstName'];
                            $lastName = $row['lastName'];
                            $emailAddress = $row['emailAddress'];
                            $accessLevel = $row['accessLevel'];

                            echo
                            "

 User ID: $userID

 User Name: $firstName $lastName

 Email: $emailAddress

 Access Level: $accessLevel

                            Edit Details

";
                        }
                    }

editUser.php
    <?php
    include ('connection.php');
    $getID = $_GET['getUser'];
    $query = "Select * From users where userID ='$getID'";
    $return = mysqli_query($conn, $query);
    ?>

 <?php
                include ('connection.php');
                $userQuery = "Select * FROM users WHERE userID = '$getID'";
                $return = (mysqli_query($conn, $userQuery));

                if (mysqli_num_rows($return) > 0) {
                    while ($row = mysqli_fetch_assoc($return)) {

                        $userID = $row['userID'];
                        $firstName = $row['firstName'];
                        $lastName = $row['lastName'];
                        $emailAddress = $row['emailAddress'];
                        $password = $row['password'];
                        $accessLevel = $row['accessLevel'];
                    }

                    echo
                    "
 Edit Profile for $firstName $lastName
;

                    <form class ='form' method ='POST' name ='Update' action= 'updatedProfile.php?getid=$getID'>
                    <fieldset>
                    <legend>Update Profile Details</legend>

                    UserID
                    <input type = 'number' value='$userID' id ='userID' placeholder = 'UserID'>

                    First Name
                    <input type = 'text' value='$firstName' id = 'firstName' placeholder = 'FirstName'>

                    Last Name
                    <input type = 'text' value = '$lastName' id='lastName' placeholder = 'Last Name'>

                    Email
                    <input type = 'email' value='$emailAddress' id ='emailAddress' placeholder = 'emailAddress'>

                    Password
                    <input type = 'password' value='$password' id ='password' placeholder = 'Password'>

                    Access Level
                    <input type = 'number' value='$accessLevel' id ='accessLevel' placeholder = 'Access Level'>

                    <button>Update Details</button>

                    </fieldset>
                    </form>

";
                }
                ?>

                <?php
                include("connection.php");

                if (isset($_POST['userID'])) {
                    $userID = $_POST['userID'];
                } else {
                    $error = true;
                    echo "big error";
                }
                if (isset($_POST['emailAddress'])) {
                    $emailAddress = $_POST['emailAddress'];
                } else {
                    $error = true;
                }
                if (isset($_POST['firstName'])) {
                    $firstName = $_POST['firstName'];
                } else {
                    $error = true;
                }
                if (isset($_POST['lastName'])) {
                    $lastName = $_POST['lastName'];
                } else {
                    $error = true;
                }

                if (isset($_POST['accessLevel'])) {
                    $accessLevel = $_POST['accessLevel'];
                } else {
                    $error = true;
                }

                if (isset($_POST['password'])) {
                    $password = $_POST['password'];
                } else {
                    $error = true;
                }

                if (!$error) {
                    //$update = "UPDATE `rdonaghy08`.`users` SET userID='$userID', `firstName` = '$firstName', `lastName` = '$lastName', `password` = '$password', `accessLevel` = '$accessLevel' WHERE `users`.`userID` = '$getID'";
                    $update = "UPDATE users SET userID='$userID', firstName = '$firstName', lastName = '$lastName', password = '$password', accessLevel = '$accessLevel' WHERE userID = '$getID'";
                    $return = mysqli_query($conn, $update) or die(mysqli_errno($conn));
                }

And finally, updatedProfile.php
<?php
include 'connection.php';
$getid = $_GET['getid'];

if (isset($_POST['userID'])) {
    $userID = $_POST['userID'];
} else {
    $error = true;
}
if (isset($_POST['emailAddress'])) {
    $emailAddress = $_POST['emailAddress'];
} else {
    $error = true;
}
if (isset($_POST['firstName'])) {
    $firstName = $_POST['firstName'];
} else {
    $error = true;
}
if (isset($_POST['lastName'])) {
    $lastName = $_POST['lastName'];
} else {
    $error = true;
}

if (isset($_POST['accessLevel'])) {
    $accessLevel = $_POST['accessLevel'];
} else {
    $error = true;
}

if (isset($_POST['password'])) {
    $password = $_POST['password'];
} else {
    $error = true;
}

if (!$error) {
    $update = "UPDATE users SET userID='$userID',
    emailAddress='$emailAddress',firstName='$firstName', lastName='$lastName'accessLevel ='$accesslevel',password='$password' WHERE userID = '$getid'";
    $return = mysqli_query($conn, $update) or die(mysqli_errno($conn));
} else {
    "something wrong";
}

$returnQuery = "SELECT * FROM users WHERE userID='$getid'";
$return = mysqli_query($conn, $returnQuery);

if (mysqli_num_rows($return) > 0) {
    while ($row = mysqli_fetch_assoc($return)) {
        $userEmail = $row['emailAddress'];
        $userID = $row['userID'];
    }
}

$content = "

            Please use the following link to login in with your
                        new details:
            http://xxxxxxxxxxxxxxx@xxxxxxx.co.uk

                        Please make a note of your new User name,
                        you will need this to log in to CaterVLE= $userID
            ";

$send = $userEmail;
$subject = "Log in Details";
$headers = "Content-type-type: text/html";

mail($send, $subject, $content, $headers);
?>

I know that is a lot of code to look at, I am seriously not looking anyone to do this for me, I just want to know if I am missing something simple or if I can be pointed in the right direction. The email gets sent OK, its just that the database never gets updated, specifically, the access level never gets updated, say from default 4 to 3.
Anyone able to help? Many Thanks!


text:
Q: Google Cloud - Stack recommendation for Tomcat/PostgreSQL/HTTPS/SFTP site? This is my first attempt at looking into cloud hosting and I'm feeling like a complete idiot. I have always had my own dedicated server with which I would would remote in and install/manage everything myself. So this cloud thing is completely new for me. I just can't seem to grasp basic things... like how I would get Tomcat and PostgreSQL installed in a way that they could talk to each other or get my domain and SSL cert on there, etc.
If I could just get a feel for where I should start, then I could probably calculate my costs and jump into the free trial where hopefully things will click for me.
Here are my basic, high-level requirements...

*

*My web app running in Tomcat over HTTPS

*Let's say approximately 1,000 page views per day

*PostgreSQL supporting my web app.

*Let's say approximately 10GB database storage

*Throughout the day, a fairly steady stream of inbound SFTP data (~ 100MB per day)

The processing load on the app server side should be fairly light. The heaving lifting will be on the DB side sorting through and processing lots of data.
I'm having trouble figuring out which options I would install and calculating costs. If someone could help me get started by saying something like "You would start with a std-xyz-med server, install ABC located here at http://blahblah, then install XYZ located at http://XYZ.... etc.. etc.  You can expect to pay somewhere around $100-$200 per month"....
Thoughts?
I would be eternally grateful. It seems like they should have some free sales support channel to ask someone at Google about this, but I don't see it.
Thank You!

A: I'll try to give you some tips where to start looking.
I will be referring to some products, here are the links

*

*If you want to stick to your old ways, you can always spin up an instance on Compute Engine and set it up the same way you did before, these are just regular virtual machines. For some use cases this is completely valid.

*You can split different components of your stack to different products:

*

*For example, if your app is fine with postgresql, you can spin up a fully managed service in Cloud SQL, which might make it easier to manage backup or have several apps access the same db.

*Alternatively, have a look at the different DB offerings to see if any of them matches your needed workload better. Perhaps have a look at BigQuery?

*If you want to turn your app into a microservice, which is then easier to autoscale and is more fault tolerant, have a look at App Engine. That way you don't need to manage a virtual machine. The docs here will lead you through some easy to follow examples on how to set up SSL.

*For the services to talk to each other, refer to docs of the individual components. It's usually very simple.

*With pricing, try https://cloud.google.com/products/calculator/
Things like BigQuery have different pricing models - you don't pay for server uptime, but for amounts of data stored & processed with your queries.


text:
Q: C# - Using a private setter with a public getter on reference types Consider the following short code example with a public getter and a private setter:
public class Foo
{
    public class Bar
    {
        ...
    }

    public Bar fooBar { get; private set; }
    public int valueType { get; private set; }
}

I want to make sure that the class members can only be written to from inside the Foo class. That works for value types like valueType in the example above. But how do reference types like the nested class fooBar behave?
Can I use the reference which is returned by the public getter, to manipulate my private member?

A: If the type you're referring to is mutable, then yes, anyone with a reference to the "container" can fetch a reference and then mutate the object. For example:
using System;
using System.Collections.Generic;

class Container
{
    public List<string> List { get; private set; }
        = new List<string>();
}

class Program
{
    static void Main()
    {
        var container = new Container();
        var list = container.List;
        Console.WriteLine(list.Count); //0

        container.List.Add("foo");
        Console.WriteLine(list.Count); // 1
    }
}

Here the List<string> is being mutated outside Container. One option to avoid this would be to use a read-only view over the mutable data:
using System;
using System.Collections.Generic;

class Container
{
    private readonly List<string> list = new List<string>();

    public IReadOnlyList<string> ListView { get; }

    public Container()
    {
        ListView = list.AsReadOnly();
    }

    public void AddItem(string item)
    {
        list.Add(item);
    }
}

class Program
{
    static void Main()
    {
        var container = new Container();
        Console.WriteLine(container.ListView.Count); //0

        // container.ListView.Add("foo"); // Compile-time error

        container.AddItem("foo");
        Console.WriteLine(container.ListView.Count); // 1
    }
}

Note that you shouldn't just return the list directly from the property, even if the compile-time type is IReadOnlyList<T> - because then a caller could just cast back to List<T> and mutate it. List<T>.AsReadOnly() returns a genuinely read-only wrapper object around the list, so callers really won't be able to mutate it.


text:
Q: md-hint is not working in angular material The tag <md-hint> is not working in Angular Material 1.1.0-rc2.
I even tried using

 as defined in Documentation but gives out same result

A: I've created a CodePen with V1.1.0-rc2 that shows input hints as displayed in the online demos.
md-hint is not a directive in Angular Material 1.1.0-rc2
The style of the hints isn't a part of Angular Material but a stand alone CSS (not sure why they don't actually create a md-hint directive):


text:
Q: Flex: Changing font size of selectedItem in SpinnerList I know you can change the fontSize of all the items in a SpinnerList
example.setStyle("fontSize", 12);
I tried doing:
example.selectedItem.setStyle("fontSize", 12);
but it doesn't work.
Any ideas?

A: example.selectedItem usually is not a UIComponent, but some Value Object. You need to access itemRenderer directly or listen style changing from your custom item renderer


text:
Q: Why do we use the (min--moz-device-pixel-ratio:0) query for the selection of devices using Mozilla Browser? I was working on a plugin and got a very basic question in mind, would be really grateful if someone can help me out with it. Why exactly do we use (min--moz-device-pixel-ratio:0) query and how does it differ from the other queries. How does it specifically select only the mozilla browser. Are there any alternatives that have appeared in the recent times?

A: Alternative targeting FF Mozilla FireFox:
@-moz-document url-prefix('') {body {background-color: red;}}

@document
Only supports an empty url-prefix() value, which is supported due to
its use in Firefox browser detection. Still supported in user
stylesheets.


text:
Q: No option to add Visual C# class in models in visual studio 2013 I'm trying to add C# class in models but there is only option for Visual Basic class. When i click online option, it's showing no items available for Visual C#

A: If you are using a vb project, you can't add c# classes. One thing you can do is add a new c# library project and then add a reference to it.


text:
Q: How check if a windows account is an administrator of pc in vb 2013? I need to check if the current Logon Windows account is an Administrator of the PC.
    If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
        'Is Admin
    Else
        'Isn't Admin
    End If

This code work fine but if i lunch the code with RUN AS "another account" the code dont do the right job becouse take the account that lunch the code not the Windows account that is logged in.
With this code i can see the current Windows User logged in:
    Dim Coll As ManagementObjectCollection
    Dim LogonName As String
    Dim GetName As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
    Coll = GetName.[Get]()
    LogonName = DirectCast(Coll.Cast(Of ManagementBaseObject)().First()("UserName"), String)
    Dim CleanName() As String = Split(LogonName, "\")

So in the string LogonName i'll have the Windows user name account that is logged in but how can i check if is an Administrator?

A: Public Function UserIsAdmin(ByVal userName As String) As Boolean
        Dim groupName As String = "administrators" '<--You can localize this'
        Dim isAdmin As Boolean
        Using context As PrincipalContext = New PrincipalContext(ContextType.Machine)
            Dim gfilter As GroupPrincipal = GroupPrincipal.FindByIdentity(context, groupName)
            If gfilter IsNot Nothing Then
                Dim members = gfilter.GetMembers
                For Each member In members
                    If String.Compare(member.Name, userName, True) = 0 Then
                        isAdmin = True
                    End If
                Next
            End If
        End Using
        Return isAdmin
End Function

A: You can use System.Security.Principle namespace for this task. I wrote a function in a separate class you can use if you would like or move the function...
This is the class...
 Option Strict On
 Option Explicit On

 Imports System.Security.Principal

 Public Class SecurityClass

 #Region "Functions"

  Public Shared Function IsAdministrator() As Boolean
    Dim isAdmin As Boolean = False
    Try
        Dim user As IIdentity = WindowsIdentity.GetCurrent()
        Dim principal As New WindowsPrincipal(CType(user, WindowsIdentity))
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator)
        Return isAdmin
    Catch ex As Exception
        Return isAdmin
    End Try
  End Function

 #End Region

 End Class

To use the class and function, just simply call it where ever needed. I used a messagebox to show it for my test using a button click event.
 Private Sub btnIsAdmin_Click(sender As Object, e As EventArgs) Handles btnIsAdmin.Click
    If SecurityClass.IsAdministrator Then
        MessageBox.Show("Current user is an Administrator")
    Else
        MessageBox.Show("Current user is not Administrator")
    End If
 End Sub


text:
Q: Yii2 Model Rules Update Checking Rules For Same Record I.E. If i update address_line1 then its giving error for mobile number allocated.
While update it should not match with it self.
Even if i change mobile number it should check with other user.
public function rules()
    {
        return [
                    [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'],
                    ['mobile_number','mobile_number_allocation_validate'],

        ];
    }

public function mobile_number_allocation_validate($attribute){
        // add custom validation
        $result = User::find()
        ->where('`mobile_number` = "'.$this->$attribute.'" AND
                `status` = "A" ')->all();
        if(!empty($result)){
            $this->addError($attribute,'Mobile number is allocated to other vehicle');
        }

    }

Thanks in Advance

A: Change your condition as :-- Override beforeSave() of User ActiveRecord
/**
 * BeforeSave() check if User ActiveRecord is created with same calculator param
 * if created then return false with model error
 *
 */
public function beforeSave($insert){
    $model = self::find()->where('`mobile_number` = "'.$this->$attribute.'" AND
            `status` = "A" ')->all();

    if($model !== null && $model->id !== $this->id){
        $this->addError('mobile_number' , 'Mobile number is allocated to other vehicle');
        return false;
    }

    return parent::beforeSave($insert);
}

A: You should be able to use the unique validator for this, by simply adding a filter condition like this
public function rules()
    {
        return [
            [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'],
            ['mobile_number','unique', 'filter' => ['status' => 'A']],
        ];
    }


text:
Q: HSL color models in animation Currently I am using the animate tag to cycle through some colors.
<animate attributeName="stop-color" begin="0s" dur="16s" values="#00ffff;#ff00ff;#00ffff" repeatCount="indefinite" />

How are the colors being interpolated, and can I use HSL instead of RGB?
Thanks.

A: interpolation of colours is defined in the SVG specification. Basically distance is the standard vector distance between the colours in the RGB colour space.
Even though you can specify the end states in HSL in most UAs these days you won't get HSL interpolation. Your HSL endpoint colours would be converted to RGB and then the interpolation would take place in the RGB colour space.


text:
Q: How can I delete all files in a folder with names that longer than X? I have a folder with 1000s of files in that are named 23123 123r3883 3929388394j f38238d etc. I need to remove all the files that have a name length > 9. How can I do this?

A: You can match filenames that consist of at least 10 characters using a simple glob expression ??????????*. So provided the number of files is not too long, you could use
echo rm -- ??????????*

For longer file lists, you could break the names up using xargs:
printf '%s\0' -- ??????????* | xargs -r0 echo rm

If you switch from bash to zsh, you could make use of glob qualifiers to test the length of each filename (passed via the REPLY variable). One advantage is that you can easily add other qualifiers like N (equivalent of the bash shell's nullglob) and . (which limits the results to plain files):
echo rm -- *(.Ne:'[[ $#REPLY -gt 9 ]]':)

or
print -rNC1 -- *(.Ne:'[[ $#REPLY -gt 9 ]]':) | xargs -r0 echo rm

To do the equivalent in bash would likely require a loop, like
for f in *; do
  [[ -f $f && $#f -gt 9 ]] && echo rm -- "$f"
done

Remove the echo once you are satisfied that the right files are being matched.


text:
Q: Sequalize join multiple model giving alias error Hello guys I am new to sequalize and I am facing difficulty to join multiple tables.
Sequalize throws error below:
SequelizeEagerLoadingError: customers is associated to estimations using an alias. You've included an alias (createdby_details), but it does not match the alias(es) defined in your association (customer_details).

Here is my Estimation model:
var Customer = require('../models/Customer')
var User = require('../models/User')

var Estimations = connection.sequelize.define('estimations',{
    id:{
        type: connection.Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    user_id: {
        type: connection.Sequelize.INTEGER
    },
    title: {
        type: connection.Sequelize.TEXT
    },
    customer_id: {
        type: connection.Sequelize.INTEGER
    },
    project_address: {
        type: connection.Sequelize.TEXT
    },
    bid: {
        type: connection.Sequelize.TEXT
    },
    due_date: {
        type: connection.Sequelize.DATEONLY
    },
    total_cost: {
        type: connection.Sequelize.INTEGER
    },
    created_by: {
        type: connection.Sequelize.INTEGER
    },
    is_deleted: {
        type: connection.Sequelize.TINYINT
    },
    created_at: {
        type: connection.Sequelize.DATE
    },
    updated_at: {
        type: connection.Sequelize.DATE
    }
},{
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
});

Estimations.belongsTo(Customer, {
    as: 'customer_details',
    foreignKey: 'customer_id',
    targetKey: 'id'
});

Estimations.belongsTo(User, {
    as: 'createdby_details',
    foreignKey: 'created_by',
    targetKey: 'id'
});

Here is my controller code:
EstimationSchema.findAndCountAll({
                    include: [
                        {
                            attributes: ['org_name'],
                            model: CustomerSchema,
                            as: "customer_details"
                        },
                        {
                            attributes: ['first_name'],
                            model: UserSchema,
                            as: "createdby_details"
                        }
                    ],
                    attributes: columnName,
                    where: whereobj,
                    limit: parseInt(req.body.length),
                    offset: parseInt(req.body.start),
                    order: [ sort ]
                }).then(records => {
                    response.recordsTotal = records.count;
                    response.recordsFiltered = records.count
                    response.data = records.rows

                }).catch(err => {

                })

I have one another model 'User' which has primary key 'id' and it has to match with my above 'Estimation' model with 'created_by' field and fetch that user data.
What I want to do is to fetch 'Estimation' table data with associated 'Customer' and 'User' table data.
Thanks in advance.


text:
Q: How to change the point-to-point link data rate during run time? I have a query that tries to change a point-to-point link data rate during runtime. I tried  this solution but SetDeviceAttribute was not resolved for me.
void
ModifyLinkRate(PointToPointNetDevice *dev) {
   dev->SetDeviceAttribute("DataRate", StringValue ("1Mbps"));
   //dev->SetAttribute("DataRate", StringValue ("1Mbps"));
}
int
main (int argc, char *argv[])
{
...
   PointToPointHelper pointToPoint;
   pointToPoint.SetDeviceAttribute ("DataRate", StringValue (linkRate));
...
   Simulator::Schedule(Seconds(2.0), &ModifyLinkRate, &pointToPoint );
}

A: In order to change the data rate of a point-to-point link, the PointToPointNetDevice installed in a node has to be retrieved. This can be done using the NetDeviceContainer where the node is associated. The example code is below:
void
ModifyLinkRate(NetDeviceContainer *ptp, DataRate lr) {
    StaticCast<PointToPointNetDevice>(ptp->Get(0))->SetDataRate(lr);
}
int
main (int argc, char *argv[])
{
...
   PointToPointHelper pointToPoint;
   pointToPoint.SetDeviceAttribute ("DataRate", StringValue (linkRate));
...
   NetDeviceContainer p2pDevices = pointToPoint.Install (p2pNodes);
...
    Simulator::Schedule(Seconds(2.0), &ModifyLinkRate, &p2pDevices,DataRate("20Mbps"));
}


text:
Q: jmeter - generate jmx file using jmeter api 2.11 I am trying to build a java app that would read some access files and dynamicaly create some load and/or functional test scenarios. I am using the jmeter API 2.11.
The application would run within a CI (jenkins). Now, I have heard of some Jenkins Plugin for jmeter that executes some predefined test and eventually produces a user friendly graphical report, I didn't get that far though. First of all I was able to programm a pretty simple  test with httpSampler and just one thread/loop. I could run it within the application using StandardJMeterEngine functionality configure() & run().
Instead, I would like to generate an output jmx file for each test plan so I could use it as an input for the CI test execution/reporting part.
I have found a class org.apache.jmeter.protocol.http.util.accesslog.StandardGenerator that would eventually take over the task. Does anyone had a simmilar task/problem and knows the best approach here? I would really appreciate any answer.
Best Redards
m.

A: I believe that 5 Ways To Launch a JMeter Test without Using the JMeter GUI guide is what you're looking for, it contains link to Jenkins performance plugin and end-to-end instructions on how to invoke existing JMeter test from .jmx file and create a new one using JMeter API.


text:
Q: For Loop only printing of 1? Python I was trying to print a list in backwards order using a for loop, however my code only prints of a 1, any ideas why?
    sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
    des_list = []
    for i in range(len(sorted_list)-2,-3,-1):
        des_list.append(sorted_list[i-2])
        des_list.append(sorted_list[i - 1])
        des_list.append(sorted_list[i])
        des_list.append(sorted_list[i+1])
    print(des_list)

A: It would probably be easier to store the chunks of data into objects. That way, you can just call reversed() on the list of objects and handle the data that way.
If you want to keep the list in the format you have, you can loop through the list in "chunks", like this: for i in range(0, len(sorted_list), 4):.
So, for every 4 elements in the list, grab the chunk of of data using list slicing notation: sorted_list[i:i+4] and insert it to the front of the destination list.
Putting that together, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
    des_list.insert(0, sorted_list[i:i+4])
print(des_list)

That will output this: [['sod', 3, 1, 0], ['tim', 5, 3, 1], ['bob', 0, 0, 10], ['jill', 4, 1, 0], ['jack', 4, 3, 1]].
Keep in mind that that code will give you a list of lists, because sorted_list[i:i+4] returns a list, which is why it might be easier to use objects instead.
If you don't want to have a list of lists, you can reverse the sliced list, loop through each element in the reversed sliced list, and insert it one at a time to the destination list.
Doing that, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
    for j in reversed(sorted_list[i:i+4]):
        des_list.insert(0, j)
print(des_list)

Which outputs this: ['sod', 3, 1, 0, 'tim', 5, 3, 1, 'bob', 0, 0, 10, 'jill', 4, 1, 0, 'jack', 4, 3, 1]


text:
Q: How to get Telegram channel Profile Photo with TelegramBotClient I'm using C# TelegramBotClient library.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var bot = new TelegramBotClient("apiKey");
var chat = await bot.GetChatAsync("@channelName");

What should I do with BigFileId to get image?

A:         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var bot = new TelegramBotClient("apiKey");
        var chat = await bot.GetChatAsync("@channelName")
        Telegram.Bot.Types.File p = await bot.GetFileAsync(chat.Photo.BigFileId);
        string filePath = p.FilePath;

        using (var outputStream = new MemoryStream())
        {
            var file = bot.GetInfoAndDownloadFileAsync(p.FileId, outputStream).GetAwaiter().GetResult();
            var array = outputStream.ToArray();
            using (var ms = new MemoryStream(array))
            {
                var image = Image.FromStream(ms);
                image.Save("C:\\test\\image.jpg", ImageFormat.Jpeg);
            }
        }


text:
Q: Proving that the set of all finite subsets of a countable set is coutable I am trying to prove the following proposition:

Proposition: Let $S$ be a countable set. Then the set of all finite subsets of $S$ is also countable.

My approach:
If $S$ is countable that means that $S$ is finite or that $S \sim\mathbb{N}$.
If $S$ is finite then the number of finite subsets of $S$ is also finite, so in this case it's easy to show that this is countable as well.
In the case that $S$ is countably infinite:
Let $A_k=\{A \subset S:\text{card} (A)=k\}$. $A_k$ is countable because it is the union of various countable sets $A \subset S$
The set of all finite subsets of $S$ will be equal to $\bigcup \limits_{i=1}^\infty A_i$. Because every $A_i$ is countable, then this union is also countable.
My question is: Can I do this union? Because $A_\infty$ means the set is the set of all infinite subsets of $S$, and I'm making an union from $i=1$ to $\infty$. So is this proof right?

A: There is no problem with that union. However, it is wrong to assert that $A_k$ is countable "because it is the union of various countable sets". An arbitray union of countable sets doesn't have to be countable. You have to justify that you have a countable union of countable sets here.


text:
Q: Rails using wrong model sometimes I have two models User and Google::User. Rails sometimes understand the difference between the two but then confuses the two models. Here is my output from rails console. Both the time I get output from User model.
irb(main):004:0> User
=> User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: inet, last_sign_in_ip: inet, name: string, location: string, website: string, github: string, created_at: datetime, updated_at: datetime)

irb(main):005:0> Google::User
=> Google::User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: inet, last_sign_in_ip: inet, name: string, location: string, website: string, github: string, created_at: datetime, updated_at: datetime)

I understand that both are perfectly namespaced. Then why would this be happening?


text:
Q: C# SQLITE Specified cast is not valid Getting error "specified cast is not valid" when trying to retrieve data from SQLite database.
Think its got something to do with DeviceRecord.ip_address.ToString think sqlite does not like it, can someone please help?
I am a total newbie to coding and SQLite so hopefully all this makes sense, my code is probably all over the place, sorry for the mess...
Error message from browser
[InvalidCastException: Specified cast is not valid.]
   System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ) +327
   System.Data.SQLite.SQLiteDataReader.GetBoolean(Int32 i) +263
   System.Data.Entity.Core.Objects.Internal.ShapedBufferedDataRecord.Initialize(DbDataReader reader, DbSpatialDataReader spatialDataReader, Type[] columnTypes, Boolean[] nullableColumns) +420
   System.Data.Entity.Core.Objects.Internal.BufferedDataReader.Initialize(String providerManifestToken, DbProviderServices providerServices, Type[] columnTypes, Boolean[] nullableColumns) +156
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +1014
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +512
   System.Data.Entity.Core.Objects.<>c__DisplayClassb.<GetResults>b__9() +203
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +341
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +38
   System.Lazy`1.CreateValue() +727
   System.Lazy`1.LazyInitValue() +184
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +15
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +202
   _Default.getIP() +982
   System.Web.UI.Control.OnLoad(EventArgs e) +103
   System.Web.UI.Control.LoadRecursive() +68
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1381

C# Code
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Configuration;
using System.Windows;
using System.Net.Sockets;

public partial class _Default : System.Web.UI.Page
{
    string serviceDesk = "email address";
    string emailSubject = "MyPc";
    string IPaddr = "";
    string deviceName = "";
    private readonly object reader;

    public DateTime DateStamp { get; private set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        getIP();
    }

    protected void getIP()
    {
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"] != null)
        {
            IPaddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"].ToString();
        }
        if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            IPaddr = HttpContext.Current.Request.UserHostAddress;
            DateStamp = DateTime.Now;

            try
            {
                deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
            }
            catch (SocketException)
            {
                deviceName = "could not be resolved";
            }
        }
        Label1.Text = "IP Address: " + " " + IPaddr;
        Label2.Text = "PC Name: " + " " + deviceName;
        Label3.Text = "Date and Time: " + " " + DateStamp;

        using (mainEntities dbcontent = new mainEntities())
        {
            var DeviceRecord = dbcontent.devices.SingleOrDefault(x => x.ip_address == IPaddr);

            if(DeviceRecord !=null)
            {
                string ipaddress = DeviceRecord.ip_address.ToString();
                string name = DeviceRecord.name.ToString();

                Label4.Text = ipaddress;
                Label5.Text = name;
            }

            }

    }

    private void EmailVerificationRequest(string recepientEmail, string subject)
    {
        try
        {
            using (MailMessage mailMessage = new MailMessage())
            {
                StringBuilder sbEmailBody = new StringBuilder();

                sbEmailBody.Append("IP address " + IPaddr + "
");
                sbEmailBody.Append("Hostname " + " " + deviceName + "
");
                sbEmailBody.Append("Date and Time " + " " + DateStamp);

                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmail"]);
                mailMessage.Subject = subject;
                mailMessage.Body = sbEmailBody.ToString();
                mailMessage.IsBodyHtml = true;
                mailMessage.To.Add(new MailAddress(recepientEmail));

                SmtpClient smtp = new SmtpClient();

                smtp.Host = ConfigurationManager.AppSettings["Host"];
                smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
                smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);

                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                NetworkCred.Password = ConfigurationManager.AppSettings["Password"];

                if (string.IsNullOrWhiteSpace(NetworkCred.UserName))
                {
                    smtp.UseDefaultCredentials = true;
                }
                else
                {
                    smtp.Credentials = NetworkCred;
                    smtp.UseDefaultCredentials = false;
                }

                smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);

                try
                {
                    smtp.Send(mailMessage);
                }

                catch (SmtpException e)
                {
                }
            }
        }

        catch
        {
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        EmailVerificationRequest(serviceDesk, emailSubject);
        Response.Redirect("~/message.aspx");
    }

}


text:
Q: Induced topology on site + Reconstructing global sections of a scheme (Orlov) Let $(C,T,O)$ be a ringed site. Let $X$ be a presheaf on C.
We get an induced ringed site $(C/X,T_X,O_X)$. C/X is the over category wrt the presheaf X. The topology $T_X$ is the biggest topology making the functor $j_X:C/X\rightarrow C$ continues and $O_X=j_X^*O$. See paragraph 1.1,1.5 and 1.6.
Given any sieve $J$ on $R\rightarrow X$ in $C/X$, how can one determine if it is covering or not?
Orlov points to SGA1, but I am a mere commoner.
I want a procedure/criteria using only my original topology $T$ and not all sheafs as in the definition.

$J$ is covering if the canonical map
  $$Hom(J,G_X)\rightarrow Hom(R\rightarrow X,G_X)$$ is bijective for any pullback $G_X=j_X^*G$ of any sheaf $G$ on $(C,T)$.

This is a prereq for my 'real' question. In the Orlov paper, $X$ is a scheme and $C$ is the category of affines.
In this set-up, how would you calculate the 'global' sections of $O_X$?
I would like to work out in detail the equivalence between his set-up and the usual one.

A: First things first: we need a more tractable definition of "continuous".

Let $\mathcal{C}$ and $\mathcal{D}$ be categories, let $J$ be a Grothendieck topology on $\mathcal{C}$, and let $K$ be a Grothendieck topology on $\mathcal{D}$. The following are equivalent for a functor $u : \mathcal{C} \to \mathcal{D}$:

*

*For every $K$-sheaf $Y$ on $\mathcal{D}$, $u^* Y$ is a $J$-sheaf on $\mathcal{C}$.

*For every object $C$ in $\mathcal{C}$ and every $J$-covering sieve $\mathfrak{U}$ on $C$, the morphism $u_! \mathfrak{U} \to u_! h_C$ becomes a split epimorphism after $K$-sheafification.

  Assuming $u_! : \hat{\mathcal{C}} \to \hat{\mathcal{D}}$ preserves monomorphisms (which happens if e.g. $\mathcal{C}$ has finite limits and $u : \mathcal{C} \to \mathcal{D}$ preserves finite limits), then the previous conditions are also equivalent to the following conditions:

*

*For every object $C$ in $\mathcal{C}$ and every $J$-covering sieve $\mathfrak{U}$ on $C$, the morphism $u_! \mathfrak{U} \to u_! h_C$ becomes an isomorphism after $K$-sheafification.

*For every object $C$ in $\mathcal{C}$ and every $J$-covering sieve $\mathfrak{U}$ on $C$, the sieve on $u(C)$ generated by $\{ u(f) : f \in \mathfrak{U} \}$ is a $K$-covering sieve.

Now, let us consider the case of the projection $u : \mathcal{C}_{/ X} \to \mathcal{C}$. It is well known that $(\mathcal{C}_{/ X})ˆ$ is equivalent to $\hat{\mathcal{C}}_{/ X}$, and under this identification, $u_! : \hat{\mathcal{C}}_{/ X} \to \hat{\mathcal{C}}$ is the projection. In particular, $u_!$ preserves monomorphisms, so the Grothendieck topology on $\mathcal{C}_{/ X}$ is the "obvious" one: a sieve in $\mathcal{C}_{/ X}$ is a covering sieve if and only if its image in $\mathcal{C}$ is a covering sieve. (Note that the image of a sieve is automatically a sieve in this case!)

Your second question is actually independent of the first one – Grothendieck topologies and sheaf conditions are irrelevant here. Again, we start with a general fact:

Let $\mathcal{C}$ and $\mathcal{D}$ be categories, let $u : \mathcal{C} \to \mathcal{D}$ be a functor, and let $Y$ be a presheaf on $\mathcal{D}$. We have the following natural bijection,
  $$\hat{\mathcal{D}} (u_! 1, Y) \cong \hat{\mathcal{C}} (1, u^* Y) \cong \Gamma (Y)$$
  where $1$ is the terminal object in $\hat{\mathcal{C}}$.

In particular, for the projection $u : \mathcal{C}_{/ X} \to \mathcal{C}$, we have $u_! 1 \cong X$, so $\Gamma (Y) \cong \hat{\mathcal{C}} (X, Y)$ in this case.
Incidentally, if $\mathcal{C}$ is the category of affine schemes and $X$ and $Y$ are the functor of points of schemes, then $\hat{\mathcal{C}} (X, Y)$ can be identified with the set of scheme morphisms $X \to Y$.


text:
Q: How to get item position for recycle-view I'm an Android programmer, I'm developing a news app using RSS feed that get the the news from the web, my code work fine ! but I wont when I click on any news to open new activity display news details ? i'm using recycle-view how i get the position of clicked item and pass the news?..
this is my ReadRss :
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://www.sciencemag.org/rss/news_current.xml";
ProgressDialog progressDialog;
ArrayList<FeedItem> feedItems;
RecyclerView recyclerView;
URL url;

public ReadRss(Context context, RecyclerView recyclerView) {
    this.recyclerView = recyclerView;
    this.context = context;
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading...");
}

//before fetching of rss statrs show progress to user
@Override
protected void onPreExecute() {
    progressDialog.show();
    super.onPreExecute();
}

//This method will execute in background so in this method download rss feeds
@Override
protected Void doInBackground(Void... params) {
    //call process xml method to process document we downloaded from getData() method
    ProcessXml(Getdata());

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressDialog.dismiss();
    FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.addItemDecoration(new VerticalSpace(20));
    recyclerView.setAdapter(adapter);
}

// In this method we will process Rss feed  document we downloaded to parse useful information from it
private void ProcessXml(Document data) {
    if (data != null) {
        feedItems = new ArrayList<>();
        Element root = data.getDocumentElement();
        Node channel = root.getChildNodes().item(1);
        NodeList items = channel.getChildNodes();
        for (int i = 0; i < items.getLength(); i++) {
            Node cureentchild = items.item(i);
            if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                FeedItem item = new FeedItem();
                NodeList itemchilds = cureentchild.getChildNodes();
                for (int j = 0; j < itemchilds.getLength(); j++) {
                    Node cureent = itemchilds.item(j);
                    if (cureent.getNodeName().equalsIgnoreCase("title")) {
                        item.setTitle(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("description")) {
                        item.setDescription(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("pubDate")) {
                        item.setPubDate(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("link")) {
                        item.setLink(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("media:thumbnail")) {
                        //this will return us thumbnail url
                        String url = cureent.getAttributes().item(0).getTextContent();
                        item.setThumbnailUrl(url);
                    }
                }
                feedItems.add(item);

            }
        }
    }
}

//This method will download rss feed document from specified url
public Document Getdata() {
    try {
        url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDoc = builder.parse(inputStream);
        return xmlDoc;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

}
my FeedsAdapter :
public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> {
ArrayList<FeedItem>feedItems;
Context context;
public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems){
    this.feedItems=feedItems;
    this.context=context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
    FeedItem current=feedItems.get(position);
    holder.Title.setText(current.getTitle());
    holder.Description.setText(current.getDescription());
    holder.Date.setText(current.getPubDate());
    Picasso.with(context).load(current.getThumbnailUrl()).into(holder.Thumbnail);

}

@Override
public int getItemCount() {
    return feedItems.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Title,Description,Date;
    ImageView Thumbnail;
    CardView cardView;
    public MyViewHolder(View itemView) {
        super(itemView);
        Title= (TextView) itemView.findViewById(R.id.title_text);
        Description= (TextView) itemView.findViewById(R.id.description_text);
        Date= (TextView) itemView.findViewById(R.id.date_text);
        Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
        cardView= (CardView) itemView.findViewById(R.id.cardview);
    }
}

}

A: I'm not sure that I understand you. But to check when a user clicks a news, you have to add the following code to your FeedsAdapter
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
  holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FeedItem item = feedItems.get(position);
            //start your activity here
        }
    });
  //other code
}

A: So you can use a Callback interface to pass the data like
interface DisplayNews{
void newsDetail(int position);// any name as per your requirement
}

Then implement that interface in your base activity/fragment like
class NewsActivity implements DisplayNews{
@Override
 void newsDetail(int position){
  // get your list item/element from list using postion and pass that into  intent to new activity
}
}

And in your adapter change the adapter contractor and some tiny code like
public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> {
ArrayList<FeedItem>feedItems;
Context context;
private DisplayNews callback;
public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems,DisplayNews callback){
    this.feedItems=feedItems;
    this.context=context;
    this.callback=callback;

}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
    FeedItem current=feedItems.get(position);
    holder.Title.setText(current.getTitle());
    holder.Description.setText(current.getDescription());
    holder.Date.setText(current.getPubDate());
    Picasso.with(context).load(current.getThumbnailUrl()).into(holder.Thumbnail);
holder.itemView.setOnClickListener(view -> callback.newsDetail(holder.getAbsoluteAdapterPosition());

}
@Override
public int getItemCount() {
    return feedItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Title,Description,Date;
    ImageView Thumbnail;
    CardView cardView;
    public MyViewHolder(View itemView) {
        super(itemView);
        Title= (TextView) itemView.findViewById(R.id.title_text);
        Description= (TextView) itemView.findViewById(R.id.description_text);
        Date= (TextView) itemView.findViewById(R.id.date_text);
        Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
        cardView= (CardView) itemView.findViewById(R.id.cardview);
    }
}
,,,


text:
Q: Calling notes URL from a web page with query string parameters in URL We have a web page with links to Notes client. We can open existing document easily or create a new one with syntax: notes://localhost/__A92574C800517FC7.nsf/company?OpenForm Is there a way how to, in notes client, ready query string parameters provided in URL like this: notes://localhost/__A92574C800517FC7.nsf/company?OpenForm&param1=value . We tried a common ways like using @UrlQueryString("param1") in the form but no luck. Is there any otheroption for doing this?

A: Could you see what happens (not sure here...) when you add a text-field xyz to the form and use a notes-url like notes://localhost/__A92574C800517FC7.nsf/company?OpenForm&xyz=something ?


text:
Q: HTTP Status 500 - No AtmosphereHandler maps request for /j_spring_security_check This gives me error, while I tried all the option regarding this question ? Regarding Spring project.
HTTP Status 500 - No AtmosphereHandler maps request for /j_spring_security_check
type Exception report
Message: No AtmosphereHandler maps request for /j_spring_security_check
Description: The server encountered an internal error that prevented it from fulfilling this request.
Exception:
    org.atmosphere.cpr.AtmosphereMappingException: No AtmosphereHandler maps request for /j_spring_security_check
        org.atmosphere.cpr.AsynchronousProcessor.map(AsynchronousProcessor.java:362)
        org.atmosphere.cpr.AsynchronousProcessor.action(AsynchronousProcessor.java:206)
        org.atmosphere.cpr.AsynchronousProcessor.suspended(AsynchronousProcessor.java:166)
        org.atmosphere.container.Tomcat7CometSupport.service(Tomcat7CometSupport.java:85)
        org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.doService(Tomcat7AsyncSupportWithWebSocket.java:59)
        org.atmosphere.container.TomcatWebSocketUtil.doService(TomcatWebSocketUtil.java:81)
        org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.service(Tomcat7AsyncSupportWithWebSocket.java:55)
        org.atmosphere.cpr.AtmosphereFramework.doCometSupport(AtmosphereFramework.java:1266)
        org.atmosphere.cpr.AtmosphereServlet.event(AtmosphereServlet.java:348)
        org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
        org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
        org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462)
        org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451)
        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        java.lang.Thread.run(Thread.java:745)

Note: The full stack trace of the root cause is available in the Apache Tomcat/7.0.56 logs.


text:
Q: Using external storage for Vert.x Session Management Vert.x inbuilt session store LocalSessionStore and ClusteredSessionStoreImpl use local Maps to store session. If I use Redis or any data store for session management i cannot directly serialize them as they don't have properly defined getters and setter. Furthermore, SessionImpl has id as private field with no setters. So even if i have proxy class i cannot re create Session.
How do i store sessions externally then ?

A: SessionImpl implements the ClusterSerializable interface, which gives you 2 methods - writeToBuffer and readFromBuffer.
You can use them to serialize / deserialize to external stores like redis.


text:
Q: Magento 2 How to add and call custom scss I want to know how to add scss i tried in below way in default.xml but it's not working
<css src="sass/styles.scss" />

How to achieve this?
Or else give me the proper way how to place and call

A: I don't think this accepts SCSS files, and even if it did your browser can't render them.
What you need to do (unless you're doing something custom) is to pass it a CSS file, and compile your SCSS into CSS.
<css src="path/file-name.css"/>


text:
Q: Sufficient condition for equality of multisets Give three finite multisets $A,B,C$ I am trying to devise a sufficient condition that implies equality of both $A$ and $B$ with $C$. More formally, if $A,B,C$ are defined over a space $\Omega$, I am looking for a function $f : \Omega \times \Omega \to \Omega$ such that $$f(A,B) = C, \text{ implies that } A = C \text{ and } B = C.$$ Naturally, equality is as multisets.
The motivation for this question was noticing the basic observation that if $A\cup B \subseteq C$ as multisets, then $A \subseteq C$ and $B \subseteq C$ as multisets. I was wondering if something similar happens with the equality "$=$" operator instead of the subset "$\subseteq$" operator. In the subset example, the function $f$ is the union of multisets $\cup$ defined as $$f(A,B) = A \cup B := \{[x,\max\{m_A(x),m_B(x)\}] : x \in A \text{ or
} x \in B\},$$
where $m_Z(x)$ counts the number of times that $x$ appears in some multiset $Z$.

A: To summarize the discussion in the comments:
No such function can exist (at least, assuming $\Omega$ is non-empty).
To see this, suppose we had such a function and let $\omega \in \Omega$ be some element, with $A=\{\omega\}$.  Then we consider $f(A,\emptyset)$ as some set (or multiset).  By definition we must have $A=\emptyset=f(A,\emptyset)$ so, in particular, $A=\emptyset$, counter to the definition of $A$, and we have a contradiction.
Technical point:  Writing $f:\Omega\times \Omega\to \Omega$ can't be what was intended.  That would mean a function that took two elements from $\Omega$ and returned a third.  I assume that what was meant was a function, or more likely a functor, from $\mathbf {MSets}_{\Omega}\times \mathbf {MSets}_{\Omega}\to \mathbf {MSets}_{\Omega}$.  That is, something that takes two multisets (of elements taken from $\Omega$) and returns a third.  That's what the contradiction I described assumes.


text:
Q: ABPersonViewController Usage for displaying contact Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in a view based project

A: Write this piece of code in navigation controller.m:
ABAddressBookRef addressBook= ABAddressBookCreate(); // this will open the AddressBook of the iPhone
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook); // this copies all the contacts from the Address Book into the array
NSString *contactName = [[NSString alloc] init];

// specify the contact name to be edited
contactName = @"ABCD";
for (int i =0 ;i<ABAddressBookGetPersonCount(addressBook);i++){
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty); // this gets the First Name of the person

// check whether the editable contact exists in the AddressBook if exists then allows the user to edit the contact
if ([contactName compare: firstName] == NSOrderedSame) {
ABPersonViewController *personController = [[ABPersonViewController alloc] init];
personController.addressBook = addressBook; // this passes the reference of the Address Book
personController.displayedPerson = ref; // this sets the person reference
personController.allowsEditing = YES; // this allows the user to edit the details
personController.personViewDelegate = self;
personController.navigationItem.rightBarButtonItem = [self editButtonItem]; // this will add the inbuilt Edit button to the view

// this displays the contact with the details and presents with an Edit button
[[self navigationController] pushViewController:personController animated:YES];
[personController release];
}
}

// setEditing method needs to be overridden for edit functionality to work properly
------------------
- (void)setEditing:(BOOL)flag animated:(BOOL)animated {
[super setEditing:flag animated:animated];
if (flag == YES){
// change the view to an editable view
[ [self navigationController] setEditing:YES animated:NO];
}
else {
// save the changes and change the view to noneditable
[ [self navigationController] setEditing:NO animated:NO];
}
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue {
return YES;
}


text:
Q: Linear Programming: from primal to dual system, how many variables needed? Suppose that you are trying to solve the optimization problem:
$$
\begin{equation*}
\begin{array}{ll@{}ll}
\text{maximize}  & v \cdot x &\\
\text{subject to}& Ax \geq b    &A \in \mathbb{R}^{m\times n}
\end{array}
\end{equation*}
$$
(i.e. trying to solve an optimization problem in $n$ variables with $m$ linear inequality constraints).
This problem can be reduced to running a solution finding algorithm on a different system of linear equations in $k$ variables. What is the smallest value of $k$ for which this can be done.

I have tried to say $n$, the number of variables we have but it turns out incorrect.
note: This question has been picked from Advanced Algorithms and Complexity Coursera course, week 2: Linear Programming.

A: The answer is $m+n$. The idea is that you need to solve for the given inequalities and for the dual as well. The given inequalities will have $n$ variables, the dual will have $m$, so all in all, you will need to solve for $m+n$ variables!


text:
Q: Issue getting a submit button to center in a wrap For some reason I cannot get the submit button to center. I have tried everything from text-align: center; to margin: 0 auto; to a left and right margin at auto. The button will not center anyway I try. What am I failing to do?

.contactForm {
  border: 2px solid black;
  background-color: #F0F0F0;
  width: 40%;
  margin: 0 auto;
  padding: 40px;
}
.contactButton {
  margin-top: 15px;
  margin-right: auto;
  margin-bottom: 15px;
  margin-left: auto;
  width: 425px;
  font-size: 20px;
  font-weight: bold;
  padding: 14px;
  cursor: pointer;
  background-color: #800000;
  border: none;
  color: #FFFFFF;
  text-align: center;
}

  <form action="" method="post" id="mycontactform">
    <input type="text" class="inputbar" name="name" placeholder="Full Name" required>
    <input type="email" class="inputbaremail" name="email" placeholder="Email" required>
    <textarea rows="4" cols="50" name="message" class="inputbarmessage" placeholder="Message" required></textarea>

      <input type="button" class="contactButton" value="Send Message" id="submit">

  </form>

A: It's hard to center is, because it is inside a label. The label is an inline element too and will size around the button. Therefor text-align: center and other solutions don't work.
In the snippet below, I've made the label show itself as a block element, which automatically occupies the available width of the parent. Then you can easily center the button inside it:
The added piece:
label[for="contactButton"] {
  display: block;
  text-align: center;
}

The whole code:

.contactForm {
  border: 2px solid black;
  background-color: #F0F0F0;
  width: 40%;
  margin: 0 auto;
  padding: 40px;
}
.contactButton {
  margin-top: 15px;
  margin-right: auto;
  margin-bottom: 15px;
  margin-left: auto;
  width: 425px;
  /* Make sure the button isn't too wide on small screens */
  max-width: 80%;
  font-size: 20px;
  font-weight: bold;
  padding: 14px;
  cursor: pointer;
  background-color: #800000;
  border: none;
  color: #FFFFFF;
  text-align: center;
}

label[for="contactButton"] {
  display: block;
  text-align: center;
}

  <form action="" method="post" id="mycontactform">
    <input type="text" class="inputbar" name="name" placeholder="Full Name" required>
    <input type="email" class="inputbaremail" name="email" placeholder="Email" required>
    <textarea rows="4" cols="50" name="message" class="inputbarmessage" placeholder="Message" required></textarea>

      <input type="button" class="contactButton" value="Send Message" id="submit">

  </form>

A: Use text-align:center on the parent div.
Fiddle: http://jsfiddle.net/gopal/su3vg018/
.contactForm {
 text-align:center;
}

A: Add this to your css file:
.contactForm label[for="contactButton"] {
    display: block;
    text-align: center;
}


text:
Q: Simple solution for different model and view value in Reactive input control in Angular I have a formControl with value set to object like {id: 1, name: 'Ramesh'}. The input field inside mat-form-field is read-only and value either coming from database or selected from a pick list.
To show different view value I am using [value] binding like below. Its correctly displaying when control is updated later by the user. But when its initialized for the first time with saved value its showing [object Object].

Internally its depending upon the order of execution of DefaultValueAccessor writeValue method and [value] binding.

https://stackblitz.com/edit/angular-ivy-mkvx8a?file=src%2Fapp%2Fapp.component.ts
<input readonly [formControl]="userControl" [value]="userControl.value?.name">

I thought to create custom value accessor but it seems too much.

A: I have solved it by extending DefaultValueAccessor and providing custom writeValue method. But I feel angular should provide a way for just custom writeValue method.
For example mat autocomplete has displayWith
Demo: https://stackblitz.com/edit/angular-ivy-mkvx8a?file=src%2Fapp%2Fapp.component.html
<input valueKeyAccessor [formControl]="control">

@Directive({
  selector: "input[valueKeyAccessor]",
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => valueKeyAccessor),
      multi: true
    }
  ]
})
export class valueKeyAccessor extends DefaultValueAccessor {
  @Input("valueKeyAccessor") propToDisplay;

  writeValue: any;
  constructor(
    _renderer: Renderer2,
    _elementRef: ElementRef,
    @Optional() @Inject(COMPOSITION_BUFFER_MODE) _compositionMode: boolean
  ) {
    // Refer signature from https://github.com/angular/angular/blob/9.1.11/packages/forms/src/directives/default_value_accessor.ts#L36-L156
    super(_renderer, _elementRef, _compositionMode);
    // overwriting the writeValue
    this.writeValue = value => {
      value = value && value[this.propToDisplay];
      const normalizedValue =
        (value === undefined || value === null) ? "" : value;
      super.writeValue(normalizedValue);
    };
  }

  ngOnInit() {
    this.propToDisplay = this.propToDisplay || "name";
  }
}


text:
Q: What does "variable" mean in this sentence? "We don't have a Trump variable in the model."
source: http://money.cnn.com/2016/05/26/news/economy/hillary-clinton-beat-donald-trump-moodys/index.html

A: It is variable as part of an algorithm. For example, in their model, they don't have a if (candidate==trump) {}.
What they mean, implicitly, is that Trump is such an odd and extravagant candidate that it is complicated to include that in their calculation and to predict what the outcome is going to be, since their algorithm only calculates the odds according to the political party of the candidate.


text:
Q: Python - RSA decryption does not return original message (very simple, short program) So I am trying to create a very simple RSA encryption/decryption program where I only encrypt/decrypt int numbers. All works fine except for one problem. Sometimes my decrypted number (message) does not match my original number (the message I needed to encrypt and decrypt). This seems to happen whenever my inputted number (message) is close to my the number in my 'n' variable (n=p*q where p and q are prime numbers). I have browsed Stackoverflow a bit now and have found out that RSA algoritms cannot properly decrypt messages that are greater than 'n'. But in my case it fails to decrypt messages that are close to 'n'. If n=35 and my input number (the number to encrypt/decrypt) is 32, the program does not properly decrypt it back to 32 despite 32 being lower than 35 (works for 31, 30 ... though). Why?
Code:
import math

def isPrime(n):
    if n>=2:
        for m in range(2, int(math.sqrt(n)+1)):
            if n%m == 0:
                return False
        return True
    else:
        return False

def gcd(x, y):
    while y != 0:
        (x, y) = (y, x % y)
    return x

def phi(n):
    amount = 0
    for k in range(1, n + 1):
        if gcd(n, k) == 1:
            amount += 1
    return amount

def findPubE(n, phiN):
    for e in range(3, n, 2):
        if gcd(e,phiN)==1:
            return e
    else:
        raise AssertionError("cannot find 'e'")

def multiplicative_inverse(a, b):
    """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
    """
    # r = gcd(a,b) i = multiplicitive inverse of a mod b
    #      or      j = multiplicitive inverse of b mod a
    # Neg return values for i or j are made positive mod b or a respectively
    # Iterateive Version is faster and uses much less stack space
    x = 0
    y = 1
    lx = 1
    ly = 0
    oa = a  # Remember original a/b to remove
    ob = b  # negative values from return results
    while b != 0:
        q = a // b
        (a, b) = (b, a % b)
        (x, lx) = ((lx - (q * x)), x)
        (y, ly) = ((ly - (q * y)), y)
    if lx < 0:
        lx += ob  # If neg wrap modulo orignal b
    if ly < 0:
        ly += oa  # If neg wrap modulo orignal a
    # return a , lx, ly  # Return only positive values
    return lx

def encrypt(m,e,n):
    return (m^(e)) % n

def decrypt(M, d):
    return M^(d)

def main():
    p=int(input("Input first prime number (p): "))
    q=int(input("Input second prime number (q): "))
    n=p*q
    print("n = ",n)
    msg= int(input("Input message: "))
    assert msg < n
    phiN=(p-1)*(q-1)
    e = findPubE(n,phiN)
    d = multiplicative_inverse(e,phiN)
    encryptedMsg = encrypt(msg,e,n)
    decryptedMsg = decrypt(encryptedMsg,d)

    assert isPrime(p) and isPrime(q)

    print("phi(n) = ",phiN)
    print("e = ",e)
    print("d = ",d)
    print("Encrypted message: ",encryptedMsg)
    print("Decrypted message: ",decryptedMsg)

main()

A: Solved it! I made two little mistakes in my code. First one was that I assumed that the "^" symbol meant "to the power of" in Python (the correct symbol is "**") and the second one was that I forgot to add "mod n" to the line in my decrypt() function (so return M**(d) % n instead of return M^(d)).


text:
Q: Ninject Creating an Extra Instance when using NinjectHttpModule For some reason Ninject is creating an additional instance of my object when I use NinjectHttpModule in my MVC 4 app.
If I use NinjectHttpModule (the Ninject.MVC3 default) but do not actually have any IHttpModule classes that require constructor injection, it works fine.  But as soon as I create a class that implements IHttpModule and that requires constructor injection, Ninject for some reason creates two instances of my object.
I added some tracking code to the class that is being duplicated to verify that it was being duplicated.  Every time an instance is created, the static count variable is incremented:
namespace Trigger.Events
{
    public class TriggerEventRegistry : ITriggerRegistry
    {
        private static int count;

        public TriggerEventRegistry()
        {
            TriggerEventRegistry.count++;
        }
    }
 }

Here is my IHttpModule:
namespace TriggerDevelopment.ApplicationTriggers
{
    public class RegisterTriggerComponentsHttpModule : IHttpModule
    {
        ITriggerEventRegistry eventRegistry;

        public RegisterTriggerComponentsHttpModule(ITriggerEventRegistry eventRegistry)
        {
            this.eventRegistry = eventRegistry;
        }
     }
     ....
}

By the time a TriggerEventRegistry is injected into my controller (on the same request), the TriggerEventRegistry.count equals 2.  If I comment out the constructor on RegisterTriggerComponentsHttpModule, then the value of TriggerEventRegistry.count equals 1 (which is should since there should only be one instance/request).
Here is the binding code:
Bind<ITriggerEventRegistry>().To<TriggerEventRegistry>().InRequestScope();

Any help on this would be greatly appreciated!
Note
I even made a request to my app using curl to avoid multiple HTTP requests being made by the browser looking for assets, a favicon or something like that. Still no joy.
Update
Upon further investigation, I'm also seeing that the ctor and the Init method of RegisterTriggerComponentsHttpModule is being called twice.

A: It's going to call your HttpModule as many times as there are requests.  For instance, most web browsers submit at least two requests, the page request and a favicon request.  Try adding something like an image to the page, and see if you get three requests...


text:
Q: Connect to Elasticsearch running on gcp instance I have a small gcp instance running elasticsearch (on port 9200) and cerebro (on port 9000). I have created firewall rules allowing connection to those 2 ports.
From my workstation I can access "http://instance_external_ip:9000" and I can get into the cerebro UI.
But if I try to curl "http://instance_external_ip:9200" from my workstation's CL I get a 'Connection refused'.
Elasticsearch is clearly running, since I can curl it from within the instance at localhost:9200, and I can access it via cerebro on my workstation.
Thanks for your help.

A: You can check if the Elasticsearch application is listening on port 9200 using netstat command and adding the atup options to show the TCP and UDP connexions, all sockets and the PID of the process:
netstat -atup

Check if the Firewall Rules are correctly configured for ingress connections, to the related port and if it's correctly applied on the network that your instance is running.


text:
Q: Erro occur when i POST Request to REST api i want to send POST Request in REST api but when i see in server side send an error message receive like this type-.
**{"messages":{"error":[{"code":404,"message":"Request does not match any route."}]}}**

this error is occurs.
and my program code is here-
NSString *post = [NSString stringWithFormat:@"postBody=%@",@"Rama"];
 NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];

 NSURL *myURL = [NSURL URLWithString:@"http://developer.b24solutions.com/grocery/api/rest/"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:0.0];

 [request setHTTPMethod:@"POST"];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *clearSession = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[clearSession start];
NSLog(@"%@",clearSession);
if(clearSession){
    NSLog(@"data send");
}
else
{
    NSLog(@"connection failed");
}

so where i am going wrong.
please help me.
and in server side work on php at same url.
 <?php
$result = $_POST['postBody'];

echo $result;

?>

A: error code 404 means file not fount. your api link not file name exits. please add full api path for example
developer.b24solutions.com/grocery/api/rest/yourfilename
Because this link not work in browser. You code is correct but incorrect api link.
NSURL *myURL = [NSURL URLWithString:@"http://developer.b24solutions.com/grocery/api/rest/giveyourfilenamewithextension"];


text:
Q: "enumeration" class, get all values I have a class I've written to act like an enumeration:
abstract class Enum {
   const VAL1 = "Val1";
   const VAL2 = "Val2";
}

I want to define a static function that will return all the constant members of the class but the only function I can find that does that is ReflectionClass::getStaticProperties. Unfortunately it doesn't look like I can use it this way. My understanding is that constants are implicitly static but the function is ignoring them. Is there a method I haven't found that will give me an array of constants in a similar way?

A: What about ::getConstants instead...?

A: You can use Reflection for this.
<?php
class Enum {
    const VAL1 = "Val1";
    const VAL2 = "Val2";
}

$refl = new ReflectionClass('Enum');
print_r($refl->getConstants());

Output:
Array
(
    ['VAL1'] => Val1
    ['VAL2'] => Val2
)


text:
Q: ADO.NET - Connect to SQL Server with Windows Login with login and password supplied by the application This is SQL Server 2008 R2, .NET 4.0.
In my SQL Server there is a user created with "Windows Authentication". The user exists in a Active Directory domain.
I want to make a .NET application connect to the SQL Server as this user. Inside the application, I know the user's domain, login and password, and the application has network access to the AD server.
How can I accomplish this?
I know that ASP.NET has it's AD provider and impersonation. But what I'm looking for is a really generic solution, one that should work on a plain console application. Something that I could use on console app, windows forms, asp.net, or a common business class library.
Thank you for the help!

A: I've done it using this class:
https://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials/
You must impersonate using LOGON32_LOGON_NEW_CREDENTIALS = 9 if the computer does not belong to the domain.
Once impersonated, then connect to SQL using "Integrated Security=true" on the SQL Connection String.
SqlConnection conn;
using (new Impersonator("myUserName", "myDomain", "myPassword", LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_DEFAULT))
{
    conn = new SqlConnection("Data Source=databaseIp;Initial Catalog=databaseName;Integrated Security=true;");
    conn.Open();
}
//(...) use the connection at your will.
//Even after the impersonation context ended, the connection remains usable.


text:
Q: Swift 5 - Unable to get images to populate from Array I am trying to populate a Collection View with an array of strings and an image but when the code runs the image being displayed is the initialized image not the one I pushed into the array.  However, the strings are correct.
I declare my class in a separate swift file:
import UIKit

class Tiles {
  var title: String?
  var image: UIImage?
  var display: String?

  init(title: String, image: UIImage, display: String) {
    self.title = title
    self.image = #imageLiteral(resourceName: "blank_whiteTile_48pt")
    self.display = display
  }
}

And then in the Collection View populate the array and then associate the array with the cells of the Collection View:
var tiles : [Tiles] = [Tiles(title: "Ceramic", image:#imageLiteral(resourceName: "ceramic_white"), display: "All"),
                       Tiles(title: "Marble", image: #imageLiteral(resourceName: "marble"), display: "All")]

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TileDisplay
    //define each cell
    cell.tiles = tiles[indexPath.item]

    return cell
}

I also tried to swap out the UIImage for UIImageView but that did not produce any different results.

A: In your initializer you need to do the following:
Remove the static value you assigned to the self.image.
Assign your image argument to self.image (thus making it dynamic)...
You can set your argument's default value so that if no argument is entered in the initialization call you automatically use the "#imageLiteral(resourceName: "blank_whiteTile_48pt")"...
What's happening right now is you have the value hardcoded.
init(title: String,
image: UIImage = #imageLiteral(resourceName: "blank_whiteTile_48pt"),
display: String) {
    self.title = title
    self.image = image
    self.display = display

}


text:
Q: What is the correct way to control thread parallelism? I was trying to benchmark a program I have writing against Mathematica (or better said the internal Kernels used, like MKL).
Since my program is not threaded I wanted to compare with Mathematica 10 running in a single core (I have a i7 processor). From this I discovered a certain option that seems to control the number of threads used by Mathematica and to my surprise, if I use it, I get better performance from Mathematica if I force it to use one threads.
In[1] := SetSystemOptions["ParallelOptions" -> "ParallelThreadNumber" -> 4];
SetSystemOptions["ParallelOptions" -> "MKLThreadNumber" -> 4];
n = 1024;
t = Table[RandomReal[], {i, 0, n}, {j, 0, n}];
Timing[Inverse[t]] // First

Out[1] := 0.626792

The above is the default and it takes 0.62 seconds to invert the matrix.
If I change the option I get better performance:
In[2] := SetSystemOptions["ParallelOptions" -> "ParallelThreadNumber" -> 1];
SetSystemOptions["ParallelOptions" -> "MKLThreadNumber" -> 1];
n = 1024;
t = Table[RandomReal[], {i, 0, n}, {j, 0, n}];
Timing[Inverse[t]] // First

Out[2] := 0.203677

I find hard to believe I found a bug in Mathematica, most likely I don't understand how this options work. Can somebody tell me if I am using these options correctly? Does the second line contain the correct code to force Mathematica to use only one thread?


text:
Q: How to include a variable and exclude numbers[0-9] and letters[a-zA-Z] in RegExp? I have a code that generates a random letter based on the word and I have tried to create a RegExp code to turn all the letters from the word to '_' except the randomly generated letter from the word.
const word = "Apple is tasty"
const randomCharacter = word[Math.floor(Math.random() * word.length)]

regex = new RegExp(/[^${randomCharacter}&\/\\#,+()$~%.'":;*?<>{}\s]/gi)
hint = word.replace(regex,'_')

I want to change all the letters to '_' except the randomly generated word. The above code for some reason does not work and shows the result: A___e __ ta_t_ and I'm not able to figure out what to do.
The final result I want is something like this: A____ __ _a___
Is there a way with regex to change all the alphabets and numbers '/[^a-zA-Z0-9]/g' to '_' except the randomly generated letter?
I'm listing all the expressions I want to include on my above code because I'm not able to figure out a way to do include and exclude at the same time using the variable with regex.

A: You can't do string interpolation inside of a RegExp literal (/.../). Meaning your placeholder ${randomCharacter} will not evaluate to its value in the template, but is instead interpreted literally as the string "${randomCharacter}".
If you want to use template literals, initialize your regex variable with a RegExp constructor instead, like:
const regex = new RegExp(`[^${randomCharacter}&\\/\\\#,+()$~%.'":;*?<>{}\\s]`, "gi");

See the MDN RegExp documentation for an explanation on the differences between the literal notation and constructor function, most notably:

The constructor of the regular expression object [...] results in runtime compilation of the regular expression. Use the constructor function when [...] you don't know the pattern and obtain it from another source, such as user input.

A: /(?:[^A\s])/
test it on regex101
just replace A in [^A\s] with you character that you want to ommit from replacement
demo:

const word = "Apple is tasty";
const randomCharacter = 'a';//word[Math.floor(Math.random() * word.length)];

regex = new RegExp('(?:[^' + randomCharacter + '\\s])', 'gi');
hint = word.replaceAll(regex, '_');

console.log(hint)