text:
Q: How to Cygwin Xwin -query an Ubuntu 11.10 Xserver? I am running Cygwin 1.7 on Win7 Pro x64, and I can query my Ubuntu 10.04 LTS server just fine.
XWin.exe -clipboard -once -rootless -nodecoration -notrayicon -query $IP_ADDRESS

I recently installed Ubuntu 11.10 with XFCE desktop on another machine, and I cannot connect to this one.
Of course, I enabled TCP and XDMCP in LightDM using /etc/lightdm/lightdm.conf
[SeatDefaults]
# ...
xserver-allow-tcp=true

[XDMCPServer]
enabled=true

and I think the fact that I can connect using my Xubuntu 11.10 laptop proves that it works.
X -query $IP_ADDRESS :1

Xwin fails to connect, while logging something like:
[333305.324] XDMCP fatal error: Session failed Failed to connect to display :0
[333305.324]
[333305.324] Server terminated with error (1). Closing log file.

Today I updated Cygwin.
CYGWIN_NT-6.1-WOW64 1.7.9(0.237/5/3) 2011-03-29 10:10

Still doesn't work. Does anyone have a clue as to what 'feature' the new and improved LightDM or Xserver has that I forgot to take into account?
Oh and did I mention the exact same Cygwin/Xwin connects to Ubuntu 10.04 just fine, using the same command line (different IP of course)?

A: I don't know what the guys over at Cygwin/X are doing to make this fail. And I don't know why I cannot find any help or even mention of similar trouble anywhere in this galaxy that is within the reach of Google. I believe I am not the only one using the software, so the lack of help puzzles me.
But let me provide a solution to my own question; I discovered that VCXsrv.exe is some kind of Cygwin/X clone in a way.
http://sourceforge.net/projects/vcxsrv/

VcXsrv Windows X-server based on the xorg git sources (like xming or
  cygwin's xwin), but compiled with Visual C++ 2010.

It works almost the same, except you need to add the -from [ip-address] command line option. No idea why. But it works:
vcxsrv.exe -clipboard -once -rootless -nodecoration -notrayicon -query [target hostname or ip] -from [current (local) ip]

Tested with both Xubuntu and xubuntu-desktop on Ubuntu. (XFCE)

A: I was having the same problem. I just added -from your.ip.v4.addr to the config line of XWin.exe, and it's now working for me. Both my windows 7 and the linux host were doing IPv6. I think that Xwin/LightDM don't know how to handle the IPv4/IPv6 mix.

A: I had the same issue, and adding -from fixed it.
/usr/bin/XWin -query kvant -nodecoration -lesspointer -from 192.168.1.132

where "kvant" is the remote host and 192.168.1.132 is the client running the Xserver.
However, after upgrading to Ubuntu 12.04 on the server, this is PITIFULLY slow.
9.x that I used to have was actually quite useful & snappy.

A: I had the same issue which was resolved by adding the "from" option. This is my windows .bat file content (could help someone else):
@echo on

C:
chdir C:\cygwin\bin
bash --login -i -c '/bin/XWin -query server_ip -from client_ip'
pause


text:
Q: Is there the exclusive list of Pythagorean triples? If there is, what is the general pattern for it? Is there the exclusive list of Pythagorean triples? If there is, what is the general pattern for it?
What about Euclid's formula? Does it generate all the Pythagorean triples?
More explicitly, if $a,b,c$ is a Pythagorean triple, then does it satisfy
$$
a = m^2+n^2, b=2mn, c= m^2 + n^2
$$
for some numbers $m,n$?
If you don't mind, could you give me a full rigorous statement of what I tried to describe right above (that is, the necessary condition of Pythagorean triples)?

A: A direct quote from the Wikipedia article you linked to:

Despite generating all primitive triples, Euclid's formula does not produce all triples. This can be remedied by inserting an additional parameter $k$ to the formula. The following will generate all Pythagorean triples uniquely:
$$a = k\cdot(m^2 - n^2) ,\ \, b = k\cdot(2mn) ,\ \, c = k\cdot(m^2 + n^2)$$
where $m, n,$ and $k$ are positive integers with $m > n$, $m − n$ odd, and with $m$ and $n$ coprime.

A: From Tree of primitive Pythagorean triples

F. J. M. Barning$^{[2]}$ showed that when any of the three matrices
  $$    \begin{array}{lcr} A = \begin{bmatrix} 1 & -2 & 2 \\ 2 & -1 & 2 \\ 2 & -2 & 3 \end{bmatrix} & B = \begin{bmatrix} 1 & 2 & 2 \\ 2 & 1 & 2 \\ 2 & 2 & 3 \end{bmatrix} & C = \begin{bmatrix} -1 & 2 & 2 \\ -2 & 1 & 2 \\ -2 & 2 & 3 \end{bmatrix} \end{array} $$
  is multiplied on the right by a column vector whose components form a Pythagorean triple, then the result is another column vector whose components are a different Pythagorean triple

A: $$x=a+\sqrt{2 a b},\quad y=b+\sqrt{2 a b},\quad z=a+b+\sqrt{2 a b}$$
generates all pythagerean triplets
$$x^2+y^2=z^2$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jekyll begin *and* end excerpt separators I'm writing a blog with Jekyll. I know that jekyll has the excerpt_separator which can be used to specify the end of an excerpt like
This is a blog post, click to see more than this

This is not in excerpt

However, I'd like to start each of my blog posts with a quote, but not include that quote in the excerpt. Something like
>   "There are two ways of constructing a software design: One way is to make it
>   so simple that there are obviously no deficiencies and the other way is to
>   make it so complicated that there are no obvious deficiencies." – C.A.R. Hoare

This is the excerpt

Not part of the excerpt.

So far I've been unable to find evidence that this is supported.
How might I go about accomplishing this?

A: I found an alternate approach that works and shouldn't break expected behavior. I found if you moved the quote to the front matter and altering your layout, you can have the excerpt ignore the quote.
The  sample post:
---
title: Test of Quote Post
layout: quotepost
categories: Random
comments: false
quote: |
    Hack the Planet!
    Hack the Planet!
---
A sample post preceded by a quote.

Section of the layout:
{% if page.quote %}

{{ page.quote | markdownify }}

{% endif %}

{{ content }}

This works because the quote is no longer part of the posts content. However the posts layout will add the quote to the pages layout ahead of the posts content. You can even give quotes their own style properties this way. This is also how you would add features to a page that are not part of the content(like comments).
Notes: You will have to add a double space after each line of the quote if you want them to be on separate lines. Also if you want to have the entire posts content displayed on another page, you will have to manually include the quote if desired.

A: Unfortunately, Jekyll doesn't by default support a way to specify the start of an excerpt.
One possible way to get around this issue would be to use the excerpt variable in Jekyll's front matter and just write the required text directly to it and then display the value of the page.excerpt variable in the page content.
It is a bit messy and breaks the page content up but it will work.
---
excerpt: 'This is the excerpt'
---

>   "There are two ways of constructing a software design: One way is to make it
>   so simple that there are obviously no deficiencies and the other way is to
>   make it so complicated that there are no obvious deficiencies." – C.A.R. Hoare

{{ page.excerpt }} // This is the excerpt

Not part of the excerpt.


text:
Q: Does rate of acceleration affect the amount of energy used to accelerate? Assume you start with a car at rest. Then you accelerate the car to 100 kilometers per hour. In terms of the energy needed, does it matter how fast you accelerated the car?
In other words, do you need to provide the same amount of energy to accelerate a car from 0 to 100 kilometers per hour whether you do it in 4 seconds or 20 seconds?

A:
Does rate of acceleration affect the amount of energy used to
  accelerate?

The answer is, in a certain sense, no.
But, really, your question as worded is ambiguous.  What does "energy used to accelerate" actually mean?
There is an energy associated with a change in speed which is precisely the change in kinetic energy:
$$\Delta KE = \dfrac{m}{2}(v^2_f - v^2_i)$$
Now, since it is net force that accelerates an object, then, if "energy used to accelerate" means "net force over distance to change speed from $v_i$ to $v_f$", then, in this sense, the answer to your question is no.
However, the applied force may not be the net force on the object as there may be, e.g., a frictional force.
So, if "energy used to accelerate" means "applied force over distance to change speed from $v_i$ to $v_f$", then the answer to your question is yes.

In other words, do you need to provide the same amount of energy to
  accelerate a car from 0 to 100 kilometers per hour whether you do it
  in 4 seconds or 20 seconds?

If it's a real car, there is energy associated with simply maintaining a non-zero speed so, again, it depends on what you mean by "energy to accelerate a care".  Do you mean "energy above and beyond that which is required to overcome the losses" or something else?

A: This answer ignores the effects of dissipative forces like friction and air resistance.

You're confusing power with energy
The total energy of the car is the sum of its kinetic and potential energies. This, of course, ignores internal energy, etc, which remain constant for the car during the time we care about it.
The energy of the car is
\begin{equation}
E = \text{Kinetic} + \text{Potential}\\
E = \frac{1}{2}mv^2 + mgh
\end{equation}
Initially, the car will have 0 kinetic energy (since its velocity is zero) and some potential energy $P_1=mgh_1$
\begin{equation}
E_1 = mgh_1
\end{equation}
After it is accelerated,
\begin{equation}
E_2 = \frac{1}{2}m(100km/h)^2 + mgh_2
\end{equation}
The energy needed is:
\begin{equation}
\Delta E = E_2 - E_1 = \frac{1}{2}m(100km/hr)^2 + mg(h_2 - h_1)
\end{equation}
Notice that none of this depends on the time taken, only on the initial and final velocities and heights.
The power supplied, however, is the work done (or energy supplied) per unit time.
Conclusion:
Energy needed is independent of time.
Power required is greater if you do it in 4 seconds than if you do it in 20 seconds

A: One thing you might want to consider. Even if it takes the same energy to accelerate slow vs. fast, if you are ultimately traveling the same distance, then because you got to the faster speed more quickly you will use more energy to cover that distance.
For example.  If you are trying to get to 100kph and you plan to travel a total distance of 1km, you now have 2 cases:
a) In the first case you get to 100kph in 4 seconds, then travel the remaining 1km at 100kph.
b) in the second case you get to 100kph in 20 seconds, then travel the remaining 1km at 100kph
Then in case "a" you will be traveling 100kph for 16 seconds longer than in case "b". Of course if you are in stop & start traffic, and hit that accelerator a lot, then you will experience a significant difference in energy use.

A: First of all as you go from 0 kmph to 100 kmph in either 4 or 20 seconds there is rate of speed/velocity only, we are not talking about rate lf acceleration here.
Now we can see that in both cases the acceleration would be different; had we been living in an ideal world it wouled not have mattered, but as accelerations are different so would be required forces for said accelerations, these forces even in absense of air would have to overcime friction and therefore heat losses, these lossss would be related to acceleration and hence acheiving same speed in different time would require different energies.

A: Basic physics.
(1) W = F * s where W is work (energy), F is force and s is distance.
(2) F = m * a where m is mass and a is acceleration.
substitute F in equation (1) with equation (2) and you get (3) W = m * a * s.
From equation (3) assuming  mass and distance are constants, then Work is directly proportional to acceleration. An increase in acceleration means in increase in energy.


text:
Q: Output impedance of a 4mA to 20mA current loop I have the most basic of basicness circuit. The implementation is a XTR115UA IC with a 40µA - 200µA input (based on sensor voltage) which is amplified to the desired 4mA to 20mA current in the current loop.
I have been given the task to calculate / measure the output impedance of this current loop. The output impedance should be below 0.1 Ohms, but I don't see anything that gets me even close.
Hope you can help.

A: Look at the circuit in the data sheet: -

The output loop comprises: -

*

*The chip itself and, as a current generator will have a very high impedance

*A series voltage supply (VLLOP) that powers the chip

*A series load resistor (RL) that is used to measure the loop current

So, from the perspective of the power supply VLOOP it will see a fairly high impedance due to Q1 being in series with RL plus a little bit of current that passes into the voltage regulator on the chip.
But from the perspective of looking at the loop across pins 7 and 4 you will see VLOOP in series with RL and, as a dynamic impedance will equal RL because VLOOP will be a voltage source with a very low output impedance that is  << RL.

A: The output impedance Rx || Cx will look something like this:

simulate this circuit – Schematic created using CircuitLab
Where R2 is your receiver resistance (in this case to give you 1-5V).
Vsupply must be high enough that the voltage across I1 is in the range of  +7.5 +36 for the transmitter to function properly. At 12mA (mid-scale) the voltage across R2 is 3.00V and should remain at about that level for Vsupply in the proper range.
You can measure the DC output impedance by varying Vsupply from (say) 10V to 30V and measuring the change in voltage \$\Delta V\$ across R2 so
Rx = \$R_2(\frac {20}{\Delta V} -1) \approx R_2(\frac {20}{\Delta V}) \$
For example, if the voltage across R2 varies by 100uV for a 20V change in Vsupply, the output impedance would be 5M\$\Omega\$
For AC analysis, Cx will enter into the complex impedance and there may be other effects as well, but leave that for another time.


text:
Q: Unit Test Help. How do I test for a message output to console? I am a newbie to unit testing. How do I check the for console output?
I have
namespace XXShapes
{
    public abstract class XXShape
    {
        public virtual void DrawXXShape()
        {
            Console.WriteLine("The XXShape was drawn.");

        }
    }

public class XXCircle : XXShape
{
    public override void DrawXXShape()
    {
        Console.WriteLine("The XXCircle was drawn.");
    }
}

}
namespace XXShapes.Test
{
    [TestFixture]
    public class XXShapeTest
    {
        [Test]
        public void MyFirstTest()
        {
            XXShape s = new XXCircle();
            string expected = "The XXCircle was drawn.";
            s.DrawXXShape();
            string actual = Console.ReadLine();
            Assert.AreEqual(expected, actual);
        }
    }

}

How should I correctly be testing this?
Thanks for any pointers.
Cheers,
~ck

A: You don't need to test 'Console.WriteLine' routine because you have to assume it works - it is not your code, so why do you want to test it. You need to test whether you produce correct string that is passed to 'Console.WriteLine'
In other words, instead of:
public override void DrawXXShape()
{
    Console.WriteLine("The XXCircle was drawn.");
}

you could do:
public override void DrawXXShape()
{
    Console.WriteLine(produceXxCircle());
}

public string produceXxCircle()
{
    return "The XXCircle was drawn.";
}

and then in the test case:
Assert.AreEqual(produceXxCircle(), "The XXCircle was drawn.");

Hope it helps.
Regads
Simon

A: The literal answer would be that you would use Console.SetOut before calling the class under test to direct stdout into a memoryStream or similar, whose contents you can later inspect.
The better answer would be to use a mocking framework,  like Rhino Mocks to create a concrete instance of your abstract class, with an expectation set that the DrawXXShape method would be called.

A: That's not at all what you'd do.
In your test you will typically check for the state of the object, with something like:
Assert.IsTrue(foo.Field, Equals, "hello")

Depending on how your chosen framework works. So you'll need to change your approach, in general, to conform to this model.

A: I'm assuming that some other tests test for the drawing capabilities - If you now want to test that your classes write something in particular to the console, then you should abstract the idea of writing to the console.
Create an interface with a WriteLine() method in it and inject instances that implement this interface into XXShapes.  Your tests can inject mocks or stubs which can capture the strings that are written and test their contents in the tests.


text:
Q: How to remove fields from WooCommerce Customer Thank You Email (Customer Processing Order) I need to remove the following from the Customer Processing Order email that WooCommerce sends customers once they have placed an order:

*

*Payment Type

*Price of items purchased

*Everything that sits within the table below the items purchased, i.e. Total and Notes.
I've attached an image for a visual look at what needs ot be removed from the email:
items to be removed:

The file is found here: yourtheme/woocommerce/emails/customer-processing-order.php and it contains the code below but as you can see it's not a simple case of remove or comment out sections.:
<?php
/**
 * Customer processing order email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-processing-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates/Emails
 * @version 3.7.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/*
 * @hooked WC_Emails::email_header() Output the email header
 */
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php /* translators: %s: Customer first name */ ?>

<?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?>

<?php /* translators: %s: Order number */ ?>

<?php printf( esc_html__( 'Just to let you know — we\'ve received your order #%s, and it is now being processed:', 'woocommerce' ), esc_html( $order->get_order_number() ) ); ?>

<?php

/*
 * @hooked WC_Emails::order_details() Shows the order details table.
 * @hooked WC_Structured_Data::generate_order_data() Generates structured data.
 * @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
 * @since 2.5.0
 */
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::order_meta() Shows order meta data.
 */
do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::customer_details() Shows customer details
 * @hooked WC_Emails::email_address() Shows email address
 */
do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );

/**
 * Show user-defined additional content - this is set in each email's settings.
 */
if ( $additional_content ) {
    echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}

/*
 * @hooked WC_Emails::email_footer() Output the email footer
 */
do_action( 'woocommerce_email_footer', $email );

I've also used the following code in my functions.php file to remove the Subtotal and just below that, the Payment Method. But I still need help removing the other items.
add_filter( 'woocommerce_get_order_item_totals', 'adjust_woocommerce_get_order_item_totals' );

function adjust_woocommerce_get_order_item_totals( $totals ) {
  unset($totals['cart_subtotal']  );
  unset( $totals['payment_method'] );
  return $totals;
}

A: you can custom the content using woocommerce_email_before_order_table hook
add_action( 'woocommerce_email_before_order_table', 'custom_process_table', 10, 4 );
function custom_process_table( $order, $sent_to_admin, $plain_text, $email ) {
      // Your Custom Table goes here
}

you can also override the email template.
https://github.com/woocommerce/woocommerce/blob/master/templates/emails/email-order-details.php


text:
Q: How to split an allocation region so that the two regions can be reallocated separately? I want to split an allocated memory region in two at a specific point, so that those two regions can be realloc'd separately. I want to do this because I want to free space in the middle of the region.
My idea is to do something like this:
┌───────────────────────────────┐
│ Allocated                     │
└───────────────────────────────┘
              ↓
          split( );
              ↓
┌───────────────┬───────────────┐
│ Allocated     │ Allocated     │
└───────────────┴───────────────┘
              ↓
         realloc( );
              ↓
┌───────────┐   ┌───────────────┐
│ Allocated │   │ Allocated     │
└───────────┘   └───────────────┘
Is this possible in Rust? If so, how?

A: This is (currently) not possible.
Rust's memory allocation API is in the alloc module. And as you can see, the functionality you need is not offered there.
In theory, allocators could offer such a feature. However, in practice, this is usually not offered nor used. The standard allocation API in C also does not offer this as far as I know.


text:
Q: How to prevent other from tampering response msg in HTTPS? In HTTPS, only server hold the private key and is able to decode the message.
My doubt is whether server will encode the response before sending it to client?
If so, how does the client decode it, since it does not have the private key?
If not, how does it prevent others from tampering the response message?

A: I think I can answer my question by myself. The server will encrypt the response with public-key and send it to client. Other than that, the server will send a checksum as well, which acts as the signature. The checksum is generated based on the private-key that only server knows, therefore it is hard for others to fabricate it. Thus, if anyone trying tampering the message, it won't match the checksum.


text:
Q: Hosting Firebase ejecuta archivos php Buen dia, tengo un proyecto simple donde use php, y firebase. Cuando configuré el hosting de firebase e inicié el firebase deploy, accedí al link de la página pero no cargó nada, mas bien se decargó mi index.php.
Me podrian explicar si firebase acepta un index.php , y donde debo configurarlo?

A: Firebase ofrece servicios que facilitan la implementación de la lógica o diversos recursos de backend a tus aplicaciones.
Entendido esto, el uso que le puedes dar al servicio de hosting de Firebase es alojar tu código de frontend y que este haga uso de servicios de backend externos a firebase (en caso de que quieras utilizar lenguajes de backend diferentes a node, como php), también puedes integrar este mismo código de frontend con los distintos servicios de backend que proporciona Firebase.
Por otro lado, si requieres desarrollar la lógica de backend en php, por ejemplo, y además hacer uso de alguno de los servicios que proporciona Firebase, siempre puedes ubicar tu código de backend en otro servidor/servicio de alojamiento que soporte php e integrarle a tu código php alguna de las librerías que te permiten consumir los servicios de Firebase.
Te dejo un link hacia la documentación de Firebase en donde te detallan como realizar esto:
Para utilizar el SDK de Firebase en tu backend, consulta estos enlaces:
PHP: ejemplo de integración con el servicio de Firebase - FireStore
Otros lenguajes: Integración del SDK de Firebase Admin a tu servidor


text:
Q: Slide/scroll effect when linking to an anchor I have a link at the top of my site, that link to an object in the middle of my site. I have made a anchor link, so the user don´t need to scroll.
But I was wondering if I could make a slide/scroll effect, so when they click on the link, it scroll "slowly" to the object.

A: You can find the answer here: http://css-tricks.com/snippets/jquery/smooth-scrolling/
Essentially you need to link your javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Then add your script code:
    <script>
   $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
 });
});
 </script>


text:
Q: Output multiple objects from function R I'm not too sure if this question exists already or not. But after looking around the internet, I can't find anything that relates to my specific problem.
So, in R programming, I would like to mass output objects (specifically time series objects) from a data frame by splitting it. Before this, I have been pasting duplicate concatenation commands for each user and it feels like an extremely tedious process, so I was wondering if I could just build a function that will split a data frame by a variable, apply the ts() function, label that object created, and output all objects created.
Now ideally, the first thing I thought of was using the by command and apply a function to each split. For example, below is the code that I tried (note, this is just a small example, my real data frame is much larger than this).
#test df for stackoverflow
df<-data.frame(user=c(rep(1,5),rep(2,5),rep(3,5),rep(4,5)))
df$values<-c(10,20,30,40,9,19,29,39,11,21,31,41,12,22,32,42,8,18,34,44)

#playing around with the by command
dd<-by(df,df$user,FUN=function(x){
  time = ts(x$values,freqency=2),
  label = x$user[1],
  label<-time,
  return(label)
})

The error just says there's an error with the squiggly bracket. I've also looked at ddply in the 'plyr' package, but I couldn't get that working either.
Any advice/help/comments would be greatly appreciated, thanks.

A: If I understood correctly you want to split your data.frame by a variable and transform each portion as a time series object.
You can use plyr and get the result as a list (if your the number of data per user are not equal)
require(plyr)
dlply(df, .(user), function(df) ts(df$value, frequency = 12))

You can still use by if you want too
by(df$value, df$user, function(x) ts(x, frequency = 12))

## df$user: 1
##   Jan Feb Mar Apr May
## 1  10  20  30  40   9
## ------------------------------------------------
## df$user: 2
##   Jan Feb Mar Apr May
## 1  19  29  39  11  21
## ------------------------------------------------
## df$user: 3
##   Jan Feb Mar Apr May
## 1  31  41  12  22  32
## ------------------------------------------------
## df$user: 4
##   Jan Feb Mar Apr May
## 1  42   8  18  34  44


text:
Q: Overwriting entries from a matrix in cpp11 I have some Rcpp code to fill entries in a matrix, here's a MWE of what it does:
#include <Rcpp.h>

using namespace Rcpp;

void invert_tri(NumericMatrix &M, int K) {
    for(int i=0 ; i<K ; ++i) {
        for(int j=i+1 ; j<K ; ++j) {
            M(j, i) = M(i, j);
        }
    }
}

// [[Rcpp::export]]
NumericMatrix multiply_entries(NumericMatrix M, int factor) {
    int K = M.ncol();

    for(int i=0 ; i<K ; ++i) {
        for(int j=0 ; j<K ; ++j) {
            M(i, j) = M(i, j) * factor;
        }
    }

    invert_tri(M, K);

    return M;
}

Then in R I would use it like this:
M = matrix(c(1,NA,2,4), nrow = 2, ncol = 2)

multiply_entries(M, 2L)

This changes
     [,1] [,2]
[1,]    1    2
[2,]   NA    4

into
     [,1] [,2]
[1,]    2    4
[2,]    4    8

Then, with cpp11 I would sketch the following code
#include <cpp11.hpp>
#include <cpp11/doubles.hpp>

using namespace cpp11;

void invert_tri(writable::doubles_matrix<> &M, int K) {
    for(int i=0 ; i<K ; ++i) {
        for(int j=i+1 ; j<K ; ++j) {
            M(j, i) = M(i, j);
        }
    }
}

[[cpp11::register]]
doubles_matrix<> multiply_entries(writable::doubles_matrix<> M, int factor) {
    int K = M.ncol();

    for(int i=0 ; i<K ; ++i) {
        for(int j=0 ; j<K ; ++j) {
            M(i, j) = M(i, j) * factor;
        }
    }

    invert_tri(M, K);

    return M;
}

But here doing M(j, i) += M(i, j) would fail and with = fails because of implicit deletion. Do you have any ideas for an alternative approach to translate the working code.

A: maybe not the best approach for large matrices, but this just works
void invert_tri(writable::doubles_matrix<> &M, int K) {
    for(int i=0 ; i<K ; ++i) {
        for(int j=i+1 ; j<K ; ++j) {
            M(j, i) += (-1.0 * M(j, i)) + M(i, j);
        }
    }
}


text:
Q: Multiline Message Hangouts Chat Chatbot I'm newbie in developing Hangouts Chat Chatbots. I have a question if there's guide on how to create multi message on onmessage function from google script?
example:

Bot: Insert Number 1
User: 5
Bot Insert Number 2
User: 5
Bot: The Answer is 5


text:
Q: A bash/zsh script isn't getting invoked from a terminal in FreeBsd, neither in bash nor in zsh I have a script in FreeBsd 11
% cat my_script.sh
#!/usr/local/bin/zsh

# [........]

It has x attribute:
-rwxr-xr--   1 root  wheel  669 Jun 14 02:45 my_script.sh

My shell is zsh. When I'm trying to execute it, I get an error. It has to do with the way I'm invoking it:
% sudo ./my_script.sh var1
sudo: ./my_script.sh: command not found

% sudo my_script.sh var1
sudo: my_script.sh: command not found

% sudo source my_script.sh var1
sudo: source: command not found

What's the matter?
update:
I've changed my shell to bash, rebooted, changed the #! to bash and now I have:
$ sudo ./my_script.sh test9
sudo: ./my_script.sh: command not found

A:
% sudo ./my_script.sh var1
sudo: ./my_script.sh: command not found

This message indicates that either the file ./my_script.sh doesn't exist, or its loader doesn't exist. For a script, the loader is the executable mentioned in the shebang line.
Check that /usr/local/bin/zsh exists and that it isn't a broken symbolic link.
Check that the file really does contain #!/usr/local/bin/zsh as its first line and not, say #!/usr/local/bin/zsh with some whitespace or otherwise invisible characters after it or in the middle. Note in particular that a carriage return is one of the invisible characters that would break things. You would end up with a CR if you created (or perhaps if you edited) the script under Windows; if you edit scripts under Windows, make sure they're saved with line endings set to "LF" or "Unix" or "Linux" or whatever your editor calls it..

% sudo my_script.sh var1
sudo: my_script.sh: command not found

This one doesn't work for a simple reason: myscript.sh is not in the command search path.

% sudo source my_script.sh var1
sudo: source: command not found

This one doesn't work for a simple reason: source is a shell builtin, it isn't an executable. (It would make no sense as an executable since its purpose is to execute some shell code in the current shell — only a shell can do that.)
Which shell you're currently running is irrelevant for all three commands.

A: The problem is that sudo is neither guaranteed to maintain your current directory or your PATH.
Thus, to be sure scripts will be found, specify the complete path:
sudo /path/to/my_script.sh
The same error also appears for sudo source because source is a shell built-in, not a file. Instead of using a shell, sudo executes its arguments using execev, which expects a file.
For more information, see man sudo (particularly the Process model section and the -E and -s options), and for configuration options see man sudoers and /etc/sudoers.
For many more options about specifying the path to your script with sudo, see https://stackoverflow.com/questions/12996397/command-not-found-when-using-sudo


text:
Q: Unable to find `systrace.py` on my local android sdk folder How can I get systrace.py on my local android sdk folder as I'm unable to find the file at /tools and /platform-tools?
Below is the image for current SDKs installed on my local machine.

Following is the image for the current contents available for reference.

A: Looks like Google has stopped shipping systrace as part of platform tools recently:
This package used to contain systrace, but that has been obsoleted in favor of Studio Profiler, gpuinspector.dev, or Perfetto.

https://developer.android.com/studio/releases/platform-tools#downloads


text:
Q: Email attachments not included within Glassfish I have a MailMessage class I've written to manage sending email from my application.  It works fine for plain text messages, and the attachment logic works when I compile and run it manually on the command line, but it fails to include my attachments when I'm running it within Glassfish 3.1.  I'm assuming there must be some subtle class loading problem that I'm clobbering on the command line by having my CLASSPATH environment set, but I haven't been able to figure out what application server setting I need to change.  Here's the code I use to create and send my mail message when running on the command line:
public static void main(String[] args) throws Exception {
  String[] toAddr = new String[] {"steve.ferguson@epsilon.com"};
  String subject = "This is a test";
  String data = "This is a message body";
  MailMessage mailMessage = new MailMessage(toAddr, subject, data);
  mailMessage.addAttachment(new File("/etc/hosts"), "text/plain");
  mailMessage.send();
}

If I change this function to a method called by my servlet, with debugging enabled, the resulting mail message looks like this:
[#|2011-11-17T11:21:37.710-0500|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=105;_ThreadName=Thread-1;|Date: Thu, 17 Nov 2011 11:21:37 -0500 (EST)
From: sender@mydomain.com
To: steve.ferguson@mydomain.com
Message-ID: <9116840.7.1321546897580.JavaMail...>
Subject: This is a test
MIME-Version: 1.0
Content-Type: multipart/mixed;
        boundary="----=_Part_6_16232037.1321546897569"

.
|#]

By comparison, when I run the same code on the command line, it shows all of the attachments, each with the separate message boundary.  This is the function I'm using to add the attachments to the underlying MimeMessage:
private Multipart buildMultipartMessage(String messageBody)
        throws MessagingException {
  MimeBodyPart messagePart = new MimeBodyPart();
  messagePart.setText(messageBody.toString());

  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messagePart);

  // Attach each of our files
  for (File part : attachment.keySet()) {
    BodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(new FileDataSource(part)));
    attachmentPart.setFileName(part.getName() + ".txt");
    attachmentPart.setHeader("Content-Type", attachment.get(part));
    attachmentPart.setHeader("Content-ID", part.getName());
    attachmentPart.setDisposition(Part.ATTACHMENT);
    multipart.addBodyPart(attachmentPart);
  }

  return multipart;
}

Which is called and used like this by my MailMessage class:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@mydomain.com"));
InternetAddress[] addresses = new InternetAddress[mailTo.length];
for (int i = 0; i < mailTo.length; i++)
  addresses[i] = new InternetAddress(mailTo[i]);
message.setRecipients(Message.RecipientType.TO, addresses);
message.setSubject(subject);
message.setSentDate(new Date());

Multipart multipart = buildMultipartMessage(messageBody.toString());
message.setContent(multipart);

Again, all of this code, exactly as is, compiles, runs, and produces a valid email with attachments when run on the command line.  It's only when I do the same thing within Glassfish that I get an empty message.
Any suggestions on how to diagnose this would be most appreciated.
Steve
UPDATE:
If I add this code after the call to buildMultipartMessage(), but before message.setContent(multipart), I can see that the content is correct:
  try {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/var/tmp/stf"));
    multipart.writeTo(bos);
    bos.close();
  } catch (Exception ex) { }

The /var/tmp/stf file contains the full message body with attachments and separators.  I'm still confused as to why this works from the command line, but not within Glassfish, but the information may be useful in resolving the problem.

A: It turned out that my solution to this problem caused the current problem.  Having javax.mail.jar in my boot classpath and activation.jar in my endorsed directory was the only way I could get email handling working with the logger, but then they didn't work for normal usage.  I have no idea why this is, but I found that eliminating the -Xbootclasspath option and removing activation.jar from my endorsed directory fixed the problem.  If anyone has any speculation as to why, I'd be glad to do some more testing and report back.  For now, I guess I have to live without email logging, because the attachments are a requirement for my application.
Perhaps if I switch to log4j instead of using the native Java EE 6 logging, I can have the best of both worlds.


text:
Q: creating generic enum wrapper for validations Disclaimer: not very strong with generics.
enum WeekDays {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
enum Months {
   JANUARY, FEBRAURY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
}
enum Directions {
   East, West, North, South, Up, Down
}

Let's say I have above enums and there is a service which sends me random Strings.
I need to verify if the targeted String response is a valid enum value or not.
I was thinking of coding of something on lines as below:
static <T> boolean isValidEnum(String value, T enumClass ){
   try {
       enumClass.valueOf(value);
       return true;
   } catch (Exception e) {
   }
   return false;
}

The call would be like:
isValidEnum("TUESDAY", WeekDays)

but line enumClass.valueOf(value); is not happy about my function.
Any pointers is appreciated! TIA

A: You can rewrite it to this:
static <T extends Enum<T>> boolean isValidEnum(String value, Class<T> enumClass ){
    try {
        Enum.valueOf(enumClass, value);
        return true;
    } catch (Exception e) {
    }
    return false;
}

and
isValidEnum("TUESDAY", WeekDays.class)

A: You need to iterate the Enum values and check if there is a match with the value passed:
With Java 8 and newer versions:
static <T> boolean isValidEnum(String value, T enumClass ){
    return Arrays.stream(((Class) enumClass).getEnumConstants())
            .anyMatch(v -> v.toString().equals(value));
}

With older Java versions:
static <T> boolean isValidEnum(String value, T enumClass ){
    for (Object v : ((Class) enumClass).getEnumConstants()){
        if (v.toString().equals(value)) return true;
    }
    return false;
}

A: There is a library for this, you can also use that in case you don't want to implement it.
EnumUtils of org.apache.commons.lang3
EnumUtils.isValidEnum(WeekDays.class, "TUESDAY")


text:
Q: Criar menu lateral igual ao App Clima do Windows 10 Os amigos que me acompanham por aqui, já devem ter lido uma pergunta anterior que fiz com esse mesmo tema.
Mas como citei em meu ultimo comentário lá, acabei desistindo da ideia inicial, pois concluir que eu estava indo rápido demais para alguém sem experiência em WPF.
Sendo assim, resolvi optar por um design um pouco mais simples, porém igualmente diferente para um sistema que venho trabalhando.
Gostaria de algumas sugestões de quais componentes, layouts, propriedades usar para criar uma MainWindows aos moldes do app Clima do Windows 10.
Como é necessário começar por algum lugar, primeiramente gostaria de receber sugestões de como criar um menu lateral como aquele, que abre e recolhe ao clicar no botão superior.

Quais layouts e componentes devo usar para conseguir isso.

A: Nos repositórios GitHub da Microsoft você encontra um específico que possui dezenas de exemplos de aplicações UWP. Cada um mostrando como usar um recurso específico.
Aqui você pode ver a lista de Exemplos de Navegação, talvez aqui tenha o que você precisa, senão precisa garimpar nos outros exemplos.


text:
Q: How to grow number smoothly from 0 to 5,000,000 This is probably basic math that I don't seem to remember.
I'm trying to get from 0 to 5,000,000 in 10 seconds while having all the numbers ticking. I don't have to have the number reach exactly 5,000,000 because I can just do a conditional for it to stop when it's over.
Right now I have this:
count+= 123456

if (count > 5000000) {
    count = 5000000;
}

It gives the sense of number moving you know? But It really starts off too high. I wanted to gradually climb up.

A: You could do something like this:
function timedCounter(finalValue, seconds, callback){

  var startTime = (new Date).getTime();
  var milliseconds = seconds*1000;

  (function update(){

    var currentTime = (new Date).getTime();
    var value = finalValue*(currentTime - startTime)/milliseconds;

    if(value >= finalValue)
      value = finalValue;
    else
      setTimeout(update, 0);

    callback && callback(value);

  })();

}

timedCounter(5000000, 10, function(value){
  // Do something with value
});

Demo
Note that with a number as big as 5000000 you won't see the last couple digits change. You would only see that with a small number like 5000. You could fix that; perhaps by adding in some randomness:
value += Math.floor(Math.random()*(finalValue/10000 + 1));

Demo with randomness

A: You can tween:
import fl.transitions.Tween;
import fl.transitions.easing.Regular;

var count = 0;
var tween:Tween = new Tween(this, "count", Regular.easeInOut,0,5000000,10, true);

This will tween you variable count from 0 to 5000000 in 10 seconds. Read about these classes if you want to expand on this code.

*

*Tween

*TweenEvent
Good luck!


text:
Q: How to show XYZ coordinates without the 'Fn' key? My keyboard doesn't have an Fn key so I can't get the coordinates to show up. I don't know how to get into the multiplayer settings and Shift + F3 doesn't work either.
How can I fix this?

A: Just press F3.
If your keyboard does not have Fn, then odds are, F3 works as normal. No keyboard manufacturer would require Fn+F3 without providing a Fn key. That doesn't make any sense.

A: You seem to be on a Mac. On there, you should open System Preferences, go in Keyboard and enable the use of Function keys as delfault actions. I had to do this too on my Mac!

A: There are many ways for going to the coordinate screen, such as:

*

*Press F3

*Go to Options, click controls and change the key needed

*You may have a 'f lock' key . Try that.

A: If f3 does not work, go to Mac system preferences, keyboard, then tick "use f keys as normal" go back to your game and hit f3.  Done

A: The Mac keyboards do not have the Fn button and the F3 key is used to manage your different windows. I fear there may be no way to access coordinates on this situation.


text:
Q: Android, why is there no way to set size proportional to parent I have looked for question on this website and through google but there are no  easy ways to set the size of the a View proportional to the parent.
Since android is a language that runs on devices of many screen densities and sizes it would make sense to have an easy to use method to set the size of views based upon the parent such as: 0.5*match_parent
I found some solutions but none of them are simple single lines that you would expect would be built into android, since every android app needs to support many screen sizes.
Is there some restriction because of the way activities are built? Is it inefficient to have to retrieve the size of the parent?

A: Now it is possible to set size proportional to parent. The Constraint Layout
allows to do it.
Check this answer for more details


text:
Q: Vectorizing A Custom Function I wrote this function to return the string before a certain character, which goes like so:
strBefore <- function(find, x, last = FALSE, occurence) {

  # Checking.
  if (class(x)[1] != "character") { stop("The strBefore function only supports objects of character class.") }

  # Getting the place of the find, and handling both caes of last.
  fullPlace <- gregexpr(find, x)[[1]] # Gets the location of the occurences of find in x.

  # Handling the case where last is TRUE.
  if (last == TRUE) { place <- max(fullPlace) # Grabbing the latest character index if last is TRUE.
  } else { place <- min(fullPlace) } # Otherwise, getting the first space.

  # Handles the occurrenceargument if given.
  if (!missing(occurrence)) { place <- fullPlace[occurrence] }

  # Subsetting the string.
  xlen <- nchar(x) # Getting the total number of characters in the string.
  x <- substr(x, 1, place - 1) # Minus 1 because we don't want to include the first hit for find.
  return(x)

}

Where find is the character you want the string before, x is the character, last asks if you to get before the last occurrence of find, and occurrence designates which occurrence of find to get before (overrides last if given).
If I use it on a single character object, it works fine like so:
> test <- "Hello World"
> test2 <- strBefore(" ", test)
> test2
[1] "Hello"

However, if I use it on a character vector, it cuts each item in the vector at the same place as the first item:
> test <- c("Hello World", "Hi There", "Why Hello")
> test2 <- strBefore(" ", test)
> test2
[1] "Hello" "Hi Th" "Why H"

Now, this link here does provide me with a method for doing what I want:
Using gsub to extract character string before white space in R
However, I do like having the functionality of the "occurrence" argument, which returns the string before the 2nd, 3rd, etc... occurrence of the find argument.
Just as a note, I can vectorize my function with sapply like so:
> test <- c("Hello World", "Hi There", "Why Hello")
> test2 <- sapply(test, function(x) strBefore(" ", x))
> test2
Hello World    Hi There   Why Hello
    "Hello"        "Hi"       "Why"

Which somewhat solves my problem...but is there a way to do this more cleanly without having to use an apply function? I'm not looking for a solution to what strBefore does, but more a solution to how to vectorize custom functions. Thanks for your time.


text:
Q: Bootstrap-vue dynamic toast isn't working I am trying to use dynamic toast from bootstrap-vue. Here what I am trying to do:
<template>
 <b-button @click="handleClick(education)"></b-button>
</template>

<script>
import { notificationToast } from "@/components/NotificationToast";

export default{
 methods:{
  handleClick(){
   notificationToast(true);
 }
}
</script>

NotificationToast.js
import Vue from "vue";
import { BVToastPlugin } from "bootstrap-vue";

Vue.use(BVToastPlugin);

let notificationToast = (append = false) => {
  this.$bvToast.toast(`This is toast`, {
    title: "BootstrapVue Toast",
    autoHideDelay: 5000,
    appendToast: append,
  });
};

export { notificationToast };

Whenever I click on the button it show the error :
TypeError: Cannot read property '$bvToast' of undefined
As it is mentioned in the doc, I imported BVToastPlugin, still the problem is occurring. What to do? Thanks in advance.

A: In the module, the this keyword does not refer to the Vue component.  The simplest workaround might be to make a second argument and pass in the context from the component:
let notificationToast = (vm, append = false) => {
  vm.$bvToast.toast(`This is toast`, {
    title: "BootstrapVue Toast",
    autoHideDelay: 5000,
    appendToast: append,
  });
};

And call it like:
notificationToast(this, true);


text:
Q: error when use ant to build android project jarsigner: Certificate chain not found for: csi.keystore. csi.keystore must ref
erence a valid KeyStore key entry containing a private key and corresponding pub
lic key certificate chain..
who has idea? thanks...

A: This is because your building in release mode. If you build in debug mode it should work. I need to set thus up for release mode myself so let me know how you do it in release mode if you get it working

A: thanks Ben!
Yes,I build it in debug mode it should work.But I build it in release get error,I cannot find the reason for it.

        <!-- sign the APK -->
        <echo>Signing final apk...</echo>
        <signjar
                jar="${out-unsigned-package}"
                signedjar="${out-unaligned-package}"
                keystore="${key.store}"
                storepass="${key.store.password}"
                alias="${key.alias}"
                keypass="${key.alias.password}"/>
        <!-- zip align the APK -->
        <echo>Running zip align on final apk...</echo>
        <exec executable="${zipalign}" failonerror="true">
            <arg value="-f" />
            <arg value="4" />
            <arg path="${out-unaligned-package}" />
            <arg path="${out-release-package}" />
        </exec>
        <echo>Release Package: ${out-release-package}</echo>
    </target>

A: I had a very similar problem.
The cause was that I was specifying a different keystore than the one for which I was providing the credentials.
Make sure that the following properties (if you've defined them) match:

*

*key.store

*key.store.password

*key.alias

*key.alias.password

In my case, I has specified the first two in my local.properties file (that I had copied from another project assuming it only held the SDK dir) and the last two specified the correct credentials.
Hope this helps.


text:
Q: $request->file return null - Laravel I tried to upload file from a pc to my Laravel application and store to XAMPP server. Unfortunately, every time when I want to check the file extension using $request->file it always return me null.
But when I tried to debug I have seen that file image name that I uploaded from my system.
Here is code from front end:
<form action="{{action('CompaniesSettingController@update', $edit_info->id)}}" method="post",enctype="multipart/form-data">

    <input class="file-upload" name="company_profile" type="file" id="" accept="image/*"/>

Here Controller code:
dd($request->all());
$filenameWithExt = $request->file('company_profile')->getClientOriginalName();

Here is what I got from dd
array:12 [▼

  "company_profile" => "myimage.jpg"
  "name" => "App Name"
  "email" => "myapp@gmail.com"
  "phone_number" => "12345678"
  "company_overview" => "dfsa"
  "mission" => "dfs"
  "working_evn" => "fgsd"
  "company_ach" => "dfsgdfs"
  "facebook" => "dfsg"
  "linkedin" => "dsf"
  "website" => "sdfsfdg"
 ]

As you can see the file that I have uploaded with named "company_profile" => "myimage.jpg". So, I want to get that image name but it return null and also that file image should be stored in my application and file name I will store in database.

A: Remove the comma after the method="post" attribute and add space.
Change this line:
<form action="{{action('CompaniesSettingController@update', $edit_info->id)}}" method="post",enctype="multipart/form-data">

to
<form action="{{action('CompaniesSettingController@update', $edit_info->id)}}" method="post" enctype="multipart/form-data">

And then check the dd($request->all()) to ensure that it is not the string against company_profile.


text:
Q: Microsoft Teams - Can't Connect To The Internet - Request Timeout After Second Start After a clean install, I can start Teams, login and use it normally for the first run only. But when I close the application and try to restart it later, there is a delay of around 55 seconds, which ends with a request timeout.

I tried to delete the files in the Teams folder and found that the error wouldn't happen the following file was deleted:
%AppData%\Microsoft\Teams\settings.json

However, every time Teams is started, the file is created or overwritten again.
The next step was to find the exact setting within the settings.json file.
After I change the enableProcessIntegrityLevel property-value from true to false and save the file, Teams starts once, without the timeout error:
"enableProcessIntegrityLevel":false

What does this value exactly do and how can I fix the problem?
Teams version 1.0 did not have this issue, but I updated to a newer version and cannot downgrade to the version that worked for me.
Some Details:
Teams version: 1.2.00.8864 x64 (last, from 30.03.2019)
Tried on:

*

*Windows Server 2016 x64 1607 Build (14393.1884)

*Windows Server 2008 R2 x64 7601 Build SP1

*Windows 7 x64 / Windows 10 x64

Error message:
Oh no ... we can't connect to the internet. Check your connection
Error code - Request timeout
Failed to connect to settings endpoint

Teams-Log:
Teams try 7 times to connect somewhere but this fails.

In this tech community thread are some more log files instances from when this error occurs.
EDIT:
Hi, today I found a workaround for the issue :)

*

*Sign out and close any instances of Microsoft Teams running.

*Navigate to the following path: %userprofile%\appdata\Roaming\Microsoft\Teams

*Create a json file called hooks.json

*Use your favourite notepad editor, add the following line to the newly created file:
{"enableProcessIntegrityLevel": false}

*Save and close the file.

*Now, re-open Microsoft Teams and sign in.
Source: thread on answers.microsoft.com
We will now distribute the hooks.json file via a policy.

A: the error no longer occurs since the MS teams application was updated (can not remember but it should be one of the last versions of 1.2 or one of the first versions of 1.3).
Here are the steps for the workaround again:

*

*Sign out and close any instances of Microsoft Teams running.

*Navigate to the following path: %userprofile%\appdata\Roaming\Microsoft\Teams

*Create a json file called hooks.json

*Use your favourite notepad editor, add the following line to the newly created file: {"enableProcessIntegrityLevel": false}

*Save and close the file.

*Now, re-open Microsoft Teams and sign in.

In the current MS Teams version (1.3.00.30866 x86), the settings.json file contains the "enableProcessIntegrityLevel" value several times, sometimes it is "true" and sometimes "false". This led to a malfunction (webcams and microphones were sometimes no longer recognized), so that we had to delete the hooks.json files from the user profiles.
Until then, the solution with the hooks.json file had worked well. The solution can also be used for other purposes to define settings for the MS Teams application.
Sorry, I was not aware that questions that do not contain an answer are still considered unsolved.


text:
Q: Extracting string from logs with regex in pig script I have log data and I want to extract each information into a variable
The following is sample one line log.
{:id=>306, :name=>"bblite", :cpu=>{:quota=>4, :allocated=>4, :actual=>0}, :memory=>{:quota=>8192, :allocated=>8192, :actual=>8578}, :cluster_stats=>{"wc1104"=>{:cpu=>0, :mem=>8578}}}
I need variable that have all ids,a variable that have all names,a variable that have CPUs and a variable that have all cluster stats
The following is the portion of my pig script. I can store the ids but I have no idea how to extract the rest of them using regex.
.
.
.
matching_messages = FILTER raw_lines BY (LOWER(message) MATCHES '.*cc_altus-plaform.*');

ids = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'id=>\\d*',0);

names = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'name=>\\"\\",',0);

line_with_date = FOREACH matching_messages GENERATE
DateFormatter(timestamp) AS formatted_time: chararray, message;

DUMP names;

A: The following codes snippet is the regex I have written which works:
id = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'(?<=id=>)\\d*',0);

name = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'name=>\\"[\\w]*\\"',0);

cpu = FOREACH matching_messages GENERATE REPLACE( REGEX_EXTRACT(message, 'cpu=>\\{.*?\\}',0), ',','');

memory = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'memory=>\\{.*?\\}',0);

cluster = FOREACH matching_messages GENERATE REGEX_EXTRACT(message,'cluster_stats=>\\{.*?\\}',0);


text:
Q: lisp last element functional form Hey guys I need help with lisp function. I am supposed to create:
(myLast L)
    Evaluates to the last element of list L.
    eg.  (myLast '(p a e g))  →  g
I cant use all of the predefined forms for lisp only the ones we have been given in class:
(atom X)
(quote X)
'X
(eq X Y)
(cons X L)
(car L)
(cdr L)
(list A B C)
(if X Y Z)
(cond (C1 S1) (C2 S2) …… (Cn Sn))

I thought I had it right when I put in:
(defun myLast (L)
   (if ((eq L '()) (cdr L))
      (car L)
      (myLast (cdr L))))

However I am getting an error:
Error: The variable MYHW4.LISP is unbound.
Error signalled by EVAL
Backtrace: EVAL
Broken at SYSTEM::GCL-TOP-LEVEL.

I am completely new to LISP and trying to complete this assignment. I was hoping you guys could help me out and let me know why I am getting this error, and is my logic for the last functional form correct? Thanks!

A: The error message is unrelated to your code. You probably typed (load myhw4.lisp) without quotes in which case your Lisp rightly think that you wanted to take the value bound to the variable myhw4.lisp, which does not exist. You need to quote strings "like so".
Also, ((eq L '()) ...) is problematic, since the first form is (eq ...) which is not a function or a lambda. That will signal an error..
The above makes your code wrong, but you are not far from it.

A: There are multiple problems with your code.
You have excess parentheses. ((eq L '()) is not allowed as the only expression allowed at operator position is an anonymous function.
Your if only have a consequence expression but not a alternative. It isn't the last expression so it's dead code.
The you do car, also not in real position so far code also.
Tail expression is the recursion and is done unconditionally. It's called infinite recursion.
I think perhaps you meant something like this:
(defun myLast (list)
  (if (null (cdr list))
      (car list)
      (myLast (cdr list))))


text:
Q: Android Basics - Two classes show image I have one main class called MainActivity.java and another class Image.java
nothing fancy
MainAcivity.java
    public class MainActivity extends Activity {

    Image myimage;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myimage = new Image();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Image.java
     public class Image extends Activity {
ImageView image_view;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      Bitmap image = BitmapFactory.decodeResource(getResources(),       R.drawable.iguana);
      image_view = (ImageView)findViewById(R.id.iv);
       image_view.setImageBitmap(image);
}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
However, it's never displayed.
If I put the show image code to my MainActivity it does work.
I assume I may not call the Image class correctly.
In my layout.xml
    <ImageView
    android:id="@+id/iv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="126dp"
    android:layout_toRightOf="@+id/textView1" />

€ SOLVED
Adding following code into my MainActivity.class startet the Image.class
Thank you
          Intent intent = new Intent(this, Image.class);
      startActivity(intent);

A: Image is an Activity, and you have to start it with startActivity. There is no need to instantiate it, android is going to take care of it for you

A: It doesn't display because Image#onCreate is never called. With new Image() you're just creating that object, not calling Image#onCreate. You need to launch the Image activity from your MainActivity. And no need to call new Image() actually.

A: You must declare Image Activity in android manifest.


text:
Q: Multiple streams reading from the same file I have a number of input files, which I'm reading in parallel and performing computations on every line that I read. However, for every line (in every file), I need to access one of about hundred files, loop through the entirety it and write the every combination into an output file.
So, basically, I have something like this (note, that I only added the crucial parts of the code):
int numberOfFiles = (int) new File("path/").listFiles().length;

IntStream.range(0, numberOfFiles).parallel().forEach(k -> {
    BufferedWriter bw = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(new File("priorityQueuePreTerminal"+k+".txt")));
        bw = new BufferedWriter(new FileWriter(new File("priorityQueuePostTerminal"+k+".txt"), true));
        ...
        try {
            while( (line = br.readLine()) != null ){
            ...
                BufferedReader br2 = new BufferedReader(new FileReader(new File("shared/"+i+".txt")));
                while( (line2 = br2.readLine()) != null ){
                    bw.write(...);
                }
            }
        } catch (Exception e) { } finally { br2.close(); }
    } catch (Exception e) { } finally { br.close(); bw.close(); }
});

What essentially happens, is that two input files can read from the same one of those hundred shared files, at the same time.
The end result is, that one of the output files is always fully completed, like it should be, while all the other output files have the starting few lines, and then they end prematurely.
Am I even able to read from the same shared file by multiple streams (I was under the impression that reading from the same file by multiple resources was fine, but writing could be problematic)? Is there an equivalent to synchronized in Java 8 streams, to make sure that one stream is currently reading only from one file?

A: Hello reading in parallel a file is a really bad idea. Because your hardware your hard drive is constrained by some number. Lets say 700 MB per second. At one point no matter how much more you read in paralel eventually you will not see any performance gains. Try to optimize your data processing in parallel instead of you IO access to the disk.
Although not a real answer. My advice to you is to read all the files at ones into the memory or as much as you can into the memory. And then do the multithreading in the processing part of the assignment instead one the file reading.


text:
Q: Compiling a MFC app from Visual Studio 2010 to 2012 RC results in LNK2038 My project is compiling and running OK in debug and release modes in VS 2010.
Today I tried to compile it with VS 2012 and I got this error :
1>  Generating Code...
1>pcrecppd.lib(pcrecpp.obj) : error LNK2038: mismatch detected for '_MSC_VER':
value '1600' doesn't match value '1700' in NamesEditorDlg.obj

I searched for "_MSC_VER" in the code but I could not find any match. Neither could I find  "1600" or "1700".
So I am wondering how I can solve this problem.

A: Looks like you're using a .lib from vc2010 in vc2012 (at a guess it looks like a PCRE library). You'll need to recompile all your .libs or run-time link with the DLLs (ie LoadLibrary, GetProcAddress etc.).

A: In Project Properties, select General and then change the "Platform Toolset" setting to "Visual Studio 2010 (v100)." After I did that, my code compiled fine with the original libraries.

A: Looking it up at http://msdn.microsoft.com/en-us/library/b0084kay.aspx It seems that variable holds the compiler's version number.  I would think the best way to fix it would be to create  a new project in 2012 and add the source files to the new project.

A: NO, all that you need is is check properties of the project. There exist link to old project files. Need open project properties on page ".NET Framework and links" there del all links end add new for new 2012 project files.


text:
Q: How to Load Component Services/DCOM Config SnapIn I have a PS script to do some DCOM configuration. It works fine as long as I have the Component Services/DCOM Config snapin loaded. I want to load that programmatically so I can do all of this as part of an install package. Does anyone know how to do it? I don't know the name of the snapin to add/import.
To load the snapin I run comexp.msc -32 and click Component Services, Computers, My Computer, DCOM Configuration.
Thanks

A: I faced a similar problem. I couldn't find a way of loading  Component services on the DCOM Config spapIn. But I found a workaround to add the user the Default DCOM Launch and Activation permissions using this powershell script:
https://www.peppercrew.nl/index.php/2012/03/set-dcom-remote-access-via-powershell/
That way, you don't need to assign the user to that particular DCOM App.
Hope this help
This is the powershell script:
   PARAM(
    [string]$Principal = $(throw "`nMissing -Principal DOMAIN\Group"),
    $Computers = $(throw "`nMissing -Computers ('server01','server02')"))

# USAGE:
# .\Set-RemotePermission-DCOM.ps1 -Principal "DOMAIN\" -Computers ('', '',...)
#
# EXAMPLE:
# .\Set-RemotePermission-DCOM.ps1 -Principal "DOMAIN\LG-Citrix-Admins" -Computers ('CTX_DC001', 'CTX_DC002')
#
# Inspired by Karl Mitschke's post:
# http://unlockpowershell.wordpress.com/2009/11/20/script-remote-dcom-wmi-access-for-a-domain-user/
#
# And inspired Brad Turner's post:
# http://social.technet.microsoft.com/Forums/en-US/ilm2/thread/5db2707c-87c9-4bb2-a0eb-912363e2814a/

function get-sid
{
 PARAM ($DSIdentity)
 $ID = new-object System.Security.Principal.NTAccount($DSIdentity)
 return $ID.Translate( [System.Security.Principal.SecurityIdentifier] ).toString()
}

$sid = get-sid $Principal

#DefaultLaunchPermission - Local Launch, Remote Launch, Local Activation, Remote Activation
$DCOMSDDLDefaultLaunchPermission = "A;;CCDCLCSWRP;;;$sid"

#DefaultAccessPermision - Local Access, Remote Access
$DCOMSDDLDefaultAccessPermision = "A;;CCDCLC;;;$sid"

#PartialMatch
$DCOMSDDLPartialMatch = "A;;\w+;;;$sid"

foreach ($strcomputer in $computers)
{
 write-host "`nWorking on $strcomputer with principal $Principal ($sid):"
 # Get the respective binary values of the DCOM registry entries
 $Reg = [WMIClass]"\\$strcomputer\root\default:StdRegProv"
 $DCOMDefaultLaunchPermission = $Reg.GetBinaryValue(2147483650,"software\microsoft\ole","DefaultLaunchPermission").uValue
 $DCOMDefaultAccessPermission = $Reg.GetBinaryValue(2147483650,"software\microsoft\ole","DefaultAccessPermission").uValue

 # Convert the current permissions to SDDL
 write-host "`tConverting current permissions to SDDL format..."
 $converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper
 $CurrentDCOMSDDLDefaultLaunchPermission = $converter.BinarySDToSDDL($DCOMDefaultLaunchPermission)
 $CurrentDCOMSDDLDefaultAccessPermission = $converter.BinarySDToSDDL($DCOMDefaultAccessPermission)

 # Build the new permissions
 if (($CurrentDCOMSDDLDefaultLaunchPermission.SDDL -match $DCOMSDDLPartialMatch) -and ($CurrentDCOMSDDLDefaultLaunchPermission.SDDL -notmatch $DCOMSDDLDefaultLaunchPermission))
 {
   $NewDCOMSDDLDefaultLaunchPermission = $CurrentDCOMSDDLDefaultLaunchPermission.SDDL -replace $DCOMSDDLPartialMatch, $DCOMSDDLDefaultLaunchPermission
 }
 else
 {
   $NewDCOMSDDLDefaultLaunchPermission = $CurrentDCOMSDDLDefaultLaunchPermission.SDDL + "(" + $DCOMSDDLDefaultLaunchPermission + ")"
 }

 if (($CurrentDCOMSDDLDefaultAccessPermission.SDDL -match $DCOMSDDLPartialMatch) -and ($CurrentDCOMSDDLDefaultAccessPermission.SDDL -notmatch $DCOMSDDLDefaultAccessPermision))
 {
   $NewDCOMSDDLDefaultAccessPermission = $CurrentDCOMSDDLDefaultAccessPermission.SDDL -replace $DCOMSDDLPartialMatch, $DCOMSDDLDefaultAccessPermision
 }
 else
 {
   $NewDCOMSDDLDefaultAccessPermission = $CurrentDCOMSDDLDefaultAccessPermission.SDDL + "(" + $DCOMSDDLDefaultAccessPermision + ")"
 }

 # Convert SDDL back to Binary
 write-host "`tConverting SDDL back into binary form..."
 $DCOMbinarySDDefaultLaunchPermission = $converter.SDDLToBinarySD($NewDCOMSDDLDefaultLaunchPermission)
 $DCOMconvertedPermissionDefaultLaunchPermission = ,$DCOMbinarySDDefaultLaunchPermission.BinarySD

 $DCOMbinarySDDefaultAccessPermission = $converter.SDDLToBinarySD($NewDCOMSDDLDefaultAccessPermission)
 $DCOMconvertedPermissionsDefaultAccessPermission = ,$DCOMbinarySDDefaultAccessPermission.BinarySD

 # Apply the changes
 write-host "`tApplying changes..."
 if ($CurrentDCOMSDDLDefaultLaunchPermission.SDDL -match $DCOMSDDLDefaultLaunchPermission)
 {
   write-host "`t`tCurrent DefaultLaunchPermission matches desired value."
 }
 else
 {
   $result = $Reg.SetBinaryValue(2147483650,"software\microsoft\ole","DefaultLaunchPermission", $DCOMbinarySDDefaultLaunchPermission.binarySD)
   if($result.ReturnValue='0'){write-host "  Applied DefaultLaunchPermission complete."}
 }

 if ($CurrentDCOMSDDLDefaultAccessPermission.SDDL -match $DCOMSDDLDefaultAccessPermision)
 {
   write-host "`t`tCurrent DefaultAccessPermission matches desired value."
 }
 else
 {
   $result = $Reg.SetBinaryValue(2147483650,"software\microsoft\ole","DefaultAccessPermission", $DCOMbinarySDDefaultAccessPermission.binarySD)
   if($result.ReturnValue='0'){write-host "  Applied DefaultAccessPermission complete."}

 }
}
#----------------------------------------------------------------------------------------------------------
 trap
 {
 $exMessage = $_.Exception.Message
 if($exMessage.StartsWith("L:"))
 {write-host "`n" $exMessage.substring(2) "`n" -foregroundcolor white -backgroundcolor darkblue}
 else {write-host "`nError: " $exMessage "`n" -foregroundcolor white -backgroundcolor darkred}
 Exit
 }
#----------------------------------------------------------------------------------------------------------

A: I faced the same issue and, I believe, it's because there's no equivalent 64-bit registry entry so PowerShell doesn't see it. Launching mmc compexp.msc /32 and expanding DCOM Config seems to create the entry in the background.
The work-around is to manually add the 64-bit AppID yourself which is simply done by the following code,
$appGUID = 'YOUR_APPNAME_OR_GUID'

New-PSDrive -PSProvider Registry -Name HKCR -Root HKEY_CLASSES_ROOT
New-Item -Path HKCR:\AppID\$appGUID -Value $appGUID
#New-Item -Path HKCR:\Wow6432Node\AppID\$appGUID -Value $appGUID
Remove-PSDrive HKCR

I've left the 32-bit location in the above code too although that should already exist. Once you run the above then PowerShell should be able to see the COM component,
Get-WMIObject -query ('SELECT * FROM Win32_DCOMApplicationSetting WHERE AppID = "' + $appGUID + '"') -EnableAllPrivileges

Hope this helps someone as it was driving me bananas for hours!


text:
Q: Using a loop to rar multiple subfolders in a main folder I have a main folder with 3 subfolders ...

*

*C:\Users\Admin\Folder

*

*Folder1

*Folder2

*Folder3

I want that the batch script grabs the first subdirectory Folder1, copy it to another location, for example C:\Temp\Folder and than WinRAR starts to archive Folder1. After copying Folder1 to another location it can be deleted in the main folder.
After WinRAR finished archiving Folder1 can also be deleted in C:\Temp\Folder. So only the .rar files remain.
Then the script starts from new with Folder2 and do the same as with Folder1.
So far I have only this and do not really know how to implement the above.
"C:\Program Files\WinRAR\Rar.exe" a -ep1 -mt5 -v50M -r -df "NAME-OF-THE-RAR-FILE" "C:\Users\Admin\Folder\*.*"

A: Open a command prompt window, type and execute for /? and read help output for this command. The option /D is explained already on first help page which is for executing commands on each subdirectory of a directory.
The batch file below archives each subfolder in C:\Users\Admin\Folder using console version of WinRAR with command m (move = archive and delete on success) instead of command a with switch -df.
@echo off
for /D %%F in ("C:\Users\Admin\Folder\*") do (
    "%ProgramFiles%\WinRAR\Rar.exe" m -cfg- -ep1 -inul -m5 -mt5 -r -tl -v50M -y "%%~F.rar" "%%~F\"
    rd "%%~F"
)

So the result is

*

*C:\Users\Admin\Folder
Folder1.rar
Folder2.rar
Folder3.rar

The folder can contain even more files after archiving and deletion of the folders depending on size of all files of the folders and how much 50 MB volumes are necessary to archive each folder.
The folder name Folder1 is not included in file Folder1.rar because of the backslash in last parameter "%%~F\" at end of third line.
The batch file can be even easier if folder name Folder1 should be also included in the archive file Folder1.rar
@echo off
for /D %%F in ("C:\Users\Admin\Folder\*") do (
    "%ProgramFiles%\WinRAR\Rar.exe" m -cfg- -ep1 -inul -m5 -mt5 -r -tl -v50M -y "%%~F.rar" "%%~F"
)

I don't think that copying each folder to a temporary folder just for archiving is necessary here.


text:
Q: How to remove the border line for the header in the expander control in silverlight 3? Please suggest a right answer

A: Edit the style for the header or edit a copy of the control template. Go research keywords: "style" and "control template".

A: Right-click the control in Expression Blend.  Click "Edit template" and then click "Edit Copy".
Give the "Style Resource" a name.
Under "Objects and Timeline", select the header and make changes to its style.

A: AS said above when code is generated then replace StrokeThickness="1" by StrokeThickness="0"
you will get the line removed
< Rectangle x:Name="FocusVisualElement" Stroke="#FF448DCA" StrokeThickness="0" IsHitTestVisible="false" Visibility="Collapsed" />


text:
Q: Can i trigger any actions via Exchange web services notifications or smth else? Exchange 2010.
I've read about notification subscriptions, mailbox events, and EWS in Exchange and as i got it, the notiified client app have to stay connected to EWS all the time. Am i right?
My task looks easy - i need to trigger some action (web call most likely) when message arrives to mailbox.  Is there anything for such task in EWS 2010? Is there  anything like this in latest versions of Exchange Server on-prem?
For now I'm starting to think about forwarding email via trasnport rules to some unix-mta for further processing.

A: Yes that's correct EWS notifications require that the client application that receives the notifications stay connected if your using Stream notifications. Pull notification don't and push notifications don't but the client does need to be available to receive the heartbeat messages and then update the subscription.
There is nothing new in the later OnPrem version of Exchange there are web-hooks in Exchange Online in the Graph API


text:
Q: Initialization issue in java.util.Map to LinkedHashMap? I had found a weird problem in Android code, that my buddy developer is working with. When we tried to initialize a Map object as a LinkedHashMap, it showed some kinda error. Our first attempt was
Map postRequestMap = new LinkedHashMap<>();
I thought maybe it's due to some JDK version issue and changed to
Map postRequestMap = new LinkedHashMap();
but both the attempts was futile. So I was forced to changed it to
LinkedHashMap postRequestMap = new LinkedHashMap();
 I checked the same in my machine, having JDK 1.8 update 20, and the code was just working fine. Could anybody help me to figure out this issue,  please ?


text:
Q: Method stops after open a new session with Facebook on Android I'm trying to post a photo from my android app to facebook wall, it works but I need to use the post button twice, the first authorization is for login, and the second one is to authorize my app.
I don't know why after asking for a new session, i.e Session.openActiveSession(this, true, callback);, the rest of my method kind of stops running, so after I call the method again, it now asks for app permission and post
Below is the part that is concerned:
Call this when I hit the post button performPublish(PendingAction.POST_PHOTO, false);
private void performPublish(PendingAction action, boolean allowNoSession) {

    // check for log in first
    if (Session.getActiveSession() == null || Session.getActiveSession().isClosed()) {
        Session.openActiveSession(this, true, callback);
    }
        // the method stops here
    Session session = Session.getActiveSession();
    if (session != null) {
        pendingAction = action;
        if (hasPublishPermission()) {
            // We can do the action right away.
            handlePendingAction();
            return;
        } else if (session.isOpened()) {
            // We need to get new permissions, then complete the action when we get called back.
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "publish_actions"));
            return;
        }
    }

    if (allowNoSession) {
        pendingAction = action;
        handlePendingAction();
    }
}

These are the rest but they don't matter to this issue
   @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
            case POST_PHOTO:
                postPhoto();
                break;
        }
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

private void postPhoto() {
     if (hasPublishPermission()) {

    //if (Session.getActiveSession().getPermissions().contains("publish_actions") && (Session.getActiveSession() != null || Session.getActiveSession().isOpened()))
            showLoading();
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), myBm, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    hideLoading();
                    showPublishResult("photo_post", response.getGraphObject(), response.getError());
                    //Toast.makeText(getApplicationContext(), "Photo successfully uploaded to Facebook.", Toast.LENGTH_SHORT).show();
                }
            });
            Bundle parameters = request.getParameters();

            // photo's description
            if (moment.name != null)
                parameters.putString("message",moment.name);

            request.setParameters(parameters);
            request.executeAsync();

        }
        else {
            pendingAction = PendingAction.POST_PHOTO;
        }
}

A: The rest of your method stops running after you call openActiveSession because opening a session is asynchronous. So right after your call to openActiveSession, the session is NOT open. It starts another activity (LoginActivity) which prompts the user, etc, and then the answer comes back via the onActivityResult method.
If you want to handle it in a single click, you should add some code in your status callback, and check if there's a pending publish, and if so, do the publish at that point.
The HelloFacebook sample app that ships with the SDK demonstrates how to do this.


text:
Q: Undocumented '-c' option for Bash's 'declare'? I was playing around with Bash variables and mistakenly used the -c option (for const) to declare instead of the correct -r option to create a readonly variable.  To my surprise, the variable retained the -c attribute and capitalized the first letter of whatever value I assigned.
This behavior is not listed in declare's usage, either within the declare --help output or on Bash's info page.  It seems to be incompatible with ksh's typeset, though the -u and -l options are compatible.
Is this a well-known undocumented feature?  Is it generally available?

A: declare -c, -l, and -u appear to have been added all together in bash 4.0 (introduced in 4.0-rc1), as long as the --enable-casemod-attributes configure flag isn't disabled (it's enabled by default). There are tests for them (in tests/casemod.tests). Why -c was never documented is a mystery.


text:
Q: How to make sure that threads spawned by a Windows Service Timer complete executing after stopping the Windows Service? I'm building a Windows Service using System.Timers.Timer. The tasks computed by the Timer's delegate can take from several seconds to several minutes. I would like to make sure that, when the service is stopped, all delegated threads currently running complete before being disposed.
Here is the code, however it does not do what I expect, as currently running threads never complete if the Windows Service is stopped while they are running.
public abstract class AgentServiceBase : ServiceBase
{
    private System.ComponentModel.IContainer components = null;
    private System.Timers.Timer _Timer;
    private string _logPath;
    private const int MAXNUMBEROFTHREADS = 10;
    protected int interval = 25000;
    protected int numberOfAllowedThreads = 2;

    public AgentServiceBase()
    {
        this.InitializeComponent();
        this._logPath = (Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).CodeBase)).Substring(6).Replace("/", @"\");
    }

    protected override void OnStart(string[] args)
    {
        if (args.Length > 0)
        {
            int.TryParse(args[0], out interval);
        }

        if (args.Length > 1)
        {
            int.TryParse(args[1], out numberOfAllowedThreads);
            if (numberOfAllowedThreads > MAXNUMBEROFTHREADS)
            {
                numberOfAllowedThreads = MAXNUMBEROFTHREADS;
            }
            if (numberOfAllowedThreads == 1)
            {
                numberOfAllowedThreads = 2;
            }
        }

        ThreadPool.SetMaxThreads(numberOfAllowedThreads, numberOfAllowedThreads);

        this._Timer = new System.Timers.Timer();
        this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper);
        this._Timer.Interval = this.interval;
        this._Timer.Enabled = true;

    }

    protected override void OnStop()
    {
        this._Timer.Enabled = false;

        Process currentProcess = Process.GetCurrentProcess();

        foreach (Thread t in currentProcess.Threads)
        {
            t.Join();
        }

    }
    /// <summary>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
        this.ServiceName = "Agent Service - Johnhenry";

    }

    private void PollWrapper(object sender, ElapsedEventArgs e)
    {
        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            string message = this.GetType().FullName + "  - Windows Service Exception\n";
            message += exception.GetNestedExceptionInSingleStringOutput();

            FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
        }
    }

    protected abstract void Poll(object sender, ElapsedEventArgs e);
}

Many thanks,
Giuseppe
UPDATE:
After few different attempts with counting the current process's own threads I eventually settled with a simpler solution which is using a counter of the threads the timer had initiated and are still running. Based on that I call the Sleep on the main thread and issue a RequestAdditionalTime until all threads have ended.
Following the revised 2 methods:
    protected override void OnStop()
    {
        this._Timer.Enabled = false;

        while (numberOfRunningThreads > 0)
        {
            this.RequestAdditionalTime(1000);
            Thread.Sleep(1000);
        }

    }

    private void PollWrapper(object sender, ElapsedEventArgs e)
    {
        numberOfRunningThreads++;

        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            string message = this.GetType().FullName + "  - Windows Service Exception\n";
            message += exception.GetNestedExceptionInSingleStringOutput();

            FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
        }
        finally
        {
            numberOfRunningThreads--;
        }
    }

A: You can achieve that by calling RequestAdditionalTime as long as your threads haven't finished the work yet in your implementation of OnStop inside the loop (before and/or after the call to Join()).
BUT BEWARE that Windows can get impatient and decide to kill your Windows Service - for example during shutdown...
For more information see the MSDN reference at http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx


text:
Q: How to Upload AudioBuffer to google cloud storage without losing header info Hello I have been trying to solve this problem for more than a month and no progress.
I am trying record some audio in the browser and then upload the audio into google cloud storage. Those all works fine, I can record audio and play it in google cloud storage. however no matter what I did when I download the file I found out the RIFF header have been lost.
For example
    'Expected "RIFF" string at 0',
    'Expected "WAVE" string at 4',
    'Expected "fmt " string at 8',
    'Unknown format: 16904',
    'chunk_size does not match file size'

The way I store my recorded audio is blob. My frontend is React and backend is Nodejs. So what I did is to send the blob to the backend. Like below. And calling readfile to read the data into buffer
router.post("/audio", upload.any(), async (req, res) => {
const { Storage } = require("@google-cloud/storage");
  const storage = new Storage();
  const audioBucket = storage.bucket("xxxxxx");
  const file = audioBucket.file("audio.wav");

  fs.readFile(req.files[0].path, null, (err, data) => {

    file.save(data, function (err) {
      file.get().then(function (data1) {
        console.log(data1);
      });
    });
}

A: According to the official documentation there are several way to make upload request to GCP:

*

*Single-request upload: For small files.

*Resumable upload: For reliable transfers which are used for large files.

*XML API multipart upload: Upload method that is compatible with Amazon S3.

I suggest you to use the client library of Node.js to upload your audio. You can do that by using the createWriteStream() method. Here is the example provided by the documentation on how to use this method:
const fs = require('fs');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
//
Uploading a File

//
// Now, consider a case where we want to upload a file to your bucket. You
// have the option of using Bucket#upload, but that is just
// a convenience method which will do the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream())
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
//
Uploading a File with gzip compression

//-
fs.createReadStream('/Users/stephen/site/index.html')
  .pipe(file.createWriteStream({ gzip: true }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
// Downloading the file with `createReadStream` will automatically decode
// the file.
//-

//-
//
Uploading a File with Metadata

//
// One last case you may run into is when you want to upload a file to your
// bucket and set its metadata at the same time. Like above, you can use
// Bucket#upload to do this, which is just a wrapper around
// the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream({
    metadata: {
      contentType: 'image/jpeg',
      metadata: {
        custom: 'metadata'
      }
    }
  }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });


text:
Q: how does the server handles if the client goes down in udp client/server application I wanted two functionalities to be implemented on my udp server application.

*

*Creating thread that continuously receives data coming from any client.

*Creating a thread that continuously sends data on server socket after specific time period and waits for reply from client (handshake mechanism). (I implemented this to make aure that whenever any client goes down, the client does not send back the data and server comes to know that client is down.)
I have created two Sokets on Server side for this purpose.
First Socket is bind()ed to INADDR_ANY.
Second Socket is bind()ed to my Machines IP Address.
All sends and receives from client are done on first socket.
The Handshake mechanism to ensure that the client has not gone down is done on the second socket.
Is this approach correct?
Please do let me know, so that I may proceed with my work.
Thank you in advance.

A: I mean, your solution will work, but I don't see a reason why you can't use slightly more in-band control mechanisms.  Try this, with only one socket on the server:
List connections contains pairs (client, lastPacketTime)
Socket is a single UDP Socket

Thread 1 Loop:
    Get new UDP Datagram P From Socket
    If P.client in List:
        update lastPacketTime
    Else:
        add P.client to list
    If P is not Ping datagram:
        Do other operations on P

Thread 2 Loop:
    For client in List with lastPacket time 3-10 Seconds ago:
        send ping request via Socket
    For client in List with lastPacket time > 10 Seconds ago:
        Mark client as down.
    Sleep for some time

And this on the client:
Loop:
    If I have data to send:
        Send it!
    Else if I have a ping request in my UDP Socket:
        Send Ping datagram
    Else
        Sleep for some time.

If you need a more reliable handshake than that, you might consider just opening a TCP connection to the Server alongside the UDP stuff.  Then the server can use the TCP connection to check liveness.  I have to be honest, the hair on the back of my neck stands up when people try to do connection oriented UDP.  If you're worried about all the processing and updating of ping times, you can add a third thread:
List contains pairs (client, lastPacketTime)
Queue contains Datagrams with time updates.
Socket is a single UDP Socket

Thread 1 Loop:
    Get new UDP Datagram P from Socket
    Add P to Queue
    If P is not Ping datagram:
        Do other operations on P

Thread 2 Loop:
    Get new Datagram P from Queue
    If P.client in List:
        update lastPacketTime
    Else:
        add P.client to list

Thread 3 Loop:
    For client in List with lastPacket time 3-10 Seconds ago:
        send ping request via Socket
    For client in List with lastPacket time > 10 Seconds ago:
        Mark client as down.
    Sleep for some time


text:
Q: Have files with querystring included in their name. Need nginx to ignore querystring for the content header Have a directory with lots of files. These are all static files from backups.
The issue is that some files that are named like the following:
mystyle.css?version=3.3.1

When serving the files, nginx is not detecting the file is a css, and thus doesn't send the Content-Type: text/css header and it is giving me some trouble. It is very troublesome to rename the files, since it would require renaming a ton of files, while also renaming them inside of html, javascript, etc. Could it be possible to assist nginx into ignoring the ? and the rest of the query string and only check mystyle.css for the determination of the kind of mimetype to serve?
This is particularly troublesome for things like SVG images, since the browsers don't detect them as such unless you serve them as image/svg+xml,
but this also causes trouble in other situations.

A: Nginx looks at the final filename and concludes that the extension is css?version=3.3.1. It looks this up in the types block and finds no match, so the value of the default_type is used instead.
If you have all CSS type files under one folder and all SVG type files under another - or if the URI path for different types is unique, you can set the mime-type for all files within a particular location:
location /css {
    types { }
    default_type text/css;
}

From the first line of your question, you indicate that there is one directory with lots of files, presumably with different mime-types.
You can use a map directive with a regular expression to identify the mime-type of the files. You will need to add a line for every type of file contained in the directory. My example contains just a few. The file /etc/nginx/mime.types contains the types Nginx is usually configured to recognise, but you will only need to add the types of files you currently archive to this directory.
map $request_uri $type {
    default         application/octet-stream;
    ~*\.css         text/css;
    ~*\.js          application/javascript;
}

server {
    ...
    location /some/path {
        default_type "";
        types { }
        add_header Content-Type $type;
    }
}

DISCLAIMER: This is probably a hack, but appears to work.
Setting the default_path to an empty string together with an empty types block, prevents Nginx from adding its own Content-Type header.
See this document for details of the map directive.


text:
Q: When I upload music track into raw folder in android studio it is showing an error

I am getting an error like this as I mentioned in the above screenshot and like when I double click it or when I run the application it is showing an error like this.

A: *

*You cant play audio in android studio.

*make name to small letters and clean your project.

*now implement a player and set raw resource to play your audio


text:
Q: Pause and Resume SKScene I was testing my game on my iPhone and I realized that I have a problem with the home button. When I pause the game and load another app the game is not paused and continues when the app is not on screen.
Here's the code:
 class GameScene: SKScene, SKPhysicsContactDelegate{

 var PauseButton = SKSpriteNode(imageNamed: "pause")

 var Resume = SKSpriteNode(imageNamed: "resume1")
}

 init(size: CGSize, won: Bool) {
    super.init(size: size)
  //pause

    PauseButton.position = CGPointMake(330, 700)
    PauseButton.zPosition = 3;
    PauseButton.size = CGSizeMake(40, 40);
    PauseButton.name = "PauseButton"

    self.addChild(PauseButton)

   //resume
    Resume = SKSpriteNode(imageNamed: "resume1")
    Resume.position = CGPointMake(520, 450)
    Resume.zPosition = 100
    Resume.setScale(1.3)

    }

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */

    show = self.scene as SKScene!

    for touch in touches  {

        let Location:CGPoint = touch.locationInNode(self)
        let Node:SKNode = self.nodeAtPoint(Location)

        if(Node == PauseButton){

            self.show.paused = true

            PauseButton.removeFromParent()

            self.addChild(Resume)

        }

        if(Node == Resume){

            Resume.removeFromParent()
            self.show.paused = false

            self.addChild(PauseButton)
        }

How do I get the game to pause when I press the home button?

A: Pause the view not the scene.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    guard let view = view else {
        return
    }

    view.paused = !view.paused
}

A: SpriteKit will auto Resume when you comeback to your app. so you need :
Step 1 : create a variable :
var wasPaused : Bool = false

Step 2 : change it in your pause/resume function :
wasPaused = true // pause func
wasPaused = false // resume fun

Step 3 : in update fun of your scene:
override func update(currentTime: CFTimeInterval) {
    if isPausing{
        self.paused = true
        return
    }
}


text:
Q: ASP.NET mvc DropDownListFor pass type to controller How to pass SelectedItem from DropDownListFor to public ActionResult Index(IndexViewModel indexViewModel). After submit i have emp=null.
What i should place instead of "Number" in IndexViewModel.ListOfEmployee = new SelectList(ListOfEmployee, "Number", "Name");
Controller:
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        List<Employee> ListOfEmployee = new List<Employee>();
        ListOfEmployee.Add(new Employee { Name = "Jhon", Number = 1 });
        IndexViewModel IndexViewModel = new IndexViewModel();
        IndexViewModel.ListOfEmployee = new SelectList(ListOfEmployee, "Number", "Name");

        return View(IndexViewModel);
    }
    [HttpPost]
    public ActionResult Index(IndexViewModel indexViewModel)
    {
        return View();
    }

}

View:
@model MvcApplication3.Models.IndexViewModel
@{
    ViewBag.Title = "Index";
}

Index

@using(@Html.BeginForm())
{
@Html.DropDownListFor(model=>model.emp ,Model.ListOfEmployee)

    <input type="submit" />
}

Model:
public class IndexViewModel
{
    public SelectList ListOfEmployee { get; set; }

    public Employee emp { get; set; }
}

A: You should keep a simple value type property to store the selected dropdown option value.
public class IndexViewModel
{
    public SelectList ListOfEmployee { get; set; }
    public int SelectedEmployeeId { get; set; }
}

and in your view
@Html.DropDownListFor(x=>x.SelectedEmployeeId, Model.ListOfEmployee)

and in your HttpPost action, access this SelectedEmployeeId property which will give you the number corresponding to the selected name. If you want the complete employee object, you should query the db again with the number(id)
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    var selectedNumber= model.SelectedEmployeeId;
    return View();
}


text:
Q: Random forest on survival data I should make prediction on survival data, using the random Forest method. My question is: should I follow the same approach as in logistic regression? taking into account only the status variable or whether I should take into account the delay to the event?  Are there any specific R functions for survival analysis other than randomForest? Or could I use this function for survival analysis as well? I've seen a function called ranger() that seems to do random forest on survival data, but I haven't understood much of it.

A: The phrase "survival analysis" is usually taken to involve time-to-event data, not just event outcomes at a certain time. Otherwise, you're just throwing away potentially important time-to-event data. Also, survival analysis is well equipped to handle censored event times, for example individuals who still haven't experienced the event by the end of data collection. Depending on the study design, that might not be handled well by logistic regression.
If you have time-to-event data, use proper survival analysis. The CRAN survival task view points out some implementations of random-forest survival analysis.