text:
Q: Companion to hypot() The hypot function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
double hypot(double a, double b)
{
  return sqrt(a*a + b*b);
}

I find myself with the need for companion functionality: given a side and the hypotenuse of a triangle, find the third side (avoiding under/overflow).  I can think of a few ways to do this, but wondered if there was an existing "best practice"?
My target is Python, but really I'm looking for algorithm pointers.

Thanks for the replies. In case anyone is interested in the result, my C99 implementation can be found here and a Python version here, part of the Hypothesis project.

A: The first thing to do is factorize:
b = sqrt(h*h - a*a) = sqrt((h-a)*(h+a))

We have not only avoided some overflow, but also gained accuracy.

If any factor is close to 1E+154 = sqrt(1E+308) (max with IEEE 754 64 bits float) then we must also avoid overflow:
sqrt((h-a)*(h+a)) = sqrt(h-a) * sqrt(h+a)

This case is very unlikely, so the two sqrt's are justified, even if its slower than just a sqrt.
Notice that if h ~ 5E+7 * a then h ~ b which means that there are not enough digits to represent b as different from h.

A: This answer assumes a platform that uses floating-point arithmetic compliant with IEEE-754 (2008) and provides fused multiply-add (FMA) capability. Both conditions are met by common architectures such as x86-64, ARM64, and Power. FMA is exposed in ISO C99 and later C standards as a standard math function fma(). On hardware that does not provide an FMA instruction, this requires emulation, which could be slow and functionally deficient.
Mathematically, the length of one leg (cathetus) in a right triangle, given the length of the hypotenuse and the other leg, is simply computed as √(h²-a²), where h is the length of the hypotenuse. But when computed with finite-precision floating-point arithmetic, we face two problems: Overflow or underflow to zero may take place when computing the squares, and subtraction of the squares gives rise to subtractive cancellation when the squares have similar magnitude.
The first issue is easily taken care of by scaling by 2n such that the term larger in magnitude is moved closer to unity. As subnormal numbers may be involved, this cannot be accomplished by manipulating the exponent field, as there may be a need to normalize / denormalize. But we can compute the required scale factors by exponent field bit manipulation, the multiply by the factors. We know that the hypotenuse has to be longer or the same length as the given leg for non-exceptional cases, so can base the scaling on that argument.
Dealing with subtractive cancellation is harder, but we are lucky that computation very similar to our computation h²-a² occurs in other important problems. For example, the grandmaster of floating-point computation looked into the accurate computation of the discriminant of the quadratic formula, b²-4ac:
William Kahan, "On the Cost of Floating-Point Computation Without Extra-Precise Arithmetic", Nov. 21, 2004 (online)
More recently, French researchers addressed the more general case of the difference of two products, ad-bc:
Claude-Pierre Jeannerod, Nicolas Louvet, Jean-Michel Muller, "Further analysis of Kahan's algorithm for the accurate computation of 2 x 2 determinants." Mathematics of Computation, Vol. 82, No. 284, Oct. 2013, pp. 2245-2264 (online)
The FMA-based algorithm in the second paper computes the difference of two products with a proven maximum error of 1.5 ulp. With this building block, we arrive at the straightforward ISO C99 implementation of the cathetus computation below. A maximum error of 1.2 ulp was observed in one billion random trials as determined by comparing with the results from an arbitrary-precision library:
#include <stdint.h>
#include <string.h>
#include <float.h>
#include <math.h>

uint64_t __double_as_uint64 (double a)
{
    uint64_t r;
    memcpy (&r, &a, sizeof r);
    return r;
}

double __uint64_as_double (uint64_t a)
{
    double r;
    memcpy (&r, &a, sizeof r);
    return r;
}

/*
  diff_of_products() computes a*b-c*d with a maximum error < 1.5 ulp

  Claude-Pierre Jeannerod, Nicolas Louvet, and Jean-Michel Muller,
  "Further Analysis of Kahan's Algorithm for the Accurate Computation
  of 2x2 Determinants". Mathematics of Computation, Vol. 82, No. 284,
  Oct. 2013, pp. 2245-2264
*/
double diff_of_products (double a, double b, double c, double d)
{
    double w = d * c;
    double e = fma (-d, c, w);
    double f = fma (a, b, -w);
    return f + e;
}

/* compute sqrt (h*h - a*a) accurately, avoiding spurious overflow */
double my_cathetus (double h, double a)
{
    double fh, fa, res, scale_in, scale_out, d, s;
    uint64_t expo;

    fh = fabs (h);
    fa = fabs (a);

    /* compute scale factors */
    expo = __double_as_uint64 (fh) & 0xff80000000000000ULL;
    scale_in = __uint64_as_double (0x7fc0000000000000ULL - expo);
    scale_out = __uint64_as_double (expo + 0x0020000000000000ULL);

    /* scale fh towards unity */
    fh = fh * scale_in;
    fa = fa * scale_in;

    /* compute sqrt of difference of scaled arguments, avoiding overflow */
    d = diff_of_products (fh, fh, fa, fa);
    s = sqrt (d);

    /* reverse previous scaling */
    res = s * scale_out;

    /* handle special arguments */
    if (isnan (h) || isnan (a)) {
        res = h + a;
    }

    return res;
}

A: Assuming IEEE 754 basic 64-bit binary floating-point, I would consider an algorithm such as:

*

*Set s (for scale) to be 2−512 if 2100 ≤ a, 2+512 if a < 2−100, and 1 otherwise.

*Let a' be a•s and b' be b•s.

*Compute sqrt(a'•a' − b'•b') / s.

Notes about the reasoning:

*

*If a is large (or small), multiplying by s decreases (or increases) the values so that the square of a' remains in the floating-point range.

*The scale factor is a power of two, so multiplying and dividing by it is exact in binary floating-point.

*b is necessarily smaller than (or equal to) a, or else we return NaN, which is appropriate. In the case where we are increasing a, no error occurs; b' and b'•b' remain within range. In the case where we are decreasing a, b' may lose precision or become zero if b is small, but then b is so much smaller than a that the computed result cannot depend on the precise value of b in any case.

*I partitioned the floating-point range into three intervals because two will not suffice. For example, if you set s to be 2−512 if 1 ≤ a and 2+512 otherwise, then 1 will scale to 2−512 and then square to 2−1024, at which point a b slightly under 1 will be losing precision relevant to the result. But if you use a less-magnitude power for s, such as 2−511, then 21023 will scale to 2512 and square to 21024, which is out of bounds. Therefore, we need different scale factors for a = 1 and a = 21023. Similarly, a = 2−1049 needs a scale factor that would be too large for a = 1. So three are needed.

*Division is notoriously slow, so one might want to multiply by a prepared s−1 rather than dividing by s.

A: hypot has its idiosyncrasies in that it's one of a very select few C standard library functions that does not propagate NaN! (Another one is pow for the case where the first argument being 1.)
Setting that aside, I'd be inclined to write merely
returns sqrt(h * h - a * a); // h is the hypotenuse

as the body of the function, and burden the caller with checking the inputs. If you can't do that then follow the specification of hypot faithfully.


text:
Q: How to draw evenly spaced diagonal text with wpf xaml I am doing a custom WPF UserControl and i need to draw a variable size text that is rotated 45 degrees and spaced evenly horizontally, like the next image (being the red bars the text):

With the following code:
    <UserControl.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="CheckTemplate">

                <!-- description -->
                <TextBlock
                    VerticalAlignment="Bottom" Margin="-10,0,0,0" Text="{Binding Check.Name}" Background="Transparent" x:Name="AAA">
                    <TextBlock.LayoutTransform>
                        <RotateTransform Angle="-45" />
                    </TextBlock.LayoutTransform>
                </TextBlock>

            <DataTemplate.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Margin" Value="0" TargetName="AAA" />
                </Trigger>
            </DataTemplate.Triggers>

        </DataTemplate>

        <ItemsPanelTemplate x:Key="ChecksItemsPanel">
            <StackPanel Orientation="Horizontal"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Bottom"
                        />
        </ItemsPanelTemplate>
    </ResourceDictionary>
</UserControl.Resources>

    <StackPanel x:Name="RootPanel" Margin="5">

    <ItemsControl
        x:Name="WorkflowChecksItemsControl"
        ItemTemplate="{DynamicResource CheckTemplate}"
        ItemsPanel="{DynamicResource ChecksItemsPanel}"
        ItemsSource="{Binding WorkflowChecks}" />

</StackPanel>

i only managed to do something like this:

How can i do this using XAML?
In this project i am also using Telerik UI for WPF, and i can use theirs framework if it is simpler.

A: You may combine a -90° LayoutTransform of the ItemsPanel with a 45° RenderTransform of each TextBlock. For the horizontal distance, simply set the  TextBlocks' Height.
<ItemsControl ItemsSource="{Binding WorkflowChecks}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel>
                <StackPanel.LayoutTransform>
                    <RotateTransform Angle="-90"/>
                </StackPanel.LayoutTransform>
            </StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Check.Name}" RenderTransformOrigin="0,1">
                <TextBlock.RenderTransform>
                    <RotateTransform Angle="45"/>
                </TextBlock.RenderTransform>
            </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Result:

redpajama_set_name: RedPajamaStackExchange


text:
Q: awk what is wrong with my syntax? awk 'if(NF==7){print$1":"$2":"$4":"$5, $7, $6}else {print$1":"$2":"$3":"$4, $6, $5}'
awk: if(NF==7){print$1":"$2":"$4":"$5, $7, $6}else {print$1":"$2":"$3":"$4, $6, $5}
awk: ^ syntax error

What is the syntax error here? the arrow points to the if

A: awk is a series of condition {action} statements.
if is not valid condition. You need to enclose that in an action block:
awk '{if(something) { do something } else { do something else }}'

Alternatively, you can leave off the if for the conditions of NF==7 for example:
awk 'NF==7{ do something; next } { do something else }'

The second is more idiomatic awk for testing NF, other built-in variables or other variables in general.

A: Rewrite your code as:
awk '{print $1":"$2":" (NF==7 ? $4":"$5, $7, $6 : $3":"$4, $6, $5)}'

and start reading Effective Awk Programming, 4th Edition, by Arnold Robbins.


text:
Q: PIG output query for selecting particular value based on groupby clause I have a table with data like:
cust_id, acct_no, ind
123111,  1233,     Y
123111,  2311,     N
222111,  1112,     N
222111,  2111,     N

I have to get output as cust_id, 1 (a binary indicator if any of the acct under that customer is Y)
so from the above table I have to get below output.
123111    1
222111    0

A: Load data and foreach row check whether the ind value is 'Y' then return 1 for that row else return 0.Finally distinct the rows.
EDIT:
--A = LOAD 'data.txt' USING PigStorage(',') as (cust_id:int,acct_no:int,ind:chararray);
-- Note: I am only loading two columns

A = LOAD 'data.txt' USING PigStorage(',') AS (id:int,ind:chararray);
B1 = FILTER A BY (ind == 'Y');
B2 = FILTER A BY (ind == 'N');
B3 = DISTINCT B2;
C = JOIN B3 BY id LEFT OUTER,B1 by id;
D = FOREACH C GENERATE B3::id as id,(B1::ind== 'Y'? 1 : 0) as ind;
E = FOREACH D GENERATE id,((ind IS NULL) ? 0 : ind);
DUMP E;

OUTPUT

Here is an example with a larger dataset
INPUT
123111,Y
123111,N
222111,N
222111,N
333111,Y
333111,N
444111,Y
444111,N
555111,N
555111,N

OUTPUT


text:
Q: iOS: How to clean data before app crash I am downloading data in background.
So if user press home button and force quit app by double click on the app icon, then I need some data cleaning.
I try to do data cleaning in the delegate method applicationWillTerminate but app did not call this method while crashes.
I can not do data cleaning in applicationDidEnterBackground as my app keeps data downloading in background. I search many hours.. but I am clueless about this.
Can anyone tell me, Is there any way to call method(to clean data) before app  crashes.
Thanks!

A: You can't clean up data if your app crashes or is forcefully quit.
You can instead clean the data the next time it's being opened. Depending on what you're doing, you could use a flag inside NSUserDefaults that will let you know if data needs to be cleaned or not.
For instance, when the download starts, you can set:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"pendingDownload"];
[[NSUserDefaults standardUserDefaults] synchronize];

When download finishes:
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pendingDownload"];
[[NSUserDefaults standardUserDefaults] synchronize];

Inside didFinishLaunchingWithOptions:
if([[[NSUserDefaults standardUserDefaults] objectForKey:@"pendingDownload"] boolValue]){
    // clean data
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pendingDownload"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


text:
Q: c++ Multiple inheritance from 2 functions, while one of them is pure virtual Let's say we have a class which inherits from 2 other classes which have both a virtual function with the same signature.
Because the signature is the same, there will be an error because the main class doesn't know who to inherit the virtual function from.
adding to that, if a function is pure virtual, it needs to be initialized in the main class.
So my question is, if the main class inherits from 2 classes with same virtual function but one of them is a pure virtual, will it just use the second one?
Or something else needs to be done?
Btw, if possible, I'd like to see the code you wrote to answer this.
Thanks :)

A:
if the main class inherits from 2 classes with same virtual function but one of them is a pure virtual, will it just use the second one?

No.  C++ will not assume that you want that behavior.

Or something else needs to be done?

You must implement the function if you don't want the derived class to be abstract.
void Derived::func()
{
    SomeBase::func();
}


text:
Q: How to change styles of one element in a array in LWC I want to change styles of one element that I received from an API, when I render it, I need to change styles for example of the second element displayed, like a font-size bigger or italic etc, any idea that how can I implement this?, I supponse to use the index but I new in salesforce, any idea welcome.
API = {
 data : [
   info_1 : {
              v1= 'v1v1v1',
              v2= 'v2v2v2',
              v3= 'v3v3v3'
            },
   info_2 : {
              v1='aaaa',
              v2='bbbb',
              v3='cccc'
            },

        ]
}

in HTML LWC I render this
  <Template for:each={data} for:item='item' for:index='index'>

{index}
{item.info_1}=

{item.info_2}

  </Template>

Result output would be:
             0 v1v1v1 =  aaaa
             1 v2v2v2 =  bbbb   ---> I need to give style to this element!!
             2 v3v3v3 =  cccc

JS:
I will try this but doesn't work
@api index;
get tiTleClass (){
return this.index == 1 ? 'slds-text-heading_large' : 'slds-text-heading_small';
}


text:
Q: exec() throws Errno::EBADF with ruby 2.1.1 The code below works fine in Ruby 1.9.3 but throws a Bad file descriptor exception with Ruby 2.1.1 (even with close_on_exec set to false).
#!/usr/bin/env ruby

if ARGV.empty?
    f = open("/dev/null")
    f.close_on_exec = false if respond_to?(:close_on_exec=)
else
    f = IO.for_fd(ARGV[0].to_i)
    exit
end

exec "./client.rb", f.fileno.to_s

Output:
./client.rb:7:in `for_fd': Bad file descriptor (Errno::EBADF)
from ./client.rb:7:in `<main>'

Has anything else, besides close_on_exec, changed that I'm missing?

A: Passing :close_others => false as options in addition to setting close_on_exec = false solves it. E.g.
exec "./client.rb", f.fileno.to_s, :close_others => false


text:
Q: Is there a mobile Safari fullscreen Javascript event? I can't even find people asking questions about this, which is baffling to me.
Does mobile Safari fire a Javascript event when the user enters fullscreen mode (iOS 6)? I am currently resizing my document onorientationchange and need to do so in full screen mode as well, but can't find ANYTHING about this.

A: Well, this might explain why no one is asking about it:
window.onresize. Duh!


text:
Q: knowing timezones native offset (when DST is not active) in php I want to list for the user, all timezones with their native UTC/GMT offset, regardless of DST
How can I do it?

A: I 've come up with this function to do the job:
function standard_tz_offset($timezone) {
    $now = new DateTime('now', $timezone);
    $year = $now->format('Y');

    $startOfYear = new DateTime('1/1/'.$year, $timezone);
    $startOfNext = new DateTime('1/1/'.($year + 1), $timezone);

    $transitions = $timezone->getTransitions($startOfYear->getTimestamp(),
                                             $startOfNext->getTimestamp());
    foreach($transitions as $transition) {
        if(!$transition['isdst']) {
            return $transition['offset'];
        }
    }

    return false;
}

How it works
The function accepts a timezone and creates two DateTime objects: January 1st 00:00 of the current year and January 1st 00:00 of the next year, both specified in that timezone.
It then calculates the DST transitions during this year, and returns the offset for the first transition it finds where DST is not active.
PHP 5.3 is required because of the call to DateTimeZone::getTransitions with three parameters. If you want this to work in earlier versions you will have to accept a performance hit, because a whole lot of transitions will be generated by PHP (in this case, you don't need to bother with creating the $startOfYear and $startOfNext dates).
I have also tested this with timezones that do not observe DST (e.g. Asia/Calcutta) and it works for those as well.
To test it:
$timezone = new DateTimeZone("Europe/Athens");
echo standard_tz_offset($timezone);


text:
Q: Extracting certain substring from a string I want to extract the last part of this string : "https://steamcommunity.com/profiles/76561198364464404".Just the numbers after '/profiles'.But the problem is the URL can change sometimes.
There are two types of url
1.First one is "https://steamcommunity.com/profiles/76561198364464404" with "/profiles" and then the "id"(id is the numbers after '/profiles').
2."https://steamcommunity.com/id/purotexnuk".Second is this type.Where "/profiles" doesn't exist.
I have come up this code :
let inc;
const index = 27;
const string = 'https://steamcommunity.com/id/purotexnuk';
if (string.includes('profiles')) {
    inc = 9;
} else {
    inc = 3;
}

console.log(string.slice(index + inc, -1));

The above code checks wheather the string "/profiles" is present.If the string contains "/profiles".inc will be 9.So that slice starts from the right side of the string(url) and ends at the first '/' from the right.inc is 9 becuase "profiles/" length is 9.Similar way if the string(url) contains "id".The slice will start from the end and stop at the first '/' from the right.inc will be 3 becuase "id/" length is 3.
The index is always constant because ,"/profiles" or "/id" only occurs after "https://steamcommunity.com" whose length is 27.Is there any better way i can extract only the profile id or profile name?
(profile id - 76561198364464404)
(profile name - purotexnuk )

A: You can split the string with delimiter / and return the last value value from the array;

function getNum(str) {
  const arr = str.split('/');
  if (!isNaN(arr[arr.length - 1])) {
    return arr[arr.length - 1];
  }
  return ' no number ';
}

const st1 = "https://steamcommunity.com/profiles/76561198364464404";
const st2 = "https://steamcommunity.com/profiles/76561198364464404";
const st3 = "https://steamcommunity.com/id/purotexnuk";

console.log(getNum(st1));
console.log(getNum(st2));
console.log(getNum(st3));

A: You can use regex for this, it will also take care if your url ends with / or has query parameters example https://steamcommunity.com/id/purotexnuk?ref=abc
/.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i

example:

const regex = /.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i;
const matches = regex.exec('https://steamcommunity.com/id/purotexnuk');
console.log(matches[1]);

A: Or do it in one line:

const string = 'https://steamcommunity.com/id/purotexnuk';
console.log(string.slice(string.lastIndexOf("/") + 1, string.length));


text:
Q: Rounding an integer fraction with maximum error I am currently working on a fraction datatype that is written in C#10 (.NET 6).
It is based on two BigIntegers in the Numerator and Denominator, which means that this fraction basically has infinite precision.
The only problem that now arises is memory consumption.
The Numerator and Denominator both get really big quickly, especially when roots are calculated using Newton's method.
An example for this using Newton's method to calculate the square root of 1/16:
x_0 = 1/16
x_1 = 17/32
x_2 = 353/1088
x_3 = 198593/768128
x_4 = 76315468673/305089687808
x_5 = 11641533109203575871233/46566125024733548077568 (≈0.2500000398)

The results get accurate quickly but the "size" of the fraction almost doubles every iteration.
When more precise results are required, the memory usage is just way too high.
A solution to this problem is rounding.
I want the user to be able to set a maximum error which the rounded fraction should be in.
My approach was using Euclid's GCD algorithm but modified for this max error clause:
public static Fraction Round(Fraction a, Fraction error)
{
    BigInteger gcd = GCD(Math.Max(a.numerator, a.denominator), Math.Min(a.numerator, a.denominator), error);
    return new Fraction(){ numerator = RoundedDivision(a.numerator, gcd), denominator = RoundedDivision(a.denominator, gcd) };
}

public static BigInteger GCD(BigInteger a, BigInteger b, BigFraction maxError) =>
    new Fraction(){ numerator = BigInteger.Abs(b), denominator = 1 } <= maxError ? a : GCD(b, a % b, maxError * a);

// Rounds an integer division: 0.5 -> 1; -0.5 -> -1
public static BigInteger RoundedDivision(BigInteger a, BigInteger b) => (a*2 + a.Sign * b.Sign * b) / (2*b);

The results looked promising at first, but i ran into cases where the rounded result was outside the specified error.
An example for this using pseudo-code:
value = 878/399 (≈2.12531; value is represented as a fraction of two integers, not the division result)
error = 1/8 (=0.125)
Round(value, error) = Round(878/399, 1/8) = 2 (=2/1)

2 is outside of the specified max error by ~0.00031 (878/399 - 1/8 ≈ 2.00031  => 2 shouldn't be possible).
Correct results would be eg. 2.125 or 2.25, because these values lie in the range of 878/399 ± 1/8.
Does someone know why this is happening and how can i fix this?
EDIT: The result of the rounding should still be a fraction.


text:
Q: Bash script escaping quotes I'm writing a bash script to find all the images in the folder and find if they have corrupt endings with ImageMagick.
This is the command I'm trying to automate:
identify -verbose *.jpg 2>&1 | grep "Corrupt" | egrep -o "([\`].*[\'])"

The issue I'm having is with storing the identify command into a variable.
There are multiple types of quotes that are present in the command I keep getting an error line 8: corrupt: command not found
#!/bin/bash
# This script will search for all images that are broken and put them into a text file

FILES="*.jpg"

for f in $FILES
do
  corrupt = "identify -verbose \"$f\" 2>&1 | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\""

  if [ -z "$corrupt" ]
  then
    echo $corrupt
  else
    echo  "not corrupt"
  fi
done

Is there a way to escape that command correctly?
UPDATE:
Some progress:
#!/bin/bash
# This script will search for all images that are broken and put them into a text file

FILES="*.jpg"

for f in $FILES
do
  echo "Processing $f"
  corrupt="identify -verbose $f 2>&1 | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\""

  if [ -z "$corrupt" ]
  then
    echo $corrupt
  else
    echo  "not corrupt"
  fi

done

This no longer throws an error, but it looks like it just stores the variable as a string.
How can I run this command?
UPDATE: Some progress. Now the command is running:
#!/bin/bash
# This script will search for all images that are broken and put them into a text file

FILES="*.jpg"

for f in $FILES
do
  echo "Processing $f"

  corrupt=`identify -verbose $f | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\"`

  $corrupt

  if [ -z "$corrupt" ]
  then
    echo $corrupt
  else
    echo  "not corrupt"
  fi

done

But the output of pipes is separate:
Processing sdfsd.jpg
identify-im6.q16: Premature end of JPEG file `sdfsd.jpg' @ warning/jpeg.c/JPEGWarningHandler/387.
identify-im6.q16: Corrupt JPEG data: premature end of data segment `sdfsd.jpg' @ warning/jpeg.c/JPEGWarningHandler/387.

I just need the final `sdfsd.jpg' string.

A: What you are probably looking for is a way of identifying corrupt images.  It's easy to query the identify tool for its exit-status to see whether it managed to identify the image file or not.
#!/bin/sh

for name in *.jpg; do
    if identify -regard-warnings -- "$name" >/dev/null 2>&1; then
        printf 'Ok: %s\n' "$name"
    else
        printf 'Corrupt: %s\n' "$name"
    fi
done

The above uses the exit-status of identify to determine whether the file was corrupt or not. The -regard-warnings option escalates the warnings you mention into errors turn, which makes them affect the exit-status of the utility.
You very seldom need to store actual globbing patterns in variables. You can often get a utility's success/failure status by testing its exit-status like what we show above without parsing the tool's output.
For older ImageMagick releases (I'm using 6.9.12.19), use convert instead of identify.
#!/bin/sh

for name in *.jpg; do
    if convert -regard-warnings -- "$name" - >/dev/null 2>&1; then
        printf 'Ok: %s\n' "$name"
    else
        printf 'Corrupt: %s\n' "$name"
    fi
done

The above loop tries to convert each image, and if it fails to process an image file, it is detected by the if statement.  We discard the result of the conversion operation.


text:
Q: Pipe Translater in Html Element So, dont know if anyone can help me. I have the below line of code in html :
<ion-item class="item-style">
  <ion-label>{{ 'SettingsPage.ChangeLanguage' | translate }}</ion-label>
  <ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{cancelText}} okText={{okText}}>
    <ion-select-option value="en">{{ 'SettingsPage.English' | translate }}</ion-select-option>
    <ion-select-option value="mt">{{ 'SettingsPage.Maltese' | translate }}</ion-select-option>
  </ion-select>
</ion-item>

and the following methods in the .ts :
 onLanguageChange() {
this.translate.use(this.language);
console.log(this.language);
this.globalVariableService.languageChanged = true;
this.globalVariableService.setCurrentLanguage(this.language);
this.storage.set('Language', this.language).then(() => {
  this.sectorDataServiceProvider.populateSectorData().then(data => {
    console.log('this.sectorInfo ', this.sectorDataServiceProvider.sectorInfo);
  });
});
this.setOkAndCancelText();

}
setOkAndCancelText() {
    if (this.language === 'en') {
      this.cancelText = 'Cancel';
      this.okText = 'OK';
    } else if (this.language === 'mt') {
      this.cancelText = 'Le';
      this.okText = 'Iva';
    }
  }

I wish to remove the s setOkAndCancelText() which is being used to fill the cancelText={{cancelText}} parameter when the language changes within the app, and have something similar to:
<p [innerHTML]="'TermsOfUsePage.Header' | translate"></p>

Any ideas how i can make this possible please?

A: Instead of reliaing on libraries, you can create your custom service and add your local strings i.e key and value as following:
@Injectable({
    providedIn: 'root'
})
export class LocalizationService {
    localizedStrings: any;

    constructor() {
        this.localizedStrings = {
            en: {
                SettingsPage: {
                    cancelText: 'Cancel'
                }
            },
            mt: {
                SettingsPage: {
                    cancelText: 'Le'
                }
            }
        }
    }

    getResource(keyString: string, workingLanguage: string): Promise<string> {
        return new Promise((resolve, reject) => {
            let resourceValue = null;
            if(this.localizedStrings[workingLanguage].hasOwnProperty(keyString)) {
                resourceValue = this.localizedStrings[workingLanguage][keyString];
            } else {
                resourceValue = this.getPropertyByKeyPath(this.localizedStrings[workingLanguage], keyString);
                // if(!resourceValue) {
                //     debugger;
                // }
            }

            if(resourceValue) {
                resolve(resourceValue);
            } else {
                resolve(keyString);
            }
        });
    }

    private getPropertyByKeyPath(targetObj, keyPath) {
        var keys = keyPath.split('.');
        if(keys.length == 0) return undefined;

        keys = keys.reverse();
        var subObject = targetObj;
        while(keys.length) {
            var k = keys.pop();
            if(!subObject.hasOwnProperty(k)) {
                return undefined;
            } else {
                subObject = subObject[k];
            }
        }
        return subObject;
    }
}

Note that it is flexible, you can go deeper in objects. Now simply create a pipe for this service:
import { Pipe } from '@angular/core';

import { LocalizationService } from '../shared/localization.service';

    @Pipe({
      name:"translate"
    })
    export class LocalizedResourcePipe {
        constructor(private localizationService: LocalizationService) {

        }

        transform(resourceKey: string, workingLanguage: string) {
            return new Promise((resolve, reject) => {
                if(!resourceKey) {
                    resolve();
                } else {
                    this.localizationService.getResource(resourceKey, workingLanguage)
                    .then((value) => {
                        resolve(value);
                    });
                }
            });
        }
    }

Now simply call it in your HTML:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'SettingsPage.cancelText' | translate: 'en' | async}} okText={{'SettingsPage.cancelText' | translate: 'en' | async}}>

You can could make the the language parameter dynamic as well and in pipe, give it a default value. anyway here is the way to call it for your other language:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'SettingsPage.cancelText' | translate: 'mt' | async}} okText={{'SettingsPage.cancelText' | translate: 'mt' | async}}>

A: We have done it in following ways:

*

*Installed the following packages:

"@ngx-translate/core": "11.0.1"
"@ngx-translate/http-loader": "4.0.0",

*

*In app.module.js, add the following in imports:

 TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: AppHttpLoaderFactory,
            deps: [HttpClient]
          }
        }),

export function AppHttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, Environment.frontend('/assets/i18n/'), '.json');
}

Here we have kept our en.json file under i18n folder where all key values of text are there.
After this you can use it in html template:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'cancel.text' | translate }} okText={{okText}/>

Here cancel.text is a key in en.json file.

A: Try this stackblitz example
Translate Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class TranslateService {
  data: any = {};

  constructor(private http: HttpClient) { }

  use(lang: string): Promise<{}> {
    return new Promise<{}>((resolve, reject) => {
      const langPath = `assets/languageFiles/${lang || 'en'}.json`;
      this.http.get<{}>(langPath).subscribe(
        translation => {
          this.data = Object.assign({}, translation || {});
          resolve(this.data);
        },
        error => {
          this.data = {};
          resolve(this.data);
        }
      );
    });
  }
}

Translate Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from './translate.service';

@Pipe({
  name: 'translate',
  pure:false
})
export class TranslatePipe implements PipeTransform {

  constructor(private translate: TranslateService) {}
  transform(key: any): any {
    return this.translate.data[key] || key;
  }

}


text:
Q: How to set the version of Ruby with rbenv on MacOS? I was trying to follow the book "Agile Web Development with Rails 5.1" (on MacOS).
I want ruby -v to be 2.4.1.
Currently, ruby -v says ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19].
I want to use rbenv to manage the version of Ruby installed. So I tried rbenv install 2.4.1 then rbenv global 2.4.1. But that still did not change the output of ruby -v. What more do I have to do?
I see that which ruby returns ~/.rubies/ruby-2.6.5/bin/ruby. I can't remember how I installed that version of Ruby - it might have been homebrew.

A: Okay so
brew install rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc
echo 'source ~/.bashrc' >> ~/.bash_profile
rbenv install 2.4.1
rbenv global 2.4.1
rbenv rehash # This is probably what you didn't do, start a new terminal or use rehash

Then try ruby -v and which ruby
You can skip some of the beginning steps in case you have rbenv setup and everything.

A: I ended up using RVM instead. I'm not sure but I might have had multiple ruby version managers installed when I asked the question.


text:
Q: Spring Integration ServiceActivator Method not invoking Migrating existing legacy application to java 11 and spring 5 and seems to be ServiceActivator method not invoking. I see publisher method invoking and printing log statement but no logs printing from ServiceActivator class
spring 5.3.14
spring-integration-* 5.5.7
XML Configuration:

<int:channel id="employeeServicesChannel">
    <int:dispatcher task-executor="employeeServicesExecutor" />
</int:channel>
<bean id="employeeServicesExecutor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="10" />
    <property name="maxPoolSize" value="40" />
    <property name="queueCapacity" value="10" />
    <property name="keepAliveSeconds" value="0"></property>
</bean>

 public class EmployeeServicesPublisher {

    @Publisher(channel = "employeeServicesChannel")
    public EmployeeServicesDto publishEmployeeServicesRequest(EmployeeServicesDto requestDto) {

        logger.info(" employee service request :" + requestDto);
        return requestDto;

    }

@MessageEndpoint
  public class EmployeeServicesServerGateway {

 @ServiceActivator(inputChannel = "employeeServicesChannel", outputChannel =
                                                      "esDynamicOutputChannel")
    public EmployeeServicesDto processRequest(EmployeeServicesDto employeeServicesDto) {

        logger.info("===================================");
        logger.info(" request Id:" + employeeServicesDto.getRequestId());
        return employeeServicesDto;
    }


text:
Q: Software to make a simple Pinout Diagram I would like to make a simple diagram showing the pin outs of all of the pins on a board that I have. I would like to do something like the image in this post. All of the answers to this question either covered electrical schematic software, or doing it completely from scratch. Is there any type of software where I can specific the dimensions of a header, and label each pin? I do not mind something even as simple as this:

A: Do you know what a CAD package is?
Any one of number of computer aided design (CAD) software packages would allow you to create the type of thing that you showed in the picture. The names of a few of these packages that pop into mind are:

*

*AutoCAD

*DraftSight

*Visio

If your tables are limited to looking pretty much like your snippet diagram then even Excel spreadsheet software can be used to show such diagrams.


text:
Q: Mysql Empty Post Error   <form action="gonder.php" method="post">

        <fieldset>
            Ad:
            <input type="text" id="ad" placeholder="Tam Adınızı Giriniz" />

            Soyad:
            <input type="text" id="soyad" placeholder="Soyadınızı Giriniz" />

            Email:
            <input type="email" id="email" placeholder="Email Adresinizi Giriniz" />

            Mesaj:
            <textarea id="mesaj" placeholder="Mesajınız"></textarea>

            <input type="submit" value="Onaya Gönder" />

        </fieldset>
    </form>

This one is my post form and this one ise gonder.php
 <?php
     $con=mysqli_connect("localhost","root","","yeniziyaretci");
     // Check connection
     if (mysqli_connect_errno())
     {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
     }

     $sql="INSERT INTO mesajlar (ad, soyad, email, mesaj)
         VALUES ('$_POST[ad]','$_POST[soyad]','$_POST[email]','$_POST[mesaj]')";

     if (!mysqli_query($con,$sql))
     {
       die('Error: ' . mysqli_error($con));
     }
      echo "";

     mysqli_close($con);
     header("location:index.php?cmd=1");
  ?>

When I tried to post. They dont give eny error but they send it to mysql as a empty . Like this.

A: Your input elements have no name attributes.
Also, please read up on the thing called 'sql injection'.

A: You must select the inputs by name not by id.
change
<input type="text" id="ad" placeholder="Tam Adınızı Giriniz" />
to
<input type="text" name="ad" id="ad" placeholder="Tam Adınızı Giriniz" />

A: You're using wrong and insecure way to query your database. To get the one you have working, just change your $sql declaration as follows:
$sql = sprintf('INSERT INTO mesajlar (ad, soyad, email, mesaj) VALUES ("%s", "%s", "%s", "%s")', $_POST['ad'], $_POST['soyad'], $_POST['email'], $_POST['mesaj']);

But I would suggest you to learn ways to avoid mysql injection.
EDIT
And yes, you're missing "name" attributes on your form.

A: Put this, it will work:
<form action="gonder.php" method="post">

        <fieldset>
            Ad:
            <input type="text" id="ad" name=="ad" placeholder="Tam Adınızı Giriniz" />

            Soyad:
            <input type="text" id="soyad" name="soyad" placeholder="Soyadınızı Giriniz" />

            Email:
            <input type="email" id="email" name="email" placeholder="Email Adresinizi Giriniz" />

            Mesaj:
            <textarea id="mesaj" name="mesaj" placeholder="Mesajınız"></textarea>

            <input type="submit" value="Onaya Gönder" />

        </fieldset>
    </form>

A: Either try
$sql="INSERT INTO mesajlar (ad, soyad, email, mesaj)
VALUES
('".$_POST[ad]."','".$_POST[soyad]."','".$_POST[email]."','".$_POST[mesaj]."')";

or
$sql="INSERT INTO mesajlar (ad, soyad, email, mesaj)
VALUES
('{$_POST[ad]}','{$_POST[soyad]}','{$_POST[email]}','{$_POST[mesaj]}')";

EDIT
Sorry I didn't notice but there is an issue in your html form too
you need to have name="" attributes into you form elements as suggested by Ø Hanky Panky Ø
<form action="gonder.php" method="post">

    <fieldset>
        Ad:
        <input type="text" id="ad" name="ad" placeholder="Tam Adınızı Giriniz" />
    </fieldset>
</form>


text:
Q: Why in C++ when i concat a string with '+' like it don't concat but remove first char of the string i was learning C++ after 6-7 years of java and i have encouter a problem, in this snippet that instead of "concat" it's just remove the n character as the input has been given..
#include <iostream>
int main()
{
    int id;
    std::cin >> id;
    std::cout << "Hello world!" + id << std::endl;
    return 0;
}

the output isn't
Hello world!*input*

but instead it's subtract to "hello world" the n character given in the input. if i give 8 the output will be rld!.
If someone could explain this.. i will glad to hear! =)

A: This is how pointer arithmetics work in C/C++.
Basically, "Hello world!" is just a const char* and its + operator works on it like a pointer. Which means that, for example, if you add 3 to it, then instead of pointing to the beginning of "Hello world" it will point to 3 characters after the beginning. If you print that, you get llo world.
So you're not doing a string concatenation there.
If you just want to print the stuff, you can use operator << and do something like this instead:
std::cout << "Hello world!" << id << std::endl;

If you need a string that actually works like a string, consider using std::string from the standard library or if you use something like Qt, you can use QString.
With a modern compiler (that supports C++11), you can use std::to_string to create a string from an int, and then you can do it like this:
std::string s = "Hello world!";
int i;
std::cin >> i;
s += std::to_string(i);
std::cout << s;

If you consider getting seriously into C++ app development, consider using a library like Qt or boost, which make your work just that much easier, although knowing the standard library well is also a good thing. :)

A: "Hello world!" is, in C (which C++ is based on), of type const char[] which then gets treated as a const char* when you try to use pointer arithmetic. In other words it's a memory address pointing to (say) the location OxDEAD0000 which contains the characters "Hello world!" and a null terminator.
"Hello world!" + id

therefore resolves (if id is 8) to 0xDEAD0008
the stream operator then operates on the contents of this address, which is an offset of 8 characters into "Hello world!" - i.e. "rld!".

A: You can either use operator<<
std::cout << "Hello world!" << id << std::endl;

Or if you have access to C++11 you can use std::to_string
std::cout << "Hello world!" + std::to_string(id) << std::endl;


text:
Q: Java memory Management for JNI I have two questions :

*

*What if I have a JNI call to a method and the JNI method leaks memory. Once this method completes will the JVM Garbage collector be able to get that memory back. I heard that the JVM does not manage the Heap Space used by JNI ? But the memory used by JNI is a part of the memory used by the Java process ?

*Is it absolutely necessary to use JNI to achieve IPC ? What are the other popular Java techniques or is there a Open Source Library to achieve Shared memory in Java ?

A: *

*No: "the JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side" (Wikipedia).

*No, Java has sockets and indeed ProcessBuilder. Shared memory can be achieved with MappedByteBuffer.

A: *

*You need deallocate any os resource created in native code, such as File Descriptor, memory address (allocate by malloc. etc) because they are not binding with any jvm instance.

*You can consider use Memory-Mapped Files (sample).

*You can use RPCs (between computer and computer) in IPC context, such as socket, web service, JMS, etc.

A: *

*in all likelihood yes - though i'm not entirely sure whether there doesn't exist a way to clear that memory.

*take a look at ProcessBuilder - it might be of some help to exclude JNI to achieve IPC.


text:
Q: How can I force Ember to get into the second level of an object in a template using a helper function? I have a 'has-many' helper (thanks to the help of @GJK in In an ember component template how can I use 'if' to check for at least one of an array having a property equal to X?) that allows me to check one level of an array in my template for a match on a property:
helpers/has-many.js

import Ember from 'ember';

// Param[0]: Array to iterate over
// Param[1]: Comparison operator to use, currently supports '===', '>', '<' and nested 'has-any'
// Param[2]: Value to check for
// (Optional) Param[3]: The property of the arrayObject to check, if this is not supplied the element of the array is checked directly

// Returns: True if array has at least one match to value

export function hasAny(params) {
console.log(params);
  var compare = function(a, b, operator) {
    console.log(a + ' ' + b + ' ' + operator);
    if (operator === '===') {
      return a === b;
    }
    if (operator === '>') {
      return a > b;
    }
    if (operator === '<') {
      return a < b;
    }

    return false;
  };

  if (params.length < 3) {
    return false;
  }

  if (params[0] === undefined || params[1] === undefined || params[2] === undefined) {
    return false;
  }

  if (params.length === 3) {
    return params[0].any((item) => compare(item, params[2], params[1]));
  }

  if (params[3] === undefined) {
    return false;
  }

  return params[0].any((item) => compare(item.get(params[3]), params[2],     params[1]));

}

export default Ember.Helper.helper(hasAny);

I now want to add a second level to this so that I can do the equivalent of
notification.account.contacts.Any(c => c.communications.Any(cm => cm.communicationType.description === 'Email'));

I tried adding to my code with the following:
helpers/has-many.js
import Ember from 'ember';

// Param[0]: Array to iterate over
// Param[1]: Comparison operator to use, currently supports '===', '>', '<' and nested 'has-any'
// Param[2]: Value to check for
// (Optional) Param[3]: The property of the arrayObject to check, if this is not supplied the element of the array is checked directly

// Returns: True if array has at least one match to value

export function hasAny(params) {
console.log(params);
  var compare = function(a, b, operator) {
    console.log(a + ' ' + b + ' ' + operator);
    if (operator === '===') {
      return a === b;
    }
    if (operator === '>') {
      return a > b;
    }
    if (operator === '<') {
      return a < b;
    }
    if (operator.lastIndexOf('has', 0) === 0) {
      var innerParams = operator.split('%');
      console.log(a);
      return hasAny(a, innerParams[1], innerParams[2], b);
    }
    return false;
  };

  if (params.length < 3) {
    return false;
  }

  if (params[0] === undefined || params[1] === undefined || params[2] === undefined) {
    return false;
  }

  if (params.length === 3) {
    return params[0].any((item) => compare(item, params[2], params[1]));
  }

  if (params[3] === undefined) {
    return false;
  }

  return params[0].any((item) => compare(item.get(params[3]), params[2],     params[1]));

}

export default Ember.Helper.helper(hasAny);

And then in the template I have:
{{#if (has-any notification.account.contacts 'has-any%===%Email' 'communicationType.description' 'communications')}}

working!

{{/if}}

The problem I have is although the template knows to fire the helper again once notification.account.contacts has resolved from the API, it doesnt know to go again once each contacts' communications have come down from the API - how can I force the template/helper to get my next level of promises?

EDIT 1
These are the models (slightly stripped down, but with the key fields):
models/order-notification.js
Export default DS.Model.extend({
  orderNotificationType: DS.belongsTo('orderNotificationType', {async: true}),
  orderNotificationDetail: DS.attr('string'),
  sent: DS.attr('boolean'),
  account: DS.belongsTo('account', {async: true}),
});

models/account.js
export default DS.Model.extend({
  name: DS.attr('string'),
  accountType: DS.hasMany('accountType', {async: true}),
  contacts: DS.hasMany('contact', {async: true}),
  addresses: DS.hasMany('address', {async: true}),
});

models/contact.js
export default DS.Model.extend({
  title: DS.attr('string'),
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  accounts: DS.hasMany('account', {async: true}),
  communications: DS.hasMany('communication', {async: true})
});

models/communication.js
export default DS.Model.extend({
  value: DS.attr('string'),
  communicationType: DS.belongsTo('communicationType', {async: true}),
  contact: DS.belongsTo('contact', {async: true})
});

models/communication-type.js
export default DS.Model.extend({
  description: DS.attr('string'),
  communications: DS.hasMany('communication', {async: true})
});

EDIT 2
I've got something nearly working:
{{#each notification.account.contacts as |contact index|}}
  {{#each contact.communications as |communication id|}}
    {{#if (has-any contact.communications '===' 'Email' 'communicationType.description' communication.communicationType.description)}}

Working!

    {{/if}}
  {{/each}}
{{/each}}

By going within the each and passing a fourth parameter to the has-any helper (that is unused), all the promises are resolved - the problem I have is that
Working!
 comes up multiple times (because the any is satisfied multiple times by multiple contacts/communications). This method could work if there is a way within an #each to display the contents of an if block only the first time the if is satisfied.

A: So I couldn't do this the way I wanted to but GLK got me in the right direction. At the very lowest layer I aliased communicationType.description in the communication model:
communicationTypeDescription: Ember.computed.alias('communicationType.description')

I then observe that in a property at the next level up
communicationsAvailable: function() {
  var commsAvailable = [];
  this.get('communications').forEach(function(comm) {
    commsAvailable.push(comm.get('communicationType.description'));
  });
  return commsAvailable.filter(function(value, index, ca) {
    return ca.indexOf(value) === index;
  });
}.property('communications.@each.communicationTypeDescription')

I then observe that observable at the next layer up (you could repeat this bit for however deep you need), in my account model:
communicationsAvailable: function() {
  var commsAvailable = [];
  this.get('contacts').forEach(function(contact) {
    commsAvailable.push.apply(commsAvailable, contact.get('communicationsAvailable'));
  });
  return commsAvailable.filter(function(value, index, ca) {
    return ca.indexOf(value) === index;
  });
}.property('contacts.@each.communicationsAvailable')

Note the subtle difference here of push.apply.
Finally, I then used my has-many function in it's 3 param form in my template:
{{#if (has-any notification.account.communicationsAvailable '===' 'Email')}}

Working!

{{/if}}


text:
Q: Delphi Firemonkey TVideoCaptureDevice Live Stream From Client-Server-Client I have been struggling to send/receive TVideoCaptureDevice Live Stream to Client-Server-Client. I am using TIdTCPServer and TIdTCPClient. When try to receive I am getting Connection closed Gracefully. How to overcome the Connection closed gracefully?
Below is my code:
Server
//for send
procedure TWebSocket.videoSendServerExecute(AContext: TIdContext);
var
  fip: string;
  ms: TMemoryStream;
  cmd: string;
begin
  cmd := AContext.Connection.IOHandler.ReadLn(IndyTextEncoding_UTF8);
  if AContext.Connection.Connected then
  begin
    fip := cmd;//AContext.Connection.Socket.Binding.PeerIP;
    fip := Copy(fip, Pos(':', fip) + 1, Length(fip));
    ms := vWebcamCollection.GetItem(vWebcamCollection.GetIndexByIP(fip)).StartedStream;
    ms.Position := 0;
    AContext.Connection.IOHandler.LargeStream := True;
    AContext.Connection.IOHandler.ReadStream(ms);
    AContext.Connection.IOHandler.WriteLn('DONE', IndyTextEncoding_UTF8);
  end;
end;

//for receive
procedure TWebSocket.videoReceiveServerExecute(AContext: TIdContext);
var
  ms: TMemoryStream;
  cmd, viewip: string;
begin
  cmd := AContext.Connection.IOHandler.ReadLn;
  viewip := cmd;
  viewip := Copy(viewip, Pos(':', viewip) + 1, Length(viewip));
  ms := vWebcamCollection.GetItem(vWebcamCollection.GetIndexByIP(viewip)).StartedStream;
  ms.Position := 0;
  AContext.Connection.IOHandler.LargeStream := True;
  AContext.Connection.IOHandler.Write(ms, 0, True);
  AContext.Connection.IOHandler.WriteLn('DONE', IndyTextEncoding_UTF8);
end;

Client
both timers interval is 500
//for sending stream in TTimer.OnTimer
procedure TfrmVideoForm.sendTimerTimer(Sender: TObject);
begin
  sendTimer.Enabled := False;
  TThread.Synchronize(TThread.CurrentThread, (
    procedure
    var
      aIp: String;
      ms: TMemoryStream;
    begin
      aIp := getLocalIPAddress;
      aIp := Format('send:%s', [aIp]);
      videoClient.IOHandler.WriteLn(aIp, IndyTextEncoding_UTF8);
      ms := TMemoryStream.Create;
      videoClient.IOHandler.LargeStream := True;
      imgVideo.Bitmap.SaveToStream(ms);
      ms.Position := 0;
      videoClient.IOHandler.Write(ms, 0, True);
      videoClient.IOHandler.ReadLn(IndyTextEncoding_UTF8);
    end));
  sendTimer.Enabled := True;
end;

//for receiving stream - fIPAddress = which IPAddress Start TVideoCaptureDevice
procedure TfrmVideoForm.receiveTimerTimer(Sender: TObject);
begin
  receiveTimer.Enabled := False;
  TThread.Synchronize(TThread.CurrentThread, (
    procedure
    var
      strm: TMemoryStream;
    begin
      videoRcvClient.IOHandler.WriteLn('receive:' + fIPAddress,
        IndyTextEncoding_UTF8);
      strm := TMemoryStream.Create;
      videoRcvClient.IOHandler.LargeStream := True;
      videoRcvClient.IOHandler.ReadStream(strm);
      videoRcvClient.IOHandler.ReadLn(IndyTextEncoding_UTF8);
      strm.Position := 0;
      imgVideo.Bitmap.LoadFromStream(strm);
      strm.Free;
    end));
  receiveTimer.Enabled := True;
end;

code for server holding IPAdress
  { TWebcamItem }

  TWebcamItem = class(TCollectionItem)
  private
    fStartedIP: string;
    fStartedStream: TMemoryStream;
  public
    procedure Assign(Source: TPersistent); override;
    constructor Create(ACollection: TCollection); override;
    destructor Destroy; override;
    property StartedIP: string read fStartedIP write fStartedIP;
    property StartedStream: TMemoryStream read fStartedStream write fStartedStream;
    procedure CreateStream;
    procedure FreeStream;
  end;

  { TWebcamCollection }

  TWebcamCollection = class(TCollection)
  private
    function GetItem(Index: integer): TWebcamItem;
    procedure SetItem(Index: integer; AValue: TWebcamItem);
  public
    constructor Create;
    function Add: TWebcamItem;
    property Items[Index: integer]: TWebcamItem read GetItem write SetItem; default;
    function GetIndexByIP(AIP: string): integer;
  end;


text:
Q: Domain Integration Calculus Suppose $G:[-1,1]\to\Bbb R$, $G(x):=\int_{-5}^{2x^4+x^2+1}{e^{-t^4}}$, $x \in [-1,1]$. I want to find a formula for the derivative without the integral symbol.
Let $G:[-1,1]\to\Bbb R$, $G(x):= \int_{-5}^{2x^4+x^2+1}{e^{-t^4}} \;dt$, for $x \in [-1,1].$
Solution: Let $C:[-5,4]\to\Bbb R$ be given by $C(x):=\int_{-5}^{x}{e^{-t^4}}$ for all $x \in [1,4]$. The function $c:[-1,1]\to\Bbb R$ given by $c(t)=e^{-t^4}$ for all $t \in [-1,1]$. The function $c$ is continuous as a composition of $t\mapsto e^t$ and $t\mapsto -t^4$ where first is an elementary function and second is a polynomial.
Hence, apply Fundamental Theorem of Calculus for continuous functions, which implies that $C$ is differentiable with $C'(x) = c(x) = e^{-x^4}$ for all $x\in \Bbb R$.
Now, observe that $G(x) = C(2x^4+x^2+1)$, so $G=C\circ g$, where $g(x):=2x^4+x^2+1$ is differentiable as a polynomial. Also, $C$ is differentiable by previous discussion using Fundamental Theorem of Calculus, so the chain rule implies that $G$ is differentiable with derivative:
$G'(x) = C'(g(x))g'(x) ({e^{-(2x^4+x^2+1)^4}})(8x^3+2x)$ for all $x \in [-1,1]$ as required. $\square$
I am really confused about the domain. I know the upper endpoint of the integral is for $[1,4]$. Can someone please help me and edit my solution where the domain / $x$-values are wrong. I think I am getting confused between the domain of the function and values of the integral. It's really annoying me because I can't seem to understand for two weeks. Can I set all $x\in\cdots$ and $[]$ to $\Bbb R$??? I don't think I can because in the question $G$ is defined for $[-1,1]$ where $x \in [-1,1]$.
My definition for the Fundamental Theorem of Calculus. If $f\colon[a,b] \to \Bbb R$
is continuous and $F\colon [a,b] \to \Bbb R$ is given by $F(x):=\int_{a}^{x}f$ for all $x\in[a,b]$, then $F$ is differentiable with derivative $F'(x)=f(x)$ for all $x \in [a,b]$.

A: The function $G:[-1,1]\to \mathbb{R}$ is defined by the formula
$$G(x)=\int\limits_{-5}^{2x^4+x^2+1}e^{-t^4}\,dt$$
The function $G$ is not defined off the interval $[-1,1],$ or it may defined there by the same or by another formula.  It will be irrelevant for the solution.
As we are dealing with the closed interval, we may calculate $G'(x)$ for $-1<x<1$ and $G'_+(-1)$ and $G'_-(1).$ We have to use one sided derivatives at the endpoints of the interval, as we have no information on the behaviour of $G$ for $x<-1$ and for $x>1.$
Consider the function $H:\mathbb{R}\to \mathbb{R}$ defined by the same formula as $G$ $$H(x)=\int\limits_{-5}^{2x^4+x^2+1}e^{-t^4}\,dt$$ but with no restriction on $x.$
By the fundamental theorem of calculus and the chain rule, we get
$$H'(x)=e^{-(2x^4+x^2+1)^4}(8x^3+2x)$$
Clearly $G(x)=H(x),$ for $|x|\le 1.$ Therefore
$$G'(x)=H'(x),\ |x|<1,\ G'_+(-1)=H'(-1),\quad G'_-(1)=H'(1)$$
Thus
$$G'(x)=e^{-(2x^4+x^2+1)^4}(8x^3+2x),\ -1<x<1$$ and
$G'_+(-1)=-10e^{-64}$,$\ $ $G'_-(1)=10e^{-64}$


text:
Q: A better timeline figure using tikz I want to draw a figure that is as close as possible to the hand drawn figure below.

I have attempted the following:
\documentclass[a4paper, 12 pt]{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{enumitem}

    \begin{document}
          \begin{figure}
        \setlist[itemize]{nosep, leftmargin=*}
        \begin{tikzpicture}[
            node distance = 0mm and 0.02\linewidth,
            box/.style = {inner xsep=0pt, outer sep=0pt,
                text width=0.32\linewidth,
                align=left, font=\small}
            ]
            \node (n1) [box]
            {   \begin{itemize}
                    \item   Households can produce or consume $x$ with equal probability
                    \item Young entrepreneurs borrow bank deposits to buy $x$ for investment
                    \item Young bankers issue deposits and loans
                \end{itemize}
            };
            \node (n2) [box, below right=of n1.north east]
            {   \begin{itemize}
                    \item  $\frac{1}{4}$ probability of type $l$ consumers
                    \item  $\frac{1}{4}$ probability of type $h$ consumers
                    \item  $\frac{1}{2}$ probability of producers
                \end{itemize}
            };
            \node (n3) [box, below right=of n2.north east]
            {   \begin{itemize}
                    \item   Old entrepreneurs get output, repay loans, consume $x$ and die
                    \item   Old bankers receive loan repayments, consume $x$ and die
                \end{itemize}
            };
            \draw[thick, -latex]    (n1.north west) -- (n3.north east);
            \draw (n1.north) -- + (0,3mm) node[above] {Day};
            \draw (n2.north) -- + (0,3mm) node[above] {Night};
            \draw (n3.north) -- + (0,3mm) node[above] {Day};
        \end{tikzpicture}
      \end{figure}
    \end{document}

The codes above produce this figure:

This is different from what I want. I want to include the $t$ and $t+1$ and also have the tick marks cut through the line and they will appear centered on the line if that makes sense? Also, probably would be better getting some chunk of text above the line like they appear on the hand drawn figure.

A: Here's a PGFKeys-powered approach where \tikztimeline expects a list of entries where you can set none or all of the four values top, above, below, bottom for each element in the list.
You can use \tikztimelineset to adjust default values on a global scale or use the optional argment of \tikztimeline to set values only for one diagram.
The lengths segment width and tick length can be adjusted.
You will make sure that segment width × entries won't be too long for your page.
Code
\documentclass[a4paper, 12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\newcommand*\tikztimelineset{\pgfqkeys{/tikz/timeline}}
\tikztimelineset{
  segment width/.initial=4cm, tick length/.initial=6pt,
  topbot/.style={
    align=flush left,
    text width=\pgfkeysvalueof{/tikz/timeline/segment width}
           -2*(\pgfkeysvalueof{/pgf/inner xsep})},
  top/.initial=, above/.initial=, below/.initial=, bottom/.initial=}
\newcommand*\tikztimeline[2][]{
\begin{tikzpicture}[timeline/every timeline/.try,timeline/.cd,#1]
\foreach[count=\CNT] \elem in {#2}{
  \tikztimelineset{/tikz/style/.expand once=\elem}
  \tikzset{xshift=\CNT*(\pgfkeysvalueof{/tikz/timeline/segment width})}
  \unless\ifnum\CNT=1\relax
  \draw (down:\pgfkeysvalueof{/tikz/timeline/tick length}) -- coordinate (lasttick)
        (  up:\pgfkeysvalueof{/tikz/timeline/tick length});
  \fi
  \node[above] (@above) at (right:{.5*(\pgfkeysvalueof{/tikz/timeline/segment width})})
    {\strut$\pgfkeysvalueof{/tikz/timeline/above}$};
  \node[above, timeline/topbot] at (@above.north) {\pgfkeysvalueof{/tikz/timeline/top}};
  \node[below] (@below) at (@above.south) {\strut\pgfkeysvalueof{/tikz/timeline/below}};
  \node[below, timeline/topbot] at (@below.south) {\pgfkeysvalueof{/tikz/timeline/bottom}};
}
\draw[->] (right:\pgfkeysvalueof{/tikz/timeline/segment width})
      -- ([xshift=\pgfkeysvalueof{/tikz/timeline/segment width}] lasttick);
\end{tikzpicture}}

\tikztimelineset{every timeline/.append style={>=Latex}}

\begin{document}
\tikztimeline{
  {
    top=Households can produce or consume $x$ with equal probabilit.,
    above=t,
    below=Day,
    bottom=Young entrepreneurs borrow bank deposits to buy $x$ for investment.\\
           Young bankers issue deposits and loans.
  }, {
    top=$\frac{1}{4}$ probability of type $l$ consumers.
        $\frac{1}{4}$ probability of type $h$ consumers.
        $\frac{1}{2}$ probability of producers.,
    below=Night
  }, {
    above=t+1,
    below=Day,
    bottom={Old entrepreneurs get output, repay loans, consume $x$ and die.\\
            Old bankers receive loan repayments, consume $x$ and die.}
  }}
\end{document}

Output


text:
Q: I am trying to detect changes on a particular element using the MutationObserver but it is not working. What am I doing wrong? I have been trying to log the updated cost information from an HTML document but have not been successful. I am sure it has to be that I am not using the mutation observer correctly. The js file is linked. Below is the HTML element that I am targeting.
HTML:
0.00
The JS file contains the following code:

const total = document.getElementById('cost');

console.log(total);
const options = {
  characterData: true
};

function logCallback(mutations) {
  console.log('called');

  for (let mutation of mutations) {
    if (mutation.type === 'characterData')
    {
      console.log('Mutation Detected: Price changed');
    }
  }
}

const observer = new MutationObserver(logCallback);

observer.observe(total.childNodes[0], options);

A: Your code would work if the code that was making the change changed the text node you're watching rather than destroying and replacing it, like this:
total.childNodes[0].nodeValue = "1.00";

Live Example:

const total = document.getElementById('cost');

const options = {
  characterData: true,
};

function logCallback(mutations) {
  console.log('called');

  for (let mutation of mutations) {
    if (mutation.type === 'characterData')
    {
      console.log('Mutation Detected: Price changed');
    }
  }
}

const observer = new MutationObserver(logCallback);

observer.observe(total.childNodes[0], options);

// Code that changes the element
total.childNodes[0].nodeValue = "1.00";
0.00

But the code making the change is probably destroying and replacing the child node, like this:
total.innerText = "1.00";

To handle that, you're probably best off watching for childList changes on the total element itself:

const total = document.getElementById('cost');

const options = {
  childList: true,
};

function logCallback(mutations) {
  console.log('called');

  for (let mutation of mutations) {
    console.log('Mutation Detected: Price changed');
  }
}

const observer = new MutationObserver(logCallback);

observer.observe(total, options);

// Code that changes the element
total.innerText = "1.00";
0.00

You may need to refine that (I removed the if checking only for characterData changes), and/or combine it with what you already had (in case some other code changes the text differently), but that's the main issue with what you had.


text:
Q: Solve triple integral and draw graph I need to solve this triple integral:
$$\iiint y^2\exp(2xy)\, dx\,dy\,dz$$
Where $$V=\{x=0,y=1,z=0,y=x,z=8\}$$
My answer $\exp(2)-1$ was wrong
I adjusted my limits: $x$ from $0$ to $y$, $y$ from $x$ to $1$, $z$ from $0$ to $8$ and got answer:
$$2x^2 - \exp(2x^2)+\exp(2)-2$$But I still have no idea whether it is right or how to draw a proper graph
Here is link to my attempt of solving it
https://fex.net/ru/s/prpd5ep

A: so, what we have is:
$$0\le z\le8$$
and since this variable is separable we can say:
$$I=\int_0^8dz\iint y^2\exp(2xy)dxdy=8\iint y^2\exp(2xy)dxdy$$

Now the lines $x=0,y=1,y=x$ forms a triangular region which I assume is the domain you want. In this region $0\le x,y\le1$ is true but we need to put the limits on properly:
$$I=8\int_0^1\int_0^yy^2\exp(2xy)dxdy$$
$$I=8\int_0^1y^2\left[\frac{\exp(2xy)}{2y}\right]_{x=0}^ydy=4\int_0^1y\left(e^{2y^2}-1\right)dy$$
$$I=4\int_0^1ye^{2y^2}dy-4\int_0^1ydy$$


text:
Q: How to exclude particular values when shuffling a column in R? I would like to shuffle all the rows in a column unless a row contains one particular value, in which case that row should not be included in the shuffling process (i.e. all rows containing the specified value stay where they are).
Using the iris example below, let's say we want to shuffle all rows of the column Species except those rows of Species which contain the value setosa. How do I do that?
Thanks!
library(dplyr)

set.seed(123)

my_df <- iris %>%
  mutate(species2 = sample(Species), # shuffles whole column
         # attempted conditional shuffle of non-setosa values (does not work!)
         species3 = sample(nrow(Species != "setosa")))

A: We can try making an external function that does that. conditional_shuffle selects cases that don't fit a condition and just uses sample on them:
library(tidyverse)

conditional_shuffle <- function(vec, condition, seed = 123) {
    set.seed(seed)
    cases2shuffle <- vec != condition
    vec[cases2shuffle] <- sample(vec[cases2shuffle])
    return(vec)
}
iris %>%
    mutate(species2 = conditional_shuffle(Species, "setosa"))
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species   species2
#> 1            5.1         3.5          1.4         0.2     setosa     setosa
#> 2            4.9         3.0          1.4         0.2     setosa     setosa
#> 3            4.7         3.2          1.3         0.2     setosa     setosa
#> 4            4.6         3.1          1.5         0.2     setosa     setosa
#> 5            5.0         3.6          1.4         0.2     setosa     setosa
#> 6            5.4         3.9          1.7         0.4     setosa     setosa
#> 7            4.6         3.4          1.4         0.3     setosa     setosa
#> 8            5.0         3.4          1.5         0.2     setosa     setosa
#> 9            4.4         2.9          1.4         0.2     setosa     setosa
#> 10           4.9         3.1          1.5         0.1     setosa     setosa
#> 11           5.4         3.7          1.5         0.2     setosa     setosa
#> 12           4.8         3.4          1.6         0.2     setosa     setosa
#> 13           4.8         3.0          1.4         0.1     setosa     setosa
#> 14           4.3         3.0          1.1         0.1     setosa     setosa
#> 15           5.8         4.0          1.2         0.2     setosa     setosa
#> 16           5.7         4.4          1.5         0.4     setosa     setosa
#> 17           5.4         3.9          1.3         0.4     setosa     setosa
#> 18           5.1         3.5          1.4         0.3     setosa     setosa
#> 19           5.7         3.8          1.7         0.3     setosa     setosa
#> 20           5.1         3.8          1.5         0.3     setosa     setosa
#> 21           5.4         3.4          1.7         0.2     setosa     setosa
#> 22           5.1         3.7          1.5         0.4     setosa     setosa
#> 23           4.6         3.6          1.0         0.2     setosa     setosa
#> 24           5.1         3.3          1.7         0.5     setosa     setosa
#> 25           4.8         3.4          1.9         0.2     setosa     setosa
#> 26           5.0         3.0          1.6         0.2     setosa     setosa
#> 27           5.0         3.4          1.6         0.4     setosa     setosa
#> 28           5.2         3.5          1.5         0.2     setosa     setosa
#> 29           5.2         3.4          1.4         0.2     setosa     setosa
#> 30           4.7         3.2          1.6         0.2     setosa     setosa
#> 31           4.8         3.1          1.6         0.2     setosa     setosa
#> 32           5.4         3.4          1.5         0.4     setosa     setosa
#> 33           5.2         4.1          1.5         0.1     setosa     setosa
#> 34           5.5         4.2          1.4         0.2     setosa     setosa
#> 35           4.9         3.1          1.5         0.2     setosa     setosa
#> 36           5.0         3.2          1.2         0.2     setosa     setosa
#> 37           5.5         3.5          1.3         0.2     setosa     setosa
#> 38           4.9         3.6          1.4         0.1     setosa     setosa
#> 39           4.4         3.0          1.3         0.2     setosa     setosa
#> 40           5.1         3.4          1.5         0.2     setosa     setosa
#> 41           5.0         3.5          1.3         0.3     setosa     setosa
#> 42           4.5         2.3          1.3         0.3     setosa     setosa
#> 43           4.4         3.2          1.3         0.2     setosa     setosa
#> 44           5.0         3.5          1.6         0.6     setosa     setosa
#> 45           5.1         3.8          1.9         0.4     setosa     setosa
#> 46           4.8         3.0          1.4         0.3     setosa     setosa
#> 47           5.1         3.8          1.6         0.2     setosa     setosa
#> 48           4.6         3.2          1.4         0.2     setosa     setosa
#> 49           5.3         3.7          1.5         0.2     setosa     setosa
#> 50           5.0         3.3          1.4         0.2     setosa     setosa
#> 51           7.0         3.2          4.7         1.4 versicolor versicolor
#> 52           6.4         3.2          4.5         1.5 versicolor  virginica
#> 53           6.9         3.1          4.9         1.5 versicolor  virginica
#> 54           5.5         2.3          4.0         1.3 versicolor versicolor
#> 55           6.5         2.8          4.6         1.5 versicolor  virginica
#> 56           5.7         2.8          4.5         1.3 versicolor versicolor
#> 57           6.3         3.3          4.7         1.6 versicolor versicolor
#> 58           4.9         2.4          3.3         1.0 versicolor versicolor
#> 59           6.6         2.9          4.6         1.3 versicolor  virginica
#> 60           5.2         2.7          3.9         1.4 versicolor versicolor
#> 61           5.0         2.0          3.5         1.0 versicolor  virginica
#> 62           5.9         3.0          4.2         1.5 versicolor  virginica
#> 63           6.0         2.2          4.0         1.0 versicolor  virginica
#> 64           6.1         2.9          4.7         1.4 versicolor versicolor
#> 65           5.6         2.9          3.6         1.3 versicolor  virginica
#> 66           6.7         3.1          4.4         1.4 versicolor versicolor
#> 67           5.6         3.0          4.5         1.5 versicolor versicolor
#> 68           5.8         2.7          4.1         1.0 versicolor  virginica
#> 69           6.2         2.2          4.5         1.5 versicolor  virginica
#> 70           5.6         2.5          3.9         1.1 versicolor versicolor
#> 71           5.9         3.2          4.8         1.8 versicolor  virginica
#> 72           6.1         2.8          4.0         1.3 versicolor  virginica
#> 73           6.3         2.5          4.9         1.5 versicolor  virginica
#> 74           6.1         2.8          4.7         1.2 versicolor versicolor
#> 75           6.4         2.9          4.3         1.3 versicolor versicolor
#> 76           6.6         3.0          4.4         1.4 versicolor  virginica
#> 77           6.8         2.8          4.8         1.4 versicolor  virginica
#> 78           6.7         3.0          5.0         1.7 versicolor versicolor
#> 79           6.0         2.9          4.5         1.5 versicolor versicolor
#> 80           5.7         2.6          3.5         1.0 versicolor versicolor
#> 81           5.5         2.4          3.8         1.1 versicolor  virginica
#> 82           5.5         2.4          3.7         1.0 versicolor  virginica
#> 83           5.8         2.7          3.9         1.2 versicolor  virginica
#> 84           6.0         2.7          5.1         1.6 versicolor  virginica
#> 85           5.4         3.0          4.5         1.5 versicolor  virginica
#> 86           6.0         3.4          4.5         1.6 versicolor versicolor
#> 87           6.7         3.1          4.7         1.5 versicolor  virginica
#> 88           6.3         2.3          4.4         1.3 versicolor versicolor
#> 89           5.6         3.0          4.1         1.3 versicolor versicolor
#> 90           5.5         2.5          4.0         1.3 versicolor versicolor
#> 91           5.5         2.6          4.4         1.2 versicolor versicolor
#> 92           6.1         3.0          4.6         1.4 versicolor versicolor
#> 93           5.8         2.6          4.0         1.2 versicolor versicolor
#> 94           5.0         2.3          3.3         1.0 versicolor versicolor
#> 95           5.6         2.7          4.2         1.3 versicolor versicolor
#> 96           5.7         3.0          4.2         1.2 versicolor  virginica
#> 97           5.7         2.9          4.2         1.3 versicolor  virginica
#> 98           6.2         2.9          4.3         1.3 versicolor  virginica
#> 99           5.1         2.5          3.0         1.1 versicolor versicolor
#> 100          5.7         2.8          4.1         1.3 versicolor  virginica
#> 101          6.3         3.3          6.0         2.5  virginica  virginica
#> 102          5.8         2.7          5.1         1.9  virginica versicolor
#> 103          7.1         3.0          5.9         2.1  virginica  virginica
#> 104          6.3         2.9          5.6         1.8  virginica  virginica
#> 105          6.5         3.0          5.8         2.2  virginica versicolor
#> 106          7.6         3.0          6.6         2.1  virginica versicolor
#> 107          4.9         2.5          4.5         1.7  virginica versicolor
#> 108          7.3         2.9          6.3         1.8  virginica  virginica
#> 109          6.7         2.5          5.8         1.8  virginica  virginica
#> 110          7.2         3.6          6.1         2.5  virginica versicolor
#> 111          6.5         3.2          5.1         2.0  virginica  virginica
#> 112          6.4         2.7          5.3         1.9  virginica versicolor
#> 113          6.8         3.0          5.5         2.1  virginica versicolor
#> 114          5.7         2.5          5.0         2.0  virginica versicolor
#> 115          5.8         2.8          5.1         2.4  virginica  virginica
#> 116          6.4         3.2          5.3         2.3  virginica versicolor
#> 117          6.5         3.0          5.5         1.8  virginica  virginica
#> 118          7.7         3.8          6.7         2.2  virginica  virginica
#> 119          7.7         2.6          6.9         2.3  virginica versicolor
#> 120          6.0         2.2          5.0         1.5  virginica  virginica
#> 121          6.9         3.2          5.7         2.3  virginica versicolor
#> 122          5.6         2.8          4.9         2.0  virginica  virginica
#> 123          7.7         2.8          6.7         2.0  virginica versicolor
#> 124          6.3         2.7          4.9         1.8  virginica  virginica
#> 125          6.7         3.3          5.7         2.1  virginica  virginica
#> 126          7.2         3.2          6.0         1.8  virginica  virginica
#> 127          6.2         2.8          4.8         1.8  virginica  virginica
#> 128          6.1         3.0          4.9         1.8  virginica versicolor
#> 129          6.4         2.8          5.6         2.1  virginica  virginica
#> 130          7.2         3.0          5.8         1.6  virginica versicolor
#> 131          7.4         2.8          6.1         1.9  virginica  virginica
#> 132          7.9         3.8          6.4         2.0  virginica versicolor
#> 133          6.4         2.8          5.6         2.2  virginica versicolor
#> 134          6.3         2.8          5.1         1.5  virginica versicolor
#> 135          6.1         2.6          5.6         1.4  virginica  virginica
#> 136          7.7         3.0          6.1         2.3  virginica  virginica
#> 137          6.3         3.4          5.6         2.4  virginica  virginica
#> 138          6.4         3.1          5.5         1.8  virginica  virginica
#> 139          6.0         3.0          4.8         1.8  virginica versicolor
#> 140          6.9         3.1          5.4         2.1  virginica versicolor
#> 141          6.7         3.1          5.6         2.4  virginica  virginica
#> 142          6.9         3.1          5.1         2.3  virginica versicolor
#> 143          5.8         2.7          5.1         1.9  virginica  virginica
#> 144          6.8         3.2          5.9         2.3  virginica versicolor
#> 145          6.7         3.3          5.7         2.5  virginica versicolor
#> 146          6.7         3.0          5.2         2.3  virginica versicolor
#> 147          6.3         2.5          5.0         1.9  virginica  virginica
#> 148          6.5         3.0          5.2         2.0  virginica versicolor
#> 149          6.2         3.4          5.4         2.3  virginica  virginica
#> 150          5.9         3.0          5.1         1.8  virginica versicolor


text:
Q: error: expected '}' at end of input I have the following code:
#include <libubuntuone-1.0/u1-music-store.h>
#include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-authentication.h>
#include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-credentials.h>
#include <libsyncdaemon-1.0/libsyncdaemon/syncdaemon-daemon.h>

static void
get_credentials (U1MusicStore *music_store,
                                 gchar **oauth_consumer_token,
                                 gchar **oauth_consumer_secret,
                                 gchar **oauth_token,
                                 gchar **oauth_token_secret)
{
    SyncdaemonCredentials *credentials;
    *oauth_consumer_token = *oauth_consumer_secret = *oauth_token = *oauth_token_secret = NULL;

    *oauth_consumer_token = g_strdup (syncdaemon_credentials_get_consumer_key (credentials));
    *oauth_consumer_secret = g_strdup (syncdaemon_credentials_get_consumer_secret (credentials));
    *oauth_token = g_strdup (syncdaemon_credentials_get_token (credentials));
    *oauth_consumer_secret = g_strdup (syncdaemon_credentials_get_token_secret (credentials));
}

int main()
{
    return 0;
}

and the only thing preventing it from compiling is the error message specified in the title of this question. The problem line has been identified as the closing brace of the main function, but that obviously isn't the case, and I can't see where else I could have missed out any parentheses. Can anyone else spot what I'm doing wrong here?

A: In case of such errors it is good idea to localize error. You can do it simply, by commenting blocks of code.
In this example you can comment body get_credentials function and check what will happen.
Also good idea to paste empty line at the end of source code file.

A: Maybe some of the included headers has mismatched braces.
Maybe the compiler is bad at handling files with non-empty last line, and there is such line in some of the files.
Try commenting out as much as you can (especially all includes) to make it compile, and then putting code back in until you localize the problem.


text:
Q: ElasticSearch Mapping Dynamic Template Java I am trying to create a dynamic template for elastic using RestHighLevelClient. The commented out code snippet in getMapping() is for static mapping which works. However, I am running into issues when attempting to create a dynamic mapping.
My intention is to treat any attribute that ends with _id as long and any attribute that end with _message as text.
Can someone please point what I am doing wrong?
":{"root_cause":[{"type":"class_cast_exception","reason":"class_cast_exception: java.util.LinkedHashMap cannot be cast to java.util.List"}],"type":"mapper_parsing_exception","reason":"Failed to parse mapping [_doc]: java.util.LinkedHashMap cannot be cast to java.util.List","caused_by":{"type":"class_cast_exception","reason":"class_cast_exception: java.util.LinkedHashMap cannot be cast to java.util.List"}},"status":400}
My code snippet:
Main method:
CreateIndexRequest request = new CreateIndexRequest(indexName);
    request.settings(Settings.builder()
            .put("index.number_of_shards", 3)
            .put("index.number_of_replicas", 2)
    );

request.mapping("_doc", getMapping());
CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);

Helper Method:
private static XContentBuilder getMapping() throws IOException {

    XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("_doc")
                    .startObject("dynamic_templates")
                            .startObject("id")
                                .field("match", "*_id")
                                .field("match_mapping_type", "long")
                            .endObject()
                            .startObject("message")
                                .field("match", "*_message")
                                .field("match_mapping_type", "string")
                            .endObject()
                    .endObject()
                .endObject()
            .endObject();

    /*XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("_doc")
                    .startObject("properties")
                        .startObject("user")
                            .field("type", "text")
                            .field("index", true)
                        .endObject()
                        .startObject("message")
                            .field("type", "text")
                            .field("index", true)
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();*/

    return mappingBuilder;
}

Reference Guide: https://www.elastic.co/guide/en/elasticsearch/guide/master/custom-dynamic-mapping.html

A: The dynamic templates is array.
For example, Elasticsearch 7.1.0
private XContentBuilder buildDynamicTemplates() throws IOException {
    XContentBuilder dynamicTemplate = XContentFactory.jsonBuilder();
    dynamicTemplate.startObject();
    {
      dynamicTemplate = DynamicTemplateFactory.templateBuilder(dynamicTemplate);
    }
    dynamicTemplate.endObject();
    return dynamicTemplate;
  }

  private static XContentBuilder builderTemplate() throws IOException {
    XContentBuilder dynamicTemplate = XContentFactory.jsonBuilder();
    dynamicTemplate.startObject();
    dynamicTemplate.startArray("dynamic_templates");
    {
      dynamicTemplate.startObject();
      {
        dynamicTemplate.startObject("strings_as_keywords");
        {
          dynamicTemplate.field("match", "*");
          dynamicTemplate.field("match_mapping_type", "string");
          dynamicTemplate.startObject("mapping");
          {
            dynamicTemplate.field("type", "keyword");
          }
          dynamicTemplate.endObject();
        }
        dynamicTemplate.endObject();
      }
      dynamicTemplate.endObject();
    }
    dynamicTemplate.endArray();
    dynamicTemplate.endObject();
    return dynamicTemplate;
  }


text:
Q: Uploading file to Google Cloud storage locally using NodeJS I'm trying to upload an image to Google Cloud Storage using the simple code locally on my machine with my service account:
const storage = require('@google-cloud/storage');
const fs = require('fs');
const gcs = storage({
    projectId: 'ID',
    keyFilename: 'KEYNAME'
});
var bucket = gcs.bucket('BUCKET NAME');

bucket.upload('hiking-image.jpg', function(err, file) {
    if (err) throw new Error(err);
});

if (err) throw new Error(err);
         ^

However, I get the error message below. Is the Google Cloud API only supposed to work when deployed on App Engine or am I doing something wrong here? I was able to get the Google Vision API to work locally using the same Service Account.
Error: ApiError: Forbidden
    at /Users/user/google-cloud/upload/upload.js:10:20
    at Pumpify.<anonymous> (/Users/user/node_modules/@google-cloud/storage/src/bucket.js:1218:9)
    at emitOne (events.js:101:20)
    at Pumpify.emit (events.js:188:7)
    at Pumpify.Duplexify._destroy (/Users/user/node_modules/duplexify/index.js:184:15)
    at /Users/user/node_modules/duplexify/index.js:175:10
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

A: You need to give appropriate role to your service account. Go to the google cloud console, menu "IAM and Admin"

*

*Create a service account

*Go to IAM panel

*Edit the role of the service account you just created. Select cloud storage and make it either a full admin, but the best is you just make it a creater or reader of storage objects depending on your needs.

A: I simply had an error in the cloud console with my service account at Overdrivr pointed out


text:
Q: Perl: calculate jackknife error from of each column of a multi-column file I am trying to calculate the jacknife average and error of each column in a multi-column file.
My example data file look like this:
$ cat data.HW2
1.1 2.1 3.1 4.1
1.2 2.2 3.2 4.2
1.3 2.3 3.3 4.3
1.4 2.4 3.4 4.4

My  attempted solution is to define arrays that will eventually be the size same as the number of columns (in this case 4) and iterate over them line by line:
cat jackkinfe.pl

#! /usr/bin/perl
use warnings; use strict;
my @n=0;
my @x;
my $j;
my $i;
my $dg;
my @x_jack;
my @x_tot=0;
my $cols;
my $col_start=0;

# read in the data
while(<>)
{
  my @column = split();
  $cols=@column;
  foreach my $j ($col_start .. $#column) {
    $x[$n[$j]][$j] = $column[$j];
    $x_tot[$j] += $x[$n[$j]][$j];
    $n[$j]++;
  }
}
# Do the jackknife estimates
for ($j=$col_start; $j<$cols; $j++)
{
  for ($i = 0; $i < $n[$j]; $i++)
  {
    $x_jack[$i][$j] = ($x_tot[$j] - $x[$i][$j]) / ($n[$j] - 1);
  }
# Do the final jackknife estimate
  my @g_jack_av=0;
  my @g_jack_err=0;
  for ($i = 0; $i < $n[$j]; $i++)
  {
    $dg = $x_jack[$i][$j];
    $g_jack_av[$j] += $dg;
    $g_jack_err[$j] += $dg**2;
  }
  $g_jack_av[$j] /= $n[$j];
  $g_jack_err[$j] /= $n[$j];
  $g_jack_err[$j] = sqrt(($n[$j] - 1) * abs($g_jack_err[$j] - $g_jack_av[$j]**2));
  printf "%e %e ", $g_jack_av[$j], $g_jack_err[$j];
}
printf "\n";

It gives me the following two warnings:
$cat data.HW2 | perl jackknife.pl
Use of uninitialized value within @n in array element at cols_jacknife.pl line 19, <> line 1.
Use of uninitialized value within @n in array element at cols_jacknife.pl line 20, <> line 1.

It is complaining at the following two lines:
$x[$n[$j]][$j] = $column[$j];
$x_tot[$j] += $x[$n[$j]][$j];

But I want to set the size of @n dynamically depending on the size of the data file.
How do I remove this warning?
Any other suggestions on my Perl usage are also welcome and much appreciated since I am trying to learn best practices.

A: This part of your code
my @n=0;
....
  foreach my $j ($col_start .. $#column) {
    $x[$n[$j]][$j] = $column[$j];
    $x_tot[$j] += $x[$n[$j]][$j];
    $n[$j]++;
  }

Will trigger the warning once for every value of $j larger than 0, because only the first element in @n is defined: $n[0] = 0. Only at the end of the loop iteration is the array value finally defined, when it is set to 1 by the increment operator with $n[$j]++.
Technically, the code will still work as you expect, because undef will be cast to 0. So.... it should be safe to ignore the warning. You can do something like this inside your loop to avoid it:
$n[$j] //= 0;     # $n[$j] is defined, or set to 0

This is equivalent to
if (not defined($n[$j])) {
    $n[$j] = 0;
}


text:
Q: Rebuild when files changes on docker i'm starting to work with docker (with boot2docker on Mac OSX) and golang,
Whenever I make changes on my .go files I want to be visible on the docker image.
Is there anyway to do this? Or docker is not the appropiate thing to do this?
Thanks

A: Docker does not do this by default. I described a couple approaches to this in my question & answer here. A simple way to accomplish what you want is to use a watcher (like nodemon) to monitor your folder and kick off a script (or better, use fig) that recreates and runs your images.


text:
Q: JSON.parse is outputting a string What's going on here?
var data = '"[2743,1,1,1,1,1]"';
var flags = JSON.parse(data);
console.log(typeof flags);      // this outputs "string"

I was expecting flags to be an object or array, but it's a string. The MDN Web Docs say, "The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string." Also:

Return value
  The Object corresponding to the given JSON text.
Exceptions
  Throws a SyntaxError exception if the string to parse is not valid JSON.

A: var data = '"[2743,1,1,1,1,1]"';

This is a string containing a string. When you parse it with
var result = JSON.parse(data);

What you get is the string
"[2743,1,1,1,1,1]"

If you parse that a second time you will get your array of flags.
Try this
var flags = JSON.parse(JSON.parse(data));

A: Looks like it's an object and everything's OK, check the snippet:

var data = '[2743,1,1,1,1,1]';
var flags = JSON.parse(data);
console.log(typeof flags);
console.log(flags);


text:
Q: Add Items to ListBox when scroll reaches the end in Windows phone? I need the requirement that..
Initially i have set of datas that are bound to ListBox... If we scroll to the end i will add some more datas to the collection and will update the ListBox... Is there any way to achieve this in Windows phone ?

A: I suppose that by "achieve this" you mean the possibility to detect if the ListBox is at the end. In that case, this should help.
You'll first need to gain access to the ScrollViewer control in order to see if a user scrolled, and what the current position is. If my page is called ListContent, then this code should give you a good start:
public partial class ListContent
{
    private ScrollViewer scrollViewer;

    public ListContent()
    {
        InitializeComponent();
        Loaded += OnLoaded();
    }

    protected virtual void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        scrollViewer = ControlHelper.List<ScrollViewer>(lbItems).FirstOrDefault();
        if (scrollViewer == null) return;

        FrameworkElement framework = VisualTreeHelper.GetChild(viewer, 0) as FrameworkElement;
        if (framework == null) return;

        VisualStateGroup group = FindVisualState(framework, "ScrollStates");
        if (group == null) return;

        group.CurrentStateChanged += OnListBoxStateChanged;
    }

    private VisualStateGroup FindVisualState(FrameworkElement element, string name)
    {
        if (element == null)
            return null;

        IList groups = VisualStateManager.GetVisualStateGroups(element);
        return groups.Cast<VisualStateGroup>().FirstOrDefault(@group => @group.Name == name);
    }

    private void OnListBoxStateChanged(object sender, VisualStateChangedEventArgs e)
    {
        if (e.NewState.Name == ScrollState.NotScrolling.ToString())
        {
            // Check the ScrollableHeight and VerticalOffset here to determine
            // the position of the ListBox.
            // Add items, if the ListBox is at the end.

            // This event will fire when the listbox complete stopped it's
            // scrolling animation
        }
    }
}

If you're talking about adding the data dynamically, make sure you are using an ObservableCollection for your data. Added items will automatically show up in your ListBox.


text:
Q: Can a null hypersurface be foliated by spacelike sections? Let $(M,g)$ be a $d$-dimensional Lorentzian manifold and let $\Sigma \subset M$ be a null hypersurface, which therefore has dimension $(d-1)$. We know that its normal vector $k^\mu$ is null and since it is null, this normal vector is also tangent to the hypersurface. Its integral lines are null geodesics which are the generators of $\Sigma$.
My question here is essentially whether or not each connected component of $\Sigma$ can be foliated by spacelike sections indexed by some parameter along the generator. I've tried formalizing this as follows.
At each point $\sigma \in \Sigma$ we can pick some $(d-2)$-dimensional spacelike subspace $\Delta_\sigma\subset T_\sigma \Sigma$ which is a complement to the space $L_\sigma$ spanned by $k_\sigma\in T_\sigma \Sigma$, meaning that $T_\sigma \Sigma$ decomposes as a direct sum $$T_\sigma\Sigma\simeq \Delta_\sigma \oplus L_\sigma,\quad L_\sigma = \{\alpha k_\sigma:\alpha \in \mathbb{R}\}.$$
This gives rise to a $(d-2)$-dimensional spacelike distribution $\sigma\mapsto \Delta_\sigma$ over $\Sigma$.
Question: Is it always possible to pick $\Delta_\sigma$ so that the resulting distribution is integrable in each connected component of $\Sigma$? If in general $\Delta$ is not integrable globally inside each connected component of $\Sigma$, around each $\sigma\in \Sigma$ can we find one neighborhood of it $U\subset \Sigma$ so that $\Delta$ restricted to $U$ is integrable?
As an example this is trivially true for the double lightcone of the origin ${\cal C}$ in Minkowski spacetime. It has two connected components ${\cal C}^\pm$ and in each of them we can pick the spacelike complement at each $\sigma\in {\cal C}^\pm$ to be spanned by the angular vectors $\partial_\theta,\partial_\phi$ in spherical coordinates. Since $[\partial_\theta,\partial_\phi]=0$ the resulting distribution is integrable. In the end each component can indeed be foliated by spacelike sections which are diffeomorphic to $S^2$ and where the indexing is by the parameter along the generators. This renders the components with topology $\mathbb{R}\times S^2$. The question is essentially if this admits some generalization to arbitrary null hypersurfaces.

A: The result is true at least locally. I do not think that it is valid globally.
I assume that $\Sigma$ is an immersed (at least) submanifold.
Take $p\in \Sigma$, then there is a local coordinate system $(u,x,y,z)$ in $M$ with domain an open neighborhood of $p$ such that a neighborhood $S\subset \Sigma$ of $p$ is represented by $u=0$. Since $\Sigma$ is lightlike, $g(du^\sharp,du^\sharp) =0$.
The vectors $\partial_x,\partial_y,\partial_z$ are therefore tangent to $\Sigma$ in $S$ and $x,y,z$ are coordinates in $S$ (viewed as an embedded submanifold).
Now observe that $$0= g(du^\sharp, du^\sharp) = \langle du^\sharp, du \rangle\:,$$ so that $du^\sharp \in TS$ as well. This smooth vector field can be integrated in $S$ since the conditions of Frobenius theorem are trivially satisfied. This means that we can change coordinates $x,y,z$ in $S$, passing to a new local coordinate system  $v,r,s$ around $p$ such that $\partial_v = du^\sharp$.
Let us study the nature of the remaining  coordinates $r,s$.
By construction $\partial_v$ is lightlike. Therefore for every $q\in S$ we can arrange an orthonormal basis of $T_qM$ where, for some constant  $k\neq 0$,
$$\partial_v \equiv k(1,0,0,1)^t\:.$$
Just in view of the definition of dual basis, we have that
$$\langle \partial_r, du\rangle =0 \:, $$
which means
$$g(\partial_r, \partial_v)=0\:.$$
Using the said basis and assuming $$\partial_r \equiv (a,b,c,d)^t$$
the orthogonality condition implies
$$\partial_r \equiv (a,b,c,a)^t\:.$$
Hence
$$g(\partial_r,\partial_r) = b^2+c^2 \geq 0$$
However, if $b=c=0$, we would have that $\partial_r$ is linearly dependent from $\partial_v$ which is not possible by construction. We conclude that
$$g(\partial_r,\partial_r) = b^2+c^2 > 0$$
Therefore $\partial_r$ is spacelike. The same argument proves that $\partial_s$ is spacelike as well. Obviously these two vectors are also linearly independent as they arise from a coordinate system.
In summary, the surfaces in $S$ at $v=const$ are spacelike and $S$ is therefore foliated by spacelike surfaces (embedded submanifolds of $S$).
The procedure generalises to every dimension.