text:
Q: C#, custom error message for my firewall Presently I am doing a project on designing and implementing a firewall. Everything is working fine. Here I am filtering all packets going through a TCP port. But I need to send a custom page if a page is being blocked. Like "Your page is blocked by admin". I don't have any idea how to do it. Can I do it using raw sockets? If so please tell me, how to? But as I know raw socket does not work for sending on Windows XP SP2 and later, is there any other solution?
EDIT: I used C++ to create a DLL for an IP address filter. Then I imported it in my C++ program. IP addresses are blocking fine. But my customer needs the custom message when a browser is not finding its page.

A: If you're selectively allowing access to certain web pages, you're essentially acting like a proxy.  And you'll need to act more like one if you want to respond to clients with an error page.
A browser making an HTTP request will expect the response on the same connection it opened.  In order to return a "blocked" page, you'll need to determine whether the connection is to someplace you don't want the user to go, and if not, return a valid HTTP response (even if that response is an HTTP error like "403 Forbidden" or something more appropriate to a proxy) on that same connection.
If you're blocking the connection before it's even opened, ie: blocking access to certain IP addresses, then you're kind of stuck.  The most you could do is return an ICMP message saying the host isn't available.  You need to at least accept the connection if you can, accept the incoming request, and reply with your error message.  Anything less, and a browser typically won't know what to do with it.

A: Hey, Since you're working on that low level
Can't you redirect the request by modifying its HTTP header?


text:
Q: Compute the highest value with a given list and operators in OCaml With a given positive integer list and the addition and the multiplication as operators, I want to compute the highest value.
So if my list is [2,3,4], it will be : 2 * 3 * 4 = 24.
If there is at least one 1 in the list, it is a little bit more difficult. I found by testing on several examples that to compute the highest value, I have to add 1 to the minimum of the list and etc... until there is no more 1 in the list and compute the product of all integers.
For example : [1,2,3,4] would return ( 2 + 1 ) * 3 * 4 = 36; [1,1,2,3,4] would return ( 1 + 1 ) * 2 * 3 * 4 = 48.
My first question is concerning the algorithm part : how to prove properly that my method is correct and will always return the highest value ?
My second concerns the implementation :
I wrote the following code in OCaml to programm it :
(* Return 'list' with the first occurence of 'x' removed *)
let rec remove list x =
match list with
| [] -> []
| hd :: tl -> if hd = x then tl else hd :: remove tl x
;;

(* Return the maximum value which can be computed with the given list*)
let rec test_max list = match list with
  | [] -> 0
  | hd :: [] -> hd
  | hd :: tl ->
    (* If the list contains 1 : remove it from the list, then sort the list to get the min value and add 1 to it *)
    if List.mem 1 list then begin
      let list = List.sort (fun x y -> if (x < y) then 1 else 0) (remove list 1) in
      let test = (List.hd list) + 1 in
      test_max test::(List.tl list);
    end
    else
     List.fold_left ( * ) 1 list;;

And at the instruction
let test = (List.hd list) + 1 in
          test_max test::(List.tl list);

in test_max I get the error :
Error: This expression has type 'a list
       but an expression was expected of type int

Well, I don't really understand why it is expecting an expression of type int in the recursive call ... ?
Thank you in advance :)

A: Function application has higher precedence than ::. So, your code test_max test::(List.tl list) should indeed be test_max (test::List.tl list).
Also, you shouldn't use a ; in this place, as it's used to separate unit instructions. Just put nothing and it'll be fine.
As for some proof hints:
n + m > n * m
<=> ( n + m ) / (n * m) > 1
<=> 1/m + 1/n > 1

As we use positive integers, and as / is decreasing in its second argument. It's easy to see that this is true iff m or n = 1 (equality can be attained when n and m = 2).
Now, how do we use this +1?
(n+1) * m > n * (m+1)
<=> n * m + m > n * m + n
<=> m > n

So here are your two lemmas. I'll let you search for a full proof.

A: Your OCaml code is parsed as such:
(test_max test)::(List.tl list)

what you want is
test_max (test::(List.tl list))

Your implementation seems correct otherwise. You should use compare as argument of List.sort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pgfpages cleardoublepage I need to divide A4 into two A5 pages (landscape) which works fine with pgfpages but i also need special double page (like titlepage) where left half-page is empty and right contains text.
But this page sometimes splits so one part is on the previous page. I tried to use \cleardoublepage which doesn't end the whole A4 page (if half empty).
minimal example to clarify: (if text fills even number of A5 pages its fine but if number of pages filled by text is odd, my double page splits)
\documentclass[12pt,a4paper]{article}
\usepackage[left=2cm,text={17cm, 24cm},top=3cm]{geometry}
\usepackage{pgfpages}
\usepackage[czech]{babel}
\pgfpagesuselayout{2 on 1}[a4paper, landscape, border shrink=5mm]
\begin{document}

{\Large Empty page}

\newpage
{\LARGE Title page}
%end of special double page
\cleardoublepage

{\LARGE text unknown length}

\null\cleardoublepage
%beginning of second special double page
{\Large Empty page}

\newpage
{\LARGE Title page}
%end of second special double page
\null\cleardoublepage
{\LARGE text unknown length}

\end{document}

A: \cleardoublepage only does what you want in two-sided printing. So, add option twoside to the class options:
\documentclass[12pt,a4paper,twoside]{article}


text:
Q: What does the notation $\mathbb{Z}[X]$ refer to? Suppose that a mathematician wrote,

Let $f_0, f_1, f_2, \cdots$ be functions in $\mathbb{Z}[X]$

What does $\mathbb{Z}[X]$ mean?
I am aware that $\mathbb{Z}$ is used to denote the set of integers.
In other words, $\mathbb{Z} = \{\cdots, -100000, \cdots, -3, -2, -1, 0, +1, +2, +3, \cdots, +100000, \cdots\}$
What on earth is $\mathbb{Z}[X]$?

A: $\mathbb Z[X]$ is the ring of polynomials with integer coefficients. Written out in set-builder notation: $\mathbb Z[X]=\{\sum_{i=0}^{n} a_iX^i|i\in\mathbb N,a_i\in\mathbb Z \}$. You can plug in values of $\mathbb Z$ in for $X$ to get back an element of the base ring $\mathbb Z$. Though some authors may refer to a specific polynomial as "$f(x)\in \mathbb Z$," we consider polynomials as distinct algebraic objects here rather than  functions – we are not considering the polynomial as a morphism/mapping between two groups/rings/fields in the same way we would think about a homomorphism. $X$ in this case is considered an indeterminate, not a variable (you can read more about this here).
$\mathbb Z[X]$ is a countably infinite ring (you can prove this by checking the ring axioms as an exercise!), but not a field – all polynomial rings are not closed under multiplicative inverses. This same notation applies to polynomial rings over other rings/fields. For example, $\mathbb Z_2[X]=\{\sum_{i=0}^{n} a_iX^i|i\in\mathbb N,a_i\in\mathbb Z_2 \}$ is the set of polynomials with coefficients $0$ or $1$. You can generate an ideal, a special subgroup of the polynomial ring, using one such $f(x)\in \mathbb Z$.


text:
Q: Grouping Levels for Tags Every now and then, I update my IGNORE tags lists on stackoverflow so it's easier to browse questions that I might know something about and be able to help with.
If I don't use the IGNORE list, I have to do a ton of scrolling & reading through question pages...
So using the IGNORE list is helpful, but it's still tedius.  For example, if I want to ignore Joomla, since I have nothing to contribute to questions about Joomla, I have to ignore all of the following tags:
   - Joomla
   - Joomla1.5
   - Joomla-sef-urls
   - Joomla-template

And in addition to those, any new tags folks might create in the future -- Joomla2, Joomla3, etc.
Could it be possible to have a tag structure where, using the example above, "Joomla" would be the parent tag, and all of the others (Jooma1.5, etc.) would be identified by their creator as child-tags of Joomla.  And then, have the ability to ignore Joomla and all of it's children in one step?
Besides allowing users to ignore parents and all of their children, I can see this helping people to search for parents and all of their children as well, all in one swipe.
The parent/child structure could be multi-leveled -- e.g., Gread-grandparent --> Grandparent --> Parent --> Child; just however it made sense for ignoring or searching for entire groups / sub-groups.
Maybe you'd need a new rep step, for folks to have the ability to group tags they didn't create or something.
EDIT
This is already answered -- but it does lead me to wondering about parents/children with different names.  For example, there's a tag for 'ASP.NET', and there's a tag for 'gridview'.  This kind of parent/child relationship isn't found using wildcards.  I don't think it's a big deal per my original question though -- the wildcard has helped a lot!  But it might not be a replacement for relationships.

A: Why don't you just ignore joomla*?
More on Wildcards are available on the blog here and in the FAQ here


text:
Q: POST Request in API Testing using ROBOT Framework Hi All I want to POST the below format as input in ROBOT Framework.
{
    "Description": "School",
    "Details": [
    {
      "name": "Test1",
      "Surname": "XYZ"
    },
    {
      "name1": "Test2",
      "Surname2": "ABC"
    }
    ]
}

But I am getting the below error
body={"Error":"module 'jsonschema._utils' has no attribute 'types_msg'"}

Below is my code for the same
${tag_1} =  create dictionary        name="Test1"     value"XYZ"
      ${tag_2} =  create dictionary        name="Test2"     value"ABC"
      ${body} =  create list        Description="School"      Details=[$tag_1,$tag_2]
      ${header}=  create dictionary   Authorization=%{TEMP_TOKEN}   content-Type=application/json
     ${create_student}=  post On Session  ABCDE    /input   json=${body}     headers=${header}       expected_status=200

A: It looks to me like there are a few issues - Mainly, you're trying to store the json in an array, not an object and you're not converting to JSON.
There was also the double quotes around the key values and invalid key/value for value"XYX" and value"ABC" which also doesn't match your example as it should be "Surname"
Some example changes below:
# Name and Surname Objects - Updated to remove double quotes and match the provided json with "Surname" instead of "value"
${tag_1}  Create Dictionary  name=Test1  Surname=XYZ
${tag_2}  Create Dictionary  name=Test2  Surname=ABC

# Details List / Json Array
@{details}  Create List  ${tag_1}  ${tag_2}

# Body - Fixed so it's an object not an array
&{body}  Create Dictionary
...      Description=School
...      Details=${details}

# Convert the body to JSON
${body}  Evaluate  json.dumps(${body})  json

Output:
{"Description": "School", "Details": [{"name": "Test1", "Surname": "XYZ"}, {"name": "Test2", "Surname": "ABC"}]}


text:
Q: GET x-Auth-Token via JavaScript/Angular/Ionic Promise I have a problem and don´t know how to solve it...
I have to authenticate a user in my IonicApp through a token based authentication. So i have to store the token inside the app, which shouldn´t be a problem...
The Problem is: How can i get the token?
Here´s my code:
    // Alle Aufrufe an die REST-Api werden hier durchgeführt
    var httpCall = {
        async : function(method, url, header, params, data) {
//          if (url != 'login') {
//              header['X-Auth-Token'] = userTokenFactory.getUserToken();
//          }
            //console.log(header['X-Auth-Token']);
            var ipurl = "IPURL";
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = $http({
                method : method,
                url : ipurl + url,
                //headers : header,
                params : params,
                data : data,
                config : {
                    timeout : 5000
                }
            }).then(function successCallback(response) {
                //console.log("data:" + response.data);
                //console.log("header:" + response.headers);
                console.log("token:" + response.headers['X-AUTH-TOKEN']);
                //console.log(response.data.token);
                console.log("token" + repsonse.token);
                // TRY TO READ THE X_AUTH_TOKEN HERE !!!!!!!!!!!!
                return response;
            }, function errorCallback(response) {
                return response;
            });
            // Return the promise to the controller
            return promise;
        }
    };
    return httpCall;
});

And here´s a picture of the Response from the Server (from Firefox). As you can see, the X-Auth-Token is there...
here´s the x-auth-token
Thanks for the help!!

A: There are lot of articles are available over handling authentication in AngularJS. This article is the one perfect suitable in your case.
So you can get token from your request as,
}).then(function successCallback(response) {
    console.log("data:" + response.data);
    $window.sessionStorage.token = response.data.token;
    return response;
}, function errorCallback(response) {
    return response;
});

Now we have the token saved in sessionStorage. This token can be sent back with each request by at least three ways
1. Set header in each request:
`$http({method: 'GET', url: url, headers: {
    'Authorization': 'Bearer ' + $window.sessionStorage.token}
});`

2. Setting defaults headers
`$http.defaults.headers.common['X-Auth-Token'] = 'Bearer ' + $window.sessionStorage.token;`

3. Write Interceptor:

Interceptors give ability to intercept requests before they are
  handed to the server and responses before they are handed over to the
  application code that initiated these requests

myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    response: function (response) {
      if (response.status === 401) {
        // handle the case where the user is not authenticated
      }
      return response || $q.when(response);
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

Refer AngularJS $http guide for detailed explanation.
As you are getting response.data null and image demonstrates that headers are being returned, I would suggest you to check if you are getting data with
response.headers(),
if then try with response.headers()["X_AUTH_TOKEN"].


text:
Q: Is it possible to receive notification on Twitter Mention? I've written an app that will hopefully have its data updated when a Twitter user mentions my Twitter user name in a tweet. Simply put I've written a Score Board app and I'd like Twitter users to be able to tweet their best times which my app would then respond to:
@HankHendrix 45:12
I'm new to the Twitter API and already I've experienced difficulty finding the answers to my questions. I can't even find an IRC channel!
I am aware you can GET the mentions of a user via OAuth - I could CRON a script every 30 seconds to do this and then update my DB but ideally I'd like to be able to trigger a script in real-time (like long-polling).
This might be possible through the Twitter Streaming API - but again, the documentation doesn't appear to be noob friendly.
What are the solutions? I'm open to Node and Web Sockets etc.


text:
Q: Quotation Mark Lost in Array I have multiple strings in an array. They each already contain a quotation mark but I want to add another " to each string's end. This is how I do it:
for var str in coordinates {
    str += "\""
    print(str)
}
print(coordinates[0])

print(str) prints My"String" which is how it should be.
But print(coordinates[0] prints My"String
How come? Is this just how the strings are displayed but the actual string contains the "?
Thanks in advance.

A: In for var the var is only for the current scope inside the loop.
It's not a reference to the strings in the array, it's a copy (value).
You could mutate the existing strings in the array but the Swifty way of doing this is to create a new one, with map for example:
let result = coordinates.map { str in return str + "\"" }

Short version:
let result = coordinates.map { $0 + "\"" }


text:
Q: How do I conditionally turn @ECHO ON/OFF in a Windows batch file? I have a batch file that can be run locally or on the build server to do some kind of interesting job. On the local machine, I want @ECHO OFF so that your console isn't full of debug strings. On the build server, I'd rather have @ECHO ON so that failures can be investigated.
The build server context can be determined if a special environment variable exists (TEAMCITY_PROJECT_NAME). So, I thought I could do something like
IF DEFINED TEAMCITY_PROJECT_NAME @ECHO ON ELSE @ECHO OFF

But, that's not working, I get the IF statement echoed along with everything else... any thoughts?

A: set parentheses (see docu...):
IF DEFINED TEAMCITY_PROJECT_NAME (@ECHO ON) ELSE @ECHO OFF

A: Well, it seems that ECHO is on by default, so you'll get the IF statement output anyway you test that conditional. You should start with
@ECHO OFF

And add your conditional as another statement to evaluate
@ECHO OFF && IF DEFINED TEAMCITY_PROJECT_NAME @ECHO ON

A: As noted in earlier responses, ECHO is on by default.  An alternative way of achieving the same behavior is:
@if "%TEAMCITY_PROJECT_NAME%" == "" @echo off

A: The command is not actually named @echo. The @ is an optional flag valid at the beginning of a statement to indicate that echo is suppressed for that statement. So using the @ on each reference to the echo command will hide the echo command itself, but not the if command that precedes it.
But the issue that is actually causing your command to fail to operated as expected is that the first echo command will slurp up the rest of the tokens on the line as its arguments, so the else echo off part will not be interpreted by CMD. Since CMD.EXE echoes by default it prints the if command, and then either executes a single echo command or nothing. Since the @ does have meaning at the start of the statement that is the body of the if, neither echo command would be printed.
In general, the solution to that is to use parenthesis to delimit the command boundaries. However, since echo is on by default and you really only want to suppress it if TEAMCITY_PROJECT is not define, we can say that directly.
@IF NOT DEFINED TEAMCITY_PROJECT_NAME ECHO OFF

I've left a single @ at the beginning to suppress echo of this line, and as a result this line will not appear in your server's logs.
Related note
The echo state also applies to an interactive session. Typing echo off at an interactive CMD session prompt will cause it to stop showing the prompt. Which is a tad disconcerting, if not expected. Typing echo on will restore normal behavior.
More on Parsing
(I've edited the earlier section for clarity, and added this section to attempt to document what is really happening.)
The CMD.EXE program that interprets .BAT and .CMD scripts, and provides the interactive command prompt in modern Windows is surprisingly well documented while effectively being undocumented. My attempts to search for an official document explaining that the at-sign has this effect and exactly where it can be used have been largely unsuccessful.
It is clear from experimentation that the at-sign is parsed and interpreted if it appears as the first non whitespace character of a command. I've tried to express that by using the phrase "beginning of a statement" above.
As far as I can tell there is no formal grammar published for CMD's language. But we do know from the documentation for CDM itself (type cmd /? to a prompt) as well as if /? and the built-in help text for other "interesting" built-in commands that there are rules that are followed when CMD parses its source text.
The start of a command appears to be at the beginning of a line, or after the conditional of an if, after the else, or after an open parenthesis (. Once the at-sign has been recognized, it applies to (most) of the balance of that command.
Try the following batch file yourself, and play with moving the at signs around and you'll quickly get the sense that the rules are hard to state precisely:
rem this remark will echo
@rem this one will not
@ rem neither will this
 @rem nor this one
@rem the if command (and else) will echo, but not either echo command
if exist q17241089.bat ( @ echo saw q17241089.bat ) else @ echo foo
if not exist q17241089.bat ( @ echo no q17241089.bat ) else @ echo bar
@ rem none of the following command is echoed
@ if exist q17241089.bat ( @ echo saw q17241089.bat ) else @ echo spam

When run on my Win 7 Pro I see:
C...>
C...>q17241089.bat

C...>rem this remark will echo

C...>if exist q17241089.bat ()  else
saw q17241089.bat

C...>if not exist q17241089.bat ()  else
bar
saw q17241089.bat
C...>

As with most of the fine details of BAT files, there is a mystery underneath any surface you scratch.


text:
Q: XPATH to match contents of all child nodes within a parent element Suppose i have XMLs like this,
text

and
text

how do i write a generic xpath to match all the contents within the element  irrespective of the child nodes () instead of writing /a/b and /a because I can have any child node for the element .

A: To get the result equal to /a on your first XML sample and equal to /a/b on your second XML sample, you can use the following expression :
//a/descendant-or-self::*[not(*)]

The XPath return descendant of a or a itself whichever is the leaf element i.e element without child.
For demo, consider the following sample XML :
<root>
    text b
    text a
    <c>text c</c>
    <c><d>text d</d></c>
</root>

When the XPath above is executed the result will be :
text b
text a
<c>text c</c>
<d>text d</d>

demo


text:
Q: Is it true that the image of a perfect set is perfect under a continuous map? It is well-known that the image of a compact set is compact and the image of a connected set is connected under a continuous map. Here $A$ is perfect if $A$ it is equal to the derived set of itself.
I would like to ask if this property holds for perfect set. i.e

The image of a perfect set is perfect under a continuous map.

Thank you so much!

A: No, any compact metric space $X$ is the continuous image of $\{0,1\}^\mathbb{N}$, the Cantor cube, which is perfect. So also for the non-perfect $X=\{0,1\}$ (projection ) or the non-perfect $X=[0,1] \cup \{2\}$ etc.
This gives perfect maps from a perfect space with non-perfect image.

A: No, it is not true. Consider the image of $\Bbb R$ under $\arctan$ (as a subset of $\Bbb R$).
For compact sets, the boundedness property lets closed sets remain closed, so compactness is preserved. However, the property of no isolated points is not enough to preserve closedness, and thus perfect-ness (perfection? perfectity?) is not preserved in general.


text:
Q: Cassandra partitioned despite having connectivity and matching schema I have a 3 node cassandra (3.0.15) cluster, where nodes seem to have partitioned. nodetool status and nodetool describecluster outputs are inconsistent when seen from different nodes. Gossip information (nodetool gossipinfo) seems to be up to date on all nodes. No errors in the logs other than read timeouts which seems to be due from the partitioning.
Attempts to resolve this that didn't work:

*

*Rolling restart

*Full cluster restart

*disable/enable gossip on each node

Node1 (192.168.2.247):
$ nodetool describecluster
Cluster Information:
        Name: Test Cluster
        Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
        Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
        Schema versions:
                59ffe9aa-aca7-34b3-8c5e-b736d221b922: [192.168.2.248, 192.168.2.247]

                UNREACHABLE: [192.168.2.249]

$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address        Load       Tokens       Owns (effective)  Host ID                               Rack
UN  192.168.2.248  210.23 GB  256          67.7%             f6593c49-6739-4b8c-a8d9-8321915a660d  rack1
DN  192.168.2.249  190.9 GB   256          68.6%             6ac211c2-bab1-4e2b-bc84-18d911e005d0  rack1
UN  192.168.2.247  157.82 GB  256          63.7%             eb462857-cbfb-4e41-8be9-5d241d273b81  rack1

Node2 (192.168.2.248):
$ nodetool describecluster
Cluster Information:
        Name: Test Cluster
        Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
        Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
        Schema versions:
                59ffe9aa-aca7-34b3-8c5e-b736d221b922: [192.168.2.248, 192.168.2.249, 192.168.2.247]

$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address        Load       Tokens       Owns (effective)  Host ID                               Rack
UN  192.168.2.248  210.24 GB  256          67.7%             f6593c49-6739-4b8c-a8d9-8321915a660d  rack1
UN  192.168.2.249  190.9 GB   256          68.6%             6ac211c2-bab1-4e2b-bc84-18d911e005d0  rack1
UN  192.168.2.247  157.82 GB  256          63.7%             eb462857-cbfb-4e41-8be9-5d241d273b81  rack1

Node3 (192.168.2.249):
$ nodetool describecluster
Cluster Information:
        Name: Test Cluster
        Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
        Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
        Schema versions:
                59ffe9aa-aca7-34b3-8c5e-b736d221b922: [192.168.2.248]

                UNREACHABLE: [192.168.2.249, 192.168.2.247]

$ nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address        Load       Tokens       Owns (effective)  Host ID                               Rack
UN  192.168.2.248  210.24 GB  256          67.7%             f6593c49-6739-4b8c-a8d9-8321915a660d  rack1
UN  192.168.2.249  190.92 GB  256          68.6%             6ac211c2-bab1-4e2b-bc84-18d911e005d0  rack1
UN  192.168.2.247  157.84 GB  256          63.7%             eb462857-cbfb-4e41-8be9-5d241d273b81  rack1


text:
Q: Constraint choco I am using choco API to solve a problem. What I need is coding a constraint that make the sum of all my variables equal to 1.
This code keeps a sum of rows equal 1:
IntegerVariable[][] rows;
int n; //number of rows
for(int i=0; i<n; i++)
model.addConstraint(eq(sum(rows[i], 1));

But what I need is programming a code that keeps the sum of all my element's matrix (sum of rows) to be equaled to 1 and not the sum of each row = 1.

A: If I understand you correctly you want to ensure that the sums of the full matrix is equal to 1.
Then you can use an ArrayList ("all") to collect all the IntegerVariables into one list and then add a constraint to "all". Your example is not complete, e.g. the number of columns, so I assume that there are n columns and that it is a 0/1 matrix. Here's an example:
// ...
ArrayList<IntegerVariable> all = new ArrayList<IntegerVariable>();
int n = 5; // number of rows and columns
IntegerVariable[][] rows = new IntegerVariable[n][n];
for(int i = 0; i < n; i++) {
  for(int j = 0; j < n; j++) {
    rows[i][j] = makeIntVar("rows["+i+","+j+"]", 0, 1);
    all.add(rows[i][j]);
  }
}
// convert ArrayList all to an array
model.addConstraint(eq(sum(all.toArray(new IntegerVariable[1])),1));
// ...


text: Q: Use custome webserver to view xml file shows blank page in vs2013 Hi I have an xml file in my vs2013 project. If I set using the customer web server. It shows blank page during viewing in browser. If I change to use default setting and it works fine.  I already set the specific port for this webiste in IIS. Is my IIS setting or VS2013 cause the issue. Would someone tell me how to fix it. Thanks in advance.


text:
Q: Why _PROTOTYPE is used header files Why do we use _PROTOTYPE e.g. _PROTOTYPE( void *memset, (void *_s, int _c, size_t _n) I saw it in MINIX3 source code

A: Because as the header block says, they didn't know if an ANSI compiler or K&R was going to be used, and this marco allows them to keep the parameters in an ANSI build, and throw them away in a K&R build.
00033   /* Keep everything for ANSI prototypes. */
00034   #define _PROTOTYPE(function, params)    function params

verse
00045   /* Throw away the parameters for K&R prototypes. */
00046   #define _PROTOTYPE(function, params)    function()

which means
00483   _PROTOTYPE( void _exit, (int _status)    );

becomes under ANSI:
void _exit(int _status);

and under K&R:
void _exit();

A: The source code you linked to explains it:

00009  * If _ANSI ends up being defined, a macro
  00010  *
  00011  *      _PROTOTYPE(function, params)
  00012  *
  00013  * is defined.  This macro expands in different ways, generating either
  00014  * ANSI Standard C prototypes or old-style K&R (Kernighan & Ritchie)
  00015  * prototypes, as needed.  Finally, some programs use _CONST, _VOIDSTAR etc
  00016  * in such a way that they are portable over both ANSI and K&R compilers.
  00017  * The appropriate macros are defined here.

Old-style K&R prototypes have the argument names first, then the types:
int foobar (x, y)
    int x;
    float *y;
{
    /* code */
}

ANSI standard prototypes combine them both at the beginning:
int foobar (int x, float *y) {
    /* code */
}

The _PROTOTYPE macro creates an appropriate signature of either type depending on whether or not _ANSI is defined. In this specific case, K&R signatures are used for function implementations, but the function declarations either include or omit their arguments depending on whether _ANSI is defined.
It is worth noting that K&R-style declarations date from 1978 and most C code currently available will use modern ANSI style signatures. It is rare that you need to support both.

A: To accommodate both K&R and ANSI C function declaration styles. Take a look at Wikipedia article about C evolution.


text: Q: a function calls google.script.run works onload but not the button onclick


text:
Q: Gulp compile less files and minify them I'm new in the use of task runners like Gulp or Grunt, I have chosen to use Gulp to automate my tasks because I'm familiar with Javascript language.
I succeeded to compile my .less files to .css, I even wrote a task to minify my .css files.
I would like to run watch task with BrowSync, which automatically compile .less files to .css and .css to .min.css.
Here's my code :
gulp.task('minifyCSS', () => {
return gulp.src([
    'web/assets/css/*.css',
    '!web/assets/css/*.min.css'
])
    .pipe(sourcemaps.init())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(rename({ suffix: '.min'}))
    .pipe(gulp.dest('web/assets/css'));});

gulp.task('less', () => {
return gulp.src('web/assets/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('web/assets/css'))
    .pipe(browserSync.reload({
        stream: true
    }));});

gulp.task('watchSync', ['less', 'minifyCSS', 'browserSync'] , () => {
   gulp.watch('web/assets/less/*.less', ['less']);
});
gulp.task('browserSync', () => {
browserSync.init({
    notify: false,
    browser: "chrome",
    proxy: "localhost/web/app_dev.php",
    open: false
});});

The browserSync task runs well but it never compiles .css to .min.css. But when I run "gulp minifyCSS" it does the job ...
Do I miss a step ? Can anyone help me on this one ? :)

A: I'm nearly sure this will work:
gulp.task('minifyCSS', ['less'], () => {
  return gulp.src([
        'web/assets/css/*.css',
        '!web/assets/css/*.min.css'
    ])
    .pipe(sourcemaps.init())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(rename({ suffix: '.min'}))
    .pipe(gulp.dest('web/assets/css'))
    .pipe(browserSync.reload({
        stream: true
    }))
   ;
});

gulp.task('less', () => {
  return gulp.src('web/assets/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('web/assets/css'))
  ;
});

gulp.task('watchSync', ['minifyCSS', 'browserSync'] , () => {
  gulp.watch('web/assets/less/*.less', ['minifyCSS']);
});

gulp.task('browserSync', () => {
  browserSync.init({
      notify: false,
      browser: "chrome",
      proxy: "localhost/web/app_dev.php",
      open: false
  });
});


text:
Q: Batch - check if user input is in a text file then proceed I am making a chat style system for LAN networked computers, and want to make a check for if username is in use or not. I can't get it to work though, here is what i have in a test file, that Does work...
@echo off
title Testing usercheck

setlocal EnableDelayedExpansion

set "user2="
set /p "user2="
find /c "%user2%" Users.twml
if %errorlevel% equ 1 goto yes
goto nope

:empty
cls
echo empty response, should not be triggered...
pause
goto end

:yes
cls
echo yes, you can use that
>> Users.twml echo %user2%
pause
goto end

:nope
cls
echo nope. that is taken... try again!
pause
goto end

:end
cls
echo.
echo End of testing file...
echo.
echo press any key to exit
pause>nul
exit

This takes user input, checks the file to see if it is in there, if it is, says cant use, if its not there, it says can use and saves the name to the text file so others cant pick same. However when i put it in my main file that im making the same thing doesnt work, when saving the name to file the file records
ECHO is off.

Being caused by this line here
>> Users.twml echo %user2%

and not the username the user entered, Strangely though it works in the test file perfectly, here is the section of my main file that doesnt work.
@echo off
title Batch Chat Room
mode con: cols=83 lines=10

setlocal EnableDelayedExpansion

:startup
cls
echo Pick A UserName
echo 1-16 Character limit.
set "user2="
set /p "name2="
if "!name2!" == "" goto startup
if "!name2!" == " " goto startup
if "!name2!" == "  " goto startup
if "!name2!" == "   " goto startup
if "!name2!" == "    " goto startup
if "!name2!" == "     " goto startup
if "!name2!" == "      " goto startup
if "!name2!" == "       " goto startup
if "!name2!" == "        " goto startup
if "!name2!" == "         " goto startup
if "!name2!" == "          " goto startup
if "!name2!" == "           " goto startup
if "!name2!" == "            " goto startup
if "!name2!" == "             " goto startup
if "!name2!" == "              " goto startup
if "!name2!" == "               " goto startup
if "!name2!" == "                " goto startup
if not "!name2:~16!" == "" goto over
find /c "%user2%" Users.twml
if %errorlevel% equ 1 goto conta
goto tryagaina

:conta
cls
echo yes, you can use that
>> Users.twml echo %user2%
pause
:: This pause is just for testing to add a wait here
copy /y NUL Connected.twml >NUL
copy /y NUL Directory.twml >NUL
attrib +h Connected.twml
attrib +h Directory.twml
cls
>> Connected.twml echo [System] %computername%:%username% Has joined as: %name2%
>> Directory.twml echo [System] %name2% Has joined the chat.
title Lightfoot Web - Batch ChatRoom - (User Typing) - (Username:%name2%)
goto A

:tryagaina
goto startup

Here is the inside of Users.twml First 2 lines were written by the testing file, the others by my main file.
twml
bob
ECHO is off.
ECHO is off.
ECHO is off.

At first i tried findstr, but couldn't get it to work, so i used errorlevel as i do know how that works quite well. but it wont save name to file using my main file. Im stumped with this because the lines for Connected.twml and Directory.twml both write their content, just Users.twml will not.

A: Answered!
Im such an Idiot lol
I used %name2% in my main file and %user2% in the test file, so of course the parts wont work together, they not same variable. Duh...
Here is the fixed code:
:startup
cls
echo Pick A UserName
echo 1-16 Character limit.
set "name2="
set /p "name2="
if "!name2!" == "" goto startup
if "!name2!" == " " goto startup
if "!name2!" == "  " goto startup
if "!name2!" == "   " goto startup
if "!name2!" == "    " goto startup
if "!name2!" == "     " goto startup
if "!name2!" == "      " goto startup
if "!name2!" == "       " goto startup
if "!name2!" == "        " goto startup
if "!name2!" == "         " goto startup
if "!name2!" == "          " goto startup
if "!name2!" == "           " goto startup
if "!name2!" == "            " goto startup
if "!name2!" == "             " goto startup
if "!name2!" == "              " goto startup
if "!name2!" == "               " goto startup
if "!name2!" == "                " goto startup
if not "!name2:~16!" == "" goto over
find /c "%name2%" Users.twml
if %errorlevel% equ 1 goto conta
goto tryagaina

:conta
cls
echo yes, you can use that
>> Users.twml echo %name2%
pause
:: This pause is just for testing to add a wait here
copy /y NUL Connected.twml >NUL
copy /y NUL Directory.twml >NUL
attrib +h Connected.twml
attrib +h Directory.twml
attrib +h Users.twml
cls
>> Connected.twml echo [System] %computername%:%username% Has joined as: %name2%
>> Directory.twml echo [System] %name2% Has joined the chat.
title Batch Chat Room (Username:%name2%)
goto A

:tryagain
goto startup

this now works, case closed :)


text:
Q: Is this Bilinear form inner product
$$Q(x,y)=x^{T}\begin{pmatrix}
     1      & 1 \\
      1        & 2
    \end{pmatrix} x$$

Can this Bilinear form be a inner product in $\mathbb{R}^2$?
It is easy to see it is symmetric, but how can I proof it is always positive?

A: x^2 + 2xy + 2y^2 = (x+y)^2 + y^2.


text:
Q: Django Many To Many Field Query Admin Page I have a field in my student model called counselors. All I am trying to do is list the users that are in the group counselors to be displayed in this many to many relationship. How do i go about doing this? Here is the field in my model. Thanks
  counselor = models.ForeignKey(User, related_name='Counselors', on_delete = models.PROTECT,null=True,blank = True)

The current setup only shows all the users within the User table not Users associated in the Counselors group.

A: counselor = models.ForeignKey(User, limit_choices_to={'groups__name': "Counselors"},on_delete = models.PROTECT,null=True,blank = True )


text:
Q: Alternative for export AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY I've been using Ansible to provision an ec2 instance. Every time I start the VM I have to execute
export AWS_ACCESS_KEY_ID = ACCESS-KEY-ID
export AWS_SECRET_ACCESS_KEY = SECRET-ACCESS-KEY

before running the ansible-playbook to provision/configure the instance.
I have written a playbook which executes above commands using raw module of Ansible, even after executing that playbook I have to manually execute those commands before I can run the provision.yml script.
Is there an efficient way of doing these from the playbook itself????, because I am actually working on some automation job which doesn't encourage manual execution of commands.

A: Ansible can set environment variables:
In your playbook:
- name: "Simple playbook"
  hosts: localhost
  roles:
     - aws
  environment:
     AWS_ACCESS_KEY_ID: "{{ aws_access_key }}"
     AWS_SECRET_ACCESS_KEY: "{{ aws_secret_key }}"

I would strongly recommend learning how to use ansible-vault as a quick an easy way to store credentials in Ansible.
Also note, that if you are using the ec2.py Dynamic inventory script, the above solution will not work. The inventory is loaded before the environment is set by the playbook. In this case, the best option would be to use one of the alternate AWS credential methods. One simple method is a ~/.boto file with the contents:
[Credentials]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_ACCESS_SECRET


text:
Q: Spawn a set of threads iteratively in C++11? I have a function that populates entries in a large matrix. As the computations are independent, I was thinking about exploiting std::thread so that chunks of the matrix can be processed by separate threads.
Instead of dividing the matrix in to n chunks where n is the limit on the maximum number of threads allowed to run simultaneously, I would like to make finer chunks, so that I could spawn a new thread when an existing thread is finished. (As the compute time will be widely different for different entries, and equally dividing the matrix will not be very efficient here. Hence the latter idea.)
What are the concepts in std::thread I should look into for doing this? (I came across async and  condition_variables although I don't clearly see how they can be exploited for such kinds of spawning). Some example pseudo code would greatly help!

A: Why tax the OS scheduler with thread creation & destruction? (Assume these operations are expensive.) Instead, make your threads work more instead.
EDIT: If you do no want to split the work in equal chunks, then the best solution really is a thread pool. FYI, there is a thread_pool library in the works for C++14.
What is below assumed that you could split the work in equal chunks, so is not exactly applicable to your question. END OF EDIT.
struct matrix
{
    int nrows, ncols;
    // assuming row-based processing; adjust for column-based processing
    void fill_rows(int first, int last);
};

int num_threads = std::thread::hardware_concurrency();
std::vector< std::thread > threads(num_threads);

matrix m; // must be initialized...
// here - every thread will process as many rows as needed
int nrows_per_thread = m.nrows / num_threads;
for(int i = 0; i != num_threads; ++i)
{
    // thread i will process these rows:
    int first = i * nrows_per_thread;
    int last = first + nrows_per_thread;
    // last thread gets remaining rows
    last += (i == num_threads - 1) ? m.nrows % nrows_per_thread : 0;
    threads[i] = std::move(std::thread([&m,first,last]{
                 m.fill_rows(first,last); }))
}

for(int i = 0; i != num_threads; ++i)
{
    threads[i].join();
}

If this is an operation you do very frequently, then use a worker pool as @Igor Tandetnik suggests in the comments. For one-offs, it's not worth the trouble.


text:
Q: Como calcular média e mostrar os valores maior e menor? Comecei a estudar SQL SERVER e de cara deparei com o seguinte problema:

crie uma função que calcula a média dos alunos e se for MAIOR IGUAL QUE 7 o aluno deve ser considerado aprovado; se não, reprovado.

Como faço isso?

A: Edit
Com a tabela passada pela @LuzineteMaciel
obs: conforme comentado pelo José Diz foi adicionado verificação se os valores são nulos para evitar retorno com NULL
SELECT
    dessecod                                AS dessecod,
    MatCod                                  AS MATERIA,
    (ISNULL(BolNota1, 0) + ISNULL(BolNota2, 0))                 AS SOMA_NOTA,
    ((ISNULL(BolNota1, 0) + ISNULL(BolNota2, 0))/2)   AS MEDIA,
    CASE
        WHEN ((ISNULL(BolNota1, 0) + ISNULL(BolNota2, 0))/2) < 7 THEN 'Reprovado'
        else 'Aprovado'
    END                     AS RESULTADO
FROM TbBoletim
GROUP BY
    dessecod,
    MatCod,
    BolNota1,
    BolNota2

Na pergunta não é informado a descrição da tabela, logo criei uma estrutura e uma query para ilustrar uma possível forma de solucionar o problema
CREATE TABLE ALUNOS(
    ID INTEGER IDENTITY,
    NOME VARCHAR(150),
    MATERIA VARCHAR(20),
    NOTA DECIMAL(10,2)
)

INSERT INTO ALUNOS(NOME, MATERIA, NOTA) VALUES
    ('Leonardo', 'Matematica', 8),
    ('Leonardo', 'Matematica', 9),
    ('Leonardo', 'Matematica', 8),
    ('João', 'Matematica', 8),
    ('João', 'Matematica', 8),
    ('João', 'Matematica', 6),
    ('Maria', 'Matematica', 4),
    ('Maria', 'Matematica', 4),
    ('Maria', 'Matematica', 4)

SELECT
    NOME                    AS NOME_ALUNO,
    MATERIA                 AS MATERIA,
    SUM(NOTA)               AS SOMA_NOTA,
    COUNT(ID)               AS TOTAL_NOTA,
    (SUM(NOTA)/COUNT(ID))   AS MEDIA,
    CASE
        WHEN (SUM(NOTA)/COUNT(ID)) <7 THEN 'Reprovado'
        else 'Aprovado'
    END                     AS RESULTADO
FROM ALUNOS
GROUP BY
    NOME,
    MATERIA

Saída:
NOME_ALUNO  MATERIA     SOMA_NOTA   TOTAL_NOTA  MEDIA       RESULTADO
João        Matematica  22.00       3           7.333333    Aprovado
Leonardo    Matematica  25.00       3           8.333333    Aprovado
Maria       Matematica  12.00       3           4.000000    Reprovado


text:
Q: TimeZone Issue during DayLight Saving I just been bugged by the Day light saving hours
I seem that 3rd November 2013 01:00:00 start EST time
Now ever Time I set my time to 3rd November 2013 00:58:xx(some seconds)
and run date
it give me valid Time zone i.e EDT
but
even after the time pass 01:00:00 and I still query the date library
I still see the Time zone as EDT and not EST
have a look at this screenshot
You can clearly see the Time zone saying as EDT even when it is EST
any one has a clue for this
Update
There is one other finding I found if I restart my machine I see this

More Update
Before Restart

After Restart

A: What was the current time and timezone when you set the clock ?
In any case, use date -u to figure out what exactly the system clock is set to.
EST time doesn't start at 01:00 but at 02:00 which turns to 01:00 EST.


text:
Q: STM32F407G-DISC1 not working if not connected to pc I have a Discovery board DISC1 version (february 2016 revision).
I had programmed a Discovery board before with no issues. The ones that I more recently bought, the DISC1 version, have a strange issue: after I flash the program, if I connect them to the PC via USB (CN1), everything works fine, but if I power it up with external +5V or with the CN1 (but not from an USB port), the LD1 led start blinking, the the LD2 red led turns on, but nothing else happens. The rest of the board is off.
I stress that this never happened with the previous revision of the same board, i always powered it up via external +5V and it always worked correctly.
Does anyone have a clue why this is happening?

A: I experienced the same problem and there are two solutions to get the behavior of the old board.

*

*Use the ST-Link Upgrade Utility to flash to an older version of the ST-Link v2/1. With version V2.J23.M9 it's ok. But you lose the compatibility to mbed.

*Open the solder bridge SB19. The new board has this bridge closed, resulting in a low BOOT1-pin. When the bridge is opened the BOOT1 is pulled to Vdd. If you do not want open the solder bridge, you can use an external jumper wire from Vdd to PB2.

A: I had the same question with V2J25 firmware. And I found if I upgrade to V2J27M15 (newest version 2016/09/16), it is solved.

A: I experienced the same problem. Here my solution, although not 100% satisfying:
Set the Jumper SB10 on the bottom of the board. A solder blob will do it.
For some reason the ST-Link/V2 part of the new STM32F407G-Disk1 board behaves different than the old version STM32F4 Discovery and prevents the STM32F4 mcu to start properly. SB10 forces the ST-link mcu in reset state.
Warning:
Since I only program the STM32F4 using the usb dfu programmer, i don't need the ST-Link/V2 part for programming. Don't set the Jumper, if you need the ST-Link! It will not work afterwards!

A: Just upgrade the firmware and it works.
V2-J28-M18 (February 2017)
Jan F. Boot1 to PB2 proposal does not work. Neither does desoldering SB19.
How to upgrade:
If you use ST-Link utility, make sure you have the latest version, in the menu:
ST-LINK-> firmware update   connect.
YOU CANNOT CHOOSE the firmware version! So, if the version is a different version, download the latest version (it comes as a little program):
http://www.st.com/en/embedded-software/stsw-link007.html
was going to comment on Jan F. but I lack one karma point to be allowed to do that!


text:
Q: SQL query to transform graph path with flux into adjacent node flux Given a table describing paths with flux in a graph
node1 | node2 | node3 | flux
A     | B     | C     | 15
E     | B     | D     | 10
A     | B     | D     | 5

I want to query the sum of flux for adjacent nodes, ie
out_node | in_node | flux
A        | B       | 20 (15 + 5)
B        | C       | 15
E        | B       | 10
B        | D       | 15 (10 + 5)

Node that A ~> C would be 0 since we don't have a direct edge between A and C
What I thought:
We could do multiple queries grouping by adjacent nodes, eg
SELECT node1 as out_node,
       node2 as in_node,
       sum(flux)
FROM table,
GROUP BY out_node, in_node

SELECT node2 as out_node,
       node3 as in_node,
       sum(flux)
FROM table,
GROUP BY out_node, in_node

Then concatenate these two queries and do another GROUP BY
Is there any better solution for a high number of nodes in a path? Since for eg 1000 nodes we would need to do 999 queries

A: You can do:
select node1, node2, sum(flux) as flux
from (
  select node1, node2, flux from t
  union all select node2, node3, flux from t
) x
group by node1, node2

Result:
 node1  node2  flux
 ------ ------ ----
 A      B      20
 B      C      15
 B      D      15
 E      B      10

See running example at DB Fiddle.


text:
Q: How to have UI subscribe to DynamoDB events? I have an EC2 service that writes data to a DynamoDB table. I also have an app that is totally unrelated to the service. Now I want the app to display components in its UI based off the status attribute of items in the DynamoDB table.
It looks like I can have the app UI subscribe to a DynamoDB Stream. However, I need data in my table to persist for >24hrs, data in DDB Streams older than 24hrs is susceptible to removal.
I would ideally like a solution where on each new DyanmoDB write/update of the status of an item, I can send a notification to the app telling them of the change which would render a change in their UI. How can I go about making the app constantly listen, and how do I send a notification? I can't have the app directly access the database, it must go through the service.
I am new to AWS.

A: You do not need longer than 24 hour retention on the stream. Streams are used to emit each modification to your items, so with each change you notify your application.
Two ways I can think of to do this, both use DynamoDB streams and Lambda.
1. SNS
Amazon Simple Notification Service (SNS) is a two way messaging service which you can have your application subscribe to a topic. For every change made to to your DynamoDB table you write that to an SNS topic and your application will receive the changes to render the UI.
https://aws.amazon.com/pub-sub-messaging/
2. API Gateway Websocket
An altern to SNS messaging is API Gateway Websocket which allows your application subscribe to a network connection. This is more useful if you need short lived notification for given events.
https://docs.aws.amazon.com/appsync/latest/devguide/aws-appsync-real-time-create-generic-api-serverless-websocket.html


text:
Q: ReferenceError when the variable is being logged in console? A followed up issue from: orderByKey is not a function in reactjs expo?
Having a issue where my variable random is generating a random number for me to use to get a random node in firebase realtime DB but I am getting a reference error even though I have console log the variable random and it is giving me a value.
Here is my code:
import { StyleSheet, Text, View } from 'react-native'

import {db} from '../firebase'
import React, {useEffect, useState} from 'react'
import {ref, get, orderByKey, limitToFirst} from 'firebase/database'

const SubScreen2 = () => {

  const [todoData, setToDoData] = useState([])

  useEffect (() => {
    get(ref(db, "food/Total")).then(snapshot => {
      const count = snapshot.val();
      const random = Math.floor((Math.random() * count));
      console.log(random)
      return get(ref(db, `food/`), orderByKey(), limitToFirst(random + 1))
    }).then(snapshot => {
      const randomKey = Object.keys(snapshot.val())[random];
      setToDoData(snapshot.val()[randomKey]);
    }).catch(error => {
      console.log(error);
    })
  }, [])
  console.log(todoData)
  return (
    <View style={styles.container}>
      {todoData ? (
        <View>
          <Text>{todoData.Description}</Text>
          <Text>{todoData.Location}</Text>
          <Text>{todoData.Halal}</Text>
          <Text>{todoData.OH}</Text>
        </View>
      ) : (
        <Text>Loading...</Text>
      )}
    </View>
  )
}

export default SubScreen2

My console log:

I don't get how am I getting a reference error even though the log for random has a value of 96?

A: The issue is with this line:
const randomKey = Object.keys(snapshot.val())[random];

The variable is out of scope as you declare it in the previous block.
Maybe you can do something like...
  useEffect (() => {
    let random = 0;
    get(ref(db, "food/Total")).then(snapshot => {
      const count = snapshot.val();
      random = Math.floor((Math.random() * count));
      console.log(random)
      return get(ref(db, `food/`), orderByKey(), limitToFirst(random + 1))
    }).then(snapshot => {
      const randomKey = Object.keys(snapshot.val())[random];
      ...


text:
Q: Download the eligible file from SFTP server by using spring Integration using Spring boot project My current project is based on Spring Integration. I am developing this project by using spring Boot.
My goal is to use Spring Integration to complete the below task.

*

*Connect to SFTP

*check if directory is created in the local at a specific folder

*check the eligible file extension of the file specific to (CSV & XLSX)

*Down load all the content from SFTP remote directory to local directory & need to track the file transfer start time and file transfer end time.

*Read the file from local directory line by line and extract the certain column info.
Can you give me some suggestions ?
And how can I get the transfer start time ?
Note : This requirement i have to develop as an rest api. Please provide some guidance how i can achieve this by using spring integration?
Thanks. :)
public class SftpConfig {

    @Value("${sftp.host}")
    private String sftpHost;

    @Value("${sftp.port:22}")
    private int sftpPort;

    @Value("${sftp.user}")
    private String sftpUser;

    @Value("${sftp.password:#{null}}")
    private String sftpPasword;

    @Value("${sftp.remote.directory:/}")
    private String sftpRemoteDirectory;

    @Value("${sftp.privateKey:#{null}}")
    private Resource sftpPrivateKey;

    @Value("${sftp.privateKeyPassPhrase:}")
    private String privateKeyPassPhrase;

    @Value("${sftp.remote.directory.download.filter:*.*}")
    private String sftpRemoteDirectoryDownloadFilter;

    @Value("${sftp.remote.directory.download:/}")
    private String sftpRemoteDirectoryDownload;

    @Value("${sftp.local.directory.download:${java.io.tmpdir}/localDownload}")
    private String sftpLocalDirectoryDownload;

    /*
     * The SftpSessionFactory creates the sftp sessions. This is where you define
     * the host , user and key information for your sftp server.
     */

    // Creating session for Remote Destination SFTP server Folder

    @Bean
    public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost(sftpHost);
        factory.setPort(sftpPort);
        factory.setUser(sftpUser);
        if (sftpPrivateKey != null) {
            factory.setPrivateKey(sftpPrivateKey);
            factory.setPrivateKeyPassphrase(privateKeyPassPhrase);
        } else {
            factory.setPassword("sftpPassword");
        }
        factory.setAllowUnknownKeys(true);
        return new CachingSessionFactory<ChannelSftp.LsEntry>(factory);
    }

    /*
     * The SftpInboundFileSynchronizer uses the session factory that we defined above.
     * Here we set information about the remote directory to fetch files from.
     * We could also set filters here to control which files get downloaded
     */

    @Bean
    public SftpInboundFileSynchronizer SftpInboundFileSynchronizer () {
        SftpInboundFileSynchronizer synchronizer = new SftpInboundFileSynchronizer();
        return null;

    }

A: If you take a look into the SftpStreamingMessageSource instead: https://docs.spring.io/spring-integration/docs/current/reference/html/sftp.html#sftp-streaming, plus use a FileSplitter to read that file line by line (which supports a "first like as header", too), you won't need to worry about transferring the file to local dir. You will do everything with the remote content on demand.
On the other hand, since you talk about a REST API, you probably are going to have some @RestController or Spring Integration HTTP Inbound Gateway: https://docs.spring.io/spring-integration/docs/current/reference/html/http.html#http-inbound, then you need to think about using an SftpOutboundGateway with an MGET command: https://docs.spring.io/spring-integration/docs/current/reference/html/sftp.html#sftp-outbound-gateway.
If you still need to track a download time for every single file, you need to consider to use that gateway twice: with a LIST command and NAME_ONLY, and the second time for GET command. At this point you can add ChannelInterceptor for input and output channels of the second gateway, so you will have a file name info to correlate and catch start and stop time before and after this gateway.


text:
Q: I Cannot Get Images From Firebase Storage Folders Dynamically I have some folders on Firebase Storage. I want to get photos from folders dynamically, but I cannot.
Example: I try to code a basic E-Commerce website, and every product's photo gallery is a seperated folder. Folder names are also written to my Firestore Database, and when the product.productImageFolder is same with Firebase Storage folder name, show me the photos inside that folder. I want to show images in the  tag dynamically, and I try to find a solution for hours but I couldn't make it.
In the code below I can get photo download link, but I want to make it dynamic. Is there any way to do that?
const listRef = ref(storage, "productImages/jacket-for-kids");

    // Find all the prefixes and items.
    listAll(listRef)
        .then((res) => {
            res.items.forEach((itemRef) => {
                // All the items under listRef.
                getDownloadURL(itemRef).then(downloadURL => {
                    console.log(downloadURL);
                })
            });
        })

    return (

            {
                products.filter(product => product.productGender.includes('Kids')).slice(0, showProducts).map(product => (

                        <Link to={`/productBuy?id=${product.productImageFolder}`}>

                                    {product.productName}

                                    €{product.productPrice}

                        </Link>

                ))
            }

I checked some resources to find a solution, but I couldn't find anything on youtube, stackoverflow, firebase documentation or other websites. Is there anyone that can help me with this question?


text:
Q: cannot make sqlcmd work after runas I followed a few examples here, but I still can not get my sqlcmd work after runas.
I can make it work with two steps:

*

*Step one:  Use runas to login into a new login and open a command prompt:
runas.exe /savecred  /user:DOMAIN_NAME\login_name cmd.exe

*Step two: execute the sqlcmd in a script
sqlcmd -S server_name -E /Q"exit(SELECT @@version )"
But I want to make it one step to get the results.  I tried to add " " after the runas command as listed below, but it did not work:
runas.exe /savecred  /user:DOMAIN_NAME\login_name "sqlcmd -S server_name -E /Q"exit(SELECT @@version )""

Any ideas?

A: Take a look at this article describing RunAs. Toward the end of the article, he specifically addresses needing to use quotes inside of quotes:

Fortunately, it's fairly easy to make RunAs happy. All you need to do is use the \ character to "escape" any double quote marks that must to be embedded within the process path.

So, it looks like your command should be:

runas.exe /savecred  /user:DOMAIN_NAME\login_name "sqlcmd -S server_name -E /Q\"exit(SELECT @@version )\""

Notice the \ before both of the nested double quotes.


text:
Q: Hartshorne Theorem 3.4: isomorphism Let $Y\subseteq\mathbb{P}_k^n$ be a projective variety with homogeneous coordinate ring $S(Y)$.
I have to prove that the following map $J$ is an isomorphism. Define $J\colon k[y_1,\dots, y_n]\to k[x_0,\dots, x_n]_{(x_i)}$ by $$J(f(y_1,\dots, y_n)):=f\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)$$
Injectivity:
Let $$f\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)=g\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)$$
Letting this element be of the form $s/x_i^e$ for some $s\in S(Y)_e$ and $e\ge 0$. we notice that $$x_i ^ef\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)=x_i^e g\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)$$ where both sides of the equality is a homogeneous polynomial of degree $e$. Now using the dehomogenization map we get $f=g$ in $k[y_1,\dots, y_n]$
Surjectivity:
Let $f(x_0,\dots,x_n)\in k[x_0,\dots, x_n]_{(x_i)}$, then $f(x_0,\dots, x_n)=s/x_i^m$, where $s\in S_m$, that is $s$ is a homogeneous polynomial of degree $m$. Then $$f(x_0\dots, x_n)=f\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg).$$
By placing $y_1=\frac{x_0}{x_i},\dots, y_n=\frac{x_n}{x_i}$ we have $$J(f(y_1,\dots, y_n)):=f\bigg(\frac{x_0}{x_i},\dots, \frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\cdots, \frac{x_n}{x_i}\bigg)=f(x_0,\dots, x_n)$$
It's correct? Thanks!


text:
Q: Why does rust's read_line function use a mutable reference instead of a return value? Consider this code to read the user input in rust
use std::io;
fn main() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("error: unable to read user input");
    println!("{}", input);
}

why is there no way to do it like this?
use std::io;
fn main() {
    let mut input = io::stdin()
        .read_line()
        .expect("error: unable to read user input");
    println!("{}", input);
}

it would be more convenient to other languages

A: TL;DR The closest you have is lines(), and the reason read_line works like it does is efficiency. The version that uses lines() looks like this:
use std::io::{self, BufRead};

fn main() {
    // get next line from stdin and print it
    let input = io::stdin().lock().lines().next().unwrap().expect("IO error");
    println!("{}", input);
}

In general, read_line() is not designed for use in small interactive programs; there are better ways to implement those.
The read_line method comes from the generic io::BufRead trait, and its primary use is reading input, typically redirected from files or other programs, and possibly coming in large quantities. When processing large amounts of data, it is advantageous to minimize the number of allocations performed, which is why read_line is designed to reuse an existing string. A typical pattern would be:
let mut line = String::new();
while input.read_line(&mut line)? != 0 {
    // do something with line
    ...
    line.clear();
}

The number of (re-)allocations is kept minimal, as line will grow only as needed to accommodate the input lines. Once a typical size is reached, allocations will become very rare, and once the largest line is read, they will disappear altogether. If read_line() supported the "convenient" interface, then the above loop would indeed look nicer - for example:
while let Some(line) = read_new_line(some_input)? {
    // process the line
    ...
}

...but would require a new allocation and deallocation for each line. In throw-away or learning programs this can be perfectly fine, but BufRead is intended as a building block for efficient IO, so its read_line method favors performance over convenience.


text:
Q: Как можно определить язык текста на windows? Есть список из русских и английских слов вперемешку, нужно разделить его на 2 словаря. Один словарь содержит все русские слова, второй все английские. Как это сделать на windows?
li = ['dog', 'cat', 'собака', 'кот']

A:  alphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
 li = ['dog', 'cat', 'собака', 'кот']
 rus = {}
 engl = {}

for word in li:
   for w in word:
    if w in alphabet:
        rus[word]=''
        rus.update()
    else:
        engl[word] =''
        engl.update()

print('*',rus)
print('**',engl)


text:
Q: Horrible experience on Stack powered sites today. What's wrong with this picture? So, I went over to SuperUser.com to ask this question:
https://superuser.com/questions/199160/any-sites-out-there-that-show-pricing-for-products-that-have-secret-pricing-clo
A little while goes by and I come back to see if there's any answers. It got migrated to webapps.stackexchange.com. Then it was immediately CLOSED by a different user on webapps.stackexchange.com for not being the right kind of question.
What's wrong with this picture?
Web app site = application = software. There are tons of questions on SuperUser like "Is there a software to manage a home phone?". My question was basically "Is there a web site/app to do X?". I thought this fit into SuperUser, but even if it didn't don't migrate it to a site where it doesn't fit. Right?
The last kick in the face was when I came over here to meta.stackoverflow.com to ask this question and I go to sign in with my normal openid login and just clicking OK, OK, OK didn't associate my normal stackoverflow.com user name (wizlb) with this site. Now I'm user152305 on meta.stackoverflow.com
This was an absolutely horrible experience to me and it made me question the use of any other Stack site ever outside of StackOverflow which I use semi-regularly. Seriously, all this intra-site crap is really annoying. Just make one darned site, will you please?

A:
Just make one darned site, will you please?

No, we won't. There's multiple sites for a reason. I'm sorry to hear you had a bad experience, but you really should stick with it, you'll learn a lot more about why the community is set up the way it is as you dig into the sites a bit deeper.

A: Asking about websites is off-topic for Super User.
Asking about help with your shopping is also off-topic.
Both of these are mentioned in the Super User FAQ
If you're looking to ask about a web application, head on over to Unsticking Web Apps.
Don't forget that there's always the hard water realisation that not all questions belong to any one of the Stack Exchange sites.

A: I was amongst the first ones to vote to close the question, let's take it one sentence at a time.

It's so annoying to be shopping around for an enterprise level software product where half the manufacturers don't want to give you pricing unless you call them or let their sales guy take you out to lunch.

OK, enterprise level. Gotcha. What's enterprise level now ?
I'm gonna ask the Big G

So I have no proper definition. I'm going to use my understanding of "enterprise level" - Huge monolithic applications ? OK. What sort of products ? No clue.
Moving on:

I'm looking for some kind of web resource that lists pricing experiences for these kinds of products

Ah, you want some web sites/web applications which list these.
Now the Super User FAQ mentions:

I voted it to move to WebApps.StackExchange.
Plain and simple.

A: The root of the problem is that your question was super vague.

I'm looking for some kind of web resource that lists pricing experiences for these kinds of products.

*Where 'these' are "enterprise level software products."
Unfortunately, I don't think this question has a good place on any of the sites.
Your question is asking about a website that provides information about actual software products. (whatever they may be)  So, I can see how it's a gray area where the question should go.
Also, meta is a bit broken right now; under normal circumstances you wont be 'kicked in the face' by having to re-register.

A:
Web app site = application = software.

Well, yes. But then again no.
Because the semantics are very different in several different ways:

*

*I can't use a webapp without access to the network. Sure the network is increasingly
ubiquitous, but it isn't actually everywhere, and even when its there there are placing that what let you use it that way.

*You generally don't control the version of the webapp you run. Because you load it from the web, and even if you take measures to lock the source the supplier isn't going to wory about protocol compatibility between versions because they expect you to track their changes.

*Webapp default to remote data while local executable default to local.

*Webapps run on a different set of platforms  [IE,mozilla,webkit,...]x[javascript,flash,...] than traditional software [windows,unix,...]x[x86,power,arm,JVM,...] in a way that renders the compatibility issues that plague the two classes very distinct.

Two categories of software with different issues, so two sites.

A: I think if you could improve the question a little, especially by naming specific examples of software, or at least more specific categories (automated billing? automated payment processing? Customer Relationship Management (CRM)?) your underlying question might actually be just barely on topic for ServerFault.
Wrestling with relationships with vendors of very expensive software with secret pricing and other silly games is exactly the kind of thing sysadmins deal with all the time.


text:
Q: Do not see changes in DataContext of DataGridRow I set the DataContext of a particular row in a WPF DataGrid to a different object. The DataContext is changed (seen in the Watch window), but the various bound columns don't reflect the changed DataContext for that row.
Here is my code:
Private Sub btnDataContextChange_Click(sender As Object, e As RoutedEventArgs) Handles btnDataContextChange.Click
    Dim row = dtgChildren.FindVisualChild(Of DataGridRow)()
    row.DataContext = DBEntities.Persons.Single(Function(x) x.PersonID = 22)
End Sub

How can I force a refresh of the bindings?


text:
Q: How can I multiple filter array in React I can only filter with search text input. but I want to use 2 select dropdown + text input while filtering the array. how can I include dropdowns into the filter?
basically, when the user selects location and search something, I just wan't to show results from that selected location. thank you for your help!
import Select from "react-select";

const Positions = ({ positions }: DataProps) => {

  const locations: any = [
    { value: "canada", label: "Canada" },
    { value: "italy", label: "Italy" },
    { value: "france", label: "France" },
  ];

  const jobs: any = [
    { value: "uidesigner", label: "UI Designer" },
    { value: "back-end", label: "Backend Developer" },
    { value: "frontend", label: "Frontend Developer" },
  ];

  const [selectLocation, setSelectLocation] = useState<any>("");
  const [selectJobType, setSelectJobType] = useState<any>("");
  const [searchTerm, setSearchTerm] = useState<any>("");

  return (
                  <input
                    type="search"
                    placeholder="Search"
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />

                <Select
                  defaultValue={selectLocation}
                  onChange={setSelectLocation}
                  options={locations}
                  instanceId={"1"}
                  placeholder="Location"
                />
              </div>

                <Select
                  defaultValue={selectJobType}
                  onChange={setSelectJobType}
                  options={jobs}
                  placeholder="Job Type"
                  instanceId={"2"}
                />

            {positions?.map((position: any) => (
              <SinglePosition
                category={position.category}
                type={position.type}
                location={position.location}
                position={position.position}
                key={position._id}
              />
            ))}

A: You can have a "list" for the result of filtering the "positions" like this:
const [searchTerm, setSearchTerm] = useState<any>("");
const [filtered, setFiltered] = useState<any[]>([]);

then a "useEffect" to change this list every time you change one of the search inputs from the original list:
React.useEffect(() => {
  if(positions.length > 0) {
     let newList = [...positions];
     if(searchTerm) {
        newList = newList.filter(i => i.XXX === searchTerm);
     }
     if(selectJobType) {
        newList = newList.filter(i => i.XXX === selectJobType);
     }
     if(selectPosition) {
        newList = newList.filter(i => i.XXX === selectPosition);
     }
     setFiltered(newList);
  }
}, [positions, searchTerm, selectJobType, selectPosition]);

Then use this "filtered" list to map in your "SinglePosition" instead of "postions"


text:
Q: UIViewPropertyAnimation Objective C question I'm following WWDC 2017 where explains how to use UIViewPropertyAnimation to manage UIPanGesture on a ViewController.
My project is entirely Objective C not Swift.
I wanted to have a clarification about this Swift feature:
func animateTransitionIfNeeded(forState state: State, duration: TimeInterval) {
let blurAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) { switch state {
        case .Expanded:
            self.blurEffectView.effect = UIBlurEffect(style: .dark)
        }
        case .Collapsed:
            self.blurEffectView.effect = nil
        }
    }
    blurAnimator.startAnimation()
    runningAnimators.append(blurAnimator)
}

At the end of the function it is called:
runningAnimators.append(blurAnimator)

runningAnimators in objective C is it a NSMutableArray or an NSDictionary?
Sorry for the stupid question. Thank you

A: It's an Array of UIViewPropertyAnimator objects. This can be "translated" as NSMutableArray. You can see the use of .append which is a method to add elements to an Array in Swift.
Check this link for more info about it.


text:
Q: Ubuntu Server, network config, cant connect I have Ubuntu server edition installed
I have setup 2 nic's
The one on the local network works perfectly but the one connecting to the internet is not working properly, I can't ping and domain name's aren't getting resolved.
My /etc/network/interfaces
auto lo
iface lo inet loopback

#Internal
iface eth0 inet static
    address 192.168.0.X
    netmask 255.255.255.0

#External
iface eth1 inet static
    address 41.161.0.XXX
    netmask 255.255.255.248
    gateway 41.161.0.XXX

I have tried stopping, starting the nics, my iptables are set to
iptables --flush
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

I can not ping the gateway any ideas?
EDIT:
The settings are as provided by the ISP, the settings work perfectly on my mac and on my windows machine, which is both disconnected from that network at the moment so there can't be IP conflicts
Netstat:
Kernel IP routing table
Destination        Gateway        Genmask          Flags        MSS  Window   irtt Iface
0.0.0.0            41.161.2.XXX   0.0.0.0          UG             0  0           0 eth1
41.161.2.XXX       0.0.0.0        255.255.255.248  U              0  0           0 eth1
169.254.0.0        0.0.0.0        255.255.0.0      U              0  0           0 eth1
192.168.0.0        0.0.0.0        255.255.255.0    U              0  0           0 eth0

A: Check the actual configuration using ifconfig eth1.
Make sure the gateway is in the same subnet as the eth1 address. (Please edit your question and unobscure the netmask and the local part (last few X) of the addresses)
Check routing using netstat -nr
Check your configuration with with the persons who provide the gateway router.


text:
Q: 2D and 3D color maps from .xyz files I'm a Python beginner and would like to create a 2D and 3D color map from data in a .xyz file as shown below :
The first column is x, the second y, and the third z.
At the end, I would like to get a 2D and 3D color maps as shown in the figures below.
I've tried a code for making 2D and 3D color map but it does not work. Could somoneone give me advices?
Here a secured link with data : https://filesender.renater.fr/?s=download&token=1d063c5a-6d26-48d8-974b-9a2ec80abec1
nb_lines=999
nb_columns=999

data = pd.read_csv("path",sep=' ',header=None).to_numpy()

#2D colormap

fig = plt.figure(figsize=(15,12))
ax = plt.subplot(1,1,1)
x=np.linspace(0,nb_columns,nb_columns)
y=np.linspace(0,nb_lines,nb_lines)
X,Y=np.meshgrid(x,y)
Xi, Yi = np.meshgrid(x, y)
cntr1 = ax.contourf(x, y, data, cmap="jet")
cbar = fig.colorbar(cntr1, ax=ax)

cbar.set_ticks(np.arange(70,140.01,10),[str(i) for i in np.arange(70,140.01,10)])
cbar.ax.tick_params(labelsize=25)
ax.axis('on')

#3D colormap
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')

surf=ax.plot_surface(X, Y, data, cmap='jet', antialiased=False)
cbar=fig.colorbar(surf, ax=ax)
cbar.set_ticks(np.arange(30,70.01,5),[str(i) for i in np.arange(30,70.01,5)])
cbar.ax.tick_params(labelsize=25)
ax.axis('on')
ax.set_zlim()


text:
Q: How to get all the checked checkboxes in an array using pure JavaScript? var subject = document.getElementsByClassName("subject");

var checkboxesChecked =[];

for (var i=0; i<2; i++) {
    // And stick the checked ones onto an array...
    if (subject[i].checked===true) {
        checkboxesChecked.push(subject[i]);
    }
}

It always return me [object HTMLCollection] and on view instead of checkboxes Object Object is displayed.

A: You need to use subject[i].value to get the value of the checkbox and push that into the array.
Change your code to:
var subject = document.getElementsByClassName("subject");

var checkboxesChecked =[];

for (var i=0; i<2; i++) {
    // And stick the checked ones onto an array...
    if (subject[i].checked===true) {
        checkboxesChecked.push(subject[i].value);
    }
}


text:
Q: C - Why is the answer 0.00000, when I try enter 3 numbers for the sum and average? #include <stdio.h>

int main(int argc, char *argv[])
{

float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;

printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3

printf("The sum of these three numbers is %f.\n", sum);//Print sum
printf("The average of these numbers is %f.\n", average);//Print average

}

This is what is displayed.
Enter three numbers:

12.0

10.0

12.0

The sum of these three numbers is 0.000000.

The average of these numbers is 0.000000.

A: Remember that C runs from top to bottom in a function without loops or conditionals.
You created num1, num2, and num3, as 0 each, and found their sum and average before inputting the numbers.
Do as follows:
float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = 0;
float average = 0;

printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3

sum = num1 + num2 + num3; //calculate
average = sum / 3;

printf("The sum of these three numbers is %f.\n", sum);//Print sum

printf("The average of these numbers is %f.\n", average);//Print average

A: You seem to misunderstand the usage of variable definition. These:
float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;

do not define the way the sum will be computed after the reading is done, but actually use these values and calculate the sum and average to be 0 before the program calls first scanf.
scanf("%f %f %f", &num1, &num2, &num3);
sum = num1 + num2 + num3;                     // <-- place it here
average = sum / 3;

A: C programs execute from top to bottom one instruction at a time. You have calculated sum and average before accepting the numbers. This evaluated to sum=0 and average=0 because all three numbers were 0.
main(int argc, char *argv[]) {
    float num1,num2,num3,sum,average;

    printf("Enter three numbers:\n"); //Enter three floats
    scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3

    sum = num1 + num2 + num3;
    average = sum / 3;

    printf("The sum of these three numbers is %f.\n", sum);//Print sum
    printf("The average of these numbers is %f.\n", average);//Print average
    return 0;
}


text:
Q: Ambiguous method overloading for method com.eviware.soapui.support.XmlHolder# When I tried this groovy script in SoapUI 5.5.0 I get this error:

groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.eviware.soapui.support.XmlHolder# . Cannot resolve which method to invoke for [null] due to overlapping prototypes between: [interface org.apache.xmlbeans.XmlObject] [interface org.w3c.dom.Node] error at line: 19

import com.eviware.soapui.support.XmlHolder

log.info "welcome to canada"

def name=context.expand ('${#TestCase#name}')

log.info context.expand ('${#TestSuite#place}')
//log.info context.expand('${#AddAutomation#id}')//its not going to grab values or properties of other testcases
def id=testRunner.testCase.testSuite.testCases["AddAutomation"].getPropertyValue("id")

def age=testRunner.testCase.testSuite.setPropertyValue("age","23")
def department=testRunner.testCase.testSuite.testCases["AddAutomation"].setPropertyValue("department","CSE")

def request=log.info testRunner.testCase.testSuite.testCases["AddAutomation"].testSteps["Add"].getPropertyValue("Request")

def xmlnew=new XmlHolder(request)
xmlnew.setNodeValue("\\typ:addEmployee\typ:name","name")

xmlnew.setNodeValue("\\typ:addEmployee\typ:id","id")

xmlnew.setNodeValue("\\typ:addEmployee\typ:age","age")
xmlnew.setNodevalue("\\typ:addEmployee\typ:department","department")

A: Your script has:
...
def request=log.info testRunner.testCase.testSuite.testCases["AddAutomation"].testSteps["Add"].getPropertyValue("Request")

def xmlnew=new XmlHolder(request)
...

The line log.info will always return null, so the next line errors. In all likelihood what you actually want is:
...
def request=testRunner.testCase.testSuite.testCases["AddAutomation"].testSteps["Add"].getPropertyValue("Request")
log.info request
def xmlnew=new XmlHolder(request)
...


text:
Q: LWC lightning-pill-container does not redraw when adding items With a simple component like so:
import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    @track infoText;
    @track data = [];

    handleItemRemove(e) {
        this.infoText = e.detail.item.name
    }

    handleClickW(e) {
        this.data.push({ label: 'a ' + this.data.length, name: 'b' + this.data.length })
        this.redraw = true;
        this.infoText = 'Count:' + this.data.length;
    }
}

HTML:
<template>

Info: {infoText}

        <lightning-button label="Neutral" title="Neutral action"
        onclick={handleClickW} class="slds-m-left_x-small"></lightning-button>

     <lightning-pill-container items={data} onitemremove={handleItemRemove}>
    </lightning-pill-container>

</template>

I never see the items in my {data} displayed in lightning-pill-container. I can get the initial set of items displayed if i wrap lightning-pill-container into a if:true={redraw} and then set it to true on click, but setting it back to false and then to true did not work.
Link in playground:
https://developer.salesforce.com/docs/component-library/tools/playground/v2VK0x6o_/1/edit
How can i add items to the list displayed by lightning-pill-container?
UPDATE
I sort of got it working like so:
@track redraw = false;
    handleClickW(e) {
        this.redraw = false;
        this.data.push({ label: 'a ' + this.data.length, name: 'b' + this.data.length })
        setTimeout(() => { this.redraw = true;}, 0);
        this.infoText = 'Count:' + this.data.length;
    }

     <lightning-pill-container items={data} onitemremove={handleItemRemove}>
    </lightning-pill-container>

There are 2 issues:
1) Supposedly setTimeout is not allowed in lwc: Restricted async operation 'setTimeOut' in LWC
2) There is a jitter when i try to add items as the whole thing needs to be re-drawn.

A: Child components only rerender when its tracked values change. When passing data structures down to child components, we're actually passing by reference, so the reference to the data structure needs to change. In other words, the child component needs to receive a new data structure.
In LWC, data structure mutations can cause components to rerender, but only for the component that owns said data structure. In your example, lightning-pill-container does not update upon mutations to the this.data array because those mutations happen in the c-app component.
I made some modifications to your playground example to illustrate this better:
https://developer.salesforce.com/docs/component-library/tools/playground/v2VK0x6o_/2/edit
On a related note, it's a best practice to clone your data structures before passing them around because you don't want other components to mutate your data.


text:
Q: How harmful are double braces in GWT? I tend to use (or even overuse) double braces object intialization in GWT. For me it looks more readable and more declarative.
new FastMap<Object>(){{
    put("Value", 12);
    put("Unit", "Kg");
}};

Before today I was not aware that this syntax is not just instantiate object but also create AnonymousInnerClass for it. Now I am concerned how GWT deal with them.

*

*How this syntax affects perfomance of the execution?

*How this syntax affects compiled size?

*Any other bad thing?

I have thousands of such initializations in my app.

A: My findings. Test code. I am creating single list with 4 maps with 21 item each. I am measuring size of all generated JavaScript files. Results:
Empty (just empty code to make sure that GWT support code rendered):

*

*PRETTY = 533 KB (546 602 bytes)

*OBF = 212 KB (217 601 bytes)

*Number of new = 167

Code without double braces:

*

*PRETTY = 557 KB (570 682 bytes)

*OBF = 222 KB (227 663 bytes)

*Number of new = 171

And same code with double braces:

*

*PRETTY = 567 KB (581 004 bytes)

*OBF = 228 KB (234 089 bytes)

*Number of new = 177

I think results are pretty self-explanatory.

A: This is standard Java and is independent of GWT. It is dealt with comprehensively in Efficiency of Java "Double Brace Initialization"?.
The biggest problem I have with this syntax is that is doesn't deliver an instance of FastMap, but rather of an anonymous subclass of that. That object doesn't compare as equal to an equivalent instance of FastMap with the data set up in the traditional way. It is also likely to have other gotchas that aren't obvious and are less that straightforward to debug.

The thread here says this

Watch out - double-brace initialization is cool looking, but it's
  orders of magnitude slower than regular initialization as it must
  generate an anonymous class.
Also, the generated class is put into the permgen space, which is not
  garbage collected. The permgen is pretty small by default - and if you
  fill it up, your system is hosed.
I use them all the time in unit tests, but never in production code.

A: As far as readability is concerned: I would change it to something like this to make it easy to read:
new FastMap<Object>()
{{
    put("Value", 12);
    put("Unit", "Kg");
}};

You however might want to read this answer to find out more about performance related issues.

A: If you're just defining constant maps like this, you'd probably be better off (both speed-wise and readability-wise) using Guava and ImmutableMap:
Map<Integer, Character> map = ImmutableMap.of(5, 'a', 1, 'b');
Map<Integer, String> largerMap = ImmutableMap.<Integer, String>builder()
  .put(1, "a")
  .put(2, "b");
  .put(5, "wisconsin")
  .build();

(They're from Google, and they're totally GWT-compatible.)


text:
Q: For expectation in probability how do I show what EX^2 is in this case? Im trying to prove $$E[X^2]=2\int_0^\infty x(1-F(x)) \, dx $$
Where the integral area is from 0(at the bottom of the integral) and infinity.
Also X>0 with density f(x) and Distribution function F(x).
I know $$E[X^2]=\int_0^\infty x^2f(x) \, dx$$
but I don't know what value of f(x) I would substitute in if thats what I am meant to do.
Thanks

A: Hint: write $F(x)=\int_0^x f(y) \mathop{dy}$ to obtain a double integral, then switch the order of integration.

 $$2 \int_0^\infty x(1-F(x)) \mathop{dx} = 2 \int_0^\infty x \int_x^\infty f(y) \mathop{dy} \mathop{dx} = 2 \int_0^\infty f(y) \int_0^y x \mathop{dx} \mathop{dy} = \cdots$$


text:
Q: How to reassign value to string variables in Erlang? I am new to Erlang. I just want to reassign a value to a string variable:
get_alert_body(Packet) ->
    BodyElement = element(8,Packet),
    Body = "my text",
    Els = xmpp:get_els(Packet),
    lists:foreach(fun(El) ->
        ElementName = io_lib:format("~s",[xmpp:get_name(El)]),
        IsFile = string:equal(ElementName,"fileType"),
        if
            IsFile ->
                FileType = fxml:get_tag_cdata(El),
                IsPhoto = string:equal(FileType,"photo"),
                IsVideo = string:equal(FileType,"video"),
                if
                    IsPhoto ->
                        %% if it gets to this I would like to return "my photo"
                        Body = "my photo";
                    IsVideo ->
                        %% else if it gets to this I would like to return "my video"
                        Body = "my video";
                    true ->
                        %% otherwise I would like to return "my text"
                        ok
                end;
            true ->
                ok
        end
    end, Els),
    Body.

But I get this error:
error,{badmatch,"test2"}

Even if I do somthing like:
A = "test1",
A = "test2",

I get the same error.
I would appreciate your help.

A: You can't.  Erlang has a feature called "single assignment", meaning that you can't change the value of a variable after assigning it for the first time.  If you try to do that, it becomes a pattern match instead, and you get a badmatch error just like if you try to do "test1" = "test2".
Your example can be written as:
A =
  if
      Condition ->
          "test2";
      true ->
          "test1"
  end

See this question and its answers for more about single assignment.

In your expanded example, what you're trying to do can be achieved with a fold.  That is, given a list and an additional value called an "accumulator", go through the list and call a function for each element, and let the return value of that function be the new accumulator - and return the accumulator in the end.
Use lists:foldl/3 for that, like this:
get_alert_body(Packet) ->
    BodyElement = element(8,Packet),
    DefaultBody = "my text",
    Els = xmpp:get_els(Packet),
    lists:foldl(fun(El, Body) ->
        ElementName = io_lib:format("~s",[xmpp:get_name(El)]),
        IsFile = string:equal(ElementName,"fileType"),
        if
            IsFile ->
                FileType = fxml:get_tag_cdata(El),
                IsPhoto = string:equal(FileType,"photo"),
                IsVideo = string:equal(FileType,"video"),
                if
                    IsPhoto ->
                        %% if it gets to this I would like to return "my photo"
                        "my photo";
                    IsVideo ->
                        %% else if it gets to this I would like to return "my video"
                        "my video";
                    true ->
                        %% otherwise return the existing value
                        Body
                end;
            true ->
                ok
        end
    end, DefaultBody, Els).

A: = is not an assignment operator in erlang, rather it's a pattern match operator.
If you write:
{A, hello} = {10, hello}.

and A has not been bound to (or you can say assigned) a value yet, then erlang attempts to create a match for the right hand side (because = is the match operator).  To create a match for the right hand side, erlang binds/assigns A the value 10 (for fun you can assume that *&* is the assignment operator in erlang, so erlang does A *&* 10 to assign 10 to the variable A).
It works the same way if you write:
B = 10,

In order for erlang to create a match for the right hand side, erlang assigns B the value 10:  B *&* 10, and the match succeeds, so execution continues on the next line.  However, if you write:
C = 3,
C = 22,

then in the first line, erlang assigns the value 3 to C: C *&* 3 to find a match for the right hand side (because = is the match operator).  But the second line is equivalent to:
3 = 22,

And the error message will say that the match operator = failed because there is no possible way to make the left hand side match the right hand side 22.

A: Variables in Erlang can't be reassigned, but they can be "shadowed" to achieve a similar effect. In this example, the variable X is "redefined" as X ++ Y within the scope of an anonymous function:
-module(main).
-export([main/1]).

main([_]) ->
    X = "X",
    Y = "Y",
    fun(X) -> io:fwrite(X) end(X++Y),
    init:stop().

This program prints XY instead of X, since X is the name of the anonymous function's parameter.


text:
Q: ORDER BY percentage in mysql - 100% is moved to the end here's my query to arrange the percentage in a correct descenting order.
SELECT
id,
concat(round(100 * ( count(t5.answ IN (t1.answ, t2.answ, t3.answ)) ) / case when t6.name < 4 then 100 when t6.name = 4 then 200 when t6.name > 4 then 300 end,0)) as score,
another_column
from t1
order by score desc

the score output is
91%, 96%, 100%, 92%,

What iam looking for this
100%, 96%, 92%, 91%

but what i get is this, the 100% is moved to the end
order by score desc
// 96%, 92%, 91%, 100%

A: That is because you are ordering by a string and not a number.  Given the complexity of the expression, just convert back to a number for ordering:
order by (score + 0) desc


text:
Q: Is there a method equivalent of removeCallback for Flash ExternalInterface? I have an Flash SWF application in the browser and I'm using ExternalInterface to communicate to JavaScript document.
In the Flash ExternalInterface API there is an addCallback method. It adds a function on the browser SWF object. When you call it it creates a method on the SWF object in the browser that JS can call:
AS:
public function myEventListener(event):void {};
ExternalInterface.addCallback("myFunction", myEventListener);

JS:
// returns "function"
console.log(typeof swfObject.getObjectById('myApp').myFunction);

But I do not see any existing removeCallback method. What would be the equivalent to removeCallback?
Here is what I have so far:
var application = this[objectId]; // gets the Flash object
application[callbackName] = null;
delete application[callbackName];

Does this look correct?

A: Just call addCallback again, setting the function as null:
ExternalInterface.addCallback("callAlert", null);

The documentation mentions this: ExternalInterface.addCallback()

Note: Repeating addCallback() on an existing callback function with a
  null closure value removes the callback.


text:
Q: ElasticSearch hits have no fields I am having a problem where when I run a search on elastic using the java api I get back results... but when I try and extract values from the results there are no fields.
ElasticSearch v5.3.1
Elastic API: org.elasticsearch.client:transport v5.3.0
My code:
SearchRequestBuilder srb =   client.prepareSearch("documents").setTypes("documents").setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(qb).setFrom(0).setSize((10)).setExplain(false);

srb.addDocValueField("title.raw");
SearchResponse response = srb.get();

response.getHits().forEach(new Consumer<SearchHit>() {

        @Override
        public void accept(SearchHit hit) {
            System.out.println(hit);
            Map<String, SearchHitField> fields = hit.getFields();

            Object obj = fields.get("title.raw").getValue();

        }

    });

When the forEach runs the obj is always coming back null. Fields has an item in it with the key of title.raw and it has a SearchHitField.

A: Fields is only used when you are trying to obtain stored fields. By default you should obtain fields using the source. With the following code samples I'll try to explain it.
PUT documents
{
  "settings": {
    "number_of_replicas": 0,
    "number_of_shards": 1
  },
  "mappings": {
    "document": {
      "properties": {
        "title": {
          "type": "text",
          "store": true
        },
        "description": {
          "type": "text"
        }
      }
    }
  }
}

PUT documents/document/_bulk
{"index": {}}
{"title": "help me", "description": "description of help me"}
{"index": {}}
{"title": "help me two", "description": "another description of help me"}

GET documents/_search
{
  "query": {
    "match": {
      "title": "help"
    }
  },
  "stored_fields": ["title"],
  "_source": {
    "includes": ["description"]
  }
}

Next the response, notice the difference between the stored field Title and the normal field description.
{
  "_index": "documents",
  "_type": "document",
  "_id": "AVuciB12YLj8D0X3N5We",
  "_score": 0.14638957,
  "_source": {
    "description": "another description of help me"
  },
  "fields": {
    "title": [
      "help me two"
    ]
  }
}


text:
Q: How can I save temporary a form and show it in JSP Pages Im learning web programming and Im trying to temporary save this form and show it in another JSP Page, here is My example:
This is like my menu, in "Alta Cliente" its my form.
Alta de Cliente

  Alta de Cuenta

  Detalles de Cliente

  Lista de Clientes

  Detalles de Cuenta

In this form I can show it without problems in another JSP Page. But my Main problem is when i go to te menu, and Select "Detalles de Cliente" i dont get the data from the form "Alta Cliente" and everything its Null.
How can I temporary save this data and Show it in this page, without using a DataBase.
 <form action="detalleCliente.jsp" method="GET">

    Nombre
    <input type="text" placeholder="Ingresa tu nombre" name="nombre" id="nombre" required>

    Apellidos
    <input type="text" placeholder="Ingresa tus apellidos" name="apellidos" id="apellidos" required>

    Direccion
    <input type="text" placeholder="Ingresa tu direccion" name="direccion" id="direccion" required>

    Codigo Postal
    <input type="text" placeholder="Ingresa tu Codigo Postal" name="cp" id="cp" required>

 <input type="submit" value="Submit"/>

</form>