text:
Q: Why I can't use nullable type in flutter I have a flutter project created in Jan 2019. I read an article in Dart and says that it support nullable type.
class c {
  int? id;
}

But I can't get the above to compile. It give some error message but has nothing to do with nullable type. Seems like it doesn't understand the '?' at all.
Error:
May I know what might have missing in my code? Do I need to upgrade my Dart or Flutter? I looked at pubspec.yaml, but can't find any where that reference to dart.

A: You don't need to use null safety now, the official support for flutter should arrive at the beginning of next year, according to the flutter team, it is not yet ready for production. But if you just want to test it, update your sdk, sdk: "> = 2.7.0 <3.0.0"
You need to create an analysis_options.yaml file in the root of your flutter app and write something like
analyzer:
  enable-experiment:
    - non-nullable

And also make sure you have a recent enough version of flutter
flutter upgrade

Michael Thomsen from Dart made this post today, where it explains more about null safety in Flutter. https://medium.com/flutter/null-safety-flutter-tech-preview-cb5c98aba187


text:
Q: Compare the month / year of a string I am using an if statement to do a set of commands when an INT (which in this case is a number of a month like 02) is equal  to a STRING (which is a date fully written out like so --> 02/14/1998) the fully written out dates are in a file
So I am asking the user to type in a date and a month (INTS) and compare that to the fully written out dates in the file and when the month is the month of the fully written out date and same w/ the year do a set of calculations.
    int userTypedMonth, userTypedYear
    string fileDate
    if(userTypedMonth == fileDate && userTypedYear == fileDate){
          5+5=10
    }

I know this is the wrong syntax of code but i wanted to show how Im trying to explain it.

A: You can fileDate.split("/") to split the fileDate into a String[] where index 0 is the month ("02"), index 1 is the day ("14"), and index 2 is the ("1998"). Then you could compare using userTypedMonth.equals(fileDateArray[0]) and userTypedYear.equals(fileDateArray[2]), assuming the userTypedMonth/Year were Strings instead of ints. If they are ints, use String.valueOf(userTypedMonth/Year) to compare.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run executable in the same folder via PowerShell I have a PowerShell script from which I want to run an executable in the same folder:
RunTests.ps1
.\nunitlite-runner.exe

When I right click the script in the Explorer and choose Execute with Powershell I get the following error:

Die Benennung ".\nunitlite-runner.exe" wurde nicht als Name eines Cmdlet, einer
Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen
Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten),
und wiederholen Sie den Vorgang.
Bei C:\Users\Test\Desktop\MyScripts\RunTests.ps1: 5 Zeichen:23
+ .\nunitlite-runner.exe <<<<
    + CategoryInfo          : ObjectNotFound: (.\nunitlite-runner.exe:String)    [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Which basically translates to:

The name ". \nunitlite-runner. exe" was not specified as the name of a
  cmdlet, a  function, a script file or an executable program. checking
  enter the spelling of the name or whether the path is correct (if it
  contains) and repeat the procedure.

A: OK, seems I have found the answer. The problem is not with Powershell or the script. Instead it's with Free Commander.
When I run the script via the context menu, Free Commander seems to not set the working directory correctly (thus the executable is not found). When I run the script via double click, it works just fine.


text:
Q: How to use Cloud Firestore in a non-realtime fashion? I've really been investing a lot of time integrating Firestore into my new apps and I'm loving it so far. One thing I noticed is it's very much "realtime" as it touts. This is awesome for writing chat apps, etc, but for non "realtime" features of those apps, it seems kind of excessive to use the Observable pattern for that as you're really probably only attempting to grab a list (not an add, update or delete event) or even a single item and doing the map on a snapshotChange gets a little repetitive in this case as well.
Is there a suggested or recommended way to use Firestore in an almost "RESTful" manner? I'm using the AngularFire2 library if that matters at all. Is it just suggested to use the firestore methods from the firebase npm packages?

A: I think you might be confusing Firebase Realtime Database and Firebase Firestore.
Firebase Realtime Database is very much as you describe in that it is expected you will subscribe to a stream of updates for the data you are interested in. Functionality is provided for "one-time" reads but the product name, documentation and samples often portray real-time scenarios.
Cloud Firestore, on the other hand, does not make these assumptions but still provides the option of real-time stream updates or "one-time" reads.
For deciding between the 2, you should read Google's own document on what they believe the suitability of each is.
If you decide to use Firestore, a sample "one-time" read is documented here.


text:
Q: PHP Match phrase only if outside of an  tag I'm trying automate internal links within pages on my website. I need already linked text to be exempted.
For the following example it should only replace the bolded text (Example).
Example

New **Example**

I tried the following but it didn't work.
$re = '/(\b'.$search.'\b)+((?=.*<a)|(?!.*<\/a>))/';
$str=preg_replace($re, $replace, $text);

A: You should follow @ThomasAyoub's advice. Use DOM functionalities to achieve such a task but this is a way to match desired word with Regular Expressions if you want to see:
]+>.*?<\/a>\K|Example

Live demo


text:
Q: How do I call my SignalR Hub from a Console app How do I call my SignalR Hub from a Console app. And then the SignalR Hub would send the message to its clients?
(see image below)

A: Simple console example I have used to demo "chatting" between browsers and console. Note that this is using .Net (4.x) server/client not .NetCore so it may not work for you if you are using .NetCore version.
using System;
using Microsoft.AspNet.SignalR.Client;

namespace SignalRChatConsole
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                var connection = new HubConnection("http://localhost:7132/");
                IHubProxy hub = connection.CreateHubProxy("ChatHub");

                hub.On<string, string>("broadcastMessage", (name, message) => { Console.Write(name + ": "); Console.WriteLine(message); });
                connection.Start().Wait();
                hub.Invoke("Notify", "Console app", connection.ConnectionId);
                string msg = null;

                while ((msg = Console.ReadLine()) != null)
                {
                    hub.Invoke("Send", "Console app", msg).Wait();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error" + e.Message);
            }
        }
    }
}


text:
Q: How to do MD5 hashing of as string in athena? MD5 hashing function in athena is not working for string. However, athena's document shows that it does : https://docs.aws.amazon.com/redshift/latest/dg/r_MD5.html
Not sure what I am missing here. If I transform varchar to varbinary then the hash that gets generated are not correct.
Getting this error :

SYNTAX_ERROR: line 1:8: Unexpected parameters (varchar(15)) for function md5. Expected: md5(varbinary)

This query ran against the "temp" database, unless qualified by the query. Please post the error message on our forum or contact customer support with Query Id: dd959e8a-7fa4-4170-8895-ce7cf58be6ea.```

A: The md5 function in Athena/Presto takes binary input. You can convert a string to a varbinary using the to_utf8 function:
SELECT md5(to_utf8('hello world'))


text:
Q: Floating point to fixed point coversion I'm creating a hardware module that is using fixed point for its computations. But the input is floating point, and I thus wish to convert the floating point input into fixed point (Q8.8).
I've been trying to use is David Bishops library (http://vhdl.org/fphdl/) for floating points and fixed point. It works well in simulation, but not when I synthesize it. E.g. in the following code the output y is routed to ground when synthesized.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
library ieee_proposed;
use ieee_proposed.fixed_float_types.all;
use ieee_proposed.fixed_pkg.all;
use ieee_proposed.float_pkg.all;

entity sigmoid is
    Port (
        clk     : in std_logic;
        x       : in  float32;
        y       : out sfixed(15 downto -16)
    );
end sigmoid;

architecture Behavioral of sigmoid is

    signal size : sfixed(15 downto -16);

begin

    set_c: process(clk)
    begin
        if rising_edge(clk) then
           y <= to_sfixed(x, size);
        end if;
    end process;

end Behavioral;

From what I've been reading on various forums and in the documentation, this code should synthesize fine. Also, fixed to float conversion using to_float(fixed) works just fine. Have I missed something? Are there other simple ways of implementing float -> fixed conversion?

A: Whenever I use Bishop's library for synthesis, I just include the packages in the project and declare them like the following for your case:
use work.float_pkg.all;
use work.fixed_pkg.all;

I don't use the ieee_proposed library.
Regarding the conversion, I believe the easiest way is to really use the package functions (directly or with more than one type conversion).


text:
Q: dplyr programatic way to filter most recent week What is the best way to efficently filter the last/most recent week (on the basis it may not be a full week worth of data).
library(lubridate)
library(dplyr)

df <- data.frame(dates =
c("2014-12-17","2014-12-18","2014-12-21","2014-12-25","2014-12-26",
  "2015-05-17","2015-05-18","2015-05-21","2015-05-25","2015-05-26",
  "2016-06-17","2016-06-18","2016-06-21","2016-06-25","2016-06-26"))

df <- df %>% mutate(dates = ymd(dates),
                    the.year = year(dates),
                    the.week = week(dates))

#Filter the last week (as may not be complete)

I can come up with solution like this
max.week <- df %>% filter(the.year == max(the.year)) %>%
  filter(the.week == max(the.week)) %>%
  group_by(the.year, the.week) %>%
  summarise(count= n()) %>%
  ungroup() %>%
  mutate(max.week = paste(the.year, the.week,sep="-")) %>%
  select(max.week) %>%
  unlist(use.names = F)

df %>% filter(!paste(the.year, the.week, sep = "-") == max.week)
   %>%

but there must be simplier solution ?

A: The shortest dplyr-way I can think of would be
filter(df, !{yw <- interaction(the.year, the.week)} %in% yw[which.max(dates)])

But you may want to break it down for better legibility:
df %>%
  mutate(yearweek = paste(the.year, the.week, sep = "-")) %>%
  filter(!yearweek %in% yearweek[which.max(dates)])

Remove the ! to achieve the opposite effect.

A: group_indices can also help:
df %>%
  filter(group_indices(., the.year, the.week) < max(group_indices(., the.year, the.week)))

Which can also be written as:
df %>% filter({id <- group_indices(., the.year, the.week)} < max(id))

or
df %>%
  mutate(id = group_indices(., the.year, the.week)) %>%
  filter(id < max(id))

A: try this:
df %>% transform(yw= the.year *100 + the.week) %>% filter(yw != max(yw)) %>% select(-yw)

Or, if your data is sorted by date as seems to be the case :
df %>% filter(the.year !=last(the.year) | the.week !=last(the.week))

A: Another possibility using dplyr,
df %>%
arrange(dates) %>%
filter(the.week != last(the.week) | the.year != last(the.year))


text:
Q: Summarising diagrams for layer I wonder if there is a possibility (plugin etc.) to create a summarising diagram of attributes more or less comparable to the summarising statistics. e.g. having a shape with a high number of polygons of different landuse attributes and want to create a diagram with the sum of area for the different land use types as a bar chart or pie chart diagram. x axes land use types, y axes sum of area.

A: I found the 'DataPlotly' plugin which solves everthing perfectly.
With it you can choose the plot type e.g. bar plot, define the x and y axes parameters. In the settings you are also able to choose the bar mode. The bar mode 'stacked' is summing up the values. However, there are some problems to visualise the charts e.g. the axes titles can´t be adapted properly if needed. There should be a link to edit the charts in the chart studio (button at the top of the chart see picture) but this functionallity is deactivated and greyed out. All in all it provides a fast overview.


text:
Q: Google Drive Video Downloader I am using youtube-dl to get google drive video links , the problem i have it's the links i get with youtube-dl only work with my ip.
One of solution i find it's was using https://redirector.googlevideo.com/ but it's not working for me , its give 404 error. (its work with youtube download link form youtube-dl)
There is websites using Google Drive for hosting their video and using https://redirector.googlevideo.com/ and they dont have any problem.
I wants know should i decode signature ?
Here is google drive link example :
https://r1---sn-4g5e6nes.c.docs.google.com/videoplayback?requiressl=yes&id=52840193735f664c&itag=59&source=webdrive&ttl=transient&app=texmex&ip=46.228.204.146&ipbits=8&expire=1474824502&cp=QVJMVklfU1VOQ1hNOndxcFIydWlqNFNB&sparams=requiressl%2Cid%2Citag%2Csource%2Cttl%2Cip%2Cipbits%2Cexpire%2Ccp&signature=9D38C83DEA269688037662F1B5795275B1E10D82.847BB187CBCDFFC5FD4582723D0CF99C97F5F19C&key=ck2&mm=30&mn=sn-4g5e6nes&ms=nxu&mt=1474809563&mv=m&nh=IgpwcjAyLmZyYTE2KgkxMjcuMC4wLjE&pl=21&sc=yes


text:
Q: Converting a string to dictionary easily I have a string:
my_str =  '{"country":{"AE":"United Arab Emirates","AL":"Albania","AM":"Armenia","AR":"Argentina","AT":"Austria","AU":"Australia","AW":"Aruba"}}'

Is there an easy way to convert it into dictionary? I'd like to use something like dict(my_str) but it doesn't exist.
Easy way.

A: Try this, this is one way only from many ways
json.loads(my_str)


text:
Q: How to use fuzzywuzzy efficiently in python? I want to compute the similarity of column Aname from dataframe Apple to column Bname from dataframe Banana, and create a new column in dataframe A that shows the similarity, my code is as follows:
Bname = []
similarity = []
for i in Apple.Aname:
        ratio = process.extract( i, Banana.Bname, limit=1)
        Bname.append(ratio[0][0])
        similarity.append(ratio[0][1])
Apple['Bname'] = pd.Series(Bname)
Apple['similarity'] = pd.Series(similarity)

However, there are over 400,000 rows in dataframe Apple and over 700,000 rows in dataframe Banana, my code runs for hours and I still haven't get the result. I wonder how to do it more efficiently? Or at least how could I know the progress of my code? Thanks a lot for your great help in advance!


text:
Q: JS React Native указание типов аргументов функции Есть функция, возвращающая объект:
const Data = (arg0: string, arg1: number) => {
    return {arg0: arg0, arg1: arg1}
};

Этот объект передаётся в другую функцию:
setData(Data("0", 1));

Правильно ли указывать в конструкторе setData тип аргумента таким образом:
const setData = (data: Data) => {...}

Или это говорит лишь о том, что передаётся сама функция, а не её результат?

A: Нет, таким образом указывать тип неправильно, передаваемый объект не является объектом типа Data.
Нужно как-то так:
class Data {
  arg0: string;
  arg1: number;
  constructor(arg0: string, arg1: number) {
    this.arg0 = arg0;
    this.arg1 = arg1;
  }
}
const setData = (data: Data) => {...}

setData(new Data('answer', 42));

A: Javascript - не типизированный язык.
Так что нет, тип аргумента указывать неправильно.
Ваш синтаксис вызывает у моего интерпретатора
Uncaught SyntaxError: Unexpected token :


text:
Q: generating two classes from one table in database using eclipse reverse engineering I tried to make hibernate reverse engineering of a simple table called Student in SQL Server database that contains an identifier as primary key and the name of a student.
Whenever I make eclipse reverse engineering I always get two classes; Student class and StudentId class. The Student class contains just an object of StudentId class. And StudentId contains the identifier and the name.
what is the solution for that?


text:
Q: ExtJS: Get file from Ajax post request response I try to make a way to generate pdf files from my extjs application. When my export button is clicked this Ajax request is fired
Ext.Ajax.request({
    url: 'data/apppdf.php?class=Export&action=composerCSV',
    method: 'POST',
    timeout: 1200000,
    params: {
        id: id
    },

    success: function (response, opts) {
        // i don't know what to do here
    }
});

In my PHP file I make a pdf file using FPDF library like so
$pdf = new FPDF();
// fill my file
return $pdf->Output(null, "rapport" . date('Y-m-d_H:i:s'));

after the success of my request and the end of my script where the file is returned how do it make it available for user (how do i get the open / save popup, with a valid pdf file) ?

A: One way to do this is saving the file on your server, with an "F" as first argument in the output() function:
$folder = '../';
$dt = date('Y-m-d_H:i:s');
$pdf->Output("F", $folder . "rapport" . $dt);

return $folder . "rapport" . $dt;

Since you now know the path and filename, you can return this string and do with it whatever you want in your ajax success function.
Note that I store the datetime first, because it's possible the return time is not the same as when creating the filename.
Check out the Output page in the docs for more information: http://www.fpdf.org/en/doc/output.htm
Your Ajax success function can be something like this:
success: function (response, opts) {
    $('div.yourdiv').html(response);
}

This will replace all html in div.yourdiv with the response from the php file. In this case, the link to your file.
Another example:
success: function (response, opts) {
    location.href = response;
}

This will redirect the user to the file after creation.
This is one way to do it, I'm sure it is possible without saving the files.

A: I usually use this approach, although there may exists better solution:

*

*define browse window

*generate PDF file on server

*download and preview PDF file

ExtJS part:
Ext.define('Test.ReportWindow', {
    extend: 'Ext.window.Window',

    xfilename: '',
    xtitle: '',

    layout : 'fit',
    width: 1200,
    height: 800,
    maximizable: true,

    initComponent: function() {
        var me = this;

        me.callParent(arguments);
        me.title = me.xtitle;
        me.add(
            {
            xtype: "box",
            autoEl : {tag : "iframe", src : me.xfilename}
            }
        );
    }
});

Ext.onReady(function(){

    Ext.Ajax.request({
        url: 'data/apppdf.php?class=Export&action=composerCSV',
        method: 'POST',
        timeout: 1200000,
        params: {
            id: id
        },

        success: function (response, opts) {
            var r = Ext.JSON.decode(response.responseText);
            if (r.success == true) {
                var win = Ext.create('Test.ReportWindow', {
                    xfilename: r.filename,
                    xtitle: 'Show PDF file'
                });
                win.show();
            } else {
                Ext.Msg.alert('Attention', r.errmsg);
            };
        }
    });
});

PHP part:
<?
// Create and save file to disk. Return filename to ExtJS.
// Uncomment next line and generate PDF as you want.
/*
require('fpdf.php');

$filename = 'test.pdf';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output('F', $filename);

// Exception or other way of error check:
if ($something_is_wrong) {
   echo "{
        success: false,
        errmsg: 'Something is wrong.'
   }";
   exit;
}
*/

echo "{
    success: true,
    filename: '".addslashes($filename)."'
}";
?>

Notes: Tested with ExtJS 4.2.


text:
Q: Find the difference between elements in an array and store the results in a new array This is my current code:
#include <stdio.h>

int index_x[] = {0,0,1,0,1,0,0,0,1,0,0,1,0};      // any number of elements
int len = sizeof index_x / sizeof*index_x;

int main(void) {

    int arr[len];
    int j = 0;

    for (int i = 0; i < len; i++)
        if (index_x[i])
            arr[j++] = i;                     // save and advance j only if value is "1"

    for (int i = 0; i < j; i++)               // only print below j !
        printf("%d\n", arr[i]);
}

Output:
2
4
8
11

From this output, I would like to generate another array that is the difference between these elements. In this case the new array would be {2,4,3}. (2-4=2, 8-4=4, 11-8=3).
I am currently struggling with two things:

*

*Saving the array generated from the current code arr[i] as a another array so I can manipulate it for future uses.

*Generating the "differences array". The tricky part is that the number of elements will not be constant so I cannot specify an array size.

A: It may be helpful to break things out into functions.
int indexes_of_non_zero(int *source, size_t len, int **dest) {
    *dest = malloc(sizeof(int) * len);

    int count = 0;

    for (int i = 0; i < len; i++) {
        if (source[i] != 0) {
            (*dest)[count++] = i;
        }
    }

    *dest = realloc(*dest, sizeof(int) * count);

    return count;
}

So we have a function indexes_of_non_zero that takes a source array of ints with size specified by argument len, and then a pointer to an array of ints that will be the destination for our output.
We can naively allocate the same amount of memory to the destination, then loop over the source array and store the indexes of non-zero elements. When we're done, we use count to know the size of destination array. We use realloc to shrink the array to just the needed size. And the key is we return the count so our main function knows how big the destination array is.
We can now create a diffs function to do basically the same thing for the differences.
int diffs(int *source, size_t len, int **dest) {
    *dest = malloc(sizeof(int) * (len - 1));

    for (int i = 0; i < (len - 1); i++) {
        (*dest)[i] = abs(source[i] - source[i + 1]);
    }

    return len - 1;
}

Putting it all together (not copying and pasting the function implementations for terseness) with a main function, and remembering to free the memory we've used, we get:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int indexes_of_non_zero(int *source, size_t len, int **dest);
int diffs(int *source, size_t len, int **dest);

int main(void) {
    int data[] = {0,0,1,0,1,0,0,0,1,0,0,1,0};
    size_t len = sizeof(data) / sizeof(*data);

    int *nz = NULL;
    int *d = NULL;
    int nzc = indexes_of_non_zero(data, len, &nz);
    int dlen = diffs(nz, nzc, &d);

    for (int i = 0; i < nzc; i++) {
        printf("%d\n", nz[i]);
    }

    for (int i = 0; i < dlen; i++) {
        printf("%d\n", d[i]);
    }

    free(nz);
    free(d);
}

And compiling and running it, the output is:
2
4
8
11
2
4
3

A: I changed it to get the differences as direct as possible; the inner loop is very simple.
The size question, first part: I (still) tried to avoid size_t for the input but added some sanity check for the size. Just to show there is a limit.
part two: a first loop to get the sum of true values in advance. Also the booldata array consists of chars and is not called index_x. Index is i.
part three: the diffs VLA gets its exact size, which can be 0 even for huge inputs. Some test could be added here after counting, to rule out a (big) input full of "1".
I added the copying, with message and printout.
#include <stdio.h>
#include <string.h>

char booldata[] = { 0,0,1,0,1,0,0,0,1,0,0,1,0 };

char sz_overf = sizeof booldata > 0xffffL * 0xffff;   // too-big-flag for exiting...
int len = sizeof booldata / sizeof * booldata;        // ...to keep len below size_t

int sum_of_trues (char *booldata, int len) {
    int sum = 0;
    for (int i = 0; i < len; i++)
        if (booldata[i])
            sum++;
    return sum;
}

void print_intarr(int *inta, int len) {
    for (int i = 0; i < len; i++)
        printf("%d\n", inta[i]);
}

int main(void)
{
    if (sz_overf) return 100;                // len might be overflowed
    int unsigned                             // signed provokes VLA warning: 9 gazillions seems ok, but not 18
    dsum = sum_of_trues(booldata, len) - 1;  // Invest a counting loop

    int diffs[dsum],                         // VLA
        di = 0;                              // diffs' index
    int sti = -1;                            // Stored last index containing true

    for (int i = 0; i < len; i++)

        if (booldata[i]) {               // true?

            if (sti >= 0) {              // and is there a left neighbour?
                int diff = i - sti;         // how far away?
                printf("%d\n", diff);       // 1. on-the-fly result
                diffs[di++] = diff;         // 2. for keeps
            }
            sti = i;                     // remember last "true"
        }

    printf("Copying %zu bytes from Diff.-Array\n", sizeof diffs);

    int diffscopy[sizeof diffs];
    memcpy(diffscopy, diffs, sizeof diffs);
    print_intarr(diffscopy, dsum);               // dsum or sizeof diffs

    return 0;
}

output:
2
4
3
Copying 12 bytes from Diff.-Array
2
4
3

The inner loop could look like this w/o multi-option:
if (booldata[i]) {
    if (sti >= 0)                     // and is there a left neighbour?
        diffs[di++] = i - st;         // 2. for keeps
    sti = i;
}

Two arrays and three variables. The rest is needed to make this work.
BUGS: all-false input segfaults. It takes one "true" to get zero diffs...


text:
Q: XSLT: how to print a value if none of checked values match with the value I want to print? XML:
<person>
    <callingName>Name3</callingName>
    <givenNames>
        <givenName>Name1</givenName>
        <givenName>Name2</givenName>
        <givenName></givenName>
    </givenNames>
</person>
<person>
    <callingName></callingName>
    <givenNames>
        <givenName>Name1</givenName>
        <givenName>Name2</givenName>
        <givenName></givenName>
    </givenNames>
</person>

I need to check all the 'givenName' elements if their value matches with the 'callingName' element inside the 'person' element. Empty values shouldn't be counted as a match. If none of the values match, the value of 'callingName' element should be printed. How can I do it?
Here's what I have tried so far:
<xsl:if test="callingName != givenNames/givenName[normalize-space()]">
    <xsl:for-each select="givenNames/givenName[normalize-space()]">
        <xsl:element name="callingname">
            <xsl:value-of select="callingName"/>
        </xsl:element>
    </xsl:for-each>
</xsl:if>

Problem is that everytime values don't match, it prints the value of 'callingName' element. How can I check if all of the values don't match, value is printed only once?

A:
If none of the values match, the value of 'callingName' element should
  be printed.

Try:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <output>
        <xsl:for-each select="people/person[string(callingName) and not(callingName=givenNames/givenName)]">
            <xsl:copy-of select="callingName" />
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

Applied to a well-formed(!) input:
<people>
    <person>
        <callingName>Name3</callingName>
        <givenNames>
            <givenName>Name1</givenName>
            <givenName>Name2</givenName>
            <givenName></givenName>
        </givenNames>
    </person>
    <person>
        <callingName></callingName>
        <givenNames>
            <givenName>Name1</givenName>
            <givenName>Name2</givenName>
            <givenName></givenName>
        </givenNames>
    </person>
</people>

will result in:
<?xml version="1.0" encoding="UTF-8"?>
<output>
   <callingName>Name3</callingName>
</output>

A: The following XSLT matches each person and includes the callingName in the output if there is no matching givenName.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="person">
    <xsl:if test="not(givenNames/givenName[text() = ../../callingName])">
        <xsl:copy-of select="callingName"/>
    </xsl:if>
</xsl:template>
</xsl:stylesheet>

Result:
<callingName>Name3</callingName>
<callingName/>


text:
Q: How to break up a percent increase over time Say I have a number, $x$, and every $12$ hours it's multiplied by $1.2.$ How would I multiply it every $5$ minutes so that after $12$ hours it's increased by the same amount as the first example?

A: HINT:
After $5$ minutes, the number becomes $ax$.
After $10$ minutes, the number becomes $a^2x$.
After $15$ minutes, the number becomes $a^3x$.
After $5n$ minutes, the number becomes $a^nx$ $(n\in\mathbb{Z^+})$.
$12$ hours is $720$ minutes or $5\times 144$ minutes. For $n=144$, can you continue?

A: After 5 minutes, the number is $1.2x$. After 10 minutes, the number is $1.2^2x$. After $5n$ minutes, the number is $1.2^nx$.
After 12 hours, the number has increased by $0.2x$. We want to find $0.2x=m^{144}x-x$. Solving gives $m=\sqrt[144]{1.2}$.


text:
Q: how do i input the previous Genuine product key in to the bios I have an HP desktop computer (HP Prodesk 600G1). A lightning strike fried the main board, so I bought a replacement. How do I input the previous Genuine product key into the bios?

A: You can't add a Product key into the BIOS/UEFI. This can be only done by OEMs with special tools from Microsoft.


text:
Q: Linking a textview with an arraylist and change text when event occurs So basically I have textview, I want the textview to be attached to ArrayList of strings, and then the text will changed based on swipe event.!
How can I make the textview show the next element text when I swipe left or right and when I swipe again it will the show the next element text and so on..!
and when it reaches the final element it will loop back again to the first element.!?
I've tried code in this answer for swipe, but I don't know how show texts from ArrayList..!?
Can this be accomplished..!?

A: int counter = 0;
@Override
public void onSwipeRight() {
super.onSwipeRight();
if(counter == arraylist.size()}{
      counter =0;
}
 textview.setText(arraylist.get(counter));
 counter++;
});

Try this.


text:
Q: I am having difficulty getting a new version of a 3rd party SDK to import into Android Studio I am having difficulty getting a new version of a 3rd party SDK to import into Android Studio.
In the earlier version they released .jar and .so files which I copied into /lib and /jniLibs and then added the lib files into the Android Studio app and everything worked.  The app ran, used the libraries and all was good in the world.  Recently a new version of this SDK was released but in this new release they have resource files (but they are not compiled into the jar/so files; there is a $Rstring.class files that they say I should import.  I've now spent days copying into various locations in the app project with no luck and the missing strings result in crashes when calling their SDK.
OK, I figure I'd try to import their SDK folder (which is how they document to do it if you are using Eclipse).  Well, no matter what I've tried and after selecting the folder or SDK's project file I get a dialog asking for the Eclipse workspace and a list of what appears to be source file names.  I can't get past this dialog because obviously I don't have their files.
Has anyone run into this and found a solution; perhaps I'm missing something in the process but after spending the better part of 3-4 days trying and searching and trying more things I'm hopeful for help from the community.

A: OK, I found the answer and it was a combination of issues in how this particular 3rd party distributed the SDK and not fully understanding the menu.
The 3rd party in question packaged the SDK with the output files of the build as well as files that needed to be imported making an import alone to not work.
Combine this with menu confusion: File->Import Module is NOT the same as New->Modules->Import Existing Project only added to the confusion.
The solution ended up being to use the File->Import Module which appears to be a very different operation and once done most of the issues where solved.  It solved the main issues I asked above which was missing resourced.
Still missing was the library (.jar) files which had to me copied into the app's lib folder and "added as library" but the .SO files did not need to be copied and in fact doing that resulted in a duplicate files warning.
I'm not sure I can fully explain what happened but what I think happened is that the "module" was where the app read the .so and string resources from but was unable to load the .jar files because (I suspect) these files where not part of the module but rather where outputs of building the source and it was removing the source files which caused the inability of the new->Module->Import to fail.
Hopefully this makes sense or at least give someone an idea of what to look for when/if they run into a similar issue.


text:
Q: How to add html email code template to javascript to send personalized mails using googlesheet Hello friends at SOF am new here i have an issue i believe can be sorted here. Am am using google sheet to send email. I have a working code that is sending personalized emails to individual using google sheet and it works fine. the issue is that i want to add an html email template to the message instead of just plan text. Here is a picture of my setup below which is working fine presently but dont know how to add my html email template code to it as the mail message body. I marked the message body in yellow i want to replace that message with my html email code template. I also place sample codes for you to copy and try out you only need create the google spreadsheet and put emails field at your end to test execution.
VIEW SHEET AND SCRIPT FILE HERE
VIEW HTML EMAIL CODE TEMPLATE HERE

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // Start at second row because the first row contains the data labels
  var numRows = 3; // Put in here the number of rows you want to process

  // Fetch the range of cells A2:B4
  // Column A = Email Address, Column B = First Name
  var dataRange = sheet.getRange(startRow, 1, numRows, 2)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
   var row = data[i];
   var emailAddress = row[0]; // First column of selected data
   var message = "Hey " + row[1] + ",\n how are you doing today?"; // Assemble the body text
   var subject = "Sending emails from a Spreadsheet";
   MailApp.sendEmail(emailAddress, subject, message);
  }
}


text:
Q: Models not working with db.collection.insert via mongoose I started with the very basics and the .save function where i use my models to autogenerate a unique id as well as the an auto generated timestamp, everything was fine.
then i tried to save an entire array to the database and this is the query i ended up wi
    let instagram = new Instagram();
let data = req.body.url.split('\n');
let dataArray = [];
data.forEach(datum => {
    split1 = datum.replace('https://www.instagram.com/', '');
    split2 = split1.replace('/', '');
    time = Date.now;
    var datetime = new Date();
    dataArray.push({
        igurl: datum,
        igid: split2,
        owner: req.user._id,
        cdate: time,
        status: "New"
        });
});

instagram.collection.insert(dataArray, function(err,docs){
    if(err){
        req.flash('danger', 'error = ' + err);
        res.redirect('/instagram/add');
    } else {

        req.flash('success', 'IG URL has been added');
        res.redirect('/instagram');
    }
    });
});

the problem is that uid is never generated while using the .collection.insert function because i think the model is never invoked or is overridden in this scenario...
how do i bulk insert via the normal model route so that my model defaults can be triggered.


text:
Q: What would happen internally when "Fish f = new BlueFish();"? Suppose we have:
  1 public class DynamicDispatch {
  2     public static void main(String[] args) {
  3         Fish f = new BlueFish();
  4         f.speak();
  5     }
  6 }
  7
  8 abstract class Fish {
  9     abstract String speak();
 10 }
 11
 12 class BlueFish extends Fish {
 13     String speak() {
 14         return "I am a blue fish";
 15     }
 16 }
 17
 18 class CatFish extends Fish {
 19     String speak() {
 20         return "I am a cat fish";
 21     }
 22 }

Question:

*

*From the assembly, a BlueFish object was created. But why the javac didn't realize that BlueFish.speak() should be invoked?

*During runtime, how does the JVM handle invokespecial #4, so that the right target wil be called?
FYI, the javap -c output is:
Compiled from "DynamicDispatch.java"
public class DynamicDispatch extends java.lang.Object{
public DynamicDispatch();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   new #2; //class BlueFish
   3:   dup
   4:   invokespecial   #3; //Method BlueFish."<init>":()V
   7:   astore_1
   8:   aload_1
   9:   invokevirtual   #4; //Method Fish.speak:()Ljava/lang/String;
   12:  pop
   13:  return

}

A: Answer:

*

*javac doesn't try to realize it, becuase it would be easy to make a situation where javaccouldn't find out as easily, or even at all. You might find out whether to use CatFish or BlueFish using user input, for example.

*For this, see BevynQ's comment. I'm surprised he didn't add it as an answer.


text:
Q: why can't I see the frame number in beamer after my Mac update? I have made a presentation with beamer and could see the frame number but i updated my MacBook to Mohave last week and I can't see the frame number after that? what should I do?I didn't change anything.
\documentclass[8pt,mathserif]{beamer}
\mode<beamer>
\mode<presentation>
%---------------------------------
\usepackage{xcolor,colortbl}

\newcommand{\mc}[2]{\multicolumn{#1}{c}{#2}}
\definecolor{Gray}{gray}{0.85}
\definecolor{LightCyan}{rgb}{0.88,1,1}
%-------------------------------------------
\usepackage{hyperref}
\usepackage{multimedia}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{soul}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{hyperref}
\usepackage{times}
\usepackage{empheq}
\usepackage[most]{tcolorbox}
\usepackage{textpos}
\usepackage{fancybox}
\hypersetup{pdfpagemode=FullScreen}
\newcommand{\comments}[1]{}
\logo{\includegraphics[scale=0.05]{logo1}}
\usetheme{Luebeck}

\usefonttheme[onlylarge]{structuresmallcapsserif}
\setbeamertemplate{navigation symbols}{}
\setbeamercovered{dynamic}

\graphicspath{{./res/}}
\usefonttheme[onlysmall]{structurebold}
\setbeamerfont{title}{shape=\itshape,family=\rmfamily}
\setbeamercolor{title}{fg=red!80!black,bg=red!20!white}
\title{\bf{ Effective dynamics}}
\author[SS]{ \textcolor{blue}{SS}}
 \institute[ BB]{
  Supervisor:\\ Dr. F}
\beamertemplatenavigationsymbolsempty

\setbeamerfont{page number in head/foot}{size=\small}
\setbeamertemplate{footline}[frame number]

\begin{document}
\begin{frame}<handout:0>
\titlepage
\end{frame}
\begin{frame}
\frametitle{Outline}
\tableofcontents[pausesections]
\end{frame}
\end{document}


text:
Q: What is the great advantage in "migrations" used by many PHP frameworks? Many PHP frameworks (becoming from Ruby) have the ability to use "migrations" and "seeding".
An example is Laravel Framework that have a documentation about that.
But I can't figure out how can it be useful.

A: It's usefulness comes from the ability to manage a web applications database much more efficiently.  Managing even a small site with 10-20 database tables becomes as simple as making the migrations files, then running a command.  Saving both time on syntax typed, and making DB tables.
tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id )
);

becomes (laravel)
Schema::create('tutorials_tbl',function($table) {
    $table->increments('id');
    $table->string('tutorial_title');
    $table->string('tutorial_author');
    $table->timestamps();
}

Now all I need to do to create the table is
php artisan migrate

Say I need to edit that table
php artisan migrate:rollback

Edit migration file and migrate.
It makes developing more efficient, creates less hassle, makes it easier to deploy on different environments.  And seeding aids in that by giving you the ability to easily create database info that can be pushed to the DB just as easily.


text:
Q: marble-touch offline map viewer fails to start Ubuntu 14.04 with Unity, marble-touch 4:4.13.3-0ubuntu0.1. It doesn't start:
$ marble-touch
qrc:/main.qml:13:1: Type MarbleWindow unavailable
qrc:/MarbleWindow.qml:11:1: module "com.nokia.meego" is not installed

Seems like the bug '14419 marble-touch does not open a window' was fixed:
https://bugs.mageia.org/show_bug.cgi?id=14419
But I can't find a packaged version with the fix (and how to build is unclear). In Vivid there is a marble-touch package with a weird version '4:14.12.3' which gives the same error.
Any help?

A: Marble Touch shouldn't be packaged on the Desktop - the target device for this application is the Nokia N9 cellphone :-) .
Please use Marble or Marble-Qt instead - on the terminal it should be accessible either via "marble" (KDE version) or "marble-qt" (Qt-Only version without KDE dependencies).


text:
Q: EventBridge Scheduler can't update ECS Service I want to shutdown\startup ECS tasks by schedule for saving costs.
I decided to use EventBridge Scheduler to update service desiredTaskCount to 0 and back to the desired amount.
The problem is the console interface doesn't provide any clues how to pass the correct data. it just promts for a JSON object in the following format:

And this is completely different from API description for UpdateSerivce operation.
So I'm not sure what's the correct way of passing service ARN and the properties I want to update.
I've tried out several formats but it doesn't work so far:

The is no any clarifications or examples in the documentation regarding this.

A: I was missing "Cluster" in the request.


text:
Q: Is the localization of an injective cogenerator an injective cogenerator? We know that in Noetherian rings any localization of an injective module is again an injective module.  Is the localization of any injective cogenerator again injective cogenerator?

A: Certainly not.  For instance, over $\mathbb{Z}$, if you localize any module with respect to the multiplicative set $\mathbb{Z}\setminus\{0\}$, you get a $\mathbb{Q}$-module.  A $\mathbb{Q}$-module can never be a cogenerator, since no torsion module can map nontrivially to it.
If you ask only for the localization to be a cogenerator for modules over the localized ring, then as Slade commented, this is still not true.  For instance, $\mathbb{Q}/\mathbb{Z}$ is an injective cogenerator over $\mathbb{Z}$, but $\mathbb{Q}/\mathbb{Z}\otimes\mathbb{Q}=0$ is not an injective cogenerator over $\mathbb{Q}$.


text:
Q: How to polygonise a binary raster with python? I already asked this in StackOverflow, but maybe it's better here. I have a ndvi raster that I binarized (I put my threshold at 0.35) with a script python and I wanted to polygonize this raster, in order to get ndvi into polygones, to store them after in a database. I found and used this code :
import rasterio
import rasterio.env
from rasterio.features import shapes
import fiona
mask = None
with rasterio.Env():
    with rasterio.open('binarized_ndvi.tif') as src:
        image = src.read()

    results = (
    {'properties': {'raster_val': v}, 'geometry': s}
    for i, (s, v)
    in enumerate(
    shapes(image, mask=mask, transform=src.transform)))

    with fiona.open(
    'ndvi_shapefile.shp', 'w',
    driver='Shapefile',
    crs=src.crs,
    schema={'properties': [('raster_val', 'int')],
    'geometry': 'Polygon'}) as dst:
        dst.writerecords(results)

But all I get is a shapefile, with only one polygon whose shape is the same as my raster, like if only the first elment of the raster was taken into account ...
I can't send you my raster, it's too big.

A: I've used this pattern, based on this and this. I'm not familiar with rasterio.Env - a quick look at the Docs suggests it's to access AWS. Main differences with your script are creating a mask and and having everything from results = statement tabbed in so it's happening with the open raster.
import fiona
import rasterio
from rasterio import features

with rasterio.open('path_to_your_raster') as src:
    image = src.read(1)
    #Make a mask
    mask = image != 1
    #iterate over shapes.
    results = (
        {'properties': {'raster_val': v}, 'geometry': s}
        for i, (s, v) in enumerate(
            shapes = features.shapes(image, mask=mask, transform = src.transform)))

    with fiona.open(
            'ndvi_shapefile.shp', 'w',
            driver='Shapefile',
            crs=src.crs,
            schema={'properties': [('raster_val', 'int')],
            'geometry': 'Polygon'}) as dst:
        dst.writerecords(results)


text:
Q: Ordinal identifier issue - QTP There are 4 static text on page
jWin.JavataStaticText("toolkit class:=nz.vdi","index:=0").GetROProperty("attached text")
jWin.JavataStaticText("toolkit class:=nz.vdi","index:=1").GetROProperty("attached text")
jWin.JavataStaticText("toolkit class:=nz.vdi","index:=2").GetROProperty("attached text")
jWin.JavataStaticText("toolkit class:=nz.vdi","index:=3").GetROProperty("attached text")

When I run this script then I get output in following way
VM
Host
Host Server
Storage Volume

When I run the same script after 4-5 mins then I output sequence get changed
Host Server
VM
Storage Volume
Host

Why is it happening? Due to this problem I am not able to perform expected task

A: The Index selector is the last fall-back that UFT uses when it can't uniquely identify an object. If you have a better way to identify the object (e.g. by using the "attached text" property) you should used that.
Basically what Index means is "from the set of objects described by this description return the Nth one" so if UFT gets the objects in a different order you will get different objects for the same Index.
I'm not familiar with Java so I don't know what order the objects are returned. Also I don't know what your use-case is but I'm pretty sure you can find a better way to verify your conditions.
One thing that may be helpful is using the Location selection property which depends on the relative location of the objects and may be more consistent in your case. The location selector orders objects first by their x coordinate and then by y.
For i = 0 to 3
  jWin.JavataStaticText("toolkit class:=nz.vdi","Location:=" & i).GetROProperty("attached text")
Next


text:
Q: Congruences and Primes Show that if $p$ is an odd prime, with $p = 3 \pmod{4}$, then
$$
(\mathbb{Z}_{p}^{*})^4 = (\mathbb{Z}_{p}^{*})^2
$$
More generally, show that if $n$ is an odd positive integer, where $p = 3 \pmod{4}$ for each prime $p \mid n$, then:
$$
(\mathbb{Z}_{p}^{*})^4 = (\mathbb{Z}_{p}^{*})^2
$$
I was thinking of using Fermats two squares theorem, but I dont really know how to approach the problem.
Any help would be great.
Thanks

A: Although one can prove it directly as in mercio's answer, it is insightful to deduce it as follows. Lagrange proved (1769) that in a group of odd order $\rm\,2n+1,\:$  every element is a square, since
$$\begin{eqnarray}\rm\, 1 &=&\rm a^{2n+1}\quad\ \text{by Lagrange's Theorem}\\  \rm \Rightarrow\ a &=&\rm a^{2n+2} = (a^{n+1})^2\end{eqnarray}$$
In a field $\rm\,\Bbb F\,$ of order $\rm\, q = 4n+3,\,$ the subgroup $\rm\,S\,$ of squares has odd order $\rm\,(q\!-\!1)/2 = 2n + 1,\,$ hence every square is a square (of a square), $ $ i.e. a fourth power; $ $  i.e. $\rm\  t \in S\:\Rightarrow\: t = s^2,\,\ s\in S,\ $ and, by definition, $\rm\:s \in S\:\Rightarrow\:s = a^2,\ a\in \Bbb F,\:$ hence $\rm\, t = s^2 = (a^2)^2 = a^4.$
Remark $ $ Lagrange's result is a special case of a $\rm\, k$'th power criterion that frequently proves handy. This criterion has a simple conceptual proof (alas, often overlooked). Suppose that we know that $\rm\, g^n = 1,\, $ so exponents on $\rm\,g\,$ can be interpreted $\rm\,mod\ n\!:\, i \equiv m\:$ $\Rightarrow$ $\rm\,g^i = g^{m}.\  $ We, $ $ consequently, $ $
see clearly that $\rm\,g^i\,$ is a $\rm\,k$'th power if $\rm\ mod\ n\!:\, k\mid i,\:$ i.e. $\rm\ i\equiv jk,\,$ so $\rm\,g^i = g^{jk} = (g^j)^k.\,$ By $\rm\color{#C00}{Bezout}$
$$\rm k\,|\, i\:\ (mod\ n)\!\iff\! \exists\,j\!:\ jk\equiv i\:\ (mod\ n)\!\iff\! \exists\, j,m\!:\ jk \!+\! mn = i\color{#C00}{\!\iff\!} (k,n)\,|\, i$$
Hence we have conceptually derived a proof of the following
Theorem $\rm\ \ \ g^n = 1,\,\ (k,n)\mid i\:\Rightarrow\: g^i\,$ is a $\rm\,k$'th power $\ \ $ [Easy $\rm\,k$'th Power Criterion]
Proof $\rm\ \  By\ Bezout,\,\ (k,n)\mid i\:\Rightarrow\:k\mid i\,\ (mod\ n) \Rightarrow\:i\equiv jk\,\ (mod\ n)\Rightarrow\: g^i = g^{jk} = (g^j)^k$
Note $\,\ $ That $\rm\ \ k\,|\, i\:\ (mod\ n)\!\iff\! (k,n)\,|\, i\ \ $ frequently proves conceptually handy, $ $ e.g. see here. $\ $ The reason behind this will become clearer when one studies cyclic groups and (principal) ideals.

A: Hint : By Fermat's little theorem, $x^{p-1} \equiv 1 \pmod p$.
In particular, $x^2 \equiv x^{p+1} = \left(x^\frac{p+1}4\right)^4$


text:
Q: Fastest way to convert object to string Python I have a ~250,000 row dataset I am pulling from Oracle DB. The main data I am concerned with is a text field that is pulled as a HUGECLOB object. Storing my data to a CSV took quite a bit of time, so I decided to switch to Feather via: Pandas read_csv speed up
There was some other question that used feather too, but I cannot find it. I tried to_hdf, but for some reason that did not work. Either way, to get my query results to work with Feather, the text column must be converted to string. So I have:
SQLquery = ('SELECT*')
datai = pd.read_sql(SQLquery, conn)
print("Query Passed, start date")
datai['REPORTDATE'] = pd.to_datetime(datai['REPORTDATE'], format='%m-%d-%Y')
print("Row done, string")
datai['LOWER(LD.LDTEXT)'] = datai['LOWER(LD.LDTEXT)'].apply(str)
print("Data Retrieved")
print("To feather start")
datai.to_feather(r'C:\Users\asdean\Documents\Nuclear Text\dataStore\rawData2.feather')
print("Done with feather")

Note: I put a bunch of print statements because I was trying to figure out where it got hung up.
The text column is identified as datai['LOWER(LD.LDTEXT)']. Some of the rows contain quite a bit of text (~ a couple paragraphs). The string conversion TAKES FOREVER (or may not even be completing). I did not have this problem when I read it from an old CSV (old data, no longer use, we updated the query, etc).
I have tried all the common ways of doing this with astype(str), map(str), apply(str), values.astype(str) with no success of speeding it up to a reasonable (less than 1 hour) pace. Is there a way to do faster object to string conversions? Is there a library I am missing here? Is there a faster way through Oracle/HUGECLOB? How can I speed this up?

A: I'm assuming the data is stored in the DB as the Oracle CLOB datatype. How big is the data? If the strings are < 1GB make sure they are being fetched as strings (not streamed) in the lower layer https://cx-oracle.readthedocs.io/en/latest/user_guide/lob_data.html#fetching-lobs-as-strings-and-bytes


text:
Q: How to solve this system to model a simple betting system? What I am asking is just for my personal curiosity.
I was thinking about the betting system (ex. football). For example let's consider just this possibilities to bet:
Win of Team A      Draw      Win of Team B
2,0                4,0       8,0

As you know, if you bet 10€ on Win of Team A, and it wins, you get 20€ back.
I was wondering if you could bet on all three possibilities (with the right distribution of money) and be sure to get a reward > 0€. My common sense said "Of course not", otherwise everyone could always win.
I don't have a lot of Math knowledge, but I tried to formalize the problem to see why, analitically, it is impossible to do so.
Here is my attempt, but I can't go no further:
Win of Team A multiplier: a (constant)
Draw multiplier: d (constant)
Win of Team B: b (constant)

Money to bet on Win of Team A: x (variable)
Money to bet on Draw: y (variable)
Money to bet on Win of Team B: z (variable)

The system I want to solve (Is it the right way to express "Always win betting onto the all three?")
$$\begin{cases} ax -(x + y + z) > 0 \\ dy - (x + y + z) > 0 \\ bz - (x + y + z)> 0 \\ x \neq 0 \\ y \neq 0 \\ z \neq 0 \end{cases}$$
This system (to me) means: if you bet for the Win of Team A and you betted for the Others, you get all your betted money back plus something won... (the same for Draw and Win of Team B).
Then:
$$\begin{cases} ax > (x + y + z) \\ dy > (x + y + z) \\ bz > (x + y + z) \\ x \neq 0 \\ y \neq 0 \\ z \neq 0 \end{cases}$$
And:
$$\begin{cases} \frac{y+z}{x} > a-1 \\ \frac {x+z}{y} > d-1 \\ \frac {x+y}{z} > b-1 \\ \end{cases}$$
At this point I know that my knowledge of math is finished. I tried to trasform the system but I really can't solve it. I never studied disequations with 3 variables (nor 2, sigh). How can i solve it and verify for which values of x, y, z it is solvable?

A: Suppose you have $n$ mutually exclusive outcomes with payoffs $p_1, \ldots, p_n$.  (In your case $n=3$ and $p_1=2$, $p_2=4$, and $p_3=8$.)  I'll show that you can "game the system" to always win precisely when
$$S=\frac1{p_1}+\frac1{p_2}+\cdots+\frac1{p_n}<1.$$
This holds in your case, as $1/2+1/4+1/8<1$; the argument below shows how to place your bets and compute your guaranteed profit.
Assume you're going to distribute a bet $B$ over the $n$ outcomes, and assume an adversary is going to control the outcome after you place your bet.  Thus you want to maximize (over all distributions of the bet) the minimum payoff (over all $n$ possible outcomes).  We'll show that in the optimal strategy, the bet on outcome $i$ is proportional to $1/p_i$.  (More precisely, the bet on outcome $i$ is $B/(S p_i)$, so that the sum of the bets is $B$.)
If the outcome is $i$, your gross payoff is $p_i\cdot B/(S p_i)=B/S$ which is actually independent of $i$.  Since you've paid $B$ to play, your profit is guaranteed to be
$B/S - B$, which is positive exactly when $1/S-1>0$, i.e. when $S<1$.
Let's see why this is true.  Finding the optimal strategy is a linear programming problem, and you can do it with matrices and all that, but it's really easier.  Concentrate on outcomes $i$ and $j$; suppose you've bet $x_i$ and $x_j$ on those outcomes.  Your payoff for that investment of $x_i+x_j$ will be
$$\min (x_i p_i, x_j p_j).$$  The maximum of this payoff, subject to $x_i+x_j$ being fixed, occurs when $x_i p_i=x_j p_j$.  Therefore, no matter what your investment in other outcomes, if you haven't chosen $x_i:x_j$ in proportion to $1/p_i:1/p_j$, you can improve your payoff.  Since $i$ and $j$ are arbitrary, the optimal strategy must set $x_i$ proportional to $1/p_i$; thus
$$x_i=\frac B{p_i S}$$
so that the sum of the bets is $B$.
In your specific case, $1/S=1/(1/2+1/4+1/8)=8/7$, so your profit will be $B/7$ if you place a total bet $B$.  For example, if you bet $4$, $2$, and $1$ respectively, where the payoffs are $2$, $4$ and $8$ respectively, your total bet is $7$, and you're guaranteed to win $8$.


text:
Q: Send post request from server to another by curl I have 2 PHP files, each one in separated server.
For example:

*

*mainServer/default/index.php

*externalServer/request.php

The first file code (index.php):
echo $_POST['file_name'];

The Second file code (request.php):
$data = array(
    'file_name' => "file.zip",
    'file_size' => 5000
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://mainServer/default/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

What I want is send the $data array from externalServer/request.php to mainServer/default/index.php, but there is an error Notice: Undefined index: file_name in default\index.php on line 13.
How to get the $data array to for instance to print an item ?

A: I found the mistake in your code. Sending an associative array directly (what you did) is not a correct way. You need to send the array as a string.
Example
This->
$data = array(
    'file_name' => "file.zip",
    'file_size' => 5000
);

Should be This->
$data = "file_name=file.zip&file_zipe=500"

Now when you'd sent the data, you'd be able to fetch it via $_POST. You can let php do the array to string conversion using http_build_query.
$data = array(
        'file_name' => "file.zip",
        'file_size' => 5000
    );
$string = http_build_query($data);
//output = file_name=file.zip&file_size=5000

Read more about http_build_query Here


text:
Q: Google Maps V3 marker with label How can I add label to my marker if my markers are populated on ajax success each result.
map.gmap('addMarker', { 'position': new google.maps.LatLng(result.latitude, result.longitude) });

I tried like this, but with no success:
map.gmap('addMarker', {
    'position': new google.maps.LatLng(result.latitude, result.longitude),
    'bounds': true,
    'icon': markerIcon,
    'labelContent': 'A',
    'labelAnchor': new google.maps.Point(result.latitude, result.longitude),
    'labelClass': 'labels', // the CSS class for the label
    'labelInBackground': false
});

A: Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.
You can now create your label marker like this:
var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude),
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.
Update October 2016:
This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

A: The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
    this.setMap(g.map);
};

Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
        this.MySpecialDiv               = document.createElement('div');
        this.MySpecialDiv.className     = 'MyLabel';
        this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers

}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
      var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
            $('.myLabel')
            .css({
                'top'   : position.y + 'px',
                'left'  : position.x + 'px'
            })
        ;
}

That's the gist of it, you'll have to do some more work in your specific implementation.

A: If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };

    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

A: I doubt the standard library supports this.
But you can use the google maps utility library:
http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker = new MarkerWithLabel({
   position: myLatlng,
   map: map,
   draggable: true,
   raiseOnDrag: true,
   labelContent: "A",
   labelAnchor: new google.maps.Point(3, 30),
   labelClass: "labels", // the CSS class for the label
   labelInBackground: false
 });

The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers

A: You can now add a class name to the marker label via google.maps.MarkerLabel interface.
For example:
const marker = new google.maps.Marker({
      position: position_var,
      map,
      label: {
        text: 'label text',
        className: "my-label-class",
      },
      title: "Marker Title",
});

For a full list of options see the google map reference doc:
https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel


text:
Q: Why isn't munin's apache_accesses report accesses? I have the ExtendedStatus enabled:
$ grep ExtendedStatus
/etc/apache2/mods-available/status.conf:ExtendedStatus On

But the "munin suggest" says it's still off:
root@SERVER:/etc/apache2# munin-node-configure --suggest|grep apache
apache_accesses            | yes  | no [ExtendedStatus option for apache mod_status is missing on port 11111]
apache_processes           | yes  | no
apache_volume              | yes  | no [ExtendedStatus option for apache mod_status is missing on port 11111]
# The following plugins caused errors:
# apache_processes:
#   Junk printed to stderr
# ip_:
#   Nothing printed to stdout
...

Maybe the problem is that there is additional configuration if apache is listening on port 11111? I already restarted apache, munin. Using Ubuntu 12.04.5 LTS with apache2 2.2.22-1ubuntu1.7.
UPDATE#1:
Apache is configured to listen on port 11111:
root@SERVER:~$ head -1 /etc/apache2/sites-enabled/000-default
<VirtualHost *:11111>
root@SERVER:~$

UPDATE#2:
The "/etc/munin/plugin-conf.d/munin-node" file has the:
[apache_*]
env.ssl yes
env.ports 11111

UPDATE#3:
If I use a:
wget --no-check-certificate https://localhost:11111/server-status?auto -O -

On the server, then I get 401, since the users can only auth via LDAP.. maybe this is the problem.. how to allow the server-status on 127.0.0.1 before the LDAP auth?
UPDATE#4:
I tried to modify the "/etc/munin/plugins/apache_accesses" file..:
...
my $URL = exists $ENV{'url'} ? $ENV{'url'} : "https://usernamehere%40xx.foo.com:password@127.0.0.1:11111/server-status?auto";
#my $URL = exists $ENV{'url'} ? $ENV{'url'} : "http://127.0.0.1:%d/server-status?auto";
my @PORTS = exists $ENV{'ports'} ? split(' ', $ENV{'ports'}) : (11111);
...

and then..
root@SERVER:/etc/munin/plugins# ./apache_accesses autoconf
Possible unintended interpolation of @127 in string at ./apache_accesses line 90.
no (Port 11111: Can't connect to usernamehere                                   11111.foo.com:password.0.0.1:11111)
root@SERVER:/etc/munin/plugins#

The username contains a "@", but I escaped it to %40..:
usernamehere%40xx.foo.com


text:
Q: Patterns/Best Practices version of Stack Overflow I've been thinking about this for some time now. Stack Overflow is great for looking up answers to specific (mostly long tail) questions. Sometimes you find bits and pieces of what you need, and put them all together to form a good solution. There are other times where the top answers have security holes or other major issues, or simply answer the question directly without going into other things the person should consider.
While most projects/websites use the same few patterns for authentication, database connections, commenting system, etc. Developers keep recreating the wheel with every new project.
What I would love to help build is a knowledge base that's up to date, with different [patterns/best practices/full examples] to problems using the Stack Exchange system. Each solution would be up/down voted, the same as an answer is now for a question. Users could easily browse all the different patterns prior to starting their project and learn the most recommended solutions (Side benefit of preventing the same questions being asked about simple things on Stack Overflow). The same problem/question can have multiple version for different languages/platforms/technologies. For example the web authentication pattern would have a version for ASP.NET, MVC, PHP, Ruby, etc. using a Database, Active Directory, OpenID, etc.
Also just having a way to see what solutions different projects have implemented would be great. How does the login/authentication system of Stack Overflow differ from Facebook, Google, Digg, Reddit, etc? Which solution has what advantages?
I've thought about starting a site with this idea, but with a full time job and a startup that takes up the rest of my time, I don't have the capacity right now. Because this fits in well with Stack Overflow, I figured this is a good place to get the idea out there.
Is there anything that exists like this already? Does anyone else want this resource to be created?

A: The place to start new sites is Area51, but there is already a site that says it for best practices, Code Review.
From their FAQ:

What kind of questions can I ask here?
Code Review - Stack Exchange is for sharing code from projects you are
  working on for peer review. If you are looking for specific feedback
  about…
Code correctness
Best practices and design pattern usage in your code
Application UI
Security issues in a code snippet, etc.
The performance of your code

and your question is not about …
Tools, best practices, improving, or conducting code reviews
Trouble-shooting, debugging, or understanding code snippets
Higher-level architecture and design of software systems

… then you are in the right place!


text:
Q: Forward Firebird database to another network Ive got a problem by connecting two shop applications with one database. The problem is they are in two different Networks...
Lets say we have network A:
192.168.1.10 = Master Instance -> uses fdb -> localhost:3065
192.168.1.20 = Other Instance  -> uses fdb -> 192.168.1.10:3065

Now i've got a secound newtwork B:
192.168.1.5  = Other Instance  -> uses fdb -> 192.168.1.10:3065

So the problem is i cant configure an instance to use an external ip, it can only use the internal range.
Is there a way how i can forward the Master Instance to Network B?
I've tried with Hamachi but its extremely unstable..
Thanks for your Help Guys :)

A: First of all Ping them from Each other.... If that works then the problem is with Firebird instance (it is disabled by default), right now I can assume that you are in the same network at all.. and you will ping all of the networks very smoothly so the problem will be with fire-bird.. or in 2nd case tell me the Sub-net Mask... or write your I.P with Network Bits like "192.168.1.10/24...25....26" Then i can tell you what is the issue....
Hope this explains


text:
Q: how to set Hibernate L2 cache with Hazelcast for two different apps, with different packages` names and Entity names I am using Hazelcast as 2L cache provider for hibernate.
My problem is that im trying to use Portable serialization, but by default when Application works it uses CacheKeyImpl class from hazelcast.hibernate.region package for Key serialization. How to disable that way of serialization?
CacheKeyImpl contains private String entityOrRoleName; field, it stores full path to the Entity, and that is why I cant set Hazelcast cache to work properly for two different Applications (because in different projects that deals with the DB, the path to the Entity is different, so thats why Keys of the same entity has different values after serialization). Do someone face the similar problem? Thanks in advance.


text:
Q: How many ways can the athletes line up? 8 athletes are to be lined up for a race. 2 of athletes are from Zambia, and one each from
Angola, Botswana, Cameroon, DR Congo, Egypt and Ghana. The two Zambian athletes are not
allowed to be next to each other, neither are the Ghanian or Congolese athletes allowed to be
next to each other.
How many ways can the athletes line up?

A: There are $8!$ to arrange athletes without restriction.
There are $2\cdot7!$ was to arrange athletes with the Zambians next to one another.
Also, there are $2\cdot7!$ with the Congolese next to the Ghanaian.
There are $4\cdot 6!$ ways with both the Zambians together and the Congolese next to the Ghanaian.
$8! - 4(7!-6!)$

A: Total number of allocations:$8!$. Number of ways to put (e.g. A and B) together: $F_2 = 7 \times6!2!$. Same for the second pair. Obviously we overcounted the cases when both pairs are together: these are
$$
F_3 = 2 \times 5 \times 4! \times 2! \times 2! +\\
5 \times 4 \times 4! \times 2! \times 2!
$$
The first line is the case when one of the pairs takes slots 1,2 or 7,8. The second line is for all other cases.
Finally, $8! - 2 \times F2 + F3$ is your solution.


text:
Q: How to build a path with a base path and relative path? Suppose I am writing a function to build a file path given a base path and relative path like that:
def buildPath(basePath: String, relativePath: String) = ???

buildPath("a/b/c/d", "x")          // a/b/c/x
buildPath("a/b/c/d", "../../x")    // a/x
buildPath("a/b/c/d", "../../../x") // x
buildPath("a/b/c/d", "../e/x")     // a/b/c/e/x

I can write buildPath using java.io.File:
def buildPath(basePath: String, relativePath: String): String = {
  val baseFile = new java.io.File(basePath)
  val toRemove = baseFile.getAbsolutePath.dropRight(baseFile.getPath.length)
  val file = new java.io.File(baseFile.getParentFile, relativePath)
  file.getCanonicalPath.drop(toRemove.length)
}

This implementation works but looks ugly. How would you improve it ?

A: new java.io.File("/" + basePath, relativePath).getCanonicalPath


text: Q: How can I fix an Ubuntu partition that gets stuck on the motherboard splash screen? I have Ubuntu 20.04 and recently did an update with sudo apt update then sudo apt upgrade. Since then, once I select Ubuntu from the GRUB loader, the machine gets stuck on the motherboard splash screen (Aorus). I've tried going into advanced mode alternate kernels and repairing packages, but nothing has worked.


text:
Q: In Soy (Closure) templates, how can I print an expression that might be undefined at runtime? Let's say the template model contains a map called $myMap whose keys are unknown at compile time. If my template attempts to print a map entry using {$myMap[$someValidKey]}, all is fine. However if I try to print using {$myMap[$someInvalidKey]}, the template fails to render and instead throws this error:
In 'print' tag, expression "$myMap[$someInvalidKey]" evaluates to undefined.
How can I tell the template to simply print nothing if that expression is undefined, i.e. no such key exists in the map?

A: I just verified that you can conditionally wrap it:
{if $myMap[$someInvalidKey]}{$myMap[$someInvalidKey]}{/if}

A: You can use {$myMap[$someInvalidKey] ?: ''} to fall back to printing nothing (empty string) in the case that it's undefined.


text:
Q: Spherical Impostors in three.js I'm working to port a native OpenGL application to WebGL by using the three.js framework. I'm stumbling on the implementation of spherical impostors.
Spherical Impostors are basically quads (or two triangles) that are rendered in a way that they always face the camera (much alike billboards).
By employing custom vertex and fragment shaders, for every point on the rendered quad, a new position and normal are generated in a way that emulates a sphere. For a more detailed description you can check out the following link: [link broken]
What is a possible strategy to port this feature in Three.js?

A: THREE.Sprite are spherical impostors.
http://threejs.org/examples/#webgl_sprites
Edit: I clearly didn't have a proper understanding of what spherical impostors are. Please, disregard this answer. We haven't implemented those yet.


text:
Q: Swift How to add the shouldReceiveTouch on Switch? I'm trying to add in my project shouldReceiveTouch on the UISwitch but i have a error
class ViewController: UIViewController,UIGestureRecognizerDelegate {
var newSwitch: UISwitch!
var deleteButtonIndex:Int!
var deleteSwitchIndex:Int!
let gesture = UILongPressGestureRecognizer()

func CreateSwitchWithIndex(index:Int) {
     let newSwitch = UISwitch()
     newSwitch.tintColor = UIColor.blackColor()
     newSwitch.on = false
     newSwitch.tag = index+1;
     newSwitch.addTarget(self, action: Selector("switchSen:"), forControlEvents: UIControlEvents.ValueChanged)
     self.view.addSubview(newSwitch)
     newSwitch.setOn(false, animated: true)

     let newSwitchConstraintL = NSLayoutConstraint(item: newSwitch, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)

    let newSwitchConstraintH = NSLayoutConstraint(item: newSwitch, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)

    let coordX = 368
    let coordY = 190

    newSwitchConstraintX = NSLayoutConstraint(item: newSwitch, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordX))

    newSwitchConstraintY = NSLayoutConstraint(item: newSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordY))

    view.addConstraints([newSwitchConstraintX,newSwitchConstraintY,newSwitchConstraintH,newSwitchConstraintL])

    var longPress = UILongPressGestureRecognizer(target: self, action: "menu:")
     longPress.minimumPressDuration = 1
     longPress.delegate = self
     newSwitch .addGestureRecognizer(longPress)
 }

func switchSen(sender:UISwitch!) {
    if (sender.on == true){
        println("on")
    }
    else{
        println("off")
    }
}

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {

    if(touch.view == newSwitch){
        return false
    }else{
        return true
    }
}

func menu(gesture:UILongPressGestureRecognizer) {

    if(gesture.state == UIGestureRecognizerState.Began){
        self.deleteButtonIndex = gesture.view?.tag
        self.deleteSwichIndex = gesture.view?.tag
        becomeFirstResponder()
        var menu = UIMenuController.sharedMenuController()
        var deleteItem = UIMenuItem(title: "Delete", action: Selector("delete"))
        menu.menuItems = [deleteItem]
        var lastLocation:CGPoint = gesture.locationInView(view)
        menu.setTargetRect(CGRectMake(lastLocation.x, lastLocation.y, 0.0, 0.0), inView: view)
        menu.setMenuVisible(true, animated: true)
    }
}

func delete(){
    println("Delete")
}
}

I just get this error : fatal error: unexpectedly found nil while unwrapping an Optional value on if(touch.view == newSwitch)
How to add the shouldReceiveTouch on Switch ?

A: Please try to use this line
let newSwitch: UISwitch!

instead of
var newSwitch: UISwitch!


text:
Q: Retrieving Windows Form properties during multithreading I am somewhat familiar with VB.NET but am very new to multi-threading.
I have a situation in which I have started a new thread separate from the main process, and with that new thread I have created and displayed a new form. One of the methods in the new form's Load() procedure is to set the form's location, dependent on the main form (Form1's) location.
I am finding, however, that when I refer to Form1's properties from this thread, they are not being accurately retrieved. In particular, the Location.X and Location.Y properties appear as 0, when they are in actuality more substantial integers.
Private Sub SetLocation()

    Dim parentx, parenty, parentw, parenth As Integer
    Dim parentForm As Form = My.Forms.Form1

    parentx = parentForm.Location.X
    parenty = parentForm.Location.Y

    parentw = parentForm.Width
    parenth = parentForm.Height

    Me.Location = New Point(parentx + (parentw / 2), parenty + (parenth / 2))

End Sub

The part I find the strangest about this is that when I set a breakpoint within this SetLocation() method, and the program breaks for debugging, the X and Y variables will first register as 0 in the value display:
x and y zero values
But then, while I'm debugging, if I access the information about Form1 in the IDE in its paused state, without resuming the application, and then return to viewing the X and Y values, the properties will eventually display as their actual values.
x and y actual values
Is it normal for form properties to be loaded in the midst of a debugging break point? Is this phenomenon a known aspect of multithreading in VB.NET? And will I have to go through much more complicated thread-communication methods in order for my new thread to access this information?
Thank you!

A: This is hard to explain but I will do my best.
In your usage Form1 is the Form Class type, NOT the form itself.
This is a common and ongoing confusion in VB.NET.
  My.Forms

Lists only the form designs you have defined in the project... NOT THE ACTIVE FORMS THEMSELF.
If your project starts with Form1, VB.NET creates an INSTANCE of that form which has it's own identity and memory allocation.
When you open a new form that references the initial form, you need to pass that identity to the second form by reference.
The best way to do that, IMHO is to augment Form2's constructor. As Follows.
Public Sub New(owner_Form As Form1)
    Owner = owner_Form
    ' This call is required by the designer.
    InitializeComponent()

End Sub

Then in your SetLocation code use the following
    parentx = Owner.Location.X
    parenty = Owner.Location.Y
    parentw = Owner.Width
    parenth = Owner.Height

NOW: your example code does not indicate where the thread is that starts the new form.
If the thread code is part of the Form1 Class you can simply do the following in your thread code.
Dim Form2 as New Form2(me)

If it is deeper than that, you would need to pass the Me down through the hierarchy.
If your application is not overly complicated, an Alternative Method is to use some other Global or shared Class Reference to identify the main form.
Example:
In a Global Module add
Public Main_Form as Form1

And in Form1_Load add
Main_Form = Me

Then in your SetLocation code use the following
    parentx = Main_Form.Location.X
    parenty = Main_Form.Location.Y
    parentw = Main_Form.Width
    parenth = Main_Form.Height

WHY IS IT SO COMPLICATED
What you have to force yourself to remember is that during execution your program can create any number of Form1s, or any other form for that matter. Each one has it's own identity.
My.Forms only lists the prototype.
CROSS-THREADED UI REFERENCING
As Enigmativity mentions, referencing the UI from a non UI-Thread can be a dangerous place to go and is fraught with issues that will drive you batty. I do agree usage of the UI through another thread is treading on very thin ice, however there are occasions, if the model is fully understood, that such referencing is acceptable. Read-Only usage like the current example being a case in point.
However, this "answer" would be the same whether the second form was started from a new thread or simply spawned as a normal Form.Show() from the initial form
PS: You could also simplify our code
Me.Location = <whatever method you choose>.Location
Me.Size = <whatever method you choose>.Size


text:
Q: Testing API:GET localhost:3000/api/locations/_id: => loads for a longtime, returns nothing I'm currently learning MEAN stack using this book called getting-MEAN by Simon Holmes, and I came across an issue, the book said the request mentioned in the title should return a response, that should be a full location object, stored in my MongoDB.
yet it just loads for a long time and outputs this Postman output
I'm thinking, I've messed up my enviroment versions since the book uses an older enviroment?
My environment:

✗ uname -srmo
  Linux 4.11.6-3-ARCH x86_64 GNU/Linux
  ✗ node --version
  v8.1.2
  ✗ express --version
  4.15.0
  ✗ mongod --version
  db version v3.4.3
  git version: f07437fb5a6cca07c10bafa78365456eb1d6d5e1
  OpenSSL version: OpenSSL 1.1.0f  25 May 2017
  allocator: tcmalloc
  modules: none
  build environment:
     distarch: x86_64
    target_arch: x86_64
   ✗ npm list mongoose
   loc8r@0.0.1 /home/username/github/Loc8r
     └── mongoose@3.8.40

Loc8r/app_api/controllers/location.js

var mongoose = require ('mongoose');
var Loc = mongoose.model ('Location');

var sendJsonResponse = function (res, status, content){
    res.status (status);
    res.json (content);
};

module.exports.locationsCreate = function (req, res) {
    sendJsonResponse (res, 200, {"status" : "Create success"});
};

module.exports.locationsListByDistance = function (req, res) {
    sendJsonResponse (res, 200, {"status" : "ListByDist success"});
};

module.exports.locationsReadOne = function (req, res) {
    Loc
 .findById (req.params.locationid)
 .exec (function (err, location){
     sendJsonResponse (res, 200, location);
 });

};

module.exports.locationsUpdateOne = function (req, res) {
    sendJsonResponse (res, 200, {"status" : "success"});

};

module.exports.locationsDeleteOne = function (req, res) {
    sendJsonResponse (res, 200, {"status" : "success"});
};

Loc8r/app_api/routes/index.js

var express = require ('express');
var router = express.Router ();
var ctrlLocations = require ('../controllers/locations');
var ctrlReviews = require ('../controllers/reviews');

//locations
router.get ('/locations', ctrlLocations.locationsListByDistance);
router.post ('/locations', ctrlLocations.locationsCreate);
router.get ('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put ('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete ('/locations/:locationid', ctrlLocations.locationsDeleteOne);

//reviews
router.post ('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);
router.get ('locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
router.put ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsUpdateOne);
router.delete ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsDeleteOne);

module.exports = router;

Loc8r/app_api/models/db.js

var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://localhost/Loc8r';
if (process.env.NODE_ENV === 'production') {
    console.log ("NODE ENVIROMENT: "+ process.env.NODE_ENV);
    dbURI = process.env.MONGODB_URI;
}

mongoose.connect(dbURI);

// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
    console.log('Mongoose disconnected');
});

// CAPTURE APP TERMINATION / RESTART EVENTS
// To be called when process is restarted or terminated
gracefulShutdown = function(msg, callback) {
    mongoose.connection.close(function() {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};
// For nodemon restarts
process.once('SIGUSR2', function() {
    gracefulShutdown('nodemon restart', function() {
        process.kill(process.pid, 'SIGUSR2');
    });
});
// For app termination
process.on('SIGINT', function() {
    gracefulShutdown('app termination', function() {
        process.exit(0);
    });
});
// For Heroku app termination
process.on('SIGTERM', function() {
    gracefulShutdown('Heroku app termination', function() {
        process.exit(0);
    });
});

// BRING IN YOUR SCHEMAS & MODELS
require('./locations');

Loc8r/app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('./app_api/models/db');

var routes = require('./app_server/routes/index');
var routesApi = require ('./app_api/routes/index');
// var users = require('./app_server/routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// tells the application to check the server application routes
// for all incoming requests
app.use('/', routes);
app.use ('/api', routesApi);
// app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

Loc8r/app_api/models/location.js

var mongoose = require('mongoose');

...

...

var locationSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    address: String,
    rating: {
        type: Number,
        "default": 0,
        min: 0,
        max: 5
    },
    facilities: [String],
    // Always store coordinates longitude, latitude order.
    coords: {
        type: [Number],
        index: '2dsphere'
    },
    openingTimes: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model('Location', locationSchema);

Mongoshell:test query
It should return the JSON object in the Mongoshell test query, when I request GET localhost:3000/api/locations/594d96ab87e3602861443e1e

A: Your findById() function may be failing. Have you tried logging the err variable to see if it is throwing an error?
Loc
    .findById (req.params.locationid)
    .exec (function (err, location){
        if(err) console.log("err", err)
        sendJsonResponse (res, 200, location);
    });


text:
Q: HTML style input with Cakephp Action In my index.ctp, I am creating a table and the last column of the table will have 3 buttons to perform actions on that specific row.  The buttons will be View, Edit, and Delete.
I am trying to decide what will be easier, using cakephp's form helper to create a button and link the button with the corressponding controller action, or use javascript to create the input but then how would I link the onclick to the controller action.
I am a total noob at cakephp so any help would be great.
Here is the code for the buttons using the form:
<input type="button" id="viewButton" value="View"/><input type="button" id="editButton" value="Edit"/><input type="button" id="deleteButton" value="Delete"/>

(I don't have any events on the button becase I don't know how to link the events to the controller)
Here is the same thing but written with cakephp's form helper:
<?php echo $this->Form->button('View', array('type' => 'button', 'action' => 'view'), $LocalClock['LocalClock']['id']);
echo $this->Form->button('Edit', array('type' => 'button', 'action' => 'edit', $LocalClock['LocalClock']['id']));
echo $this->Form->button('Delete', array('type' => 'button', 'action' => 'delete', $LocalClock['LocalClock']['id']));?>

I needed help with getting the buttons to communicate with their actions.
Ultimately I will try and open a modal window with one of the views in the window.
Thanks in advance

A: I found an answer to my own question.
I can use a button like this
<button onclick="location.href='<?php echo $html->url('/controller/
action'); ?>';">Click me</button>

When adjusted to fit my specific program I got
 <input type="button" class="viewButton" value="View" onclick="location.href='<?php echo $this->Html->url(array('controller' => 'localClocks', 'action' => 'view', $LocalClock['LocalClock']['id'])); ?>';"/>
    <input type="button" class="editButton" value="Edit" onclick="location.href='<?php echo $this->Html->url(array('controller' => 'localClocks', 'action' => 'edit', $LocalClock['LocalClock']['id'])); ?>';"/>

Html->url(array('controller' => 'localClocks', 'action' => 'delete', $LocalClock['LocalClock']['id'])); ?>';"/>

I just thought I would share what I found.
Thanks