text:
Q: Ushahidi - How to make the markers stay on the map on zoom change? I am using the platform Ushahidi Web-2.7.3 , see: http://ti5.net.br/provedorlegal.com.br, and when I zoom in beyond a certain level, the clustered markers disappear from the map. I also tested this on an older version of a site, see: http://movimentofichalimpa.org/mapa, where the clustered markers do not disappear on zooming in, but just become ungrouped, as is normal with a cluster strategy. How can I make the markers remain on the map when zooming in?

A: Ushahidi actually uses OpenLayers under the hood -- the images may come from Google, but the Javascript library is pure OpenLayers. These markers are actually generated by adding what is known as a context to the style attribute of the OpenLayers.Layer.Vector and an associated Cluster.Strategy. There is a good example of it working properly here: OpenLayers cluster example and if you look at the Javascript source you will see how it is done: view-source:http://dev.openlayers.org/releases/OpenLayers-2.13.1/examples/strategy-cluster-threshold.html by defining a radius in the context of the styleMap.
The reason that your example isn't working is that there is actually a script error being triggered, which is stopping the clustering/styling from being performed. The styles are defined in the file ushahidi.js. If you open a Javascript debugger you will see the error for yourself that is firing before the ushahidi.js functions are called to determine the number of features in the cluster and therefore the radius of the markers.
The actual error is http://ti5.net.br/provedorlegal.com.br/index.php/json/cluster?s=1401591600&e=1404183599&z=9, but I have no idea why, as the OpenLayers is the minified version which is very hard to debug. You might find moving your application to OpenLayers directly will help, as it will be easier to debug, and it also works on mobiles, which I know is one of the reasons people like to use Ushahidi.


text:
Q: Squid only cache content for a specific domain and file type. I want to setup Squid to cache specific files (.jpeg) from a specific domain. These files are updated daily. I'm running Ubuntu. I have a script on my laptop that makes use of these files and ideally I would like this script to make calls to the Squid cache instead of directly to the server. I don't want to cache content that is not from the domain and is not of the correct file type. Is this possible, and what do I need to edit in squid.conf ?

A: The proposed solution:
acl filecachetype urlpath_regex \.jpeg
acl cacheDomain dstdomain <your domainname> or acl cacheDomain dst <domain ip>
cache deny !filecachetype !cacheDomain

Will not work. ACLs do AND on the same like so it means that it will only avoid caching when a file is both non-jpeg and not on domain.com. It will still cache:

*

*all files on <your domain>

*all jpeg files on any domain

What you need is:
acl filecachetype urlpath_regex \.jpeg
acl cacheDomain dstdomain <your domainname>
cache deny !filecachetype
cache deny !cacheDomain

This will deny caching files that are not jpeg (no matter where they are, even on your server) and also will deny caching files not on <your domain> (even if they are jpeg). Logical OR, instead of AND.

A: acl filecachetype urlpath_regex \.jpeg
acl cacheDomain dstdomain <your domainname> or acl cacheDomain dst <domain ip>
cache deny !filecachetype !cacheDomain
cache all

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to visuzlize facebook post I have a post id (obtained from the Graph API), can I generate a URL which will display this post in Facebook's interface?
Seems there should be something like http://facebook.com/viewpost?postid=6666666666 ...

A: You want to manually construct a permalink given only the post ID?
The Graph API for a post ID returns the URLs the user should go to to comment on or like the post, assuming the viewing user has permission to do so.
Example:
GET http://graph.facebook.com/19292868552_10150189643478553?access_token={access token here}
Snipped some of the fields of the response, but you're looking for 'actions':
{
  "id": "19292868552_10150189643478553",
  "from": {
    "name": "Facebook Platform",
    "category": "Product/service",
    "id": "19292868552"
  },

  // removed fields from response

  "actions": [
    {
      "name": "Comment",
      "link": "https://www.facebook.com/19292868552/posts/10150189643478553"
    },
    {
      "name": "Like",
      "link": "https://www.facebook.com/19292868552/posts/10150189643478553"
    },
    {
      "name": "Share",
      "link": "http://networkedblogs.com/hGWk3?a=share"
    }
  ],
  // Snipped rest of response

In general, the format of a permalink seems to be:
https://www.facebook.com/{source id}/posts/{post object id}
(Source ID being the user or page ID where the post is)
You can't definitely reply on that URL format always being the same; the API response should be always accurate though


text:
Q: Convert method with loop for, without parameters, into a recursive method I have a working method mostFrequent() with loop 'for', but I need convert it to the same recursive method mostFrequent() without parameters:
public char mostFrequent()
    {
        int maxNum = 0;
        int num = 97;

        for(int i = 0; i < 26; i++)
        {
            maxNum = howMany(num) //do something;
            num++;
        }
        return ...something;
    }

A method howMany(num) is recursive and I don't want to change it. I only need the same method mostFrequent(), recursive, without loops. Thanks.

A: int i = 26;
int num = 97;
public char mostFrequent()
{
    if(i == 0)
        return .. something;
    int maxNum = 0;
    maxNum = howMany(num) //do something;
    num++;
    i--;

    mostFrequent();
}

I did what i could with the information i have, but this is recursive.


text:
Q: PostgreSQL LIKE query on ARRAY field Is there any way to have a Postgres LIKE query on a ARRAY field?
Currently I want something like that:
SELECT * FROM list WHERE lower(array_field) LIKE '1234%'

Currently lower is not needed that much. However it should find ONE matching field inside the ARRAY. Is that even possible?
Currently I use a materialized view to generate the "list" table with a JOIN and a ARRAY_AGG(), since I JOIN a table where more values could be on the right table. Which would duplicate fields on the left table, which is not what I want.
Edit this is how I create the view (really sluggish and ugly):
CREATE MATERIALIZED VIEW article_list_new AS
SELECT a.id,
       a.oa_nr,
       a.date_deleted,
       a.lock,
       a.sds_nr,
       a.kd_art_nr,
       a.kd_art_index,
       a.kd_art_extend,
       a.surface,
       a.execution,
       a.surface_area,
       a.cu_thickness,
       a.endintensity,
       a.drilling,
       array_agg(o.id::text) AS offer_list
FROM article_list a LEFT JOIN task_offer o ON o.article = a.oa_nr
GROUP BY .....;

I also need to return the IDs of the task_offer table.

A: Have you considered the parray_gin extension, also located here?
I haven't used it in production yet, but from what I have seen of it it does what you want against the array.  You can create the relevant index on the materialized view.
However, I would only do that if you are going to have the materialized view anyway.  Otherwise I think @ErwinBrandstetter's answer is better than creating a materialized view only to hold the index.

A: You can use unnest() like @dezso already mentioned, for instance with a LATERAL join (Postgres 9.3+)
SELECT l.*
FROM   list l, unnest(array_field) a  -- implicit lateral
WHERE  lower(a) LIKE '1234%';

You don't need any of this for the presented case. No materialized view at all. This query on the underlying tables is faster, because it can use an index:
SELECT *  -- or selected columns
FROM   article_list a
JOIN   LATERAL  (                      -- only matching IDs
   SELECT array_agg(id) AS offer_list
   FROM   task_offer
   WHERE  article = a.oa_nr            -- LATERAL reference
   AND    id::text ILIKE '1234%'       -- or just LIKE
   ) o ON offer_list IS NOT NULL;

offer_list is an array of the original data type in my result, and contains only matching IDs.
Returns a single row from article_list with an array of matching IDs in task_offer. Add a text_pattern_ops index (for left-anchored matches) to get best read performance:
CREATE INDEX task_offer_foo_idx ON task_offer (article, (id::text) text_pattern_ops);

*

*Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL
Or a trigram index for infix matches (not left-anchored):

*

*How is LIKE implemented?
Or maybe a plain join for selective patterns:
SELECT a.*, o.offer_list -- or selected columns
FROM   article_list a
JOIN   (                          -- only matching IDs
   SELECT article, array_agg(id) AS offer_list
   FROM   task_offer
   WHERE  id::text ILIKE '1234%'  -- or just LIKE
   GROUP  BY 1
   ) o ON o.article = a.oa_nr;

Needs an index on article_list, too. (Which you probably have - no information in the question.) Like:
CREATE INDEX article_list_oa_nr_idx ON article_list (oa_nr);


text:
Q: Prove that the series $\sum_{k=n}^{\infty}a_k$ converges for each positive integer $n$ Suppose that $\sum_{k=1}^{\infty}a_k$ is a convergent series.
Prove that the series $\sum_{k=n}^{\infty}a_k$ converges for each positive integer $n$.
My attempt thus far:
$$\sum_{k=1}^{\infty}a_k -  \sum_{k=1}^{n-1}a_k = \lim_{m\to \infty}  \left(\sum_{k=1}^{m}a_k -  \sum_{k=1}^{n-1}a_k\right)= \lim_{n\to \infty}  \left(\sum_{k=n}^{m}a_k\right) =  \sum_{k=n}^{\infty}a_k$$
But I am not sure how to conclude from here out that it converges. Basically, I don't understand how to wind up this answer.

A: You've noticed that if $m\geq n$ then
$$
\sum_{k=n}^{m}a_k = \sum_{k=1}^{m}a_k - \sum_{k=1}^{n-1}a_k\tag{1}
$$
Recall that we say that the series $\displaystyle\sum_{k=n}^{\infty}a_k$ converges if its sequence of partial sums $\displaystyle\sum_{k=n}^{m}a_k$ (for $m\geq n$) converges. That is to say, if $\displaystyle\lim_{m\to\infty}\displaystyle\sum_{k=n}^{m}a_k$ exists (in $\mathbb{R}$). Now, in view of $(1)$, we have
$$
\lim_{m\to\infty}\sum_{k=n}^{m}a_k = \lim_{m\to\infty}\left(\sum_{k=1}^{m}a_k - \sum_{k=1}^{n-1}a_k\right)\tag{2}
$$
By hypothesis $\displaystyle\lim_{m\to\infty}\sum_{k=1}^{m}a_k$ exists (hence is a real number). The term $\displaystyle\sum_{k=1}^{n-1}a_k$ is a constant (with respect to $m$) finite sum and is also a real number. Finally, we know that, for sequences, "the limit of the sum is equal to the sum of the limits". In particular, when the two separate limits exist (which is the case here), then the limit of the sum exists. Hence, in view of $(2)$, we conclude that the limit $\displaystyle\lim_{m\to\infty}\sum_{k=n}^{m}a_k$ exists. Moreover, you even found an expression for its value in terms of the value of $\displaystyle\lim_{m\to\infty}\sum_{k=1}^{m}a_k$:
\begin{align*}
\lim_{m\to\infty}\sum_{k=n}^{m}a_k &= \lim_{m\to\infty}\sum_{k=1}^{m}a_k - \lim_{m\to\infty} \sum_{k=1}^{n-1}a_k \\
&=\lim_{m\to\infty}\sum_{k=1}^{m}a_k - \sum_{k=1}^{n-1}a_k \tag{3}
\end{align*}
Note that by definition, using the usual notations, $(3)$ merely says that
$$
\sum_{k=n}^{\infty}a_k = \sum_{k=1}^{\infty}a_k - \sum_{k=1}^{n-1}a_k
$$
Note: Your work is correct (except one of your $\displaystyle\lim_{n\to\infty}$ should be $\displaystyle\lim_{m\to\infty}$). You basically started from the end (unless you read from right to left!), but at each stage of your argument you had a valid equality and hence you can conclude that $\displaystyle\sum_{k=n}^{\infty}a_k$ exists and equals $\displaystyle\sum_{k=1}^{\infty}a_k - \sum_{k=1}^{n-1}a_k$. You implicitly used the hypothesis that $\displaystyle\sum_{k=1}^{\infty}a_k$ is convergent when you wrote $\displaystyle\lim_{m\to\infty}\sum_{k=1}^{m}a_k$.

A: Here is a more rigorous proof.
You want to show that,
for any $n > 0$,
$\lim_{m \to \infty} \sum_{k=n}^{m} a_k$
exists.
This means that,
for each $n$,
there is a $L(n)$
such that
$\lim_{m \to \infty} \sum_{k=n}^{m} a_k
=L(n)$.
You aleady know that
$\lim_{m \to \infty} \sum_{k=1}^{m} a_k$
exists.
Call this $L$.
Then, for any $n$ and $m$,
$\sum_{k=n}^{m} a_k
=\sum_{k=1}^{m} a_k-\sum_{k=1}^{n-1} a_k
$.
Therefore,
if we define
$L(n)
=L-\sum_{k=1}^{n-1} a_k
$,
then
$\sum_{k=n}^{m} a_k-L(n)
=\sum_{k=n}^{m} a_k-(L-\sum_{k=1}^{n-1} a_k)
=\sum_{k=1}^{m} a_k-L
$
and we know that
 this latter difference
goes to zero as $m \to \infty$.
Therefore
$\lim_{m \to \infty}\sum_{k=n}^{m} a_k-L(n)
= 0
$.

A: Remember, that in your  $\sum_{k=1}^{\infty}a_k$- $\sum_{k=1}^{\ n-1}a_k$
your first one already converges and left one is just a finite sum, which converges too. So there you go.

A: The really important concept is that convergence or divergence only depends on what happens "near infinity".  Anything that impacts finitely many terms cannot change whether the sum converges or diverges.  If you want to do an $\epsilon - N$ proof, you can use the same $N$ for all of your sums.  Deleting a finite number of terms doesn't change whether the infinite sum converges, it just changes the sum by the sum of the deleted terms.


text:
Q: How do I set up a semi-encrypted Ubuntu installation? You know that Ubuntu installer has an option to encrypt the whole root partition. The password is asked every time you boot.
This seems to be a great deal, easy, convenient, really nice except one thing - I don't think that it is so necessary to encrypt the whole installation. It would be nice to set up separate partitions for private information (like /var and /home) and keep them encrypted while leaving system files (all binaries, mans, etc.) unencrypted. I think it should be nice not so much for performance but for SSD life-time and stability.
So, the password is asked on every boot like it has the whole installation encrypted, but actually only several partitions are encrypted.
Is there a way to set that up smoothly during installation? And what do you think about all that? Please advise.

A: Possibly the easiest way to achieve what you ask is to do an install without encryption and afterwards set up ad hoc encryption on specific folders. The Community documentation suggests encfs for the task. A plugin exists to integrate encfs with Nautilus.
Ecryptfs is an alternative that facilitates the specific encryption of users' home folders.

A: You might also consider moving /home and /var to their own partitions and then just encrypt those; but IMHO the possibility of improved SSD life is negligible, and you will still be prompted to password in at boot for booting requires access to /root.

If you want the SSD to last longer, add more system RAM and do without swap. That's what I did and it works well for me.


text:
Q: How do I add months to a CURRENT_TIMESTAMP in SQL? How can I add months to the CURRENT_TIMESTAMP in SQL Server?
The solution probably lies in DATEADD() but this works with a date only, not a datetime.
Thanks.

A: The Current_Timestamp is the ansi equivalent of GetDate() in SQL, so it is perfetly acceptable to use within a DateAdd function.
select dateadd(m,3,current_timestamp)

Adds 3 months to the current timestamp.

A: This works perfectly fine
SELECT DATEADD(month,1,CURRENT_TIMESTAMP)

From DATEADD (Transact-SQL)

date
Is an expression that can be
  resolved to a time, date,
  smalldatetime, datetime, datetime2, or
  datetimeoffset value.

A: add_months(Tablename,No.of months)


text:
Q: Where is array's length property defined? We can determine the length of an ArrayList<E> using its public method size(), like
ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();

Similarly we can determine the length of an Array object using the length property
String[] str = new String[10];
int size =  str.length;

Whereas the size() method of ArrayList is defined inside the ArrayList class, where is this length property of Array defined?

A: it's public final field , which contains the number of components of the array (length may be positive or zero)
An array thus has the same public fields and methods as the following class:
class A implements Cloneable, java.io.Serializable {
    public final int length = X;
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e.getMessage());
        }
    }
}

more info at
10.7 Array Members
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html

A: Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members
The members of an array type are all of the following:

*

*The public final field length, which contains the number of components of the array. length may be positive or zero.

*The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

*All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

*

*JLS - Arrays

A: To answer it as it-is, where is this length property of array defined? In a special Object header.
Easy to see via JOL
 int [] ints = new int[23];
 System.out.println(ClassLayout.parseInstance(ints).toPrintable());

One of the lines from this output is going to be:
OFFSET  SIZE      TYPE DESCRIPTION
16       4        (object header)   17 00 00 00 (00010111 00000000 00000000 00000000) (23)

Usually Objects have two headers (mark and klass), arrays have one more that always occupy 4 bytes in length, as size is an int.

A: It's defined in the Java language specification:

The members of an array type are all of the following:

*

*The public final field length, which contains the number of components of the array. length may be positive or zero.

Since there is a limitless number of array types (for every class there is a corresponding array type, and then there are multidimensional arrays), they cannot be implemented in a class file; the JVM has to do it on the fly.

A: Even though this is not a direct answer to the question, it is an addition to the .length vs .size() argument. I was researching something related to this question so when I came across it I noticed that the definition(s) provided here

The public final field length, which contains the number of components of the array.

is not "exactly" correct.
The field length contains the number of available places to put a component, not the number of components present in the array. So it represents the total available memory allocated to that array, not how much of that memory is filled.

Example:
static class StuffClass {
    int stuff;
    StuffClass(int stuff) {
        this.stuff = stuff;
    }
}

public static void main(String[] args) {

    int[] test = new int[5];
    test[0] = 2;
    test[1] = 33;
    System.out.println("Length of int[]:\t" + test.length);

    String[] test2 = new String[5];
    test2[0] = "2";
    test2[1] = "33";
    System.out.println("Length of String[]:\t" + test2.length);

    StuffClass[] test3 = new StuffClass[5];
    test3[0] = new StuffClass(2);
    test3[1] = new StuffClass(33);
    System.out.println("Length of StuffClass[]:\t" + test3.length);
}

Output:
Length of int[]:        5
Length of String[]:     5
Length of StuffClass[]: 5

However, the .size() property of the ArrayList does give the number of elements in the list:
ArrayList<Integer> intsList = new ArrayList<Integer>();
System.out.println("List size:\t" + intsList.size());
intsList.add(2);
System.out.println("List size:\t" + intsList.size());
intsList.add(33);
System.out.println("List size:\t" + intsList.size());

Output:
List size:  0
List size:  1
List size:  2

A: It's "special" basically, with its own bytecode instruction: arraylength. So this method:
public static void main(String[] args) {
    int x = args.length;
}

is compiled into bytecode like this:
public static void main(java.lang.String[]);
  Code:
   0:   aload_0
   1:   arraylength
   2:   istore_1
   3:   return

So it's not accessed as if it were a normal field. Indeed, if you try to get it as if it were a normal field, like this, it fails:
// Fails...
Field field = args.getClass().getField("length");
System.out.println(field.get(args));

So unfortunately, the JLS description of each array type having a public final field length is somewhat misleading :(

A: The keyword length acts like a data filed defined. When using in an array, we can use it to access how many elements in an array. Regarding to String[], we can invoke length() method defined in String class. With regard to ArrayList, we can use size() method defined in ArrayList. Note that when creating an array list with ArrayList<>(capacity), the initial size() of this array list is zero since there is no element.


text:
Q: dropdown menu doesn't show when i hover

#menu {
 overflow: hidden;
 background: #202020;
}

#menu ul {
 margin: 0px 0px 0px 0px;
 padding: 0px 0px;
 list-style: none;
 line-height: normal;
 text-align: center;
}

#menu li {
 display: inline-block;
}

#menu a {
 display: block;
 position: relative;
 padding: 0px 100px 0px 40px;
 line-height: 70px;
 letter-spacing: 2px;
 text-decoration: none;
 text-transform: uppercase;
 text-align: center;
 font-family: 'Varela Round', sans-serif;
 font-size: 13px;
 color: rgba(255,255,255,0.5);
 border: none;
}

/* Dropdown Content (Hidden by Default) */
#menu .dropdown-container{
 position: relative;
}
#menu .dropdown {
 position: relative;
 display: inline-block;

  }
#menu .dropdown-content {
 position: absolute;
 display: none;
 background-color: #202020;
 min-width: 160px;
 z-index: 9999;
 box-shadow: 0px 8px 16px 0px rgba(255,255,255,0.5);
  }

  /* Links inside the dropdown */
#menu .dropdown-cotainter a {
 color: rgba(255,255,255,0.5);
 padding: 3px;
 position: relative;
 text-decoration: none;
 display: Block;
 z-index: 9999;
  }

  /* Change color of dropdown links on hover */
#menu .dropdown-content a:hover {color: #ddd;}

  /* Show the dropdown menu on hover */
#menu .dropdown:hover .dropdown-content {
 display: block;
 z-index: 9999;
}
import React from 'react';
import {
  Link
} from 'react-router-dom';

function Header() {
  return (

<Link to="/">Homepage</Link>

              Services

                  Link 1
                  Link 2
                  Link 3

<Link to="/AboutUs">About Us</Link>

<Link to="/ContactUs">Contact Us</Link>

  );
}

export default Header;

when i hover on the link i can see a part of the menu showing but not all of it, i think it's because the container is covering it but i don't know how to make the menu independant or above the container to be shown. I tried to change position to absolute but it still doesn't work. can someone help me out :D

A: if you remove overflow: hidden your code works.
#menu {
    overflow: hidden; //remove this line
    background: #202020;
}


text:
Q: Export multiples modules in next.config.js : next-images I need to export more than 1 module in my next.config.js file.
Now my file is like this:
const nextTranslate = require("next-translate");
module.exports = { ...nextTranslate() };

And i need to put this too:
   const withImages = require('next-images')
   module.exports = withImages()

A: next-compose-plugins is a great way to keep your next.config.js file clean
https://github.com/cyrilwanner/next-compose-plugins
example:
const withPlugins = require('next-compose-plugins');
const sass = require('@zeit/next-sass');

module.exports = withPlugins([
  [sass],
]);

As it relates to you:
const nextTranslate = require("next-translate");
const withImages = require("next-images");
const withPlugins = require("next-compose-plugins");

module.exports = withPlugins([
withImages,
nextTranslate
], { other configs here that aren't plugins })

I'm not sure about the shape of nextTranslate, but that's the gist of it.


text:
Q: Simulink Error: The overall system has unobservable mode in z=1 I am using simulink to model a process with time delay, compensators and MPC controller.
Problem is when I hit the Simulate button I get this error:
MPC: Utility: Kalman1, Message = Problems encountered when designing the overall state observer(Kalman Filter).
The overall system has unobservable modes in z=1
The overall system Transfer Function is:
     0.2713 z^4 - 1.755 z^3 + 4.05 z^2 - 3.919 z + 1.353
--------------------------------------------------------------
  z^7 - 6.21 z^6 + 11.57 z^5 - 3.192 z^4 - 8.476 z^3 + 5.311 z^2

Can anyone help with this error?
Thanks


text:
Q: What is different between maximal cyclic subgroup with cyclic maximal subgroup? What is different between  "maximal cyclic subgroup" with "cyclic maximal subgroup"?
Are these are equal or different?(example?)

A: A maximal cyclic subgroup is a cyclic subgroup that is maximal among all cyclic subgroups. That is there is no other cyclic subgroup that would contain it while there might be other non-cyclic subgroups that are larger.
A cyclic maximal subgroup is a maximal subgroup (among all subgroups) that is cyclic. That is it is a maximal subgroup that happens to be cyclic.
I think this is the default reading, but I would not rely on everybody using or understanding it in this way.
Note that a cyclic maximal subgroup is always a maximal cyclic subgroup but the converse might not be true.

*

*In the additive group  $\mathbb{Z}/p^2\mathbb{Z} \times \mathbb{Z}/p^3\mathbb{Z} $.
The subgroup $ \{0 \} \times \mathbb{Z}/p^3\mathbb{Z}$ is a maximal cyclic subgroup, yet not a maximal subgroup and thus not a cyclic maximal subgroup either.

*In the additive group  $\mathbb{Z}/p\mathbb{Z} \times \mathbb{Z}/p^3\mathbb{Z} $.
The subgroup $ \{0 \} \times \mathbb{Z}/p^3\mathbb{Z}$ is a maximal cyclic subgroup, and also a maximal subgroup and thus a cyclic maximal subgroup.


text:
Q: Question about the difference between WLLN and SLLN? Let $X, X1,X_2,\cdots$ be i.i.d random.variables. Check if the WLLN and the SLLN hold if the common d.f. is given by,
(1)$P(X=n)=P(X=-n)=\frac{C}{2n^2ln^2(n)}$, $n \geq 3$
(2)$P(X=n)=P(X=-n)=\frac{C}{2n^2ln(n)}$, $n \geq 3$
(3)At this time, $X_i$ are independent though not identical. Let $P(X_1=0)=P(X_2=0)=1$ and $P(X=n)=P(X=-n)=\frac{1}{2nln(n)}$,$P(X_n=0)=1-\frac{1}{nln(n)}$, $n \geq 3$  (Hint:This sequence obeys the WLLN but not the SLLN)
Solution:
According to the SLLN:  Let $X_1,X_2,\cdots$ be pairwise independent with identically distributed random variables with $E|X_i|<\infty$. Let $E(X_1)=u$ and $S_n=X_1+X_2+\cdots+X_n$. Then, $S_n/n \rightarrow u$ as $n\rightarrow \infty$
According to the WLLN:  Let $X_1,X_2,\cdots$ be i.i.d with $E|X_i|<\infty$. Let $E(X_1)=u$ and $S_n=X_1+X_2+\cdots+X_n$. Then, $S_n/n \rightarrow u$ as $n\rightarrow \infty$
As for the question (1):
$E(X_i)=\sum_{k\geq 3}\frac{C}{2k^2ln^2(k)}k+\sum_{k\leq -3}\frac{C}{2k^2ln^2(k)}k=0$
$E|X_i|=\sum_{k\geq 3}\frac{C}{2k^2ln^2(k)}|k|+\sum_{k\leq -3}\frac{C}{2k^2ln^2(k)}|k|=2\sum_{k\geq 3}\frac{C}{2k^2ln^2(k)}|k|=\sum_{k\geq 3}\frac{C}{2k  ln^2(k)}=\infty$
It seems that (1) does not satisfy both WLLN and SLLN. Since $E|X_i|=\infty$\
As for the question (2):
$E(X_i)=\sum_{k\geq 3}\frac{C}{2k^2ln(k)}k+\sum_{k\leq -3}\frac{C}{2k^2ln(k)}k=0$
$E|X_i|=\sum_{k\geq 3}\frac{C}{2k^2ln(k)}|k|+\sum_{k\leq -3}\frac{C}{2k^2ln(k)}|k|=2\sum_{k\geq 3}\frac{C}{2k^2ln(k)}|k|=\sum_{k\geq 3}\frac{C}{2k  ln(k)}=\infty$
It seems that (2) does not satisfy both WLLN and SLLN. Since $E|X_i|=\infty$\
What is the difference between the condition of WLLN and SLLN? Can the statement satisfy the WLLN, though not satisfy SLLN?  Or can the statement satisfies the SLLN, though not satisfy WLLN? For me, the conditions for these two are the same.
Thanks a lot!

A: This is the standard example of a sequence that satisfies the hypotheses of WLLN but not of SLLN, so you are correct. Also note that WLLN says something about convergence in probability, while SLLN says something about convergence almost surely, which is stronger.
If the hypotheses of SLLN would always be satisfied if those of WLLN are satisfied, WLLN would be a useless result after all. This exercise shows that this needs not be the case.

A: Sequence (1) satisfy WLLN and SLLN since i.i.d.r.v's satisfy $\mathbb E[|X|]<\infty$.
Consider sequence (2). Since $\mathbb E[|X|]=\infty$, SLLN is not fulfilled.
This is a consequence of the SLLN:

Let $X_1,X_2,\ldots$ be i.i.d. and $S_n=X_1+\ldots+X_n$. Then $\frac{S_n}{n}\to a$ a.s. iff exists $\mathbb E[X_1]=a$.

And the WLLN can be fulfilled. You can find the following theorem in W.Feller's book "An Introduction to Probability Theory and its Applications", in Vol.2, Chapter VII, paragraph 7:

Theorem. Let $X_1,X_2,\ldots$ be independent with a common distribution $F$. In order that there exist constants $\mu_n$ such that for each $\epsilon>0$
$$\mathbb P\left(\left|\frac{S_n}{n}-\mu_n\right|>\epsilon\right)\to 0\tag{1}$$
  it is necessary and sufficient that
  $$n \mathbb P(|X_1|\geqslant n)\to 0 \text{ at } n\to\infty. \tag{2}$$
  In this case (1) holds with
  $$\mu_n =\mathbb E[X_1\mathbb 1_{\{|X_1|\leq n\}}].$$

Since our r.v.'s have symmetric distribution, we can take $\mu_n=\mu=0$ and check only (2).
$$
n \mathbb P(|X_1|\geqslant n) = n\sum_n^\infty \frac{C}{k^2 \ln k}\leqslant \frac{n}{\ln n}\sum_n^\infty \frac{C}{k^2} \sim \frac{n}{\ln n} \int_n^\infty \frac{C}{x^2}dx = \frac{C}{\ln n}\to 0.
$$
Therefore WLLN fulfilled.
For (3) both WLLN and SLLN are not fulfilled. You can check it by the same way. Note that the values $X_3,X_4,\ldots $ are i.i.d. so you can apply both theorems. $X_1$ and $X_2$ don't matter.


text:
Q: Loading data from the datasets package in knitr I'm using the following code in knitr
```{r,results='markup'}
library(datasets)
toothgrowth = data(ToothGrowth)
summary(toothgrowth)
toothgrowth
```

When I run the code directly in RStudio, the data is loaded just fine. But when I generate the HTML, the data set is just one element:
summary(toothgrowth)
Length     Class      Mode
     1 character character

I'm new to R and this could be something silly, but I cannot figure out what's going on with knitr. Can someone help please?

A: Your problem is your use of data(). According to ?data, the function will return "A character vector of all data sets specified, or information about all available data sets in an object of class..." rather than the dataset itself. Calling summary() directly on ToothGrowth will suffice.


text:
Q: Conditional Batch file renaming with mysql data I wonder if anyone knows how could I rename multiple files, all of them originally named with same structure, and add some data extracted from a mysql DB according to specifics rules.
For example I have 500 files named with this vars:
ID NAME ADDRESS PHONE.wav => 1234567 PAULSIMON WESTDR122 9942213456.wav
Now I need to rename files taking some data from the databases for each file, and
append the data from a query appended to the filename.
For example add the data resulting from a query Where some conditions match,
and the data to build the query is taked from original file name, as ID or NAME.
i other words, lets say that I want to build a query taking ID & NAME from file
1234567 PAULSIMON WESTDR123 9942213456.wav as WHERE statements to take another value
as BirthDATE and add this to new filename, so final result should be:
ID NAME ADDRESS PHONE BIRTHDATE.wav
I will appreciate any help on this.
I need this to be done on a LINUX server.

A: #!/bin/sh

# adjust this to your actual database name
# also some tweaks will be needed if you use mysql login/password authentication
DB_NAME=my_db_name

IFS=$'\x0d\x0a'
FNAMES=`find . -name "*.wav" -printf '%P\n'`
for FNAME in $FNAMES; do
    echo "[.] file $FNAME"
    ID=`echo $FNAME | awk '{print $1}'`
    NAME=`echo $FNAME | awk '{print $2}'`
    echo "[.] id=$ID name=$NAME"
    # adjust query at next line to your needs
    Q=`mysql $DB_NAME --skip-column-names -Be "SELECT birthdate FROM users WHERE id='$ID' AND name='$NAME' LIMIT 1"`
    echo "[.] mysql returned $Q"
    if [ "$Q" != "" ]; then
        echo renaming "$FNAME"  TO  "${FNAME%.wav} $Q.wav"
        # uncomment next line to do actual rename
        #mv "$FNAME" "${FNAME%.wav} $Q.wav"
    fi
    echo
done


text:
Q: Perl Win32::Console error My little Perl script on Windows tried to call a dependency library C:/strawberry/perl/vendor/lib/Term/ReadPassword/Win32.pm which was written by somebody else.
Here is a part of C:/strawberry/perl/vendor/lib/Term/ReadPassword/Win32.pm:
package Term::ReadPassword::Win32;
use strict;

if (IsWin32()) {
  eval('use Win32');
  eval('use Win32::Console');
  eval('use Win32API::File');
} else {
  eval('use Term::ReadPassword');
}

...

my $CONIN = new Win32::Console(Win32::Console::STD_INPUT_HANDLE());
my $CONOUT = new Win32::Console(Win32::Console::STD_ERROR_HANDLE());
...

The following error showed up when running my script:
Undefined subroutine &Win32::Console::STD_INPUT_HANDLE called at C:/strawberry/perl/vendor/lib/Term/ReadPassword/Win32.pm line 58, <STDIN> line 2.

Using parens is legit, as discussed How can I optionally use Win32::Console and its constants in a cross platform way? and I've looked up http://metacpan.org/pod/Win32::Console.
Thanks.

A: eval('use Win32::Console');

doesn't do any error checking.  If Win32::Console fails to load for any reason, the code will proceed anyway until it actually calls one of the subroutines that was supposed to have been loaded, but wasn't.  At that point, you'll get failures like you describe.
What happens if you add use Win32::Console; to your script?  (I'm guessing you'll get some kind of error saying Win32::Console couldn't be loaded.)


text:
Q: Ionic 2 File Plugin usage examples Does anyone have complete examples about how to use the Cordova Native File Plugin in a Ionic 2/Angular 2 project?
I installed this plugin but the documentation don't seems to make much sense to me due the fact it is fragmented and lacks of a complete example, including all needed imports.
For example, the following example don't shows where objects like LocalFileSystem or window came from.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {

    console.log('file system open: ' + fs.name);
    fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {

        console.log("fileEntry is file?" + fileEntry.isFile.toString());
        // fileEntry.name == 'someFile.txt'
        // fileEntry.fullPath == '/someFile.txt'
        writeFile(fileEntry, null);

    }, onErrorCreateFile);

}, onErrorLoadFs);

For example, I need to crate a property file. First I need to check if a file exists on app sandbox storage area, if don't exists I must create it. Then I must open the file write data and save it . How could I do that?

A: Ionic 2 comes with a Cordova file plugin wrapper:
http://ionicframework.com/docs/v2/native/file/.
The necessary file system paths (e.g. cordova.file.applicationDirectory) you can find here at the documentation of the original plugin:
https://github.com/apache/cordova-plugin-file#where-to-store-files. Note that not all platforms support the same storage paths.
I even managed to build a file browser with it. Use it like so:
import {Component} from '@angular/core';
import {File} from 'ionic-native';

...

File.listDir(cordova.file.applicationDirectory, 'mySubFolder/mySubSubFolder').then(
  (files) => {
    // do something
  }
).catch(
  (err) => {
    // do something
  }
);

A: Here is an example using IonicNative for an app I am working on where I want
to send an email with a csv file attachment.

import {EmailComposer} from '@ionic-native/email-composer';
import {File} from '@ionic-native/file';

class MyComponent {
 constructor(private emailComposer: EmailComposer, private file: File) {

 }
 testEmail() {
 this.file.writeFile(this.file.dataDirectory, 'test.csv', 'hello,world,', {replace: true})
     .then(() => {
       let email = {
         to: 'email@email',
         attachments: [
           this.file.dataDirectory + 'test.csv'
         ],

         subject: 'subject',
         body: 'body text...',
         isHtml: true
       };
       this.emailComposer.open(email);

     })
     .catch((err) => {
       console.error(err);
     });

 }
}

This was tested with ionic 3.7.0 on IOS.


text:
Q: Can't play this video because of VideoView error I'm trying to play a video as a splash screen in my Android app.
I've searched for a lot of tutorials and responser regarding problems with VideoView but I don't know what to do anymore...
I tried using hardcoded link to my sdcard (/sdcard/filename.mp4), I tried using Environment.getExternalStorageDirectory(), also I tried using a video from folder inside my app (R.raw.filename) and nothing seems to be working. I get either a black screen or a message that I can't play this video...
For every method I tried using various video formats (all of them supported by Android)
Here is my Java code:
package com.example.android;

import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;

public class SplashScreen extends Activity implements OnClickListener {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_splash);

    String path = Environment.getExternalStorageDirectory() + "/splash.mp4";
    VideoView vid =(VideoView)findViewById(R.id.videoView1);
    vid.setVideoURI(Uri.parse(path));
    vid.setMediaController(new MediaController(this));
    vid.start();
    vid.requestFocus();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.pocetna, menu);
    return true;
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_splash,
                container, false);
        return rootView;
    }

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

And my XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<VideoView
    android:id="@+id/videoView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>

A: Adding this in the manifest worked for me:
android.permission.READ_EXTERNAL_STORAGE

A: I`m not sure but could It be possible that you need instead of
vid.setVideoURI(Uri.parse(path));
vid.setVideoPath("/sdcard/splash.mp4");?
Or maybe you find there the answer: Playing a video in VideoView in Android


text:
Q: MySQL Query Select where id does not exist in the JOIN table I wanna know a single MySQL query for solving this problem:
I have a table that consists of member ids and location ids..

_________________________________________________________
|      |                        |                        |
| ID   |  Member Id             |       Location         |
|______|________________________|________________________|
|      |                        |                        |
| 1    |    2371                |           7            |
|      |                        |                        |
| 2    |    5123                |          10            |
|      |                        |                        |
| 3    |    2371                |           9            |
|      |                        |                        |
| 4    |    5123                |           9            |
|      |                        |                        |
| 5    |     565                |           9            |
|      |                        |                        |
| 6    |    2371                |           5            |
|      |                        |                        |
| 7    |    5123                |           6            |
|      |                        |                        |
|______|________________________|________________________|

Another table consists of all the locations data:

__________________________________________________
|                        |                        |
|  Location Id           |       Location Name    |
|________________________|________________________|
|                        |                        |
|      1                 |           ABC          |
|                        |                        |
|      2                 |           BCD          |
|                        |                        |
|      3                 |           CDE          |
|                        |                        |
|      4                 |           DEF          |
|                        |                        |
|      5                 |           EFG          |
|                        |                        |
|      6                 |           GHI          |
|                        |                        |
|      7                 |           HIJ          |
|                        |                        |
|      8                 |           IJK          |
|                        |                        |
|      9                 |           JKL          |
|________________________|________________________|

I wanna find all location ids from the table where member id 2371 is not present. How can I find this in single query? I know I can do it if I break the query into two pieces.. Like array of all locations.. and array of all locations where member id exist. Then using !in_array function of PHP
Thanks for your time and help in advance.

A: You can find all locations that member 2371 is in by doing:
SELECT location
FROM memberlocation
WHERE memberid = 2371

You can find all other locations (the ones you want) by:
SELECT *
FROM location
WHERE locationid NOT IN
    ( SELECT location
      FROM memberlocation
      WHERE memberid = 2371)

A: You could use the following join query to filter the results by MemberID:
SELECT l.LocationName FROM MemberLocations AS ml
INNER JOIN Locations AS l ON ml.Location = l.LocationID
WHERE ml.MemberID != 2371


text:
Q: Evaluating $\int_{0}^{x}\frac{\arctan(t)}{t}dt-\int_{0}^{\frac{1}{x}}\frac{\arctan(t)}{t}dt$ The paper here https://www.imsc.res.in/~rao/ramanujan/collectedpapers/Integral/Integral1.htm says that, $\int_{0}^{x}\frac{\arctan(t)}{t}dt-\int_{0}^{\frac{1}{x}}\frac{\arctan(t)}{t}dt=\frac{1}{2}\pi\ln(x)$
I tried verifying this result graphically using Desmos. But the graph seems oddly off. It looks like the answer must be $\pi\ln(x)$ and not $\frac{1}{2}\pi\ln(x)$.

Any help ? Thanks :)

A: Hint. You may differentiate the function given by
$$
f(x)=\int_{0}^{x}\frac{\arctan(t)}{t}dt-\int_{0}^{\frac{1}{x}}\frac{\arctan(t)}{t}dt, \qquad x>0,
$$ obtaining
$$
f'(x)=\frac{\arctan(x)}{x}-\left(-\frac1{x^2} \right)\frac{\arctan(\frac1x)}{\frac1x}=\frac{\arctan(x)+\arctan(\frac1x)}{x}, \quad x>0,
$$ then one may recall that
$$
\arctan x+\arctan\frac1x=\frac \pi2,\qquad x>0,
$$that is
$$
f'(x)=\frac \pi2 \: \frac1x, \quad x>0.
$$Observe that $f(1)=0$.
I hope you can take it from here.
The case $x<0$ is similar.


text:
Q: AWK and matrices handling Good day,
I was wondering how to handle (in awk) a square and symmetric matrix to do:

*

*Identify the row with only zeros.

*Delete that row and its symmetric column.

*Print the resultant matrix.

Input
  1234567
 xabcdefg
1a0101101
2b1010001
3c0101001
4d1010101
5e1001000
6f0000000
7g1111000

Expected output Sixth row and column deleted
  123457
 xabcdeg
1a010111
2b101001
3c010101
4d101011
5e100100
7g111100

Thanks in advance for any clue

A: this line should work:
awk  'BEGIN{FS=OFS=""}NR==FNR{if(/^0+$/)z[NR];next}
                      !(FNR in z){for(x in z)$x="";print}' file file

test:
kent$  cat f
0101101
1010001
0101001
1010101
1001000
0000000
1111000

kent$  awk  'BEGIN{FS=OFS=""}NR==FNR{if(/^0+$/)z[NR];next}!(FNR in z){for(x in z)$x="";print}' f f
010111
101001
010101
101011
100100
111100

it works for multiple "all-zero" rows too:
kent$  cat f
00001
00000
00000
00000
10000

kent$  awk  'BEGIN{FS=OFS=""}NR==FNR{if(/^0+$/)z[NR];next}!(FNR in z){for(x in z)$x="";print}' f f
01
10

A: $ awk '{row[NR]=$0} $0=='0000000' {bad=NR} END{for (i=1;i<=NR;i=i+1+(i==bad-1)) {print substr(row[i],1,bad-1) substr(row[i],bad+1)}}' input
010111
101001
010101
101011
100100
111100


text:
Q: How to access specific json data PHP Good day,
I'm fetching my data directly from and API endpoint. I was able to get the id but how can I access "type":"participant", specifically the skillTier?
Here's my code but it's throwing an error: NOTICE: UNDEFINED INDEX: SKILLTIER IN C:\XAMPP\HTDOCS\VGAPP\INDEX.PHP ON LINE 219
if(is_array($finaljson) || is_object($finaljson)){
if(!empty($finaljson['included']) && $finaljson['included'] !== ""){
    foreach ($finaljson['included'] as $key => $value) {
        if(!empty($value['attributes']['name']) && $value['attributes']['name'] === $username){
            $userid = $value['id'];
            $skillTier = $value['skillTier'];
        }
    }

Here is the json data:
https://gist.github.com/kamaelxiii/18ef0c1600330b98717b96db00532d6a

A: As the same way that you've accessed the $value['attributes']['name'] , it's multi-dimensional array , so think about it as a town , and you want to arrive to flat number 6 which is at building 9 , which is located at street number 4 , you will not be able to ask somebody to tell you where is flat 6 without telling the full address , so in your case , you simply can achieve your skillTier index when only you provide your variable with the full address of your index , as follows :
$value['attributes']['stats]['skillTier']

A: foreach($finaljson['included'] as $included) {
  if($included['type'] == 'participant'){
    $userid = $included['id'];
    $skillTier = $included['attributes']['stats']['skillTier'];
   }
}

A: First of all you have 2 PHP syntax errors where you have two missing }'s to close off your first ifstatement and foreach loop.
Also you want to loop your included nodes and check if you have a participant object before continuing since the other items don't have the skillTier value. Also best practice to check if the skilltier isn't empty before trying to save it in a variable.
This is the updated version of your code:
if(is_array($finaljson) || is_object($finaljson)) {
    foreach($finaljson['included'] as $included) {
        if($included['type'] === 'participant') {
            if(!empty($included['attributes']['stats']['skillTier'])){
                $id = $included['id'];
                $skillTier = $included['attributes']['stats']['skillTier'];
            }

        }
    }
}

Here is a working example with your JSON that will var_dump the ID's and skilltier. http://ideone.com/DrXWe7 (click fork to see the code)

A: It is patient work to whittle down a big json / array to target and isolate your desired data.  You just need to traverse the structure step-by-step, print each level's data to screen, and identify the keys that hold what you want.
Code:
$array = json_decode($json, true);
foreach ($array['included'] as $included) {  // iterate all children of "included"
    if ($included['type'] === 'participant') {  // only access "participant" subset data
        $result[$included['id']] = $included['attributes']['stats']['skillTier'];  // access the skillTier data which is beneath "stats" beneath "attributes"
    }
}
echo "<pre>";
var_export($result);
echo "</pre>";

Output:
array (
  '4cfe4736-f47b-11e6-b633-0242ac110030' => 16,
  '4cfe473f-f47b-11e6-b633-0242ac110030' => 10,
  '4cfe4727-f47b-11e6-b633-0242ac110030' => 27,
  'd4003883-f423-11e6-865e-0242ac110008' => 23,
  'd4003869-f423-11e6-865e-0242ac110008' => 24,
  'd400387a-f423-11e6-865e-0242ac110008' => 23,
  '4cfe471f-f47b-11e6-b633-0242ac110030' => 27,
  'd400386d-f423-11e6-865e-0242ac110008' => 24,
  'd4003887-f423-11e6-865e-0242ac110008' => 23,
  '4cfe4724-f47b-11e6-b633-0242ac110030' => 24,
  'd4003864-f423-11e6-865e-0242ac110008' => 18,
  '4cfe473b-f47b-11e6-b633-0242ac110030' => 17,
)


text:
Q: jQuery clone input table with latest user inputs I am trying to re-use an input table. My idea is to save the final state of an input table using jquery and then add it to the output page. However, my code only saves the default inputs, which means any changes made by user will not be saved. So any suggestions on this issue? For example, how to let the drop-down input element save user selection using jquery (I have about 100 input elements, so it will be nice if the code is very generic). Thanks!
HTML code:

            No. of Time-Varing Factors:

            <select name="nott" id="id_nott">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>

<input class="submit input_button" type="button" value="Click" />

jQuery:
$("input[value='Click']").click(function () {
    var html_input = $(".tab").clone().html();
    console.log(html_input)
})

JSFiddle

A: DEMO
http://api.jquery.com/serialize/ -- simple way to get and deliver state of your inputs, but you have to wrap html in form tag.
$("input[value='Click']").click(function (){
    $("form").on( "submit", function (event){
      event.preventDefault();
      console.log($(this).serialize());
    });
});

output:
nott=2

recommendation:
Try to use a conventional naming for id and name attributes.


text:
Q: Is there any way to rename 'set' While trying to rename the set function,
I got the error too many nested evaluations (infinite loop?) (see below).
Perhaps because rename uses set internally. Is there any way to override this behaviour?
rename set Set
too many nested evaluations (infinite loop?)
    while executing
"set cmd [lindex $args 0]"
    (procedure "::unknown" line 8)
    invoked from within
"set cmd [lindex $args 0]"
    (procedure "::unknown" line 8)
    invoked from within
"set cmd [lindex $args 0]"
    procedure "::unknown" line 8
    ...

A: The rename command is a built-in command of Tcl, and does not depend on any other commands. However, the interactive evaluation loop does use set quite a bit in its history management code, as does the unknown command which handles what to do when a command name is not resolved to an existing command. That triggers an infinite loop as handling what to do when set is absent requires set to be present as part of the handling code; the stack protection code (see interp recursionlimit) eventually kills things off…
The simplest fix is to make sure that you keep something in place called set.
# Make our replacement
proc replacement_set {varName {value ""}} {
    # This is 8.6-specific code, but you can do other equivalent things
    tailcall old_set {*}[lrange [info level 0] 1 end]
}

# Swap things in, with both renames on the same line...
rename set old_set; rename replacement_set set

Note that you don't need to be quite as careful in a script.


text:
Q: Herencia en Java - Al llamar a un constructor se salta el contenido de este mismo y va a otro? No entiendo porque en el constructor de C al acabar de llamar al constructor de A con un parámetro, este en vez imprimir por pantalla "Soy el constructor C" va directamente a instanciar un objeto de B y accede a su constructor, en vez de decir "Soy el contructor C" primero antes que "Soy el contructor B". No entiendo por qué?
class A {
    public A ( ) {  System.out.println(" Soy el constructor A");    }
    public A (int a) {
        System.out.println(" Soy el constructor A " + a);
    }
}

class B {
    public B ( ) {  System.out.println(" Soy el constructor B");    }
    /*public B (int b) {
        System.out.println(" Soy el constructor B " + b);
    }*/
}

class C extends A {
    public C ( ) {
        super(1);
        System.out.println(" Soy el constructor C");
    }
    B ob= new B();
}

public class ex6b_2 {
    public static void main ( String args[] ) {
        C oc= new C();
    }
}

A: La creación del objeto ob, aunque es parte de la construcción del objeto, no está escrita dentro de tu constructor, sino que es un campo con un valor default que también se crea durante el proceso de construcción de tu instancia.
Solo para tener mayor claridad, otra forma de escribir la clase C sería esta:
class C extends A {
    public B ob = new B();

    public C ( ) {
        super(1);
        System.out.println(" Soy el constructor C");
    }
}

Que produce exactamente el mismo resultado en todos los sentidos. La representación en memoria de los objetos es la misma y la salida producida por el programa también, simplemente queda claro que new B() no es una parte de código explicitamente escrita en el constructor.
Y ocurre que en Java, todos los campos que están declarados en una clase, son creados cuándo se termina de construir la parte del objeto que se ha heredado y antes que se ejecute la primera línea del constructor, dado que este ya tiene acceso a los valores de estos campos.
Para probar esto, he extendido un poco tu ejemplo, creando una clase PreA que ahora es ancestro de A y un par de clases auxiliares, de esta forma puedes observar el orden en el que se van creando los objetos en memoria a medida que se construye la instancia de C:
public class So287592 {
    public static void main ( String args[] ) {
        C oc= new C();
    }
}

class PreA {
  public PreA() { System.out.println(" Soy el constructor PreA"); }

}
class A extends PreA {
    public B1 ob1 = new B1();
    public A ( ) {  System.out.println(" Soy el constructor A");    }
    public A (int a) {
        System.out.println(" Soy el constructor A " + a);
    }
}

class B {
    public B ( ) {  System.out.println(" Soy el constructor B");    }
}

class B1 {
    public B1 ( ) {  System.out.println(" Soy el constructor B1");    }
}

class C extends A {
    public B ob = new B();
    public C ( ) {
        super(1);
        System.out.println(" Soy el constructor C");
    }
}

Esto produce la siguiente salida:
 Soy el constructor PreA
 Soy el constructor B1
 Soy el constructor A 1
 Soy el constructor B
 Soy el constructor C

Como ves, primero se ejecuta el constructor de PreA, luego, se crean los campos declarados en A y dado que ob1 tiene como default una nueva instancia de B1, se invoca en constructor de esta clase, antes de ejecutar el código del constructor de A.
Luego, se ejecuta el código del constructor de A, y cuando se termina de construir esta parte del objeto, se crean los campos declarados en C. Esto implica, de manera análoga, la creación del objeto ob, por lo que se invoca al constructor de B.
Finalmente, se ejecuta el código específico del constructor de C, que ya tiene acceso a todos los campos de la clase, incluidas las instancias creadas para los miembros ob y ob1

A: Si no recuerdo mal, tiene que ver con el orden en que java o otros lenguajes leen la información y la guardan.
En función de esto ejecutan el código, y aunque a veces parezca de mentira, ejecutan el código de una manera imprevista.
Puedes probar 2 cosas.
La primera es cambiar el orden
class A {
    public A ( ) {  System.out.println(" Soy el constructor A");    }
    public A (int a) {
        System.out.println(" Soy el constructor A " + a);
    }
}

class C extends A {
    public C ( ) {
        super(1);
        System.out.println(" Soy el constructor C");
    }
    B ob= new B();
}
 class B {
    public B ( ) {  System.out.println(" Soy el constructor B");    }
    /*public B (int b) {
        System.out.println(" Soy el constructor B " + b);
    }*/
}
public class ex6b_2 {
    public static void main ( String args[] ) {
        C oc= new C();
    }
}

Creo que te dará el mismo resultado.
La segunda forma.
  class C extends A {
        public C ( ) {
            super(1);
            System.out.println(" Soy el constructor C");
            B ob = new B(); // o creando un método para el
        }

    }

Espero que te ayude.


text:
Q: ¿Cómo pasar componentes como parámetros en React? Necesito pasar como parámetro un componente para que se renderize desde otro componente.
En el siguiente ejemplo quiero renderizar Titulo1 o Titulo2 dentro de Perfil
Dados los componentes:
export class Titulo1 extends React.Component {
  render () {
    return (

this.props.nombre

this.props.apellido

)
  }
}

export class Titulo2 extends React.Component {
  render () {
    return (

this.props.nombre

this.props.apellido

)
  }
}

y
export class Perfiles extends React.Component {
  render () {
   let perfiles= this.props.usuarios.map((usuario, index, coll) => {
        var props = {
          id: usuario.id,
          index: index,
          apellido: usuario.apellido,
          nombre: usuario.nombre
        }
         return (<Perfil {...props}>
            {React.createElement(this.props.extraComponent, props)}
          </Perfil>)
      }, this)
    }
    return ({perfiles})
  }
}

   export class Perfil extends React.Component {
      render () {
        return (

this.props.id
{this.props.children}
)
      }
    }

el objetivo es llamar a
<Perfiles extraComponent={Titulo1} usuarios={lista} />

o
<Perfiles extraComponent={Titulo2} usuarios={lista} />

según se necesite, pero no me deja me da error en React.createElement(this.props.extraComponent, props).
¿Alguna sugerencia?
¡¡muchas gracias!!

A: Podrías probar con
<this.props.extraComponent {...props} />

El valor que pasas en el prop extraComponent es un Component como tal, por lo tanto puedes usarlo con sintaxis de JSX.

A: Hay dos técnicas para esto: composición y herencia, React utiliza composición, mira la documentación, un ejemplo donde se utiliza herencia es Swing en Java o Android.
Centrándonos en React la implementación es la siguiente
export class Perfiles extends React.Component {
    ...
    render () {
        return(

                {this.props.children}

        )
    }
}

posteriormente utilizas tu componente de la siguiente manera
<Perfiles usuarios={lista} />
    <Titulo nombre="Jose Maria" apellido="Toscano"/>
</Perfiles>


text:
Q: String + an incremental value in JavaScript I've added comments at the middle of the code. Please help me If you can, I have to deliver the product today.
 if (a === 3) { //this would be how many of the answers further the action
                 var starting = 2; // for an example: yes or no; two of the answers go to no, one goes to yes.
                 //                                  we take 2 as a starting point /you can set these individually for each scenario;
                 if (starting === 2) {
                     for (i = 0; i < starting; i++) {
                         answers[i] = 1; //sets the two checking points of the answer to the no, remaining yes;

 document.getElementById("btn" + i).style.backgroundColor = "red";

     // the problem lies here
    // I tried multiple ways but none of them worked so far
    //i want to apply the style change to multiple buttons at once.

                     }

                     alert(answers);

                     for (i = 0; i < starting; i++) {
                         if (answers[i] == 1) {

                         }
                     }

                 }
             }

The problem is that the name of the button which is btn and the buttons are named as btn1, btn2,btn3; I want the for loop to change it to all of the buttons, however the string literal at the id doesn't recognize the i;
Example: "btn" + i; = change the style of the btn1
I fixed it guys. The mistake was that the for loop starts at 1;
And I have named the id of the buttons wrong. Novice mistake! :)

A:

for (i = 0; i < 3; i++) {
  if (document.getElementById("btn" + i) != undefined)
    document.getElementById("btn" + i).style.backgroundColor = "red";

}
<input type="button" value="Submit" id="btn3">
<input type="button" value="Submit" id="btn1">
<input type="button" value="Submit" id="btn2">

The problem is your button id starts from btn1 and your code starts from 0 which is not located in your html so either add a check before setting background color or start your loop from 1

if (document.getElementById("btn" + i) != undefined)


text:
Q: Fetching data from MSSQL I got an interface that sends (FROMDATE and TODATE) to the MSSQl and retrieves the selected details and after receiving them the data is shown on the grid.
I'm using the MVC.
This is the js script that I'm using.
$('body').on('submit', '#form', function (e) {
    e.preventDefault();

    $('#btnSubmit').html('  Please wait ....');
    $('#btnSubmit').prop('disabled', true);

    var fromdate = $('#PeriodFrom').val();
    var todate = $('#PeriodTo').val();

    if ($('#PeriodFrom').val() > $('#PeriodTo').val())
    {
        ToastMessage("To date cannot be less than From date ");
        return false;
    }

    debugger;
    $.ajax({
        url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,

        dataType: 'JSON',
        method: 'GET',

        beforeSend: function () {
            $('#btnSubmit').html('  Please wait ....');
            $('#btnSubmit').prop('disabled', true);
        },
        complete: function () {
            $('#btnSubmit').html('Save');
            $('#btnSubmit').prop('disabled', false);
        },
        success: function () {
            FillGrid();
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    });
});

url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
When the user picks the date range.By using the following  URL it sends the Fromdate and Todate toward the controller then the Service and then the Entry.
It returns backs ReservationNo and Name from MSQL.
So according to my program, everything is fetched to the model (the values which is fetched from MSQL).
As you can see when it redirects back I'm calling a function called **FillGrid();**in my js.
function FillGrid() is the function that I'm using to draw the grid in the HTML.
Even the data is fetched nothing is displayed on my grid is this wrong?
can anyone help me?
function FillGrid() {
    debugger;
    if ($('#grid').length == 1) {
        $('#grid tr').not(':first-child').remove();
        $.ajax({
            //url: '/ReservationInquiries/select?search=' + $('#txtSearch').val(),
            //dataType: 'JSON',
            beforeSend: function () {
                $('.grid').hide();
                $("#loadingProjects").show();
            },
            complete: function () {
                ShowGrid();
                $("#loadingProjects").hide();
            },
            method: 'POST',
            success: function (data) {

                debugger
                //var inquirieslist = JSON.stringify(data.InqueryList)

                $('#grid tr:not(:first)').empty();
                if (inquirieslist != null) {
                    $.each(inquirieslist, function (index, item) {

                        $('
' +
                            '' + item.ReservationNo  + '	' +
                            '' + item.Name + '	' +
                            '
').appendTo($('#grid'));

                    });

                }
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        });
    }
}


text:
Q: Suppose X has the uniform distribution on [0,1]. Suppose that given X, Y has the Gamma distribution with mean X and variance 3X. Suppose $X$ has the uniform distribution on $[0,1]$. Suppose that given $X$, $\,Y$ has the Gamma distribution with mean $X$ and variance $3X$.
a) Find $E(Y)$
b) Find $Var(Y)$
c) Give and integral expression for $P(XY>1)$ without solving it.
This is what I think I should do.
for parts (a), $E(Y) = E(E(Y\mid X))$. The expectation of $Y$ given $X$ is $X$. So,
$E(Y) = E(E(Y|X)) = \int_0^1 X \times1 \ dX = \frac{1}{2}$
Also, for part(b),
$Var(Y) = E(Var(Y\mid X)) + Var(E(Y\mid X)) = E(3X) + Var(X) = 3E(X) + \frac{1}{12} = 3 \times 0.5 + \frac{1}{12} = \frac{19}{12}$
if part (a) and (b) are correct, how should I continue for part (c)?
Thanks.

A: Your answers for $(a)$ and $(b)$ are correct.  For $(c)$, we want $\Pr[XY > 1]$, and the most natural way to do this is to condition on $X$:  $$\Pr[XY > 1] = \int_{x=0}^1 \Pr[Y > 1/X \mid X = x]f_X(x) \, dx = \int_{x=0}^1 \int_{y=1/x}^\infty \frac{y^{x/3-1} e^{-y/3}}{3^{x/3} \Gamma(x/3)} \, dy \, dx.$$
Here I have used the fact that if the conditional mean and variance are $X$ and $3X$, then this implies the gamma distribution must have shape $X/3$ and rate $1/3$.


text:
Q: How to automatically update data source and index for a view in Azure Search How can I update the exiting data source which is create from azure SQL view.
What are steps I need to follow once when dealing with azure search for Database view.
My Data source& index should be updated once my view gets updates.

A: Assuming that by "updating the view" you mean adding more columns to the SELECT clause:

*

*You don't need to update the datasource as long as you didn't change the name of the view or the credentials.

*You will need to add newly added fields to your index definition. This doesn't happen automatically. Once you add new fields to your index schema, indexer will start populating those fields for newly indexed rows. To populate documents that have already been indexed, reset the indexer (in the portal or using the Reset Indexer API).


text:
Q: Table Name for @Embeddable I have one class as below
@Entity
@Table(name = "template")
public class DynamicTemplate {
    @Id
    private Long id;

    @ElementCollection
    Set<TemplateAttributes> attributes;

    //setters and getters

and another table is like below
@Table(name = "attribute")
@Embeddable
public class TemplateAttributes {
    private String name;
    private Double normalLow;

In the database @Embeddable table is being created with template_attributes name rather than  provided name attribute

A: You need to use the CollectionTable-Annotation:
@Entity
@Table(name = "template")
public class DynamicTemplate {
    @Id
    private Long id;

    @ElementCollection
    @CollectionTable(name = "attribute")
    Set<TemplateAttributes> attributes;

    ...
}

@Embeddable
public class TemplateAttributes {
    private String name;
    private Double normalLow;

    ...
}

A: Your schema does not make much sense.
@Embeddable marks that this object is not to be mapped as a table, but rather a set of properties that go/are embedded into another entities/tables (in fact, you may use it for several properties at different entities).
If DynamicTemplate had an TemplateAttributes attribute; property, you would have name and normalLow columns in the table template. But you cannot have a set of values as columns in the same table.
What you need is to either make TemplateAttributes an entity, or, if you need to reuse TemplateAttributes, create a new entity that has an id and a TemplateAttributes property and have a set of them.


text:
Q: Get age from date_of_birth with age greater than 35 # Customer table contains 3 columns - id, first_name, last_name, date_of_birth

create table Customer(id integer, first_name varchar(100), last_name varchar(100), date_of_birth datetime);
insert into Customer(id, first_name, last_name, date_of_birth) values(1, 'Akash', 'Agarwal', '1985-09-03');
insert into Customer(id, first_name, last_name, date_of_birth) values(2, 'Harish', 'Gupta', '1981-09-24');
insert into Customer(id, first_name, last_name, date_of_birth) values(3, 'Ramesh', 'Reddy', '1992-01-03');
insert into Customer(id, first_name, last_name, date_of_birth) values(4, 'Bhola', 'Banerjee', '1975-05-03');
insert into Customer(id, first_name, last_name, date_of_birth) values(5, 'Gagan', 'Mani', '1968-05-02');
insert into Customer(id, first_name, last_name, date_of_birth) values(6, 'Mahesh', 'Iyer', '1988-05-09');

This mysql query is not working
select timestampdiff(YEAR, date_of_birth, curdate()) as age
from Customer
where TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) > 35;

the output should look be only age greater than 35

A: select timestampdiff(YEAR, date_of_birth, curdate()) as age from Customer where TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) > 35;

A: A perhaps neater way using having:
select timestampdiff(YEAR, date_of_birth, curdate()) as age
from Customer
having age > 35;

A: Personally, I prefer:
where date_of_birth < curdate() - interval 35 year

However, that doesn't use the age that you have specifically calculated.


text:
Q: Bouncy Castle FIPS Mode issue Existing jars: bc-fips-1.0.0.jar, bcpkix-jdk15on-1.54.jar
Upgraded to: bc-fips-1.0.2.3.jar, bcpkix-jdk15on-1.69.jar and added dependent jar: bcutil-jdk15on-1.69.jar.
we are using ssl authentication with following properties
keystore.type=bcfks
keystore.type.compat=true

security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
security.provider.2=com.sun.net.ssl.internal.ssl.Provider BCFIPS
security.provider.3=sun.security.provider.Sun
security.provider.4=sun.security.jgss.SunProvider

ssl.KeyManagerFactory.algorithm=SunX509
ssl.TrustManagerFactory.algorithm=PKIX

Our application was working with no issues with old jars. After upgrade, it is failing with following error
java.lang.NoSuchMethodError: org.bouncycastle.asn1.ASN1Integer.intValueExact()I
        at org.bouncycastle.asn1.cms.CCMParameters.<init>(Unknown Source)
        at org.bouncycastle.asn1.cms.CCMParameters.getInstance(Unknown Source)
        at org.bouncycastle.jcajce.provider.ProvBCFKS$BCFIPSKeyStoreSpi.decryptData(Unknown Source)
        at org.bouncycastle.jcajce.provider.ProvBCFKS$BCFIPSKeyStoreSpi.engineLoad(Unknown Source)
        at java.security.KeyStore.load(KeyStore.java:1445)

The reason is org.bouncycastle.asn1.ASN1Integer.intValueExact() is not present in bc-fips-1.0.2.3.jar. There is no compatible jar to address this issue.
Can anyone help fix this issue?

A: Probably I'm late to the party, but as I recall, KeyStorage must use PKIX algorithm in FIPS mode.
Documentation says that this line must be present in Java security file (or loaded dinamically):
ssl.KeyManagerFactory.algorithm=PKIX


text:
Q: Sum of random variables and expectation ... difference? $C_j = 1/s_j \sum_{i=1}^n w_iJ_i^j$.
$w_i$ is some (real) number. $J_i^j$ is a 0-1 random variable and the P($J_i^j = 1)= p_i^j$.
$l_j = 1/s_j \sum_{i:[n]} w_i p_i^j$. This is a sum over all $i$. (Both summations are over all $i$. So there are $n$ $i$'s). Intuitively, $i$ are the number of tasks to be completed.
What is the difference between $l_j$ and $C_j$? If so, what is it?

A: Looking solely at your formulation and taking $s_j$ to be a fixed, real number >0:
The main difference between $C_j$ and $l_j$ is that the former is a random variable while the latter is the expected value of $C_j$. By linearity of expectation:
$E[C_j]=E[1/s_j \sum_{i=1}^n w_iJ_i^j]=\frac{1}{s_j}E[\sum_{i=1}^n w_iJ_i^j]=\frac{1}{s_j}\sum_{i=1}^n w_iE[J_i^j]$
Since $J_i^j$ is an indicator variable with $P(J_i^j = 1)= p_i^j, P(J_i^j = 0)= 1-p_i^j$, we get: $E[J_i^j]=p_i^j\rightarrow E[C_j]=\frac{1}{s_j}\sum_{i=1}^n w_iE[J_i^j]=1/s_j \sum_{i:[n]} w_i p_i^j =l_j$


text:
Q: Sending mail using gmail server in play framewrok I am trying to send mail using gmail server in my play app but it gives time out. I configured it as stated in the play documentation. my configuration is
mail.smtp.host=smtp.gmail.com
mail.smtp.user=*******
mail.smtp.pass=*******
mail.smtp.channel=ssl.

It was sending successfully a couple of days ago. Is there anyone who knows the solution?

A: *

*Are you using google apps for domain? Did you specify your domain in user name?

*Remove "." from "ssl.".

*Verify that you don't have "mail.smtp=mock" anywhere in your conf file.

*Verify that you're not overriding mail configuration somewhere later in file.

*Try to login manually with your account, check if you can send email, maybe you sent too  - many emails and you're temporary banned by gmail smtp.

Following works perfectly for me:
mail.smtp.host=smtp.gmail.com
mail.smtp.user=***@yourdomain.com
mail.smtp.pass=***
mail.smtp.channel=ssl


text:
Q: How to install/change locale on Debian? I've written a web application for which the user interface is in Dutch. I use the system's date and time routines to format date strings in the application. However, the date strings that the system formats are in English but I want them in Dutch, so I need to set the system's locale. How do I do that on Debian? I tried setting LC_ALL=nl_NL but it doesn't seem to have any effect:
$ date
Sat Aug 15 14:31:31 UTC 2009
$ LC_ALL=nl_NL date
Sat Aug 15 14:31:36 UTC 2009

I remember that setting LC_ALL on my Ubuntu desktop system works fine. Do I need to install extra packages to make this work, or am I doing it entirely wrong?

A: You may need to install the locales package.  This will ask you which locales to generate.  If it's already installed, then dpkg-reconfigure locales will let you generate more locales.

A: None of these answers worked for me, on an LXC container installed with:
lxc-create -n sse-master -t download -n sse-master -- \
    -d debian -r jessie --arch i386

I always got the following output from locale-gen, i.e. not generating any locales (none listed):
$ sudo locale-gen
Generating locales (this might take a while)...
Generation complete.

Running dpkg-reconfigure locales and selecting some locales did not update /etc/locale.gen as I expected it to.
However, when I modified that file manually and uncommented the locales that I wanted, then locale-gen started working properly:
$ sudo locale-gen
Generating locales (this might take a while)...
  en_GB.UTF-8... done
  en_US.UTF-8... done
Generation complete.

I was also able to generate locales manually like this:
sudo localedef -i en_US -f UTF-8 en_US.UTF-8
sudo localedef -i en_GB -f UTF-8 en_GB.UTF-8

But this was not a permanent solution: I found that running locale-gen without the --keep-existing option will delete all such manually-generated locales, i.e. every locale not listed (and uncommented) in /etc/locale.gen.

A: Answers here are incomplete as with most elsewhere. After piecing together information from a few places, what worked for me was to (1) make sure the locale I wanted was available (generate it if it wasn't) then (2) set locale related environment variables to desired locale.
In my case I needed en_US.UTF-8 programmatically (i.e. non-interactively) installed in a docker container. The ff accomplished what I need but it should work just fine in an interactive shell.
apt-get update

# Install locales package
apt-get install -y locales

# Uncomment en_US.UTF-8 for inclusion in generation
sed -i 's/^# *\(en_US.UTF-8\)/\1/' /etc/locale.gen

# Generate locale
locale-gen

# Export env vars
echo "export LC_ALL=en_US.UTF-8" >> ~/.bashrc
echo "export LANG=en_US.UTF-8" >> ~/.bashrc
echo "export LANGUAGE=en_US.UTF-8" >> ~/.bashrc

On the same shell, you will need to do source ~/.bashrc for the env vars to take effect immediately. You can check that locale has been configured correctly by invoking locale.
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

There were a lot of Q&A entries regarding this subject but only a few were actually helpful. Credit where credit is due:

*

*https://unix.stackexchange.com/a/247019/21289

*https://perlgeek.de/en/article/set-up-a-clean-utf8-environment

A: For a web application, it might be better to use setlocale() inside the program, rather than requiring that the system default locale be set appropriately outside. Less loose ends that way.

A: For those who, like me, on Ubuntu 14.04 LTS, have, somehow, no /etc/locale.gen file, you can add a new locale in /var/lib/locales/supported.d/local and then run :
sudo dpkg-reconfigure locales
You can also add the french (for example) locale this way (instead of editing /var/lib/locales/supported.d/local) :
sudo locale-gen fr_FR fr_FR.UTF-8
to add and generate the ISO-8859-1 and UTF-8 codesets of the fr_FR locale and finally type :
sudo dpkg-reconfigure locales
to finish the job

A: Note: Some of the commands below require root privileges, consider the use of sudo.
Basic info
According to man locale-gen, locales are set in several files.

/etc/locale.gen
The main configuration file, which has a simple format: every line that is not empty  and does not begin with a # is treated as a locale definition that is to be built.
/var/lib/locales/supported.d/
A  directory  containing  locale.gen  snippets provided by language-pack packages.  Do not edit these manually, they will be overwritten on package upgrades.

Comprehensive details on locales at the Arch Wiki.
Checking locales and the locale
To check the (already) generated locales, run any of the following commands (with minor output differences).
locale -a
localedef --list-archive
localectl list-locales

To check the currently used locale, run any of the following commands (with minor output differences).
locale
localectl

Setting and generating (new) locales
Locales are typically set by uncommenting lines in /etc/locale.gen, after which running locale-gen is required.
nano /etc/locale.gen # uncomment desired lines (locales)
locale-gen

This will generate locales files for each uncommented line in /etc/locale.gen (and under /var/lib/locales/supported.d/), whether they were previously generated or not.
Alternatively, the command
locale-gen <locale>

will uncomment the corresponding line in locale-gen while generating the desired locale and only this one.
Removing locales
To remove locales in /etc/locale.gen, simply comment the desired lines and regenerate the locales using locale-gen. The command locale-gen --purge <locale> doesn't do what the modifier suggests.
To remove locales under /var/lib/locales/supported.d/ is trickier. Since any file /var/lib/locales/supported.d/<code> depends on the package language-pack-<code>-base, any change on the former will be restored when the latter is updated.
Workaround. To prevent changes under /var/lib/locales/supported.d/, set files in it with the "immutable (i)" attribute. So instead of removing files, empty them. For instance:
cd /var/lib/locales/supported.d/
rm <code> && touch <code> # <code> has been emptied
lsattr <code>    # regular attributes
chattr +i <code> # adding (+) immutable
lsattr <code>    # checking attributes

Setting the locale
Setting and generating locales does not set the system locale. Any of the following commands achieves this.
echo LANG=<code> | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu)
localectl set-locale LANG=<code>

A: Edit /etc/default/locale and set the contents to:
LANG="nl_NL.UTF-8"

You can check which locales you currently have generated using:
locale -a

You can generate more by editing /etc/locale.gen and uncommenting the lines for the locales that you want to enable. Then you can generate them by running the command:
locale-gen

You can find a list of supported locales in /usr/share/i18n/SUPPORTED
There is more information available on the Debian wiki.

A: But first you need to have needed language pack installed. On my German based VPS there was no english language pack pre-installed. So first you check that you have it installed:
aptitude install language-pack-en


text:
Q: how can I detect if my infinite cp command has failed using bash I have a little data collector, a Raspberry Pi Zero W, which, on boot, mounts a remote folder on mnt using sshfs. The data transfer is effected using a cp command, e.g., cp device file & where device is local and file is in the remote folder. This is intended to be an infinite loop. If power to the Pi fails the process restarts when power returns. But what if the server goes down during the copying? I'd like to then loop into a reboot until copying resumes. But how can I tell, from the pi, when the server is out?

A: There's a number of problems with this:

*

*cp is meant to copy files, not streams.  Every time the pi reboots, it will restart the copy, zeroing out any previous data.  If this isn't what you want, you might be better off with something like cat device >> file or maybe dd

*sshfs is not very robust.  When the server reboots, the sshfs connection will die and not resume without something actively restarting it, and the cp will die.  NFS is designed to handle this situation, and would just pause until the server is back up and then resume as if nothing happened.  Even using just ssh by itself might be better than sshfs.

*Depending on what you are doing, you might be better off setting up a service of some sort on the server to collect the data rather than using filesystem semantics.  Netcat on both ends might be better, but even that is less robust than it could be.

Without more details on why you are doing this and what your goals are, it's difficult to give better advise.


text:
Q: How to escape the output of an entire blade template from a parent template I have a blade template that produces random XML using Faker. When I include the XML output inside an HTML5 template as such:
@extends('splash')

@section('content')

    @yield('output')

@endsection

all my XML gets evaluated instead of displayed as is. I am only able to see the tag contents when I would like to be able to see the tag names and attributes. I would like to be able to escape the output of the XML generating template so something like:
@extends('splash')

@section('content')

    {{@yield('output')}}

@endsection

Except of course that doesn't work because PHP interprets this as a yield statement prepended with a suppress errors operators instead of the blade directive. So basically what I would like to know is what the raw php equivalent of the @yield directive is.

A: So I figured it out.
@extends('splash')

@section('content')

    {{View::getSection('output')}}

@endsection

Did the trick for me


text:
Q: Convert wifi signal to wired signal I have a Rpi which is unable to connect to wifi, but it has Ethernet port.
In which mode should I use my Tp-link device to convert my existing wifi to wired signal?
I tried out the wifi extender to this task, but in that mode the tp-link device will produced an another wifi signal, which caused problem -> The 2 wifi signal interference caused slowness in speed on both wifi signal.
So the tp-link should only get the wifi signal and forward the signal with Ethernet cable to my Rpi.

*

*Wireless Router(Default): In this mode, the device enables multiple users to share the Internet connection via Ethernet port. The LAN devices share the same IP from ISP through Wireless port. While connecting to Internet, the Ethernet port works as a WAN port.

*WISP: In this mode, the device enables multiple users to share Internet connection from WISP. The LAN port devices share the same IP from WISP through Wireless port. While connecting to WISP, the Wireless port works as a WAN port. The Ethernet port acts as a LAN port.

*Access Point: In this mode, this device can be connected to a wired network and transform the wired access into wireless that multiple devices can share together, especially for a home, office or hotel where only wired network is available.

*Range Extender: In this mode, this device can copy and reinforce the existing wireless signal to extend the coverage of the signal, especially for a large space to eliminate signal-blind corners.

A: There's no option that'll do exactly what you want, although "WISP" mode is fairly close and might work in your case.
However, WISP mode is for connecting to WAN, so it won't bridge both sides – the description says that the Wi-Fi connection will be considered the "WAN port", meaning the TP-Link will still create its own IP subnet, which might be undesirable. (Like "chaining" two routers, you'll have to mess around with static routes, or with port-forwarding.)
Real bridging or "pure signal conversion" is generally impossible with Wi-Fi clients, as the client device isn't allowed to forward other devices' MAC addresses from the Ethernet side; in other words, Wi-Fi isn't symmetric. It could be done if both the Wi-Fi router and the TP-Link client supported the special "WDS bridge" mode, but most home devices don't. It could also be emulated if the TP-Link supported "L2 NAT", but sounds like it doesn't.
There are however some devices sold as "range extenders" which can be switched around to act as a Wi-Fi client (bridge mode), allowing you to connect the RPi to their Ethernet port, and they do implement L2NAT allowing the RPi to be in the same subnet as your main Wi-Fi network.


text:
Q: PHP ImageMagick convert doesn't work under OSX I have an apache web server under OSX and an installed and configured ImageMagick. If I try to execute some ImageMagick command from the terminal, it works fine, but if I try to do that with exec or shell_exec from PHP, it doesn't work.
That is what I do:
I set the environment variable:
apache_setenv("PATH", "/etc/ImageMagick-6.8.1/bin:".apache_getenv("PATH"));

and try to execute some command:
exec('convert -version', $imgkOut);

the $imgkOut array is always empty.
I tried to set both paths: 'convert ...' and '/etc/ImageMagick-6.8.1/bin/convert ...' - nothing helps.
In the apache log file I found these errors:
sh: convert: command not found

for the first case, and this:
sh: /etc/ImageMagick-6.8.1/bin/convert: Permission denied

for the second.
What do I do wrong?

A: *

*did you see http://php.net/manual/en/book.imagick.php ?

*try install imagemagick from macports - http://www.macports.org/ports.php?by=name&substr=imagemagick

*check exec for convert (maybe file hasnt +x flag? so just chmod +x convert)

A: The errors you are getting imply that:

*

*The apache_setenv command is not working.

*The web user does not have permission to run the command.

If you do
    cd /etc/ImageMagick-6.8.1/bin
    chmod +x convert

and try again with the second version, where you supply the complete path, it should work.


text:
Q: How to access KeyCloak endpoints via proxy API I currently have the following architecture
APP -> API -> KeyCloak
I want the APP to be able to send requests to my API which will then internally proxy certain requests to KeyCloak.  For example, I'd like to make a request to the /userinfo endpoint in KeyCloak through my API.  If I can figure this out I can then perform more complex features.
APP -> http://api:port/api/userinfo
API -> http://keycloak:port/auth/realms/quartech/protocol/openid-connect/userinfo
I have a valid JWT Bearer token.  As I can directly make the request to KeyCloak successfully, however if I attempt to make the request via my API it returns 401.  Even though it is using the same JWT Bearer token.
I believe it has something to do with configuring the KeyCloak client to allow requests to come from the API.  But so far I haven't been able to figure it out.

A: I've discovered it required a DNS entry to local development within a Docker container.
I've edited the hosts file and added a 127.0.0.1 keycloak and then al


text:
Q: Characters found after end of SQL statement VBA code Access 2007 I'm writing a VBA code in Excel to access an Access database.
I'm using this provider
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= " & DBFile & ";"

and here is my SQL string
SQlSrc = "SELECT YEAR FROM Data ORDER BY YEAR ASC"
SQlSrc = SQlSrc & ";SELECT STN FROM STN_List WHERE include = TRUE"

When I open each recordset individualy it works (just first line or second) but when I make as a single statement as above I get an error

"Characters found after end of SQL statement"

Does anybody have idea if it's a problem with Access 2007?

A: You can reuse the connection.
Dim cn As Object
Dim rs As Object

cn="Provider=Microsoft.ACE.OLEDB.12.0; Data Source= " & DBFile & ";"

SQlSrc = "SELECT YEAR FROM Data ORDER BY YEAR ASC"
rs.Open SQlSrc, cn

''Do stuff

SQlSrc = "SELECT STN FROM STN_List WHERE include = TRUE"
rs.Open SQlSrc, cn

cn.Execute "UPDATE Table SET Column=2"

A: It looks like Access and/or the provider doesn't accept multiple SQL statements for opening a single recordset.
That said, I'm not sure if this is standard for all OLEDB providers or just the one you're using.

A: IMO MS Access does not support multiple SELECT statements in a single Command. You may have to split this into individual commands.


text:
Q: MySQL many to mny (n:n): Setting 1 entry as main entry Using this example1 for a n:n relationship:

(source: tekstenuitleg.net)
What would be the best way to set a main or primary many-to-many field? Example: Let's say I want to set distributor "Devrolijke drinker" (ID AB999) as main or preferred distributor for "Sint" beer (ID 160). My first guess would be be to add an additional field in the junction table, e.g. (bool) is_primary. But this could easily become inconsistent if two fields would be (accidentally) set to true, right? Any ideas? Thanks!
Reference
1 The many-to-many relationship
2 Another thread

A: 1) You can adda "preferred distributer" column to the beer table, which will have the preferred distributor's ID as the datatype. then add another column of main distributor with that distributor ID.  This will allow for the queries n joins you want it sounds like.
2) You can use a numbering system. Add this as a single column to the "beer distributor" table. You can make main distributor = 1, preferred distributor = 2, etc.  Then query by this value if you want to find all preferred distributors of a beer.  (This way would work better if you have more than one preferred distributor for the same beer.


text:
Q: Setting value of combobox in the beforePageLoad event I have a button in a view called "Add Line Item". You select a document, then hit this button. The intent is that we create a new document with values from the selected document being stuffed into the new document.
In the view-button, I set a sessionScope variable with a long string. I delimit each entry with a "~". Within each entry, the first thing is the actual name of the field. The next thing is the value of that field. These two are delimited by a pipe "|". If the actual value of the field is an array, they naturally have semicolons dividing them. I mention all of this so the following code can be understood.
In the form I launch, in the beforePageLoad event, I have the following;
var AddingNewLine = sessionScope.get("AddingNewLine");
if (AddingNewLine != null) {
  fieldsArray = AddingNewLine.split("~"); // make an array that has the field names & its value(s)
  for (i = 0 ; i < fieldsArray.length ; i++) {
    splitValue = fieldsArray[i].split("|"); // now we make an array out of the entry. value 0 will be
    fieldName = splitValue[0];              // the name of the field. value 1 will be the values which
    fieldValues = splitValue[1].split(";")  // in turn will be split into an array
    var f = "PayRates:HourlyRates:CPrompts:IssuingCountry:ServiceCurrency:ReceivedDate:InvoiceDate:Client:InvoiceNumber:WBS";
    if (f.search(fieldName) >= 0) {
      currentDocument.setValue(fieldName,fieldValues);
      if (fieldName == "CPrompts") { var CPrompts = fieldValues }
    }
  }
// new doc but adding new line item or replicating? then get our prompts from the original doc
for (i = 0; i < CPrompts.length ; i++) {sessionScope.put("CPrompt"+(i+1),CPrompts[i])}
}

Note: I'm screening out the numeric values with "f" variable right now as I'm having a different problem with them
Anyway, all of my textboxes are getting updated, but the comboboxes are not (Which happen to be IssuingCountry, ServiceCurrency, Client, and WBS.
I've verified that the field names and their values are correct with print statements when I do the currentDocument.setValue. I've even tried doing a currentDocument.replaceItemVale. Neither seems to work for comboBox type fields. This also holds true for the date value fields.
Combobox field example:
<xp:comboBox
  id="IssuingCountry"
  style="width:160.0px"
  value="#{FInvoiceDoc.IssuingCountry}">
    <xp:selectItem
      itemLabel="United States of America"
      itemValue="United States of America"
      id="selectItem1">
    </xp:selectItem>
    <xp:selectItems id="selectItems1">
      <xp:this.value>
        <![CDATA[#{javascript:@DbLookup("", "Keywords", "Countries", 2)}]]>
    </xp:this.value>
    </xp:selectItems>
</xp:comboBox>

Could it be that I need to somehow update the itemLabel? If so, how?
Date field example;
<xp:inputText
  value="#{FInvoiceDoc.ReceivedDate}"
  id="ReceivedDate"
  style="width:85px">
    <xp:this.converter>
      <xp:convertDateTime
        pattern="MM/dd/yyyy">
      </xp:convertDateTime>
    </xp:this.converter>
  <xp:dateTimeHelper
    id="dateTimeHelper1">
  </xp:dateTimeHelper>
</xp:inputText>

A: The session scope can handle complex objects. Creating a string reduces maintainability quite a bit. I would create the stuff like this:
  var prepopulate = [];
  prepopulate.push({ "name" : "IssuingCountry", value : "United Stated of America"});
  prepopulate.push({ "name" : "ReceivedDate", value : [date1, date2]);

  sessionScope.AddingNewLine = prepopulate;

Then is the afterPageLoad (which runs before renderResponse) you do something like this (omitted the test for valid field names):
  if (!sessionScope.AddingNewLine) {
     return;
  }
  var prepopulate = sessionScope.AddingNewLine;

 for( var i = 0; i < prepopulate.length; i++ ) {
    var oneItem = prepopulate[i];
    FInvoiceDoc.setValue(oneItem.name, oneItem.value);
 }

  // reset
 sessionScope.AddingNewLine = null;

So the 2 important differences: use afterPageLoad and use a complex object, not a wild string. Instead of an array, you might want to use a object since you have a special use for CPrompts.
Btw you declare a variable inside a condition. Only the fact that JS doesn't use block level variables prevents the code from failing if you don't have CPrompts in your string. So the complex object might be:
 var prepopulate = {};
 prepopulate.cprompts = ["some","prompts"];
 prepopulate.fields = [];
 prepopulate.fields.push(....);

Hope that helps

A: Or you can just give UNID of selected document in parameter with something like that :
context.redirectToPage( "issue.xsp?action=newDocument&parentId=" + selectedUNID );

and in beforePageLoad, retrieve parentDoc to get all fields needed
if (dataDoc.isNewNote()) {
    var sParentId = dataDoc.getParentId();
    if (sParentId != null) {
        var parentDoc:NotesDocument = database.getDocumentByUNID(sParentId);

        dataDoc.setValue("KeyParent", parentDoc.getItemValueString("KeyDoc"));
        dataDoc.setValue("Domain", parentDoc.getItemValueString("Domain"));
    }
}


text:
Q: How to encrypt using a random key only known to a third party or stored in the DB and known only to DB? I don't want myself or team mates to know the key with which data has been encrypted. Ideally the cryptographic function will chose a random key but know which one was used so the information can be decrypted when needed.
I'm OK with using a third party service or would like a suggestion on how to do this with postgresql.


text:
Q: How is XP dispersed in Batman: Arkham Origins multiplayer? At the end of multiplayer matches players are awarded the EXP they earned during that round. But I can't seem to figure out how EXP is dispersed? Sometimes I seem to get only weapon points, and then sometimes I get Overall Level EXP and other times I get Gang Level XP (and combinations of all three)?
So doing what different things in the round will get you EXP for which different areas (e.g. what actions gives you Gang Level XP, etc.)?


text:
Q: Automatic interactions with web pages I need to retrive information from a web page which accept only a form as an input.
I usually use HttpClient to retrieve info and parse the html, but this page take a Javascript rather than an explicit url as argument, and print input again as a javascript.
I tried HTMLUnit but is painfully slow, especially on Android. Moreover it seems like I can't make it works correctly, as I'm not able to retrive the html after filling the form, maybe due to the page being a javascrpit (see attached code).
How can I retrive information from this web page in Android?
Cheers :D
package com.htmlUnitTest;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class HtmlUnitTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {

            submittingForm();

        } catch (Exception e) {

            System.out.println("Something bad happened");

            e.printStackTrace();
        }

    }

    static public void submittingForm() throws Exception {
        final WebClient webClient = new WebClient();

        // Get the first page
        final HtmlPage page1 = webClient.getPage(
                  "http://mobile.viaggiatreno.it/viaggiatreno/mobile/stazione?lang=IT");

        System.out.println(page1.getForms());

        // Get the form that we are dealing with and within that form,
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getForms().get(0);

        final HtmlSubmitInput button = form.getInputByValue(" Cerca ");
        final HtmlTextInput textField = form.getInputByName("stazione");

        // Change the value of the text field
        textField.setValueAttribute("Milano Centrale");

        // Now submit the form by clicking the button and get back the second page.
        final HtmlPage page2 = button.click();

        System.out.println(page2.getAnchors());

        webClient.closeAllWindows();
    }

}

A: You need to POST to /viaggiatreno/mobile/stazione, parse the answer, then post again if you want to drill down. More info about posting here:  google.com/search?q=webClient+post