Double basses - C extension v 5 strings v neither

Question: This is a curiosity of mine.  Each time I attend a concert, I look at the double basses to see whether they have either a C extension, 5 strings, or neither.  For the concerts that I have attended in the UK, the answer seems to be mostly C extension.  However, on TV or discs, I see 5 strings occasionally; I think (not claim) that this seems to be more common in Germany.
What are the pros and cons?
Is the extra string always C to just enable an octave below the cello or is it sometimes B to retain the spacing?
Also what music requires it or may use it?  I have not noticed notes below the standard 4 string bass being used in concerts that I have attended but, of course, my musical tastes and powers of observation might be the explanation.
Answers on 5 strings bass guitars are also welcome.  I get the impression that the extra string is more commonly B on these.
Comment: I'd be interested to find out what the string spacings are on 4 and 5 double basses. On bass guitars, there seems to be a choice between 5 strings squashed into 4 string necks, and wider necks allowing the same spacing between strings for 5, as the 4 has. It may make bowing slightly tricky, don't know.
Comment: The bowing issue may explain why the C extension seems more popular.  It has a capo like device which can be locked at each of the extension notes.  So, it could be locked at E and then I expect that it can be played like a standard bass.  On the downside, when the lower notes are needed, I guess that the fingering is a little awkward.
Answer: Five-string basses in orchestra would be tuned BEADG (from low to high). Another option, which would be used more for solo work, would be EADGC, with the fifth string being an additional higher string instead of a lower one.
There are a number of pieces that call for (explicitly or implicitly) lower notes than the typical 4-string bass can play.
Schubert's 8th symphony has a falling bass line down to a low C in the cello score, but for the bass score, the last two notes, the D and C are written up an octave. Most recordings include the implied notes using either 5-string basses or basses with extensions. I've heard a recording of Rachmaninov's Rhapsody on a Theme by Paganini in which there are clearly basses playing pizzicato on a low B. I imagine a lot of newer music takes advantage of this capability, as these basses become more popular and accessible.
Pros for extensions:

Extended range while keeping the same neck width
They can be retroactively added to 4-string basses with minimal
modifications

Cons for extensions:

More awkward fingering on lower notes, though some basses have
special mechanisms to help deal with that
Adding an extension requires drilling a hole through the scroll, as
well as mounting the extension to the bass, so if it is ever removed,
the bass will be marred

Pros for 5-string basses:

Even more extended range down to B
More natural fingering, just an additional string
The bass is often designed with 5 strings in mind, so it is a more
natural fit

Cons for 5-string basses:

The fingerboard is wider, which may make for difficult fingering for those with smaller hands
Bowing may be trickier
Unless the bass is purpose built for 5 strings, it may not be large
enough or have big enough components to fully support the low notes
Comment: Retrofitting 5 strings to a 4 string bass had not occurred to me.  I knew that the extensions were often added but I expected that 5 string basses were built that way.
Comment: I don't think it's common, and it is definitely not preferred. However, I was more referring to using the same body design but putting 5 strings on it during manufacture, so widening the neck, different scroll design for 5 tuners, etc, but the body isn't larger, the bass bar, etc aren't beefier, so the sound is less powerful, and the bass may even be weaker.
Comment: Ah, that is easier to see.
Comment: I've used 5 string (eelectric) basses witth 5 strings, that fitted into figerboards designed for 4 strings. They work, but they're certainly not for me. Might work for guitarists who want to be budding bassists.
Comment: It's certainly possible to be far more agile on a low B string than on a C extension. Some C extensions have levers. Others require you to move your hand up to the fingerboard extension. Either way, it's hard to play fast.
Answer: I can't can't speak to double basses, but as for bass guitars

Answers on 5 strings bass guitars are also welcome. I get the impression that the extra string is more commonly B on these.

A 5-string bass guitar typically adds a low B, but I have heard of people using a high C instead. A 6-string bass guitar typically adds both a low B and a high C.
As for usage I see most 5 string players in the metal and jazz genres. Metal because they want the special effect of getting extra low notes. And jazz players like the extra option but tend to use it sparingly. Then there are quite a few people that think they want a low B until they realize that it usually sounds a bit floppy and muddy.
Most 6 string players I have seen have been jazz players that like playing solo or with busier chordal passages. The extra range gives you a lot more arrangement options. I personally kind of want a 6 string for this reason—I love playing solo using the upper range of the bass.
Comment: Yeah a lot of it comes down to string tension. On a typical bass guitar low B, it's just not quite enough. You can mess with string gauges or use a longer scale bass, but I'd guess a lot of that is easier with a double bass.
Comment: Thanks.  I had forgotten about 6 string basses.

I guess that the extra low string might work better on a double bass since it is larger.  A bass guitar can get away with low notes for its comparatively small size due to its amplification but there may be a limit to the effectiveness of this.
Answer: 5 String Double Basses are becoming more popular these days because they've improved the design also they weigh less than a Bass w/ a C Extension.
Comment: You can see that the neck is only a bit bigger than a 4 String Bass, the strings are closer together so that it feels more comfortable to hold, the B String is hanging off the Side, & there's just enough curvature in the bridge to where you can change your bow angles. Thomas George & Martin have really solved the play ability problem w/ 5 String Basses (same goes for basses w/ more strings than that) meaning you can now play Gospel Music in an Unplugged setting.
Comment: As someone who has tried 5 strings, and who actually uses "low G" extension strings (B string extended, not "low C"), I find this video to be the most objective and complete explanation of below-E problems ever put online. You hit every nuance and addressed every problem. Bravo!!
Answer: I think 5 string Double Basses are becoming more common these days. Thomas & George Martin cleverly solved the playability problem of the 5 string Double Bass by making some adjustments to the setup which include making the neck & fingerboard a bit wider, having the B string hang off to the side, & increasing the overstand so that the top can be the same thickness, plus it puts the strings further away from the body for easier playabiltiy. How about a Hole-in-the-heart 5 string Double Bass based on a Hole in the Heart Violin to Viola Conversion?
A hole in the heart 5 string Double Bass would be where the function of the soundboard, between the action of the treble bridge  foot and the soundpost is bypassed, this has the effect of reducing the  amplitude of higher frequency resonances, and gives the lower registers  greater sonority.
Comment: Well look right here:https://www.youtube.com/watch?v=xSj0SHc0lgA
Answer: I've also seen two types of extensions on electric basses:
The "Hipshot", which consists of a tuner with lever to drop the string's tuning by as much as a 4th (depending on string gauge):

(Image from hipshotproducts.com)
...and the much rarer Kubicki extension which resembles a shortened version of the extensions seen on string basses, though limited to a maj. 2nd:

(Image from thebassgallery.com)
I've not played either (5 strings since 1992), but the Hipshot seems less flexible as you have to keep your thumb against the lever.
The obvious disadvantages to the Kubicki extension are limitation in range and extreme rarity of existence.
Answer: I can only answer referring to electric basses. As already stated, 5 string basses use either a high C or low B. The low B is more common, as the high C takes the bass into guitar territory. One of the reasons I prefer 5 string is that there is often no need to play on the first few frets, as a lower note is available on that B string. Occasionally, it's nice to finish a song on a root note lower than the usual E, though.
The 6 stringers are often used by jazzers, especially where there's no guitar player, to form partial chords.
As an aside, I used to play with an 8 string player - low F# to high F. Quite interesting!
Comment: @badjohn - not floppy, just quite thick!  Felt rather than heard.
Comment: It's a Marmite thing. I actually changed a 4 string so that it has BEAD. That's nice to play, but I then miss the pop-ability of the G string. But it's good for lending out at open mic venues. It gets returned quite soon.
Comment: An 8 string bass?  That's exotic.  F# nearly an octave below the usual E?  That must be really floppy.  Also close to the limit of our hearing.
Comment: I was thinking of user37496's comment that even the more common low B can be floppy.
Comment: Played quite a few 5 strings over several years, and never found a floppy B string. I use .125".
Comment: "there is often no need to play on the first few frets, as a lower note is available on that B string". This what I was referring to as the jazz use-case on either 5 or 6 strings. While metal players specifically want those extra lower notes, jazz players (or anybody playing a lot of changes) tend to just like having more fingering options for the notes that already exist on the E string.
Comment: I have played a standard bass guitar a few times and enjoyed it; I had some lessons from a friend.  I have not tried a 5 string bass but I expect that it would be fun to play with those extra low notes.


Why are the poles of the z-transform of the Fibonacci sequence the golden ratio?

Question: I recently derived the poles of the $z$-transform of the Fibonacci sequence to be the golden ratio by doing the following:
$u(k+2)=u(k+1)+u(k); u(0)=u(1)=1$
$z^2U(z)-z^2u(0)-zu(1) = zU(z)-zu(0)+U(z)$
$U(z)(z^2-z-1) = z^2$
$U(z) = \displaystyle\frac{z^2}{z^2-z-1}$
poles: $(z^2-z-1) = 0\rightarrow z = \displaystyle\frac{1\pm\sqrt{5}}{2}$
I could see that they turned out to be the golden ratio when I did this but I'm wondering why that is. What about z-transforms and poles cause this outcome? Why does this result make sense?
Comment: [Related](https://math.stackexchange.com/q/338740).
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Comment: What do you mean by "why"? Mathematically or philosophically or whatever?
Comment: Its fairly well known that the Fibonacci sequence and the golden ration are strongly connected, so its not too surprising. See Binet's formula https://en.wikipedia.org/wiki/Fibonacci_sequence
Comment: I understand that the Fibonacci sequence is related to the golden ratio, I'm just wondering why the relationship shows up in this way. What is it about z-transforms and their poles specifically that causes this outcome?
Answer: Let us start with something a bit more general and consider the sequence
$$
u(n) = \alpha z_1^{n}+\alpha z_2^{n}
$$
where $\alpha=(z_2-1)/(z_2-z_1)$, $\beta=(1-z_1)/(z_2-z_1)$, $z_1>1$, and $z_2<-1$.
From this expression, we obtain
$$
\begin{array}{rcl}
L(n)&:=&\dfrac{u(n+1)}{u(n)}\\
&=&\dfrac{\alpha z_1^{n+1}+\alpha z_2^{n+1}}{\alpha z_1^{n}+\alpha z_2^{n}}\\
%
&=&\dfrac{(z_2-1)z_1^{n+1}+(1-z_1)z_2^{n+1}}{(z_2-1)z_1^{n
}+(1-z_1)z_2^{n}}\\
%
&=&\dfrac{z_1[(z_2-1)z_1^{n}+(1-z_1)z_2^{n}]+(1-z_1)z_2^{n+1}-z_1(1-z_2)z_2^n}{(z_2-1)z_1^{n
}+(1-z_1)z_2^{n}}\\
%
&=&z_1+\dfrac{(1-z_1)z_2^{n+1}-z_1(1-z_2)z_2^n}{(z_2-1)z_1^{n
}+(1-z_1)z_2^{n}}\\
%
&=&z_1+\dfrac{z_2^n(z_2-z_1)}{(z_2-1)z_1^{n
}+(1-z_1)z_2^{n}}\\
%
&=&z_1+\dfrac{(z_2-z_1)}{(z_2-1)\left(\dfrac{z_1}{z_2}\right)^n+(1-z_1)}.
%
\end{array}
$$
Since $z_1>z_2$, we have that $(z_1/z_2)^n\to\infty$ as $n\to\infty$, which implies that $L(n)\to z_1$ as $n\to\infty$.
If we pick $z_1=(1+\sqrt{5})/2$, and $z_2=(1+\sqrt{5})/2$, then the sequence is the Fibonacci sequence and we have that
$$
\lim_{n\to\infty} \dfrac{u(n+1)}{u(n)}=z_1=\dfrac{1+\sqrt{5}}{2}.
$$


Stratified sampling when there are too many strata

Question: I am working on a sampling exercise which involves both random and stratified sampling. The sampling is for a series of experiments run on multiple populations. Some experiments may run on the same population either during non-overlapping time periods or might overlap at the same time.
When the test don't overlap then i do simple random sampling but if they do overlap at the same time then for the first test i do random sample and for the second experiment i perform stratified sampling to ensure there is no bias and also to study the incremental value of the 2nd experiment.
I am facing troubles with the stratification in terms of the number of treatment groups. This particular population group has 99 people in it. A case that i am currently facing is as below:
Experiment 1: Control-50 people; Test-49 people
Experiment 2: Control-6%; 16 Test-groups adding upto 94%

For experiment 2, the 6% for control is a mix of 6% of the population each from control and test from the first experiment. And the same for each of the treatment groups. When the # of treatments is low, this is not the issue but when there are cases like above where there are 16 treatments i end up with a unbalanced group like below
Split of test-control is
control: 6%, T1-6%,T2-6%, T3-6%.......T15 & T16-5%. Thus adding up to 100%

Experiment 2: Control = 6% of Exp1.Control + 6% of Exp1.Test
              T1 = 6% of Exp1.Control + 6% of Exp1.Test
               .
               .
               .
              T15 = 5% of Exp1.Control + 5% of Exp1.Test

Expected Split of people across the control and 16 treatment is :
6-6-6-6-6-6-6-6-6-6-6-6-6-6-6-5-5

Even though the split for 1st experiment is 50-50 since there are only 99 people, control gets 50 people and test gets 49 ppl or vice versa.
But during stratification 6% or 5% of 50 & 49 people results in decimals and hence i using the lower function. And because of that i am getting this split instead of what is expected:
5-5-5-5-5-5-5-5-5-5-5-5-5-5-5-5-20
So instead of using Floor, using Ceiling would most likely solve the problem in this case but it will cause a problem if the # of groups is more than 17. At some point there wont be any for the last group if i go with ceiling and there will be skewed split if i got with floor.
So is there a way to find at how many number of splits will it mathematically not be possible to do stratification?
Comment: Please note that "strata" is plural. The singular is *stratum*. I have edited the question title accordingly
Answer: One possible answer to your problem is to not stratify so strictly. Don't always use floor nor always ceiling. Distribute as many observations as you can so that you have an equal number in each treatment. Distribute the rest with some sort of random number generator.
But even then, I think you are stratifying too much. It is always a trade-off between enforcing presence of relevant observations in all strata and interfering with the randomness of sampling. At the level of stratification you want to enforce, you are practically handpicking the observations into the strata. That calls into question the random i.i.d. distribution of your treatment samples and thereby any inference you can do based on it.

So is there a way to find at how many number of splits will it mathematically not be possible to do stratification?

Before you run into the problem of not being able to have uniformly stratified groups because rounding up- or down will make too much of a difference to the group sizes, you will have run into many other, I think bigger, problems.

As I mentioned, this is not really random sampling anymore
Each test will have extremely low power with such a small $n_g$ in each group (if $n_g$ was remotely large enough for statistical power considerations, it would also be large enough that rounding it up or down wouldn't make a relevant difference)
Not only is each test underpowered, you will also have multiple comparisons and need to correct for false discovery rates which further reduces power

How to deal with your current problem? Don't try to do exploratory analysis and hypothesis testing at the same time: Reduce the number of treatments through exploratory analysis before you test the remaining credible candidates with new data. (Or, if you must do it all at once, have more budget for much larger $n$ and do a rigorous power analysis to determine that $n$.)
Comment: Hi, thanks for the reply. I considered the power analysis initially when the experiments were being designed but i don't have a say over the number of stratas or the split%. Considering the 99 population group is fixed, i will have go with your first approach EDA.
Comment: For the EDA would the best approach be simulating scenarios with different number of split% and stratas?


Recursive functional dependency not working

Question: I'm trying to multiply array of units (from dimensional) in a phantom type and I'm having trouble with functional dependencies. A simplified version of the problem is the following :
I have the following type
data F (a:: [*]) = F String

Where the string represent an expression in a foreign language and a phantom type representing a list of types.
I can do things like
x = F "x" :: F '[Double]
y = F "(1,3)" :: F '[Int, Int]

I managed to implements arithmetics operators like this by creating a Nums class which is a list of Num.
class Nums (a::[*])
instance Nums '[]
instance (Num a, Nums as) => Num (a ': as)

Then I can do instanciate Num F
instance Nums as => F as where
   (F a) * (F b) = F (a ++ "*" ++ b)
   ... etc ...

Now, I'm trying to do the same using physical units. I can do it with a list of one type this way
import qualified Numeric.Units.Dimensional as Dim

data F (a::[*]) = F String
(!*!) :: (Num n, Dim.Mul a b c) => F '[Dim.Dimensional v a n]
                                -> F '[Dim.Dimensional v b n]
                                -> F '[Dim.Dimensional v c n]

(F a) !*! (F b) = F (a ++ "*" ++ b)

That's seem to work, I can "multiply" 2 'F's of different units, and the result is in the corret unit.
Obviously, I want to generalize this to any list and use the same tricks as Nums which I call Muls.
class Muls a b c | a b -> c
instance '[] '[] '[]
instance (Num n, Mul a b c, Muls as bs cs)
   => Muls (Dim.Dimensional v a n ': as)
           (Dim.Dimensional v b n ': bs)
           (Dim.Dimensional v c n ': cs)

!*! :: (Muls as bs cs) => F as -> F bs -> F cs
(F a) !*! (F b) = F (a ++ "*" ++ b)

I got an Illegal Instance declaration error :
Illegal instance declaration for
 'Muls
    (Dim.Dimensional v a n : as)
    (Dim.Dimensional v b n : bs)
    (Dim.Dimensional v c n : cs)'
 The coverage condition fails in class 'Muls'
   for functional dependency: 'a b -> c'
 Reason: lhs types 'Dim.Dimensional v a n : as', 'Dim.Dimensional
                                                    v b n
                                                    : bs'
   do not jointly determine rhs type 'Dim.Dimensional v c n : cs'
 Using UndecidableInstances might help
In the instance declaration for
 'Muls (Dim.Dimensional v a n : as) (Dim.Dimensional v b n
                                    : bs) (Dim.Dimensional v c n : cs)'

If I use the UndecidableInstances extension, it seems to work indeed. My question, is why do I need this extension and is there a way I could avoid it ?
Alternatively, I probably could get this working using the type family version of dimensional. Unfortunatly, I need custom units and it's not clear if dimensional-tf supports user defined units.
Answer: By default Haskell requires that instance selection be decidable, ie, that an attempt to decide if an type satisfy a constraint cannot cause an infinite loop in the compiler. Consider the following code:
class A (a :: *)
class B (a :: *)
instance A a => B a

This obviously instance could cause an infinite loop (it won't do so necessarily!). Even if every other instance by itself can't cause an infinite loop, the addition of this instance can. There is probably a rigorous proof of this somewhere but I don't know it.
The only thing UndecidableInstances does is say "I promise I will never call my functions with types which cause infinite loops, so even though my instances can produce infinite loops, I accept responsibility for making sure that doesn't happen."
On the other hand, instances of the form:
instance (C1 a1, C2 a2 ... Cn an) => C (T a1 a2 .. an)

Will never produce an infinite loop, since Haskell doesn't allow infinite types, and this instance unpacks a single constructor, so even if Ci refers back to C you will eventually get to a type constructor which has 0 type parameters.
If you write an instance which is not decidable, you should get
test.hs:26:10:
    Constraint is no smaller than the instance head
      in the constraint: A a
    (Use UndecidableInstances to permit this)
    In the instance declaration for `B a'

I think this is the error you should see in your case and that displaying the error you actually see should be considered a bug.
Comment: Why is it "obvious" that it can cause an infinite loop ?
Comment: @mb14 Would you agree that the proof that `instance C a => C a` can produce an infinite loop is trivial? The same principle is at work in the above case. Since the universe of type class instances is open, the constraint `A a` in `instance A a => B a` *could* end up containing a `B a` once it was expanded. So `A a` could be equal to something like `C1 a, C2 a, .. Cn a, B a`. This would make the instance reduce to `instance (C1 a, C2 a, .. Cn a, B a) => B a`, which is trivially overlapping.
Comment: Ok, or  I suppose I could have also `instance B a => A a`.


Global Filter as main menu drop down link

Question: I'm looking for right steps to implement Global Filter module not as a block, but rather as an main menu links. The biggest problem is that each user can see only links they have access to (taxonomy access). So it's not possible to make these links static.
I've tried to include a block in the menu link, but that's not what I want.
Has anybody an idea where I could begin?
Comment: I came a little bit forward. I have placed Taxonomy menu exactly how i wanted. But now I only need to replace all automatic generated links taxonomy/term/$id to ?my_filter_field=$id. I can't find where I have to do it. It were very helpfull for me.
Answer: To rewrite your taxonomy URLs (you should probably rewrite your question to this end) you can use the following.
<code>/*
 * Modify taxonomy uris to point back to facetted search
 */
function my_module_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_my_module_term_uri';
}

/**
 * Rewrite term URIs to point to our search query.
 */
function _my_module_term_uri($term) {
  $path = null;
  // Do your stuff to get your path correct.

  // Return your path if you've managed to rewrite it.
  if ( $path ) {
    return array(
      'path' => $path,
      'options' => array(), // url style options
    );
  }

  // Otherwise just return the default.
  return taxonomy_term_uri($term);
}
</code>
Comment: Thank you. I have found another possibility, but the redirect does not work at all.         function test_entity_info_alter(&$entity_info) {
      $entity_info['taxonomy_term']['uri callback'] = 'test_taxonomy_term_uri';
    }

    function test_taxonomy_term_uri($term) {
      switch ($term->vocabulary_machine_name) {

        case 'voc1':
          return array(
            'path' => 'voc1/' . $term->tid,
          );
        break;

        default:
          return array(
            'path' => 'no_voc/' . $term->tid,
          );
        break;
      }
    }


Adding comma between array items except for last (wordpress)

Question: I'm trying to list authors for a certain category on Wordpress and I'm having trouble inserting a comma between each item, except for the last.  Here's my code:
<?php
 if (is_category() || is_tag()) {
  $at_least = 1;
  $author_array = list_author_in_this_cat ($at_least);
  foreach (array_slice($author_array, 0, 10) as $author):
   $name = get_userdata($author)->display_name;
   $link = get_userdata($author)->user_login;
   echo "".$name."";
  endforeach;
 }
?>

Comment: What's wrong with just joining them?
Comment: Get all items except the last one (use `array_slice()`), `implode()` it with a `,`, and concatenate the result with the last item.
Comment: See: http://us2.php.net/array_map + http://us3.php.net/implode
Answer: Try this:
$nameArray = array();
foreach (array_slice($author_array, 0, 10) as $author):
    $name = get_userdata($author)->display_name;
    $link = get_userdata($author)->user_login;
    $nameArray[] = "".$name."";
endforeach;

echo implode(',', $nameArray);

This will put each author entry into an array; when you echo it out, you're merging the array using commas as the glue.
Comment: Andrewski, having a problem that I didn't realize previously.  Rather than linking to the author.php, it is linking to "localhost:8888/author/author-name".  Any thoughts on how I can get it to link to the author page?
Comment: If that's all you need, you should be able to fix it by changing the `href` to whatever you need - `href="/author/author.php"`, or wherever you need to link to.


Large SATA hard drive for Intellistation A Pro 6217

Question: I posted this question to the IBM forums, but got no response!  I'm hoping someone here will be able to help.
I have recently become the lucky new owner of an Intellistation A Pro 6217. I would like to install some large SATA disks, but have not been able to find information regrading any limits on drive size that the BIOS supports. I have upgraded the BIOS from PXJT125 to PXE136A, which I believe to be the most recent BIOS.
The documentation I've seen shows that IBM supplied SATA disks as large as 500GB - has anyone successfully installed drives larger than this?
Before I splash out on a couple of drives, can anyone offer advice on what is likely (or unlikely!) to work. I'm hoping to put a pair of 1.5TB drives in if possible.
Thanks,
Dan
Answer: Barring some fluke drive incompatibility, that workstation should support all SATA drives on the market today (limited to 1.5Gbps). It's got a Silicon Image 3512A SATA chipset (which is none too impressive, but works well enough).
Comment: Thanks Chris - unless I get advice to the contrary, I'll give it a go in the next couple of week and report back here with my findings.
Comment: Worked without a problem.  It's now sporting two 1.5TB SATA drives.


Strange characters while reading gzipped CSV file

Question: I'm trying to read a CSV file, that I saved as UTF-8 encoded file. When I try to read the file with Pandas, it takes a lot of time but I get the desired output.
out_pd = pd.read_csv('../files/example_file_out.csv.gzip', sep='\t', encoding='utf-8', compression='gzip')

Doing almost the same in Spark to read exactly the same file from HDFS:
out_spark = spark.read.format('csv').options(header = "true", sep = "\t", encoding = "UTF-8").load("/Path/to/Folder/example_file_out.csv.gzip" )
out_spark.show()

With this result:
+-----------------------------------------------------------------------------------------------------+
|���_�example_file_out.csv.gzip�Ѳ�Fr$�|�l�A?��̈��L��F��cWZ�F��Ef�^�5C�k�hW���H$��j�xH�}N|
+-----------------------------------------------------------------------------------------------------+
|                                                                                @�#"<=<^�������...|
|                                                                                ?��ϟ���Ͽ��O�����...|
|                                                                                ރ����Y�^�x�o��e>Y...|
+-----------------------------------------------------------------------------------------------------+
I really don't know what I'm doing wrong. Thanks in advance for your help!
Comment: try changing the file extension to `.gz`?
Comment: Related: https://stackoverflow.com/a/49502965/480982
Comment: ...or wait for the https://issues.apache.org/jira/browse/SPARK-29280 to be implemented.
Comment: Thank you! That answered my question. As i mentioned below i've read some json.gzip files prior to the csv file and had no problems. Only the show() function takes for ever which is a little bit strange, because the json files are not as big as the csv. The latter works perfectly now. I'm now curious why the show() function takes that long, even though it may not belong in this topic.
Answer: Spark infers the file compression format using the file extension. By default gzipped files have the extension .gz, so if you rename your file to have an extension of .gz instead of .gzip, Spark should be able to decompress the csv file properly.
Comment: Thank you, i will do that immeadiately. The only reason why I haven't tried that yet is because I've read other gzipped files without any problems. Or does it only apply to csv files, that it's better to use .gz instead of .gzip?
Comment: I think it doesn't apply to csv files only - all other files should have the extension `.gz` for Spark to process properly. Not sure why other files worked for you.


Find the chromatic number of the graph below.

Question:
I know the chromatic number can't be 2 because there's a cycle of 5 there. I tried 3 but to no avail. So I assume the answer is 4. But I can't prove that it's four and not three. Can someone help out? Thanks.
Comment: The next time you have a question like this, please consider **LABELLING THE VERTICES IN YOUR DIAGRAM**. That will make it easier for people to write answers to your question, and it will make it easier for you to read those answers.
Answer: Adding notation: Let A be the vertex at the top of the whole thing, and B, C, D, E the other vertices of the outer pentagon, in counter-clockwise order (descent from A to the left on the drawing). Use r, b, g to denote three colors (red, blue, green). I will show that a coloring with three colors is not possible. The proof is by contradiction: assume a coloring with three colors is possible.
Start with the outer pentagon. It must use all three colors as you observed already; and it can't use one color more than twice. (Prove that!) So then the five vertices must use one color once, and the other two colors twice - and those must alternate around the pentagon. For symmetry reasons, we may assume A=r, B=b, C=g, D=b, E=g (with an obvious meaning).
Now let M, N, P be the midpoints of AC, AD and BE. Then M=b, N=g, P=r (Prove!)
Let X and Y be the two vertices at the base of the small triangle inside the whole thing (the midpoints of BD and CE). Continue the reasoning from where I left it off (two more steps, same nature) to show that X and Y must both be r. Which is the desired contradiction.
This also shows the graph can be colored with four colors: at the very end, all you have to do is color Y with the fourth color.
Added: As bof shows in his comment below, what I showed above is not a complete proof, because the graph does not have rotational symmetry, it is only symmetric in the vertical axis. So let's fix that.
Let's say the color that is used only once in ABCDE is r. The case B=r is easy; we may assume A=g, E=b, D=g, C=b. Then M=r, P=g, X=b, and the midpoint of PX has no color left for its coloring.
Finally, say C=r and A=g, B=b, D=g, E=b. Then M=b, X=r, Y=g, and then the midpoint of PX must be g, then P=r and finally the midpoint of PY is b. But this is connected to M which is also b, contradiction.
Thank you bof!
Comment: Err... yes, you are correct. I wasn't thinking straight.


$f(x)=x^3+ax^2+bx+c$ has roots $a,b$ and $c$

Question: How many ordered triples of rational numbers $(a,b,c)$ are there such that the cubic polynomial $f(x)=x^3+ax^2+bx+c$ has roots $a,b$ and $c$?
The polynomial is allowed to have repeated roots.
Answer: [There was a mistake in the first version of this answer that caused one solution to go missing.]
The only monic polynomial with roots $a,b,c$ is $(x-a)(x-b)(x-c)$, so we must have
$$
\begin{align}
a&=-a-b-c\;,\\
b&=ab+bc+ca\;,\\
c&=-abc\;.
\end{align}
$$
If $c=0$, this becomes
$$
\begin{align}
a&=-a-b\;,\\
b&=ab\;,\\
\end{align}
$$
and thus either $b=0$ and $a=0$ or $a=1$ and $b=-2$.
If $c\ne0$, the third equation becomes $ab=-1$; substituting $b=-1/a$ into the first equation yields
$$
c=-2a+\frac1a\;,
$$
and then the second equation becomes
$$
-\frac1a=-1+2-\frac1{a^2}-2a^2+1\;.
$$
Multiplying through by $a^2$ yields
$$
2a^4-2a^2-a+1=0\;.
$$
The solution $a=1$ is readily guessed, and dividing through by $a-1$ yields
$$
2a^3+2a^2-1=0\;,
$$
which has one irrational and two complex roots (computation). The solution $a=1$ leads to $b=c=-1$.
Thus the only ordered triples are $(0,0,0)$, $(1,-2,0)$ and $(1,-1,-1)$, with corresponding polynomials $x^3$, $x^3+x^2-2x$ and $x^3+x^2-x-1$, respectively.
Comment: Not much familiar with solutions of biquadratic equations..."no real solutions since the first term is non-negative and the quadratic equation obtained by dropping it has no real solutions" Please explain... and I hope you need to arrange the possibilities of the second case (1,-2,0) in 3! ways because a,b and c can be permuted in 3! ways... Please tell if I'm wrong...
Comment: @Raj: No, there's no symmetry among $a$, $b$ and $c$. They are coefficients of different terms of the polynomial. You can also see from the three equations in the beginning that they play different roles. Perhaps more convincingly, just try it out; $0$ isn't a root of $x^3+x^2+0\cdot x-2$. On your first question: This is not a biquadratic equation. What are the roots of $2a^2+a+1$? The fact that they're not real implies that $2a^2+a+1$ never changes sign; since it's positive at $a=0$, it's always positive. Adding the non-negative term $2a^4$ doesn't change that.
Comment: Abc 123 points out that the third equation should be $c=-abc$
Comment: @Ross: Thanks; correcting that mistake yields one further solution.
Comment: @Raj: Please note that the first version (to which your comment refers) contained a mistake that caused one solution go missing; sorry about that.


O que é o padrão Adapter?

Question: O que é e como funciona o padrão Adapter em Java, estou tentando entender esse padrão pois irei utilizar o mesmo em um projeto.
Comment: É estranho você querer usar uma coisa que você não entende. Padrões não foram feitos para você escolher e usar. Eles foram feitos para usar quando existe a necessidade. E para saber se tem a necessidade é preciso entendê-lo.
Comment: Talvez o padrão esteja citado no documento de arquitetura, é comum quando um sistema ou parte dele é projetado em alto nível e a implementação delegada a outra equipe.
Comment: É projeto de faculdade, requisito do professor @bigown
Comment: Fazendo uma colinha básica no Stackoverlow. Brincadeira :)
Comment: @WallaceMaxters eh mais ou menos, mais pra entender msm, pq tenho q desenvolver um projeto nesse padrao
Answer: Em resumo, o padrão de projetos Adapter consiste em adaptar a interface de uma classe ou objeto para ser usada de outra forma, porém sem alterar a interface ou implementação.
Exemplo: persistência em diferentes serviços
Um caso comum é quando desenvolvemos um código cliente que pretende usar diversas fontes heterogêneas.
Por exemplo, você tem várias implementações capaz de ler e gravar arquivos de diversos serviços:
class DropBox {
    void upload(DropBoxFile dbFile) {}
    DropBoxFile download(String id) {}
}

class AWS {
    void save(InputStream input, int id) {}
    InputStream restore(int id) {}
}

class GoogleDrive {
    void send(byte[] data, String name) {}
    byte[] get(String name) {}
}

Cada uma dessas classes está em uma biblioteca ou projeto diferente. Você não quer fazer alterações nem duplicar o código.
Agora imagine que você tem um sistema onde o usuário pode decidir em qual serviço os dados serão salvos. Uma saída é escrever um código procedural cheio de ifs e elses cada vez que o sistema precisar usar um dos serviços disponíveis, exemplo:
if (dropbox) {
  //faz alguma coisa
} else if (aws) {
 //faz outra
} else if (drive) {
 // outra ainda
}

Mas você não vai querer isso várias vezes no sistema, mais o código necessário para converter os tipos do sistema para os tipos específicos dos serviços. Pense em quanta manutenção seria necessária para adicionar um novo serviço
Então podemos definir uma interface de persistência:
interface Persistencia {
    void gravar(File file);
    File ler(String id);
}

Todo o sistema seria implementado usando apenas esta interface. Uma maravilha do ponto de vista da Orientação a Objetos, sem ifs, sem necessidade de alterar o código se algum serviço mudar.
Mas o problema não está completamente resolvido. As classes dos serviços que nós não queremos alterar não implementam nossa interface.
Então, para cada serviço, devemos implementar um adaptador. Por exemplo:
class DropBoxAdapter implements Persistencia {
  DropBox dropBox;
  DropBoxAdapter(DropBox dropBox) {
    this.dropBox = dropBox;
  }
  void gravar(File file) {
    dropBox.upload(new DropBoxFile(file.getAbsolutePath());
  }
  File ler(String id) {
    DropBoxFile dbFile = dropBox.download(id);
    return new File(dbFile.getLocalPath());
  }
}

Note que acabamos de criar uma classe que nos permite usar um objeto DropBox usando a interface Persistencia. Nós adaptamos a classe original conforme a interface desejada.
Outras implementações de adapters deveriam então ser providas para os outros serviços usando o mesmo princípio.
Exemplo: melhorando código legado
Agora imagine que temos de dar manutenção num sistema mal projetado que implementa logs manualmente usando a seguinte classe:
class HomeMadeLog {
    public void log(int nivel, String mensagem, Throwable erro) {
        String s = formatarLog(nivel, mensagem, erro);
        adicionaLogNoArquivo(s);
    }
    private String formatarLog(...) { }
    private String adicionaLogNoArquivo(...) { }
}

Precisamos modernizar os logs usando um framework como Log4j, porém há milhares de chamadas ao método antigo e muitas delas são complicadas demais para simplesmente fazer uma substituição automática.
Além do mais, queremos evitar gerar alterar 99% dos arquivos do projeto, pois isso iria gerar um grande problema de conflitos no sistema de controle de versões para todos os demais desenvolvedores.
Uma solução é estender a classe HomeMadeLog de forma que ela seja um adaptador para o Log4j. Exemplo:
class HomeMadeLogToLog4jAdaptor extends HomeMadeLog {
    Logger logger = Logger.getLogger();
    @Override
    public void log(int nivel, String mensagem, Throwable erro) {
        if (nivel == 0) logger.debug(mensagem, erro);
        else if (nivel == 1) logger.info(mensagem, erro);
        else if (nivel == 2) logger.error(mensagem, erro);
    }
}

Agora basta fornecer uma instância de HomeMadeLogToLog4jAdaptor ao invés HomeMadeLog e todas as classes passarão a funcionar com o Log4j sem modificações.
Considerações
Note que o principal trunfo do padrão de projetos Adapter é permitir reuso do código de forma consistente, mantendo compatibilidade com outras bibliotecas e versões anteriores de código.
Uma classe adaptadora nada mais é do que uma classe que implementa a interface que se deseja usar e delega a real execução para uma classe terceira que possui a implementação que desejamos usar.
Note também que meus exemplos são propositalmente simplificados. Alguns detalhes e complexidades que não são relacionados com o padrão em si foram omitidos para não complicar os exemplos.
Comment: No caso do exemplo do Log4j eu teria de necessariamente substituir a referência da classe HomeMadeLog pela HomeMadeLogToLog4jAdaptor em todas as classes, correto? Ou nesse exemplo você está considerando que quem fornece a HomeMadeLog seria um construtor estático e, nesse caso bastaria substituir o retorno pela subclasse?

O que é o padrão Adapter?


Pentatonic Scales Question

Question: I'm learning the notes on the fret board and I just wanted to ask something about the pentatonic scales you see, A minor pentatonic is A C D E G on the 5th fret, but when I play it on the 2nd fret its G A C D E, can someone tell me what's the theory behind this? Thank you guys
Comment: Music works relatively - it's all about intervals from a starting note. All you've done is move the starting note so it all still works with itself, just a bit lower down the fretboard :-)
Answer: It's the same scale, you just start on a different note. For example if you start on the 8th fret, you will play the notes C, D, E, G, A. It's all the same scale just where you start is different and there are many places you can play it on the neck of your guitar.

This picture shows everywhere that you can play the A minor pentatonic scale. The red dots are the root note of the scale the A in this case.
Once you remember the patterns you can easily shift it to any key. Just find the root that you want and the scale falls into place.
Comment: It's worth it to learn [all five patterns.](http://guitarteacher.com/wp-content/uploads/2010/02/CAGED-in-G-3.png)  It's all the same scale, just different places to play it. Just remember where the roots are because those are important when improvising. Also, A minor pentatonic is the same as C Major pentatonic, so if you play the same scale but start and end on C you get a Major Pentatonic form. All five shapes can be used for both Major and minor, only the position of the root notes change.
Answer: I believe understanding this would be much easier if we differentiated between patterns and shapes. The pattern of a major pentatonic scale is 22323, a minor pentatonic scale follows the pattern 32232. The numbers refer to the semi-tone distances between the notes. So the pattern for the major pentatonic A gives us the notes A B C# E F# back to A, and the pattern for the minor pentatonic scale in A results in A C D E G back to A. The respective first shapes of each pattern start with the root note on the sixth (low E) string.
Answer: Each of the five patterns would be a mode of that pentatonic scale. Adding the flat five (of your original A minor pentatonic) in each of those positions opens up new improvisational ideas too.

Pentatonic Scales Question


The Mean Value Theorem ( Increasing at point)

Question: As I go over some important topics in Calculus (by Salas), he stated such a theorem;

"Suppose that $\ f(x)\ $ differentiable at $\ x=c,\ $ if $\ f'(c)>0,\ $ then
$f (c − h) < f (c) < f (c + h)\ $
for all positive $\ h\ $ sufficiently small. "

But some times we cannot find such "$\ h\ $" at some point even though the derivative there is positive; ex.
$f(x)=$\begin{cases}x+2x^2sin(1/x) & x\neq\ 0\\ 0 & x=\ 0 \\ \end{cases}
the derivative at $\ 0\ $ equals $\ 1 $; however, it is not possible to find any open interval around zero satisfies the condition since the derivative values fluctuate between negative and positive about zero, this condition satisfies only if the function is increasing at some point. So, did I make a mistake and what is the correct understanding?
Comment: $f(x) = x(1+2x\sin(1/x))$ *is* positive for small $x > 0$, and negative for small $x < 0$.
Comment: Why do you think that the derivative of $f$ at $x=0$ is $1$?
Comment: Yes the derivative of that function fluctuates around $c=0$. But this is irrelevant. What is relevant is that for any $\ h>0,\ f(c-h)<f(c)<f(c+h)\ $, that is, $\ f\ $ is increasing *at the point* $\ c=0$.
Comment: @aexl the derivative at x=0 equal 1!!
Comment: @AdamRubinson Robert Bartle stated in his book (Introduction to Real Analysis) that increasing at some point implies the function should be increasing on some neighborhood of the point, he mentioned this example and said that thi function is neither decreasing or increasing at 0!!!
Comment: "Robert Bartle stated in his book (Introduction to Real Analysis) that increasing at some point implies the function should be increasing on some neighborhood of the point". Then I think Robert Bartle is wrong, and your function is a counter-example. Unless he has a non-standard definition of "increasing at a point"?
Comment: @AdamRubinson As I remember Stephen Abbott (Understanding Analysis) mentioned same definition on the exercises, same thing with Kenneth A.Ross (Elementary Analysis: The Theory of Calculus) I think in some exercise has asked to prove that some particular function is not increasing nor decreasing at 0, despite the derivative there is positive.
Answer: It is true that $f$ is not increasing or decreasing in any interval containing the origin, but that is not what the theorem claims.
We can verify the conclusion of the theorem in this case directly: For $0 < |x| < 1/2$ is
$$
 1+2x \sin(1/x) \ge 1-2|x| > 0 \, ,
$$
so that $f(-h) < f(0) < f(h)$ for $0 < h < 1/2$.
In other words: For fixed $c$ are

$f(c-h) < f(c) < f(c+h)$ for sufficiently small positive $h$.

and

$f$ is increasing on $[c-h, c+h]$ for sufficiently small positive $h$.

different statements. The former holds if $f'(c) > 0$, but not necessarily the latter.
Comment: @HumamKh.: I am not sure if I understand what you mean. The theorem does *not* claim that $f$ is increasing near $c$. It only claims that $f(x) < f(c)$ in some interval $x \in (c-h, h)$ and $f(x) > f(c)$ in some interval $x \in (c, c+h)$.
Comment: @HumamKh.: That is correct. As I tried to explain in the answer, the first statement is true, but the second statement can be false (as your example demonstrates).
Comment: Where does $1+2x \sin(1/x)$ come from?
Comment: @AdamRubinson: From $f(x) = x(1+2x\sin(1/x))$. The second factor is positive for small non-zero $x$, and then has $f(x)$ the same sign as $x$.
Comment: Yes, I see it now. Thanks.
Comment: thank you a lot, that seems precisely. But still have small note if you don't mind about second conclusion that "f is increasing", I think the inequality is not so far right since for all "h" you'll find δ such that δf(c+δ)>f((c+δ)+ξ) ∧ f((c+δ)-ξ),f(c+δ),f((c+δ)+ξ) ∈ [c-h,c+h] ; ξ is positive arbitrary small number, which means f(x) is not so far increasing on the interval [c-h,c+h].
Comment: @MartinR , Everything is alright, I was just wondering about your conclusion above "f is increasing on [c-h,c+h] for sufficiently small positive small h. " which I think seems contradict with theorem but you re-answered me and said "The theorem does not claim that f is increasing near c.". Now I think I understand the theorem in the right way. Thanks, that was very helpful.
Comment: @MartinR Last thing I want to be sure with it, your conclusion above that "f is increasing on [c-h,c+h]" because you re-answered me that it's not increasing. It only claims that f(x)f(c) in some interval x∈(c,c+h). Thank you for cooperation.


Get-ADUser over multiple OUs and filter results

Question: This script is supposed to grab users from several OUs and assign the users to one variable, then it takes the users from that variable and filters through each one based on last logon dates over 30 days of age. Then it exports to a CSV with some info I'd like.
The problem is, when I get to the foreach part, it searches through the entire directory and doesn't use the users in the variable I supplied.
Any criticism is greatly appreciated as well.
$30days = (get-date).adddays(-30)

$Users1 = Get-ADUser -SearchBase 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'
$Users2 = Get-ADUser -SearchBase 'OU=Users-Remote,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'
$Users3 = Get-ADUser -SearchBase 'OU=Contractors,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'
$Users4 = Get-ADUser -SearchBase 'OU=Temps,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'
$Users5 = Get-ADUser -SearchBase 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'
$Users6 = Get-ADUser -SearchBase 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com' -LdapFilter '(UserPrincipalName=*)(extensionAttribute9=*)'

$Users = $Users1,$Users2,$Users3,$Users4,$Users5,$Users6
$useraccountsover30days = foreach ($user in $($Users)){Get-ADUser -filter {lastlogondate -le $30days} -Properties lastlogondate}

$lastlogonreadable = $useraccountsover30days | Select-Object SamAccountName,lastlogondate

    $lastlogonreadable | Export-Csv C:/Users/myname/Desktop/Usersover30days.csv

Answer: There are a few recommendations I'd make with your current script.
First off, a single large query is almost always going to perform better than many smaller queries. So rather than running get-aduser separately for each target OU, I would combine them into a single call using a higher level common OU as the search base. Obviously, this may end up returning results from OUs you didn't want to include. But it's much faster to filter those out later.
You're also calling get-aduser again for each result from the first set of queries just to filter on lastLogonDate. But you could instead combine that filter with the -ldapfilter from your original queries. It's just a matter of converting the -filter version with an equivalent -ldapfilter version. The secret to doing this is knowing that lastLogonDate is just a Powershell converted version of the lastLogonTimestamp attribute. And you can convert a normal Powershell DateTime value into the format that lastLogonTimestamp uses with the ToFileTime() method.
The last thing that confused me was the (UserPrincipalName=*) portion of your ldapfilter. In every domain I've ever touched, this attribute will always have a value (just like SamAccountName or DistinguishedName). It may be different than the default value of <SamAccoutnName>@<DomainFQDN>, but it's never empty. The filter isn't hurting anything necessarily. It's just one extra thing for AD to spend CPU cycles evaluating when it doesn't need to. But if you have reason to believe it might be empty in your environment, by all means leave it in.
So here's how I'd modify your script if I understand your intentions correctly.
# make the comparison value using ToFileTime()
$30daysago = (Get-Date).AddDays(-30).ToFileTime()

# make the combined ldapfilter value
$LdapFilter = "(&(lastLogonTimestamp<=$30daysago)(extensionAttribute9=*)"

# make an array of the OU DNs you care about
$TargetOUs = @(
    "OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com"
    "OU=Users-Remote,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com"
    "OU=Contractors,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com"
    "OU=Temps,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com"
)

# define your common search base
$base = "OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com"

# get your combined results and the additional attributes you care about
$OldUsers = get-aduser -ldapfilter $LdapFilter -searchbase $base -pr lastLogonDate

# convert the target OU list into a regular expression we can compare each DN against in a single comparison call
$regex = ""
$TargetOUs | %{ $regex += ".*," + [Regex]::Escape($_) + "$|" }
$regex = $regex.Substring(0,$regex.Length-1)

# filter the results that aren't in your target OUs
# (depending on your OU layout, it might be more efficient to flip this
#  and define the OUs you explicitly want to leave out)
$FilteredUsers = $OldUsers | ?{ $_.DistinguishedName -match $regex }

# export your CSV (sorted for good measure)
$FilteredUsers | select SamAccountName,LastLogonDate | sort LastLogonDate | export-csv C:/Users/myname/Desktop/Usersover30days.csv

P.S. Be wary of treating lastLogonTimestamp (or lastLogonDate) as 100% accurate. It may be anywhere from 9 to 14 days out of date by design.
Answer: I solved a similar request for multiple OUs with repeating the same set like the following multiple times with the OU specified:
get-aduser -filter 'enabled -eq $true' -Properties Name, LastLogonDate, AccountExpirationDate, description, Department, title, UserPrincipalName -SearchBase "OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com" | Where-object {$_.lastlogondate -lt (get-date).AddDays(-30)} | Select-Object Name, LastLogonDate, AccountExpirationDate, description, Department, title, UserPrincipalName | Export-csv C:\temp\users-nologin-30.csv -Encoding UTF8 -Append -NoTypeInformation -Force -Delimiter ";"

It gets all enabled Accounts, with the properties Name, LastLogonDate, AccountExpirationDate, description, Department, title, UserPrincipalName and appends it to a csv-File. As stated in the other Answer 30 days can be not precise, so better call for 44 days just to be sure.
If "LastLogonDate" is empty, the user has never logged on, perhaps it is a new Account.
Answer: You never use the $user value in the Get-ADUser call...try changing the $UsersX value to the parameters you need to send to Get-ADUser and substitute them in...and since you're reusing the same LdapFilter, might as well make that a variable as well.  (Also, you're reusing the "OU=Users,OU=US-Location" three times, I assume that's just for example purposes?)
$30days = (get-date).adddays(-30)

$LdapFilter = '(UserPrincipalName=*)(extensionAttribute9=*)'

$Users1 = 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users2 = 'OU=Users-Remote,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users3 = 'OU=Contractors,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users4 = 'OU=Temps,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users5 = 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users6 = 'OU=Users,OU=US-Location,OU=Americas,DC=Domain,DC=Domain,DC=com'

$Users = $Users1,$Users2,$Users3,$Users4,$Users5,$Users6
$useraccountsover30days = foreach ($user in $($Users)){Get-ADUser -SearchBase $user -LdapFilter $LdapFilter -filter {lastlogondate -le $30days} -Properties lastlogondate}

$lastlogonreadable = $useraccountsover30days | Select-Object SamAccountName,lastlogondate

    $lastlogonreadable | Export-Csv C:/Users/myname/Desktop/Usersover30days.csv

Comment: I don't believe you can use the -Filter and -LdapFilter in the same call to Get-ADUser.
Comment: Searchbase expects a string, and not an array!


What is the value of (Vandermonde matrix)$^4~$?

Question: This is Vandermonde matrix:

$\omega$ is primitive N-root.
What is $W^4$?
I'm trying to calculate it but I don't know how exactly....
Thank you!
Comment: try to calculate $W^2$ and use the result, $\sum_{i=0}^{i=N-1}\omega^i=0$
Comment: it is not Vandermonde?
Comment: @Kumar - I tried but I don't know exactly how...
Answer: Firstly when u say $\omega$ is a primitive N-root, it means it is a root of $X^{N-1}+X^{N-2}+...X+1$ and so is $\omega^{2},...,\omega^{N-1}$.
First try to see what $W^2$ is, what will be the $i+1,j+1^{th}$ element of $W^2$
$\frac{1}{N}(1+\omega^{i+j}+\omega^{2(i+j)}+...+\omega^{(N-1)(i+j)})=0,$ if $i+j\neq0, N, 2N$ and $=1$ if $i=j=0$ or $i+j=N$ or $2N$. So,
$$W^2=\begin{bmatrix}
    1&0& \dots &0 & 0 & 1 \\
0 &0 & \dots&0&1&0\\
\vdots& \vdots& ⋰&\vdots\\
1&0&\dots&0&0&1
  \end{bmatrix}$$
Therefore,
$$W^4=\begin{bmatrix}
2 & 0 & \dots&0 &2 \\
0 & 1 & \dots&0 &0\\
\vdots& \vdots& \ddots&\vdots&\vdots\\
0&0&\dots&1&0\\
2 & 0 & \dots&0 &2
  \end{bmatrix}$$
Comment: It's: $\frac{1}{N}\cdot (1+\omega^{i+j}+\omega^{2(i+j)}+...+\omega^{(N-1)(i+j)})=0,$?
Comment: Yes It is $\frac{1}{N}$, hope it is more clear now. Hope this answered your question
Comment: Why $\frac{1}{N}(1+\omega^{i+j}+\omega^{2(i+j)}+...+\omega^{(N-1)(i+j)})=0$ if $i+j\neq0, N, 2N$?
Comment: because then $\omega^{i+j}$ is a solution of the polynomial above.
Comment: BTW, Why do you put out the $\frac{1}{N}$, where it came from? and how the matrices will be without it? Thank you!!


ERROR: JETTY_HOME not set

Question: I have tried installing Jetty server on my Ubuntu 12.04 following this steps. But when I start my server I get the following error,
service jetty start
** ERROR: JETTY_HOME not set, you need to set it or install in a standard location
Comment: Have you considered doing exactly that?
Comment: related: http://serverfault.com/q/374699/127106
Comment: Yes I tried doing the same by adding in /etc/environment but ended up with the same error. As far as I searched JETTY doesn't need the variable to be set explicitly and is set by Jetty's start mechanism. (start.jar)
Answer: Here's a pointer in the right direction: JETTY_HOME refers to an environment variable set with a value corresponding to the directory path where you have installed jetty.
https://stackoverflow.com/questions/2655641/set-environment-variable-in-ubuntu
Comment: I am new to linux after years of using window and hence having some difficulties. I followed this tutorial to install Jetty  [link](http://pietervogelaar.nl/ubuntu-12-04-install-jetty-9/#comment-9071) step by step and was getting the mentioned error. I did google and I did try setting the environment variable explicitly but wasnt working. Thanks.
Answer: This is a rather frustrating error with little help out there. I thought I'd post my solution here for someone who is looking to solve the same problem.
Anyway, the correct solution is to set JETTY_HOME in /etc/default/jetty like so:
 JETTY_HOME=/opt/jetty

Hope this helps someone.

ERROR: JETTY_HOME not set


Postgres JSONB Query searching dynamic path

Question: I have a Postgres json field products with jsonb like this
{
  "user": "7871425f-abb4-42c6-8e4d-36c99ec2f67c",
  "product": {
    "ef688ed3-12c9-4e22-af5f-32a7b32db628": {
      "category": "basic"
    },
    "8fbef749-42dd-4a40-a98a-ebe7b54c4388": {
      "category": "advanced"
    },
    "d475185f-d014-4c60-aebd-cecaed7df550": {
    }
  }
}

I am trying to extract category for each product to get something like
"ef688ed3-12c9-4e22-af5f-32a7b32db628": "basic"
"8fbef749-42dd-4a40-a98a-ebe7b54c4388": "advanced"
"d475185f-d014-4c60-aebd-cecaed7df550": NULL

Any help highly appreciated
Answer: jsonb_each() would do the trick:
SELECT  key
    ,       value->>'category'
FROM    jsonb_each('{
  "user": "7871425f-abb4-42c6-8e4d-36c99ec2f67c",
  "product": {
    "ef688ed3-12c9-4e22-af5f-32a7b32db628": {
      "category": "basic"
    },
    "8fbef749-42dd-4a40-a98a-ebe7b54c4388": {
      "category": "advanced"
    },
    "d475185f-d014-4c60-aebd-cecaed7df550": {
    }
  }
}'::jsonb ->'product');

The sort order is up to you.


Uploading files to two separate locations

Question: I'm uploading a clients website early next week and they've just informed me that they use load balancing software to distribute over two servers.
Normally this wouldn't be an issue because content is stored in the database and as long as both files areas can access it then it should be fine.
However, the issue comes in when uploading files. I've been informed that files should be uploaded to both servers.
I wouldn't even know where to begin to make this modification. Can anybody shed some light on it for me?
Is there a global method that's invoked when files are uploaded?
Note: This needs to work with the file field on several content types and even when files are added through modules/cck
Answer: I very much suggest a solution which actually shares the files/ directory.
My primary recommendation here is some dedicated hardware. To avoid marketing for anyone in particular, I just recommen you read, on Wikipedia, SAN and FAN.
If hardware is out of the question, then we have good experience with NFS for direct sharing. Samba on the other hand has proven to be to slow.
There is also a "native" Drupal solution called Storage API which can do a lot of neat things with your files, but I don't think your particular needs can be solved out of the box, but would require some extra coding.
I would only use some type of syncing as a last resort, but here's a really basic bash-script you could cron run. The major part of this script is a safeguard so it will refuse to start if it's already running.
<code>#!/bin/bash
LOCK_FILE=~/.lockfile

if [ -f "${LOCK_FILE}" ]; then
  PID=$(head -n1 "${LOCK_FILE}")

  TEST_RUNNING=$(ps -p ${PID} | grep ${PID})

  if [ -z "${TEST_RUNNING}" ]; then
    echo $$ > "${LOCK_FILE}"
  else
    exit 0
  fi
else
  echo $$ > "${LOCK_FILE}"
fi

rsync -az local_files/ username@host:/remote/path/to/files
rm -f "${LOCK_FILE}"

exit 0
</code>
Answer: I would imagine that if the 2 storage servers are accessible from the web server through a share or mount, then you can make some system calls in your custom module to copy the file to the 2 locations.
Or do something really clunky with the sysadmins and do a schedule task or cron job to mirror a directory.


How to point domain name into an IP address (ubuntu server)?

Question: I have one ubuntu server running in a specific ip address. Multiple apps are running with the help of gunicorn and nginx. I can access all those apps after editing the '/etc/hosts' file in my local machine.
Then, I bought a domain name. Now, the problem I'm having is to point my domain name to my ip address of the server.
I contacted the domain provider but they told me 'for custom name server you need to contact your hosting provider to point A record on your branded name server'. This went over my head, as I'm not familiar with these.
I researched a bit and found the use of 'BIND' but I'm not 100% sure. I don't want to end up breaking my server. So, what do i do?
Answer: When you get a domain they just register it for you. But it won't activate unless few DNS records are published to the internet, informing about its existence. A DNS server has to be there to announce those records and enable you to define sub-domains under it.
Either you run that name server yourself, OR you have to buy a hosting space, by which you get a name server you can add records to. Providers usually try to sell you the second option. BIND is one of name server programs you may run on your server to do the job. This is a bit technical and is not suggested unless you know what you are doing.
Comment: I assumed DNS records are provided after domain is registered and it can be edited. I didn't know that I had to buy the hosting space to be able to edit the DNS records. Job done. Thanks.


How to create a product without a variation?

Question: I'm migrating to drupal commerce (kickstart 2) from woocommerce and contao isotope.
My biggest problem was/is understanding the terminology behind it - product types, variations, etc.
In woocommerce and isotope the product categories would be for example:
- Books
- Computers
- T-Shirts.
Each category would then have individual products in it, and each product would have optional variation.
I'm having hard time understanding this in kickstart2. More than that, is it even possible to create a product without variations? How can I create a store of simple unique products that would belong to different categories (woocommerce terminology), without variables.
For example:

Books: product1, product2, product 3, ... (no variables)
PCs: -- || --
...

Thanks.
Answer: It is - as You said - difference of terminology.
The easiest way for You would be trying this: https://simplytest.me/
Here You can quickly test Drupal modules and whole distributions. Please try Commerce Kickstart with this tool and during install click to install demo content.
There You'll see that Variations are more like Categories in Your meaning:
Each product display must have one or more product variations, which is why each product display type has a matching product variation type.
Different product variation types have different fields, used for storing images, attributes such as color and size, as well as any other information.
And Categories are more like taxonomy - You can list colors, sizes etc there and reuse it in multiple products.
Hope i helped You a little :)
Comment: Thank you for answering. So basically, I can create let's say variation type: books.
And then, I could put in several products in this "category" with only one variation:
- product 1
- product 2, ...etc.
Comment: Let's use this books example.
So You have 5 different books to sell.

First you create the categories - for informations about the books like:
 - Soft Case/Hard Case
 - Book / eBook etc

Then You can create variation type: Books -> where You group those fields.

Then You create a product of type Books -> and You fill the fields.
If You want to offer two kinds of the same product - like eBook/Book, or hardcase/softcase -> then You can create another variations for each type - they can vary in price etc.

For another book - you just create another product.
Comment: A product variation is a combination of fields. (More or less like a content type vanilla Drupal.) For books these fields could be author, title, description, etc. You can use the books variation for every book in your site. However, if you also want to sell lunchboxes, these fields are irrelevant. More interesting would be the size and the color. These would be new fields and you would require a new product variation for all lunchboxes. Variations are bundles of fields that products have in common.


Fastest way to generate shuffled range array form zero to x

Question: I'm trying to find the fastest way to generate a shuffled array of indices. A shuffled range from 0 to a number, so to say.
Currently I've compared these two methods:
setup = "import numpy as np; idxlen = 1000; rng = np.random.default_rng(); matrix = -np.ones([100,idxlen],dtype=int)"
test1 = "rand_idxs = np.arange(idxlen);
         rng.shuffle(rand_idxs);
         matrix[0][:] = rand_idxs"
test2 = "matrix[0][:] = rng.choice(range(idxlen),idxlen,replace=False)"
print(timeit.timeit(test1, setup, number = 10000))
print(timeit.timeit(test2, setup, number = 10000))

Returning the following timings:
0.1846354000736028
0.950088300043717

I assume that under the hood, the rng.shuffle() method randomizes the indices of the array past to it, and rearranges it according to those indices. Now, since I'm generating an array containing every integer from 0 to a certain number, this practically corresponds to generating randomized indices. So I can't shake the feeling that there is a faster way to do what I'm trying to achieve. Is there?
Answer: If you remove range from the test two then you will see changes and find test2 is faster then first
import timeit
setup = "import numpy as np; idxlen = 1000; rng = np.random.default_rng(); matrix = -np.ones([100,idxlen],dtype=int)"
test1 = "rand_idxs = np.arange(idxlen); rng.shuffle(rand_idxs); matrix[0][:] = rand_idxs"
test2 = "matrix[0][:] = rng.choice(idxlen,idxlen,replace=False)"
print(timeit.timeit(test1, setup, number = 10000))
print(timeit.timeit(test2, setup, number = 10000))

Now for testing
for idxlen=1000
0.15045420000024023
0.24143790000016452

for idxlen=10000
1.4334205999984988
1.3395810999973037

for idxlen=100000
14.489788099999714
8.599601199999597

Also there is one more method that is np.random.Generator.permutation
And the testing for this method are these
test3 = "matrix[0][:] = rng.permutation(idxlen)"

for idxlen=1000
0.1567758999990474

for idxlen=10000
1.4174363000020094

for idxlen=100000
13.964398899999651

In the end the comparison of timing between all three
Graph for number=10000

Code for graph


How to easily display a 12 by 12 matrix of input field for integers?

Question: I am still very new to Drupal. I need to let users create nodes to enter 12 by 12 matrix of numbers on one screen block. I don't really know where to start regarding displaying those fields (i.e. layout).
Is there a module/functionality helping defining the layout of those 144 input field in a square shape in Drupal? Some kind of WYSIWIG layout editor? Or, should I try to position those input fields with Javascript within a block?
Thanks.
Comment: Whatever the user enters in the matrix is just for display or there will be any processing you'll do on the numbers? Can you explain more as to whats the purpose of the node, matrix etc?
Comment: There will be some processing performed based on these numbers once they are stored in the database. Typically, the node content would be exposed via a Services for external application to fetch, process and put the result in a new node...
Answer: Might be worth trying CCK table field or Table Field
Both seem to do a very similar function, I would give them both a try on a local dev environment
Answer: if you're using drupal 7, you already have your work done using fieldAPI, its the part of core and you dont need to download any additional module.
All you need to do is to create a content type and add a field to it using field API, now the creation of field is your job, you need to create a field which will hold the serialized data of first 12 columns. When finalizing the creation of your field, you will specify the number of field instances in the field creation form, and you can put 12 in it.
Now on the UI you can show 12 fields in columns whose serialized data will go in single instance of you field
Comment: you can even create you custom field using Field API which can contain 12 instances of 12 fields, but it would need a little RnD
Comment: I am ready to cover that extra mile if it helps, I have tech skills, just missing Drupal skills (I climbing the learning curve). Thanks for the pointer, I'll definitely investigate this option.
Comment: Unfortunately, one can only create 10 instances of a field in the creation form... I also need the users to be able to edit the cells...


How to select droid sans condensed font?

Question: I see that a Driod Sans Condensed font is available on the android, but from what I can see the android:typeface attribute can only have the following values - normal, sans, serif and monospace.
Question is how do I select this "condensed" font? Also, it's not clear from the page which version onward is this font available.
EDIT:
I ran a test with two TextView objects having typefaces set to normal and mono respectively and as far as I can tell there's no difference between the two.
Answer: Looks like Droid Sans Condensed is not included in the SDK, but it's available for purchase:

http://www.droidfonts.com/droidfonts
http://www.ascenderfonts.com/font/handset-condensed-family.aspx

If you decide to buy it, you can use it in your app this way:
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
textView.setTypeface(font);

Comment: This is a free font, do not pay for it.


Cannot access SimpleResponse from dialogflow webhook using Dialogflow Android Client. Cant acess Payload

Question: Cannot access webhook payload in my android app. Therefore I am unable to show responses from the webhook into my chatbot interface in android. Can someone help me with this?
Answer: Use the following Dialogflow Android client SDK to communicate between Android and Dialogflow.
Comment: I am using this library only. However the getSpeech() method only fetches the hardcoded text response from dialogflow. I want to display responses from webhook.


Conditional independence for multiple variables

Question: Say we have a situation where A depends on B, and B depends on C. If I'm not mistaken, this means that A is independent of C given B (even though B depends on C, A given B sort of indirectly incorporates that already- that's how I understand it)
And we have the probability functions for
P(A|B) and P(B|C) and P(A,B|C)
There should be a way to get P(A|C) directly. My first guess is that P(A,B|C) can be changed into P(A|C), but I'm not sure how.
It makes sense intuitively since we have a chain of dependence, but I don't know where to start with the math. I tried using the chain rule and rearranging
$$P(A,B|C) = \frac{P(C|A,B)P(A|B)P(B)}{P(C)}$$
But I'm not sure how to rearrange that further
Comment: What exactly do you mean by "There should be a way to get $P(A|C)$ directly"? In general, if you know $P(A,B|C)$, you can use the relation $P(A|C) = \sum_{\mathcal{B}} P(A,B|C)$.
Comment: Your argument about the conditional independence of A and C does not convince me. It seems that all what you know is that $P(A \cap B) \neq P(A)P(B)$ and $P(B \cap C) \neq P(B)P(C)$. I do not see how can you conclude that $P(A \cap C \mid B) = P(A \mid B)P(C \mid B)$ using probability axioms. what do you mean by "get $P(A\mid C)$ directly"? Do you mean in terms only of $P(A \mid B)$, $P(B \mid C)$ and $P(A \cap B \mid C)$?
Comment: Yes, that's what I meant by P(A|C). Sorry for the confusion. What I was trying to convey was a case where A only depends on B. But B in turn depends on C. And we're also given P(A,B|C). Supposedly that's enough to get an equation for P(A|C) in terms of P(A,B|C). I'm just not sure how to go about doing that.
Answer: I think that you can't establish a relationship between event A and event C from the given information. The dependency and independency between event A and event C might occur. You can utilize Venn diagram to illustrate both cases. The given information indicates $\text{A} \!\cap\!\text{B}  \neq \varnothing$ and $\text{B} \!\cap\!\text{C} \neq \varnothing$. Now your goal is to check $\text{A} \!\cap\!\text{C}  \stackrel{?}{=} \varnothing$ from the given information. Using Venn diagram, the dependency and independency between event A and event C might occur. For the later case, see the below picture

Now is it possible to show the former case? Yes, it is. See the below picture,

Notice that for both cases, $\text{A} \!\cap\!\text{B}  \neq \varnothing$ and $\text{B} \!\cap\!\text{C} \neq \varnothing$ hold.


Replace an null element in a list with a value

Question: I have an issue in the code snippet below:
I have a list of list, some of which is empty. First I want to replace the empty value with a value and then flatten it.
Here's the code snippet:
a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]

flat = ['0' if i == '[]' else i for element in a for i in element]

But I'm unable to get the result. Kindly help
Comment: You might want to keep strings: `[v[0] if v else '0' for v in a]`
Comment: `[]` and `'[]'` are two very different values.
Comment: why are some resulting values mutated to strings?
Comment: Thanks @Matthias, you literally saved my life
Comment: This is where I wish `list` had a `get` method: `[v.get(0, '0') for v in a]`.
Answer: You can use next with a default value
flat = [next(x, "0") for x in a]

or just the fact that an empty list is falsy
flat = [x[0] if x else "0" for x in a]

Comment: Didn't know you could use `next` like that. That's really useful.
Answer: Try the below code,
Code1 -
a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]
updated = [val[0] if val else '0' for val in a]
print(updated)

Code2 (For understanding purpose in a long form) -
a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]

for i in range(len(a)):
    if a[i] == []:
        a[i] = '0'
    else:
        a[i] = a[i][0]
print(a)

Both the above code fulfills your requirment.
Answer: Here is another way to flatten it to a 1-dimensional array, but it doesn't replace the empty array as 0.
from itertools import chain

a = [
    ['3'],
    ['4'],
    [],
    ['6']
]

flatten_list = list(chain.from_iterable(a))

print(flatten_list)


How to make the height of div same as width to create responsive squares when using grid system?

Question: I'm using Skeleton boilerplate to create my grid. The grid I'm trying to achieve consists of 3 squares per row. I have tried making the height percentage (33.33%) but it still doesn't create a square. Thank you! :)
Answer: On CSS3 you will use vh unit, this is same at percentage unit, is relative, in this case to viewport height.
33.33% as same to 33.33vh and your box should adjust to view height of viewport.
View all Css Units.
example

.box{
  width: 100%;
  height: 33.33vh;
  }
.foo{background-color: red;}
.bar{background-color: purple;}
.na{background-color: blue;}

These are Relative Unit on CSS.
Try one of them.


Show Search Suggestions while typing in landscape-mode

Question: i already get the search suggestion while typing in the searchfield of the search-dialog. While typing in Portrait-Mode, the result are listed under the search-dialog. But when i change into landscape-mode, the text-input-field of the searchdialog becomes fullscreen (i hope you know what i mean) and the search suggestions couldn't be see anymore. i know for example from google maps that also in landscape mode the search suggestions are show under the "big" text-input-field...Wich code should i type to get this "view" while typing in landscape-mode?
Thanks!
Thomas
Comment: Can you show your layout code for that screen?
Answer: If you want your suggestions to show up in landscape, you need to do one of the following:

Add SUGGEST_COLUMN_QUERY to your suggestion results
Add android:searchMode="queryRewriteFromText" or ``android:searchMode="queryRewriteFromData"to yoursearchable.xml`

However, I think for suggestions it's nicer to just show the normal popup instead of a fullscreen keyboard. You can achieve this by adding android:imeOptions="flagNoExtractUi" to your searchable.xml.
And that's all. If you're curious, here's how I tracked this down:
Hierarchy Viewer will tell you that the search dialog is implemented by SearchDialog, which uses an AutoCompleteTextView for the completion text view. Its buildDropDown() function calls Filter.convertResultToString() (through convertSelectionToString()) on the items returned by the AutoCompleteTextView's mAdapter.getItem() and then passes these on to InputMethodManager.displayCompletions() (which is responsible for the suggestions you want).
In the case of SearchDialog, the adapter is a SuggestionsAdapter. This is a subclass of CursorAdapter, whose getFilter() method returns a CursorFilter class, which implements convertResultToString() by just delegating to convertToString() on the adapter class. SuggestionsAdapter finally implements this method as follows:
public CharSequence convertToString(Cursor cursor) {
    if (cursor == null) {
        return null;
    }

    String query = getColumnString(cursor, SearchManager.SUGGEST_COLUMN_QUERY);
    if (query != null) {
        return query;
    }

    if (mSearchable.shouldRewriteQueryFromData()) {
        String data = getColumnString(cursor, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
        if (data != null) {
            return data;
        }
    }

    if (mSearchable.shouldRewriteQueryFromText()) {
        String text1 = getColumnString(cursor, SearchManager.SUGGEST_COLUMN_TEXT_1);
        if (text1 != null) {
            return text1;
        }
    }

    return null;
}

…which results in the recommendations in the first paragraph above.


Basic Property of Finite Presentation of Modules

Question: I'm struggling to prove some rudimentary facts about finite presentations of a module $A$ over a ring $\Lambda$, which is defined in Hilton/Stammbach's A Course in Homological Algebra as a short exact sequence $0 \to N \to P \to A \to 0$ with $N$ finitely-generated and $P$ finitely-generated projective.
I'd like to show that if $A$ has a finite presentation, then for all short exact sequences $0 \to R \to S \to A \to 0$ with $S$ finitely-generated, $R$ is also finitely-generated. Here's my progress so far: If we denote the surjective maps in the two exact sequences above by $\epsilon : P \to A$ and $\epsilon' : S \to A$, then since $P$ is projective we have a map $\alpha : P \to S$ such that $\epsilon = \epsilon'\alpha$. We can identify $N$ with $\operatorname{Ker}{\epsilon}$ and $R$ with $\operatorname{Ker}{\epsilon'}$. We then have $\alpha(\operatorname{Ker}{\epsilon}) = \alpha(P) \cap \operatorname{Ker}{\epsilon'}$, and here I get stuck. We know that $\alpha(\operatorname{Ker}{\epsilon})$ and $\alpha(P)$ are finitely-generated, but how do we use this to show that $\operatorname{Ker}{\epsilon'}$ is finitely-generated? A hint would be much appreciated.
Answer: The simplest way is to make a pullback diagram
$$\require{AMScd}
\begin{CD}
{} @. {} @. 0 @. 0 \\
@. @. @VVV @VVV \\
{} @. {} @. N @= N \\
@. @. @VVV @VVV \\
0 @>>> R @>>> Q @>>> P @>>> 0 \\
@. @| @VVV @VVV \\
0 @>>> R @>>> S @>>> A @>>> 0 \\
@. @. @VVV @VVV \\
{} @. {} @. 0 @. 0 \\
\end{CD}
$$
The rows and columns are exact; the arrows marked with equality are easily seen to be isomorphisms when $Q$ is the pullback of the maps $P\to A$ and $S\to A$.
Since $N$ and $S$ are finitely generated by assumption, $Q$ is finitely generated as well. Since $P$ is projective, the sequence $0\to R\to Q\to P\to 0$ splits and therefore $R$ is finitely generated.
Another way is to use Schanuel's lemma. In order to do this, take a finitely generated projective module $S'$ and an epimorphism $S'\to S$; let $K$ be the kernel of the composition $S'\to A$. Then, by Schanuel's lemma, $K\oplus P\cong N\oplus S'$, which implies $K$ is finitely generated because $N\oplus S'$ is.
The homomorphism theorem provides a surjective homomorphism $K\to R$.


Como listar dados de JSON em uma div usando jquery?

Question: Amigos, tenho o seguinte JSON:
{
"codigo": "12345",
"cerca": "Rato",
"host": "df",
"eventos": [
    {
        "data": "21\/02\/2020",
        "hora": "19:38",
        "local": "Moema\/SP",
        "status": "Morto",
        "subTim": [
            "Um dia sem PC"
        ]
    },
    {
        "data": "21\/02\/2020",
        "hora": "18:29",
        "local": "Tatuapé\/SP",
        "status": "Meio vivo",
        "subTim": [
            "Quatro dias sem PC"
        ]
    },
    {
        "data": "21\/02\/2020",
        "hora": "18:09",
        "local": "Anápolis\/GO",
        "status": "Só tonto",
        "subTim": [
            "Dois dias sem PC"
        ]
    }
]}

Consigo carregar no form corretamente alguns dados do JSON assim com JS:
jQuery("#codigo").val(resposta.codigo);
jQuery("#cerca").val(resposta.cerca);
jQuery("#host").val(resposta.host);

Qual a maneira correta jquery de listar os "eventos", com "data", "status" e "subTim" em uma div de nome #ocorridos no form ? Exemplo:
Ocorridos: Meu código: 12345 / Cerca: Rato / Host: df

Evento1: 21/02/2020 19:38 / Status: Morto / SubTim: Um dia sem PC

Evento2: 21/02/2020 18:29 / Status: Meio vivo / SubTim: Quatro dias sem PC

Evento3: 21/02/2020 18:09 / Status: Só tonto / SubTim: Dois dias sem PC
Desde já muito obrigada pela atenção de vocês
Answer: Colega, o código está meio engessado. Dá pra fazer melhor (mais dinâmico). Mas dá uma olhada e vê se te atende. Qualquer dúvida, você avisa no comentário, que eu tento melhorar algo. Você poderia adaptar melhor de acordo com sua necessidade. Essa resposta foi só pra te dar uma ideia de onde partir.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE-edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Utilizei jQuery (como você solicitou) e Bootstrap (só usei para dar uma alinhada ali, por preguiça de fazer em CSS, rs). Espero que sirva pra você.
Comment: Deu certinho @Gambi, sua resposta foi de grande ajuda. Obrigada.
Comment: Funcionou perfeitamente Gambi, minha ultima dúvida sobre: Como fica ao invés do let json, carregar esses mesmos dados json de uma url externa? let url = "https://.... ? a estrutura da resposta da url remota é a mesma.
Comment: @AnaCavalcante , não deu pra responder antes, pois eu estava com a conta bloqueada pelo absurdo motivo de manipulação de votos. Mas você já conseguiu resolver seu problema ? Dá pra fazer essa sua situação com Ajax.


Remove cookies by cookie name in nginx reverse proxy

Question: I am fairly new to nginx and I am trying to set it up as a reverse proxy server. So far I have apache working as a backend server on 8080 and nginx on port 80.
My website uses a lot of cookies which I have no control on... I am using Expression Engine CMS, and it does not allow me to disable the cookies that I don't want (don't want to mantle with EE core code).
So lets say that a typical hit on my homepage returns cookies A, B and C which I don't use. Sometimes I also have cookies D and E which I need.
I want to set up nginx to hide cookies A, B and C from the response and return cached content only if the request is cookie free or cookies D and E are empty.
Is that possible to set up under nginx?
So far I have this in my config, which ignores any cookies. I just want to ignore or hide certain cookies:
proxy_cache_path /opt/nginx/cache levels=1:2 keys_zone=mycache:20m max_size=1G;
proxy_temp_path /opt/nginx/tmp_cache/;
proxy_hide_headers Expires Cache-Control Set-Cookie;
proxy_cache_use_stale error timeout invalid_header http_502;
proxy_cache_bypass $cookie_nocache;
proxy_no_cache $cookie_nocache;

...
location / {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_cache mycache;
    proxy_cache_valid  200 302  6h;
    proxy_cache_valid  404      1m;
    proxy_pass http://x.x.x.x:8080;
}

Comment: Because you are using 'proxy_ignore_headers' on Set-Cookie, you are going to cache responses even if they do have cookies D or E, that may not be what you want.
Comment: yeah, I need proxy_hide_headers but only on the ones that I want to hide
Answer: Wouldn't it be possible to explicitly set the cookie-headers? So something like:
add_header Set-Cookie "A=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com
add_header Set-Cookie "B=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com
add_header Set-Cookie "C=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com

You could use proxy_set_header with the header name "Cookie" instead of add_header, if it doesn't work. I don't have a development nginx instance running here so I can't test..
Sources:

http://wiki.nginx.org/HttpHeadersModule#add_header
http://en.wikipedia.org/wiki/HTTP_cookie
Comment: proxy_set_header sets the headers that are sent to the backend (apache in this case), so that won't do what you want in this case.
Comment: You're right about that. Edited my response.
Comment: The proposed solution does not work on my setup: the cookie set and delete are being sent in the same header, which apparently causes the browser to effectively set the cookie instead of ignoring or removing it.


SQL Incorporado no C#

Question: Tenho uma aplicação em C# que usa um banco de dados MySQL com Entity Framework. Entretanto, o tamanho do banco é ridiculamente pequeno, de modo que não acredito que valha a pena ter um servidor de banco de dados MySQL apenas para rodar esta aplicação.
Qual seria abordagem para que o banco de dados ficasse incorporado na aplicação, de forma que ela pudesse ser executada sem estar conectada a nenhum servidor?
E como eu transportaria os dados do banco de dados para esta nova solução?
Comment: Oi @Felipe, acho uma boa idéia neste caso usar o SQLite, ele é um arquivo (extensão .db) e tu usa as referencias dele no C#, não fica rodando nenhum serviço, você pode as bibliotecas [aqui](https://sqlite.org/download.html) ou também [aqui](https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki) e para visualizar uso o [SqliteExpert](http://www.sqliteexpert.com/download.html) que tem a versão free e a paga..
Comment: Oi Marco! Me pareceu uma excelente ideia! Obrigado pela dica! Abraço!
Answer: A solução normalmente é usar o SQLite. Ele é um banco de dados incorporado e costuma atender a maioria das necessidades das aplicações, principalmente se não há acesso direto vindo de máquinas diferentes. Note que o acesso indireto funciona bem sem problemas, o que é normal em aplicações web ou que possuem um servidor de aplicação (middleware ou algo do tipo).
Ele atende grandes volumes de dados e acessos muito bem. Só teria problemas se tiver uma quantidade muito grande de escritas longas efetivamente simultâneas.
Existe driver oficial para Entity Framework disponível.
Veja quando usar o SQLite.
Obviamente que existem outras soluções possíveis se não quiser um banco de dados incorporado, como apresentado em outras respostas. Nelas haverá a conexão com um servidor, mesmo que ele não esteja remoto.
O transporte de dados se dá de forma tradicional. Ou usa um software cliente, possivelmente GUI, igual de qualquer outro banco de dados, e tem bastante opção, ou faz programaticamente, nesse caso claro que teria que fazer uma conexão com o banco de dados não incorporado para ler os dados que serão escritos no SQLite, ou teria que se conectar a um serviço seu que forneça os dados (conectando no servidor).
Answer: Existe opções de instalação do MySQL diretamente no Android, transformando-o num Server.
Uma uma boa opção seria migrar seu banco para o MariaDB (versão OpenSource do MySQL) e usar o :
https://play.google.com/store/apps/details?id=com.esminis.server.mariadb
Answer:
Qual seria abordagem para que o banco de dados ficasse incorporado na aplicação, de forma que ela pudesse ser executada sem estar conectada a nenhum servidor?

Uma boa abordagem é o SQL Server LocalDb. Ele é idêntico ao SQL Server Express e usa as configurações do Entity Framework idênticas, da mesma forma.
Projetos ASP.NET MVC5 normalmente são criados com o LocalDb sendo usado por padrão.

E como eu transportaria os dados do banco de dados para esta nova solução?

Usando o SQL Server Management Studio.
Utilize o assistente de migração.
Aqui tem o plugin do MySQL.
Comment: Valeu Cigano! Mais uma vez me ajudando muito!
Comment: Obrigado, Cigano! Acho que é a opção mais adequada mesmo. Sabe me dizer se, ao criar um arquivo de instalação, posso integrar este recurso? Ou o cliente teria que instalar a parte?
Comment: Pode. [A ideia está aqui](http://stackoverflow.com/a/15867103/1314276).
Comment: Cigano, tua ideia deu muito certo no meu computador. Ele cria uns arquivos .mdf e tudo funciona bem, até no instalador. Entretanto, quando eu instalo em outro PC, a princípio dá um erro falando que não consegue conectar no SQLServer. Eu instalei o arquivo SQLLOCALDB.MSI e o erro mudou. Diz que não consegue criar o arquivo pois ele já foi criado... Tem alguma dica de como fazer ele funcionar com a instalação em qualquer computador?
Comment: Você se certificou que o LocalDb está instalado em outro computador? [Aqui tem o instalador em separado](https://www.microsoft.com/pt-br/download/details.aspx?id=42299), para 32 e 64 bits.
Answer: O fato é saber se você realmente precisa persistir/salvar esses dados. Se sim, terá que ser em algum lugar. Essa parte é ontem toma-se a decisão sobre persistência.
Muitas vezes, usar um banco de dados simples como o MySQL é mais vantajoso - como simples e rápida implementação - do que tentar uma solução mais "criativa".
Então a pergunta é: você precisa persistir dados?
Se sim, qual vantagem você enxerga em não ter um banco de dados? Qual problema você irá resolver não tendo um serviço de persistência como um MySQL?
Se não, pode-se partir para uma solução In Memory, como instanciar um System.Data.DataSet, nele criar todas as tabelas e relacionamentos que sua aplicação precisa. Então fazer um primeiro seed de dados para sua aplicação começar a funcionar. Essa é uma opção onde, caso sua aplicação seja reciclada, todos os dados serão limpos e iniciará do zero.
Importante também considerar que sua aplicação já existe e já está funcionando com um banco de dados. Vale a pena remove-lo? O ROI - retorno de investimento - é interessante? Pois remover um banco de dados, já implementado com EF, irá custar algumas horas do desenvolvedor para a adaptação.
Comment: Oi Thiago! Os dados são apenas para consulta. Ela ainda não foi instalada no cliente e estou querendo evitar instalar e configurar o banco de dados. Porém, como os dados já estão no MySQL gostaria de uma forma simples de transportá-los. Eu já vi algumas abordagens parecidas, mas nunca utilizei...
Comment: @FelipeBulle, use um banco de dados local. Os da [resposta](http://pt.stackoverflow.com/a/150796/3825) do Cigano são bem convenientes.

SQL Incorporado no C#


How to write guitar solos from a keyboardist perspective?

Question: I'm a keyboardist and sole composer in a band, and usually I write organ/keyboard solos, but I wanted to write a guitar solo for one of the songs. I would let the guitarist make his solo, but he is a primarily rhythm guitarist without lead experience. So, I tasked myself with writing the solo.
I wanted to know differences when writing for guitar compared to keyboards. I know the basics, such as range, speed, chord voicing, and interval limitations, however I don't really understand how to phrase for guitar, and how to apply the textural changes, such as bending, vibrato, hammer-ons/pull-offs, etc.
I'm aware that this question is super wide and not specific at all, but I don't really know what I don't know. When I search on YouTube how to write a guitar solo, they tend to be broad tips on how to construct a solo and not instrument specific. I don't know where to begin, and when I try to write for keyboard and move it to guitar, it doesn't sound like it belongs on guitar. If there is a clarification needed, feel free to leave a comment, and I'll try to add more information.
Comment: The solo will be greatly influenced by the kind of music that is to be played. There could be a dozen different answers at the moment - none of which may help! More info. please. Having a dabble on guitar will be advantageous.
Comment: The chord sequence for the solo helps to develop that solo. Maybe post that?
Comment: It's a progressive rock band, and the tone is meant to be dark. It is in 5/8 in Phrygian. I want the solo to be more about the melody and rhythm rather than note density/virtuosity.
Comment: Some would say a solo should not be written, but I suppose it depends on the style of music.
Comment: When you say 'writing' the solo, do you mean actually writing the part out, or just coming up with some ideas on keyboard that the guitar can elaborate on? There's a big difference!
Comment: @Tim The chords are F minor and Ebmin7, but I'm not adhering to the progression; I'm writing it solely in F Phrygian. I am actually writing out the solo. Usually I wouldn't do this but I'm trying to establish thematic material to develop the song, and I want the notes to be carefully chosen.
Answer: The best way to write for an instrument you are unfamiliar is, is to work together with whoever is going to be playing the part.
Start by writing the piece as you imagine it, in a way that you think will work. Then show this to your guitarist and get them to play it for you. You'll get plenty of feedback on what works and what doesn't, and things you can improve. Modify your piece and try again. After a couple of iterations of this, you'll probably have something that works well and sounds good.
In general just writing the notes you want is a good start. A guitar player will know how to phrase the music and when to use things like bends or vibrato. They'll use those effects automatically
Comment: Also, if you get used to playing solo parts on a keyboard with the _feel_ of a guitar — for example, using pitch bend and mod along with solo-type sounds — then some of that may come naturally.
Answer: ''I don't really understand how to phrase for guitar, and how to apply the textural changes, such as bending, vibrato, hammer-ons/pull-offs, etc.''
Well, you can't turn the keyboard into a guitar. However it's easy enough to emulate (and a surrogate emulation it is) a guitar solo on keyboard: use the pitch wheel for bending, some overdrive or distortion (yuck! this will sound quite bad as keyboards use digital distortion, whereas proper guitar sounds use tube amp distortion), and also use the pentatonic scale more than other scales, and hey presto. You have a great emulation of a guitar solo. :)
The best way to emulate it would be actually to learn a simpler guitar solo on keyboard, one that isn't too difficult, such as the ones found in 'Hotel California' or such songs. It will sound poor, again you can't turn a keyboard into the sound of Jimmy Page and his Marshall amp. As for phrasing your solos, that's a whole other field. If you can't phrase nicely, no solo will ever sound really that good, on any instrument.
And of course, don't forget Amazon. Surely many other keyboardists wrote books about how to do what you want to learn to do on keyboard.


Trouble with uploading certain files PHP

Question: I just got a dedicated server and I can't upload MP4, MPEG, or FLV files.
I'm debugging and am not even uploading right now.  I'm just doing this when the form / upload script is posted:
    if(!empty($_REQUEST['add_lesson_info'])) {

            echo $video_name = $_FILES['add_lesson_video']['name'];
            echo '
';
            echo $video_type = $_FILES['add_lesson_video']['type'];
            echo '
';
            echo $video_size = $_FILES['add_lesson_video']['size'];
            echo '
';
            echo $video_tmp_name = $_FILES['add_lesson_video']['tmp_name'];
            echo '
';
    ........

When I upload any jpg, jpeg, png, or gif if outputs the data.  But, if I try MP4, MPEG, or FLV it doesn't output any data.  Any reasons why? Thank you.
Note: this wasn't an issue on a shared server.  So, it could be some root setting I'm unaware of.
Here's the php.ini
register_globals = off
allow_url_fopen = off

expose_php = Off
max_input_time = 10080
max_execution_time = 10080

;extension_dir = ./
upload_tmp_dir = ./tmp

;precision = 12

session.cache_expire = 10080
session.cookie_lifetime = 200000
session.gc_maxlifetime = 10080

memory_limit = 100M
post_max_size = 100M
file_uploads = On
upload_max_filesize = 192M

Comment: It probably has something to do with the max filesize allowed, since videos tend to be larger than images. I would check the `php.ini` for these settings.
Comment: *UPDATED.  I added my php.ini
Comment: Have you considered checking $_FILE[']['error']?
Comment: Have you looked at your logs?
Comment: http://www.php.net/manual/en/features.file-upload.errors.php
Answer: Before you do any further manipulation of uploaded files you need to make sure there were no errors during the upload. That's the part where you have to check $_FILES['field_name']['error'] where you'll find a corresponding code indicating what might have gone wrong.
Here are the values which $_FILES['field_name']['error'] returns. Anything other than 0 or UPLOAD_ERR_OK means there was a problem during the upload.