text:
Q: Why should I use startActivity in a Service Why should I use startActivity() in a Service? If I need an Activity a have to call an activity and if I need a "delayed activity" I have to use the notification. So, why should I use startActivity()?

A:
why should I use startActivity() in a
  Service?

Generally, you should not use startActivity() from a Service.


text:
Q: Javascript contact form submit post I am trying to validate an email field and if valid submit my form. But the form is giving me an error when i submit it to the server. If i submit it with a submit button it works fine.

<form action="mailer.php" id="form1"   name="form1" method="POST">

  <input type="text"  size="19" name="name"/>
<input type="text"  size="19" name="phone"/>
<input type="text"  size="19" name="email"/>

    Submit

</form>

<?php
if(isset($_POST['submit'])) {

$to = "marshal@smedia.ca";
$to2 = $_POST['email'];
$subject = "Lead Gen";
$subject2 = "Coupon2";
$first_field = $_POST['name'];
$email_field = $_POST['email'];
$phone_field = $_POST['phone'];
$headers .= "Content-type: text/html\r\n";
$headers .= 'From: Nurray GM <welcome@mycompany.com>' . "\r\n";

$body = "

From: $first_field \n

E-Mail: $email_field\n

Phone Number: $phone_field\n ";

$body2 = "

Hello  $first_field,

Thank you for applying for pre approval. balbalblah.

";

mail($to, $subject, $body, $headers);

mail($to2, $subject2, $body2, $headers );

header("Location: http://www.smedia.ca/clients/leadgen/murray/redirect.html");
} else {
echo "Sorry - something seems to be wrong. Your message was not sent";
}

?>

A: You shouldn't do it that way. You should attach the validate function to onsubmit event of the form, and decline submitting if there are issues (by returning false or preventing the default behaviour).
<form action="mailer.php" id="form1" onsubmit="return mysubmitcheck()"
      name="form1" method="POST">

.
function mysubmitcheck() { if (...) return true; else return false; }

That's the way it was done with pure javascript, and it still works. You should, instead of a link, have a regular submit button for submitting forms.
Nowadays people do the same with jquery (like explained here), but if you're not using jquery anywhere else it doesn't add special value here.
Attaching to events such as onsubmit can also be done so that it wouldn't pollute HTML, like
window.onload = function() {
  // find the form
  form.onsubmit = mysubmitcheck;
}

A: If you INSIST on using inline script on a link, then change
Submit

to
Submit

to avoid the reload of the page
Here is how I would do it
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
window.onload=function() {
  document.getElementById("form1").onsubmit=function() {
    if(!this.email.value.match(mailformat)) {
     alert("You have entered an invalid email address!");
     this.email.focus();
     return false;
    }
    return true;
  }
}

and use an <input type="submit" /> instead of the link.
If you want it to look like a link, we can style the button like one

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can We pass id in url using jquery? Code:
 <script type = "text/javascript" >
  $(document).ready(function($) {
    $('#university_name').autocomplete({
      source: 'autocomplete.php',
      minLength: 2,
      select: function(event, ui) {
        var x = ui.item.value;

        x = encodeURIComponent(x);
        location.href = "university_page.php?university_name=" + x + "&university_id=" + x;
        return false;
      }
    });
  }); < /script>

autocomplete.php
<?php
    include('conn.php');
    $searchTerm = $_GET['term'];
    $query = $db->query("SELECT * FROM all_university WHERE university_name LIKE '%".$searchTerm."%' ORDER BY university_name ASC");
    while ($row = $query->fetch_assoc()) {
      $data[] = $row['university_name'];
    }
    echo json_encode($data);
?>

how can I pass id in url still when I search in textbox field url have university_page.php?university_name=xyz
but I want
university_page.php?university_name=xyz&university_id=1 ?
Thank you

A: For Jquery Request Try This
var get_url = "<baseurl>/autocomplete.php?university_name="+x;
    $.get(get_url, function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
});

requested file is : autocomplete.php
you must handle uni name by
$_GET['university_name']


text:
Q: Virtual reality interface Now that VR is becoming a big thing again, with the release of Oculus Rift and Playstation VR doing quite well, the lack of VR support on Stack Exchange is a significant drawback.
Can we have a virtual holographic interface to float around my kitchen, please?

A: Actually, there is already a little known Oculus Rift VR app that will let you visit the Stack Exchange Headquarters and even meet some of the lead developers as they go by their daily activities.
You can download it here. No need to thank me.


text:
Q: Invoke in-built gingerbread screenshot facility via code From Gingerbread onwards there is a built-in OS facility for taking screenshots (on non-rooted phones as well).
By pressing home and power button together and it also saves it to a folder on the SD card.
Is there a way to invoke this via code? The ability to take a screenshot is needed as part of my other app. There is an app named screenshot-UX that has a method called embedded screenshot capture, which I believe invokes that.
Does anyone know how to invoke the built-in Gingerbread screenshot facility or even how to use it? (with having optional parameters like save path, extensions etc..) as well as for non-rooted phones.

A: This is not a built-in feature of the Android platform at the Gingerbread (2.3) level, although some OEMs did include it (Samsung, for instance, has you press HOME and BACK at the same time).  It was not introduced to the platform as something users could do with a button sequence until 4.0, where the sequence is now to press the Power and Volume buttons at the same time.
Even still, there is no public API via which developers can take screenshots.  The way that screenshot apps capture images Android devices is to read the frame buffer directly via the SurfaceFlinger in native code.


text:
Q: most frequent character in 2d array with pointer i want to find the most frequent character for 5 strings,i thought of this ,i have done it for a specific character,in my ocasion s ,but how can i make it for every character,its only part of my code
Ch is a pointer!!!
for(i = 0; i < five; i++){
    ch = strchr(cities[i], 's');

    if (ch != NULL){ //if this is true
        ch1++;
        printf("exists in %s\n", cities[i]); //print
    }
    else
    {
        printf ("doesnt exist in %s\n", cities[i]); //print
    }
}
printf("The character 's' appears in %d cities\n", ch1);

A: You have to somehow store the number of occurences for each character somewhere.
With that given a hint would be to keep one variable with storing the max occurence of the character and the character itself. Nothing else. And for looping you need to consider all characters from a to z.
The code will be something like:-(Only look if you feel you have tried enough).
To make you aware of what this code does - it counts the character which occurs in maximum number of cities. In case there is a tie, it selects the smaller alphabet first (lexicographically).

for( char c = 'a'; c <= 'z';c++){
    int ch1 = 0, mxch1 = 0;
    char mch='?';
    for(i = 0; i < numOfCities; i++){
      ch=strchr(cities[i],c);
        if( ch ){
           printf("Exist in %s\n",cities[i]);
           ch1++;
        }
        else
           printf("Doesn't Exist in %s\n",cities[i]);
    }
    if( ch1 > mch1) {
      mch1 = ch1;
      mch = c;
  }
    printf("The character %c appears in %d cities\n",c,ch1);
}
printf("Character which occured in max number of cities is %c %d",mch,mch1);

The code for most frequent character will be a bit different.

int charMap[26]={0};
for(size_t i = 0; i < numOfCities; i++){
  for(size_t j = 0; cities[i][j]; j++)
      charMap[cities[i][j]-'a']++;
}
int mx = 0;
mxi = 0;
for(size_t i = 0; i < sizeof(charMap)/sizeof(charMap[0]); i++){
  if(charMap[i]>mx){
      mx  = charMap[i];
      mxi = i;
  }

printf("Character which occured max number of times is %c %d", (char)(mxi+'a'),mx);

A: You can use count sort to achieve this task in O(n) time complexity and O(1) space complexity if your input strictly consists of ASCII characters only.
You keep an array int count[128] = {0}; which keeps track of how many time each character occurred. You use the index of the array as the ASCII value of the character.
for(int i = 0; i < 5; i++)
    for(int j = 0; cities[i][j] != '\0'; j++)
         count[cities[i][j]]++;

If you want to ignore non-graphic characters or you just want to count alphanumeric characters or whatever your requirements maybe, you will have to add an if check with the correct combination of functions (isalpha, isalnum, etc) from ctype.h
You now have to run through the count array and find the largest number. The index at which the largest number was found is the ASCII value of the most common character.


text:
Q: javascript - remove array element on condition I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)
Ex.
ar = [ 1, 2, 3, 4 ];
ar.removeIf( function(item, idx) {
    return item > 3;
});

The above would go through each item in the array and remove all those that return true for the condition (in the example, item > 3).
I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done.
--update--
It would also be great if the condition could work on object properties as well.
Ex.
ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return item.str == "c";
});

Where the item would be removed if item.str == "c"
--update2--
It would be nice if index conditions could work as well.
Ex.
ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return idx == 2;
});

A: You can use lodash.remove
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

A: Make it a one-liner with arrow function:
ar = ar.filter(i => i > 3);

A: You could add your own method to Array that does something similar, if filter does not work for you.
Array.prototype.removeIf = function(callback) {
    var i = 0;
    while (i < this.length) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
        else {
            ++i;
        }
    }
};

To me, that's one of the coolest features of JavaScript.  Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:
Array.prototype.removeIf = function(callback) {
    var i = this.length;
    while (i--) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
    }
};

This avoids the need to even worry about the updating length or catching the next item, as you work your way left rather than right.

A: You can use Array.filter(), which does the opposite:
ar.filter(function(item, idx) {
    return item <= 3;
});

A: simply write the following example if condition could work on object properties as well
var ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
var newArray = [];
for (var i = 0, len = ar.length; i<len; i++) {
        if (ar[i].str == "b")
        {newArray.push(ar[i]);};
 };
console.log(newArray);

See the example Live Example

A: if you need to remove exactly one item, and you know for sure that the item exists, you can use this one-liner:
ar.splice(ar.findIndex(el => el.id === ID_TO_REMOVE), 1);

// or with custom method:
let ar = [ {id:1, str:"a"}, {id:2, str:"b"}, {id:3, str:"c"}, {id:4,str:"d"} ];
ar.removeById = id => ar.splice(ar.findIndex(el => el.id === id), 1);
ar.removeById(ID_TO_REMOVE);

http://jsfiddle.net/oriadam/72kgprw5/
ES6 only

A: I love these kinds of questions and just a different version from me too... :)
Array.prototype.removeIf = function(expression) {
   var res = [];
    for(var idx=0; idx<this.length; idx++)
    {
      var currentItem = this[idx];
        if(!expression(currentItem))
        {
            res.push(currentItem);
        }
    }
    return res;
}

ar = [ 1, 2, 3, 4 ];
var result = ar.removeIf(expCallBack);

console.log(result);
function expCallBack(item)
{
    return item > 3;
}

A: My solution for an array of numbers would be:
ar = ar.filter(item => item < 4);

A: You can use Array filter method.
The code would look like this:

ar = [1, 2, 3, 4];
ar = ar.filter(item => !(item > 3));
console.log(ar) // [1, 2, 3]

A: For the in-place remove, my solution is
ar.filter(item => !(item > 3))
  .forEach(obsoleteItem => ar.splice(ar.indexOf(obsoleteItem), 1));

A: Incorrect way
First of all, any answer that suggests to use filter does not actually remove the item. Here is a quick test:
var numbers = [1, 2, 2, 3];
numbers.filter(x => x === 2);
console.log(numbers.length);

In the above, the numbers array will stay intact (nothing will be removed). The filter method returns a new array with all the elements that satisfy the condition x === 2 but the original array is left intact.
Sure you can do this:
var numbers = [1, 2, 2, 3];
numbers = numbers.filter(x => x === 2);
console.log(numbers.length);

But that is simply assigning a new array to numbers.

Correct way to remove items from array
One of the correct ways, there are more than 1, is to do it as following. Please keep in mind, the example here intentionally has duplicated items so the removal of duplicates can be taken into consideration.
var numbers = [1, 2, 2, 3];

// Find all items you wish to remove
// If array has objects, then change condition to x.someProperty === someValue
var numbersToRemove = numbers.filter(x => x === 2);

// Now remove them
numbersToRemove.forEach(x => numbers.splice(numbers.findIndex(n => n === x), 1));

// Now check (this is obviously just to test)
console.log(numbers.length);
console.log(numbers);

Now you will notice length returns 2 indicating only numbers 1 and 3 are remaining in the array.


text:
Q: How to load data into a Postgres table skipping the header row and adding serial primary key I have a large tab delimited data file of the form
fieldA   fieldB   fieldC
xxx      123      456
yyyyy    32       1654
...
I would like to load it into a table that has a serial primary key, e.g.
create table my_data (
    ID serial primary key,
    fieldA varchar(10),
    fieldB int,
    fieldC int
)

I would like to use a command like
COPY 'data.txt' TO my_data (HEADER TRUE)

Two issues:
1) The file contains a header row, but copy only allows the HEADER option on CSV files. It's a big data file and I would prefer not to have to create an extra copy just to remove one header row. Any work arounds?
2) The ID serial primary key needs to be generated, it is not in the data file. Do I have to first use COPY to load a temp table and then do an INSERT specifying the fields? Again, a big file and would prefer to avoid unnecessary data moves.
Thanks

A: The trick is to use CSV format, but specify TAB as the separator. This allows you to skip the header line.
COPY my_data(fieldA, fieldB, fieldC)
  FROM 'data.txt'
  WITH CSV HEADER DELIMITER e'\t'
  ;


text:
Q: Camel route broke when receive large data I have a route camel which uses camel-undertow and camel-http4 to be used as gateway between two distinct web applications.
The route works fine when last endpoint response has small size. However when last endpoint response has large size I receive truncated data.
Example of correct response:
{
    "field1": "something",
    "field2": "something",
    "field3": "something"
}

Example of incorrect (truncated) response:
{
    "field1": "something",
    "field2": "something",
    "field3": "something",
    "fiel

This is my route:
from("undertow://0.0.0.0:8080/mec?httpMethodRestrict=POST,GET") //receive only POST and GET http methods
.to("http4://something/endpoint?bridgeEndpoint=true&throwExceptionOnFailure=false&copyHeaders=false");

The endpoint "http4://something/endpoint" response an JSON. As I already said, when response of "http4://something/endpoint" is small everything works fine. However when is large the route broke.
I think there is some buffer that I need configure in this components but I did not found anything.


text:
Q: Are there arbitrarily sparse "lattices" in negatively curved symmetric spaces? Let $X$ be a negatively curved symmetric space. In other words, $X$ is one of the four examples: a hyperbolic space, a complex hyperbolic space, a quaternionic hyperbolic space or the hyperbolic Cayley plane.
Let $B\subset X$ be a compact set (wlog, a large ball). Does there always exist a subgroup $\Gamma$ of the isometry group of $X$ such that $X/\Gamma$ is a compact manifold and the images of $B$ under $\Gamma$ are disjoint (i.e. $B\cap\gamma B=\emptyset$ for every nontrivial $\gamma\in\Gamma$)?
Remark: It would suffice to find just one (for each $X$) residually finite discrete co-compact group of isometries. I am sure there is one but I don't know where to look. (Or maybe they all are residually finite?)
Meta-proof: If the answer is negative, then, for some of the model geometries (in some dimension), all compact manifolds with this local geometry are "uniformly thin" - all injectivity radii are bounded above by some universal constant. Such a wonderful fact would be widely known.

A: Let me give an explicit example for the Poincare disk in dimension 2. In the disk model, just take the regular $4g$-gon centered on the origin. Identifying opposite sides, we get a compact surface of genus g. The polygon is a fundamental domain for the group $\Gamma$
generated by $b_1...b_{2g-1}$ with
$b_k=\pmatrix{\cosh(a) & e^{ik\pi\over 2g}\sinh(a)\cr e^{-ik\pi\over 2g}\sinh(a)& \cosh(a)}$
where a is defined by $\cosh(a)=1/\tan(\pi/4g)$. The value of a is in fact equal to the radius of the maximal disk contained in the fundamental domain. This is also the distance from any side of the 4g-gon to the origin. It goes to infinity with g, so we are done.
The Gauss-Bonnet formula tells us that surfaces of a given genus have a bounded volume, hence cannot contains arbitrarily large embedded balls. Hope that helps.

A: The examples are arithmetic groups, constructed in general by Borel and Harish-Chandra.
See also Dave Witte Morris' preliminary book.
However, examples in hyperbolic and complex hyperbolic spaces probably go back further to the study of quadratic forms.
For hyperbolic lattices, one can take a quadratic form over a quadratic number field (such as $\mathbb{Q}(\sqrt{2})$), which
is Lorentzian at one place, and definite at the other places (such as $x_1^2+\cdots +x_n^2-\sqrt{2} x_{n+1}^2$), and take the group of matrices $\Gamma$ in $GL(n+1,\mathbb{Z}[\sqrt{2}])$ which preserve this quadratic form. Then Mahler's compactness theorem (cf. Witte Morris) implies
that the quotient $\mathbb{H}^n/\Gamma$ is compact. Then by Selberg's Lemma and residual finiteness (as Greg points out, Malcev's Theorem), you may find a torsion-free subgroup
of finite-index with as large injectivity radius as you like.
For hyperbolic and complex-hyperbolic spaces, there are other examples which don't come from the arithmetic construction (in fact, most hyperbolic surfaces and 3-manifolds are not arithmetic). These are attributable to Gromov and Piatetski-Shapiro in the hyperbolic case in all dimensions, and there are finitely many examples in the complex hyperbolic case (at least for $\mathbb{C}$-dim >1) going back to Deligne and Mostow (see also Thurston's paper). However, Gromov and Schoen have shown that quaternionic and Cayley-hyperbolic lattices are all arithmetic, so the Borel Harish-Chandra construction is complete in these cases.
Addendum: Related to Protsak's comment, there is a simple example of a negatively curved homogeneous space which has no lattice action. This is Thurston's "9th geometry", which is excluded as a geometry precisely for this reason. One can take the double warped product metric $$ dr^2 + e^{2a r} dx^2 + e^{2b r} dy^2, $$ for $a,b >0$. When $a=b$, this gives hyperbolic space. But when $a\neq b$, the sectional curvatures are $-a^2, -b^2, -ab$. This has a solvable transitive group of isometries, so is homogeneous. But using the solvability, one may see that there is no cocompact action. (Remark:  when $a=-b$, this gives sol geometry).


text:
Q: Downloading 1 files took 6.526568 second(s) Error: Command 'download_from_google_storage --no_resume --platform=linux* --no_auth --bucket I am trying to build v8 as it says here: https://github.com/v8/v8/wiki/Building%20with%20Gyp
By this command gclient sync. But I got this results:
Running depot tools as root is sad.
/home/m/.gclient_entries missing, .gclient file in parent directory /home/m might not be the file you want to use.
Syncing projects: 100% (23/23), done.

________ running '/usr/bin/python v8/gypfiles/landmines.py' in '/home/m'
Clobbering due to missing landmines file.
Running hooks:  17% ( 4/23) clang_format_linux
________ running 'download_from_google_storage --no_resume --platform=linux* --no_auth --bucket chromium-clang-format -s v8/buildtools/linux64/clang-format.sha1' in '/home/m'
Failed to fetch file gs://chromium-clang-format/5349d1954e17f6ccafb6e6663b0f13cdb2bb33c8 for v8/buildtools/linux64/clang-format. [Err: Traceback (most recent call last):
  File "/home/m/depot_tools/gsutil.py", line 182, in <module>
    sys.exit(main())
  File "/home/m/depot_tools/gsutil.py", line 179, in main
    clean=args.clean)
  File "/home/m/depot_tools/gsutil.py", line 128, in run_gsutil
    gsutil_bin = ensure_gsutil(force_version, target, clean)
  File "/home/m/depot_tools/gsutil.py", line 107, in ensure_gsutil
    target_zip_filename = download_gsutil(version, instance_dir)
  File "/home/m/depot_tools/gsutil.py", line 65, in download_gsutil
    u = urllib2.urlopen(url)
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 435, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 473, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
]
0> Failed to fetch file gs://chromium-clang-format/5349d1954e17f6ccafb6e6663b0f13cdb2bb33c8 for v8/buildtools/linux64/clang-format, skipping. [Err: Traceback (most recent call last):
  File "/home/m/depot_tools/gsutil.py", line 182, in <module>
    sys.exit(main())
  File "/home/m/depot_tools/gsutil.py", line 179, in main
    clean=args.clean)
  File "/home/m/depot_tools/gsutil.py", line 128, in run_gsutil
    gsutil_bin = ensure_gsutil(force_version, target, clean)
  File "/home/m/depot_tools/gsutil.py", line 107, in ensure_gsutil
    target_zip_filename = download_gsutil(version, instance_dir)
  File "/home/m/depot_tools/gsutil.py", line 65, in download_gsutil
    u = urllib2.urlopen(url)
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 435, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 473, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
]
Downloading 1 files took 6.526568 second(s)
Error: Command 'download_from_google_storage --no_resume --platform=linux* --no_auth --bucket chromium-clang-format -s v8/buildtools/linux64/clang-format.sha1' returned non-zero exit status 1 in /home/m
Hook 'download_from_google_storage --no_resume '--platform=linux*' --no_auth --bucket chromium-clang-format -s v8/buildtools/linux64/clang-format.sha1' took 13.36 secs

Also I don't know should I run all the command till end of that page or not?!
I use an ARM-based board with armbian OS(armv7l armv7l armv7l GNU/Linux). My goal of building v8 is to using it inside libaiml program as it wants to enable it by this command: --enable-javascript --with-v8-path=/path/to/v8.


text:
Q: Generic data list in C++ I'm working with Lists using C++ and I had a little doubt. Each Cell have a pointer to next cell and your data. Now each cell is using the class Data1.
class Data1
{
    public:
        int item1;
};

class Data2
{
    public:
        int item2;
};

class List
{

    /* Each cell of list */
    typedef class Cell
    {
        public:
            class Data1 data;
            class Cell *next;

    }Cell;
    .
    .
    .
}

How can I generic it to use Data1 or Data2 for diferent applications?
A better explaination is if Data2 are on another source code and the Cell point to Data2 not Data1.
Thank you!

A: You can use templates for this:
template<class Data>
class List
{
    struct Cell { Data data; Cell* next; };
};

At instantiation time you can pass the intended class to be used as the type of data:
List<Data1> list1;
List<Data2> list2;

Also, you don't need the prefix class or struct when defining instances of classes in C++.


text:
Q: BIND subnet syntax I am trying to add an entire subnet to BIND, rather than individual IP addresses. For example instead of doing this:
example1.test.com     IN     A     192.168.5.43
example2.test.com     IN     A     192.168.6.74
I want to just have:
*.test.com     IN     A     192.168.0.0/19
Is there some way to do this rather than add all IPs individually? There are way too many for me to add but I need to only add the IPs in this subnet.

A: If you care about a particular name being associated to a particular IP address, then there are two options: either do it manually, or if you're using DHCP to assign IP addresses, configure dynamic DNS updates, and let either the clients themselves, or perhaps more securely, the DHCP server, update the DNS information automatically as the clients renew their DHCP leases.
But if you only need to make sure that every IP address is associated with a name, you could use the $GENERATE syntax in the DNS zone file to auto-generate a set of systematic names. Like this:
$GENERATE 0-255 example000dot${0,3}.test.com. A 192.168.0.$
$GENERATE 0-255 example001dot${0,3}.test.com. A 192.168.1.$
$GENERATE 0-255 example002dot${0,3}.test.com. A 192.168.2.$
...

... and so on for a total of 31 lines.  You should get a series of names with the form exampleXdotY.test.com for every IP address 192.168.X.Y.
To generate the corresponding reverse records, you could use:
$GENERATE 0-255 $.0 PTR example000dot${0,3}.test.com.
$GENERATE 0-255 $.1 PTR example001dot${0,3}.test.com.
$GENERATE 0-255 $.2 PTR example002dot${0,3}.test.com.

... and so on.


text:
Q: Should I separate cron into its own docker container? Suppose I have a Docker container with Nginx or PostgresQL. I need Cron to delete old log files. Where should I run cron? In the same container inside an entrypoint script? In its onw container? Outside docker?
Running in outside Docker will defeat Docker's control over configurations. I will have to use some other configuration management system to pin its config.

A: I think you might need to rethink why you actually need a cron job.
Why do you have old log files inside of your container? One of the best practices with building applications inside containers is the fact of logging everything towards stdout/stderr. This way you keep the paradigm of 1 container = 1 process and your log management is a responsibility of docker and/or your host.
You can do this fairly easy by either:

*

*reconfiguring your application to log to /dev/stdout

*linking your application log file /var/log/nginx/access.log to /dev/stdout in your dockerfile

ln -sf /dev/stdout /var/log/nginx/access.log
ln -sf /dev/stderr /var/log/nginx/error.log

If you actually need to log towards a location inside your container, a good practice could be to log towards a shared volume. Then run a cron job that spins up a container which also mounts this volume and cleans the logs. You can schedule this clean-up container with a cron job.
If you use some kind of orchestrator like Kubernetes it'd be done with a Scheduled pod which does exactly this.


text:
Q: Microphone Boost not available anymore in Windows 10 For many years, I used to have the option to enable/control a "Microfone Boost" level in the Windows Microphone Settings under the "Levels" tab:

However, for some time now, that Microfone Boost slider has disappeared. This applies to all my various sound cards, both on-board and several external USB sound cards. Furthermore, the issue also occurs on a laptop which has completely different hardware from my main PC.
There are some typical instructions on the web on how to supposedly restore Microfone Boost, e.g. here. I have tried all of these several times, but without success.
Is there any other way to re-enable Microfone Boost?


text:
Q: Control bubble chart layer attributes in Highcharts rCharts I have a population pyramid using the rCharts-highChart library implementation presented in here. I am trying to add a layer of bubble chart over the population pyramid. I have partial success in implementing it. The image below shows the chart I achieved.
enter image description here
I am not able to control some attributes of the bubble chart. I want datalabels to be displayed on the the bubble chart. However, the dataLabels are activated for the bar chart only. I want the dataLabels to be displayed on the bubble chart also. The code I use is below.
 n1 <- hPlot(x = 'Agec',
           y = 'Category',
           type = 'bar',
           group = 'HbA1c_levels',
           plotBorderWidth = 1,
           data = MyD.melt)

# Adding a series of bubble chart
n1$series(type = 'bubble',
          data = (as.numeric(as.character(MyD$low)))
n1$series(type = 'bubble',
          data = (as.numeric(as.character(MyD$high))))

n1$plotOptions(series = list(stacking = 'normal', pointPadding = 0, borderWidth = 0, dataLabels = list(enabled = TRUE)))
#dataLabels gets activated only for bar chart as shown in the figure

Further, the bubblechart is able to read the 'Y axis' when I specify a particular column from the dataframe as shown in the above code. I would want it to read the "X,Y,Z,name" attributes from a list or dataframe and then plot the bubbles. Any idea how it can be done?


text:
Q: Recommended Magento cron frequency and setup All over the internet, there is a variety of suggestions for how often a cron should be run, without any real suitable explanation.
Thus, I was wondering if anyone could help myself identify 'ideal', settings.
Magento's recommendation is:

*

*

*

*

*

*

*

*

*

*/bin/sh /path/to/your/magento/site/root/cron.sh

For clarity, Magento suggests to execute on every minutes. But, have seen some of the following recommended by others:

*/5 * * * * sh /path/to/your/magento/site/root/cron.sh
*/1 * * * * sh /path/to/your/magento/site/root/cron.sh
*/10 * * * * sh /path/to/your/magento/site/root/cron.sh

My current settings for cron in admin:
Generate schedules every: 15
Schedule ahead for: 20
Missed if not run within: 15
History cleanup every: 10
Success history lifetime: 60
Failure history lifetime: 600

A: As you state in your question:

Magento suggests to execute on every minute

Unless you have a specific use-case, I would recommend you follow Magento's recommendation.


text:
Q: Unable to select just certain columns from table with Entity Framework - get anonymous type error I am trying to select only certain columns from a table using EF 6.1. However, it won't let me pull back just the columns I want. I have to pull back every column from the table which has 14,000 rows so the query takes ~30 seconds. The column that kills the query is a NVARCHAR in the table. But with EF it's all or nothing. I am using IEnumerable also. Perhaps I should be using IQueryable?>
Using this query I get an anonymous type error:
 Using db As Ctx = New Ctx
     Dim postcount = db.be_Posts.Count
     posts = db.be_Posts.Select(Function(S) New With {S.DateCreated, S.Description, S.PostRowID, S.Title}).OrderByDescending(Function(x) x.DateCreated)
     Return posts.ToList
 End Using

Error:
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[VB$AnonymousType_0`4[System.DateTime,System.String,System.Int32,System.String]]' to type 'System.Collections.Generic.IEnumerable`1

This works but is getting all the records and the columns I don't need:
Using db As Ctx = New Ctx
            Dim postcount = db.be_Posts.Count
            posts = db.be_Posts.OrderByDescending(Function(x) x.DateCreated).ToList

            Return posts
        End Using

A: What I would do is:

*

*Create PostSummaryDto class:
public class PostSummaryDto
{
    public DateTime DateCreated { get; set; }
    ...rest of fields...
}

*Use PostSummaryDto class in query:
New PostSummaryDto { DateCreated = S.DateCreated, ...}

*Define return type of function as IEnumerable<PostSummaryDto>.
I am not a fan of Visual Basic, so I am not sure if returning anonymous types is allowed, but I believe it is good custom to define return types clearly.


text:
Q: Two spinners look different in same activity My application activity Image

First spinner is using string array resources. and second is from arrayList in XML file
<Spinner
    android:id="@+id/spnExam"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/Exams" />

<Spinner
    android:id="@+id/spnPaper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Code for spinner two
            List<String> list = new ArrayList<String>();
            c.moveToFirst();
            do
            {
                list.add(c.getString(2));
            } while (c.moveToNext());
            c.close();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_dropdown_item, list);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spnPaper.setAdapter(adapter);
            db.close();

A: Difference is the using style. You insert data to your first spinner(spnExam) from a string array which will specify the simple list layout to use when the list of choices appears.
But the second spinner which get data through adapter specify the simple spinner list layout to use when the list of choices appears .
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);

I think to if you want to same both of your spinner layout then you have to use android.R.layout.simple_spinner_dropdown_item instead of android.R.layout.simple_spinner_item
before you want to show your list i.e on setDropDownViewResource method.
If same problem happens then also change your adapter from:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_dropdown_item, list);

to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_item, list);

A: use below code for both spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

A: There is a problem to set View resource for Second spinner. If you need same spinner as first spinner that you have to change by this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_item, list);

for your second spinner in your java file..
Thanks!!

A: The problem is your spinner view so change your code android.R.layout.simple_spinner_dropdown_item to android.R.layout.simple_spinner_item.
eg :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_item, list);

A: My first answer describes the differences for your problem.
And these are your solutions:
1st solution:
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            ListSpinners.this,
            android.R.layout.simple_spinner_item, list);
    adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
    spnPaper.setAdapter(adapter);

2nd Solution As before:
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            ListSpinners.this,
            android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spnPaper.setAdapter(adapter);

3rd And Expected Solution:
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                ListSpinners.this,
                android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnPaper.setAdapter(adapter);

All are useful for you.
Thank You

A: try this ...
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListSpinners.this, android.R.layout.simple_spinner_item, list);


text:
Q: Creating different tables using using same base abstract class I have 2 models which have exactly same fields, but I chose to make different models for them because I needed two different tables, one for each.
Earlier everything was working fine when I had two different tables for each model, but then I started using abstract base class because the code inside both the models were same.
Now I have a single table comprised of all the data that I save.
How can I create different tables for those two models.
 public abstract class baseGrammar
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string question { get; set; }
    [Required]
    public string ans { get; set; }
    public string ruleId { get; set; }
    public string ruleApplicable { get; set; }
    [ForeignKey("ruleId")]
    public virtual ruleTable RuleTable { get; set; }
}

The one shown above is my abstract base class.
public class article : baseGrammar
{

}
 public class adjective : baseGrammar
{
}

Just if someone intrested in ruleTable model.
public class ruleTable
{
    [Key]
    public string ruleId { get; set; }
    public string topic { get; set; }
    public string rule { get; set; }
    public string example { get; set; }
    public virtual ICollection<baseGrammar> BaseGrammar { get; set; }
}

Am also adding context class so as to provide better description
public class english : DbContext
{
    public english() : base("name=localServerEng")
    {
        Database.SetInitializer<DbContext>(null);
        Database.SetInitializer<english>(new UniDBInitializer<english>());
    }

    public virtual DbSet<adjective> adjectiveDb { get; set; }
    public virtual DbSet<adverb> adverbDb { get; set; }
    public virtual DbSet<alternativeVerb> alternativeVerbDb { get; set; }
    public virtual DbSet<antonyms> antonymsDb { get; set; }
    public virtual DbSet<article> articleDb { get; set; }
private class UniDBInitializer<T> : DropCreateDatabaseIfModelChanges<english>
    {
    }

    public System.Data.Entity.DbSet<StructureSSC.Areas.AreaEnglish.Models.baseGrammar> baseGrammars { get; set; }
}

Screenshot of SQL Server showing 1 table comprising of all columns instead of different tables

A: This set up will give you 2 tables: (1) adjectives (2) articles
The context should be like this:
public class SomeContext : DbContext
{
    public SomeContext()
        : base("name=SomeContext")
    {
    }
    public virtual DbSet<article> Articles { get; set; }
    public virtual DbSet<adjective> Adjectives { get; set; }
}

public abstract class baseGrammar
{
    //... common properties/columns
}

public class article : baseGrammar
{

}
public class adjective : baseGrammar
{
}

Please note the naming convention. In .NET class names and property names should follow Pascal Notation. Therefore, they should be:
BaseGrammar
Article
Adjective
RuleApplicable // other properties should follow same convention


text:
Q: DNS, PTR, Mail Server HELP! I am not really sure which route to take. Here is my current setup.
We host our web server on RackSpace Cloud (moved from EC2)
Previously we hosted our own name servers, now we use RS (RackSpace) name servers.
Our mail server is hosted locally running on an ATT T1. ATT Will not setup a PTR unless they are hosting the domain. So they have to "delegate" control and whoever they delegate to can create the PTR. RS will not create a PTR because they said their Reverse DNS isn't setup to run that way.
We have a few domains, big domains that are our primary customers, rejecting our mail because of this issue.
So just to clarify, this is our setup:
Domain Registrar is at Godaddy.com
DNS Name Servers point to RS DNS
Mail is hosted locally via ATT T1, ATT Delegates DNS authority for our IP Block to our OLD name servers at ns1 and ns2.mycompany.com.  (These no longer exist as we host with RS now)
Any advice you could give me would be greatly appreciated. I have been dealing with this for 3 days now and feel like a complete newb. It's driving me mad.  So mad I will be willing to pay a consultant to assist in this matter.
The Error that our mail server is giving is:
delivery temporarily suspended: host or domain not found. name service error for name=domain.mil type=mx:host not found, try again

A: AT&T does this. It's their policy. It's an ugly policy, but I will often times either host a minor domain attached to the company with AT&T or delegate the primary DNS domain to them. If you have a small domain you don't mind hosting with AT&T, do it. Then they'll give you the reverse PTR records.

A: A PTR record can only be set up by the netblock owner or another entity that they delegate it to. If your email server runs on AT&T's ip address then they have to set up the PTR record for you if it can't be delegated to RS. You may be out of luck unless you have AT&T host your domain. GoDaddy can continue to be the registrar and RS can continue to host your web site but you can move your domain (DNS) to AT&T.
It's not a requirement that all of your eggs be in one basket.
I can have one company as my domain registrar, another company that hosts my DNS, another company that hosts my email, and yet another company that hosts my web site.

A: You could consider an alternative, low-cost solution to bypass your current problem, by using an external server from a hosting company which allows you to set the PTR record, for example, linode or slicehost (a RackSpace company.)
The external server should then be configured as the primary mail relay for your domain whilst your existing T1-hosted mail server should be removed as a mail relay from your DNS. The primary relay can then relay incoming mails privately to your T1-hosted mail server.
Similarly, for outgoing email, you can avoid sending mail directly from the T1-hosted mail server and instead configure this to use the external server as a smarthost.
You'll then need to consider different issues, for example, which email addresses will be accepted by the external server, spam filtering, etc, although how that is achieved is dependent on your choice of mail server software. But that's a different question for stack exchange.

A: If AT&T will not allow you a PTR record, your only alternative is to use a smarthost to relay your mail. Usually ISP's have a mail server to relay through, most requiring authentication although sometimes they rely simply on the fact that if you are on their subnet, you can relay.
If they do not, you will need to purchase a service that will let you do relaying. Here is one from DYDNS.org for just $20/year: http://www.dyndns.com/services/sendlabs/outbound.html. I am not sure if that one allows business class service, but you get the idea.
Lastly, you then have to know how to set your specific server up to use it. In Exchange 207/2010, you do it under Organization Configuration>Hut Transport>Send Connectors. On the network tab, you select "Route mail through the following smart hosts", and enter the information appropriately.

A: I work for a business class ISP and we usually handle PTR records for anyone using one of our IPs regardless of whether he host email for them or not.


text:
Q: Android: How do you pass a callback to an activity? I am creating a library. It creates an activity, starts it, and finishes it after a button is pressed.
After the button is pressed, I'd like to execute some client code through an interface.
That is, users of this library pass in an implementation, and I simply execute it.
The analogous iOS code would be:
MyViewController *vc = [[MyViewController alloc] init];
vc.callOnComplete = ...
[self presentViewController:vc animated:YES completion:nil];

The desired code is:
public interface SaveStuff {
    void save();
}

In my library's Activity:
private SaveStuff saveStuff;
public void onButtonClicked(View v) {
    saveStuff.save() // client passes in saveStuff obj
    finish();
}

I've tried serialization. I made a class that implemented the interface and also implemented Serializable, and tried passing that in and extracting it with getSerializableExtra. I end up getting a non serializable exception. So far as I know, this is probably not a viable solution, as it would mean that clients must use only serializable classes in their implementations. Correct me if I am wrong on this. In my trials, the client activity was showing up in the non serializable exception.
I've tried using a static reference. Basically global state/singleton. As it turns out, according to a variety of answers such as this one: Java Static Variable becomes null, I cannot rely on any static state, and any solutions that do work with static state are just working coincidently.
I haven't tried simply starting the activity with startActivityForResult, because that would require me to cast the context we are accepting as a parameter to an Activity.
The activity is started inside the library with this:
private void startNewActivity(int newVersion) {
    Intent i = new Intent(context, MyActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(i); // context variable is passed in by the client
}

As you can see, context is passed in by the client. I could perhaps cast the context to an Activity in order to call startActivityForResult, but I don't want to do this, as I have read that is not always safe. I could require that an Activity be passed in. This is perhaps a reasonable requirement, but I don't want to go there just yet.
I've looked at the existing questions and something I haven't tried is using broadcasts.  Correct me if I am thinking about this incorrectly, but the best I could do is have the object that holds the reference to client interface implementation be a broadcast receiver, and then send a broadcast in the activity that I create. I am worried that the receiver will not persist, however. What happens if my library shows the user the activity, but then the user kills the app before pressing the button? The reference to the client code was held by the previous activity. Will nothing happen upon pressing the button?
Should I just broadcast a message, and leave it up to the client to handle these cases? How would the client handle this? Register something on app start up/shutdown? Do I have to force the user to do this to use my library? Is it reasonable?
Update:
As it turns out, we are just going to have the activity in the library access a singleton.
To avoid all the issues with state being wiped based on activities being killed and the like, users of this library will be required to run a 'setup' method on the singleton, and pass in the callback obj there. They will run this on some sort of base Activity's onResume.
I'll wait a little before answering self-answering this question to see if there any alternatives.

A: Why don't you use same process for android as well i.e.
1) make an interface
2) declare a public variable of interface in your activity.
3) user will initialize that interface when start to launch your activity.
4) use the interface variable to call the method.


text:
Q: I'm trying to use spring security with PostgreSQL, I want get users from database but getting StackOverflowError: null @ComponentScan(basePackages = {"conf"})
@ComponentScan(basePackages = {"application.controller"})
@ComponentScan(basePackages = {"applicaion.model"})
@ComponentScan(basePackages = {"applicaion.dao"})
@ComponentScan(basePackages = {"usersDetails"})
@SpringBootApplication
@EnableJpaRepositories
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Security config part
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }

    @Override
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();

    }

    @Bean
    public PasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}

}

User Entity
"felhasznalonev"==username and "felhasznalo"==user
in hungarian
in the database table has theese names
@Entity
@Table( name="felhasznalo")
public class User {

    @Id
    @GeneratedValue
    private int id;

    @Column( unique=true, nullable=false )
    private String felhasznalonev;

    @Column( nullable=false )
    private String jelszo;

    private int statusz;

    public User() {}

    public User(String felhasznalonev,String jelszo,int statusz) {
        this.felhasznalonev=felhasznalonev;
        this.jelszo=jelszo;
        this.statusz=statusz;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFelhasznalonev() {
        return felhasznalonev;
    }

    public void setFelhasznalonev(String email) {
        this.felhasznalonev = email;
    }

    public String getJelszo() {
        return this.jelszo;
    }

    public void setPassword(String password) {
        this.jelszo = password;
    }

    @Override
    public String toString() {
        return null;
    }

    public int getStatusz() {
        return statusz;
    }

    public void setStatusz(int statusz) {
        this.statusz = statusz;
    }

}

userServiceimpl part
@Service("userDetailsService")
public class UserServiceImpl implements UserService, UserDetailsService  {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = findByUsername(username);

        return new UserDetailsImpl(user);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}

UserDetailsImpl part
public class UserDetailsImpl implements UserDetails {

    private User user;

    public UserDetailsImpl(User user) {
        this.user = user;
    }

    public UserDetailsImpl() {}

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("USER"));
    }

    @Override
    public String getPassword() {
        return user.getJelszo();
    }

    @Override
    public String getUsername() {
        return user.getFelhasznalonev();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}

UserService part
public interface UserService {
    public User findByUsername(String username);
}

UserRepository
public interface UserRepository extends JpaRepository<User,Integer> {

    User findByUsername(String username);

}

When i run the code everything looks fine, the basic login page come in, i enter the username/password from the database but nothing happen
and IntellIj write this:
2021-11-25 13:12:48.870 ERROR 13928 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Filter execution threw an exception] with root cause

java.lang.StackOverflowError: null
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:472) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:472) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
-||-

the connection with database is good, i can list users as well
Thanks for reading all this and sorry for bad english and mistakes, have a good day!

A: java.lang.StackOverflowError error tell you method declaration in service layer is not linked with any JpaRepository. Problem is came up from loadUserByUsername method in userServiceimpl. You declare method findByUsername without linked with Repository.
Change
User user = findByUsername(username);

To
User user = userRepository.findByUsername(username);

And UserServiceImpl Implements with UserDetailsService only. You need to change inSecurity config code because it has more problem like add wrong annotation and two method declare with same name etc...
Modified Security config
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public AuthenticationProvider authProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception     {
        http
            .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

}

A: You have doubly declared userDetailsService with the same name,
First:
   @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }

Second:
@Service("userDetailsService")
public class UserServiceImpl implements UserService, UserDetailsService  {

It may cause the problem. You should have only one instance of userDetailService.

A: In your SecurityConfig Can you try removing
    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }

And changing the implementation for
 @Override
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

to
@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception{
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}


text:
Q: Quick conversion of pcl::PointCloud to std::vector using no iteration I'm looking for a quick way to convert a PCL point cloud of type pcl::PointCloud<PointXYZ> to std::vector<cv::Point3f>.
The problem is that pcl::PointXYZ consists of 4 floats (x, y, z, padding) while cv::Point3f only has 3 floats (x, y, z). If they were both just 3 floats I could do a simple pointer cast of the data buffer.
So, the underlying question basically is: how to convert an array of structs with 4 floats into an array of structs with 3 floats without using iteration (i.e. for loops)?

A: If you have some point cloud pcl::PointCloud<pcl::PointXYZ> cloud and you want to create a vector of points containing the OpenCV type cv::Point3f just use range-based for loop like that:
std::vector<cv::Point3f> points;

for (const auto& point : cloud) {
    points.push_back(cv::Point3f(point.x, point.y, point.z));
}


text:
Q: Help with a Pearson's chi-square test exercise The following exercise is from some assessment test from Hong Kong.  It looked like a GOF test at first, but I've only ever done them with a single column of data.  I'm a maths tutor but I had to transfer him since I didn't recognize the correct procedure.  And of course I would like that not to happen again, so, can anyone show me the correct way to approach this problem?  Here it is:
Exercise. A random sample of 230 workers at a company were surveyed about their satisfaction with their life.  The answer about their satisfaction was recorded along with their annual wages:
$$
\begin{array}{lccccr}
 & \$\text{20-35k} & \$\text{35-50k} & \$\text{50-75k} & \$\text{75-90k} & \text{Total}
\\
\text{Very satisfied} & 13 & 11 & 19 & 15 & 58
\\
\text{Somewhat satisfied} & 29 & 31 & 28 & 12 & 100
\\
\text{Not satisfied} & 34 & 20 & 10 & 8 & 72
\\
\text{Total} & 76 & 62 & 57 & 35 & 230
\\\hline
\text{Pearson's Chi-square test} & \chi^2=20.0043 & \text{df}=6 & \text{p-value}<0.001
\end{array}
$$
Assuming there's no relationship between income and life satisfaction, how many people who earn between $20-35k would you expect to be 'not satisfied' with life?
Thanks in advance!

A: HINT: The expected values are defined as the the frequencies that should be found in each cell of the table assuming no association between the two variables.
The expected value for each cell is obtained by multiplying the row total to the column total, and then dividing by the grand total.

A: Below is analysis of this data table using the chisq.test procedure in R.
Nothing here is classified 'secret'; formulas for everything should be in
the course textbook.
Data table:
vs = c(13,11,19,15)
ss = c(29,31,28,12)
ns = c(34,20,10, 8)
TBL = rbind(vs,ss,ns);  TBL
   [,1] [,2] [,3] [,4]
vs   13   11   19   15
ss   29   31   28   12
ns   34   20   10    8
rowSums(TBL)
vs  ss  ns
58 100  72
colSums(TBL)
[1] 76 62 57 35

Chi-squared test:
The test statistic (X-sq in printout) is
$$Q = \sum_{i=1}^r\sum_{j=1}^c \frac{(X_{ij}-E_{ij})^2}{E_{ij}},$$
where the table has $r = 3$ rows and $c = 4$ columns, $X_{ij}$ are
observed cell counts, and $E_{ij}$ are expected counts determined
from table row and column totals in accordance with the null hypothesis.
Provided that all $E_{ij} \ge 5,$ the test statistic $Q$ has approximately
a chi-squared distribution with degrees of freedom $\nu = (r-1)(c-1) = 6.$
chi.out = chisq.test(TBL); chi.out

        Pearson's Chi-squared test

data:  TBL
X-squared = 20.008, df = 6, p-value = 0.00276

Notice that you can match the output here with results included in your Question.
The expected counts $E_{ij}$ are available:
chi.out$exp
       [,1]     [,2]     [,3]      [,4]
vs 19.16522 15.63478 14.37391  8.826087
ss 33.04348 26.95652 24.78261 15.217391
ns 23.79130 19.40870 17.84348 10.956522

In particular, following @Anatoly's response (+1), $E_{31} = \frac{76(72)}{230} =  23.7913,$
can be obtained from appropriate row and column totals of the table.
Figure: Below is a plot of the density function of $\mathsf{Chisq}(\nu = 6)$ along with
the 5% critical value of the test (vertical dotted line) and the observed value
of $Q = 20.01$ (solid line). The 95th quantile $c = 12.5916$ of the chi-squared distribution
can be found in printed tables of chi-squared distributions or from R (see below).
qchisq(.95, 6)
[1] 12.59159

The exact P-value (here $0.003),$ often shown in computer printouts, cannot usually be found from printed tables. The value from R is shown below:
1 - pchisq(20.008, 6)
[1] 0.00276033

In the figure below the area to the right of $c$ under the chi-squared density curve
is 5% and the (very small) area to the right of $Q$ is $0.003.$


text:
Q: jboss 5 stop start application without bouncing container I'm using jboss 5 on solaris and have a simple question.
If a single server is hosting multiple web applications is it possible to stop/start/restart an individual application without bouncing the entire server from the jmx console/command line.
The setup we have at work is that each application is hosted by a different jboss instance, this was done as no-one knows how to stop/start individual apps without affecting the other. This doesn't make sense to me and creates additional load on the server. I know in glassfish you can do it through the admin console but the jmx console is not so user friendly to make this obvious to me
thanks sapatos

A: Yes. Go in admin-console at http://localhost:8080/admin-console to the respective web-app and then on the operations tab from where you can invoke start/stop/restart.
You can of course also do it in jmx-console.


text:
Q: Is it possible to remove a file from the circular dependency chain check? Usually, circular dependencies are a sign of bad design in Angular. I have a specific feature that triggers circular dependencies and I am not surprised in this case.
The feature is a route pipe which allows me to generate urls dynamically in the templates by using the route name and route parameters, e.g. <a routerLink="{{ 'my_route_name' | route : {param1: value1, ...} }}"> . This is very handy.
But here is the consequence: the route pipe has an indirect dependency on every view component. And as soon as the route pipe is used by some components template, the circular dependency is there. I don't think this can be avoided, this is by design and I accept this.
But the warnings are here and they bother me. I would like to avoid disabling the whole circular detection mechanism because it's a good check. So, my question is as follows: is there a way to remove a file from the check? other ideas which could help me solve this issue are welcome.
Thanks


text:
Q: php - Find array for which a key have a given value I have an array of dictionnaries like:
$arr = array(
    array(
        'id' => '1',
        'name' => 'machin',
    ),
    array(
        'id' => '2',
        'name' => 'chouette',
    ),
);

How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?

Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.

A: Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).

A: As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
    1 => 'machin',
    2 => 'chouette',
);

This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.

A: $name;
foreach ($arr as $value){
    if ( $value['id'] == 2  ){
        $name = $value['name'];
        break;
    }
}

A: I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }

The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');

Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
    if($value == "machin"){
        return $key;
    }
}

But of course the same would work with your old array:
foreach($arr as $item){
    if($item['name'] == "machin"){
        return $item['id'];
    }
}

It depends on what you are planning to do with the array ;-)

A: It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
    if($v['id'] == '2') {
         $name = $v['name'];
         break;
    }
}
echo $name;

So no, you are not forced to reindex the array, but it would make things easier.

A: array_key_exist() is the function to check for keys.  foreach will help you get down in the multidimensional array.  This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
    foreach($bigArray as $array) {
        if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
            return $array['name'];
        }
    }
    return false;
}

//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"


text:
Q: Java/JAXB: Unmarshall XML elements with same name but different attribute values to different class members I am trying to parse XML that has several "Fields" elements to different class members according to one of their attributes.
Here is the XML:
<Series>
    <Fields type="SelectedFields" operation="SUM">
        <Field name="Remaining" />
        <Field name="Invested" />
    </Field>
    <Fields type="FirstSelectedFields" operation="SUM">
        <Field name="Estimated" />
    </Field>
</Series>

And here is the java class it should be mapped to:
public class APMSeries {

    private List<Field> selectedFields;

    private List<Field> firstSelectedFields;

}

Can anyone tell me how can I set the Fields element with attribute type="SelectedFields" to the selectedFields member and the Fields element with the attribute type="FirstSelectedFields" to the firstSelectedFields member?

A: public class APMSeries {

    @XmlElementWrapper(name="SelectedFields")
    private List<Field> selectedFields;

    @XmlElementWrapper(name="FirstSelectedFields")
    private List<Field> firstSelectedFields;

}


text:
Q: SizeChanged event but only after total change is done I need to use the SizeChanged event of a windows Chart for replotting in correct scale whenever the user resises the form.
But while the user is resizing the form (normally, by dragging the form's borders), this event is fired a lot of times and I don't want to keep replotting during the total operation, only when the user stops resizing the form.
Is there a way to do this?

A:
While the user is resizing the form (normally, by dragging the form's borders), this event is fired a lot of times and I don't want to keep replotting

You can handle this behavior by using the Form.ResizeEnd Event. This event is raised when the user finishes resizing a form, typically by dragging one of the borders or the sizing grip located on the lower-right corner of the form, and then releasing it.
For example:
private void Form1_ResizeEnd(Object sender, EventArgs e)
{
   MessageBox.Show("You are in the Form.ResizeEnd event.");
}

Update:
As per comment below by @Reza Aghaei, this event will not be raised in case a user selects the Maximize button. Please see his answer there for more details.
References:
Form.ResizeEnd Event on Microsoft


text:
Q: Outputting files from Mapping Data Flow in defined hierarchy is slow When using Data Factory to transform data and output with a set filename and path pattern, performance doesn't meet expectations. The main performance bottleneck appears to be the way files are written. Azure Data Lake Storage (Gen 2) is being used in this instance.
The transformation is being done via a Mapping Data Flow. A sink filename is being generated via a Derived Column activity, which is then used in the sink (Delimited Text) with 'File name option' set to 'As data in column' and the field is selected.
From what I've observed, when the pipeline runs the files are written to a temporary location then moved to the intended target location.
[Temp location]
- GUID
  - SinkFilename=<escaped full target path>

[Final destination]
- GUID
  - Year
    - Month
      - Data.csv

It's the second part of this process that seems very slow where only 5 or so files were being moved per second. When there are thousands of files being output it's unsuitably slow.
Documentation for data flow performance details the overhead of this 'shuffle' process, but doesn't provide guidance on any alternate approach. If have seen an example where partitioning was set to key columns which was then reflected in the folder hierarchy as Year=2020/Month=05/<generated file names> which wasn't optimal from an output perspective.
What is the best approach to maintaining performance while outputting files in a defined structure for other systems to comsume?


text:
Q: Can apps downloaded under another Apple ID be transferred to new iPhone? I'm recently planning to upgrade my iPhone from an 8 plus to a 14 plus. There is an app, Shadowrocket, I purchased an vpn service, along with an bought version of Shadowrocket from others, so I have to download the app under another Apple ID. The country I'm in, the app store does not have the app.
That is not downloaded under my personal Apple ID, I'm concerned about whether, as the title says, the app can be transferred to an new iPhone.
ps. the 8 plus is on iOS 15.7.1.

A: I've removed the spoiler tags but it's still not clear quite what your sequence of events is.
Apps themselves do not transfer from phone to phone - they are re-downloaded from the App Store, even if you set up the new phone from a backup of the old.
You cannot transfer any app to a different owner. If it was downloaded under different credentials it will need those credentials again to re-download - which would not be possible if it's not on your country's app store.


text:
Q: Can I sync HTML text or divs with SWF (Flash character animation)? I have flash animation (swf) in my HTML Page.
Now, I like to have my flash animated character (700kb) to speak dialogues, the related text should pop and go in the html side of the page.
I've already used this amazing cool script from Text highlight with audio sync in Jquery by Marnix van Valen  & HTML5 works cool as he says. BUT, what about flash???.
Is there any way to do this? thanks in advance.

A: Perhaps you need to run some code from flash file, there is a good tool for it - ExternalInterface
for example as3 code:
class Character {
  public function say(msg:String):void
  {
    trace(msg);
    ExternalInterface.call('say', msg);
  }
}

js code on the html page where your swf embedded:
<script>
function say(msg) {
  alert('character says: ' + msg);
}
</script>

So when you run character.say('hi') you'll get new message in flash console (from trace) and popup with your message.
Hope this helps.


text:
Q: How do I reference the hashed image (in the html page in the dist folder) after it has been created with copy-webpack-plugin? I have in my index.ejs file (you can consider this the .html file) a classic tag  that I'm copying in the dist folder with copy-webpack-plugin
My problem is that in 'production' mode I add an hash to my image instead in the index.ejs file the attribute src of the  still will point to the image without the hash. Thus my index.html in the dist folder doesn't display the image.
Thi is my project :
https://github.com/cuccagna/Webpack28
For convenience I put here the package.json , the webpack.production.config.js and the index.ejs files:
webpack.production.config.js

const pathM = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
/* const { CleanWebpackPlugin } = require('clean-webpack-plugin');
 */
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
   entry: './src/js/index.js',
   output: {
      filename: 'js/bundle.[contenthash].js',
      path: pathM.resolve(__dirname, './dist'),
      assetModuleFilename: '[path][name].[contenthash][ext]',
      publicPath: './',
      clean: true /* {
         dry: false,
         keep:/\.css$/
      } */   //Serve per cancellare la cartella dist dalla precedente esecuzione
   },
   mode: 'production',
   module: {
      rules:[
         {
            test: /\.(png|jpe?g|webp|avif|gif|svg)$/,
            type: 'asset',
            parser: {
               dataUrlCondition: {
                  maxSize: 3 * 1024 //3 Kilobytes QUI CAMBIA LA SOGLIA A 3 KByte

               }
            }
         },

         {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader,'css-loader']
         },
         {
            test: /\.scss$/,
            use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
         },
         {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
               loader: 'babel-loader',
               options: {
                  presets: [['@babel/env', {
                      targets: "> 0.1%, not dead",
                     debug:true,
                     useBuiltIns: 'usage',
                     //Puoi mettere anche solo version:3
                     //La versione la puoi prelevare da package.json
                     corejs:{version:3.26 , proposals:true}
                  }]],
                  //plugins: ['@babel/plugin-proposal-class-properties']
               }
            }
         }
      ]
   },
   plugins: [
       new CopyWebpackPlugin({
         patterns: [
             { from: './assets/img', to: './assets/img/[name].[contenthash][ext]' },

          ],
          options: {
        concurrency: 100,
      }
      }),
      new MiniCssExtractPlugin({
      filename:"css/main.[contenthash].css"
      }),
      new HtmlWebpackPlugin({

         inject: false,
         template: "./index.ejs", //Puoi mettere anche un file html
         minify:true
      })

   ]

}

package.json

{
  "name": "project5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress --profile --config webpack.production.config.js",
    "dev":"webpack --progress --profile --config webpack.dev.config.js",
    "watch": "webpack --progress --profile --watch"
  },
  "watch": {
    "build": "./src"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.7.2",
    "npm-watch": "^0.11.0",
    "sass": "^1.56.2",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1"
  },
  "dependencies": {
    "core-js": "^3.26.1"
  }
}

index.ejs

<!DOCTYPE html>

      <title>Custom insertion example</title>

      <% if (process.env.NODE_ENV === 'production'){%>
       <%  for(var i=0; i < htmlWebpackPlugin.files.css.length; i++) {%>
      <link
         type="text/css"
         rel="stylesheet"
         href="<%= htmlWebpackPlugin.files.css[i] %>"
      />
      <% } }%>

      <button class="hello-world-button">Ciao</button>

      <% for(var i=0; i < htmlWebpackPlugin.files.js.length; i++) {%>

      <% } %>

A similar problem is described here:
https://github.com/webpack-contrib/copy-webpack-plugin/issues/279
I tried to fix the problem from myself but I can't figure how to proceed.


text:
Q: Is it possible to include one Caffe's prototxt file in another? Caffe requires at least three .prototxt files: for training, for deployment and to define solver parameters.
My training and deployment files contain identical pieces, describing network architecture. Is it possible to refactor this, by moving this common part out of them into a separate file?

A: You are looking for "all-in-one" network.
See this github discussion for more information.
Apparently, you can achieve this by using not only include {phase: XXX}, but also take advantage of stage and state.


text:
Q: Multiparticle States in String Theory I am new to string theory and I hope that the following question, if not actually deep, may provoke answers that might not only be useful to me but also to other newcomers:
I believe to have understood that, when first quantizing a free string, the resulting Hilbert space is that of different "one particle states" of different "particles" (e.g. Zwiebach, 2nd ed., 2009, section 12.6, page 267: "Each state |Lambda> of the quantum string represents a one-particle state of fixed momentum. Thus, the ... are one-photon states, and the a ... are one-particle tensor states not two-photon states", or alternatively see also Tong chapters 2 - 3, http://www.damtp.cam.ac.uk/user/tong/string.html ).
Now, the most natural way for me to construct a two particle state |1,2> out of known one particle states |1> and |2> would be to form |1>|2> + |2>|1> (or the antisymmetric counterpart), i.e. to ultimately build a new Fock space of free multiparticle states out of free one particle states and to formulate creation/annihilation operators in that space, and to try to find a Hamiltonian acting in that space such as to formulate interacting theories. I guess this is what string field theory is trying to do, but I am not entirely sure.
Instead, this route is apparently not followed in any textbook known to me, and rather two or more particles are later on handled by the usual scattering formalism that considers a sum over worldsheets of more complicated topology, e.g. Zwiebach, section 25.3 "Two strings, with energies E1 and E2, can come together to form a single open string, of energy E1 + E2", or Tong chapter 6.
I have two questions:
1) why is the Fock space formalism suggested by me above not introduced (not even as a counterexample) or followed in the textbooks? The idea seems natural and not very deep to me. So why not? Is it wrong, or a dead end? If so, why and where does it fail? Is it eventually getting too complicated? Why?
2) assuming the suggested Fock space formalism was sound in principle: can one show its equivalence to the usual multiparticle treatment in string scattering amplitudes (possibly the same question: is Tong chapter 6 "derivable" from a string field theory? If so, what Hamiltonian is used for deriving first quantized string theory?)
I would be truly grateful for explanations, clarifications, and especially also for pointers to the literature (preferably, if at all possible, at a beginner's level).

A: Thanks for all replies/comments to my post. By using them as a starting point, I believe to have eventually found what I have been asking for, i.e. is it possible to use one string product states to define multi-string states and to obtain the "usual" scattering amplitudes also from this viewpoint. The answer seems to be "yes" (as expected) and the papers one might want to read are indeed relating to the operator formalism for String Field Theory, including, for example:
Charles B. Thorn, String field theory, Physics Reports, Volume 175, Issue 1, 1989, Pages 1-101, ISSN 0370-1573, http://dx.doi.org/10.1016/0370-1573(89)90015-X
Charles B. Thorn, Perturbation theory for quantized string fields, Nuclear Physics B, Volume 287, 1987, Pages 61-92, ISSN 0550-3213, http://dx.doi.org/10.1016/0550-3213(87)90096-4
David J. Gross, Antal Jevicki, Operator formulation of interacting string field theory (I), Nuclear Physics B, Volume 283, 1987, Pages 1-49, ISSN 0550-3213.
These papers use special "product" definitions (e.g. eq. (2.19) in the Gross, Jevicki paper), which is not surprising since different string excitations correspond to different types of particles: thus the need for a special Fock space construction was anyway to be expected.
PS: "Hamiltonian Formulation Of String Theory And Multiloop Amplitudes In The Operator Context", by Adrian R. Lugo, Jorge G. Russo, SISSA, Trieste, Nov 1988 as cited above by Jake Lebovic brought me on the right track (so special thanks to him), even though, if I am not mistaken, that paper is not constructing multi-string product states, but rather uses an operator approach to rewrite the sum over higher genus topologies within the standard scattering formalism.


text:
Q: Is my design for UDP socket server correct? I am designing a server which is used in UDP communication using MFC. I have the following classes

*

*CMyDlialog - Take care of User interface

*CController - Act as an Mediator between all the classes

*CProtocolManager - Take care of Encoding/Decoding msgs (This is a static class)

*CConnectionManager - Take care of UDP connection, Sending, Receiving

I am creating an object of CConnectionManager as a member variable in CController and object of CController as member variable in CMyDialog.
When user type something and presses send, I am calling a method in CControler which will call a method in CProtocolManager to construct the packet and call the CConnectionManager method to send it.
When i receive some data, it is handled in a thread of CConnectionManager. There i am creating a local object of CController and call a method, which will pass the data to CProtocolManager to decode.
Now i want to inform the UI about the data, how should the CControler do it? i can post a message to the UI by making the main dialog handle global, is that a correct approach.
Also tell me whether this design is correct one.
Thanks in advance

A: It seems you are doing it all in a single thread. Since it takes time for packets to go back and forth, it's advised to make do to time-consuming job in a different thread, and post status/results the UI thread. (Or the UI will be frozen).

A: I think designs are never right or wrong, but you can rate them according to some principles that many people consider to be "good" (see the SOLID principles).
Your sending approach sounds reasonable, but making the Dialog global for receiving is definitely considered "not so good". See the hollywood principle. I suggest you better pass a callback method to your connection manager that is a method of CController (which then lets CProtocolManager decode it and calls another callback method from the dialog). If callbacks are not what you want you can define AbstractBaseClasses (ABC) like this "AbstractMessageReceiver" with a method
 virtual void receive(const char*, int length) = 0;

You can then implement this ABC in CProtocolManager pass this as a "AbstractMessageReceiver*" to CConnectionManager which then calls
m_myMessageReceiver->receive(m_buffer, m_length);

or something similar.
This approach reduces the coupling, is much more testable and increases the reusability.
Furthermore, I agree with Am that you should think about your threading model!


text:
Q: How does Mongodb $pull work under the hood Imagine the following two documents in a myCollection:
{_id: '1', fruits: ['Apple', 'Banana', 'Lemon']}
{_id: '1', fruits: ['Apple', 'Lemon']}
Is there a difference of performance between:
db.myCollection.update({}, {$pull: 'Banana'}, {multi: true)}
and:
db.myCollection.update({fruits: {$elemMatch: 'Banana'}}, {$pull: 'Banana'}, {multi: true)}

A: //output from mongo client
//ran below queries and compared the output from explain. I did not find any difference in //execution stats for performance
> db.myCollection.explain("executionStats").update(
...    {},
...    {$pull:{fruits:{$in:["Banana"]}}},
...    {multi: true}
...    );
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "test.myCollection",
                "indexFilterSet" : false,
                "parsedQuery" : {

                },
                "winningPlan" : {
                        "stage" : "UPDATE",
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "direction" : "forward"
                        }
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 0,
                "executionTimeMillis" : 0,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 2,
                "executionStages" : {
                        "stage" : "UPDATE",
                        "nReturned" : 0,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 4,
                        "advanced" : 0,
                        "needTime" : 3,
                        "needYield" : 0,
                        "saveState" : 0,
                        "restoreState" : 0,
                        "isEOF" : 1,
                        "nMatched" : 2,
                        "nWouldModify" : 2,
                        "wouldInsert" : false,
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "nReturned" : 2,
                                "executionTimeMillisEstimate" : 0,
                                "works" : 4,
                                "advanced" : 2,
                                "needTime" : 1,
                                "needYield" : 0,
                                "saveState" : 2,
                                "restoreState" : 2,
                                "isEOF" : 1,
                                "direction" : "forward",
                                "docsExamined" : 2
                        }
                }
        },
        "serverInfo" : {
                "host" : "XXXX",
                "port" : XXXX,
                "version" : "4.2.6",
                "gitVersion" : "XXXX"
        },
        "ok" : 1
}
>
--
> db.myCollection.explain("executionStats").update(
...   {},
...   {$pull:
...       {fruits:{$elemMatch:{$in:["Banana"]}}}
...   },
...   {multi: true}
... );
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "test.myCollection",
                "indexFilterSet" : false,
                "parsedQuery" : {

                },
                "winningPlan" : {
                        "stage" : "UPDATE",
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "direction" : "forward"
                        }
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 0,
                "executionTimeMillis" : 0,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 2,
                "executionStages" : {
                        "stage" : "UPDATE",
                        "nReturned" : 0,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 4,
                        "advanced" : 0,
                        "needTime" : 3,
                        "needYield" : 0,
                        "saveState" : 0,
                        "restoreState" : 0,
                        "isEOF" : 1,
                        "nMatched" : 2,
                        "nWouldModify" : 2,
                        "wouldInsert" : false,
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "nReturned" : 2,
                                "executionTimeMillisEstimate" : 0,
                                "works" : 4,
                                "advanced" : 2,
                                "needTime" : 1,
                                "needYield" : 0,
                                "saveState" : 2,
                                "restoreState" : 2,
                                "isEOF" : 1,
                                "direction" : "forward",
                                "docsExamined" : 2
                        }
                }
        },
        "serverInfo" : {
                "host" : "XXXX",
                "port" : XXX,
                "version" : "4.2.6",
                "gitVersion" : "XXXX"
        },
        "ok" : 1
}
>


text:
Q: Azure Functions: serving content for root URL I have an C# Azure Function project, with a variety of functions.
One of the functions is to serve some HTML content. This function can currently be accessed at /api/home. However, I want to have it triggered for the root / URL.
I have added a proxies.json file in my project:
{
  "Home": {
    "matchCondition": {
      "methods": ["GET"],
      "route": "/"
    },
    "backendUri": "https://localhost:7071/api/home"
  }
}

But this still has no effect - it continues to serve up the default Azure Fucntions webpage.
Is there any way to do this?

A: I'm afraid you can't use the root path to access this function, because https://localhost:7071/ is always the default page of Azure function:

Below are my verification steps, I will change the path of the function to https://localhost:7071/, but it still displays the default page of Azure function app.
By default, the route for your azure function would be localhost:7071/api/{functionName}
You must have noticed by now that almost all the function routes had /api/ in the route. In case, you wanted to change it, you can change it by modifying the content using the host.json.
You need to add "extensions": { "http": { "routePrefix": "" } } in your host.json:
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensions": { "http": { "routePrefix": "" } }
}

Now, your route might look like this:
localhost:7071/{functionName}

You also need to set the Route in the code to "".
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "")] HttpRequest req,

The current route should meet your requirements:

But using this path to access this function still fails, so I think it is invalid to set the path of the Azure function as the root path, and you cannot use it to access your Azure function.
If you deploy to Azure portal, you can try to add "AzureWebJobsDisableHomepage ": true in app settings to disable the homepage of Azure function. I tested it locally and it doesn't seem to work. Azure portal seems to work.

A: You can add a Proxy in the proxies.json file to a selected function and re-direct it to the root url like below
{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "Proxy1": {
      "matchCondition": {
        "route": "/"
      },
      "backendUri": "https://<AnotherApp>.azurewebsites.net/api/<FunctionName>"
    }
  }
}

This will redirect all the calls to the rool URL to the function with name "<FunctionName>"

Bonus Tip:
If you'd like to remove /api from your URL, you can do so by adding the following code in host.json file
  "extensions": {
     "http": {
       "routePrefix": ""
       }
    }

A: I don't know about matchConditions but setting route to / works for me in v4 Functions (Node):
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "route": "/",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}


text:
Q: How did the Caretaker not kill everyone on Voyager when pulling them into the Delta quadrant? We know that ships in the Star Trek universe can travel very fast, but this is still generally limited by the technology of the time. Sometimes travel is accomplished by instantaneous travel using wormholes. Q teleporting, or slipstream travel.
The Caretaker used his array to pull Voyager across the universe. From the way it was depicted in the show, this was essentially a wave of energy that pushed Voyager across space - it didn't transport them immediately, place them into a corridor, or open any kind of 'shortcut' through another dimension.
Assuming that the wave simply accelerated the ship to way above warp-10, how was the entire crew (not to mention the ship itself) not liquefied by the forces? I would assume that the inertial dampeners and whatever other technology was in place could easily handle speeds that the ship was intended to travel at, but Voyager hit speeds exponentially higher than what it was capable of managing on its own. I can't imagine that safety technology of the day could simply mitigate any arbitrary amount of acceleration - surely it had upper limits just like any other tech of the time.

A: We've seen this kind of hyper-acceleration before, with even greater distances - the Enterprise-D was flung to another galaxy in Where No One Has Gone Before.
Given that inertial dampeners are a requirement to prevent turning the crew into warp soup, it does make both the Enterprise and Voyager incidents a bit difficult to reconcile.
The fact that both ships survive their rapid travel, we can only assume that part of the phenomenon causing the hyper-acceleration also somehow protected them. Some curving of space-time which moves the ships without  actually accelerating them (which,  in point of fact,  is how the Alcubierre drive - a theoretical real world radio engine - would work), or some kind of wormhole. This would have been intentional in the case of Voyager, since the Caretaker wanted living specimens.


text:
Q: Stopping students handing in others visual studio 2012 projects (lazy cheating) I'm an assisting marking student work being handed in (vb.net programming projects, absolute beginners).
With other MS products we filter out most of the lazy cheaters simply by looking at the Authors embedded in the property's of the file.

*

*Is there a way to uniquely identify the project author or originating computer a project came from?

*Is there a simple way to embed a unique code into each starter project hidden from students?


text:
Q: How to position JPanel to upper right corner of JFrame I have written a board game and have gotten to the point where I want to add a timer to the right corner of my JFrame. I was thinking it might be best solved through putting a JPanel in the upper right corner that I then will update with the count down time. However, I have run into the issue that I can't seem to figure out how to place the JPanel to a set location. Whatever I try to do it just seems to cover the entire screen, rather than the size and location I have put it to.

    private final JFrame frame = new JFrame("myBoardGame");
    private JPanel jp = new JPanel();

    public ShowBoard(Board board){
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setContentPane(board);
        frame.setLayout(new BorderLayout());
        frame.pack();
        frame.setVisible(true);
        jp.setLayout(null);
        jp.setLocation(300,300);
        jp.setSize(100,100)
        frame.add(jp);
        this.board = board;
        getKeyBindings(); }

Instead of it moving to the location 300x300 and setting it size to 100x100 it makes the entire screen go grey. What am I doing wrong? I simply want to be able to move the JPanel around the JFrame to where it fits best.

A: You can use a BorderLayout contentPane, as the frame's content pane. This pane would include:

*

*In its BorderLayout.NORTH position, a JPanel (timerPane) with a FlowLayout (with orientation ComponentOrientation.RIGHT_TO_LEFT). You can use this panel to house your timer Component.

*In its BorderLayout.CENTER position, your board.

Your code (modified to include this considerations) would look like this:
private final JFrame frame = new JFrame("myBoardGame");
private JPanel contentPane = new JPanel(new BorderLayout());
private JPanel timerPane = new JPanel(new FlowLayout());

public ShowBoard(Board board){
    timerPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    contentPane.add(timerPane, BorderLayout.NORTH);
    contentPane.add(board, BorderLayout.CENTER);

    frame.setResizable(false);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setVisible(true);

    this.board = board;
    getKeyBindings();
}


text:
Q: Facebook Graph API get access token I'm new to Facebook Development using PHP. I have created a nice script which gathers the facebook news feed from my fan page to a JSON array using the graph api....
eg//
  $url="https://graph.facebook.com/".$fbID."/feed?access_token=".$token."&limit=20";

(ghdn using the curl commands to collect the JSON..)
The problem is the access token expires after 2 hours, how can I make this not expire or renew?
Thanks for any help...

A: If your fan page is public and has no restrictions like demographic restriction, then you can use your App Access Token to query and retrieve your fan page's feed.
In case your fan page is having restrictions you may use Page Access Token by giving your app manage_pages permission and retrieving Page Access Token using following Graph request
/{user-id}/accounts


text:
Q: Power BI - calculating duration between calls time_start column holds start of conversation
time_ends column holds end of conversation, both are in time type of data in hh:mm:ss format
how can I calculate time duration between calls:
time_between_calls = time_start2 - time_end1

time_start2 - start of 2nd call
time_end1 - end of 1st call
I need to create measure which will give average of that duration for xy calls.
I don't know how to calculate this. I guess I need some kind of temporary table where I would sort dates first.
Any hint could be useful.
I forgot to add that I need to filter by agent_id first in order to get call information only for that individual agent.
So
FOR EACH agent_id do {
all above }

A: I've manage to solve it by following this solution.