text:
Q: Show the suffixIcon after the suffixText in a textField I just wanted to show the suffixIcon after the suffixText.
Now I know that in the InputDecoration documentation says explicitly that it will show the suffixText before the suffixIcon.
What would I like to do is:

the '*' represents that it's a mandatory field.
And I'm getting this :

is there a way for me to change the order of the suffixes in my TextField?
I tried using SizedBox, or Container widgets but never got the result I wanted.

A: You can use suffix (edit: suffixIcon) property and pass in a Row widget instead. Put both elements in the Row, and you can decide exactly how you want them to appear. For example:

Soure code:
TextField(
  decoration: InputDecoration(
    suffixIcon: Row(
      mainAxisSize: MainAxisSize.min, // <-- important
      children: const [
        Icon(Icons.visibility, color: Colors.grey),
        SizedBox(width: 4), // add a small gap
        Text('*'), // second element
      ],
    ),
  ),
)

A: Try below code, use Row() widget for suffixIcon
TextField(
      decoration: InputDecoration(
        suffix: Row(
          mainAxisSize: MainAxisSize.min,
          children: const [
            Icon(
              Icons.visibility,
              color: Colors.green,
            ),
            SizedBox(width: 5),
            Text(
              '*',
              style: TextStyle(
                color: Colors.red,
              ),
            ),
          ],
        ),
      ),
    ),

Your result screen->

A: You can modify your suffixIcon property to:
suffixIcon: Center(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Icon(Icons.remove_red_eye),
                              Text(
                                "*",
                                style: TextStyle(color: Colors.red),
                              )
                            ],
                          ),
                        ),

The alignments here are important to maintain.


text:
Q: setting a path in cygwin im getting the error
        ImportError: No module named matplotlib

But I have it installed under python2.7 and can see the location.  Is there a way I can get cygwin to recognize it if I know the file location? When I ask "which matplotlib" it just tells me its not in a odd folder location chain like such
 $ which matplotlib
which: no matplotlib in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/NVIDIA Corporation/PhysX/Common:/cygdrive/c/Program Files (x86)/Silverfrost/FTN95:/cygdrive/c/Program Files/Common Files/Microsoft Shared/Windows Live:/cygdrive/c/Program Files (x86)/Common Files/Microsoft Shared/Windows Live:/cygdrive/c/windows/system32:/cygdrive/c/windows:/cygdrive/c/windows/System32/Wbem:/cygdrive/c/windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files/WIDCOMM/Bluetooth Software:/cygdrive/c/Program Files/WIDCOMM/Bluetooth Software/syswow64:/cygdrive/c/Program Files (x86)/Pinnacle/Shared Files:/cygdrive/c/Program Files (x86)/Pinnacle/Shared Files/Filter:/cygdrive/c/Program Files (x86)/Windows Live/Shared:/cygdrive/c/Program Files (x86)/QuickTime/QTSystem:%CYGWIN_HOME%/bin:%CYGWIN_HOME%/sbin:%CYGWIN_HOME%/usr/bin:%CYGWIN_HOME%/usr/sbin:%CYGWIN_HOME%/usr/local/bin:%CYGWIN_HOME%/usr/local/sbin:/cygdrive/c/Anaconda:/cygdrive/c/Anaconda/Scripts:/usr/lib/python2.7/user/scripts:/usr/lib/python2.7/User:/usr/lib/python2.7/User/Scripts:/usr/lib/lapack:/usr/openwin/bin:/cygdrive/c/python27:/cygdrive/c/Anaconda:/cygdrive/c/Anaconda/python:/c/Anaconda:/cygdrive/Anaconda:/cygdrive/c/Anaconda:/cygdrive/c/Anaconda:/cygdrive/c/Anaconda/Python27:/cygdrive/c/Python27:/cygdrive/c/Python27)

(There are several mentions of Anaconda but that I believe is remnants of trying to place it within Cygwin when I was messing around one day)
Thanks for the help.

A: Try
import sys
a="your path to python/lib/site-packages"
sys.path.append(a)

Then you should be able to do import matplotlib from cygwin

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comunicação/Autenticação .net para PHP Preciso de implementar um sistema de autenticação numa página.
O cenário é o seguinte, tenho uma página que só pode ser acedida por utilizadores autenticados que vêm  de um site (em ASP). Isto do lado do cliente.
Pensei num cenário em que do meu lado existisse um mecanismo (em PHP) que validasse se o cliente estava/vinha autenticado ou não... Pensei em enviar uma chave encriptada do lado do cliente e que o PHP ao validar essa chave permitisse o acesso aos conteúdos, contudo não sei como o fazer em .net, uma vez que o que o cliente tem é um CMS.
Alguém tem uma ideia de como me ajudar?

A: Na aplicação em .Net, crie um botão, por exemplo, onde o usuário clicará para aceder a aplicação em PHP no outro servidor.
Ao clicar nesse botão, é gerado um token (chave criptografada única).
O token servirá como autenticação. A lógica é gerar o toke pelo app .Net e salvá-lo num banco de dados.
Esse token deve estar relacionado com a identificação do usuário na aplicação em PHP. Portanto precisa resolver um meio de criar essa relação.
Um modo simples é uma tela no .Net com um formulário onde o usuário insere os dados de login e senha para acesso a aplicação PHP. Esses dados ficariam salvos no banco de dados do app .Net para então poder relacionar com os tokens.
Uma feita a estrutura, continuamos. Ao clicar no botão, é gerado o token e o usuário é direcionado para o app PHP.
O app PHP recebe o token e verifica se é válido, consultando o banco de dados de onde foi salvo previamente. Para essa consulta, recomenda-se uma API (webservice). Evite fazer uma consulta diretamente ao banco de dados. Consulte por uma API.
Após verificar se o token é válido, caso seja válido, buscará a relação com o usuário e fará a então a autenticação no app PHP.
Importante: O token deve ser excluído ou invalidado sempre que for utilizado. O token só pode ser usado uma vez.

Note que isso tudo é independente das linguagens que utiliza de ambos os lados. O app .net poderia ser um app JAVA e o app PHP poderia ser um app RoR. A lógica do token de autenticação é a mesma.


text:
Q: JavaScript confirm on blur/focusout event caught in endless loop on some OS's I have this jsfiddle of a JavaScript confirm box. Here's the snippet as well:

$('#txtTestOne, #txtTestTwo').on('blur', function(e) {
  var retval = confirm('Do you really want to go there?');
  if (!retval) {
    e.target.focus();
  } else {
    e.relatedTarget.focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="txtTestOne" autofocus>
<input type="text" id="txtTestTwo">

This works fine on my laptop (OS X 10.6.8), tested in both Chrome and Opera. However, when I test it on my desktop machine running OS X 10.11.6, I find that the confirm box gets caught in an endless loop, both in Chrome and Safari (keeps re-displaying the window after making a selection).
I added the snippet in as well, to make sure that it wasn't a problem with jsfiddle, and no, it isn't. Same behavior both for the snippet and jsfiddle.
Since the problem exists in two different browsers on one OS, and doesn't in two browsers on another, it seems unlikely that it's a browser issue. I don't think I'm doing anything wrong with the code, either, but one never knows until one knows.
Am I doing something wrong, or is there some sort of problem with the confirm method that I don't know about? Also, if it runs correctly on your machine, perhaps you'll be so kind as to mention in the comments what OS you're running.

A: It seems I have found a solution. If you have a clearer picture than I do of why we have to do this, please explain.

$('#txtTestOne, #txtTestTwo').on('blur', function(e) {
  if (!$(e.relatedTarget).is(':text')) {
    return;
  }

  var retval = confirm('Do you really want to go there?');
  if (!retval) {
    e.target.focus();
  } else {
    e.relatedTarget.focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="txtTestOne" autofocus>
<input type="text" id="txtTestTwo">

A: Here you go buddy I fixed it. I also had an infinity loop problem using Chrome, but this should now work as you expected in all browsers I hope

$('.input').on('click', function(e) {
  count++;
  var retval = confirm('Do you really want to go there?');
  if (!retval) {
    $('.input').not(e.target).focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtTestOne" class="input" autofocus>
<input type="text" id="txtTestTwo" class="input">

Nope sry, blur with focus didn't work, didn't tested it properly


text:
Q: How do I make a list of all links on a web page (DownThemAll!)? How can I download the links (not the content in the pages that the links point to, just the links themselves.  I'm trying to give a list of about 300 videos to my network admin to unblock, he just wants the URLs.

A: In PHP:
<?php

$webpagehtml=file_get_contents("http://www.example.com");

$dom=new DOMDocument();
$dom->loadHTML($webpagehtml);

$xpath=new DOMXPath($dom);
$items = $xpath->query("//a");

$links=array();

for ($i = 0;  $i < $items->length; $i++ ) {
$item = $items->item($i);
$title=$item->textContent;
$href=$item->getAttribute('href');

if($href && $title){
echo "$href = $title<br/>";
}
}
?>

In Python, use http://arshaw.com/scrapemark/docs/examples/.
Or you can use downthemall in firefox to do the dirty work.

A: When I want to see the links on a webpage, I grab an old copy of Avant browser (ver 10) out of my archives and install it. Run the webpage you want. Right-click on the page and select "Open All Links in This page." You can't cut-and-paste them.


text:
Q: Set style for connector and endpoints on hover I'm trying to create a css style for all connections and endpoints which are connected to a specific element. I have managed to color all source/targets but I'm not managing to color the connections (lines)
Here is my current code...
var endpoints = jsPlumb.getEndpoints(this);

for (var i = 0; i < endpoints.length; i++) {
if (endpoints[i].connections[0] != null) {
    $(endpoints[i].connections[0].target).addClass('red_color');
    $(endpoints[i].connections[0].source).addClass('red_color');
}

}

A: The connection class also has an addClass method. So you could call
endpoints[i].connections[0].addClass('red_color')

and then, as discussed at https://docs.jsplumbtoolkit.com/community/lib/styling-via-css#css-for-svg-elements, you can target the connector path like this:
svg.red_color path {
  stroke:red;
  stroke-width:3;
}


text:
Q: Warnings when initialising map using std::uint8_t as key Problem
I am trying to create a map of std::uint8_t ->  char, and initialise it with some values:
const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { 0x12, 'b' },
    { 0x13, 'c' },
    { 0x15, 'a' },
    { 0x16, 'f' },
    ...
}

This generates a compiler warning because these integer literals (0x12, etc.) are recognised as unsigned ints, which are larger than a std::uint8_t:
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\utility(172): warning C4244: 'initializing': conversion from '_Ty' to '_Ty1', possible loss of data
1>        with
1>        [
1>            _Ty=unsigned int
1>        ]
1>        and
1>        [
1>            _Ty1=uint8_t
1>        ]
1>d:\my-project\src\myfile.cpp(75): note: see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<unsigned int,char,0>(_Other1 &&,_Other2 &&) noexcept' being compiled
1>        with
1>        [
1>            _Kty=uint8_t,
1>            _Ty=char,
1>            _Other1=unsigned int,
1>            _Other2=char
1>        ]
1>d:\my-project\src\myfile.cpp(12): note: see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<unsigned int,char,0>(_Other1 &&,_Other2 &&) noexcept' being compiled
1>        with
1>        [
1>            _Kty=uint8_t,
1>            _Ty=char,
1>            _Other1=unsigned int,
1>            _Other2=char
1>        ]

Solutions
I am aware of 2 possible ways to fix this:
1) Disable warnings for this section
#pragma warning( push )
#pragma warning( disable : 4244 )
const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { 0x12, 'b' },
    { 0x13, 'c' },
    { 0x15, 'a' },
    { 0x16, 'f' },
    ...
}
#pragma warning( pop)

2) Cast every key explicitly
const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { static_cast<std::uint8_t>(0x12), 'b' },
    { static_cast<std::uint8_t>(0x13), 'c' },
    { static_cast<std::uint8_t>(0x15), 'a' },
    { static_cast<std::uint8_t>(0x16), 'f' },
    ...
}

I am not particularly happy about either approach, but the second is especially ugly to me.
Am I, perhaps, missing a simpler solution?

A: An integer literal can never be an std::uint8_t. Instead of using a static_cast, you can make an explicit cast of the literal:
const std::map<std::uint8_t, char> alphabet = {
    { std::uint8_t(0x12), 'b' },
    { std::uint8_t(0x13), 'c' },
    { std::uint8_t(0x15), 'a' },
    { std::uint8_t(0x16), 'f' },
};

A: You can write a user-define literal
#include <cstdint>

constexpr std::uint8_t operator "" _ui8(unsigned long long value)
{
    return static_cast<std::uint8_t>(value);
}

#include <type_traits>

int main() {
    static_assert(std::is_same_v<decltype(0x12_ui8), std::uint8_t>);
}

A: The warning is an erroneous one and it happens only on \W4 warning level.
A conversion from a literal to std::uint8_t should not generate any warnings, unless the literal is out of range of the converted to type, which is not the case here.
Any option you choose is OK in my opinion. It just boils down to a matter of personal preference. I personally would prefer the std::uint8_t{0x12} syntax.
Another option would be to go down one warning level to \W3 and then use a separate linter (\W4 is mostly used for lint-like warnings anyway).


text:
Q: how to generate list of products from elements of a pair of lists in mathematica Is there a pre-canned operation that would take two lists, say
a = { 1, 2, 3 }
b = { 2, 4, 8 }

and produce, without using a for loop, a new list where corresponding elements in each pair of lists have been multiplied
{ a[1] b[1], a[2] b[2], a[3] b[3] }

I was thinking there probably exists something like Inner[Times, a, b, Plus], but returns a list instead of a sum.

A: You can do this using Inner by using List as the last argument:
In[5]:= Inner[Times, a, b, List]

Out[5]= {2, 8, 24}

but as others already mentioned, Times works automatically.   In general for things like Inner, it's frequently useful to test things with "dummy" functions to see what the structure is:
In[7]:= Inner[f, a, b, g]

Out[7]= g[f[1, 2], f[2, 4], f[3, 8]]

and then work backwards from that to determine what the actual functions should be to give the desired result.

A: a = {1, 2, 3}
b = {2, 4, 8}

Thread[Times[a, b]]

Or, since Times[] threads element-wise over lists, simply:
a b

Please note that the efficiency of the two solutions is not the same:
i = RandomInteger[ 10, {5 10^7} ];
{First[ Timing [i i]], First[ Timing[ Thread[ Times [i,i]]]]}

(*
-> {0.422, 1.235}
*)

Edit
The behavior of Times[] is due to the Listable attribute. Look at this:
SetAttributes[f,Listable];
f[{1,2,3},{3,4,5}]
(*
-> {f[1,3],f[2,4],f[3,5]}
*)


text:
Q: How to configure a router in angular test case In my angular 4 app, I am writing a test case for a method which navigates to a different route.
In my test case I am importing RouterTestingModule.withRoutes and passing the route.
const testRoutes: Routes = [ { path: 'sampleApp', component: SampleComponent}];
 imports: [RouterTestingModule.withRoutes(testRoutes)]

This doesn't seem to work I still get the error,
angular jasmine  ERROR: 'Unhandled Promise rejection:', 'Cannot match any routes. URL Segment ...
How can I resolve this.


text:
Q: Add single quotation mark I create a query using this code
    For i As Integer = 0 To myMetaColumnInformation.result.Count - 1
        query.Append("[")
        query.Append(myMetaColumnInformation.result(i).questionCode.ToString)

        query.Append("] ")
        query.Append(typeList(i))
        query.Append("""")

        query.Append(", ")
    Next

My problem is that query.Append("""") creates two quotation marks but I just need one. If I reduce the command to query.Append(""") the code does not run through. Every hint I can get is about adding two quotation marks but not for one. I also tried \" but this does not help as well. Anyone who can help me get this done?


text:
Q: how to display text encoded in ISO-8859 on android device I need to display the content from a url in a text view. The content of this url is just plain text (no metadata) in a non-english language. I am reading the content using InputStreamReader with UTF-8 encoding,
URL url = new URL(url);
URLConnection urlConnection = url.openConnection();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream(), "Charset.forName(UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    sb.append(line);
}
return sb.toString();

The text display code :
textView.setText(text);

But the text appeared all garbled, I googled and finally guessed the text is in ISO-8859_1, so I changed the encoding in the InputStreamReader to ISO-8859_1, but the text still looked garbled.
I googled and finally found that modifying the textView code actually works
textView.setText(new String(text.getBytes("ISO-8859-1"), "UTF-8"));

My question is, 1. why changing the charset in inputStreamReader did not work?
Also, 2. I do not understand why the text view change worked. The text was read in UTF-8 format, so why are we converting the text into bytes using ISO-8859 and then encoding it again in UTF-8?
Can somebody shed some light on it? Or may be some text that I can read to understand what is happening.

A: The InputStreamReader reads bytes from the underlying InputStream and tries to decode them using the charset that you provided. What seems to be your issue is that the InputStream itself is encoded in UTF-8, which results from the server and your HTTP client agreeing to use it.
So, if you have an ISO-8859-1 string and you sent through this channel then its bytes will be encoded (again) as UTF-8, resulting in the actual message being doubly encoded.
bytes = encode(encode("ISO-8859-1", "string"), "UTF-8");

In order to decode the string, you must first undo the UTF-8 encoding (via new InputStreamReader(urlConnection.getInputStream(), Charset.forName("UTF-8")) and then undo the ISO-8859-1 encoding too via new String(text.getBytes("ISO-8859-1"), "UTF-8").
You can probably see that the last step would not be necessary if the original content was already provided in UTF-8, so if you also have access to the server code, you should make it return the data in UTF-8 to avoid the unnecessary work on the client.


text:
Q: Android Warning : Grows due to localized text expansion I am getting this type of warning

@id/order_row_date can overlap @id/order_row_amout if
@id/order_row_date grows due to localized text expansion.
If relative layout has text or button items aligned to left
and right sides they can overlap each other due to localized text
expansion unless they have mutual constraints like toEndOf/toStartOf.

My XML File is:
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/order_row_lower_layout"
        android:layout_below="@+id/order_row_upper_layout"
        android:layout_toEndOf="@+id/order_row_box_layout"
        android:layout_toRightOf="@+id/order_row_box_layout"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/order_row_amout"
            style="@style/TextAppearance.AppCompat.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/spacing_normal"
            android:layout_marginRight="@dimen/spacing_normal"
            android:textColor="@color/color_gray"
            android:textStyle="bold"
            android:text="50000"
            tools:text="@string/string_amout_with_ruppe" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/order_row_date"
            style="@style/TextAppearance.AppCompat.Subhead"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:textColor="@color/color_gray"
            tools:text="08/09/2016" />

</RelativeLayout>

Anyone Know about this type of warning?
Appreciated in Advance :)

A: I have just changed width of first AppCompatTextView with match_parent and added following two lines:
android:layout_toLeftOf="@+id/order_row_date"
android:layout_toStartOf="@+id/order_row_date"

So Final XML:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/order_row_lower_layout"
    android:layout_below="@+id/order_row_upper_layout"
    android:layout_toEndOf="@+id/order_row_box_layout"
    android:layout_toRightOf="@+id/order_row_box_layout"
    android:orientation="horizontal">

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/order_row_amout"
        style="@style/TextAppearance.AppCompat.Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/spacing_normal"
        android:layout_marginRight="@dimen/spacing_normal"
        android:layout_toLeftOf="@+id/order_row_date"
        android:layout_toStartOf="@+id/order_row_date"
        android:textColor="@color/color_gray"
        android:textStyle="bold"
        android:text="50000"
        tools:text="@string/string_amout_with_ruppe" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/order_row_date"
        style="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:textColor="@color/color_gray"
        tools:text="08/09/2016" />

</RelativeLayout>

Problem Solved in few Mins and It's very easy to understand.
May be helpful to others.

A: I used constraint layout to solve this issue. With 0dp for both widths and applying margin as per requirements, Setting proper constraints, This issue won't aris at all.
BTW I got this issue while I was modifying someone's code after a long time.


text:
Q: Check if directory has already been processed by cmake I need to invoke get_directory_properties on a given directory. However the given directory may be a directory that cmake has not processed (yet) in which case aforementioned command returns an error:
CMake Error at CMakeLists.txt:111 (get_directory_property):
  get_directory_property DIRECTORY argument provided but requested directory
  not found.  This could be because the directory argument was invalid or, it
  is valid but has not been processed yet.

Therefore my idea is to verify that the given directory was indeed processed by cmake already (and thus I can safely invoke get_directory_properties on it) and if not I want to do something else.
I was however unable to find a way to check for that and I can't seem to find anything on that on the internet so far. Does anyone know how this could be done?


text:
Q: Convergence of a random "mix" Let $R_1,R_2,\dots$ and $S_1,S_2,\dots$ be two sequences of independent random variables with uniform distribution in the interval $[0,1]$.  We start from $X_0 = 1$ and $Y_0 = 0$ and generate at each step a new pair $X_i$ and $Y_i$ by the following "mixing" rule:
$$
\left\{\eqalignno{X_i &= R_iX_{i-1} + (1-R_i)Y_{i-1}\cr
                  Y_i &= S_iX_{i-1} + (1-S_i)Y_{i-1}}\right.
$$
From numerical experimentation I see that both $\{X_i\}$ and $\{Y_i \}$ converge almost certainly to some unique random variable $L$.  How can it be shown? And what is the distribution of $L$?

A: 1. The convergence part is easy. From the observation
$$ \min\{X_{i-1},Y_{i-1}\}
\leq \min\{X_{i},Y_{i}\}
\leq \max\{X_{i},Y_{i}\}
\leq \max\{X_{i-1},Y_{i-1}\}, $$
we find that both $(\min\{X_{i},Y_{i}\})_{i\in\mathbb{N}}$ and $(\max\{X_{i},Y_{i}\})_{i\in\mathbb{N}}$ converge. Also, note that
$$ |Y_i - X_i| = |R_i - S_i| |Y_{i-1} - X_{i-1}|. $$
Since $|R_i - S_i| \leq 1$ for all $i$ and $|R_i - S_i| \leq \frac{1}{2} $ for infinitely many $i$'s with probability one, we find that $|Y_i - X_i| \to 0
$ almost surely. This proves the existence of $L = \lim X_i = \lim Y_i$.
2. As for the distribution of $L$, we claim the following:

Claim. $L$ has the density function $f_{L}$ of the form
$$ f_{L}(x) = 6x(1-x). $$

The following is the comparison of $f_L$ and the proability histogram of $10^6$ samples from a simulation:

Proof. By regarding $(X_1, Y_1) = (R_1 - S_1)(1, 0) + S_1(1, 1)$ as our new starting point and apply the same procedure, we will end up with the limit having the same distribution as $L$. So we obtain an identity in distribution of the form
$$ L \stackrel{d}= (R - S)L + S, \tag{1} $$
where $R, S \sim \operatorname{Uniform}([0,1])$ and $R, S, L$ are independent. Moreover, since $(1-Y_i, 1-X_i)$ has the same distribution as $(X_i, Y_i)$ for all $i$, it follows that the distribution of $L$ is symmetric about $\frac{1}{2}$, i.e.,
$$ L \stackrel{d}= 1-L. \tag{2} $$
So we are led to solve the system of distributional equations given by $\text{(1)}$ and $\text{(2)}$.
Now, for any continuous function $\varphi$ on $[0, 1]$, the above equation gives
\begin{align*}
\mathbf{E}[\varphi(L)]
&= \mathbf{E}[\varphi(LR + (1-L)S)] \\
&= \mathbf{E}[\mathbf{E}[\mathbf{E}[\varphi(LR + (1-L)S) \mid L, R] \mid L]].
\end{align*}
By noting that $LR + (1-L)S$ is uniform over $[LR, 1-L + LR]$ given $L$ and $R$ and that $LR$ is uniform over $[0, L]$ given $L$ (or simply using a suitable change of variables), the last line reduces to
\begin{align*}
\mathbf{E}[\varphi(L)]
&= \mathbf{E}\left[ \int_{0}^{L} \int_{r}^{1-L+r} \frac{\varphi(s)}{L(1-L)} \, \mathrm{d}s\mathrm{d}r \right] \\
&= \mathbf{E}\left[ \int_{0}^{1} \int_{0}^{1} \frac{\varphi(s)}{L(1-L)} \mathbf{1}_{\{0 \leq r \leq L\}\cap\{r\leq s \leq 1-L+r\}} \, \mathrm{d}s\mathrm{d}r \right] \\
&= \int_{0}^{1} \mathbf{E} \left[ \frac{1}{L(1-L)} \int_{0}^{1}  \mathbf{1}_{\{0 \leq r \leq L\}\cap\{r\leq s \leq 1-L+r\}} \mathrm{d}r\, \right] \varphi(s) \, \mathrm{d}s \\
&= \int_{0}^{1} \mathbf{E} \left[ \frac{1}{L(1-L)} \left( \min\{L,s\} - \max\{0,s-1+L\} \right) \, \right] \varphi(s) \, \mathrm{d}s
\end{align*}
This shows that $L$ has a PDF $f_L$ that satisfies the following functional equation
$$ f_L(s)
= \int_{0}^{1} \frac{f_L(\ell)}{\ell(1-\ell)} \left( \min\{\ell,s\} - \max\{0,s-1+\ell\} \right) \, \mathrm{d}\ell. $$
To solve this, note that the right-hand side becomes
\begin{align*}
&\int_{0}^{1} \frac{f_L(\ell)}{\ell(1-\ell)} \int_{0}^{s} \left( \mathbf{1}_{[0,\ell]}(t) - \mathbf{1}_{[1-\ell,1]}(t) \right) \, \mathrm{d}t\mathrm{d}\ell \\
&= \int_{0}^{s} \left( \int_{t}^{1} \frac{f_L(\ell)}{\ell(1-\ell)} \, \mathrm{d}\ell  - \int_{1-t}^{1} \frac{f_L(\ell)}{\ell(1-\ell)} \, \mathrm{d}\ell\right) \, \mathrm{d}t.
\end{align*}
This shows that the regularity of $f_L$ bootstraps itself, proving that $f_L$ is indefinitely differentiable. So by differentiating both sides twice and using that $f_L(s) = f_L(1-s)$, we get
$$ f_L''(s) = -\frac{2f_L(s)}{s(1-s)}.$$
Solving this differential equation and using the conditions $f_L'(\frac{1}{2}) = 0$ and $\int_{0}^{1} f_L(s) \, \mathrm{d}s = 1$ proves the desired claim. $\square$

A: This is my attempt at answering my own question.  Let $m_i = \min(X_i, Y_i)$ and $M_i = \max(X_i, Y_i)$.  Then, at each step, with probability $1$ the following inequalities hold:
$$
\left\{\eqalignno{m_{i-1} < &X_i < M_{i-1}\cr m_{i-1}< &Y_i < M_{i-1}}\right.
$$
This implies that the distance $|X_i-Y_i|$ is almost surely monotonously decreasing and hence converges to some number $d$.  If I show that $d$ is $0$, then I've shown that both $\{X_i\}$ and $\{Y_i\}$ converge almost certainly to the same limit variable $L$. But I'm not sure how to proceed.
Regarding the second part, that is finding the distribution of the limit $L$, I also have no idea how to proceed.  Can you give me some hint?


text:
Q: How to determine exact date/time of Windows Update planned restart? When updates are pending, at login screen of Windows 8 there is a notification

Your PC will restart in 1 day to finish installing important updates.

Is there a way to determine exact date/time of planned restart?
Practical reason: Restart Friday 2:10 PM is different from restart Friday 7:30 PM because it can influence my planning of Friday's work. When restart comes during work hours, it can easily take 20 minutes until I return to the point where I left (opened apps, documents etc.).
EDIT: I don't think I'd like to disable automatic restarts at the moment. Generally I welcome them. Otherwise I won't restart until I meet the bluescreen :) but I don't want to go this way.

A: What you could do is schedule your Windows Updates for Everyday (or whatever day you choose) at say 3am then force an automatic reboot after Windows Updates by:

*

*Making sure Windows Update KB2822241 is installed (it should be already since it was released in 2013).

*Start Registry Editor (search regedit.exe)

*Locate the following registry subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU and right-click AlwaysAutoRebootAtScheduledTime then click Modify.

*If the entry does not exist, follow these steps to add it:
On the Edit menu, point to New, and click DWORD Value.
Type AlwaysAutoRebootAtScheduledTime in the Name field then press Enter.

*In the Value data box, type 1.

(Source: MSKB2835627: How to force automatic restarts after important updates in Windows 8 and Windows Server 2012)
http://www.thewindowsclub.com/force-automatic-restart-windows-update
Edit: If you really want to know what time it'll reboot, you could go to:

*

*Control Panel → System Security → Windows Update → View Update History

*Find the most recently installed update right click then select View Details.

It'll tell you when it completed it's update install. Since Windows automatically reboots in 3 days time, you can determine when it will restart by adding three days to the time. I.E. Windows Update finished at 6:33am on 10/15/14 then it should restart at 6:33am on 10/18/14.
Alternatively, you could also schedule a task in Task Scheduler for Windows Updates and schedule a force reboot after the scheduled Windows Updates runs.
Either way, it would be easier to schedule your automatic updates and reboot in the middle of the night/when you know you won't be using the computer than to find the time of when it updated and schedule your day around it.
http://blogs.technet.com/b/wsus/archive/2013/10/08/enabling-a-more-predictable-windows-update-experience-for-windows-8-and-windows-server-2012-kb-2885694.aspx

A: Finally, I've found an answer by myself[1]... I can't understand I did not look at the very obvious place earlier. Installation time of recent update is visible right after opening Windows Update control panel. Add 3 days and you will get restart time.

[1]: after I found the solution and returned to this question, I saw that in meantime something similar was added to BNP0007's answer, although it requires more steps to get the result.


text:
Q: How to filter, select and interact with a reactive data frame without user inputs? Shiny, Rmarkdown and Flexdashboard I have a problem since a few days with the selection or filtering of a reactive data frame, all this in the context of the development of a dashboard in Rmarkdown, Flexdashboard and Shiny.
The data frame is a web service of the type:
 www.somewebpage.com/project1/service.py?parameter1=2020&parameter2=ABC
Where the user selects the parameters (parameter1 and parameter2) and presses a button to execute the call to the web service, returning a JSON that I subsequently transformed it into a data frame.
Now my question is.

I have a reactive data frame, it is a function more than a data frame, how can I filter or select variables from the reactive data frame, but only in the code, without any user input?

Below is an example code of how I create the reactive data frame.
myData <- reactive({
        input$params # Action Button

        serv <- "www.somewebpage.com/project1/service.py?parameter1=2020&parameter2=ABC"
        dataURL <- isolate(urltools::param_set(urls = serv, key = "parameter1", value = input$parameter1))
        dataURL <- isolate(urltools::param_set(urls = dataURL, key = "parameter2", value = input$parameter2))
        resp <- httr::GET(dataURL)
        jsonRespText <- httr::content(resp, as = "text")
        jsonRespParsed <- httr::content(resp, as="parsed")
        df_json <- jsonlite::fromJSON(jsonRespText)
        modJson <- jsonRespParsed$Data

        dfCol <- modJson %>% bind_rows %>% dplyr::select(var1,
                                                         var2, var3, var4, var5, var6, var7, var8)
})

In the code provided above, I show how to create the reactive data frame called "myData".

How can I filter or select variables from the "myData" object?

For example, I want to show only some variables from "myData" in a Data Table:
renderDT({
  A <-  DT::datatable(data = myData() , extensions = "Buttons",
                      options = list(
                        columnDefs = list(list(className = 'dt-center', targets = c(2,3,4))),
                        pageLength = 10,
                        searchHighlight = TRUE,
                        language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json'),
                        buttons = list("copy", "print", list(
                          extend = "collection",
                          buttons = c("csv","excel","pdf"),
                          text = "Descargar"
                        )),
                        dom = "Bftip"
                      ))
  A
})

And what I get is shown in the image, I only want to show some variables, not all.

I will remain alert if you need more information from me.
Thank you very much.
EDITED
Partially solved!
I'm still looking at how to filter a reactive data frame, but to select, simply specify the columns as I show in the code.
renderDT({
  A <-  DT::datatable(data = myData()[,c(2,3,4)]) # Selecting columns 2, 3 and 4.
  A
})


text:
Q: Haskell IO program that calculates mean and highest value I have doubts to do this exercise. I have the solution (which is apparently wrong) but I could not understand:
Write a program that reads integers from the default input device, one per line, to a negative or zero universe, and prints an average and the largest of the read values.
My code:
a6 ::Int -> Float ->Int->Int-> IO()
a6 cBigger average2 sum2 cCount = do
 c <- getLine
 let digit = read c :: Int
 let sum = sum2 + digit
 let average = fromIntegral sum2/ fromIntegral cCount
 if (digit <=0)
     then putStrLn("Bigger :" ++show(cBigger)++ "average "++show(cAverage))
     else
     if digit > cBigger
          then a6 digit average sum (cCount+1)
           else a6 cBigger average sum (cCount+1)

As I do not understand much Haskell I have doubts of how to do.

A: Although a little off topic, I thought I would comment on separation of concerns and modularity.
Usually, we try to keep the pure parts of the program separate from the impure (IO) parts.
We can read a list of Ints with impure code, and then process it with a pure function to find the max, sum, and length in order to compute the average.
Below, readInts reads Ints from stdin until it reads a non-positive value, returning the positive Ints in a list (in IO).  maxSumLength takes the current maximum, sum, and length of the elements processed so far
as a tuple, and the next element to process, and returns a new tuple with the next element folded in.  Finally, main reads the list of Ints, and applies a strict left fold (foldl') using maxSumLength and an initial state of (0, 0, 0) to compute the final maximum, sum, and length.   It then prints the maximum and the average from the sum and length.
module Main where

import Data.List ( foldl' )

readInts :: IO [Int]
readInts = do
  i <- read <$> getLine
  if i <= 0
    then return []
    else (i:) <$> readInts

maxSumLength :: (Int, Int, Int) -> Int -> (Int, Int, Int)
maxSumLength (m, s, l) x = (max m x, s+x, l+1)

main :: IO ()
main = do
  (m, s, l) <- foldl' maxSumLength (0, 0, 0) <$> readInts
  putStrLn $ "max=" ++ show m ++ ", avg=" ++ show (fromIntegral s / fromIntegral l)

This code is more modular than before.  We could reuse readInts in other programs that need a list of Ints.  Also, the pure part of the algorithm no longer cares where the list of Ints comes from.  However, there is a problem with this code.  When written this way, the entire list has to be buffered in memory before the pure code can start processing it, even though the processing code can consume the input as it arrives.
This is where the conduit package can help.  The conduit package allows a stream to be produced by an impure Source and connected to a pure Consumer, and allows the pure code to be interleaved with the impure code.  The conduit-combinators package provides combinators that allow streams to be treated much like lists (in particular, foldlC allows us to perform a strict left fold over a conduit stream instead of a list).
In the code below, the readInts function is now a Source of Ints that runs in the IO monad.  It uses the repeatWhileMC combinator to perform the looping and the termination test.  The pure maxSumLength is unchanged; however, in main, rather than use foldl', we use foldlC to fold over the conduit stream.
module Main where

import Conduit

readInts :: Source IO Int
readInts = repeatWhileMC (read <$> getLine) (> 0)

maxSumLength :: (Int, Int, Int) -> Int -> (Int, Int, Int)
maxSumLength (m, s, l) x = (max m x, s+x, l+1)

main :: IO ()
main = do
  (m, s, n) <- runConduit (readInts =$= foldlC maxSumLength (0, 0, 0))
  putStrLn $ "max=" ++ show m ++ ", avg=" ++ show (fromIntegral s / fromIntegral n)

This code will interleave pure maxSumLength with the impure readInts so that the Ints are consumed as they are created, but without sacrificing modularity.  The readInts stream can be used in other programs that need a stream of Ints, and the pure code still no longer cares where the Ints are coming from.

A: While not optimal, your program is almost working. Here's some minor fixes and cleanups. I tried to keep your original code when possible, even if there might be better solutions.
First, you are using cAverage which is not defined. This error can be easily fixed.
The average2 parameter is pointless, since it is unused -- let's remove it.
Some lets can be moved to the branches where we actually use those variables.
We can also perform a minor refactoring and compute the new bigger value using a conditional, instead of using a conditional to perform two different recursive calls. (It would be even better to use the max function, though.)
Consider to rename "bigger" to "biggest", or "greatest", or "maximum". It sounds better to me.
a6 :: Int -> Int -> Int -> IO()
a6 bigger oldSum count = do
 c <- getLine
 let digit = read c :: Int
 if digit <= 0
     then let average = fromIntegral oldSum / fromIntegral count :: Double
          in putStrLn ("Bigger: " ++ show bigger ++ ", average: " ++ show average)
     else let newBigger = if digit > bigger then digit else bigger
              newSum = oldSum + digit
          in a6 newBigger newSum (count+1)


text:
Q: Graph with chromatic number $4$ that is not a supergraph of $K_3$ I've been trying to find a graph in which the chromatic number is equal to $4$ but it cannot be a supergraph of $K_3$.
I tried with an $11$-gon and join vertices every two vertices, (excuse me If my explanation is not clear, I'm learning English) anyway the resulting graph has chromatic number equal to $3$ and I thought that it was going to be the same with every cyclic graph.
Any examples?
Thanks.

A: Start with a $13$-gon.  For each independent triple of vertices $\{a,b,c\}$in the $13$-gon, add a vertex $v_{\{a,b,c\}}$ and edges connecting $v_{\{a,b,c\}}$ to each of $a,b,c$.  Call the resulting graph $K$.
Here by independent triple of vertices we mean three distinct vertices in the polygon, none of which are connected by an edge of the polygon.
Then $K$ is $4$-colourable: simply $3$-colour the $13$-gon, and colour all the $v_{\{a,b,c\}}$ with the fourth colour.
Also $K$ is triangle free: the $13$-gon is triangle free, so a triangle would have to involve a vertex $v_{\{a,b,c\}}$.  However ${\{a,b,c\}}$ are independent, so there is no such triangle.  Thus $K$ is not a supergraph of $K_3$.
It remains to show that $K$ is not $3$-colourable.  Suppose we have a $3$-colouring of $K$. Then for any independent triple ${\{a,b,c\}}$ of vertices in the polygon, they cannot all be different colours, as that would leave no choice of colour for $v_{\{a,b,c\}}$.
Pick a vertex $x$ in the polygon.  Call its colour $c_1$.  Opposite $x$ is an edge, with at least one end vertex not coloured $c_1$.  Call this vertex $y$, and its colour $c_2$.  Let $c_3$ denote the remaining colour.
Now the only vertices that may be coloured $c_3$ are the four vertices adjacent to $x,y$, as if any other vertex $a$ were coloured $c_3$, then ${\{x,y,a\}}$ would be an independent triple all coloured differently, which cannot happen.
Conversely, at least one of those four vertices must be coloured $c_3$, as a $13$-gon is not $2$-colourable.  Call this vertex $z$.
Now if we exclude $x,y$, the four vertices adjacent to them, which may be coloured $c_3$, and the remaining four vertices adjacent to those, we are left with one vertex $u$ on one side of the polygon, and two adjacent vertices $v,w$ on the other.

All three of $u,v,w$ are coloured by $c_1$ or $c_2$.  As $v, w$ cannot be the same colour, one of them must be coloured differently to $u$.  Thus $\{u,v,z\}$ or $\{u,w,z\}$ are an independent triple, all coloured differently, which cannot happen.
We conclude that $K$ is not $3$-colourable.


text:
Q: RANDOM.ORG сделать public ссылку Сделал некий запрос на random org api , но по итогу получил лишь такой ответ:

Почему-то я не наблюдаю там поле hashedApiKey чтобы потом сделать ссылку. Как в данном случае:
{
"method":"generateSignedIntegers",
"hashedApiKey":"oT3AdLMVZKajz0pgW/8Z+t5sGZkqQSOnAi1aB8Li0tXgWf8LolrgdQ1wn9sKx1ehxhUZmhwUIpAtM8QeRbn51Q==",
"n":6,"min":1,
"max":6,
"replacement":true,
"base":10,
"data":[6,1,4,4,3,6],
"completionTime":"2014-06-03 17:15:13Z",
"serialNumber":79924
}

Это пример JSON массива который должен быть для проверки, но у меня получается почему-то не такой результат (см скрин первый).
Почему мне не возвращают hashedApiKey
В мануале : https://api.random.org/verify/manual
Почему-то написанно:

Вы можете использовать наш API для проверки подписи, но это также возможно сделать сами. На этой странице объясняется, как выполнить проверку подписи без использования RANDOM.ORG API.

Но я не нашёл как сделать это с использованием API, вместо этого там приводится пример с работой на LINUX.
Как это можно организовать?
Хочется сделать публичную ссылку на которую может перейти любой человек.

A: Опять, всегда так. Ищешь проблему час.. два.. Задаёшь уже вопрос на форуме, а в итоге сразу находишь ответ на свой вопрос.
В методе при запросе на RANDOM ORG API нужно указать "method": "generateSignedIntegers" а не "method": "generateIntegers"
Тогда все данные прийдут для запроса на верификацию и создание паблик ссылки.
Всем спасибо :^ , чтобы я без вас делал!


text:
Q: PreAuthorize annotation of Symfony2 JMSSecurityExtraBundle not working Using the JMSSecurityExtraBundle of Symfony2 I try to create my own expression method and bind it in a controller using the PreAuthorize annotation.
I don't know why but the method is never fired, and the security bundle while trying to evaluate the PreAuthorize annotation concludes with a "Token does not have the required roles.". Seems like is trying to validate roles and not to resolve the PreAuthorize expression.
Example about what I'm trying to do:
<?php

namespace Acme\HelperBundle\Security;

use Symfony\Component\DependencyInjection\ContainerInterface;
use JMS\DiExtraBundle\Annotation as DI;

/** @DI\Service */
class RequestAccessEvaluator
{
    private $container;

    /**
     * @DI\InjectParams({
     *     "container" = @DI\Inject("service_container"),
     * })
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /** @DI\SecurityFunction("isAllowed") */
    public function isAllowed()
    {
        return true;
    }
}

My Controller:
   /**
     *
     * @PreAuthorize("isAllowed()")
     * @Route("/bla/{id}")
     * @Method({"POST"})
     * @return json
     */
    public function postBlaAction(Request $request, $id)
    {

A: I finally solved my problem... actually I missed that config.
It worked just putting that in my config.yml and setting the option "expressions" to true.


text:
Q: Can't convert varchar into date using sas data integation studio I am new using sas data Integartion Studio 4.9005.  i am using database oracle 18.
the scenario is i move from table_A with data type varchar(100) to table_B with date data type.
the format from table_A is YYYY/MM/DD

but the result is give me random number (01-01-1960) it doesn't make sense.

for code to convert is "INPUT( TANGGAL_LAHIR  ,yymmdd10.)"

Is there i am missing ? Thank you very much.


text:
Q: Jquery Datatable add a row from one table to another I am trying  add the rows from table 2 in table one.
if I select the row in the checkbox column and press add user, will add this row in the table 1
beside add user button I have a option for select all or none, if I click in the input select all
all rows from table 2 will be added in table 1 after button add user been pressed.
if I select none clear all check boxes
if I click all select all check-boxes
jsfiddle: http://jsfiddle.net/f7debwj2/11/
html:

 table1

      First name
      Place
      Order

 table 2

      First name
      Place
      checkbox

    <button type="button" class="btn btn-success">Add a user</button>

select all or none

        <input type="checkbox" name="vehicle1" value="Bike">

All

None

jquery
$(document).ready(function() {
  var dt = $('#example').dataTable();
  dt.fnDestroy();
});

$(document).ready(function() {
  var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
  var table = $('#example').DataTable({
    ajax: url,
    createdRow: function(row, data, dataIndex) {
      $(row).attr('id', 'row-' + dataIndex);
    },
    rowReorder: {
      dataSrc: 'order',
    },
    columns: [{
      data: 'order'
    }, {
      data: 'name'
    }, {
      data: 'place'
    }]
  });
  table.rowReordering();

});

$(document).ready(function() {
  var dt = $('#example2').dataTable();
  dt.fnDestroy();
});

$(document).ready(function() {
  var url = 'http://www.json-generator.com/api/json/get/cnmZgfsBKa?indent=2';
  var table = $('#example2').DataTable({
    ajax: url,
    createdRow: function(row, data, dataIndex) {
      $(row).attr('id', 'row-' + dataIndex);
    },
    rowReorder: {
      dataSrc: 'order',
    },
    columns: [{
      data: 'order'
    }, {
      data: 'name'
    }, {
      data: 'checkbox'
    }]
  });
  table.rowReordering();

});

$(document).ready(function() {
  $('body').on('mouseenter', 'input', function() {
    $('.btn').prop('disabled', true);
  });
  $('body').on('mouseout', 'input', function() {
    $('.btn').prop('disabled', false);
  });
});

A: I've altered your code slightly. This sample appears appropriate for your task and requirements. Hopefully, it will help you.
Html:

    table1

      First name
      Place
      Order

    table 2

      First name
      Place
      checkbox

    <button type="button" class="btn btn-success" id="btnAddUser">Add a user</button>

select all or none

        <input type="checkbox" name="vehicle1" value="Bike">

All

None

JavaScript:
function addUser()
{
    var $source = $("#example2").DataTable();
    var names = $($source.rows().nodes())
        .filter(':has(:checked)')
        .map(function () {
            return $(this).children().first().text();
        }).toArray();

    var $rows = $source.rows(function (i, data) {
        return names.indexOf('' + data.order) != -1;
    });

    var data = $rows.data();

    if (data.length > 0)
        $("#example").DataTable().rows.add(data.toArray()).draw();
}

function checkAll(check)
{
    var $source = $("#example2").DataTable();
    var names = $($source.rows().nodes())
        .find('input[type="checkbox"]')
        .each(function (i, el) {
            el.checked = check == 1;
        });

        return false;
}

$(document).ready(function() {
    var dt = $('#example').dataTable();
    dt.fnDestroy();
});

$(document).ready(function() {
    var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
    var table = $('#example').DataTable({
        ajax: url,
        createdRow: function(row, data, dataIndex) {
          $(row).attr('id', 'row-' + dataIndex);
        },
        rowReorder: {
          dataSrc: 'order',
        },
        columns: [{
          data: 'order'
        }, {
          data: 'name'
        }, {
          data: 'place'
        }]
    });
    table.rowReordering();
});

$(document).ready(function() {
    var dt = $('#example2').dataTable();
    dt.fnDestroy();
});

$(document).ready(function() {
    var url = 'http://www.json-generator.com/api/json/get/cnmZgfsBKa?indent=2';
    var table = $('#example2').DataTable({
        ajax: url,
        createdRow: function(row, data, dataIndex) {
          $(row).attr('id', 'row-' + dataIndex);
        },
        rowReorder: {
          dataSrc: 'order',
        },
        columns: [{
          data: 'order'
        }, {
          data: 'name'
        }, {
          data: 'checkbox'
        }]
      });
      table.rowReordering();
});

$(document).ready(function() {
    $('body').on('mouseenter', 'input', function() {
        $('.btn').prop('disabled', true);
    });
    $('body').on('mouseout', 'input', function() {
        $('.btn').prop('disabled', false);
    });

    $('#checkAll').click(function () { checkAll(1);});
    $('#uncheckAll').click(function () { checkAll(0);});
    $('#btnAddUser').click(function () { addUser(); });
});

JSFiddle: http://jsfiddle.net/jahn08/f7debwj2/26/?


text:
Q: Does IE9 recalculate all styles after I use javascript to add a stylesheet? After using JS to add a new <link rel="stylesheet"> to my document, I expect a browser to request the new stylesheet and apply its styles, and IE 9 does that.  However, IE 9 fails to respect the precedence of other styles in the document, eg. in a subsequent style block.
Given a stylesheet blue.css like this:
.box { background-color: blue; }

.. and a document like this ..
<!DOCTYPE html>

hello

When all is said and done, IE 9 will show a blue box, and other browsers like FF 12 or Chrome 19 will show a red box.
Is IE just being lazy here?  Is lazy too nice a word?  Should I force IE to recalculate all styles by using a hack like this or this?


text:
Q: How do i make regex for final occurence of a string I want to make a regex of that search for the final occurence of given alphabet in a string.
import re
string = "Hello stackoverflow"
[print(re.sub('o', '*', string))]

i'm expecting "Hello stackoverfl*w" as the result

A: You could reverse the string, do the replacement once, and return the re-reversed string:
re.sub('o','*',string[::-1],1)[::-1]
#                           ^ this means do the replacement only once

A: We can try using re.sub for a regex option:
string = "Hello stackoverflow"
output = re.sub(r'^(.*)o(.*)$', '\\1*\\2', string)
print(output)

This prints:
Hello stackoverfl*w

A: Another solution:
re.sub(r"(.*)o", r"\1*", string)


text:
Q: How to check if custom product attribute exists I want to check if my custom product attributes exist before I attempt to utilize it in any way. Whats the best way to check it in Magento 2.
Note that I don't want to check if specific product has the attribute. I want to check if that attribute exists in Magento.
I've found partial answer on stackexchange https://magento.stackexchange.com/a/107993/14809
but that answer is very limited. Especially the code example is very scarce:
try {
   $attribute = $this->attributeRepository->get($entityType, $attributeCode);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    //  attribute is not exists
}

*

*It's not clear what to enter in $entityType.

*What will get return if the attribute does not exist?

*I don't know where to find example implementation of the methods (e.g. get(...)) defined in the interface \Magento\Eav\Api\AttributeRepositoryInterface.php

A: *

*$entityType in your case is the 'catalog_product' as its a product attribute

*It will throw an exception

*vendor/magento/module-eav/Model/AttributeRepository.php and check the public function get($entityTypeCode, $attributeCode)

A: You can inject Magento\Eav\Model\Config object and use the getAttribute('catalog_product', $attributecode) function to check if your custom eav attribute with code $attributecode already exist or not.
Here is the code sample:
$attribute = $this->eavConfig->getAttribute($entityTypeCode, $attributeCode);
if (!$attribute || !$attribute->getAttributeId()) {
    throw new NoSuchEntityException(
        __('Attribute with attributeCode "%1" does not exist.', $attributeCode)
    );
}
return $attribute;

A: Check "eav_entity_type" table. It will show you all the attribute type code you can use while fetching the information.


text:
Q: Can't Use () {} (AKA: Anonymous Function) in flutter I did created a brand-new project just now and I encountered this problem.
I Can't Use Buttons because I can't Assign a function to them!
Here is my code:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: const Align(
          alignment: Alignment.center,
          child: TextButton(onPressed: () {}, child: Text('LAUNCH'))), //PROBLEM IS HERE
    );
  }

  Future<void> _launchUrl(String urlString) async {
    if (await canLaunch(urlString)) {
      await launch(
        urlString,
        forceWebView: true,
      );
    } else {
      Fluttertoast.showToast(
          msg: "Try Again",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }
}

As you can see I can't give () {} to the onPressed method of TextButton. This is the root of my problem.
The Error that Flutter shows for this is:
Invalid constant value.
Also the packages I use:
dependencies:
  fluttertoast: ^8.0.8
  url_launcher: ^6.0.17
  animated_splash_screen: ^1.1.0

A: To solve this issue please remove const infront of align.
From this:
child: const Align(
          alignment: Alignment.center,
          child: TextButton(onPressed: () {}, child: Text('LAUNCH'))),

To this:
child: Align(
          alignment: Alignment.center,
          child: TextButton(onPressed: () {}, child: Text('LAUNCH'))),


text:
Q: change the path variable of the parent shell in a shell script I wanted to change the path environment variable in a shell script.
The path variable should be modified after the execution of the shell script.

A: There are two ways I know of to do this. The first is to run the script in the context of the current shell with either of:
. myscript.sh
source myscript.sh

but that runs the risk of polluting the current shell with all sorts of stuff.
I'd prefer a solution where the amount of information leakage is minimal. That means still running it as a subshell but outputting the new path on statndard output:
PATH=$(myscript.sh)

This method is a much better one since the path is the only thing that can be affected by the subshell but you have to be careful with what that subshell outputs.

A: You need to source your script instead of executing it.
. script.sh

or
source script.sh

Inside of the script it's enough to either export od just set the variable.
When the script is executed, it runs in a separate shell process, and can't easily change parent shell's variables.
More about it here: Can a shell script set environment variables of the calling shell?


text:
Q: How to create a CSS class for use in activeClassName I'm trying to set the styles for the active link in a navbar using a CSS class generated with Emotion.
<Link activeClassName={activeLink} to="/contact/">Contact</Link>

I've defined my style in the same file.
import { css } from '@emotion/core'

const activeLink = css`
  color: red;
`

The style isn't applied to the active link and I'm getting a console error:
Warning: Failed prop type: Invalid prop `activeClassName` of type `object` supplied to `GatsbyLink`, expected `string`.

How can I use an Emotion style with activeClassName?

A: Unfortunately, you can't use import { css } from '@emotion/core', instead you need to use
import { cx, css } from 'emotion'

const activeLink = css`
  color: red;
`
<Link activeClassName={cx(activeLink)} to="/contact/">Contact</Link>

I hope it's helpful for you.
Alternatively, you may achieve this with the styled element
import styled from '@emotion/styled'

const NavLink = styled(Link)`
  &.active {
    color: red;
  }
`
<NavLink activeClassName='active' to="/contact/">Contact</NavLink>

A: I think activeClassName only require a string, but have you tried to use activeStyle instead of activeClassName ?

A: You can use the <ClassNames/> component from @emotion/core like this:
import {ClassNames, css} from '@emotion/core'

const activeLink = css`
  color: red;
`

const Component = () => {
  <ClassNames>
    {({css}) => (
      <NavLink activeClassName={css(activeLink)} to="/">Home</NavLink>
    )}
  </ClassNames>
}


text:
Q: React Hooks(use State) Error in Ionic react i am using ionic-react and everything is going smooth but when i tried to use useState from react hooks, i ran into this problem:
What i have tried:

*

*Updating all packages to latest in Project folder using 'npm update'

*linking with react and react dom (first answer)

*Changing my package.json file.

The problem still presists.
The app works smoothly without using hooks, but it is much need and if there is an alternative to it, i can also use that.
NOTE:
i did'nt explicitly created react library which is done in this question here i installed all dependencies using npm
This is my package json file:
{
  "name": "frontend-client-cpp",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "@ionic/react": "^5.6.5",
    "@ionic/react-router": "^5.6.5",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.6.3",
    "@types/jest": "^26.0.20",
    "@types/node": "^12.19.15",
    "@types/react": "^16.14.3",
    "@types/react-dom": "^16.9.10",
    "@types/react-router": "^5.1.11",
    "@types/react-router-dom": "^5.1.7",
    "ionicons": "^5.4.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.2",
    "typescript": "^4.1.3",
    "web-vitals": "^0.2.4",
    "workbox-background-sync": "^5.1.4",
    "workbox-broadcast-update": "^5.1.4",
    "workbox-cacheable-response": "^5.1.4",
    "workbox-core": "^5.1.4",
    "workbox-expiration": "^5.1.4",
    "workbox-google-analytics": "^5.1.4",
    "workbox-navigation-preload": "^5.1.4",
    "workbox-precaching": "^5.1.4",
    "workbox-range-requests": "^5.1.4",
    "workbox-routing": "^5.1.4",
    "workbox-strategies": "^5.1.4",
    "workbox-streams": "^5.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "description": "An Ionic project"
}

A: In your package.json, the dependency  "@ionic/react-hooks" is missing, so install it:
$ npm install @ionic/react-hooks


text:
Q: Count a variable during a time span by joining four tables There are four tables:
Propertyno (
    propertyno,
    street,
    city,
    postcode,
    type,
    rooms,
    rent,
    ownerno,
    staffno,
    branchno)

Viewing (
    clientno,
    propertyno,
    viewdate,
    comment)

Client (
    clientno,
    fname,
    lname,
    telno,
    preftype,
    maxrent)

Registration (
    clientno,
    branchno,
    staffno,
    datejoined)

Finding the number of property views per branch within 1 month, 2 months, and 3 months of client registration requested. Since the exact database is not accessible as of now the answer to the question would be subjected to kind of interpretation and perception in the similar situation (This question can consider as a kind of abstract one). I provide a sample code according to my understanding. Since I am a beginner, certainly the below code is most probably wrong. Also, I do not have an exact idea about the counting of views during one month, 2months and so on.  I appreciate if you could correct me with your codes and comments.
SELECT
   PR.propertyno, PR.branchno, V.clientno, V.propertyno, V.viwedate,
   R.clientno, R.datejoined
FROM
   PropertyforRent PR LEFT JOIN Viewing V ON PR.propertyno = V.propertyno
   INNER JOIN Client AS C ON V.clientno = C.clientno
   INNER JOIN Registration AS R ON C.clientno = R.clientno
SELECT COUNT(viewdate) WHERE start_date <=@date AND end_date >=@date
   GROUP BY propertyno
   GROUP BY branch;


text:
Q: How to programatically submit a spark application in yarn-client mode? I have a simple spark job which replaces spaces with commas in a given input file.
When this job is submitted locally (Using IDE and executing the built jar) it completes successfully and when the master is set to "yarn-client" the job hangs for very long time and throws the following exception.
We have a usecase where we want to submit the job programatically rather than building a jar and submitting it through spark-submit.
Spark version : 1.6.1
Hadoop version : 2.7.1
and i got all the spark, yarn and hadoop dependencies in my pom.
Job failed due to following exception
java.net.ConnectException: Call From spark.node123.com/192.168.2.1 to 0.0.0.0:8032 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
    at sun.reflect.GeneratedConstructorAccessor13.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:792)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:732)
    at org.apache.hadoop.ipc.Client.call(Client.java:1480)
    at org.apache.hadoop.ipc.Client.call(Client.java:1407)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at com.sun.proxy.$Proxy10.getClusterMetrics(Unknown Source)
    at org.apache.hadoop.yarn.api.impl.pb.client.ApplicationClientProtocolPBClientImpl.getClusterMetrics(ApplicationClientProtocolPBClientImpl.java:152)
    at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:187)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy11.getClusterMetrics(Unknown Source)
    at org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.getYarnClusterMetrics(YarnClientImpl.java:246)
    at org.apache.spark.deploy.yarn.Client$$anonfun$submitApplication$1.apply(Client.scala:129)
    at org.apache.spark.deploy.yarn.Client$$anonfun$submitApplication$1.apply(Client.scala:129)
    at org.apache.spark.Logging$class.logInfo(Logging.scala:58)
    at org.apache.spark.deploy.yarn.Client.logInfo(Client.scala:62)
    at org.apache.spark.deploy.yarn.Client.submitApplication(Client.scala:128)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:57)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:144)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:530)
    at tardis.platform.TardisContext$.apply(TardisContext.scala:20)
    at tardis.common.plugins.Heartbeat.isAbleTocreateContext(Heartbeat.scala:45)
    at tardis.common.plugins.Heartbeat.performAction(Heartbeat.scala:33)
    at tardis.core.scheduler.jobs.PluginExecutorJob.execute(PluginExecutorJob.scala:40)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:531)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:495)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:609)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:707)
    at org.apache.hadoop.ipc.Client$Connection.access$2800(Client.java:370)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1529)
    at org.apache.hadoop.ipc.Client.call(Client.java:1446)
    ... 25 more

A: I had to add the hadoop and yarn configurations to successfully submit the application in yarn-client mode.

A: You can not remotely submit your spark job in client mode since your computer have to run the driver program itself which require a lot of connection. If you insist using this method, you have to config your firewall to allow some port to connect to the cluster. Using cluster mode or submit it from master node are much less painful.


text:
Q: Could these hypothetical very long distance properties of light offer alternatives to an expanding universe or a finite number of galaxies? Assume that there could be a property of light that it gets very gradually steadily red-shifted by traveling large astronomical distances, in exactly the same way that Doppler shift from receding velocity would. Perhaps there is a period of 1000 years or more from emission before there is any observable red-shift, so we would not be able to measure this effect in laboratory for quite a while. Could this be an alternate explanation for why other galaxies appear red-shifted in proportion to distance from us, as opposed to the proportional redshift being from Doppler effects?
Also assume that there could be a property of light that after an enormous distance, it stops traveling as observable light. Something unknown happens that may conserve mass and energy or whatever, but practically speaking, we can't observe light after it has traveled the radius of the observable universe. Could this be an alternate explanation of why there seem to be a finite number of observable galaxies in the visible universe? Could this not also be a possible explanation for what cosmic background radiation is (i.e. perhaps light at superlong range degrades in stages, first producing the noise of cosmic background radiation which is what we can detect of galaxies beyond what we see as galaxies, and it's not infinitely bright because a certain range beyond that, it doesn't even reach us as cosmic background radiation)?
In other words, is it possible that the observed galaxies are not generally all expanding away from each other, but that light simply redshifts over extreme distance? What evidence besides redshift and a finite number of observed galaxies suggests that galaxies are all expanding away from each other? Is there a non-redshift-based distribution of observed galaxies in relation to each other that points to a specific location other than our own from which everything seems to expand? Is there some evidence that contradicts the hypothesis that light has a maximum range after which it can't be observed? Do we seem to be on one particular side of the universe of known galaxies? (I have read a bit about the Tolman surface brightness test - is there a reason this could not just be a property of light at great distance? Is it just that there is a convincing correspondence of galaxy redshift data to independent calculations of expected frequencies from expanding/receding sources?)
Furthermore, even if we have multiple forms of evidence that there seems to be one cloud of galaxies expanding from one point, what if there is a limited range of light propagation that could be even greater than the width of the cloud of visible galaxies? Could there not then be other galaxies (or whatever) even further than what we can see? Or is there some evidence that contradicts that possibility? Does the universe seem to be a non-Cartesian bubble in some sense?
Post-script: I have read about the history of "tired light" theories and how they have been discounted since the 1990's and (as I mentioned) about the Tolman surface brightness test (about which I am just interested why it might not be that light just behaves that way at range - is it because of congruence of distant galaxy data with a previous finite expansion theory's formulae which would have no other reason to match some arbitrary behavior of light over distance?). I am not proposing that my assumptions be treated as competing theories - I am asking about the nature of the evidence and reasoning there is that has people discount such theories.
Also I am not asking "what else could explain cosmological redshift?", as the people who marked this as duplicate suggest. I am asking "what evidence contradicts the possibility that some unknown long-range properties of light are leading to an expanding finite cosmological model?"
Post post-script: Again this has been marked as a duplicate, and SE generated a message asking if the answers there answer my question. There is overlap in the questions, but I prefer my more detailed wording to the suggested one, and I prefer the answers and comments found here.
And no, the answers there don't entirely answer my question, or at least I don't understand the detail of them. It seems to me that the downvoted answer here leaves an aspect that I still don't really understand the answer to - that is, could it not be that the "time dilation" could also be the result of some long-distance effect, and would we not expect to be able to see more large-scale effects of this time dilation on the movements of objects? The suggestion was galaxy rotation statistics, though I wonder if anything else is distant-yet-distinguishable enough to test this.

A: The light curve peaks of Type Ia supernova become broader at higher redshifts. The amount of broadening is in proportion to the amount of redshift $(1+z)$. i.e the cosmological time dilation works exactly as expected for an expanding universe, see for example Blondin et al. (2008). A "gradual redshifting" of light as it travelled a distance does not explain this time dilation.
The plot below shows how the measured "de-dilation factor" from supernova light curves depends on their redshift (from Blondin et al. 2008). It goes as $1/(1+z)$, exactly as expected. The horizontal dashed line is what would be expected from "tired light".
This method was proposed by Wilson (1939) as a test of the expanding universe theory rather than the "gradual dissipation of photonic energy" (aka "tired light"). The test has been passed with flying colours.

A: If all galaxies in the universe have always rotated at roughly the same speed and if more distant galaxies are receding more rapidly than we should observe slower rotation rates for more distant galaxies. This is simple classical physics, if an ice cream truck drives away from the observer the song is not just lower in pitch, it is also slower in tempo so the tempo of galactic rotation should appear to be slower with distance.
This is NOT what has been observed however, the speed of galactic rotation is observed to show a consistent average with distance which means that over the presumed life of the universe galactic speeds must have been decreasing if inflation/expansion is the explanation for the red shift which seems very unlikely.
To presume an unknown process by which light is downshifted in frequency, possibly by transferring its energy with downshifting into increasing the strength of the gravitational fields it is passing through is far less of a leap than presuming dark matter and energy.
The real reason the tired light hypothesis is anathema is that it would falsify the big bang which any such attempt is career suicide,anyone who tries must be discredited Dark mater and energy are terms used to imply evidence will be found in the future that will prove the big bang hypothesis, current observations falsify the big bang hypothesis however, there is no explanation for why galaxies are able to hold together given the current calculated rate of rotation assuming a Doppler shift explanation for the red shift, and the Doppler shift explanation requires an infinite acceleration of expansion which can not be explained in terms of energy, so falsifying evidence against the big bang is instead touted as future evidence that will prove the big bang, the scientific equivalent of a knowledge pyramid scheme
scientists are people, falsifying the popular big bang theory is career suicide if one works as a scientist hence all the hysterical derogatory name calling. Its very unfashionable to attempt to extend Newtonian physics to account for current observations
this book will answer your questions in a rational manner
http://www.amazon.com/Selected-Topics-Advanced-Fundamental-Physics/dp/3980094243
and this is a general data base that will provide a complete picture from the late Physicist James Paul Wesley
http://www.worldsci.org/php/index.php?tab0=Scientists&tab1=Scientists&tab2=Display&id=55


text:
Q: How to pipe to a program in the same directory as a Bash script on macOS? I've written a Bash script that's meant to delete a file then run sqlite3. It runs fine in my mingw64 Bash on Windows, but fails in Bash on macOS.
My script comes with its own copy of sqlite3 in the same directory as the script.
rm -f Input.sqlite
cat SqliteCommands.txt | sqlite3

Output:

compy:program me$ ./Run-Bash.sh
  : command not found 2: sqlite3
  cat: SqliteCommands.txt: No such file or directory

I remembered that to run a program in the current directory you need to prefix it with ./, so I changed it to:
cat SqliteCommands.txt | ./sqlite3

...which weirdly gets me this error output (verbatim). I don't know why it removed the "sql" part of the file name, that's weird.

: No such file or directorylite3
  cat: SqliteCommands.txt: No such file or directory

As macOS comes with its own copy of sqlite3 I changed it to use the full path, but as macOS comes with an older version it means I had to change my SqliteCommands.txt to be compatible which isn't ideal.
cat SqliteCommands.txt | /usr/bin/sqlite3

So how can I pipe to an executable in the same directory as the script?

A: I am not sure, but try this:
sqlite3 "$(cat SqliteCommands.txt)"

or
cat SqliteCommands.txt | xargs -I {} sqlite3 {}


text:
Q: C++ vector of set gives segmentation fault after performing push_back I have created a vector of sets in my program, and I need to go through each of the sets. In case a specific element is found in the set, I need to add a new set to the vector. However, this gives me a segmentation fault as soon as my array's counter reaches the elements that I inserted later (within the loop). In the following code, switching on list.push_back(cS) gives me a segmentation fault.
int main(void)  {
set<int> cS;
vector<set<int> > list;

cS.insert(1);
list.push_back(cS);

cS.insert(2);
list.push_back(cS);

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            //list.push_back(cS);
        }
    }
}

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        cout << *itr << endl;
    }
}

return 0;
}

I would be grateful if someone could explain why this gives an error (in gcc).
Thank you for going through my post.

A: When you push_back into your vector you invalidate all references to elements in it in the case the vector needs to allocate more memory. In your case the iterator itr becomes invalid after the push_back. One solution would be to add the sets to a separate list (vector) and then append them all at once after the for loop:
vector<set<int> > add;
for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            add.push_back(cS);
        }
    }
}
list.insert(list.end(), add.begin(), add.end());


text:
Q: Can Google App Engine projection query return entity keys? Let's say I have:
class Like(db.Model):
    user = db.ReferenceProperty(User,collection_name='likes')
    photo = db.ReferenceProperty(Photo,collection_name='likes_received')
    created = db.DateTimeProperty(auto_now_add=True)

Is it possible to run a projection query that returns only a list of photo keys?
photos = db.GqlQuery("SELECT photo FROM Like WHERE created < DATETIME(2013, 1, 1, 0, 0, 0)").fetch(10)

The code above produces:
BadValueError: Unsupported data type (<class 'models.Photo'>)

A: Sounds like your Photo class hasn't been imported yet.

A: I apologize, my first answer was wrong.  There is a real problem with projection queries -- ReferenceProperty is not (yet) supported.  Alfred is looking into this; since the 1.6.6 prerelease SDK went out today and this was already present in the 1.6.5 SDk I doubt we'll get this fixed in 1.6.6 but 1.6.7 is a possibility.
As workarounds, you could use db.ListProperty(db.Key), which is a list of keys (you'd store only one key), or a StringProperty whose value is the str() of the key.


text:
Q: Reusability and Extensibility in OOPL I have 3 problems, which are more or less similar.

*

*Given a integer array, I want to find the longest continuous subarray, such that the subarray is in increasing order of numbers.

*Given a integer array, I want to find the longest continuous subarray, such that the subarray have all same numbers.

*Given a character array, I want to find the longest continuous subarray, such that the subarray have all same characters.
I want to fully exploit concepts of reusability and extensibility in oops. I have implemented some code using templates. I have gave it a try and made a class template for problem 2 and 3 since they both can be done just comparing the ascii value of number or character. But I am not sure how to integrate the code for problem 1? I just want to know how tackle such problems from the perspective of reusability and extensibility using inheritance.

A: Strategy pattern to the rescue: you can define an interface that encapsulates the matching strategy, say SubarrayMatcher and create two implementations, one that matches "increasing order of values" and another that matches "same values". Your main algorithm can then take the interface as a parameter and call out to it to do the matching.
High-level structure in pseudo-code:
Array<T> findLongestSubarray(Array<T> values, SubarrayMatcher<T> matcher);

interface SubarrayMatcher<T>
class IncreasingSubarrayMatcher<T> implements SubarrayMatcher<T>
class ConstantSubarrayMatcher<T> implements SubarrayMatcher<T>


text:
Q: How can i find out the Last row in a datagridview and write it to text file I would like to find the last row of the datagridview and i would like to write that particular row data to a text file can any one help me

A: I will give you a sample code, it may help.
 List<string> lstContents = new List<string>();
        foreach (DataGridViewCell cell in mydataGrid.Rows[mydataGrid.RowCount - 1].Cells)
        {
            lstContents .Add((string)cell.Value);
        }
 string myData= string.Join(",", lstContents.ToArray());

Now using streamwriter you can write this string to your file. Also you can use any separator. I have used "," comma here.
///This will append data to your text file...
using (StreamWriter sw = new StreamWriter(FilePath, true))
        {
            sw.WriteLine(myData);
        }


text:
Q: LED intensity issues on Attiny85 with 74HC595 to control 8 LEDs I want to light up 8 LEDs where I should be able to control intensities of the LEDs as well. Since I want the circuit to be as small as possible on a printed circuit board (PCB,) I am using an Attiny85 IC for the following problem.
For all the 8 LEDs, I would like to light them up with a very good brightness level. So say, current of each LED is 20mA.
The Attiny85, has two PWM pins (PB0 and PB1)(i.e., pin 5 and pin 6.)
But since the maximum output of each pin on the Attiny85 (or Arduino Uno) is 40mA, if I connect 3 LEDs to a single Attiny85 pin, the current will be   divided and the intensity of LED is lower.
I am planning to use a 74HC595 shift register IC so that I can connect the PWM pins of micro controller as the input to 74HC595 IC and control 8 LEDs with the 8 output pins of 74HC595 without any current dividing factor.
Is this a good idea, or will the low current (low intensity of LED) issue on each output pin of 74H5C95 still exist since we are using only 3 pins of the Attiny85 to control all the LEDs with a 74HC595 IC?
Basically, I want to know how much current output will be getting from each pin of 74HC595.
Any other thoughts would be very helpful.

A: 74H5C95 has 6mA output with a 5v supply according to the datasheet. If you want to run your LEDs at 20mA, you will not be able to with just the shift register. You could use a transistor for each LED as a switch controlled by the shift register pin and the other pins of the transistors attached to your supply voltage if you are married to the 74H5C95.


text:
Q: MSVC fails with compiler errors without compiling any sources All source files seem to have compiled fine.
However, since I achieved that, I am getting a new compiler error:
1>------ Erstellen gestartet: Projekt: OpenLieroX, Konfiguration: Debug Win32 ------
1>Der Buildvorgang wurde am 29.03.2012 23:57:39 gestartet.
1>InitializeBuildStatus:
1>  Aktualisieren des Timestamps von "Debug\OpenLieroX.unsuccessfulbuild".
1>ClCompile:
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>  Alle Ausgaben sind aktuell.
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(54): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_STANDA'
1>
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(76): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_SECURE'
1>
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\yvals.h(367): warning RC4011: identifier truncated to '_DISABLE_DEPRECATE_STATIC_CPPLI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(83): warning RC4011: identifier truncated to 'BOOST_NO_CV_VOID_SPECIALIZATION'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(92): warning RC4011: identifier truncated to 'BOOST_NO_LIMITS_COMPILE_TIME_CO'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(102): warning RC4011: identifier truncated to 'BOOST_NO_LONG_LONG_NUMERIC_LIMI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(117): warning RC4011: identifier truncated to 'BOOST_NO_MS_INT64_NUMERIC_LIMIT'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(133): warning RC4011: identifier truncated to 'BOOST_NO_TEMPLATE_PARTIAL_SPECI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(134): warning RC4011: identifier truncated to 'BOOST_BCB_PARTIAL_SPECIALIZATIO'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(141): warning RC4011: identifier truncated to 'BOOST_NO_TEMPLATE_PARTIAL_SPECI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(142): warning RC4011: identifier truncated to 'BOOST_NO_ARRAY_TYPE_SPECIALIZAT'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(149): warning RC4011: identifier truncated to 'BOOST_NO_TEMPLATE_PARTIAL_SPECI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(158): warning RC4011: identifier truncated to 'BOOST_NO_TEMPLATE_PARTIAL_SPECI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(159): warning RC4011: identifier truncated to 'BOOST_NO_PARTIAL_SPECIALIZATION'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(169): warning RC4011: identifier truncated to 'BOOST_NO_TEMPLATED_ITERATOR_CON'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(186): warning RC4011: identifier truncated to 'BOOST_NO_ARGUMENT_DEPENDENT_LOO'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(186): warning RC4011: identifier truncated to 'BOOST_FUNCTION_SCOPE_USING_DECL'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(341): warning RC4011: identifier truncated to 'BOOST_NO_0X_HDR_INITIALIZER_LIS'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(344): warning RC4011: identifier truncated to 'BOOST_NO_0X_HDR_INITIALIZER_LIS'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/config/suffix.hpp(566): warning RC4011: identifier truncated to 'BOOST_NO_EXPLICIT_FUNCTION_TEMP'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/limits.hpp(22): warning RC4011: identifier truncated to 'BOOST_NO_LONG_LONG_NUMERIC_LIMI'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/limits.hpp(23): warning RC4011: identifier truncated to 'BOOST_NO_MS_INT64_NUMERIC_LIMIT'
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/cstdint.hpp(300): error RC2177: constant too big
1>
1>C:\Program Files (x86)\boost\boost_1_47\boost/cstdint.hpp(300): fatal error RC1012: mismatched parenthesis : missing '
1>
1>Fehler beim Erstellen

I don't really understand why I get that. And also not from what source file because it isn't compiling any sources anymore (because all have been compiled successfully).

A: (Reposting from comment so question can be marked answered.)
You shouldn't be compiling normal code with the resource compiler.

A: While the marked answer is already correct here some background:
The MSVC Resource Compiler truncates macro names at char 31.
Similar problems occur also with newer system headers like those from VC10 or later which have macro names defined with more than 31 chars. See also M$'s reply who call this simply 'by design' instead of fixing their RC.EXE:
http://connect.microsoft.com/VisualStudio/feedback/details/532929/rc4011-warnings-from-vc10-rc
Affected system headers with macro names greater than 31 chars are since VC10 string.h, tchar.h, wchar.h, yvals.h and probably some more ...
see also:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/ea289832-c48c-475b-a922-bf94d2ee54e4/vs2012-update-1-fatal-error-rc10056-in-c-project-when-v110xp-platform-is-chosen

A: When attempting to use Visual Studio 2013 to compile for Windows XP and POS Ready 2009 as a target, I ran into a similar problem. The application compiled fine with the standard Visual Studio 2013 (v120) setting in the Platform Toolset Configuration Properties however when changed to Visual Studio 2013 - Windows XP (v120_xp) to target Windows XP, I received a compilation error of:
>C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\include\winsock2.h(2752): fatal error RC10056:

Jumping to the location in the WinSock2.h include file showed a function prototype which used the __out_bcount_part_opt() macro.
After seeing this posting I realized that the error was a resource compiler error. Looking further what I discovered was that a header file, piflocal.h, that was included in both the source code and the resource file contained an include of the WinSock2.h header file.
In other words the application source code had a header file, piflocal.h, which contained defines needed by the header file resource.h used by the resource file pif.rc as well as the C source files. Some of the definitions in piflocal.h required definitions from the Microsoft standard header file WinSock2.h so the WinSock2.h file was #included into piflocal.h making it available. However when the resource compiler, as part of pulling in the various header files, attempted to process the WinSock2.h file as a part of processing piflocal.h, it ran into the __out_bcount_part_opt() macro and failed.
The __out_bcount_part_opt() macro, by the way, is part of the Header Annotations used in Windows headers.

Header annotations describe how a function uses its parameters and
  return value. These annotations have been added to many of the Windows
  header files to help you ensure that you are calling the Windows API
  correctly. If you enable code analysis, which is available starting
  with the Visual Studio 2005, the compiler will produce level 6000
  warnings if you are not calling these functions per the usage
  described through the annotations. You can also add these annotations
  in your own code to ensure that it is being called correctly. To
  enable code analysis in Visual Studio, see the documentation for your
  version of Visual Studio.
These annotations are defined in Specstrings.h. They are built on
  primitives that are part of the Standard Annotation Language (SAL) and
  implemented using declspec("SAL*").

I then made the necessary source code changes to the resource.h and the piflocal.h header files so that few defines needed by pif.rc from piflocal.h were moved into resource.h and the header file piflocal.h was no longer included or pulled in by the resource compiler when compiling pif.rc.
By removing WinSock2.h from the list of header files pulled in by the resource compiler, the error no longer happened.
I do not know why this compiled with the standard Visual Studio 2013 settings and failed with targeting Windows XP and its variants.
Conclusion: if you are running into this error or similar error, more than likely you are including into the resource compiler a header file with a macro definition which is incompatible with the resource compiler.


text:
Q: Add carousel control (next - prev) automaticlly I have more than one bootstrap carousel in my project and I want to reduce my html elements I remove my carousel-indicators and I added with js.I want to do same thing for carousel-control but my head is swollen how can I adapt my code

var myCarousels = $(".carousel");
  myCarousels.each(function( index, element  ) {
    var myCarousel = $("#"+$(element).attr('id'));
    myCarousel.append("

");
    var indicators = $("#"+$(element).attr('id') + " .carousel-indicators");
    $("#"+$(element).attr('id') +" .carousel-inner").children(".item").each(function(index) {
      (index === 0) ?
      indicators.append("

") :
      indicators.append("

");
    });
  });
<!DOCTYPE html>

 <meta charset="UTF-8">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        ...

        ...

    ...

    Previous

    Next

A: append controls inside of myCarousel:

var myCarousels = $(".carousel");
myCarousels.each(function(index, element) {
  var myCarousel = $("#" + $(element).attr('id'));
  myCarousel.append('PreviousNext');
  var indicators = $("#" + $(element).attr('id') + " .carousel-indicators");
  $("#" + $(element).attr('id') + " .carousel-inner").children(".item").each(function(index) {
    (index === 0) ?
    indicators.append("

"):
      indicators.append("

");
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        ...

        ...

    ...


text:
Q: Using Select-String (PowerShell) to find a word from error file I have the following code
Select-String -path errors.log -Pattern 'VirtualMachine\s*-vm-' | %{$_.Matches
| Select Value}

It outputs:
Value

--

VirtualMachine-vm-

The error file has VirtualMachine-vm-12345 but will change so I need to find not an exact match.

A: Select-String -path errors.log -Pattern 'VirtualMachine\s*-vm-\d\d\d\d\d\d' | %{$_.Matches | Select Value}

I figured it out
How do I run Get-VM -ID on this value?
Update
here is the answer:
$match = Select-String -path C:\errors.log -Pattern 'VirtualMachine\s*-vm-\d\d\d\d\d\d' | %{$_.Matches | Select -expand Value}

Get-VM -id $match | ft -Property Name,ID -AutoSize


text:
Q: Using the Smart phone URL with Omniauth I am developing an application in Rail 3 using the Omniauth gem for Facebook Connect. Currently the gem is using the normal Facebook website for login but I know that Facebook got a specialised website for Smartphones located at touch.facebook.com.
Does anyone know how to use the smart phone URL with the Omniauth Gem instead of the default?

A: Jonathan,
The strategy for facebook is hard coded to graph.facebook.com => https://github.com/intridea/omniauth/blob/master/oa-oauth/lib/omniauth/strategies/facebook.rb
I suggest to fork the project and create something like oa-mobile.
Also, remember they got a google group : http://groups.google.com/group/omniauth?pli=1
Regards

A: Apparently, according to Facebook you just have to pass an additional parameter to the authentication url to get the wap or touch versions of the site: http://developers.facebook.com/docs/guides/mobile/#web
Have you tried using the :options available in the facebook strategy code linked to by Marcel in the answer above? It looks like it should be pretty simple!


text:
Q: Threshold for feature correlation I have around 70 features and 3000 data points divided into 6 classes. I'm applying Random Forest, Nearest Neighbours, SVM with RBF kernel and Naive Bayes. Some of the features are correlated (mostly positive).
Are there some heuristics what a good correlation threshold for removing features is (also regarding the mentioned classifiers)? Currently I'm removing features having a correlation greater than 0.9.


text:
Q: Stream from external source using iframe with sandbox tag? I am trying to show the stream from an external site. That site has too many pop-up ads, and I am trying to block pop-up using the sandbox attribute. But it is showing

Remove sandbox attributes on the iframe tag

How can I solve it?
removing the sandbox fixes the issue, but there are a lot of pop-ups.
Here is the code I am using.
<iframe allowfullscreen="true"
    referrerpolicy="same-origin"
    sandbox="allow-form allow-pointer-lock allow-same-origin allow-scripts"
    frameborder="0" height="540" scrolling="no" src="https://somesrc.com/11.php"
    width="780"
>


text:
Q: How to safely store Google Api keys with rails and use them in scripts? I'm trying to safely store the Google api key that I'm using in a rails project. I tried storing it in a my secrets.yml file but if I then say in my google script &key=ENV['google_api'], it can't fetch it.
I'm pretty sure this is not the way but after googling the topic, I can't really find a clear answer on this. Anyone who can offer some help?
Thanks,
Thomas
UPDATE, here's the code I'm using to fetch the key in my layouts file:
Issue, I'm still receiving the error that my api_key is "nil".
  <script>
    var GOOGLE_API_KEY="#{ENV['GOOGLE_API_KEY']}"
  </script>
  <%= javascript_include_tag "//maps.google.com/maps/api/js?v=3.23&key=#{ENV['GOOGLE_API_KEY']}&libraries=geometry,places&language=&hl=&region=&callback=initMap"%>

A: You will want to put the script call in your application.html.erb file so ruby can parse the ENV['google_api']. Here is an example application file (in HAML):
!!!
%html
  %head
    %title Pursuit
    = stylesheet_link_tag 'application', media: 'all'
    = csrf_meta_tags

    :javascript
      var GOOGLE_API_KEY="#{ENV['GOOGLE_API_KEY']}"
    = javascript_include_tag 'application'
    = javascript_include_tag "//maps.googleapis.com/maps/api/js?libraries=places&key=#{ENV['GOOGLE_API_KEY']}"

  %body
    = render 'layouts/menu'
    .row
      .col.m12.l10.offset-l1
        = yield

A: I was using the figaro gem. For me worked adding the environmental variable to  application.yml file.
GOOGLE_API_KEY: there_put_the_key

Then on top of the
app/views/layouts/application.html.erb
(If you want to add source to all of views else you can add this line to specific view) simply add this line
<%= javascript_include_tag "//maps.google.com/maps/api/js?key=#{ENV['GOOGLE_API_KEY']}" %>