text:
Q: String test, with complicated arguments I have a command \mycom{} which takes 1 argument. The command should perform a test on the argument and do something accordingly. For simple arguments, I can use \ifthenelse, but I need to consider more general arguments, e.g. containing commands or environments.
The following MWE follows a solution for a more robust string test, which was given in this post:
\documentclass{article}
\makeatletter
\newcommand{\strtest}[2]{%
\ifnum\pdfstrcmp{#1}{#2}=\z@
  \expandafter\@firstoftwo
\else
  \expandafter\@secondoftwo
\fi}
\makeatother

\newcommand{\mycom}[1]{%
\strtest{#1}{}%
{content :  empty}%
{content : #1}%
}

\begin{document}
\mycom{}

\mycom{coucou}
\end{document}

This works. But if i try to call \mycom{\textbf{coucou}}, then the compilation fails.

A: The \pdfstrcmp primitive fully expands its argument. Thus things go wrong with macros that cannot be expanded, which includes \textbf. You can prevent this using the \unexpanded primitive:
\newcommand{\strtest}[2]{%
  \ifnum\pdfstrcmp{\unexpanded{#1}}{\unexpanded{#2}}=\z@
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}

A: I want to show an alternative. Based on the LaTeX3 engine one approach is:
\documentclass{article}
\usepackage{xparse,expl3,}
\ExplSyntaxOn

\NewDocumentCommand{ \mycom } { m } {
 \tl_if_empty:nTF { #1 }
   {content:~empty}
   {content:~#1}
}
\ExplSyntaxOff
\begin{document}
\mycom{}

\mycom{coucou}

\mycom{\textbf{coucou}}
\end{document}

Base on the comments question you can compare strings with:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\mystringcase}{  m }
  {
    \prg_case_str:nnn { #1 }
         {
          { a }  { Your~string~\textbf{a} }
          { b }  { Your~string~\textbf{b} }
          { c }  { Your~string~\textbf{c} }
         }
         { Not~in~list }
  }
\ExplSyntaxOff
\begin{document}
\mystringcase{a}

\mystringcase{b}

\mystringcase{d}
\end{document}


text:
Q: When does kafka producer start clocking linger.ms Here, for batch.size:

This setting gives the upper bound of the batch size to be sent.
If we have fewer than this many bytes accumulated for this partition,
we will 'linger' for the linger.ms time waiting for more records to
show up. This linger.ms setting defaults to 0, which means we'll
immediately send out a record even the accumulated batch size is under
this batch.size setting

So when does system start clocking the time to track linger?

A: The clock starts when the batch is created, i.e when the first record is added to it, i.e. the first time the app calls .send() for that partition since the last time the Kafka client sent a batch (or since the app started if it's the first batch).
This batch will then be closed and sent when it's full (i.e. when batch.size is reached) or when linger.ms milliseconds have elapsed since the batch was created, whichever comes first.
linger.ms = 0 is essentially equivalent to no batching, which optimizes latency at the expense of throughput.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constructing An if Statement with is_category(); in archive.php (WordPress) I am trying to use an if statement with is_category() in order to build a bigger piece of code later. I can't get the code to recognize the if statement though. Basically below I've posted the coding with the if statement commented out. It works without the if statement but if I uncomment the if statement (and the closing curly bracket) then there is an error and the page doesn't display. I am only checking this on a category page so I assumed it should recognize that it is a category page and display the posts (I can understand it being a problem if I was on a 'tag' archive page, etc.). Why would this have a problem displaying?
EDIT
I've included a bunch of code before the relevant code BTW so there is a context. The conditional if (is_category()) works when applied to the title of the page (i.e. Archive for the NEWS category) but then just a little further down it doesn't work...
(btw, I do understand there is a WordPress stack exchange site but I rarely get answers to my questions on there. I have submitted this question there as well but thought someone could help me here as well, given that the answer is PHP related. Thanks!)
  <?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
  <?php /* If this is a category archive */ if (is_category()) { ?>
    <?php _e('
Archive for the ·
', 'life-is-simple'); ?>
<?php single_cat_title(); ?>
<?php _e('
· Category...
', 'life-is-simple'); ?>
  <?php /* If this is a tag archive */ } elseif( is_tag() ) { ?>
    <?php _e('
Posts tagged ·
', 'life-is-simple'); ?>
<?php single_tag_title(); ?>

·...

  <?php /* If this is a daily archive */ } elseif (is_day()) { ?>
    <?php _e('
Archive for
', 'life-is-simple'); ?>
<?php the_time('F jS, Y'); ?>

...

  <?php /* If this is a monthly archive */ } elseif (is_month()) { ?>
    <?php _e('
Archive for
', 'life-is-simple'); ?>
<?php the_time('F, Y'); ?>

...

  <?php /* If this is a yearly archive */ } elseif (is_year()) { ?>
    <?php _e('
Archive for
', 'life-is-simple'); ?>
<?php the_time('Y'); ?>

...

  <?php /* If this is an author archive */ } elseif (is_author()) { ?>
    <?php _e('
Archive for the author ·
', 'life-is-simple'); ?>
<?php echo $curauth->display_name; ?>

·...

  <?php /* If this is a paged archive */ } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?>
    <?php _e('
Blog archives...
', 'life-is-simple'); ?>
  <?php } ?>

<?php if (have_posts()) : ?>

<?php
/*if (is_category()) {*/
if ($paged == 0)
  $offset = 0;
else
  $offset = ($paged - 1) * 11;
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 11, 'offset' => $offset, 'category__in' => array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
foreach($myposts as $post) :
setup_postdata($post);
/*}*/
?>

A: The problem isn't the if is_category() check. You can verify that yourself by simply trying:
if(is_category()) {
  echo "category!";
}

When I tried running your code as-is I also "got an error." That type of super-error means the PHP is badly formatted, so badly that PHP couldn't even tell you where to look to fix the problem.
Here's how I rewrote the code so that it would run:
if ($paged == 0) {
  $offset = 0;
}
else {
  $offset = ($paged - 1) * 11;
}

global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 11, 'offset' => $offset, 'category__in' =>   array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
foreach($myposts as $post) {
  setup_postdata($post);
}

A: like itecedor said, there's nothing problematic about your conditional ( apart from the not-so-usual but irrelevant, space after the keyword if)
i've changed the syntax for the foreach to a more conventional syntax and the 500 error is gone:
foreach($myposts as $post) setup_postdata($post);

A: The problem is that you aren't terminating your foreach. If, While, and Foreach statements can be set up one of two ways:
Less common method:
<?php
if(true) :
    do_stuff();
endif;
while(true) :
    do_stuff();
endwhile;
foreach($arr as $var) :
    do_stuff();
endforeach;
?>

Common method:
<?php
if(true)
{
    do_stuff();
}
while(true)
{
    do_stuff();
}
foreach($arr as $var)
{
    do_stuff();
}
?>

You should set your code up like so:
<?php
if (is_category())
{
    $offset = $paged ? ($paged - 1) * 11 : 0;
    global $post;
    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;
    $myposts = get_posts(array('numberposts' => 11, 'offset' => $offset, 'category__in' => array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
    foreach($myposts as $post)
    {
        setup_postdata($post);
        the_title(); //JUST SO YOU KNOW IT'S WORKING
    }
}
?>


text:
Q: Eclipse extreme slow at auto completion i have the following Problem:
I have a maven project and in these project eclipse is very slow. Sometimes it freeze for serveral seconds. And if want to use auto completion it takes up to one minute before this message is shown:

The 'org.eclipse.jdt.ui.JavaAllCompletionProposalComputer' proposal computer from the 'org.eclipse.jdt.ui' plug-in did not complete normally. The extension took too long to return from the 'computeCompletionProposals()' operation.

I can fix that issue by disable java proposals under content assist -> advanced. But then the auto completion wont work anymore.

A: Try to change these memory values to eclipse.ini file (In your eclipse directory)

-Xms1024m
-Xmx4096m

These values depends on your system.

A: I don't know why, but after i deleted the .metadata folder in my workspace everything works correctly now.
Thanks for your help guys :)
Edit: thanks for the comments, a better solution would be the way howlger decripded in his comment.


text:
Q: Date jumps to year 2285 in Vagrant It happened yesterday, and today again.
The vagrant box on my machine jumped to the year 2285
(venv3.9.0) root@v-yf:/var/log# timedatectl
                      Local time: Mon 2285-09-21 06:15:40 CET
                  Universal time: Mon 2285-09-21 05:15:40 UTC
                        RTC time: Thu 2021-01-07 14:25:15
                       Time zone: Europe/Berlin (CET, +0100)
       System clock synchronized: no
systemd-timesyncd.service active: yes
                 RTC in local TZ: no

From /var/log/syslog
Jan  7 14:35:01 v-yf CRON[5823]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Sep 21 05:32:03 v-yf kernel: [8318599810.152743] hrtimer: interrupt took 80102242147 ns
Sep 21 05:32:03 v-yf kernel: [8318599810.152814] clocksource: timekeeping watchdog on CPU0: Marking clocksource 'tsc' as unstable because the skew is too large:
Sep 21 05:32:03 v-yf kernel: [8318599810.152825] clocksource:                       'kvm-clock' wd_now: 73719a74f60024e0 wd_last: 11027f6d11a9 mask: ffffffffffffffff
Sep 21 05:32:03 v-yf kernel: [8318599810.152834] clocksource:                       'tsc' cs_now: fffff7900a43c874 cs_last: 25b8395a9da9 mask: ffffffffffffffff
Sep 21 05:32:03 v-yf kernel: [8318599810.152843] tsc: Marking TSC unstable due to clocksource watchdog

My laptop runs Ubuntu 20.04, Vagrant Ubuntu 18.04
It already happened three times.
What could be the reason?


text:
Q: How control ubuntu as a speaker bluetooth I connected my phone to the PC and any sound that plays on the phone, can play and be heard in my PC speakers.
Now I want to be able to control my phone media through the computer keyboard in Ubuntu (With media keys or anything) but I can't control the musics to next sound or previous.
How can I do this?

A: I found the solution myself.
Install blueZ and by below commands, you can control your phone (or any bluetooth device).
For example for the next music:
dbus-send --system --print-reply --dest=org.bluez /org/bluez/hci0/dev_11_22_33_44_55_66 org.bluez.MediaControl1.Next

find your device MAC Address and replace with 11_22_33_44_55_66
Note: D-feet can help you to see bluez data.
Finally you can Add custom shortcut keyboard in setting for run your commands.
enjoy.


text:
Q: Client certificate with Hybrid Authentication Flow I'm developing a authentication/authorization server with IdentityServer3 and everything worked fine until now.
I'm trying to verify the hybrid flow client by a X509Certificate instead of the hashed secret in the samples.
My question is: How do I configure the client application to send the certificate for the authentication flow?
I saw in the source code for X509CertificateSecretParser.cs in order to get the client certificate, the owin environment variable "ssl.ClientCertificate" must have a value, but I cannot find where this value is set, even in the Microsoft.Owin source code.
I also try to use the certificate that I'm loading on the server as the SSL certificate for the client application, but this doesn't work too.
Code for setup the client secret:
[my client].ClientSecrets.Add(new Secret
{
    Value = Convert.ToBase64String(cert.Export(X509ContentType.Cert)),
    Type = Constants.SecretTypes.X509CertificateBase64
});

Code for setup de authentication of the client application:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    Authority = ...,
    Scope = ...,
    ClientId = ...,
    RedirectUri = ...,
    ResponseType = "code id_token token",
    ClientSecret = "" , //What should I do with this?
    SignInAsAuthenticationType = "Cookies",
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        RedirectToIdentityProvider = ...,
        AuthorizationCodeReceived = ...
    }
});

A: a) You need to enable client certificates on IIS - our host has this commented out:
https://github.com/IdentityServer/IdentityServer3/blob/master/source/Host.Web/Web.config#L19
This will populate the OWIN SSL environment variable after a successful HTTPS handshake.
b) The OpenID Connect middleware will not automatically contact the token endpoint for you. You need to do that manually. This way you can configure the client cert to use. Here's a sample:
https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/Clients/ClientCertificateConsoleClient/Program.cs#L26


text:
Q: Can't connect to local server with android emulator I am trying to develop a simple android login and registration application which will fetch data from local server(for now). I am using android studio and WAMP server. I have provided the internet permission in the manifest file. I have tried the urls:

*

*10.0.2.2

*127.0.0.1

*192.168.1.5(my IPv4 address)

*192.168.1.5:8080

*localhost:80

Still evry time it shows
org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.5:8080 (or any of the above) refused

I have been trying this and followed every advice but the application stops unfortunately(as the emulator says).I have posted all my required java files and logcat in my previous question here: Unfortunately the application stopped working.
It would be of great help if anyone guides me on this.

A: Use 10.0.2.2:8080 to connect to local server if server is running at port number 8080
Thanks

A: I had same problem, until I got here
FYI: I had to change port on Wampserver (from port 80 to port 8080, because port 80 was already used (cmd, netstat -aon).
In my java class, I tried above addresses, but only 10.0.2.2:8080 helped for me.


text:
Q: ruby double question mark I came across this piece of ruby code:
str[-1]==??

What is the double question mark all about? Never seen that before.

A: Ruby 1.8 has a ?-prefix syntax that turns a character into its ASCII code value.  For example, ?a is the ASCII value for the letter a (or 97).  The double question mark you see is really just the number 63 (or the ASCII value for ?).
?a    # => 97
?b    # => 98
?c    # => 99
?\n   # => 10
??    # => 63

To convert back, you can use the chr method:
97.chr   # => "a"
10.chr   # => "\n"
63.chr   # => "?"

??.chr   # => "?"

In Ruby 1.9, the ?a syntax returns the character itself (as does the square bracket syntax on strings):
??           # => "?"

"What?"[-1]  # => "?"

A: As Ryan says, the ? prefix gives you the ASCII value of a character. The reason why this is useful in this context is that when you use the index notation on a string in Ruby 1.8 the ASCII value is returned rather than the character. e.g.
irb(main):009:0> str = 'hello'
=> "hello"
irb(main):010:0> str[-1]
=> 111

so the following wouldn't test if the last character of a string was the letter 'o'
irb(main):011:0> str[-1] == 'o'
=> false

but this would:
irb(main):012:0> str[-1] == ?o
=> true

and (provided you know what the ? does!) this is slightly clearer than
irb(main):013:0> str[-1] == 111
=> true


text:
Q: How to get an object in a list with a given Index I made an array which contains a list with locations of a few teleport tiles in a game.
 std::list<vec2> teleportTiles[15];

Here it adds elements to the list:
        std::list<vec2>::iterator lastField = teleportTiles[Index - 144].end();
        float width = i / m_Height;
        float height = i / m_Width;
        teleportTiles[Index - 144].insert(lastField, vec2(ceil(width), ceil(height)));

But now I want to access a random element in this list - but how? Is there something like this: (Which would work in java)
teleportTiles.get(
    myRandom(0, teleportTiles.size() - 1)
);

A:
(Which would work in java)

That's because Java's List takes many forms, most notably LinkedList and ArrayList:

Interface RandomAccess
Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
The best algorithms for manipulating random access lists (such as ArrayList) can produce quadratic behavior when applied to sequential access lists (such as LinkedList). Generic list algorithms are encouraged to check whether the given list is an instanceof this interface before applying an algorithm that would provide poor performance if it were applied to a sequential access list, and to alter their behavior if necessary to guarantee acceptable performance.

Reference

C++'s std::list is a double-linked list, and as such, isn't able to provide efficient random access, so it doesn't provide it at all. If you want random access, use std::vector. Especially if the only other operation you're doing is appending at the end.


text:
Q: What is random seed about? For example the code below. It has a random class. However it always produce the same output everywhere . In this case which item is the seed?
source: link
import java.util.Random;
public class RandomTest {
    public static void main(String[] s) {
        Random rnd1 = new Random(42);
        Random rnd2 = new Random(42);

        System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
        System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
        System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
        System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
    }
}

A: 42 is the seed, as the very same Javadoc says. So, what is a seed? A random number is seldom truly random - often it's a pseudo-random instead. This means it's generated from a function, which is said PRNG (pseudo random number genrator). Being generated from a function, in turn, means that the output is not random anymore, since it's predictable!
However, depending on your needs, this pseudo-randomness may be enough - I said enough because generating random bit is expensive, and I'm not talking about time or memory, but about money (see this link on wikipedia). So, for example, if you need a random value to place enemies in your game, a pseudo-random number is ok - but if your are building security-related software, you want to use a true random number, or at least a cryptographically secure PRNG.
How can we describe a PRNG, like the one used in Math.random()? It's a function, initialized with a seed S that returns an array of values A. Note that, for each integer S, is defined one and only one array A. For example (values are not actual):
                first call     second call     third call
seed: 14329            .18             .82             .5
seed:  3989             .7             .02            .93

So you seed you PRNG with some known value when you want its result to be predictable - for example for testing purposes or to ensure that, each time you run level 1 in your game, the enemies are always placed in the same (pseudo) random places - otherwise you don't need to explicitely pass a seed.

A: Random Seed on Wikipedia:

A random seed (or seed state, or just seed) is a number (or vector)
  used to initialize a pseudorandom number generator.

In other word, it is the number from which a seem-to-be-random sequence will be generated. Therefore, if you use the same number, the senquence will always be the same.
In practice, we usually use System Time as seed.

A: The seed is given as the argument of the constructor of Random; using the same seed will yield the same sequence of numbers. However this is discussed under the link in thet question.

A: In this case the seed is 42. This is the reason for the same output - you use the same seed.
You can use for example
  Random rnd1 = new Random(System.currentTimeMillis())

for different outputs.

A: From the Java documentation in the Random class

Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).
The invocation new Random(seed) is equivalent to:
Random rnd = new Random();
rnd.setSeed(seed);

So 42 is the seed given to the new Random() in your example

A: The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).
The invocation new Random(seed) is equivalent to:
 Random rnd = new Random();
 rnd.setSeed(seed);


text:
Q: Angular 2 Forms - How to patchValue on a nested Form Group that contains an array of objects I've got a form that has the ability to add/remove rows of items. Whenever I want to go to edit my form, I run an asynchronous call to grab some data then patch/set the values of the form controls accordingly. Everything works as expected, however, with my rows of items, when I utilize Angular 2's patchValue function, it only patches a form group with the first object of an array of objects, instead of all of the objects.
So for example, if my form had 3 rows of line items, like in an invoice, only the first one is being populated. Can anyone tell me what I'm doing wrong?
Here is my component functionality
constructor() {
    this.createCheckRequestForm();
}

createCheckRequestForm() {
    this.createRequestForm = this._fb.group({
      issued_date: [new Date().toISOString(), [<any>Validators.required]],
      due_date: [new Date().toISOString(), [<any>Validators.required]],
      invoice_number: ['', [<any>Validators.required]],
      how_to_send: ['Mail', [<any>Validators.required]],
      normal_processing: ['', []],
      is_corporation: ['', []],
      line_items: this._fb.array([this.initLineItem()])
    });
  }

  /**
   *  Init the line item for the form builder
   */
  initLineItem(options?) {
    return this._fb.group({
        description: ['', []],
        coding: ['', []],
        amount: ['', []],
        line_item_types: [[], []]
    });
  }

populateFormWithRequest(requestId) {
    this.formPopulationObs = this._checkRequests.getRequest(requestId).subscribe(requestData => {

      // Iterate through the line items and patch them
      let lineItems = [];
      requestData.line_items.forEach((lineItem, index) => {

        let lineItemTypes = [];
        if(lineItem.line_item_types) {
          lineItemTypes = lineItem.line_item_types;
        }

        // Separate key-store for the coding dropdown models
        this.lineItemCodings[index] = lineItem.coding;

        let lineItemObj = {
          description: lineItem.description,
          coding: lineItem.coding,
          amount: lineItem.amount,
          line_item_types: lineItemTypes,
        }
        lineItems.push(lineItemObj);
      })

      this.createRequestForm.patchValue({line_items: lineItems});
  })
}

If I have an array like this, only the first element shows up in the "patch"
[
 {amount: "600", coding: "-Kfxw732pfWUS5rU0TRu", description: "Cameras"},
 {amount: "600", coding: "-Kfxw732pfWUS5rU0TRu", description: "Lights"}
]

Thanks in advance!

A: Alright, so in order to get this to work, I had actually push form group array elements onto the "line_items" control that already existed THEN patch the values. Here is my updated function:
populateFormWithRequest(requestId) {
    this.formPopulationObs = this._checkRequests.getRequest(requestId).subscribe(requestData => {

      // Iterate through the line items and patch them
      requestData.line_items.forEach((lineItem, index) => {

        let lineItemTypes = [];
        if(lineItem.line_item_types) {
          lineItemTypes = lineItem.line_item_types;
        }

        // Create the item obj
        let lineItemObj = {
          description: lineItem.description,
          coding: lineItem.coding,
          amount: lineItem.amount,
          line_item_types: lineItemTypes,
        }

        const control = <FormArray>this.createRequestForm.controls['line_items'];
        control.push(this.initLineItem());
        control.at(index).patchValue(lineItemObj);
      });
  })
}

A: The same result, a little bit easier - without creating a empty item and overwriting it:

populateFormWithRequest(requestId) {
  this.formPopulationObs = this._checkRequests.getRequest(requestId).subscribe(requestData => {
    this.createRequestForm["line_items"] =

requestData.line_items.forEach(itm=>(<FormArray>this.createRequestForm["line_items"]).push(this.createRequestForm.group(itm)));

));
});
}


text:
Q: How to check that an element is in a std::set? How do you check that an element is in a set?
Is there a simpler equivalent of the following code:
myset.find(x) != myset.end()

A: If you were going to add a contains function, it might look like this:
#include <algorithm>
#include <iterator>

template<class TInputIterator, class T> inline
bool contains(TInputIterator first, TInputIterator last, const T& value)
{
    return std::find(first, last, value) != last;
}

template<class TContainer, class T> inline
bool contains(const TContainer& container, const T& value)
{
    // This works with more containers but requires std::begin and std::end
    // from C++0x, which you can get either:
    //  1. By using a C++0x compiler or
    //  2. Including the utility functions below.
    return contains(std::begin(container), std::end(container), value);

    // This works pre-C++0x (and without the utility functions below, but doesn't
    // work for fixed-length arrays.
    //return contains(container.begin(), container.end(), value);
}

template<class T> inline
bool contains(const std::set<T>& container, const T& value)
{
    return container.find(value) != container.end();
}

This works with std::set, other STL containers, and even fixed-length arrays:
void test()
{
    std::set<int> set;
    set.insert(1);
    set.insert(4);
    assert(!contains(set, 3));

    int set2[] = { 1, 2, 3 };
    assert(contains(set2, 3));
}

Edit:
As pointed out in the comments, I unintentionally used a function new to C++0x (std::begin and std::end). Here is the near-trivial implementation from VS2010:
namespace std {

template<class _Container> inline
    typename _Container::iterator begin(_Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::const_iterator begin(const _Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::iterator end(_Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Container> inline
    typename _Container::const_iterator end(const _Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *begin(_Ty (&_Array)[_Size])
    { // get beginning of array
    return (&_Array[0]);
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *end(_Ty (&_Array)[_Size])
    { // get end of array
    return (&_Array[0] + _Size);
    }

}

A: The typical way to check for existence in many STL containers such as std::map, std::set, ... is:
const bool is_in = container.find(element) != container.end();

A: Just to clarify, the reason why there is no member like contains() in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end() internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find(), which is inefficient. It's better to use find directly, so you can cache your result, like so:
auto it = myContainer.find(key);
if (it != myContainer.end())
{
    // Do something with it, no more lookup needed.
}
else
{
    // Key was not present.
}

Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)

A: Since C++20, there is simply (and at last!) bool std::contains(const K&)
https://en.cppreference.com/w/cpp/container/set/contains

A: You can also check whether an element is in set or not while inserting the element.
The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
For example: Suppose the set already has 20 as an element.
 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

If the element is newly inserted than pair::first will point to the position of new element in set.

A: In C++20 we'll finally get std::set::contains method.
#include <iostream>
#include <string>
#include <set>

int main()
{
    std::set<std::string> example = {"Do", "not", "panic", "!!!"};

    if(example.contains("panic")) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

A: Another way of simply telling if an element exists is to check the count()
if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

Most of the times, however, I find myself needing access to the element wherever I check for its existence.
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it
}

C++ 20
In C++20 set gets a contains function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
if (myset.contains(x)) {
  // x is in the set
} else {
  // no x
}

A: I use
if(!my_set.count(that_element)) //Element is present...
;

But it is not as efficient as
if(my_set.find(that_element)!=my_set.end()) ....;

My version only saves my time in writing the code. I prefer it this way for competitive coding.

A: Write your own:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
  return container.find(elem) != container.end();
}

A: I was able to write a general contains function for std::list and std::vector,
template<typename T>
bool contains( const list<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

// use:
if( contains( yourList, itemInList ) ) // then do something

This cleans up the syntax a bit.
But I could not use template template parameter magic to make this work arbitrary stl containers.
// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

Any comments about improving the last answer would be nice.

A: It's this, by a mile.
bool once(uintptr_t val) {
    return visited.emplace(val).second;
}

How could it be otherwise?
https://godbolt.org/z/9zP77jqMc
func5(unsigned long):
        sub     rsp, 24
        mov     QWORD PTR [rsp+8], rdi
        lea     rsi, [rsp+8]
        mov     edi, OFFSET FLAT:visited2
        call    std::pair<std::_Rb_tree_iterator<unsigned long>, bool> std::_Rb_tree<unsigned long, unsigned long, std::_Identity<unsigned long>, std::less<unsigned long>, std::allocator<unsigned long> >::_M_emplace_unique<unsigned long&>(unsigned long&)
        add     rsp, 24
        mov     eax, edx
        ret

A: //general Syntax
       set<int>::iterator ii = find(set1.begin(),set1.end(),"element to be searched");

/* in below code i am trying to find element 4 in and int set if it is present or not*/
set<int>::iterator ii = find(set1.begin(),set1.end(),4);
 if(ii!=set1.end())
 {
    cout<<"element found";
    set1.erase(ii);// in case you want to erase that element from set.
 }


text:
Q: Load list item to dispaly get_fieldValues? I'm using SharePoint online and have a SharePoint-hosted app.
I have a page with a question form that send data in to Sharepoint using listItem.set_item('GEN_1_blabla', $('#GEN_1').val());
Now in my list when you click on an item it's open in DispForm.aspx and in there i have my question page again how can i get it to load the information to the textboxes in my question page.
I have read about get_fieldValues() but dont know how to get it to work.
var appContext, hostweburl, hostContext, parentWeb, list;

appContext = new SP.ClientContext.get_current();
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
hostContext = new SP.AppContextSite(appContext, hostweburl);
parentWeb = hostContext.get_web();
list = parentWeb.get_lists().getByTitle("CoromaticIFU");

$(document).ready(function () {
    $("#tabs").tabs();
    $(document).tooltip();
    $('#GEN_4').datepicker({ dateFormat: 'yy-mm-dd' }).val();
    $('#save').click(setItems);
});

function setItems() {
   var listCreationInformation = new SP.ListItemCreationInformation(), listItem = list.addItem(listCreationInformation);

    listItem.set_item('GEN_1_Sum_Scope_Assigment', $('#GEN_1').val());
    listItem.set_item('GEN_1_Sum_Scope_Assigment_D', $('#GEN_1_D').val());
    listItem.set_item('GEN_2_CRMname', $('#GEN_2').val());
    listItem.set_item('GEN_2_CRMname_D', $('#GEN_2_D').val());
    (etc)
    listItem.set_item('GEN_19_BYGG_GOLV', $('input[name="GEN19"]:checked').val());
    (etc)
    listItem.set_item('DRI_6_Personnel_Servicetype', $("#DRI_6 option:selected").text());
    (etc)
    listItem.update();

    appContext.load(listItem);
    appContext.executeQueryAsync(function (success) { alert("Din sparning lyckades!"); }, function (sender, args) { alert('Error:' + args.get_message()); });
}

I have tried this with get_fieldValues
function getItems()
{
    listItem.get_fieldValues('GEN_1_Sum_Scope_Assigment', $('#GEN_1').val());
    listItem.update();

    appContext.load(listitem);
    appContext.executeQueryAsync(function (success) { alert("lyckades!"); }, function (sender, args) { alert('Error:' + args.get_message()); });

}

A: Answer:
var item = list.getItemById(92);

$(document).ready(function () {

appContext.load(item);
appContext.executeQueryAsync(function () {
   $('#GEN_1').val(item.get_fieldValues().GEN_1_Sum_Scope_Assigment);
    $('#GEN_1_D').val(item.get_fieldValues().GEN_1_Sum_Scope_Assigment_D);
    $('#GEN_2').val(item.get_fieldValues().GEN_2_CRMname);
    $('#GEN_2_D').val(item.get_fieldValues().GEN_2_CRMname_D);
}, function (sender, args) { alert('Error:' + args.get_message()); });

)};


text:
Q: OAM Header is not seen after adding in Access Manger Protected Resource Policy Authorization Policy I have an OAM and a weblogic server,my web application is hosted in weblogic server .I have protected the web app through OAM and added the response as below

After successfull authenication i am able to view the cookie but not able to view the header in the request.Is there anyother settings to be done?


text:
Q: HP ProLiant DL360 G5 disk diagnostic issue We recently got two used drives (15000) and installed on our HP proliant dl360 G5 server. Created RAID1 and used HP SmartStart CD to perform diagnostics.
Interestingly, the Diagnostic tab immidiately fails on Logical drive testing saying the Disk1 should be replaced, while the Test tab successfully runs all the complete tests on both disks and does not find any issue.
At the meantime, when booting to esxi 5, vSphere periodically shows the Disk1 as Unknown and Logical drive in recovery process. This happens every 5-10 minutes.
Here is the log from HP SmartScan diagnostic:
1 - Device, Test: Logical Drive 1, Storage Controller in Slot 0
1 - Description: The controller has reported a critical error in the drive error log.
1 - Recommended Repair: This drive should be replaced.
1 - Failed Count: 44
1 - Error code: F157
There is also another error log record (see below):
2 - Device, Test: test_components/libstorage.so ID
2 - Description: An unexpected exception occurred while performing an operation.
Exception message: CISS_StatusHandler::evaluate: commandStatus = 4 (INVALID); hexdump of CISS_ErrorInfo: 00000000: __ __ 04 __ 20 __ __ __ __ __ __ __ __ __ __ __ .... ... ........ 00000010: __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ ........ ........ 00000020: __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ ........ ........ Device: Hard Drive 2, Storage Controller in Slot 0 Property name: Bad Target Count
2 - Recommended Repair: Reboot or restart Insight Diagnostics. Retry the test. If the problem persists, upgrade to the latest version of Insight Diagnostics.
2 - Failed Count: 48
2 - Error Code: F62
Note that rebooting didn't help and I was running the latest diagnostic software version.
Anyone has a clue? Is this a real disk issue? BTW, the controller is Smart Array E200i
Thanks in advance

A: Update your firmware.
That's the first step you should take with a system of that vintage, as there have been bugfixes on the Smart Array controller that address issues like yours.
The quickest way to accomplish this is to use the bootable Firmware DVD available from HP. Download it, unzip and burn it to DVD or boot the system via its ILO interface.
Try your array creation after this.
If the firmware change does not help, you may want to try a different set of disks.


text:
Q: why is the following code returning a xml output in webbroswer? const Koa = require('koa');
const app = new Koa();

const main = ctx => {
  if (ctx.request.accepts('xml')) {
    ctx.response.type = 'xml';
    ctx.response.body = '<data>Hello World</data>';
  } else if (ctx.request.accepts('json')) {
    ctx.response.type = 'json';
    ctx.response.body = { data: 'Hello World' };
  } else if (ctx.request.accepts('html')) {
    ctx.response.type = 'html';
    ctx.response.body = '
Hello World
';
  } else {
    ctx.response.type = 'text';
    ctx.response.body = 'Hello World';
  }
};

app.use(main);
app.listen(3000);

I'm playing this koa webframework for nodejs http://www.ruanyifeng.com/blog/2017/08/koa.html. Yet, I'm confused. I do not understand logically why is the above code, after running, would return a xml output. Could anyone shad some lights?


text:
Q: Optimizing very slow PostgreSQL LEFT JOIN between two large tables For this case I have two tables in my database.  One storing transactions entered by a user and another storing accounts that each transaction can be assigned to.  Accounts have the ability to be marked as inactive and users also have the ability to enter transactions that aren't assigned to an account.
I have a query to grab the first 400 transactions a user has entered where the account is active or the user didn't assign the transaction to an account.
The query looks like this:
select t.*
from transactions_20000 as t
left join accounts as a
    on t.account_id = a.id
where t.user_id = 1
    and (a.status=1 or t.account_id=0)
order by t.date desc, t.transaction_type asc, t.id desc
limit 400 offset 0;

When I run EXPLAIN ANALYZE on the query, I get the following result: https://explain.depesz.com/s/YM2v The problem seems to be in step #5 where it takes over a second and a half to process that part of the query.  While a total run time of 1.6 seconds doesn't seem like a lot, it really starts to add up when there are thousands of users hitting that query hourly when they load the app.  Obviously changing the limit won't really affect anything since that's not where the slow part is.
I'm at a bit of a loss in trying to figure out how to speed this query up.  I know it shouldn't take this long and it's bugging me that I'm probably missing something easy.
The transactions table has a 4 million rows in it, only about 10k of which are assigned to the user.  The accounts table has about 2 million rows in it.
For reference, here are the two tables:
Table "public.accounts"
    Column    |              Type              | Collation | Nullable |               Default
--------------+--------------------------------+-----------+----------+--------------------------------------
 id           | bigint                         |           | not null | nextval('accounts_id_seq'::regclass)
 user_id      | integer                        |           | not null |
 name         | character varying(250)         |           |          |
 type_id      | integer                        |           | not null |
 status       | integer                        |           | not null |
 currency_id  | integer                        |           |          | 1
 credit_limit | numeric(15,2)                  |           |          | 0
 group_id     | integer                        |           |          | 0
 created_at   | timestamp(0) without time zone |           |          |
 updated_at   | timestamp(0) without time zone |           |          |
Indexes:
    "accounts_pkey" PRIMARY KEY, btree (id)
    "a_user_id" btree (user_id)

Table "public.transactions_20000"
       Column       |            Type             | Collation | Nullable |                    Default
--------------------+-----------------------------+-----------+----------+------------------------------------------------
 id                 | bigint                      |           | not null | nextval('transactions_20000_id_seq'::regclass)
 user_id            | integer                     |           | not null |
 date               | timestamp without time zone |           | not null |
 amount             | numeric(15,2)               |           | not null |
 transaction_type   | integer                     |           | not null | 0
 description        | character varying(255)      |           |          |
 account_id         | integer                     |           |          | 0
 category_id        | integer                     |           |          | 0
 jive               | integer                     |           |          | 0
 specialstatus      | character varying(50)       |           |          |
 parent             | integer                     |           |          | 0
 ccparent           | integer                     |           |          | 0
 related_transfer   | character varying(50)       |           | not null | 0
 created_at         | timestamp without time zone |           | not null | now()
 check_num          | character varying(32)       |           |          |
 payee              | character varying(255)      |           |          |
 memo               | character varying(255)      |           |          |
 additional_user_id | integer                     |           |          | 0
 initial_balance    | boolean                     |           |          |
 jived_date         | timestamp without time zone |           |          |
 attachment         | character varying(100)      |           |          |
 add_source         | character(25)               |           |          |
Indexes:
    "transactions_20000_unique_pkey" PRIMARY KEY, btree (id)
    "transactions_20000_user_ccparent_idx" btree (user_id, ccparent) WHERE ccparent > 0
    "transactions_20000_user_date_idx" btree (user_id, date)
    "transactions_20000_user_id_key" btree (user_id)

Does anyone see anything obvious that's causing this query to take so long?

A: It looks like it is spending most of the time reading data from disk for the transactions table, jumping to different parts of the table.  One way to improve that (other than getting faster disks, or more RAM so that the data is cached) would be to CLUSTER the table on the index transactions_20000_user_date_idx, or one of the other indexes which lead with user_id.  That would group all the data for the same user_id together on disk.  The problem is that a clustered table won't stay clustered for future INSERTs or UPDATEs.
Another option is to create an index on
create index on transactions_20000 (user_id,date, transaction_type desc, id );

Or
create index on transactions_20000 (user_id,date desc, transaction_type, id desc);

With either of those indexes, it could collect the rows already in the order it needs them, and stop early once it has obtained 400 which meet the conditions.  Rather than collecting all 3,274 rows, then sorting them.

A: Since you don't actually retrieve anything from accounts I would rewrite the query as:
SELECT t.*
FROM   transactions_20000 t
WHERE  t.user_id = 1
AND   (t.account_id = 0 OR
       EXISTS (SELECT FROM accounts a WHERE a.id = t.account_id AND a.status = 1))
ORDER  BY t.date DESC, t.transaction_type, t.id DESC
LIMIT  400;

That probably doesn't change much yet, though.
Index
A multicolumn index with columns in this order should help performance:
CREATE INDEX transactions_20000_special_idx ON transactions_20000
(user_id, date DESC, transaction_type, id DESC, account_id);

It delivers rows per user_id readily sorted and also covers the account_id we need to join to accounts. Should get rid of the expensive Parallel Bitmap Heap Scan  in your query plan.
(Not sure if adding account_id is an improvement.)
If most accounts are not active (status <> 1), this partial index (consequently small) should help some more:
CREATE INDEX accounts_special_idx ON accounts (id)
WHERE status = 1;


text:
Q: Showing that $x^3-x^2-1$ has only one REAL root. So, I need to prove that $x^3-x^2-1$ = 0 has only one root.
Here's what I have so far:
We have $f(-2) = -13 < 0, f(2) = 3 > 0$. Because f is a polynomial, it is continuous on all $\mathbb{R}$ and there is c s.t. $-2 < c < 2$ and $f(c) = 0$ by I.V.T. This shows the equation has at least one solution.
Usually from here, people show that $f '(x)$ is strictly increasing, and thus can't have second root. But in this case $f'(x)$ = $3x^2-2x$, and $f'(x) = 0, $ when $x = 0$ and x = $2/3$.
So, I have no idea how to prove it has ONLY one root :( Thanks in advance for your help!

A: So, you know $f'$ is zero at two points and only two points. We can make use of this information.
Recognize that,

*

*for $x\in (-\infty,0)$, $f'(x)>0$

*for $x \in (0,2/3)$, $f'(x)<0$

*for $x \in (2/3,\infty)$, $f'(x)>0$
Evaluate $f(x)$ first at each of the zeros of $f'$. Taking a look at the graph of $f$ (below), we immediately conclude that the $f(x) \in (-2,0)$ at those points. More specifically, $f(0) = -1, f(2/3) = -31/27$. The important bit being, they're less than $0$.
Thus, by the monotonicity of $f$ on these intervals we know the behavior of $f$:

*

*It ascends to $-1$ when $x\in(-\infty,0)$

*It then descends to $-31/27$ when $x \in (0,2/3)$

*Then we ascend for $x>2/3$, cutting through the $x$-axis and giving us our one real root

Since $f$ is not given any other opportunity to ascend above the $x$-axis, we conclude the uniqueness of this root.

The graph promised:

A: You know that $f$ is increasing until $x = 0$, then decreasing till $x = \frac{2}{3}$, then increasing again till the rest of time. But $f(0)$ is negative, so the graph can only cross the $x$-axis once.

A: You have found that $f(x)$ has two critical points using the first derivative rule. Now find which kind of critical points they are, either by the first derivative test or (easier and more common) the second derivative test.
Then find the values of $f(x)$ at those two points. It will then be clear that the function does not have a zero between those two points and also does not have a zero between one of the infinities and one of those points. That means there is only one zero.

A:
$f(-\infty,0)=(-\infty,-1)$ therefore $f(x)<-1, \forall x\in (-\infty,0)$
$f(0,2/3)=(-\frac{31}{27},-1)$ therefore $f(x)<-1, \forall x \in(0,2/3)$
$f(2/3,\infty)=(-31/27,\infty)$ and $f$ strictly increasing therefore vanishes a single time in $(2/3,\infty)$.

A: Here is a proof that does not use derivatives.
If one consider $f(1)<0$ and $f(2)>0$, one can conclude from the intermediate value theorem that $f$ has a real root $a$ such that $1<a<2$.
Thus for some real numbers $b$ and $c$, one has
$$
f(x)=x^3-x^2-1=(x-a)(x^2+bx+c)=x^3+(b-a)x^2+(c-ab)x-ac.
$$
So, one has
$$
c-ab=0,\quad ac=1,\quad a\neq 0.\tag{1}
$$
which implies that
$$
a^2b=1.\tag{2}
$$
It follows from (1) and (2) that
$$
f(x)=(x-a)(x^2+\frac{x}{a^2}+\frac{1}{a}).\tag{3}
$$
Now, it is not difficult to see that
$$
\frac{1}{a^4}-\frac{4}{a}<0\tag{4}
$$
since $a>1$. By (3) and (4), $f$ cannot have any other real root.

[Note:] (4) is equivalent to
$$
1-4a^3<0\quad \Leftrightarrow\quad 4a^3>1.
$$

A: You only need to restrict the possible domain where a real root can occur.
To do so, note that

*

*$x^3-x^2-1 = 0 \Leftrightarrow x^3 = x^2+1 \color{blue}{\geq 1}$

*It follows that any real solution can only exist for $\color{blue}{x \geq 1}$
Now, you can reason as usual:

*

*$f(1) <0, f(2) >0$ and $f$ is strictly increasing for $x\geq 1$.

*It follows that there can be only one real root.

A: You look for the zero(s) of function $$f(x)=x^3-x^2-1$$ Its first derivative
$$f'(x)=3x^2-2x=x(3x-2)$$ cancels for $x=0$ and $x=\frac 23$. By the second derivative test, $x=\frac 23$ corresponds to a minimum; then $x=0$ corresponds to a maximum.
Now $f(0)=-1$ and $f\left(\frac{2}{3}\right)=-\frac{31}{27}$ and, by inspection $f(1)=-1$ and $f(2)=3$. So, only one real root soewhere between $1$ and $2$.


text:
Q: Implementing AJAX into posts I am building a custom post type (CPT) that requires a form that users may choose to submit. Regardless, I want any user to be able to see the current summation of the results. This is similar to how to codex article on AJAX says WordPress uses it..
"Several themes and plugins also use Ajax; for instance, some post rating plugins use Ajax to store the visitor's rating in the database and then display an updated average rating." - http://codex.wordpress.org/AJAX
How can I create an element that shows an average rating from user inputs on a CPT entry?


text:
Q: Why isn't the derivative of a rotation matrix skew symmetric? Consider the rotation matrix
$$R(\theta) = \begin{pmatrix}
\cos \theta & -\sin \theta \\
\sin \theta & \cos \theta
\end{pmatrix}$$
Differentiating $R(\theta)$ with respect to $\theta$ gives a matrix that is not skew symmetric. Aren't infinitesimal rotations heuristically supposed to be skew-symmetric?

A: The general formula is $$\frac{ dR_{\theta}}{d\theta}=\begin{bmatrix} & -1\\ 1 & \end{bmatrix}R_{\theta},$$ where $R_\theta$ is the rotation matrix you wrote. When $\theta=0$, one has $R_0=I$ and so $\frac{d R_{\theta}}{d\theta}$ is skew-symmetric.


text:
Q: WSO2 an Open Source Enterprise Service Bus (ESB) I am new to this can  u please guide me which is good site to start WSO2 ESB Open Source Enterprise Service Bus (ESB)  proxy services

A: WSO2 Docs is the best place to get started.
You can refer WSO2 ESB 4.7.0, which is the latest WSO2 ESB release.
Please go through the samples.
You have few things to do before trying samples and then you can go through Proxy Service samples.
I hope this helps!


text:
Q: How do I collect the check box name and send the request? I am using 'react-hook-form' and I need to use checkbox to send a post request
the request formate will be like this
{"project":['A','B','C','D']}
but what I got is , it's {"project":['on','on','on','on']} or  {"project":true}
is there any way to get the checkBox name by clicking it?
<Form.Group controlId="product">
            <Form.Label>Product</Form.Label>
            {productArray.map((product) => (
              <div key={product} className="mb-3">
                <Form.Check
                  ref={register({
                    required: "Required",
                  })}
                  custom
                  name='products'
                  type='checkbox'
                  id={product}
                  label={product}
                  onChange={handleChange}
                />
              </div>
            ))}
          </Form.Group>

A: Try this, add value for your checkbox component.
               <Form.Check
                  ref={register({
                    required: "Required",
                  })}
                  custom
                  name='products'
                  type='checkbox'
                  id={product}
                  label={product}
                  value={product}
                  onChange={handleChange}
                />


text:
Q: WiX : Checking for Currently Running Installations with Custom Action I am trying to use a custom action (written in native C++ code) to check whether my installer is already running at time of installation.
Code is :
#include <Windows.h>
#include <Msi.h>
#include <MsiQuery.h>
#include <tchar.h>

#pragma comment(linker, "/EXPORT:CheckMultipleInstances=_CheckMultipleInstances@4")
#pragma comment(lib, "msi.lib")

extern "C" UINT __stdcall CheckMultipleInstances(MSIHANDLE hInstall)
{
CreateMutexA(0, FALSE, "SIERRAINSTALL_MUTEX");
if (GetLastError() == ERROR_ALREADY_EXISTS)
    MsiSetProperty (hInstall, "INSTALLRUNNING", "1");

return ERROR_SUCCESS;
}

The relevant WiX code is as follows:
<CustomAction Id='CheckOtherInstalls' BinaryKey='InstallCheck' DllEntry='CheckMultipleInstances'/>
<CustomAction Id='RefuseInstall' Error='Sierra Installer is already running.'/>

<Custom Action='CheckOtherInstalls' After='CostFinalize'/>
<Custom Action='RefuseInstall' After='CheckOtherInstalls'>INSTALLRUNNING = "1" AND NOT Installed</Custom>

The problem is, no matter when I schedule this custom action, it doesn't actually execute it until after the user has said "Install" on the installer.
I want this custom action to be executed when the installer launches, before the welcome screen is even displayed (if this is possible).
How can I accomplish this?
EDIT :: This is my solution (ish)
I ended up triggering my custom actions when the user clicks "Next" on the welcome dialog.  No fiddling around with the installexecutesequence or installUisequence worked, and this ends up being a good middle ground for my purposes.
If anyone is interested, this is what I came up with:
<UI Id='MyWixUI_Mondo'>

  <UIRef Id='WixUI_Mondo'/>

  <Publish Dialog='WelcomeDlg' Control='Next' Event="DoAction" Value="CheckOtherInstalls">1</Publish>
  <Publish Dialog='WelcomeDlg' Control='Next' Event="DoAction" Value="RefuseInstall">INSTALLRUNNING = "1"</Publish>

A: Why not creating a "bootstrapper" to check if the installation is running and displaying a message or sth. else. Or let the user cancel the other installation, or let the user wait for a "free slot"...
this would be better than doing it in the msi in my opinion.


text:
Q: What is the best way to enable Windows feature programmatically? I need to turn "Desktop Experience" Windows feature on. Is it possible to do it using C# and do not involve user in this process (or with minimal involving)? What it is the best way to do it?
UPD: PowerShell Add-WindowsFeature is not a solution, because the ServerManager commands are only available from 64 bit version of PowerShell

A: You can install "Desktop Experience" using Powershell.
This article desribes it:
http://blogs.technet.com/b/rmilne/archive/2013/07/11/install-desktop-experience-on-windows-server-2012.aspx
IMHO it's easier than going the C# route.


text:
Q: How to get Alt-nnnn keyboard shortcuts to work under Linux? A few weeks ago, I switched from Windows to Linux, and one thing I'm missing is Altnnnn keyboard shortcuts to insert an em dash and other things. Is there any way to get them working under Linux? I'm using Arch Linux and KDE, if that matters.

A: Using numeric code points
In Tobu's answer, I believe the keystroke combination on US or UK keyboards would be called Ctrl+Shift as in "Ctrl-Shift-2702 is for the scissors character (✂)".
Personally I find it much easier to remember digraphs.
Digraphs / Compose-Key / Multi-Key
X11 Modmap
The X Window system (X11) provides for what is sometimes called a compose key which allows the entry of special characters by using digraphs.

Keying the combination Shift+AltGr (in that order), releasing these
  keys, then entering two other keys will produce a special character.
  Many of these will be the reasonable result of overtyping the
  character keys, eg.

Shift+AltGr  ~  a -->  ã  (ã in HTML)
Shift+AltGr  /  o -->  ø  (ø in HTML)
Shift+AltGr  o  c -->  ©  (© in HTML)
Shift+AltGr  c  o -->  ǒ  (Ŏ in HTML)

How to
There is an article at linuxquestions.org that describes how to set this up.

first you need to choose which key you want to be the Compose key.
  Then, open a terminal and enter the command xev.
  A window called "Event Tester" will pop up. Make sure that
  it's focused by clicking on it and leaving the mouse cursor in it.
Now press and release the key that you want to become the Compose key.
  Remember or write down the number after the word "keycode" in the
  output
Now open the file ".Xmodmap" (the name begins with a dot) in your home
  directory (create it if it isn't there already) with a text editor and
  type in the following line, replacing  with the number
  you got in xev.
keycode <keycode number> = Multi_key Now, open the file .xinitrc
  (it's in your home directory, and it's a hidden file) in a text
  editor. Insert this line in the beginning of the file:
xmodmap ~/.Xmodmap And next time you log in the Compose key
  should work! To start using the Compose key right now, enter the
  command xmodmap ~/.Xmodmap in a terminal.

Wikipedia
The howto article refers to a wikepdia article which says

The compose key is known as "Multi_key"
  in the X Window System, and must be interpreted by the client
  program (typically Xlib), not the server. In XFree86 and X.Org Server,
  many keyboard layouts have a variant that maps Multi_key to some key,
  usually (on PC keyboards) to either of the Windows keys, or sometimes
  ⇧ Shift+AltGr[1] or ⇧ Shift+Right-Ctrl. It can also be specified in
  XkbOptions (for example, "compose:rwin"). Multi_key can also be
  assigned with the xmodmap(1) utility.

A: Gtk/Gnome has Ctrl-Shift-U, followed by the digits of the unicode character, then enter. Additionally "—" may be available in the standard keyboard layout for your language, or an alternative one. Mine is at AltGr-Shift-4 for example; gnome-keyboard-properties can display the layout so you can look for keys.


text:
Q: Android Studio Gradle - Unable to solve dependency I'm getting the following errors when trying to add implementation 'com.android.support:cardview-v7:27.1.1' to my build.gradle (app):
Unable to resolve dependency for ':app@debug/compileClasspath': Could not
resolve com.android.support:cardview-v7:27.1.1.

Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath':
Could not resolve com.android.support:cardview-v7:27.1.1.

Unable to resolve dependency for ':app@debugUnitTest/compileClasspath':
Could not resolve com.android.support:cardview-v7:27.1.1.

Unable to resolve dependency for ':app@release/compileClasspath': Could not
resolve com.android.support:cardview-v7:27.1.1.

Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath':
Could not resolve com.android.support:cardview-v7:27.1.1.

Here is my App gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "afinal.recipe.p.recipe1"
        minSdkVersion 22
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-media-compat:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-storage:16.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support:cardview-v7:27.1.1'
}
apply plugin: 'com.google.gms.google-services'

And my Project gradle:
// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they
belong
        // in the individual module build.gradle files
     }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I've already been stuck on this for a while and tried a variety of solutions with no success such as ensuring offline mode isn't checked and changing
apply plugin: 'com.android.application'

to:
apply plugin: 'com.android.library'

and, without success, deleting:
applicationId "afinal.recipe.p.recipe1"

Thanks in advance for any help, would be greatly appreciated.


text:
Q: How to select an entry from the rows of numbers I need to select number like 36/5 from string, but does not get the result.
I can only select number 36.
Code:
DECLARE @s nvarchar(255);
SET @s = 'http://kbyte.ru/ru/Programming/Sources.aspx?id=36/5&mode=show'
-- берем переднюю  часть строки, начиная с числа
SELECT @s = SUBSTRING(@s, PATINDEX('%[0-9]%', @s), LEN(@s));
-- отсекаем хвост до числа
SELECT @s = SUBSTRING(@s, 0, PATINDEX('%[^0-9]%', @s));
-- выводим
SELECT @s;

A: If your string is always going to be in that format just add / to your second pattern index.
DECLARE @s nvarchar(255);
SET @s = 'http://kbyte.ru/ru/Programming/Sources.aspx?id=36/5&mode=show'
SELECT @s = SUBSTRING(@s, PATINDEX('%[0-9]%', @s), LEN(@s));
SELECT @s = SUBSTRING(@s, 0, PATINDEX('%[^0-9/]%', @s));
SELECT @s;

A: An alternative if you're always going to retrieve 4 characters. Otherwise you can tweak it to how you need.
 DECLARE @s nvarchar(255);
 SET @s = 'http://kbyte.ru/ru/Programming/Sources.aspx?id=36/5&mode=show'
 SELECT @s= SUBSTRING(@s,(CHARINDEX('id=',@s)+3),4)
 SELECT @s;

EDIT
This may solve the problem of limited characters... This will work if your value is always between "id=" and "&mode"
 DECLARE @s nvarchar(255);
 DECLARE @int INT
 SET @s = 'http://kbyte.ru/ru/Programming/Sources.aspx?id=36/5&mode=show'
 SELECT @int = CHARINDEX('&mode',@s) - (CHARINDEX('id=',@s)+3)
 SELECT @s= SUBSTRING(@s,(CHARINDEX('id=',@s)+3),@int)
 SELECT @s;


text:
Q: How to create a dataframe from a text file with the first word as a column using pandas? I have a dataset with millions of lines. I need a faster way to create the dataframe in the following format:-
   column_1   column_2
    1         line 1
    Yes       Go to School
    NO        Play video games for hours

file format:-
1 line 1
Yes Go to School
No Play video games for hours

Is there any faster way to perform this task using pandas like any inbuilt function or so?? there are approx. 3 million lines in the file.

A: Try the following (it takes 20 seconds approx to load in my machine, i don't know if it's good enough for you though)
with open('yourfile.txt') as f:
    data = [line.split(' ', maxsplit=1) for line in f]

df=pd.DataFrame.from_records(data, columns=['column_1', 'column_2'])

A: Try regex to split file rows-
df = pd.read_csv('file.txt', sep='^(\S+)', names=['column_1', 'column_2'], engine='python', usecols=[1, 2])


text:
Q: Magento multiple level menu In my Magento website, I need to display Main categories and sub categories on a multilevel menu. The sub categories will change according to the main category selected.I need it as  shown in the link given below. http://www.bhphotovideo.com/ .

A: Your question is too much off the goals of SO, and I'm afraid it will get closed by someone with enough reputaion.
Just to give you a starting point, it can be achieved by CSS, as making current menu item of class active and then forcing its child elements to display because of that active class in parent. Try this, you'll surely get what you want.
Cheers.

A: in navigation.php append all main categories and its child categories to jquery tabs


text:
Q: Automorphisms of $D_{2n}$ Let $D_{2n}$ be presented as $\langle r, s \mid r^n=s^2=1, srs=r^{-1}\rangle$. Is it the case that sending $r$ to any power of $r$ relatively prime to $n$ and sending $s$ to any reflection gives an automorphism, making $|Aut(D_{2n})|=n\phi(n)$? In addition, what is the structure of the automorphism group?

A: Yes, that's correct. When $n>2$, the cyclic rotation group is characteristic, so all automorphisms have that form. The automorphisms that map $r$ to $r$ form a normal cyclic subgroup $N$ of order $n$. The subgroup that maps $s$ to $s$ forms a non-normal subgroup $U$ of order $\phi(n)$ isomorphic to the automorphism group of $N$, The complete automorphism group of $D_{2n}$ is the semidirect product $N \rtimes U$ (also known as the holomorph of $N$).

A: To check if some map is a homomorphism, it suffices to check that the generators satisfy the same defining relations. Then it will be an automorhpism because bijectivity holds.
Sending $r\mapsto r^k$ where $k \not\mid n$ satisfies $(r^k)^n=1$.
Sending $s\mapsto sr^m$ (another reflection) satisfies $(sr^m)^2=1$.
Finally, $$((sr^m)(r^k))^2=sr^{m+k}sr^{m+k}=ssr^{-m-k}r^{m+k}=1.$$
So yes, it seems that this map $\phi$ that you defined is an automorphism.
You also claim that all automorphisms take that form. I think that this is true with the exception of $D_2 \simeq C_2 \times C_2$ (the Klein 4-group), which has some other automorphisms since the elements of order two are indistinguishable.
I'm not sure what the automorphism group is though...
Disclaimer: I don't have much experience with algebra, so please correct me if I have said anything wrong!


text:
Q: Calculating Exponential Moving Average using Esper Looking for a way to calculate the Exponential Moving Average over a window of 5 EMA5 and EMA20 using Esper (EPL) statements.
I have a stream of priceEvent (timeStamp , symbol and price) coming in and I wrote a Simple moving avrage SMA over a sliding window of 5 . But being fairly new to Esper , was looking for a way to calculate Exponential Moving Average (EMA) over sliding window.
http://www.iexplain.org/ema-how-to-calculate/
Also it will be great help if someone can help me in writing parabolic SAR function

A: Ok Guys, I did more learning and research to get to the solution of finding Exponential Moving Average , below are the EPL statements that will help calculating ema5
//create a named window EMA5 Window
create window EMA5Window.win:length(1) as select price as ema5 from Quote

//insert the mean of first 5 events
insert into EMA5Window select Avg(price) as ema5 from Quote.win:firstlength(5)

//after 5 events calculate todays ema = (today's price)/3 +  (yesterday's ema)*2/3, refer to http://www.iexplain.org/ema-how-to-calculate/ for ema formula

insert into EMA5Window select ((price)*(1/3)+(2/3)*(select ema5 from EMA5Window)) as ema5 from Quote output after 5 events

// now select the ema5 as below
select ema5 as ema5 from EMA5Window output after 5 events

Working on calculating parabolic SAR will update once I am done.
Thanks


text:
Q: Custom control onPaint event not working Hey people I have a problem I am writing a custom control. My control inherits from Windows.Forms.Control and I am trying to override the OnPaint method. The problem is kind of weird because it works only if I include one control in my form if I add another control then the second one does not get draw, however the OnPaint method gets called for all the controls. So what I want is that all my custom controls get draw not only one here is my code:
If you run the code you will see that only one red rectangle appears in the screen.
public partial class Form1 : Form
{
    myControl one = new myControl(0, 0);
    myControl two = new myControl(100, 0);

    public Form1()
    {
        InitializeComponent();
        Controls.Add(one);
        Controls.Add(two);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

public class myControl:Control
{
    public myControl(int x, int y)
    {
        Location = new Point(x, y);
        Size = new Size(100, 20);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Pen myPen = new Pen(Color.Red);
        e.Graphics.DrawRectangle(myPen, new Rectangle(Location, new Size(Size.Width -         1, Size.Height - 1)));

    }

}

A: I'm guessing you are looking for something like this:
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(0, 0,
                                                this.ClientSize.Width - 1,
                                                this.ClientSize.Height - 1));

Your Graphic object is for the interior of your control, so using Location isn't really effective here.  The coordinate system starts at 0,0 from the upper-left corner of the client area of the control.
Also, you can just use the built-in Pens for colors, otherwise, if you are creating your own "new" pen, be sure to dispose of them.

A: LarsTech beat me to it, but you should understand why:
All drawing inside of a control is made to a "canvas" (properly called a Device Context in Windows) who coordinates are self-relative. The upper-left corner is always 0, 0.
The Width and Height are found in ClientSize or ClientRectangle. This is because a window (a control is a window in Windows), has two areas: Client area and non-client area. For your borderless/titlebar-less control those areas are one and the same, but for future-proofing you always want to paint in the client area (unless the rare occasion occurs where you want to paint non-client bits that the OS normally paints for you).


text:
Q: How to prevent next npm command from running? I'm trying to run preflight checks via npm before allowing other scripts to process.
The following works but I'm wondering if there's a better way
package.json
"deploy": "npm run _deploy:preflight && npm run _deploy:real",

"_deploy:preflight": "node ./build-utils/deploy-preflight.js",

build-utils/deploy-preflight.js
if (checksFail()) {
    console.log("--------------");
    console.log("preflight checks failed!");
    console.log("--------------");
    process.exit(1);
}

The problem isn't so much that it doesn't work, it's that the console is then littered with a huge npm ERR / stacktrace and I'd much rather just see the clean "preflight checks failed" message and still have it prevent npm run _deploy:real from running

A: Yes, I agree - npm can be rather noisy/verbose at times.
The following suggestion assumes you keep deploy-preflight.js as it currently is, whereby you continue to exit with an exit code 1 on error, i.e. process.exit(1).

*

*The npm --silent  command-line option, or it's shorthand equivalent -s, is probably the most favoured!. However, it does require you to include it with the CLI command that you run.
For instance:
$ npm run deploy -s
                 ^

or
$ npm run -s deploy
          ^


text:
Q: MapTo() inside of LINQ returning multiple iterations of same data I am using .NET Core with the ASP.NET Boilerplate framework. In some code that I was given to fix, we had a GetAll() method that was supposed to return a collection of rows from the MsSql database. The original code:
public IEnumerable<GuidelineCategoriesDto> GetAll(bool activeFilter = true)
{
    return _guidelineCategoriesRepo.GetAll().Select(x => x.MapTo(new GuidelineCategoriesDto())).ToList();
}

The problem I was running into with this method, is that it would return the latest row that had not been soft-deleted in the database. However, it would return that same row a number of times equal to the amount of non-deleted rows in that table. So essentially I would get back an IEnumerable that contained all duplicates. To fix this, I changed this method to the following.
public IEnumerable<GuidelineCategoriesDto> GetAll(bool activeFilter = true)
{
    // return _guidelineCategoriesRepo.GetAll().Select(x => ObjectMapper.Map<GuidelineCategoriesDto>(x)).ToList();
    return ObjectMapper.Map<IEnumerable<GuidelineCategoriesDto>>(_guidelineCategoriesRepo.GetAll());
}

This (including the commented line) fixed all my issues and returned the correct data. My question is why the first method I mentioned acted in the way that it did. I am not familiar with the MapTo method as I'm used to using ObjectMapper, but from what I found about it I still cannot determine why it behaved in the way that it did.
My DTO has the correct AutoMap data annotation and the DbSet is in the DbContext, if any of that matters.

A: This...
_guidelineCategoriesRepo.GetAll().Select(x => x.MapTo(new GuidelineCategoriesDto())).ToList();

...is effectively:
var dto = new GuidelineCategoriesDto();
_guidelineCategoriesRepo.GetAll().Select(x => x.MapTo(dto)).ToList();

In other words, you are mapping every entity to the same DTO.
Since the last entity is mapped last, this means that the DTO mapped from every entity appears to be a duplicate of the DTO mapped from the last entity. But is actually one DTO appearing multiple times.
This would work:
_guidelineCategoriesRepo.GetAll().Select(x => x.MapTo<GuidelineCategoriesDto>()).ToList();

Avoid MapTo; use ObjectMapper
From https://aspnetboilerplate.com/Pages/Documents/Object-To-Object-Mapping#mapto-extension-methods:

Since the MapTo extension methods are static, they use AutoMapper's static instance (Mapper.Instance). This is simple and fine for the application code, but you can have problems in unit tests since the static configuration and mapper is shared among different tests, all effecting each other.


text:
Q: Design a RESTful API in Laravel 5.2, using a resource that conceptually can contain other resources First of all I am really not very familiar with the REST practice, and I am not very confident about the title of my question.
So I am trying to built a RESTful API using Laravel for a phonebook application. The phonebook may contain telephones of either employees (i.e real persons) or offices. For that reason I have three models

*

*a Directorate with id and name fields,

*an Employee with id and name fields and

*a Telephone with id, tel, employee_id, directorate_id, description and type fields.

Telephones corresponding to a directorate's office have only the id, tel, directorate_id and description fields set, while the telephones corresponding to a person (i.e an employee) have set only the id, tel, employee_id, directorate_id, and type fields. That is how I separate them: a telephone having a description can only be an office's telephone, while a telephone having both the employee_id and the type_id set is an employee's telephone.
The models are related as follows:

*

*an employee may have many telephones

*a directorate, may have many telephones
class Directorate extends Model
{
    public function telephones()
    {
        return $this->hasMany(Telephone::class);
    }

    public function employees()
    {
        return $this->hasMany(Employee::class);
    }
}

class Employee extends Model
{
    public function telephones()
    {
        return $this->hasMany(Telephone::class);
    }

    public function directorate()
    {
        return $this->belongTo(Directorate::class);
    }
}

class Telephone extends Model
{
    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
}

My question is what should I a consider as my resource.
So far I am thinking of the following approach:
I shall use the concept of contact as resource. A contact may be the joined information of either an employee and a telephone, or a directorate and a telephone. For instance, a "contact" may contain the name of an employee with his related telephone numbers and telephone types, or it can contain the name of a directorate with the description of the telephone and the telephone number.
The "problem" with this approach is that I have ended up with (let's put it this way) two different types of resource: the employee's contacts and the directorate office's contacts, which contain slightly different information and thus, I need also to have different create and edit forms to interact with these two "types" of resources.
In order to implement the REST API, I am thinking of two different scenarios:

*

*Use two different RESTful controllers, one EmployeeContacts and another OfficesContacts for separating conceptually the resource to an employee's and an office's resource, and accessing them through different URIs like:
example.com/phonebook/employees/{id}/edit
example.com/phonebook/offices/{id}/edit
example.com/phonebook/employees/create
etc...

*Use a single RESTful controller, e.g. PhonebookContacts to access the resources through the same URIs as one resource  (i.e. both employee's and office's contact resources now are considered to be just a "contact" resource)
//this refers to a contact resource that can be either an office's or a n employee's contact
example.com/phonebook/contact/{id}/edit
//this should list all resources (both employees and offices contacts)
example.com/phonebook/contact/
and then use conditional statements in the controller's create/store/edit/update methods to deal with them separately (e.g if an http POST request contains a description_id then it is an office contact and do this, or else if has an employee_id then it is an employee's contact so do that...)
I would like to hear your views, what of these two different scenarios do you consider to be better in the context of REST for my phonebook app? Would be better to think of a single "contact" resource and handle it using conditional statements with different return in the controller, or shall I separate the concept of "contact" to "employee's contact" and "office's contact" and use separate controllers and URI's to handle them?
Is there another approach that I could follow instead?

A: The way I would do it is with 2 different controllers for the simple reason of speed and responsiveness. Loading all contacts and filtering isn't as quick as loading the one part only.
However, you can always set in your controller the same return with different data. Such as EmployeeController@index returns view('contacts.index', compact('employeeContacts')), and OfficesController@index returns view('contacts.index', compact('officesContacts'))
EDIT:
Sorry, I have misread it...I thought you wanted to do the filtering in the view. Anyway, my practice is to do it separately, simply because the code is cleaner. If you want to make the whole REST more readable, you can put both resources in a group like so: Route::group(['prefix' => 'contact'], function(){ //routes here// });
So now you will have routes like:
example.com/contact/employees/

example.com/contact/offices/

A: I am not familiar at all with Laravel but since this question is about REST concepts (I have a small background on these) I should give it a try.
Since you are building a RESTful application, you must not consider others as human beings but only as machines. IMO the urls should determine the action that will be performed. Thus, by using different urls for different actions (perform a CRUD on a contact - either an Employee or a Directorate or SomethingElseInTheFuture) sounds good to me and fits the REST nice.
Hope this clarify the things for you!
[EDIT]
I believe jannis is right. It should be the verbs (GET, POST, PUT, PATCH etc) that make the action instead of the URLs. The urls are just respresenting the resources. My mistake. So both of your points of view are correct. It's just how convenient each approach is for your project (for now and for the near future of your project). IMO, I see #1 (two different restful controllers) more approchable.
Cheers and sorry for any misconception!


text:
Q: Parsing through XML in C# and searching for a "FAILED" I am trying to write a program in C# to parse through an XML file and look through the status of multiple elements to find one that failed. I don't have much experience working with XML but have done some research and am a little stuck. I'll post an example XML file below for reference. I figure I'll check the   of each group first to see which group failed then search that group's individual elements.
<Diagnostics ActionType="SPV" Ver="48">
  <StartTimestamp>2014-04-18 13:36:44Z</StartTimestamp>
- <Iteration>
- <NODE1>
     <Device Name="A" Register="IDCODE" Status="PASSED"/>
     <Device Name="B" Register="IDCODE" Status="PASSED"/>
     <Device Name="C" Register="IDCODE" Status="PASSED"/>
     <Device Name="D" Register="IDCODE" Status="PASSED"/>
     <Device Name="E" Register="IDCODE" Status="PASSED"/>
     <Device Name="F" Register="IDCODE" Status="PASSED"/>
     <Device Name="G" Register="IDCODE" Status="PASSED"/>
     <Device Name="H" Register="IDCODE" Status="PASSED"/>
     <Device Name="I" Register="IDCODE" Status="PASSED"/>
     <Status>PASSED</Status>
  </NODE1>
- <NODE2>
     <Status>PASSED</Status>
  </NODE2>
- <NODE3>
     <Status>PASSED</Status>
  </NODE3>
- <NODE4>
     <Device Name="A" Register="IDCODE" Status="PASSED"/>
     <Device Name="B" Register="IDCODE" Status="PASSED"/>
     <Device Name="C" Register="IDCODE" Status="PASSED"/>
     <Device Name="D" Register="IDCODE" Status="PASSED"/>
     <Device Name="E" Register="IDCODE" Status="PASSED"/>
     <Device Name="F" Register="IDCODE" Status="PASSED"/>
     <Device Name="G" Register="IDCODE" Status="PASSED"/>
     <Device Name="H" Register="IDCODE" Status="PASSED"/>
     <Device Name="I" Register="IDCODE" Status="PASSED"/>
     <Status>PASSED</Status>
  </NODE4>
- <NODE5>
     <Device Name="E" Status="PASSED" />
     <Device Name="F" Status="PASSED" />
     <Device Name="H" Status="FAILED" />
     <Device Name="I" Status="PASSED" />
     <Status>FAILED</Status>
  </NODE5>
  <Passed>False</Passed>
 </Iteration>
 <EndTimestamp>2014-04-18 13:36:44Z</EndTimestamp>
</Diagnostics>

A: XmlNodeList nodes = xmlDoc.SelectNodes("//Device[@Status='FAILED']");


text:
Q: Getting the output from a process created by CreateProcess In my console app I've created a process by using CreateProcess method.
Now, this process either writes to the console "OK" or "Not OK". How can I intercept that information so I can as well as to console write it to a file?

A: *

*Use CreatePipe to create an anonymous pipe.

*Set the standard output of your child to be the write end of the pipe

*Parent process reads from the read end of the pipe

*Parent process can write to file and console, and wherever.

See Creating a Child Process with Redirected Input and Output on MSDN for full details.

A: Pipes are difficult to get right, especially in Windows. When you have simple one-line output, as in this case, just redirect the process' standard output to a temporary file and read that. A very simple way to redirect is to let cmd.exe do the job, via its > operator.

It sounds as if you are developing the started process.
If that's the case, consider using the process exit code instead of output, for a yes/no result.
The process exit code is the result value from main. The (usually identical) values 0 and EXIT_SUCCESS mean success, like "OK", and the value EXIT_FAILURE, plus, in Windows, the value E_FAIL from <windows.h>, mean failure, like "Not OK". In Windows EXIT_SUCCESS (from the <stdlib.h> header) is always 0, and EXIT_FAILURE is usually 1.
It's much simpler and more efficient to check a process exit code than to check a process' output.
In particular, the C++ standard library's system function returns the process exit code, and passes your command to cmd.exe, so there's no need to do the API-level dance for this case.


text:
Q: Multiple Swipe down Gestures in one fragment //this is my code for SwipeDown on a image view, de image disappears. This is working fine
//But on the same fragment i want another swipe down on a recyclerview (refresh). How can i do that?. I tried a when statement but its not working.
private fun swipeDown() {

    imageOne.isVisible = false. // so this is for swipe 1
    RecyclerviewAdapter?.notifyDataSetChanged()  // this is for swipe 2

A: Is the initial image inside the RecyclerView?  If so, you might have overlapping gestures.  Perhaps you could try passing down a reference to the View object that is getting the gesture action as a parameter to your method to better discriminate between the two different Views.
E.g.
private fun swipeDown(view: View) {
    when (view) {
        myTextView -> imageOne.isVisible = false. // so this is for swipe 1
        myRecyclerView -> RecyclerviewAdapter?.notifyDataSetChanged()  // this is for swipe 2
    }

Also, have you considered using androidx.swiperefreshlayout as part of your RecyclerView layout? I bet it could make your life a lot easier!