text:
Q: Mapping BigInt on model with INT I have a table in a database that has a BigInt column. The data in this table will never exceed INT.
I can't change the structure of the database because Legacy can break ...
Can I map BigInt to a model with INT?
I tried:
 var converter = new ValueConverter<int, long>(
            v => v,
            v => (int)v);

and call HasConversion(converter) in Fluent Api
But catch:

System.InvalidCastException : Unable to cast object of type
'System.Int32' to type 'System.Int64'.

If i swap types:

System.InvalidOperationException : Converter for model type 'long'
cannot be used for 'DocumentRequest.Id' because its type is 'int'.

=> first option is valid
I would do in the Int64 model, but in the main table there can be ID BigInt, and in the children the Foreign Key link as INT => mapping does not work ...
Damn bd...

A: This is a quirk of C#.  You can't actually cast between these types, but they have Cast Operators to perform the conversion.  Eg
    long l = 0;
    Int32 i = (Int32)l; //works

    Int32 i2 = (Int32)(object)l; //fails System.InvalidCastException: 'Unable to cast object of type 'System.Int64' to type 'System.Int32'.'

The fix is simply to use Convert instead of the a C# cast.  EG
    var converter = new ValueConverter<int, long>(
            i => Convert.ToInt64(i),
            l => Convert.ToInt32(l));


text:
Q: How can I run a UWP WebApp with selenium and appium? I have a UWP WebApp and I want to run it with selenium and appium. How can I run this app?
I have Cordova Ionic app and I have .exe file and appx file, but when I use winium in selenium and give the .exe file, it's open but for install the app. I want to open this app and test it. Please advise me on how can I run it:
public static void main(String[] args) throws MalformedURLException, InterruptedException {

        DesktopOptions option = new DesktopOptions();

        option.setApplicationPath("C:\\Users\\admin\\Downloads\\FieldService-3.1.28.1.exe");
        Thread.sleep(40000);
        WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999"), option);
        Thread.sleep(4000);

        //For Login Emerson
        driver.findElement(By.name("Username")).sendKeys("aashish.kumar");
        Thread.sleep(4000);
        driver.findElement(By.name("Password")).sendKeys("#####");
        Thread.sleep(5000);
        driver.findElement(By.name("SIGN IN")).click();
        Thread.sleep(5000);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to detect whether or not a BitmapFactory.decodeFile needs to have a set (insamplesize) option depending on the phone? I have tried working with a bit of code to decode a file from SD and then edit it. Because of this editing that needs to be done, keeping a higher scaled image is important. Some phones run into memory issues, whereas others have enough room in their heap to continue the decode without a set option.
    //the following is ending a process in which a photo is taken and saved
    //under "/sdcard/folder/photo.png"
    FileOutputStream fos= new FileOutputStream(photo.getPath());
    fos.write(jpeg[0]);
    fos.close();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    Bitmap originalFile = BitmapFactory.decodeFile("/sdcard/folder/photo.png",options);

I am basically looking into whether there is a way to almost set an if statement to put the option into place (if needed) otherwise continue without it.

A: As a workaround, wrap decoding into a try-catch and if "out of memory"  exception happen, just catch it and try decode with properly set inSampleSize.
However, this looks more like a hack than a solution.
Basically, you need to know how much memory your decoded bitmap will take and how much memory is available for your application's heap to grow in the system right now.
First is easy to find out: width*height*4 bytes (by default decoding is in ARGB8888).
But I have no idea how to get the heap's memory size.


text:
Q: Symfony2 Twig printing variable related entity properties I am having some trouble trying to access variables in twig.
I have a class called staff and a class called image
every staff has 1 image_id which maps to the image table
I can call the following code in php to access the image url
//...get 1 staff member
echo $staff->getImage()->getWebPath();

However calling this code in twig does not seem to work
{{ staff.image.webpath }}

If I pull the image in php and pass it to the template i can access it like so
php
---
$image = $staff->getImage();

twig
----
{{ image.webpath }}

I would like to pass all staff to my template and then use a for loop to print out their names bios titles and images. Is this possible to do with the Image?

A: I will define the __toString method in the image entity like this:
public function __toString() {
return $this->getWebPath();
}
Then you will access variable in the Twig like:
<img src="{{ staff.image }}" alt="image" />


text:
Q: error CS1009: Unrecognized escape sequence getting the error

error CS1009: Unrecognized escape sequence

string to be replaced

newDate = "/Date(1430370000000+0530)/"

Code
newDate.Replace("/","\/")

I am trying to replace a backslash

/

with forward and backward slash
\/

A: I believe you want
newDate.Replace("/","\\/")

as \ has special meaning and you used it improperly causing the quoted error. See escape character for more details.
Alternatively try verbatim literal using @-quoting:
newDate.Replace("/", @"\/")


text:
Q: Confused by an example of generalization of a point Suppose $A=\operatorname{Spec}\mathbb{C}[x,y]$. We say that a point $P\in\operatorname{Spec}A$ is a generalization of a point $Q\in\operatorname{Spec}A$ if $Q\in\overline{\{P\}}$. So let $P=[(y-x^2)]$ and $Q=[(x-2,y-4)]$. The claim is that $P$ is a generalization of $Q$, but I'm having trouble seeing this.
I know that $(y-x^2)\in (x-2,y-4)$, which is equivalent to the ideal $(y-x^2)$ vanishing at the closed point $(x-2,y-4)$ (which we can think of as $(2,4)$). But this doesn't help me see that $(x-2,y-4)\in\overline{(y-x^2)}$ (where the closure is with respect to the Zariski topology).
Now, certainly, $[(x-2,y-4)]$ is a closed point, but why is it in the intersection of all closed subsets containing $(y-x^2)$? Is there a better way to see this? How would one go about finding the closure of $(y-x^2)$?

A: To prove that $(x - 2, y - 4)$ is in the closure of $\{ (y - x^2 ) \}$, you have to prove that every closed set that contains $(y - x^2 )$ also contains $(x - 2, y - 4)$.
By the definition of the Zariski topology, the closed sets in ${\rm Spec \ }A$ are sets of the form $V(I) = \{ \mathfrak p { \rm \ prime \ } \subset A : I \subseteq \mathfrak p \}$.
But if $I \subseteq A$ is any ideal such that $V(I)$ contains $(y - x^2)$, then $I \subseteq (y - x^2) \subset (x - 2, y - 4)$ too, hence $V(I)$ contains $(x - 2, y - 4)$. Thus $(x - 2, y - 4)$ is in the closure of $\{ (y - x^2 ) \}$.
[By the way, I used the fact that $(y - x^2 ) \subset (x - 2, y - 4)$.]


text:
Q: Summation involving floor of irrational numbers. I need to compute the following sum for large $N$, i.e. $N = 10^{16}$.
$$ S(N) = \sum_{x=2}^{x=N-1} \left(\sum_{y=x+1}^{y=min(N, \lfloor \phi \times x \rfloor)} x + y\right) $$
where $\phi = \frac{1 + \sqrt{5}}{2}$, $x$ and $y$ are positive integers.
My first step is to break the sum at $x = x_0$ such that $(x_0 \times \phi) \leq N$ and $((x_0 + 1) \times \phi) > N$. So, we now have two sums,
$$ S_1(N) = \sum_{x=2}^{x=x_0} \left(\sum_{y=x+1}^{y=\lfloor \phi \times x \rfloor} x + y\right) $$
$$ S_2(N) = \sum_{x=x_0+1}^{x=N-1} \left(\sum_{y=x+1}^{y=N} x + y\right) $$
Now, note that $S_2(N)$ has a closed form and can be computed very quickly. My question is,
is there a way to compute $S_1(N)$ quickly, any sub-linear time algorithm would be great.
Here are some values of $(N, S(N))$ for small values of $N$, $[(2,0),(3,5),(4,12),(5,21),(6,42),(7,67),(8,109),(9,157),(10,211),(11,289),(12,375)]$.

A:
I would like to know/learn how to compute such summations.

In this case, we can use $\phi$'s connection to Fibonacci recurrences, as well as the fact that $x+y$ is linear. Start with a plot of the summands:

Then, the problem is to find the (weighted) area. You've already noticed that the $\min(N,\cdot)$ limit is not interesting, so let's get rid of it. While we're at it, let's fill the triangle to the axis:

To find the total weight in this plot, split it recursively into smaller pieces. There is a Fibonacci-like recurrence:

(You could also derive the recurrence from the continued fraction representation $\phi = [1;1,1,\dots]$. It's not as picturesque though.)
It's not quite that simple, because these similar pieces have different weights $\sum_{x,y} x+y$. However, $x+y$ is linear, so when you shift a $k$-term piece by $(\Delta x, \Delta y)$, its weight changes by $k (\Delta x + \Delta y)$. Modulo this adjustment there are only $\mathcal{O}(\log N)$ distinct pieces, so $S(N)$ can be calculated in $\mathcal{O}(\log N)$ operations.

A: Here's a partial solution:
The best rational approximations to $\phi$ are ratios of successive Fibonacci numbers $\phi \approx F_{n+1} / F_n$.  Take the first Fibonacci number $F_n >= 2 x_0$.  We have $|\phi - F_{n+1} / F_n| < 1/ F_n^2 <= 1/2x_0 F_n$.
So $|\phi * x - x * F_{n+1} / F_n| < 1/2F_n$, and $\lfloor \phi * x \rfloor = \lfloor x * F_{n+1} / F_n \rfloor$.
We now have
\begin{equation}
S_1(N) = \sum_{x=2}^{x_0} \big( \sum_{y=x+1}^{\lfloor x * F_{n+1} / F_n \rfloor } x+y \big)
\end{equation}
The inner sum can be expressed as a quasi-polynomial in $x$ with period $F_n$.  I suspect there is a nice closed form for sums of the form $\sum_{y=x+1}^{x + \lfloor x * p / q \rfloor } x+y$ with $p,q$ prime in terms of the Dirichlet characters mod $q$, but that's as far as I got.

A: Thanks to Japheth Lim for providing an answer to this question. Based on his answer, I implemented a Haskell program that computes $S(10^{16})$. I needed to use an extended precision up to 50 digits for $\phi$. Here is sample output:
vamsi@vamsi-laptop:~/learn/project_euler/257_to_384/problem_325$ ghci
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Prelude> :l problem_325_fast.hs
[1 of 1] Compiling Main             ( problem_325_fast.hs, interpreted )
Ok, modules loaded: Main.
*Main> s 10
211
*Main> s 10000
230312207313
*Main> s (10 ^ 16)
230327668541684176515052475525037682834286696168

The code itself:
import qualified Data.List as L
import qualified Data.Map.Strict as M
import qualified Data.Ratio as R

phi :: Double
phi = 0.5 * (1.0 + (sqrt 5.0))

phi_r :: Rational
phi_r = 161803398874989484820458683436563811772030917980576 R.% (10 ^ 50)

triangular :: Integer -> Integer
triangular n
  | n < 0 = error "triangular: n must be >= 0."
  | otherwise = (n * (n + 1)) `div` 2

sum_of_squares :: Integer -> Integer
sum_of_squares n
  | n < 0 = error "sum_of_squares: n must be >= 0."
  | otherwise = (n * (n + 1) * ((2 * n) + 1)) `div` 6

fibonacci :: Integer -> [Integer]
fibonacci n = loop [2, 1]
  where loop [] = error "fibonacci: empty list found!"
        loop [_] = error "fibonacci: singleton list found!"
        loop fs@(f : g : rest)
          | f >= n = fs
          | otherwise = loop ((f + g) : fs)

as_fibonacci_sum :: Integer -> [Integer]
as_fibonacci_sum n = reverse $ loop fs n []
  where fs = fibonacci n
        loop [] x ds
          | x == 0 = ds
          | otherwise = error "as_fibonacci_sum: could not compute sum!"
        loop fs@(f : rest) x ds
          | (x == f) && (x < n) = (f : ds)
          | f < x = loop rest (x - f) (f : ds)
          | otherwise = loop rest x ds

as_limits :: [Integer] -> [(Integer, Integer)]
as_limits [] = error "as_limits: found empty list!"
as_limits fs@(f : rest) = reverse $ loop rest [(1, f)]
  where loop [] ls = ls
        loop (f : rest) ls@((l, u) : _) = loop rest ((u + 1, u + 1 + f - 1) : ls)

s_2 :: Integer -> Integer
s_2 n
  | n < 2 = error "s_2: n must be >= 2."
  | otherwise = t_1 + t_2 - t_3 - t_4
  where x_0 = floor ((fromIntegral n) / phi_r)
        ff x = (x * (x + 1) * (x + 2)) `div` 6
        t_1 = n * ((triangular (n - 1)) - (triangular x_0))
        t_2 = (triangular n) * (n - 1 - x_0)
        t_3 = (sum_of_squares (n - 1)) - (sum_of_squares x_0)
        t_4 = (ff (n - 1)) - (ff x_0)

slow_F :: Integer -> Integer
slow_F x_0 = sum [(x + y) | x <- [1..x_0], y <- [1..(floor (phi_r * (fromIntegral x)))]]

_G :: Integer -> Integer -> Integer -> Integer
_G a b h = (h * (((b * (b + 1)) `div` 2) - (((a - 1) * a) `div` 2))) + ((h * (h + 1) * (b - a + 1)) `div` 2)

f :: Integer -> Integer
f x = floor (phi_r * (fromIntegral x))

g :: Integer -> Integer
g x = (x * h) + ((h * (h + 1)) `div` 2)
  where h = floor (phi_r * (fromIntegral x))

slow_k :: Integer -> Integer
slow_k x = sum [f y | y <- [1..x]]

type Memo = M.Map Integer Integer

fast_k :: Memo -> Integer -> (Memo, Integer)
fast_k m x
  | M.member x m = (m, m M.! x)
  | otherwise = let (m_1, s_1) = L.foldl fold_fn (m, 0) fd
                in (M.insert x s_1 m_1, s_1)
  where fd = as_limits $ as_fibonacci_sum x
        fold_fn (m, s) x = let (m_1, s_1) = compute_k m x
                           in (m_1, s + s_1)
        compute_k m x@(l, u)
          | l == 1 = fast_k m u
          | otherwise = let (m_1, k_1) = fast_k m (u - l + 1)
                        in (m_1, k_1 + ((u - l + 1) * ((f l) - (f 1))))

fast_F_shifted :: Memo -> Memo -> Integer -> Integer -> (Memo, Memo, Integer)
fast_F_shifted m_k m_f x y
  | x <= y = (m_k_2, m_f_1, t_1 + (k * (dx + dy)) + (_G x y dy))
  | otherwise = error "fast_F_shifted: x must be <= y."
  where w = y - x + 1
        (m_k_1, m_f_1, t_1) = fast_F m_k m_f w
        (m_k_2, k) = fast_k m_k_1 w
        dx = x - (f 1)
        dy = (f x) - (f 1)

fast_F :: Memo -> Memo -> Integer -> (Memo, Memo, Integer)
fast_F m_k m_f x_0
  | M.member x_0 m_f = (m_k, m_f, m_f M.! x_0)
  | otherwise = let (m_k_1, m_f_1, s_1) = L.foldl fold_fn (m_k, m_f, 0) fd
                in (m_k_1, M.insert x_0 s_1 m_f_1, s_1)
  where fd = as_limits $ as_fibonacci_sum x_0
        -- m = M.insert 2 ((g 1) + (g 2)) $ M.singleton 1 (g 1)
        fold_fn (m_k, m_f, s) x = let (m_k_1, m_f_1, s_1) = compute_F m_k m_f x
                                  in (m_k_1, m_f_1, s + s_1)
        compute_F m_k m_f x@(l, u)
          | l == 1 = fast_F m_k m_f u
          | otherwise = fast_F_shifted m_k m_f l u

s_1 :: Integer -> Integer
s_1 n
  | n < 2 = error "s_1: n must be >= 2."
  | otherwise = t_0 - t_1 - t_2 - t_3
  where x_0 = floor ((fromIntegral n) / phi_r)
        ff x = (x * (x + 1) * (x + 2)) `div` 6
        (_, _, t_0) = fast_F m_k m_f x_0
        t_1 = 2
        t_2 = (sum_of_squares x_0) - (sum_of_squares 1)
        t_3 = (ff x_0) - (ff 1)
        m_f = M.insert 2 ((g 1) + (g 2)) $ M.singleton 1 (g 1)
        m_k = M.insert 2 ((f 1) + (f 2)) $ M.singleton 1 (f 1)

s :: Integer -> Integer
s n
  | n < 2 = error "s: n must be >= 2."
  | otherwise = (s_1 n) + (s_2 n)


text:
Q: jQuery division of two time to get the ratio So they have this formula to get their ratio. It is
total working hours = time-start - time-end
ratio = total working hours / duration
I can get the total working hours using this code,

var timestart = '11:32:59 AM';
var timeend = '5:24:04 PM';
var duration = '00:44:08';

var totalworkinghours = timemod3(timestart, timeend);
console.log(totalworkinghours);

function timemod3(start, end) { //(H:MM:SS AM/PM) // GET THE DIFFERENCE OF TWO TIME
  //get the 24 hour format of start time
  Number.prototype.padDigit = function() {
    return (this < 10) ? '0' + this : this;
  }
  var ssplit = start.split(':');
  //var hour = ssplit[0];
  //var minutes = ssplit[1];
  var ss2 = ssplit[2].split(' ');
  var ampm1 = ss2[1]; //start

  var ssplit2 = end.split(':');
  //var hour2 = ssplit2[0];
  //var minutes2 = ssplit[1];
  var ss3 = ssplit2[2].split(' ');
  var ampm2 = ss3[1]; //end

  var st = convertTo24hr(start);
  var et = convertTo24hr(end);
  /************************************/
  var st1;
  var en;
  if (ampm1 == 'AM' && ampm2 == "PM") {
    //if sched is morning
    st1 = et;
    en = st;
  } else if (ampm1 == 'PM' && ampm2 == "AM") {
    //if sched is evening
    st1 = st;
    en = et;
  }
  var s = st1.split(':');
  var e = en.split(':');
  var se = Number(s[2]) - Number(e[2]);
  var sems = Math.floor(parseInt(se / 60));
  var mi = Number(s[1]) - Number(e[1]) - sems;
  var mihr = Math.floor(parseInt(mi / 60));
  var hr = Number(s[0]) - Number(e[0]) - mihr;

  if (se < 0) {
    mi = mi - 1;
    se = se + 60;
  }
  if (mi < 0) {
    hr = hr - 1;
    mi = mi + 60;
  }
  if (hr < 0) {
    //se = 0;
    //mi = 0;
    hr = 0;
  }
  var result = hr.padDigit() + ':' + mi.padDigit() + ':' + se.padDigit();
  if (result == 'NaN:NaN:' + se) {
    result = '00:00:00';
  }
  return result;
}

function convertTo24hr(time) {
  var t = time.split(':');
  var hours = Number(t[0]);
  var minutes = Number(t[1]);
  var t2 = t[2].split(' ');
  var sec = t2[0];
  var AMPM = t2[1];
  if ((AMPM == "pm" || AMPM == "PM") && hours < 12) {
    hours = hours + 12;
  }
  if ((AMPM == "am" || AMPM == "AM") && hours == 12) {
    hours = hours - 12;
  }
  var sHours = hours.toString();
  var sMinutes = minutes.toString();
  if (hours < 10) sHours = "0" + sHours;
  if (minutes < 10) sMinutes = "0" + sMinutes;
  return (sHours + ':' + sMinutes + ':' + sec);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

But I don't know how to get the ratio. Help me get the ratio. And by the way, the result of it in excel is 7.95506 roundup to make it 8 so the ratio is 8.

A: Since both the total working hours and duration are given in xx:xx:xx time format, convert the times into seconds before dividing to get the ratio.
var myTotalHours = '05:51:05';
var myDuration =  '00:44:08';

function determineRatio(totalHours, duration) {

    var totalHoursArray = totalHours.split(':');
    var durationArray = duration.split(':');

    var numerator = parseInt(totalHoursArray[0])*3600
        + parseInt(totalHoursArray[1])*60
        + parseInt(totalHoursArray[2]);
    var denominator = parseInt(durationArray[0])*3600
        + parseInt(durationArray[1])*60
        + parseInt(durationArray[2]);

    return Math.round(numerator/denominator);

}

alert(determineRatio(myTotalHours,myDuration));


text:
Q: cannot curl a redis service from an alpine pod I have this yaml manifest for redis
apiVersion: v1
kind: Pod
metadata:
  name: redis-pod
  namespace: redis-namespace
  labels:
    app: redis
spec:
  containers:
  - name: redis-cntr
    image: redis
    imagePullPolicy: IfNotPresent
    ports:
    - name: redis-port
      containerPort: 6379
    envFrom:
    - secretRef:
        name: redis-secret
    command:
    - redis-server
    readinessProbe:
      exec:
        command:
        - redis-cli
        - ping
      initialDelaySeconds: 3
      periodSeconds: 10
      timeoutSeconds: 1
      successThreshold: 1
      failureThreshold: 3
    volumeMounts:
    - name: redis-vol
      mountPath: /data
    - name: config
      mountPath: /usr/local/etc/redis
  volumes:
  - name: redis-vol
    emptyDir: {}
  - name: config
    configMap:
      name: redis-config
      items:
      - key: redis-config
        path: redis.conf

---
apiVersion: v1
kind: Service
metadata:
  name: redis-service
  namespace: redis-namespace
spec:
  type: ClusterIP
  selector:
    app: redis
  ports:
  - name: redis-srv-port
    port: 6379
    targetPort: redis-port
    protocol: TCP

I run this manifest and the pod is running (no errors) and the service is as:
$ kubectl describe service redis-service
Name:              redis-service
Namespace:         redis-namespace
Labels:            <none>
Annotations:       Selector:  app=redis
Type:              ClusterIP
IP:                10.107.206.191
Port:              redis-srv-port  6379/TCP
TargetPort:        redis-port/TCP
Endpoints:         172.17.0.5:6379
Session Affinity:  None
Events:            <none>

To test the connection from another pod I create an interactive pod:
$ kubectl run -it alpine --image=alpine --restart=Never -- /bin/sh

I try to curl the redis pod with curl redis-service:6379 but the is returned curl: (1) Received HTTP/0.9 when not allowed. I have attempted to do curl -u default:mysecretpassword redis-service:6379 and get the same results. I do a nslookup:
$ / # nslookup redis-service
Server:     10.96.0.10
Address:    10.96.0.10:53

Name:   redis-service.redis-namespace.svc.cluster.local
Address: 10.107.206.191

If I curl the endpoints curl 172.17.0.5:6379 I get the same thing. Both pods are on the same namespace. Any idea why the alpine pod unable to curl the redis-service? Not really sure if being able to curl the service is crucial for other applications to be able to connect to the redis pod.

note: the redis.conf has the following changes:
requirepass mysecretpass
# bind 127.0.0.1  //commented
appendonly yes
protected-mode yes

A: Redis is not using HTTP protocol for client connection. So any http client like CURL cannot directly communicate with Redis server.
You can use redis-cli for testing


text:
Q: How can I create a single/multiple selection dialog using JQueryUI? JQueryUI has a very nice Dialog, but I wonder how I could create a similar dialog with multiple values I can select from.
It does not necessarily need to have a text area. Similar to how the right-click window looks or how the selection dialogs work on Android.

A: I'm not sure exactly what you are trying to do here, but I think you mean that you have various different options from which you want you want your user to select one.  You can do this by creating multiple buttons using the buttons option:
$(selector).dialog({
    buttons: {
        'button 1': function() {
            // handle if button 1 is clicked
        },
        'button 2': function() {
            // handle if button 2 is clicked
        },
        'button 3': function() {
            // handle if button 3 is clicked
        }
    }
});

If this isn't what you need, perhaps you could provide a more detailed explanation of what you want to achieve.


text:
Q: How do I split a table cell within a cell? I have this table that I'm creating online for an rp.  And several of the cells call for multiple colors.  I'd figured I'd use a gradient, but black turns out to be far too over powering.
How would I split these cells?  They're not near the header, and need to be half the size of the cells themselves.

A: If you're just splitting it in 2 you can use 2
's with float:left; and float:right;

If you have to add more color variation, just add more
's with the appropriate float designation based on which side you're adding it too.  I think that will work in most cases.

A: What do you mean by "black turns out to be far too over powering" ?
You can use linear gradients and create exact borders like in the following two classes .x and .y, notating each color twice and making a "border" between them at 50% / 51% of the gradient:

table {
  width: 50%;
  height: 50px;
}
td {
  border: 1px solid #ddd;
}
.x {
  background: linear-gradient(to right, #fa0, #fa0 50%, #0fa 51%, #0fa 100%);
}
.y {
  background: linear-gradient(to right, #dc3, #dc3 50%, #c3f 51%, #c3f 100%);
}


text:
Q: How do I get a user's input values into a JS array? I'm adding the ability for the user to input his own values into 6 input fields, some or all of which may be left blank. I already have an array populated with default values. How do I get the user's values into that array so the calculations will be performed on it?
The user can use the supplied values or enter in his own values. The supplied values section works fine. I am now adding the ability for the user to add own values (lower part of HTML).

                    <form id="form2">
                        <select class="displayLength" name="ratio" size="6">
                            <option value=''>Choose:</option>
                            <option value='sc10_4x4'>SC10 4x4: 58, 60, 62, 93</option>
                            <option value='sc10'>SC10: 75, 78, 81, 84, 87</option>
                            <option value='sc8'>SC8: 50, 52, 54</option>
                            <option value='b44'>B44: 72, 75, 78, 81, 84</option>
                            <option value='b4t4'>B4, T4: 72, 75, 78, 81, 84, 87</option>
                            <option value='gt2'>GT2: 54, 55, 56</option>
                        </select>

// THIS PART IS NEW:

                Alternate spur values:

                <input class="display" type="number" size="14" value="" name="spur1">
                <input class="display" type="number" size="14" value="" name="spur2">
                <input class="display" type="number" size="14" value="" name="spur3">

                <input class="display" type="number" size="14" value="" name="spur4">
                <input class="display" type="number" size="14" value="" name="spur5">
                <input class="display" type="number" size="14" value="" name="spur6">

                    <input id="buttonNewRatios" class="buttPress2" type="button" value="Alternates">

                        <textarea name="moreRatios" cols="42" rows="8"></textarea>

</form>

Here's the Javascript part I'm having trouble with. I don't know how to incorporate the user values into the switch so the rest of the code can run those values. I ran the code through JSHint.com and it passed. However, there are no results being displayed.
    function gearSpurs(ratio) {
    var form = document.getElementById('formGearRatio');
    var spur1 = form.elements.spur1.value,
        spur2 = form.elements.spur2.value,
        spur3 = form.elements.spur3.value,
        spur4 = form.elements.spur4.value,
        spur5 = form.elements.spur5.value,
        spur6 = form.elements.spur6.value;

        var spurs = [];

        switch (ratio) {
            case 'sc10_4x4':
            spurs = ['58', '60', '62', '93'];
            break;
            case 'sc10':
            spurs = ['75', '78', '81', '84', '87'];
            break;
            case 'sc8':
            spurs = ['50', '52', '54'];
            break;
            case 'b44':
            spurs = ['72', '75', '78', '81', '84'];
            break;
            case 'b4t4':
            spurs = ['72', '75', '78', '81', '84', '87'];
            break;
            case 'gt2':
            spurs = ['54', '55', '56'];
            break;
            default:
            spurs = [spur1, spur2, spur3, spur4, spur5, spur6];
            break;
        }
        return spurs;
    }

How do I get spur1...6 to incorporate into the switch statement properly? (This code is being used in the iPhone and  Android environments.) Works great apart from the additions.)

A: You can add them before the switch statement like so:
spurs = [spur1, spur2, spur3, spur4, spur5, spur6];

Then change the statements in your switch cases to use the push function which will add to the end of the array:
spurs.push(['58', '60', '62', '93']);

Alternatively, you can leave your switch alone and add the 6 values after the switch statement using push like so:
spurs.push([spur1, spur2, spur3, spur4, spur5, spur6]);

A: EDIT: Based on the answer you accepted, you now seem to want to return an Array that contains 2 Arrays. One with the pre-defined ratios, and one with the user defined spurs.
If that's correct, the function becomes even simpler:
var ratios = {
    sc10_4x4: ['58', '60', '62', '93'],
    sc10:     ['75', '78', '81', '84', '87'],
    sc8:      ['50', '52', '54'],
    b44:      ['72', '75', '78', '81', '84'],
    b4t4:     ['72', '75', '78', '81', '84', '87'],
    gt2:      ['54', '55', '56']
};

function gearSpurs(ratio) {

    var form = document.getElementById('formGearRatio'),
        spur1 = form.elements.spur1.value,
        spur2 = form.elements.spur2.value,
        spur3 = form.elements.spur3.value,
        spur4 = form.elements.spur4.value,
        spur5 = form.elements.spur5.value,
        spur6 = form.elements.spur6.value;

    return [ [spur1, spur2, spur3, spur4, spur5, spur6], ratios[ratio] ];

}

Your form tags are unbalanced. Just wrap the entire
 with the <form>. (You can't start a form in one  and end it in a different one.)
<form id="form2">

...

...

...

</form>

I don't see any element with the ID formGearRatio.
And you can rework the code like this to simplify a little:
var ratios = {
    sc10_4x4: ['58', '60', '62', '93'],
    sc10: ['75', '78', '81', '84', '87'],
    sc8: ['50', '52', '54'],
    b44: ['72', '75', '78', '81', '84'],
    b4t4: ['72', '75', '78', '81', '84', '87'],
    gt2: ['54', '55', '56']
};

function gearSpurs(ratio) {

    if (ratios[ratio]) {
        return ratios[ratio];
    } else {
        var form = document.getElementById('formGearRatio'),
            spur1 = form.elements.spur1.value,
            spur2 = form.elements.spur2.value,
            spur3 = form.elements.spur3.value,
            spur4 = form.elements.spur4.value,
            spur5 = form.elements.spur5.value,
            spur6 = form.elements.spur6.value;
        return [spur1, spur2, spur3, spur4, spur5, spur6];
    }
}

A: The only thing I see wrong with your code is you're trying to find a form called formGearRatios but the form's actually called form2.  If you change that line, the rest worked in my tests (if user doesn't select anything, it'll use the values from the alternate inputs).
edit as a note, I also had to edit in a way to call your function and retrieve the value of ratio, so assuming your full code already does that properly, the only problem is the form id.


text:
Q: overflow text to the left in a table WITHOUT rtl I have a table that I am trying to make behave more-or-less like Excel. I've successfully made left-aligned cells overflow into cells to the right (by putting their contexts in a wrapper div with max-width, overflow:visible, and white-space:nowrap) but am having no success making right-aligned cells overflow to the left. I've tried floating the wrapper div to the right (and various permutations of that) without success; the text invariably overflows to the right regardless.
Other answers to this question on StackOverflow and elsewhere suggest using dir:rtl, but I really really don't want to do this. I don't know in advance which cells are going to overflow and I also don't want to deal with the wacky stuff it does to punctuation.
Bonus points if you can also figure out how to get a center-aligned cell to overflow equally into both neighbors.
edit: here is an example jsfiddle: http://jsfiddle.net/AlexGodofsky/2uaHN/2/

A: I found your Q&A while doing research for the same problem: getting text inside a table cell to align right and overflow to the left.
I strongly agree with you on not using dir:rtl as mentioned e.g. in this SO answer. Besides the practical disadvantages with regards to puctuation: dir is not meant for this problem!
In your solution, the height issue is caused by the absolute positioning of the inner div: it is placed outside the flow and thus takes no height.
I did get 'right align' to work using floats and I'm happy to share this minimal example here for anyone who may need it. I also have a 'bonus' solution for the center-case.

td {
  width: 8em;
  max-width: 8em;
  border: 1px solid #000;
}
div.fix_right {
  float: right;
  white-space: nowrap;
  text-align: right;
  overflow: visible;
  background-color: #ddd;
  /* and to obscure the contents of the cell on the left: */
  position: relative;
}
div.fix_center_a {
  position: relative;
  left: 50%;
  display: inline-block;
}
div.fix_center_b {
  position: relative;
  display: inline-block;
  margin-left: -50%;
  white-space: nowrap;
  /* and to obscure the contents of the cell on the left: */
  background-color: #ddd;
}

    some text here

align right

    some text here

    some text here

do align and overflow right

    some text here

    some text here

centered text, extending to the left and right

    some text here

Align to the right
I think the key in this solution is to use the combination of float in the div and max-width in the td.
The relative positioning and bg-color are needed in order to let the contents 'obscure' the contents of the column(s) to the left. If these left columns are empty anyway, this is not even needed.
Center
This solution (unfortunately) needs an additional layer of non-semantic div, but it works as follows:

*

*The td is left alone so that it may get a border etc. Note that the border shows that the cell itself is not expanding, only the contents overflow it.

*The first div (fix_center_a) gets us in the middle of the cell and gets us the total width needed for the content.

*The second div (fix_center_b) just shifts the content 50% of the total width (from fix_center_a) to the left, thus centering the content.
(Because of the relative positioning of the first div, the content already obscures the content of the left and right cells if you apply a background-color on the fix_center_b.)

A: Based on crush's suggestion in the comments, I've figured out a way to do this:
http://jsfiddle.net/AlexGodofsky/2uaHN/3/
The key is for these cells to have an outer wrapper div with position:relative along with the normal wrapper styling (max-width, overflow:visible, and white-space:nowrap), then an inner wrapper div with a flexible size and position:absolute right:0.
An issue I ran into on the way is that you either need to give the outer wrapper a fixed height (height:100% does not work) or play with vertical-align on the td, otherwise the top of the outer wrapper will be in the middle of the cell. Which is optimal probably depends on whether you can know the row height in advance.


text:
Q: Automating vector data entry in ArcMap I have a vector contour data(polyline). I want to add values to each contour lines. Means I want to digitize my contour lines with proper values. Those values are with me in a paper. I'm adding those (z values) in the "id" column in the attribute table after selecting each line separately. it's taking a lot of time since there are around 20000 lines. Actually I created these contours after digitizing my raster map.(raster to vector conversion after scanning those maps)
Is there any way to add values automatically in between lines, if I select two extreme lines (contour is varying by an interval of 1 unit) or is it possible to create a GUI like that, or can I program like that in ArcMap 10.4?
I'm new to this.

I checked whether is there any pattern of change in "FID" of lines. But I couldn't find a common pattern. I'm adding my contour values to the "id" table.

A: In my earlier comment I said:

Try running a transect line across your contours and then doing an
  Intersect of that with your contours.  If the resultant points
  preserve the order you want then you could iterate through them to
  select the contours (Select By Location) and update their values
  (Calculate Field or UpdateCursor).  This would be easier to do with
  ArcPy but I think would be doable in ModelBuilder too.

To flesh that out a bit these are more detailed steps, but if you have trouble with any of them, then I think that specific step should be asked about in a new question.

*

*Create a new Line feature class and digitize into it a "transect" that crosses the contours that you want to update the attribute of.  It can be a two or many point line.

*Intersect this line feature class with the contour feature class.  This should create a point feature class, and I am hoping the feature IDs of those points will be in the order that they crossed the contours.  If not, then this workflow will need to be re-thought.

*Add an attribute to the point feature class and calculate values into it that match what you want to put onto your contours.

*Iterate through the points in your point feature class and use each to Select Layer By Location on the contour feature class.

*Each point should select a different contour.

*Read the current point's attribute value and write it to the attribute of the only selected contour using Calculate Field.

If you wanted to get fancy you could use a Feature Set parameter on your tool to enable you to capture the transect line at the start of the tool.
I would be more comfortable doing all of the above using ArcPy, but I think it is all doable in ModelBuilder too.


text:
Q: Nested loops for Paste function I wish to use nested loops to produce 125 labels for 25 manifest variables & 5 latent variables
as_1_1 to as_25_1 ... as_1_5 to as_25_5
I can't seem to get the code working.
I have tried this:
for (i in 1:25) for (j in 1:5)
  {
    AsLabs1  <- paste("as",1:i,1:j,sep="_")
  }

AsLabs1

"as_1_1"  "as_2_2"  "as_3_3"  "as_4_4"  "as_5_5"  "as_6_1"  "as_7_2"
"as_8_3"  "as_9_4"  "as_10_5" "as_11_1" "as_12_2" "as_13_3" "as_14_4"
"as_15_5" "as_16_1" "as_17_2" "as_18_3" "as_19_4" "as_20_5" "as_21_1"
"as_22_2" "as_23_3" "as_24_4" "as_25_5"

but I need the loop to be output all 25 variables for each value of j (1 to 5), not just 5.
I realize the solution must be quite simple what i am doing wrong.

A: This should do it:
paste("as", apply(expand.grid(1:25, 1:5), 1, paste, collapse = "_"), sep = "_")

Your own code works with slight modification:
AsLabs1 <- character()
for (i in 1:25) {
  for (j in 1:5) {
    AsLabs1  <- append(AsLabs1, paste("as", i, j, sep = "_"))
  }
}

Edit Corrected mistake in nested loop.

A: I personally wouldn't bother with a nested loop, just use paste with a "_" sep, and rep function with times and each arguments specified.
AsLabs <- paste(rep("as", times = 25*5), rep (1:25, times = 5),
  rep(1:5, each = 25), sep = "_")

... If you are determined to use a nested loop, it can be done with a slight modification to your code, adding the rep function:
AsLabs1 <- rep(NA, 125)
for (i in 1:25) for (j in 1:5)
  {
    AsLabs1  <- paste("as",rep(1:i, each = 5),1:j,sep="_")
  }

I wouldn't use a nested loop because i) it's unnecessarily complex code and ii) considerably slower  to run (my paste approach is about 40 times faster than the nested loop solution [and about 7 times faster than the apply method in the answer from Anders])

A: I'd use outer for this,
paste0('as_', outer(1:25, 1:5, paste, sep = '_'))


text:
Q: Imaginary time and string theory Is imaginary time an extra dimension?
In other words, are time and imaginary time considered two separate dimensions?
If so, does imaginary time appear (as a separate dimension) in string theory (thus contributing to the 11 dimensions in M-theory)?

A: In physics, it is often possible/meaningful to analytically continue various real quantities into a corresponding complex variable.
In case of time, such analytical continuation allows us to wick-rotate a real time integration contour into an imaginary integration contour if we avoid singularities in the complex plane.
Wick-rotation is a mathematical procedure that doesn't count/qualify as an extra physical space-time dimension.
That said, there exists a branch of string theory, known as F-theory, that formally operates with two
time-dimensions, cf. this Phys.SE post.

A: In addition to Qmechanic's nice answer, in string theory the wick rotation changes the Lagrangian such that the equations of motion are given by the Laplace equation instead of the conventional wave equation.
In calculations of the world sheet integral, for example for two strings to join and split again, one can make use of the conformal invariance of the Laplace equation to conformally map the integration over all world sheets to an integration over the unit disk.
In the transformed world sheet coordinates, the S-T (channel) duality can easily be seen as an equivalence of putting the injection points on the bottom and top or on the right and the left of the unit circle.


text:
Q: Use look up to find the values in xml , xsl I am new to this Technology. I need to use the lookup concept here,
I have a XML file: As below,
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <?xml-stylesheet type="text/xsl" href="lookup.xsl"?>

    <member>

            <name>Indhu</name>
            <pir>PIR1</pir>
            <age>25</age>
            <novel>Nothing hides</novel>

    </member>

The xsl file is:
      <?xml version="1.0" encoding="utf-8"?>

         <title>YOU</title>

Hello world

<xsl:value-of select="member/name" />

<xsl:value-of select="member/age" />

         PIR Rate:
              <xsl:value-of select="member/pir"/>
                <xsl:call-template name="pircode_lookup">
                <xsl:with-param name="pircode" select="pirCode" />
                </xsl:call-template>

               </xsl:template>
             </xsl:transform>

I have a lookupValues xsl file :
       <?xml version="1.0" encoding="UTF-8"?>
       <xsl:stylesheet version="1.0"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

         <xsl:template name="pircode_lookup">
         <xsl:param name="pircode"/>
         <xsl:choose>
          <xsl:when test="$pircode='PIR0'">
            <xsl:text>Zero</xsl:text>
        </xsl:when>
        <xsl:when test="$pircode='PIR1'">
            <xsl:text>One</xsl:text>
        </xsl:when>
        <xsl:when test="$pircode='PIR2'">
            <xsl:text>Two</xsl:text>
        </xsl:when>
        <xsl:when test="$pircode='PIR3'">
            <xsl:text>Three</xsl:text>
        </xsl:when>
        <xsl:when test="$pircode='PIRD'">
            <xsl:text>Default</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>Unknown PIR Code: </xsl:text><xsl:value-of select="pirCode"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

I want this call to access the lookupValues.xsl and get me the value of PIR1, but i am getting the default value as result (Unknown PIR code)

A: At the time when you call the pircode_lookup template, you are at the root node want to pass the member/pir node as the $pircode param. So:
<xsl:with-param name="pircode" select="member/pir" />

You also wrote pirCode one time, when you should have written $pircode in your <xsl:choose>:
<xsl:choose>
    <xsl:when test="$pircode='PIR0'">Zero</xsl:when>
    <xsl:when test="$pircode='PIR1'">One</xsl:when>
    <xsl:when test="$pircode='PIR2'">Two</xsl:when>
    <xsl:when test="$pircode='PIR3'">Three</xsl:when>
    <xsl:when test="$pircode='PIRD'">Default</xsl:when>
    <xsl:otherwise>Unknown PIR Code: <xsl:value-of select="$pircode"/></xsl:otherwise>
</xsl:choose>

Note: You can work with <xsl:text>, this is absolutely correct to avoid unwanted whitespace in the output.
However as long as you don't have any unnecessary whitespace in the XSL, you can compress the code a bit by dropping the <xsl:text>, like shown above.


text:
Q: SQLite: Create File Structure Table from String Path. New query or modify existing? I have a SQLite table:
FileDataID | Path
0            /FileAtRoot.txt
1            /video/gopro/father/mov001.mp4
2            /pictures/family/father/Oldman.jpg
3            /documents/legal/father/estate/will.doc

Using an elegant solution designed by forpas, a new table consisting of only the directory structure is created:
Directory | Directory_Parent | Value
0           null               root
1           0                  documents
2           1                  legal
3           2                  father
...

Reference: SQLite: Create Directory Structure Table from A List Of Paths
Now that a table of the directory structure exists, I need to link the original files to their parent by using a foreign key Directory_Parent in a new table:
FileDataID | Directory_Parent | Value
0            0                  FileAtRoot.txt
1            19                 mov001.mp4
2            9                  Oldman.jpg
3            4                  will.doc

How can I create this table from the original data using SQLite?

*

*Can forpas's solution be modified so it creates both tables at once?

*Or should this 2nd "file_struct" table be created in a 2nd SQLite query?

A 1 megabyte example database can be found here:
A bounty will be awarded for helping with this final question, thank you.

A: For this to work, you must have already the table dir_struct (from your previous question) so that the file names can be inserted to the table with the id of the directory they belong to.
First I create the new table files:
CREATE TABLE files(
  FileDataID INTEGER REFERENCES listfile(FileDataID),
  Directory_Parent INTEGER REFERENCES dir_struct(Directory),
  Value
);

You must also create a unique index for FileDataID in listfile, because it is not defined as the PRIMARY KEY or UNIQUE, so columns in other tables (like the column FileDataID of files) can reference it.
CREATE UNIQUE INDEX idx_listfile_FileDataID ON listfile(FileDataID);

A recursive CTE is used to query dir_struct and build all the possible paths and it is joined to listfile to match the file names and their paths:
WITH cte AS (
  SELECT Directory, Directory_Parent, Value, '' full_path
  FROM dir_struct
  WHERE Directory = 0
  UNION ALL
  SELECT d.Directory, d.Directory_Parent, d.Value, full_path || d.Value || '/'
  FROM dir_struct d INNER JOIN cte c
  ON c.Directory = d.Directory_Parent
)
INSERT INTO files(FileDataID, Directory_Parent, Value)
SELECT f.FileDataID, c.Directory, SUBSTR(f.Path, LENGTH(c.full_path) + 1)
FROM listfile f INNER JOIN cte c
ON f.Path LIKE c.full_path || '%' AND INSTR(SUBSTR(f.Path, LENGTH(c.full_path) + 1), '/') = 0

See the demo, where the code for the insertions in dir_struct has also been modified because now the table listfile contains files at the root, which did not exist in the sample data of your previous question.
So the code in the demo must be executed as a whole.
I used your 1MB sample data and the queries ran very fast.
But, for 1M rows (from the link you first posted), which I also tested (and found duplicates which you must delete before doing anything else), the creation of the table files took about 1.5 hour.
As I mentioned in my answer of your previous question, if this is a one time thing then use it. If you will need it frequently, then you should consider something else.


text:
Q: What is wrong with this approach to find Expected value of distance between $X, Y \in$ Uniform $(0, 1)$? Let $X$ and $Y$ be i.i.d. random variables with Uniform $(0, 1)$ continuous distribution.
The problem is to find the expected value of the distance between X and Y.
My reasoning was, for all $(x, y) \in X \times Y$, any distance must be $0 \le |x - y| \le 1$, so we can consider two cases, $0 \le y - x \le 1$ and $0 \le x - y \le 1$.
So to find the expectated value of the distance, I would take the sum of the two integrals,
$$ \int_0^1 \int_{y-1}^1 (y - x) \; dx \; dy $$
$$ \int_0^1 \int_{x-1}^1 (x- y) \; dy \; dx $$
The first and second integrals each give $1/3$, so the answer I reached is $2/3$, whereas the correct answer for expected distance is $1/3$ and uses integrals over different limits of integration. I know what the correct answer says, but where am I going wrong here?

A: The setting up of the integrals was not correct. If $X$ and $Y$ are our random variables, we want to find
$$\iint_{S} |x-y|\,dxdy,$$
where $S$ is the $1\times 1$ square.
Draw that square. Now it is useful to break up this integral into two parts, by drawing the line $y=x$, which slices our square into two parts: (i) where $y\ge x$ and (ii) where $y\le x$.
To do (i), express as an iterated integral. If you wish to integrate first with respect to $x$, note that $x$ travels from $0$ to $y$. The travels of $x$ can be seen clearly in the picture. So for (i) we need
$$\int_{y=0}^1\left(\int_{x=0}^y(y-x)\,dx    \right)\,dy.$$
Because of symmetry, (ii) will give the same result.
There are a couple of problems with your integrals. First note that there has not even been an integration with respect to $y$. Secondly, the setting up of the limits has no clear connection to the geometry.

A: Edit: my previous answer was actually not correct, so I removed it completely.
I had said that you need to divide your integral results by 2, since they each represented half of the domain space. This is not correct; if the integrals' bounds are set up correctly and we are actually integrating over the correct areas, the fact that they individually account for only half of the domain will naturally be accounted-for.
The only error in your original approach is the setup of the integrals. So, draw the image of $[0,1]\times[0,1]$ as a visual aid, and work from there. The integrals corresponding to your two cases should be $$\int_{0}^{1}\int_{0}^{y}(y-x)dxdy$$ for the upper triangle, where $y>x$, and $$\int_{0}^{1}\int_{0}^{x}(x-y)dydx$$, where $x>y$. By symmetry these integrals will have the same value, so double the calculation from each. (each has value 1/6).
Sorry for the confusion.

A: This is not really an answer to the question "Where am I going wrong here?"
but rather an alternative way of approaching the problem to be solved that
gives the answer quite easily.
$Z = |X-Y|$ is a non-negative random variable taking on values in $[0,1]$, and hence
$$E[Z] = \int_0^{\infty} P\{Z > z\}\,\mathrm dz = \int_0^1 P\{Z > z\}\,\mathrm dz.$$
But, for $0 \leq z \leq 1$, $P\{Z > z\}$ is the probability that the random point
$(X,Y)$ lies in one of two right-triangular regions of area $\frac{1}{2}(1-z)^2$ each.
This is easiest to figure out if you follow André Nicolas's suggestion to draw
a sketch: the triangles have vertices $(z,0), (1,0), (1,1-z)$ and $(0,z), (0,1),(1-z,1)$
respectively. Hence,
$$E[Z] = \int_0^1 P\{Z > z\}\,\mathrm dz = \int_0^1(1-z)^2\,\mathrm dz
= \left. \frac{-1}{3}(1-z)^3\right|_0^1 = \frac{1}{3}.$$


text:
Q: How can i declare a int type input variable eg. take a input x(0I try to use this code
#include <stdio.h>
int main() {
    int x,y,z;

    scanf("%d%d", &x, &y);
    z = x + y;
    printf("%d", z);
    return 0;
}

The problem is: Two man have x and y dollar. Take input of x(0 < x < 10000) and y(0 < y < 10000) and print the summation of their dollars.

A: You cannot put restriction on user entering any value. But you can ask user to re-enter the values again in specified limit with little modification in your code.
scanf("%d%d", &x, &y);
while( x <= 0 || y <= 0 || x >= 10000 || y >= 10000) {
    // Suitable message for re-entry of numbers.
    scanf("%d%d", &x, &y);
}
z = x + y;
printf("%d", z);

A: There's no standard way to do a range check as part of an input operation in C - IOW, you can't tell scanf to reject an integer input that's outside of a specific range.  You will have to add a range check separately:
if ( scanf( "%d%d", &x, &y ) == 2 ) // make sure both x and y are read
{
  if ( 0 < x && x < 1000 && 0 < y && y < 1000 )
  {
    z = x + y;
    printf( "z = %d\n", z );
  }
  else
  {
    printf( "Both x and y must be between 0 and 1000\n" );
  }
}
else
{
  printf( "At least one bad input for x or y\n" );
}

A: You cannot restrict scanf to not to get an undesired integer, but you can re-take the input from the user if the value entered is bigger than 10k or smaller than 0. That would be a simple solution.
scanf("%d%d", &x, &y);

if( x > 10000 || x <= 0) {
 printf("Please re-enter a value for x: \n");
 scanf("%d", &x);
 }

if( y > 10000 || y <= 0) {
 printf("Please re-enter a value for y: \n");
 scanf("%d", &y);
 }

If you want you can also make a termination scenario by using "End of File" (EOF). Putting this here for source.
How to use EOF


text:
Q: Programmatic way to get output directory in Bookdown? Is there a way to detect the Bookdown output directory in code running within an RMarkdown document?
I'm happily using Bookdown to write tutorials using Python code.  To make the tutorial interactive, I want to make copies of the .Rmd files as Jupyter Notebooks, and put something like this at top of the relevant .Rmd files:
`r make_link_notebook()`

where the make_link_notebook function creates the Jupyter Notebook file, and makes a link to the notebook within the output document.
To do this, make_link_notebook needs to know where the Bookdown output directory is.  By default, of course, this is _book, but I am customizing this in some configuration files, so I want to be able to find the output directory programmatically.  Is this possible?


text:
Q: Paragraph text from model object coming in same line I have an ASP.NET MVC application which is used to show details from database. My index view for an entity having only one property i.e. text is
@foreach( var item in model)
{

@Item.text

}

If the text field is too long, it is shown in a single line and a horizontal scroll bar appears. I want it to flow to next line. Kindly help me figure out the solution. Thanks

A: If I understand you correctly, just use word-break: break-all;

p {
  word-break: break-all;
}

LOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUMLOREMISPUM


text:
Q: Strengthening Quine's New Foundations with a more flexible stratification criterion? Let's say that a formula in the language of set theory is flexibly stratified iff there exists a function $f$ from variable symbols to $\omega$ such that if $x=y$ appears in the formula, then $f(x)=f(y)$, and if $x\in y$ appears in the formula, then $f(x)<f(y)$ (this is in contrast to regular stratification which requires $f(y) = f(x) + 1$ exactly).
I'm going to define Flexible NF as:

*

*Extensionality (same as in NF)

*Flexibly Stratified Comprehension (same as in NF except allowing comprehension over "flexibly stratified" formulae)

This is clearly at least as strong as NF, since every theorem of NF is a theorem of Flexible NF.
Is Flexible NF obviously inconsistent, or obviously equiconsistent with NF?

My thoughts:
Could we somehow use flexible stratified comprehension to define the bijection $f: x \mapsto \{x\}$ on e.g. the universal set, and then use that in contradiction with Cantor's Theorem to get inconsistency?

A: Flexibly Stratified Comprehension is inconsistent. By Flexibly Stratified Comprehension, there is an s such that
$$\forall x\:\bigl(x\in s\leftrightarrow\exists y\:\bigl(\forall t\:(t\in y\leftrightarrow t\in x)\land y\notin x\bigr)\bigr).$$
If $s\in s$, then there is an $S$ with the same members as $s$ such that $S\notin s$.
But if $S\notin s$, then for all $T$ with the same members as $S$, $T\in S$. In particular $S\in S$ and thus $S\in s$.
If $s\notin s$, then for all $S$ with the same members as $s$, $S\in s$. In particular $s\in s$.


text:
Q: Прервать установку Вот часть скрипта inno
[Files]
Source: "C:\Users\Жека\Desktop\Goons Raid Her – New Version 0.2\directx.exe"; DestDir: "{app}"; AfterInstall: Rundirectx
Source: "C:\Users\Жека\Desktop\Goons Raid Her – New Version 0.2\Goons Raid Her.exe"; DestDir: "{app}"
Source: "C:\Users\Жека\Desktop\Goons Raid Her – New Version 0.2\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; NOTE: Don't use "Flags: ignoreversion" on any shared system files

[Code]
procedure Rundirectx;
var
  ResultCode: Integer;
begin
  if not Exec(ExpandConstant('{app}\directx.exe'), '', '', SW_SHOWNORMAL,
    ewWaitUntilTerminated, ResultCode)
  then
    MsgBox('directx failed to run!' + #13#10 +
      SysErrorMessage(ResultCode), mbError, MB_OK);
end;

В данном скрипте перед распаковкой папки с игрой происходит установка directx. Как сделать так, что если пользователь отменил установку directx, то и отменялась бы операция распаковки папки с игрой? Выше в скрипте этого не происходит если прервать установку directx, то далее происходит распаковка папки с игрой.


text:
Q: Xamarin.Android & Azure Push Notifications Internal Server Error I'm following the guide at https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-android-get-started-push (as well as the original Xamarin one that this appears to have cribbed from), but I'm running into a problem registering my client.
I am successfully logging a user in prior to setting up the push notification service.
Both GcmClient.CheckDevice(...) and GcmClient.CheckManifest(...) succeed, and my PushHandlerService is being called.
Push.RegisterAsync(...) in my PushHandlerService is throwing a MobileServiceInvalidOperationException because it received an HTTP 500 Internal Server Error from the service.
Looking at FREB logs, it appears that the "error" is actually supposed to be a success, and interestingly is somehow related to the EasyAuthModule:

*NOTIFY_MODULE_COMPLETION    ModuleName="EasyAuthModule_64bit", Notification="AUTHENTICATE_REQUEST", fIsPostNotificationEvent="true", CompletionBytes="297", ErrorCode="The operation completed successfully.
(0x0)"   05:51:01.092

*Module_set_response_error_status
Warning ModuleName="EasyAuthModule_64bit", Notification="AUTHENTICATE_REQUEST", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="79", ErrorCode="Unspecified error
(0x80004005)", ConfigExceptionInfo=""    05:51:01.092

*NOTIFY_MODULE_COMPLETION    ModuleName="EasyAuthModule_64bit", Notification="AUTHENTICATE_REQUEST", fIsPostNotificationEvent="true", CompletionBytes="0", ErrorCode="The operation completed successfully.
(0x0)"   05:51:01.092

A: I take it the error is happening when you call client.GetPush().RegisterAsync()?  This is currently an issue and we are deploying a fix on the Azure side to fix this.  In the interim, you can see the fix for this here: https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter5/android/


text:
Q: get wrong-type-argument sequencep in emacs () I always get
Error during redisplay: (wrong-type-argument sequencep 42) [22 times]

in emacs Message buffer. whole Message buffer is this error message.
Even I use fundamental mode, the error still counted.
Time count happens when I Save buffer, change buffer.
  But time don't change when just simply put in characters or move
  cursors in one buffer.
What should I do to find out the root cause?
  a Better method to find out this problem conveniently ,
  just as add a --debug-init when emacs startup. At least, It can tell me which line
  raise errors.
My settings:
emacs 24.1, 24.2(currently). archlinux.

A: This Error during redisplay means that the error is in Elisp code that is run during redisplay, so Emacs can't conveniently give you much info because that would require displaying something, and that's already what it's trying to do.

A: Here's a semi-wild guess: some of your code is trying to do something to the mode-line text, which redisplay tries to update often.  42 as a character is *, and a string is a sequence. Here's another semi-wild guess: some code that you load, and that tries to fiddle with the mode line,  tries to handle the character * as if it were the string *, performing a sequence operation on that (expected) string.
Anyway, to find the problem, bisect your init file (~/.emacs) recursively until you locate the culprit code. (I assume you do not have the problem when you start Emacs without your init file: emacs -Q.)


text:
Q: Using trigger to automatically update field when inserting a new row I have this table Studentinformation I want to create a trigger so that whenever a new row is inserted, without the Email column specified, the trigger will fire and automatically update the Email column. The email format will look like this FirstName.LastName@youremail.com  For example: ('John', 'Smith') This would look like: JohnSmith@youremail.com
However, if the insert statement already contains an email address, the trigger will not update the email field.
Can someone help me write or modify the query I have so far?
Studentinformation table:
CREATE TABLE Studentinformation (
                    StudentID int NOT NULL IDENTITY(100,1) PRIMARY KEY,
                    Title char(10) NULL,
                    FirstName char(10) NULL,
                    LastName char(10) NULL,
                    Address1 char(50) NULL,
                    Address2 char(50) NULL,
                    City char(50) NULL,
                    County char(50) NULL,
                    Zip char(10) NULL,
                    Country char(50) NULL,
                    Telephone char(10) NULL,
                    Email varchar(255) NULL,
                    Enrolled char(10) NULL,
                    AltTelephone char(10) NULL);

What I have so far:
-- This code creates a trigger
DROP TRIGGER IF EXISTS trg_assignEmail;

CREATE TRIGGER trg_assignEmail ON Studentinformation
FOR INSERT
AS
UPDATE Studentinformation
SET Email = FirstName+'.'+LastName+'@youremail.com'

Thank you in advance!

A: The basic statement you need is as follows. Using the inserted table which contains only the row(s) inserted for the current server process, join back to the table on its primary key and update only the inserted rows which are not blank (and implied also not NULL).
update s
  set s.email = Concat(s.FirstName, '.', s.LastName, '@youremail.com')
from inserted i
join Studentinformation s on s.StudentId = i.StudentId
where i.email != '';

A: I complete the answer with ISNULL function.
CREATE TRIGGER trg_assignEmail ON Studentinformation
After INSERT
AS
    UPDATE s
      SET Email = Isnull(i.Email, Concat(i.FirstName, '.', i.LastName,'@youremail.com'))
    FROM inserted i JOIN Studentinformation s on s.StudentId = i.StudentId


text:
Q: Why does adding border increase box size by more than 2 px? My html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Day 01</title>

Lorem ipsum dolor sit.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quod unde rerum, deleniti ea obcaecati sint hic
                odit dicta tenetur qui ut dolorum provident sit, atque, reprehenderit nulla voluptate! Officiis,
                consectetur?

Iste ipsa enim delectus porro, ullam repellendus maiores quis rem debitis cum, necessitatibus architecto
                dolor? Velit, ad quaerat blanditiis veritatis expedita totam vel voluptatem officiis officia ab modi
                voluptatibus obcaecati.

Accusantium minima iusto nobis fuga hic explicabo unde illum, perferendis et animi aperiam quaerat, eaque
                deleniti alias blanditiis exercitationem commodi repudiandae ullam consequatur incidunt reiciendis
                repellat officia laboriosam. Esse, modi.

Expedita cupiditate iure odit, delectus placeat optio magnam assumenda mollitia aspernatur at saepe nisi
                commodi natus excepturi voluptate. Recusandae nisi dolorem, necessitatibus optio aliquam repellat.
                Adipisci, incidunt. Consequuntur, natus nulla.

When Div intro-content's border is set to 1px, intro-content box is of size 1594x238. But when I remove the border, it size is 1594x200 instead f 1594x236. Why is it so? Screenshots are below.
Screenshot with border

Screenshot with no border

A: If the element is the first child it will add the margin-top to the parent element, collapsing with the margin-top of the parent element. Check Collapsing margins article for more information.
The question was already answered in Margin on child element moves parent element
As described there, you can just add the following css rules
.container {
  overflow: auto;
}


text:
Q: How to pass a form value to another view How to get a form value form one view to another.
for example i would like to get the 'web_input' value from  InputWebView() and pass it into DisplayWebView()
<form method="POST" action="">
  {% csrf_token %}
    {{ form.non_field_errors }}
    {{ form.web_input }}
    <input type="submit">
</form/>

def InputWebView(requests)
    form = WebInputForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            return redirect('add_web', web_url=request.POST['web_input'])

def DisplayWebView(request, web_url):
    url = web_url

A: You can use sessions to pass data from one view to another. In InputWebView:
def InputWebView(requests)
    form = WebInputForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            request.session['web_input'] = request.POST['web_input']
            return redirect('add_web')

In DisplayWebView:
def DisplayWebView(request):
    url = request.session.get('web_input')


text:
Q: VS2010 Reportviewer header hides the menu on my ASP.NET 4.0 site I have a webforms asp.net 4.0 app, with a Webcontrols.Menu on the Site.Master.  This menu is configured as a DropDown menu.
On some of the pages I have a VS2010 ReportViewer on the page, and when it is rendered, the header row, of the report, will stay in front of the drop down menus.
Any ideas on how to fix this?  Make the menus, render in front of the header?  I have looked at all the properties I could find for the header, or the rv webpart, but no luck yet.

A: It seems to be a CSS only problem. try playing with the stylesheet a bit or you can also change the z-index property of the menu bar.
Hope This helps.


text:
Q: Get Products by Product category in a shortcode with WooCommerce I have a shortcode, I would like to get all the products from a specific Woocommerce category.
add_shortcode( 'list-products', 'prod_listing_params' );
function prod_listing_params( $atts ) {
ob_start();

extract( shortcode_atts( array (
    'type' => 'product',
    'order' => 'date',
    'orderby' => 'title',
    'posts' => -1,
    'category' => '',
), $atts ) );

$options = array(
    'post_type' => $type,
    'order' => $order,
    'orderby' => $orderby,
    'posts_per_page' => $posts,
    'product_cat' => $product_cat,
);
$query = new WP_Query( $options );
if ( $query->have_posts() ) { ?>

        <?php while ( $query->have_posts() ) : $query->the_post(); ?>

        <span id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

        <?php endwhile;
        wp_reset_postdata(); ?>

<?php
    $myvar = ob_get_clean();
    return $myvar;
}
}

So I use the shortcode:
[list-products category="shoes"]

But it returns all the products from all categories despite providing the category in the shortcode.
How can I amend this to get by category?
Thanks

A: Instead of 'product_cat' => $product_cat, you should use a tax_query this way:
'tax_query' => array( array(
     'taxonomy' => 'product_cat',
     'field' => 'slug',
      'terms' => $atts['cat'],
) ),

So your code should be something like (I have revisited a bit your code):
// Creating a shortcode that displays a random product image/thumbail
if( !function_exists('prod_listing_params') ) {
    function prod_listing_params( $atts ) {
        ob_start();

         $atts = shortcode_atts( array (
            'type' => 'product',
            'order' => 'date',
            'orderby' => 'title',
            'posts' => -1,
            'category' => '', // category slug
        ), $atts, 'list_products' );

        $query = new WP_Query( array(
            'post_type' => $atts['type'],
            'order' => $atts['order'],
            'orderby' => $atts['orderby'],
            'posts_per_page' => $atts['posts'],
            'tax_query' => array( array(
                 'taxonomy' => 'product_cat',
                 'field' => 'slug',
                  'terms' => $atts['category'],
            ) ),
        ) );

        if ( $query->have_posts() ) {
            ?>

                    <?php while ( $query->have_posts() ) : $query->the_post(); ?>

                    <span id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                    <?php endwhile;
                    wp_reset_postdata(); ?>

            <?php
            $myvar = ob_get_clean();
            return $myvar;
        }
    }
    add_shortcode( 'list_products', 'prod_listing_params' );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Example USAGE:
[list_products category="shoes"]

Related answers:

*

*Nested shortcode to display dynamically woocommerce products category

*Display a random product thumbnail for a product category in WooCommerce

A: you can also use shortcodes provided by WooCommerce itself
[product_category category="appliances"]


text:
Q: Extracting objects from a list by quantity I have ArrayList<Drink> drinks
The Drink class consists of 2 items, name and amount.
If I have many instances of a Drink class populated in ArrayList<Drink, for example:
"coke", "30"
"fanta", "10"
"coke", "5"
"sprite", "1"
"coke", "10"
I want now to have only one list, that combines those elements and output to be like this:
"coke", "45"
"fanta", "10"
"sprite", "1"
How can I achieve this. Also I don't know what drinks the list will contain, it may be some other. Just want to combine them by amount and without repetitions?
Thanks.

A: If you are using java-8 or later then
List<Drink> list = new ArrayList<>();
list.add(new Drink("coke", 30));
list.add(new Drink("fanta", 10));
list.add(new Drink("coke", 5));
list.add(new Drink("sprite", 1));
list.add(new Drink("coke", 10));
Map<String, Integer> map = list.stream()
    .collect(Collectors.groupingBy(Drink::getName,
                 Collectors.summingInt(Drink::getAmount)));
System.out.println(map);

output
{sprite=1, coke=45, fanta=10}
Collection<Drink> c =
       list.stream().collect(Collectors.groupingBy(Drink::getName,
            Collectors.collectingAndThen(
                Collectors.reducing((Drink a, Drink b) -> {
                   a.setAmount(a.getAmount() + b.getAmount());
                   return a;
            }), Optional::get))).values();


text:
Q: iphone - setting a property on another class I have a property declared on a class:
.h
@interface myClass : UIView {
  BOOL doStuff;
}

@property BOOL doStuff;

.m
@synthesize doStuff;

this class is a delegate of another one. On the other class, I am trying to set this property, doing something like
[delegate setDoStuff:YES];

I receive an error telling me that "method -setDoStuff: not found..."
How do I declare the property on the class, so other classes can read and set them?
thanks.

A: is your delegate declared as type "id" ?
either you declare its true type MyClass delegate in the other class (which points to your myclass) or
declare a protocol that delegate has to implement id  in declaration.
Last (but not right approach) is to typecast it [(MyClass)delegate doStuff].

A: Make sure that you're importing your custom class's header and that delegate is declared as an instance of that class.

A: you could also specify the name of setter function in @property.
@property (nonatomic,setter = setMyDoStuff,assign) BOOL doStuff;


text:
Q: TinyMCE upgrade an modified editor to the latest version mayhem It is this sad moment to a developer's life that he has to maintain and fix legacy code... In my case I have to deal with a modified (core scripts) tinyMCE 3.2.2 which I have to update to the latest version in order to play in IE9+...
So my question is if there is a way to check which files have been changed since version 3.2.2 and try to update only those cause it is an overkill to check all the code for the modifications...
Thanks in advance

A: I fear there are so many changes in so many files that most of them have changed since then and in order to work with IE9.
If possible you should never ever modify the core code. Instead use custom plugins if possible.


text:
Q: Visual studio code not running any flutter commands I just started mobile app development and i want to use visual studio code but the problem is it does not execute any flutter commands that i run.
Not even flutter --version works but all the flutter commands work when i run them on the cmd.
I tried creating project using vscode and i left it for almost two hours and when i got back it was still the same like on the image below. What could be the problem?


text:
Q: CakePHP 3.0 - Post Link - adding classes removes alert confirmation functionality When I add the class array to the postLink, the confirm alert stops working. I have moved the class array into different positions but within the postLink but nothing seems to work.
<?= $this->Form->postLink(__('Delete'),
['controller' => '<%= $details['controller'] %>', 'action' => 'delete', <%= $otherPk %>],
['class' => 'btn btn-danger btn-sm'],
['confirm' => __('Are you sure you want to delete # {0}?', <%= $otherPk %>)]) %>

The above code will add the right classes to the link, but the confirmation doesn't work, it just deletes the entry right away.

A: the confirm message and the other html options like class go in the same array
<?= $this->Form->postLink(__('Delete'),
    ['controller' => '<%= $details['controller'] %>', 'action' => 'delete', <%= $otherPk %>],
    ['class' => 'btn btn-danger btn-sm'],'confirm' => __('Are you sure you want to delete # {0}?', <%= $otherPk %>)]) %>


text:
Q: Invoking AWS Step Function from API Gateway and returning response? From my understanding, API Gateway can trigger the Step Function. To kick off our state machine execution we need to send a post request as input.
The issue I am coming across is that API gateway will not wait for the execution to finish so it is no way of allowing the step function to respond back to the request:
Below is an image to outline this.

If this is in fact true, is there a way to call a lambda from within my lambda?

A: That is true, any invocation of Step Functions will immediately return a success response with an execution ARN that can be used to track the execution status.

If this is in fact true, is there a way to call a lambda from within
my lambda?

Yes absolutely, via the AWS SDK for the programming language you are using you can call the Lambda invoke() method. Although if you have one Lambda waiting on another Lambda to finish executing, be aware that you are going to be doubling the AWS Lambda charges you incur.


text:
Q: Python script freezes for no apparent reason (afaik) i'm not particularly new at python but i just thought there might be a reason for this program not working properly. i have written a similar one from which this is derived, and that still works fine. it is a program to graph the average time of a set of ping responses, to see if there is any pattern in the time over the day. the source is as follows
from Tkinter import *
import matplotlib
import time
import os, sys, threading, Queue
matplotlib.use('TkAgg')
from numpy import arange, array, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

import Tkinter
import sys
class App(object):
    def __init__(self):
        self.q = Queue.Queue()
        self.q2 = Queue.Queue()
        self.avvals=[]
        self.addlist=['bbc.co.uk', 'google.co.uk', 'nhgs.co.uk', 'bing.co.uk', 'msn.com']
        self.addlistlen = len(self.addlist)
        self.root = Tkinter.Tk()
        self.root.wm_title("Connection Speed")
        self.frame = Tkinter.Frame(self.root)
        self.frame.pack(side='top', expand=1, fill='both',)
        self.frame2 = Tkinter.Frame(self.frame)
        self.frame2.pack(side='bottom', expand=1, fill='both',)
        self.f = Figure(figsize=(5,4), dpi=100)
        self.a = self.f.add_subplot(111)
        self.gframe = Tkinter.Frame(self.frame)
        self.gframe.pack(side='top', expand=1, fill='both',)
        self.canvas = FigureCanvasTkAgg(self.f, master=self.gframe)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)
        self.lt = threading.Thread(target=self.loop())
    def getping(self, add):
            pingaling = os.popen("ping -n 2 "+str(add).strip())
            sys.stdout.flush()
            line = pingaling.read()
            if line:
                try:
                    line = line.split('Maximum = ')[1]
                    time = line.split('ms, Average')[0]
                    self.q.put(int(time))
                except:
                    self.q.put(None)
    def gpthread(self, *a):
        t = threading.Thread(target=self.getping, args=a)
        t.isDaemon = True
        t.start()
    def loop(self):
        while 1:
            for x in self.addlist:
                self.gpthread(x)
            while self.q.qsize<self.addlistlen:
                pass
            tl = []
            for u in range(self.addlistlen):
                temp = self.q.get()
                if temp != None:
                    tl.append(temp)
            if len(tl)>0:
                self.update(sum(tl)/len(tl))
            else:
                self.update(None)
    def update(self, val):
        self.a.clear()
        self.avvals.append(val)
        self.a.plot(self.avvals, linewidth=0.5, color = 'b')
        self.canvas.draw()
a = App()
try:
    a.root.mainloop()
except:
    a.root.destroy()

i probably dont need the bottom try..except but i put it in to check if it would make a difference.
i haven't had a chance to try it on another computer, but my other scripts are working fine so....
i simply can't comprehend why it freezes, stops responding, and if i exit it by any method i get a error saying
Fatal python error: PyEval NULL tstate
or somthing very similar.
now it doesn't even expand! it just goes straight to not responding!

A: Change
self.lt = threading.Thread(target=self.loop())

to
self.lt = threading.Thread(target=self.loop)

target=self.loop() calls the loop method before passing the result to threading.Thread.
Passing target=self.loop passes the method object to threading.Thread without calling it. This lets threading.Thread call the method in a new thread.

Here is some code which uses threads to ping some ips, and displays the average ping times in an animated matplotlib bar chart, embedded in a Tkinter window:
import Tkinter
import threading
import subprocess
import Queue
import shlex
import re
import matplotlib.pyplot as plt
import matplotlib.backends.backend_tkagg as tkagg
import atexit
import numpy as np

pingers=[]
def cleanup():
    print('terminating ping subprocesses...')
    for pinger in pingers:
        pinger.proc.terminate()
atexit.register(cleanup)

class Pinger(threading.Thread):
    def __init__(self,app,queue):
        threading.Thread.__init__(self)
        self.app=app
        self.queue=queue
    def run(self):
        # One ping subprocess is started by each Pinger thread.
        # The ping subprocess runs indefinitely, terminated by the cleanup function
        # which is called by atexit right before the main program terminates.
        ip = self.queue.get()
        cmd="ping %s" % ip
        self.proc = subprocess.Popen(shlex.split(cmd),
                                     stdout=subprocess.PIPE)
        for line in iter(self.proc.stdout.readline,''):
            match=re.search('time=(.*)\s+ms',line)
            if match:
                avg=float(match.group(1))
                self.app.update(ip,avg)

class App(object):
    def __init__(self,master,ips):
        self.ips=ips
        self.fig = plt.Figure(figsize=(5,4), dpi=100)
        self.fig.subplots_adjust(bottom=0.25)
        self.ax=self.fig.add_subplot(1,1,1)
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=master)
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        self.canvas.show()
        N=len(self.ips)
        self.idx=dict(zip(self.ips,range(N)))
        # I set an initial ping time of 200 just to make the initial bar chart
        times=[200]*N
        self.rects=self.ax.bar(range(N), times)
        self.ax.set_xticks(np.arange(N)+0.8*0.5)
        self.ax.set_xticklabels(self.ips, rotation=25)
    def update(self,ip,avg):
        # This is called by Pinger threads, each time a new ping value is obtained
        print(ip,avg)
        self.rects[self.idx[ip]].set_height(avg)
        self.canvas.draw()

def main():
    root = Tkinter.Tk()
    root.wm_title("Connection Speed")
    ips=['bbc.co.uk', 'google.co.uk', 'nhgs.co.uk', 'bing.co.uk', 'msn.com']
    app = App(root,ips)
    queue = Queue.Queue()
    for ip in ips:
        queue.put(ip)
        # This starts one Pinger for each ip.
        pinger=Pinger(app,queue)
        pingers.append(pinger)
        pinger.daemon=True
        pinger.start()
    Tkinter.mainloop()

if __name__=='__main__':
    main()


text:
Q: The value entered in Select_list is not stored in Browser variable I am entering the value in select list through below code
b.select_list(:id,'something').select('hi how are you')

And yes it's choosing as expected and it appears in the select list, but the value which is entered has not actually stored in the browser variable behind screen, So the wrong page arrives due to the missing value in select_list, But when I choose manually,it happening and the right page arrives. How would I rectify this error?
Code on the page look like this,

select  value="-1" origValue="-1"   tabindex="249" class="QuestionnaireSelect" name="nameid" id="2000007@2000064" style= ""
  onkeypress="onComboKeyPress(this)"  onchange="closeAfterUnload = false"  onmousedown="onFocusFieldHandler(this)"   helpTextInfo=""  onblur="releaseCurrentFocusField()"  onclick="closeAfterUnload = false"


text:
Q: Manually scale features after fitting StandardScaler to data I have scaled some training_data using Scikit Learns StandardScaler. Let's say I have stored this scaler in a variable called my_scaler.
Now I wanna use this my_scaler to scale some data I'll be getting from a form. However, I don't have access to my_scaler on the server that receives the form input.
So I'll need to somehow be able to export the parameters from my_scaler and then perform a manual scaling of the form data.
How can I do this?
I'm wondering both how I'd be able to export the parameters from my_scaler and how I'd use these parameters to perform a manual scaling on the data I'm getting from the form.
Any help is highly appreciated!


text:
Q: MySQL: SELECT and COUNT in same query I have these two tables:
CITY TABLE

CLUB TABLE

What I'm trying to do, is to select with the same query all cities that contain published clubs (published field set to 1) and the total of clubs published in that city.
At the moment, I am doing it with two steps, but I would like to improve performance by merging these in just one query.
SELECT c.id, c.name, c.slug
FROM city c, club cl
WHERE c.id = cl.city_id
AND ( SELECT COUNT(*)
      FROM club cl, city c
      WHERE cl.city_id = c.id AND cl.published = 1) > 0
GROUP BY c.id

After this, I'm doing a query for each city just to get the COUNT.

A: Something like this:-
SELECT city.id, city.name, city.slug, COUNT(club.id) AS club_count
FROM city
INNER JOIN club
ON city.id = club.city_id
WHERE club.published = 1
GROUP BY city.id, city.name, city.slug
HAVING club_count > 0


text:
Q: Database data not displaying on webpage I am trying to view data of a row in phpmyadmin.
I have a table of employees in my database. It is a leave management portal. I created a "view" button, so if an admin clicks on it, it should display the details of the employee and the leave requested/taken. But it doesn't seem to work.
Below is my code. I'm new to php

  First Name

    <?php echo htmlspecialchars($FirstName, ENT_QUOTES);  ?>

    Last Name

      <?php echo htmlspecialchars($LastName, ENT_QUOTES);  ?>

    Leave Type

      <?php echo htmlspecialchars($LeaveType, ENT_QUOTES);  ?>

    From Date

      <?php echo htmlspecialchars($FromDate, ENT_QUOTES);  ?>

    To Date

      <?php echo htmlspecialchars($ToDate, ENT_QUOTES);  ?>

    Description

      <?php echo htmlspecialchars($Description, ENT_QUOTES);  ?>

    Admin Remark

      <?php echo htmlspecialchars($AdminRemark, ENT_QUOTES);  ?>

    Admin Remark Date

      <?php echo htmlspecialchars($AdminRemarkDate, ENT_QUOTES);  ?>

    Status

      <?php echo htmlspecialchars($Status, ENT_QUOTES);  ?>

    Read

      <?php echo htmlspecialchars($IsRead, ENT_QUOTES);  ?>

    Back to Leave History

  <?php

    $id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');

    try {

        $query = "SELECT id, FirstName, LastName, LeaveType, FromDate, ToDate, Description, AdminRemark, AdminRemarkDate, Status, IsRead FROM tblleaves WHERE id = ? LIMIT 0,1";
        $stmt = $con->prepare( $query );
        $stmt->bindValue(1, $id, PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $FirstName = $row['FirstName
        $LastName = $row['LastName'];
        $LeaveType = $row['LeaveType'];
        $FromDate = $row['FromDate'];
        $ToDate = $row['ToDate'];
          $Description = $row['Description'];
        $AdminRemark = $row['AdminRemark'];
        $AdminRemarkDate = $row['AdminRemarkDate'];
        $Status = $row['Status'];
        $IsRead = $row['IsRead'];
    }
    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }
    ?>

A: You are querying the results and storing it in variables after your HTML. Since variables aren't set, HTML will not have those values and hence it's not printing any values.
Place query results on top and HTML at the bottom.


text:
Q: preg_replace words longer than x characters I need a preg_match pattern which got all strings longer than x characters. I need this for the following reason: The user uploads a pdf which is stored on my server. then the script reads the pdf and extracts cleartext (I need this for search functionality the database). This works not in all cases proper. Sometimes there are long patterns in this string. for example things like that:
PDF document properties Control PDF opening mode Can be configured to add
functionality to Acrobat Distiller Free: Creates PDFs without annoying watermarks Free: Fully functional, not a trial and d
oes not expire Over 5 million satisfied customers Over 1000 Enterprise Customers worldwide  Please visit us at www.pdf995.com to learn more.
 This document illustrates several features of the Pdf995 Suite of Products. APPROVEDShortlyaftertheGenevaBOFsession,the
www-vrmlmailinglistwascreatedtodiscussthedevelopmentofaspecificationforthefirstvers
ionofVRML.Theresponsetothelistinvitationwasoverwhelming:withinaweek,therewereov
erathousandmembers.Afteraninitialsettling-

For this reason I need to cut all strings longer than x (for example 30) characters, because this strings make no sense to store in the database.
My code line is this, but I appreciate help for the pattern (first var):
$result = preg_replace('\S{30,}', '', $result);

I took this because \S is for any non-whitespace character and {30,} for all stings longer than 30 characters.
Is this correct or is there a better way? It works, but I'm not sure if I'm on the right way.
Kind regards
IW


text:
Q: Extracting nested elements in column and storing into new columns I have some data that I want to expand into new columns. The data looks like:
    id  d
0   403 {'cases': 1, 'suspects': 22, 'negative': 0, 's', ...}
1   402 {'cases': 0, 'suspects': 18, 'negative': 0, 's', ...}
2   401 {'cases': 0, 'suspects': 31, 'negative': 0, 's', ...}

I am trying to get it such that the nested column d is spread out into new columns. I can get some of the data from d using:
rows = []
for i, row in myDF.iterrows():
    for stat in row['d']['stats']:
        new_row = {
            **row.to_dict(),
            **stat,
        }
        rows.append(new_row)

However I cannot get it all. How can I extract the objects such that I have a new column with the corresponding cases as the observations?
Expected Output (column names do not have to be exact):
cases   suspects   negative   diag_casesELISA_sex_F   diag_suspects_sex_M   diag_suspects_sex_F   diag_suspectsPCR_sex_F diag_suspectsPCR_sex_M
  1         22         0                1                      11                     10                   1                           NA
  0         18         0                NA                     9                       9                   NA                          NA
  0         31         0                NA                     12                     18                   NA                          1

Data:
myDF = pd.DataFrame.from_dict({'id': {0: '403', 1: '402', 2: '401'}, 'd': {0: {'cases': 1, 'suspects': 22, 'negative': 0, 'stats': [{'diag': 'casesELISA', 'sex': 'F', 'cases': 1}, {'diag': 'suspects', 'sex': 'M', 'cases': 11}, {'diag': 'suspects', 'sex': 'F', 'cases': 10}, {'diag': 'suspectsPCR', 'sex': 'F', 'cases': 1}]}, 1: {'cases': 0, 'suspects': 18, 'negative': 0, 'stats': [{'diag': 'suspects', 'sex': 'M', 'cases': 9}, {'diag': 'suspects', 'sex': 'F', 'cases': 9}]}, 2: {'cases': 0, 'suspects': 31, 'negative': 0, 'stats': [{'diag': 'suspects', 'sex': 'M', 'cases': 12}, {'diag': 'suspects', 'sex': 'F', 'cases': 18}, {'diag': 'suspectsPCR', 'sex': 'M', 'cases': 1}]}}})

A: You can write a custom function here and use pd.Series.apply.
def transform_dict(d):
    new = {}
    for k, v in d.items():
        if isinstance(v, list):
            for _dict in v:
                key = "_".join(
                    [key + "_" + val for key, val in _dict.items() if key != "cases"]
                )
                new[key] = _dict["cases"]
        else:
            new[k] = v
    return pd.Series(new)

out = df["d"].apply(transform_dict)

#out
   cases  suspects  negative  ...  diag_suspects_sex_F  diag_suspectsPCR_sex_F  diag_suspectsPCR_sex_M
0    1.0      22.0       0.0  ...                 10.0                     1.0                     NaN
1    0.0      18.0       0.0  ...                  9.0                     NaN                     NaN
2    0.0      31.0       0.0  ...                 18.0                     NaN                     1.0

#out.columns
Index(
    [
        "cases",
        "suspects",
        "negative",
        "diag_casesELISA_sex_F",
        "diag_suspects_sex_M",
        "diag_suspects_sex_F",
        "diag_suspectsPCR_sex_F",
        "diag_suspectsPCR_sex_M",
    ],
    dtype="object",
)
# out.values
array([[ 1., 22.,  0.,  1., 11., 10.,  1., nan],
       [ 0., 18.,  0., nan,  9.,  9., nan, nan],
       [ 0., 31.,  0., nan, 12., 18., nan,  1.]])

Explanation:
transform_dict(df['d'][0])

cases                      1
suspects                  22
negative                   0
diag_casesELISA_sex_F      1
diag_suspects_sex_M       11
diag_suspects_sex_F       10
diag_suspectsPCR_sex_F     1
dtype: int64

We are transforming every dict in column d to a Series.

A: Using apply
def parse_row_dfields(x):
    """
    use in apply axis such as x is a row
    """
    dico ={}
    d = x["d"]
    dico["id"] = x["id"]

    dico["cases"] = d["cases"]
    dico["suspects"]  = d["suspects"]
    dico["negative"] = d["negative"]
    stats_list  = d['stats']
    for dico_stat in stats_list:
        dico[dico_stat["diag"]+ "_" +dico_stat["sex"]] = dico_stat["cases"]
    return dico

x = myDF.apply(parse_row_dfields, axis=1)
pd.DataFrame.from_dict(dict(x)).T


text:
Q: Python procedure that uses another procedure returns none I very new with python and I'm doing an online class to learn the basics. While everything is going well, there are still a things that I don't seem to grasp in python..
Even though I found a much simpler way to solve the bellow problem, I'd still like to understand why my procedure is returning "None" .. Is it mistake with my if statements ? a syntax error ?
Here is the problem:
Define a procedure, union, that takes as inputs two lists.
It should modify the first input list to be the set union of the two lists. You may assume the first list is a set, that is, it contains no repeated elements.
The result we are expecting:
a = [1,2,3]
b = [2,4,6]

union(a,b)
print a
#>>> [1,2,3,4,6]

You will note that, in my procedure, I'm using another procedure to find if a list item is in the other list. Could the problem be coming from that ?
Here is my code:
def find_element(a,b):
    if b in a:
        return a.index(b)
    return - 1

 def union(a,b):
        i = 0
        while i < len(b) - 1:
            c = find_element(a,b[i])

            if c != -1:
                i = i + 1
            if c == -1:
                a = a.append(b[i])
                i = i + 1
        return a

    a = [1,2,3]
    b = [2,4,6]

    print(union(a,b))

A: a = a.append(b[i])

Here, a.append(b[i]) appends b[i] to a and returns 'none' which you have assigned to 'a'.
change this to
a.append(b[i])

and you should atleast get an output.

A: just in case you may need it.
you code could will be easier to read if you have it like this.
but its nice to challenge yourself.
best,
def union(a, b):
    for item in b:
         if item not in a:
             a.append(item)
    return a

a = [1, 2, 3]
b = [2, 4, 6]
x = union(a, b)
print(x)


text:
Q: C++ - writing a scheduler with std::difftime - how to check for a time (HH:MM:SS) occurence during the day? I try to have my program figure if an event is getting reached during the day
for instance, I want to be able to create events at 10:00:00 so that a task gets executed at that moment in the day (only once)
so I have this function that can tell the time has passed, but it will always return true after 10:00 (time parameter)
bool Tools::passedTimeToday(std::time_t time)
{
    auto now = std::chrono::system_clock::now();
    std::time_t _now = std::chrono::system_clock::to_time_t(now);
    if (std::difftime(_now,time)<0)
        return false;
    else
        return true;
}

how do I check the time has passed only once ?
do I use some sort of epsilon around that time ? what value shoud I use for that epsilon ?
    double delta = std::difftime(_now,time);
    if ( (delta<0) && (delta>-epsilon) )
    {
        ...

I mean it could work, but what if my program tests that condition too late (bigger than epsilon) ?
I thought about using a boolean flag instead (bool processed), but then evey time I run the program, it would also run all tasks that happened around that time
any help appreciated
thanks

A: *

*Create a list with the scheduled tasks and their next run time sorted by the next run time.

*When the current time is after the next run time of the first task in the list, remove it from the list, execute the task and then add it back to the list with the run time incremented by a day (or whatever repetition period you need).

*Go to step 2 unless the list is empty.

A: Here is my way of doing it
I only admit  tasks within a 5 seconds period
bool Tools::passedTimeToday(std::time_t time)
{
    auto now = std::chrono::system_clock::now();
    std::time_t _now = std::chrono::system_clock::to_time_t(now);
    double delta = std::difftime(_now,time);

    if ( (delta>0) && (delta<5) )
        return true;
    else
        return false;
}


text:
Q: Stuck in finding an alternative to finding the hypotenuse of a right triangle (using Dickson's method) I was trying an alternative to finding the hypotenuse of a right triangle using simple algebra and Dickson's model of a right triangle. I have a problem:
Given $r + t$ and $r + s$, how do you find $s + t$? I tried the following method:
Subtract $r + t$ from $r + s$.
Obtain $s - t$.
Here I'm stuck. How do we find $s + t$? If we find $s + t$, we will have the following:
$$(r + t + r + s + s + t) = 2r + 2s + 2t.$$
On dividing by $2$, we obtain the hypotenuse of the triangle. An alternative to this is finding $r - t$. If know $r - t$, we can find $s + t$ and follow the above procedure.
In trying more to research about it, I came across a new relation which may help you:
$s + t = √(r^2+s^2+t^2)$
To find the value (numerical) of $s+t$, can we arrive at this relation?
So the question is: Is it possible to find $s + t$ or $r - t$? If so, how, or is it impossible?
Thanks,
S Sandeep

A: Have a look at this Wikipedia link.
Let $x = r + s, y = r + t, z = r + s + t$.  Then, by the Pythagorean theorem:
$$x^2 + y^2 = (r + s)^2 + (r + t)^2 = (r + s + t)^2 = z^2.$$
But:
$$(r + s)^2 + (r + t)^2 = 2{r^2} + 2rs + s^2 + 2rt + t^2$$
while
$$(r + s + t)^2 = r^2 + s^2 + t^2 + 2rs + 2st + 2rt$$
so that
$$r^2 = 2st.$$
Therefore, $r = \pm\sqrt{2st}$.
Consequently, $r - t = \pm\sqrt{2st} - t$.
Can you take it from here?


text:
Q: React vs GWT for large scale web application As Java developer, I always felt comfortable developing web applications using GWT, but every now and then I am trying to check if there is a better framework that I can use for developing a large scale web application.
I tried out React, and I liked it, but as a Java developer I am not feeling as comfortable developing using JS, and I am scared that when the project will become really big I will have troubles maintaining it, and I will get "spaghetti code".
Basically I wanted to know what are the benefits of React over GWT? and am I right to be scared of big scale projects developed in JS?

A: Now you could try VueGWT: Github project
The idea is to write your control in Java and your views with vueJS templates. We have started (only a few part for now) to use it for GenMyModel, a very big GWT application.

A: I'm a java born developper who now works in react-redux and miss the object language. If you try to develop a real good application you will have to add redux to react but its pattern is quite weird and not well documented.
If you feel more comfortable with Java than JS you should use GWT. It's true that ag-grid with infinite loading for example, may not exist in GWT for the moment but you have Google support. If you want the latest amazing widgets (the react virtualized select is another example) for your app and you really need them you will have to document yourself about these (with lacks of documentation) and use react.