Why does my condition on %{REQUEST_METHOD} not appear to work in my apache .conf file

Question: I was trying to whittle down the cases where the Access-Control-Allow-Origin is sent in a response to only some specific scenarios such as only for specific request methods. In this situation we already included the response header on all requests for a specific directory but then after adding the If condition below it no longer seems to work.
<Directory "/var/www/myapp">
<If "%{REQUEST_METHOD} == 'HEAD'">
  Header set Access-Control-Allow-Origin 'https://some.example.com'
</If>
</Directory>

What's more is that I have also tried to debug this through various means and from what I can tell the %{REQUEST_METHOD} variable is not being resolved correctly. Here are the tests that I've done to determine this so far.
✔ No condition includes the header as expected.
<Directory "/var/www/myapp">
  Header set Access-Control-Allow-Origin 'https://some.example.com'
</Directory>

✔ Condition which should always be true, includes the header as expected.
<Directory "/var/www/myapp">
<If "'HEAD' == 'HEAD'">
  Header set Access-Control-Allow-Origin 'https://some.example.com'
</If>
</Directory>

❌ Add a header to echo the value resolved by %{REQUEST_METHOD} seems to break Apache, response comes back with no headers looks like an error in handling.
<Directory "/var/www/myapp">
  Header set X-Method "%{REQUEST_METHOD}"
  Header set Access-Control-Allow-Origin 'https://some.example.com'
</Directory>

I can't help to think that I must have some syntax wrong but I've checked things over several times and nothing sticks out to me.
Comment: I have not yet, as the nature of workarounds go, I was able to get past this issue as a blocker and haven't had the chance to circle back. I'll try the `LogLevel` next time though, but I'm not that familiar with Apache logs and troubleshooting in general so it may take me a bit to get familiar in general to know that I'm looking in the right place.
Comment: The syntax seems fine as you wrote it in first code sample. I think that REQUEST_METHOD is not equal with HEAD. check that cases is matching. Try also with regex matching. Increase `LogLevel` - see httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging and test with `curl`
Comment: That was my thought too @MirceaVutcovici, I tried ` ` as well as the debug case with `X-Method` to see if it was a casing issue but neither of these seemed to support a case mismatch scenario. Instead it seems to me the best I can tell that %{REQUEST_METHOD} just isn't resolving in some cases or that I'm somehow getting the syntax wrong. Oddly enough in my workaround in `RewriteCond` it seems to work just fine .
Comment: Have you tried also increasing the `LogLevel`? I was just curious what is happening.
Answer: I've found a workaround which appears to be working for me so far but I still want to understand why my original attempt using If conditionals didn't work. To me the workaround below is less readable than my original attempt.
<Directory "/var/www/myapp">
  RewriteCond %{REQUEST_METHOD} 'HEAD'
  RewriteRule ^ - [ENV=cors:true]
  Header set Access-Control-Allow-Origin 'https://some.example.com' env=cors
</Directory>

Shout out to the following references which helped me discover this workaround:

How to Set Apache Header Conditionally
Set multiple headers conditionally with rewrite rules [apache httpd.conf]


X-Frame-Options to sameorigin

Question: My Drupal site is on a subdomain of my old html/php site. So, I am running into problems sharing content from my Drupal site via iFrame.
I looked up solutions that worked for others and the consensus seems to be either edit settings.php
<code>$conf['x_frame_options'] = '';
</code>
Or to use the Securit Kit module to change the X-Frame options to disabled.
I have tried both, cleared the cache and the site with the iFrame is still saying Refused to display https://example.com/entity_iframe/node/1 in a frame because it set 'X-Frame-Options' to 'sameorigin'.
Any ideas?
Answer: The htaccess file was overriding everything. I installed https://www.drupal.org/project/htaccess and added "Header always unset X-Frame-Options"
That fixed it.

X-Frame-Options to sameorigin


Does an English Premier League team play its first 19 fixtures of a season against 19 different clubs?

Question: Does the Premier League have a concept of 'cycles'?
In the first 'cycle' every team plays the other 19 teams once. In the second 'cycle', the fixture venues are reversed (although the fixture order may differ).
Answer: Yes, this is how the games are scheduled unless games get cancelled due to bad weather , ... and are scheduled to be played later on (which usually doesn't happen). The team that hosted the first game will play in the opponents' venue in the second game. This is the conventional schedule for National European football leagues.
EDIT:
So in response to those who downvoted or asked for reference, the following was taken from Wikipedia

There are 20 clubs in the Premier League. During the course of a
season (from August to May) each club plays the others twice (a double
round-robin system), once at their home stadium and once at that of
their opponents, for a total of 38 games

So each 'cycle' mentioned by @Yatizme is a half-season where each team plays the other teams once.
Comment: I didn't downvote, but it would be a much better answer if it had some references.
Comment: FYI.  The second half of the season is not in the same order as the first.
Comment: Why is this answer downvoted?


Creating search pages for specific content types

Question: I am currently in the process of implementing different search pages, with distinct layouts/templates and behaviors for specific content types (a search for "blog" nodes, one for "video" nodes, etc), and I am confused as to what the best approach is for this. I've read that the Facet API module may help implement this behavior. I'm already using Apache Solr for the searching component, is this the best approach and what's the path of least resistance if using Facet API?
Answer: The best method for me is Search API:

This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

Uses multiple backends (solr, database, elastic search), is fully integrated with views, etc.


What is the optimal proportion between the teacher time (lesson) and self dependent work?

Question: I am aware that it is important to practice between the teacher lessons, otherwise they will not bring much use. From the other side, learning self-dependently or just very little guidance is also usually seen as sub-optimal.
What is the optimal, reasonable proportion between the time spent with the teacher and the time spent practicing self-dependently?
This, of course, also depends on the resources available. However probably there is some boundary where adding more teacher time brings much less value for the same duration, and also the boundary when it makes much more sense to take a lesson than keep struggling alone.
If you think this may be instrument specific, please indicate the instrument.
Comment: Is Self Dependant Time a euphemism for practice?
Comment: Something else probably can also be done like reading a music theory book.
Answer: In my experience a week of good practice that includes work on material covered in the lesson goes well with a once a week lesson. How long that lesson should be depends on a few things:

How much time you put in to your practice.
How much new stuff you can handle each week. (Do long lessons leave you feeling overwhelmed?, do short ones leave you feeling underwhelmed? Does a practiced week still leave you with a feeling that you did too little?)
How good your instructor is with disseminating information in the allotted time. (Most professional teachers have a standard of a half hour to work with for most students, and should be able to impart information within that time period.)
How experienced you are. Experienced players tend to benefit from longer lessons.
How much you talk. This is an important one. I have had many students who love to talk, and that talk is nice but it cuts into the lesson time and how much the teacher can convey.

Under the right conditions, a half hour is sufficient once a week. But for advanced students and those who like to talk allot, an hour is often about right. I rarely felt or wished I needed more time than an hour once a week lesson, but I did come across the rare student, or occasion where more time would have been helpful.
This interaction needs to be tailored to the students needs for the most part.
I would also note that Hour long lessons tended to create a more relaxed atmosphere, which helped my performance as a teacher.
Key to success however is the practice time you spend. Spend time practicing every day, and that will make any lesson you have better, more relevant and inspiring. The more time you spend the better. I have heard professionals say they practice 2 or 3 hours a day (there may or may not be limitations here on some instruments). That is probably enough to be really great before too long. I have had successful students (progress making) that practiced 15 minutes a day. 30 minutes a day is probably a good minimum time for a majority of teacher recommendations based on my interaction with other teachers. I tend to emphasize the "every day" part, and "work on material from the lesson" part of the discussion.
One thing to note is the timing scheduling of your practice. 4 hours one day does not equal more practice than a half hour every single day. In fact 5 minutes a day is worth more than one practice session of 4 hours. The consistency of doing it every day helps your brain, muscles, spine, and any other parts you use to form and keep memory and skill from the work you are doing.
Comment: Also how old you are. 10 year olds don't get the same lesson time as adults.
Comment: Oh yes. Often half hour lessons with 8 year olds seem like ten hours.


Form with Multiple fields in table format

Question: I have a requirement to design this type of form for a custom content type. This is one part in a large form.
At first what I did is made a Field Group called Income Information
Inside the Field Group I made new fields:

Age as textfield Integer
Sex as select list
Description as Long text
Family Income as Field Collection

Family Income field collection field would have a collection of fields like Family Member, Income, Savings and Loan.
My question is here how to present this part Family Member, Income, Savings, Loan in a table format as the picture below.
In Family Member: Father, Mother, Spouse are just listed by default. If users want to add some other then there is textbox for that, but the total family member will not increase from 5, that means no add more field button there.
Comment: This is really a lot of different questions, for example, formatting as a table, default values, save as draft, etc. are all their own questions. The title of the post is about formatting as a table so the questino really should just be about that. It helps others make use of any answers you get if you stick to one question per question. Also, asking a bunch of things like this (and asking how to implement a mockup) is basically asking others to do your work for you, which is also not allowed on drupal.stackexchange.
Comment: Hi, jhilke bro ..just another method, you can write custom module for doing this using Drupal "form API". and theming the form.
Comment: and how am I supposed to use the same form in my content type?
Comment: you can add permission to that form for making accessible only for admin. In case of creating content type for your form follow this link.
http://public-action.org/content/drupal-7-field-api-drupal-7-adding-custom-content-type-custom-fields-field-api
Comment: I have formatted my question to put the focal point in my requirements. And no, I am not asking anybody to do my task, I am asking for guidance how I can make the input fields in content type look like table form.
Answer: You have multiple questions, so answering the title one: "Form with Multiple fields in table format"
You can do it with custom code by themeing the form and printing the fields in a table (I can elaborate on this if you want).
One thing to note though is that if you want the user to be able to add more rows to the table this solution gets trickier.
If you do want to add more rows or if you don't want to do custom themeing for your form you you can use the field collection module along with the field collection table module.
It works pretty well, however I currently recommend using the latest dev version of the field collection table module as there are some bug fixes in there you will want.
There are also a few patches in the issue queue that you might need depending on your specific needs, so if you run into bugs (I did when I used it) try searching the issue queue for patches.
Comment: I don't think field collection table would be helpful here because it renders the field collection value in table format that is in view mode , not on node create/edit form. There are very few modules(display suite form,panel fields) available for theming forms element compare to view mode themings. Other wise theming the form is the only thing which could be done in d7.
Answer: This is not going to be pretty, but I've managed to achieve this before by using the '#prefix' and '#suffix' properties of the form elements.
First make sure all the form elements are in the right order, then begin by adding the table html to these properties.
Here's an example:
// This code will give you a table with two columns and two rows:
// one header row and a row with the form fields.
$form['first_form_elment'] = array(
  '#type' => 'textfield',
  '#title' => t('Can have a title'),
  '#prefix' => '

' . t('Header 1') . '	' . t('Header 2') . '

    ',
  '#suffix' => '	',
);

$form['second_form_elment'] = array(
  '#type' => 'textfield',
  '#title' => '', // <-- Can leave title blank.
  '#prefix' => '

    ',
  '#suffix' => '

    ', // Don't forget to close the table rows, and finally the table.
);

As I said it's not a pretty solution but it gets the job done. You can apply it in a form_alter hook.
Comment: This is pretty clever!!
Answer: I personally used Matrix field to achieve something similar but I needed to use the multi value settings module too which is still buggy and poorly maintained.
Matrix field: https://www.drupal.org/project/matrix
Multivalve settings: https://www.drupal.org/project/multivalue_settings
This is what my form looks like:
Answer: One method to achieve this is with a lot of css work.
Conceptually, each row would be a Field Collection (https://drupal.org/project/field_collection) of 4 fields, which would give you the ability to Add More as needed.  If the person's Father has a lot of dependents, this 'table' could get very big.
For achieving the table appearance, I would recommend the illusion of a table.  Create a Markup field with the table header (https://drupal.org/project/markup), hide the Field Collection labels with css, make everything display: inline-block; with solid 1px borders ... etc.
You should then have a content type form with a table that can grow as needed.
A save button for an incomplete form used to mean Required For Publishing (https://drupal.org/project/required_for_pub) but I have not had to find the Drupal 7 equivalent yet.
I doubt that you can nest field collections, so Age, Description, and Gender will need to be moved out to the Field Group.
Making the Description Requirement depend on the fields inside the field collection is not easy with php and drupal, so javascript would be the better choice for that.
Answer: Try this module, https://drupal.org/project/tablefield.
Once you add this field in your content type, add number of rows and columns required in field settings. Look for default value settings for the field and add father, mother, spouse in it. Hope this helps ....


what is the slope of the tangent at the point (4,f(4))

Question: Consider $f(x)=x+\sqrt{x}$ what is the slope of the tangent line to the graph of f at the point (4,f(4)). Just asking: am I doing this wrong?
$$f'(a)= \lim_{h\to a}\frac{f(a+h)-f(a)}{x-a}$$
f'(4)= 4 + ${\sqrt 4}$ =4+2=6 --> f"(a)=6
y - f(a) = f'(a)(x-a)
y - (${\sqrt 4}$) = (6)(x - 4)
y - (-4) = (6)(x - 4)
y + 4 = 6x - 24 + x + 4
y = 7x - 24
= -17x
Comment: You can either use $f'(a) = \lim_\limits{h \to 0} \dfrac{f(a+h)-f(a)}{h}$ or $f'(a) = \lim_\limits{x \to a} \dfrac{f(x)-f(a)}{x-a}$. You want to make sure you get the definition right. What exactly did you do on the second line? (Clearly $f(a) \color{red}{\neq f'(a)}$.) Also, are you supposed to use this definition to find $f'(4)$ or can you use derivative rules?
Comment: i think use this definition to find f'(4) i used the the tangent line equation i think           y-f(a) = f'(a)(x-a)
Comment: You should try it again using the right definition and see if you can get it right. You're supposed to get $f'(4) = \dfrac{5}{4}$.
Comment: yes thank you i got it!! does this mean the domains of f and f' are the same?
Comment: Not necessarily. Note that $f$ is defined at $x = 0$, while $f'$ isn't. Since you got it, why not edit your question and show your work?
Answer: The formula you are using is the alternate definition which is fine to use. The derivative should come out as $1 + \frac{1}{2\sqrt{x}}$. I personally would suggest plug in the function expressions to the limit definition, simplify, then plug in 4 as your x-value. You should get $\frac{5}{4}$. After that, plug $\frac{5}{4}$ for $m$ into point slope form: $y - y_1 = m(x - x_1)$ and substitute $x_1$ and $y_1$ for (4, f(4)). Finally, use Algebra to convert point slope form into slope intercept form.
Answer: The definition is:
$$f'(a) = \lim_{h \to 0} \frac{f(a + h) - f(a)}{h}$$
Start with that. In your case, $a = 4$.


Sum numbers in row of text file (linux command terminal)

Question: Say i have the numbers 6 1 4 in that format, what would be the best way to sum them so that i get the result 11 in the command terminal in linux using bash?
Comment: check for `bc` in google. If that does not help , please share more details about your question.
Comment: how about google a bit ?
Answer: One Line Answer :
$echo "6 4 1" | awk '{print $1+$2+$3}'
11

Answer: You can use bc
a=6; b=4; c=1;
echo "$a+$b+$c" | bc

Output-
11
Answer: With awk, it would be straight forward:
awk '{tot=0; for(i=1;i<=NF;i++) tot+=$i; print tot}' filename

But if you prefer bash-only then you can use a loop:
while read -r line; do
   tot=0
   for val in $line; do
      ((tot+=val))
   done
   echo $tot
done < filename

If the numbers in the file are float then you can use bc or dc as bash doesn't support floating point arithmetic.


PIE disabled. Absolute addressing when asm programming with gcc on mac OS X

Question: I wrote the code below. I want to compile it using gcc on mac OS X,
but I get a message saying "PIE disabled. Absolute addressing" when I run gcc.
I googled it, but cannot find a solution.
Please advise.
hello.s file:
.data
hello: .string "Hello World!\n"

.text
.globl _main

_main:
    push %rbp
    mov %rsp, %rbp
    movabs $hello, %rdi
    call _printf
    leave
    ret

The error:
ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not allowed in
code signed PIE, but used in _main from /var/folders/xs/4z9kr_n93111fhv9_j1dd9gw0000gn/T/ex2_64-369300.o.
To fix this warning, don't compile with -mdynamic-no-pic or link with -Wl,-no_pie

Comment: You must use relative addressing. Instead of `movabs` do `lea hello(%rip), %rdi`. Also, you might have to zero `AL` because `printf` is vararg.
Comment: based on the error message where it says "to fix this warning..." you might try, as I did, `clang -o hello hello.s -Wl,-no_pie` to get what you wrote to assemble and link.  Alternatively, follow the suggestion from @Jester and use `lea`.  @Jester is also correct about `al`.  See section 3.5.7 of the ABI docs.
Comment: Thanks to your advise I complile it completely.
Comment: I don't understand this error completely. In case 32 bit, What do I use instead of 'push $hello'?
Comment: 32 bit is usually not `PIC` except for libraries. You need to use clever trick to get the actual load address of a known reference point and then address relative to that point. This is typically done by fetching the return address from the stack after a `CALL` instruction. For libraries, you get special support by the assembler for handling stuff like `GOT` and `PLT`.
Answer: Looks like there are a couple solutions:

Link with -Wl,-no_pie:

clang -o hello hello.s -Wl,-no_pie

Don't use absolute addressing.

.data
hello: .string "Hello World!\n"

.text
.globl _main

_main:
    push %rbp
    mov %rsp, %rbp
    lea hello(%rip), %rdi
    mov $0, %rax
    call _printf
    leave
    ret

Then you can compile and run:
host % clang -o hello hello.s
host % ./hello
Hello World!

The bit about zeroing out al is mentioned in section 3.5.7 of System V Application Binary Interface. Here's the relevant excerpt:

When a function taking variable-arguments is called, %al must be set
to the total num- ber of floating point parameters passed to the
function in vector registers.

In your case this is zero.  You are passing in zero floating point parameters.
Comment: The efficient way to zero AL is `xor %eax,%eax`.  `mov $0, %eax` is less efficient but perhaps more obvious; `mov $0, %rax` is even less efficient than that (eve more code size), and seems like a weird choice when we know that only `mov $0, %al` would be sufficient for correctness.  But yeah, for the main question, seems like MacOS doesn't do runtime fixups of 64-bit absolute addresses in PIE executables, or at least not in the `.text` section.


Find/replace macro that properly formats a date cell

Question: I'm using an app that exports certain data to a CSV format. The date column, however, is not properly format in the raw data and contains unnecessary trailing characters for the year, which prevents Excel from interpreting it correctly once imported.
If I manually run Find and Replace on the column, the values are automatically recognized as dates. If I record the operation as a macro, however, and run it again, the trailing character is removed, but the data in the column is retained as a text, not as a date.
Here's the VBA code:
Sub formatDate()

Columns("A:A").Select
Selection.Replace What:=" г.", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End Sub

The regional format for a date is DD.MM.YYYY. Also, if I simply edit any of the resulting cells (F2) and hit Enter without anything else, Excel switches to the proper format.
Sample data:
4 март 2017 г.
4 март 2017 г.
3 март 2017 г.
1 март 2017 г.
28 февруари 2017 г.
27 февруари 2017 г.
27 февруари 2017 г.
26 февруари 2017 г.
26 февруари 2017 г.

Comment: Are the text-that-look-like-dates-with-extras in a fixed format so they are all the same length; e.g. are they 03/05/2017 or 3/5/2017? If so, then Text-To-Columns with Fixed length and the proper DMY vs. MDY format is a better method. Sorry, no sample data so no solution.
Comment: Unfortunately, the text-that-should-be-a-date is not with fixed length, as the generating program uses the month's name and, besides, the date is sometimes with 1 digit, sometimes - with two.
Comment: So I guess supplying several examples of the 'date-with-text' might have been a good idea.
Answer: Use TextToColumns to quickly strip off the trailing characters and convert to dates.
With the text-that-look-like-dates in a fixed dd.mm.yyyy format,
with selection
    .TextToColumns Destination:=.cells(1, 1), DataType:=xlFixedWidth, _
                   FieldInfo:=Array(Array(0, xlDMYFormat), Array(10, xlSkipColumn))
    .numberformat = "dd.mm.yyyy"
end with

With the text-that-look-like-dates showing a space after the date and before the trailing text,
With Selection
    .TextToColumns Destination:=.Cells(1, 1), DataType:=xlDelimited, ConsecutiveDelimiter:=True, _
                   Tab:=False, Semicolon:=False, Comma:=False, Space:=True, Other:=False, _
                   FieldInfo:=Array(Array(1, xlDMYFormat), Array(2, xlSkipColumn))
End With

If the TextToColumns is giving you problems with the Bulgarian month names (VBA is very US-EN-centric), then simply add a single line to your existing code and optionally set the cell format.
with Selection
    .Replace What:=" г.", Replacement:=vbNullString, LookAt:=xlPart, _
             SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
             ReplaceFormat:=False
    .value = .value2
    .numberformat = "dd.mm.yyyy"
end with

I've used Selection here (not particularly recommended) but you should be able to easily convert.
Comment: Here's a sample list of dates. Would that help you tweak the VBA? http://pastebin.com/ePwiEd3w

Also, I can see you've used TextToColumns, I assume that means I'll need an empty column somewhere? Or not?
Comment: Just to clarify, because I'm not too proficient in VBA: should there be an empty column somewhere in the array of raw data, say after the date column (because it's not the only one)?
This is what happens if I use the second snippet above: http://imgur.com/a/fPvo5;
If I use the first one, `17` is stripped from the year.
If I use the last one, the trailing characters do get removed, but what's left is still a text for Excel. :(
Comment: How are you getting `" г."` to show up in VBA code without being reverted to `" ?."`? The `г` is actually unicode `ChrW(1075)` which VBA code does not reproduce without ChrW.
Comment: Well, initially I used the point-and-click method to record the macro, so the  `г.` appeared on its own in the code.


React-Bootstrap Definitely Typed: Error TS2309: An export assignment cannot be used in a module with other exported elements

Question: I've just upgraded typings for react-bootstrap and I'm getting error:

Error TS2309: An export assignment cannot be used in a module with other exported elements.

on this line:
declare namespace ReactBootstrap {
    // Import React
    import React = __React;
    //definitions omitted
}

declare module "react-bootstrap" {
    export = ReactBootstrap; //Error TS2309: An export assignment cannot be used in a module with other exported elements.
}

Is the definition file wrong or am I doing something wrong?
Answer: Ok, in my case I had previously written my own definitions, because they were missing from the definitely typed typings:
custom.d.ts:
declare module "react-bootstrap" {
    // Import React
    import React = require("react");

    // <InputGroup.Addon>
    interface InputGroupAddonProps extends React.HTMLAttributes {
    }
    class InputGroupAddon extends React.Component<InputGroupAddonProps, {}> {
    }
}

the definitions from definitely typed was previously looking like this:
declare module "react-bootstrap" {
    // Import React
    import React = require("react");
    //all typings listed here
}

but this has changed to:
declare namespace ReactBootstrap {
    // Import React
    import React = __React;
    //all typings listed here, including InputGroupAddon which was previously missing
}

declare module "react-bootstrap" {
    export = ReactBootstrap;
}

I fixed the error by removing duplicate definitions from custom.d.ts


group and combine items using LINQ

Question: public class Product
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Amount { get; set; }
}

public List<Product> Products = new List<Product>()
{
    new Product() { Code="A1", Name="Vacuum", Amount = "10" },
    new Product() { Code="A2", Name="Iron", Amount = "20" },
    new Product() { Code="A3", Name="Kettle", Amount = "13" },
    new Product() { Code="A2", Name="Microwave", Amount = "11" },
    new Product() { Code="A3", Name="Dryer", Amount = "3" }
};

I need to select all products without duplicate code. Products with the same code should be combined into one line, in this case name and amount should be separated by commas. How to modify the following code to make it more elegant
    var list1 = new List<Product>();
    var gl = Products.GroupBy(x => x.Code).Where(x => x.Count() > 1);
    gl.ToList().ForEach(x => list1.AddRange(x));

    var list2 = Products.Where(x => !list1.Contains(x)).ToList(); // uniq values

    var list3 = gl.Select(x =>
    {
        var p = new Product() { Code = x.Key };
        p.Name = string.Join(",", x.ToList().Select(r => r.Name).Distinct());
        p.Amount = string.Join(",", x.ToList().Select(r => r.Amount).Distinct());
        return p;
    }).ToList();

    list2.AddRange(list3);
    list2.ForEach(x =>
    {
        Console.WriteLine($"{x.Code.PadRight(20)},{x.Name.PadRight(20)},{x.Amount.PadRight(20)}");
    });

the result should be:
Code  Name              Amount
A1    Vacuum            10
A2    Iron, Microwave   20, 11
A3    Kettle, Dryer     13, 3

Comment: This is a good question apart from the fact there is no expected output, and the part that describes it, is a little ambiguous
Comment: @TheGeneral edited , i put the expected result
Comment: @John my logic is to separate duplicate and unique codes into different list , then process duplicates , then add them back into list of products with unique code
Comment: Why though? Why not just use a single `.GroupBy(...).Select(...)`? After all, a single item will become a group with a single item, and then will come out the other side as a single item.
Answer: Use GroupBy on Code, then iterate over it to get the individual elements to combine using string.Join().
var results = products
    .GroupBy
    (
        p => p.Code
    )
    .Select
    (
        g => new
        {
            Code = g.Key,
            Name = string.Join
            (
                ",",
                g.Select( p => p.Name )
            ),
            Amount = string.Join
            (
                ",",
                g.Select( p => p.Amount.ToString() )
            )
        }
    );

Output:
A1 Vacuum 10
A2 Iron,Microwave 20,11
A3 Kettle,Dryer 13,3

Link to working example on DotNetFiddle

group and combine items using LINQ


puppetlabs/firewall - "Could not find resource type 'firewall'"

Question: I'm fairly new to puppet, so this might just be me not seeing the obvious.
I want to use the puppetlabs-firewall module and wrote a small module of my own. The init.pp looks like this:
class cmmfirewall {
  resources { 'firewall':
    purge => true,
  }
  Firewall {
    before  => Class['cmmfirewall::postv4', 'cmmfirewall::postv6'],
    require => Class['cmmfirewall::prev4', 'cmmfirewall::prev6'],
  }
  class { ['cmmfirewall::prev4', 'cmmfirewall::postv4']: }
  class { ['cmmfirewall::prev6', 'cmmfirewall::postv6']: }
}

When I apply this class to a node I get the following message:
err: Failed to apply catalog: Parameter name failed on Resources[firewall]: Could not find resource type 'firewall' at /etc/puppet/environments/testing/modules/cmmfirewall/manifests/init.pp:42
My puppet.conf on the agent looks like this:
# File managed by Puppet

[main]
    vardir = /var/lib/puppet
    ssldir = $vardir/ssl
    logdir = /var/log/puppet
    rundir = /var/run/puppet
    modulepath = /etc/puppet/modules:/opt/puppet/share/puppet/modules
    user  = puppet
    group = puppet
    archive_files = true
    archive_file_server = handsoff.dc0.mynetwork.de

[agent]
    certname = test3.dc0.mynetwork.de
    server = handsoff.dc0.mynetwork.de
    report = true
    classfile = $vardir/classes.txt
    localconfig = $vardir/localconfig
    graph = true
    pluginsync = true
    runinterval = 300

So as you can see, pluginsync should be activated, but both of the folders in the modulepath /etc/puppet/modules:/opt/puppet/share/puppet/modulesare empty. So my guess would be the problem is somewhere there and pluginsync isn't working as i expect it to work.
Can someone point me in the right direction on where to look for the error, please?
Comment: Does the module appear when you do `puppet module list`?
Comment: You mean an the agent or on the master? On the agent, that list is empty, but I'm using other modules there and they work fine. On the master it also doesn't show up, but I'm using environments here. This module is in testing, whereas the master himself is in 'production'.
Comment: Have you installed the module from puppet forge? puppet module install puppetlabs-firewall
Comment: The module must be available in the `$modulepath` for the `$environment` that your agent chooses. The agent must have `pluginsync` enabled so that the type/provider code is downloaded to its `$vardir`. Once the code has been synced to the agent, it should work for all environments.
Comment: So, that might be the problem. In my puppet.conf on the agent there are those 2 module paths: `/etc/puppet/modules:/opt/puppet/share/puppet/modules`, both are empty. But pluginsync is set to true. - I attached the puppet conf to my main question.
Answer: Ok, actually the moment I copied the puppetlabs-firewall module to my common folder (which gets includes in both environments, testing and production) it worked.
Now I just really would like to now why. Here is the puppetmaster config file. Maybe someone can tell my why it behaves the way it does.
### File managed with puppet ###
## Module:           'puppet'

[main]
    # The Puppet log directory.
    # The default value is '$vardir/log'.
    logdir = /var/log/puppet

    # Where Puppet PID files are kept.
    # The default value is '$vardir/run'.
    rundir = /var/run/puppet

    # Where SSL certificates are kept.
    # The default value is '$confdir/ssl'.
    ssldir = $vardir/ssl

    # Allow services in the 'puppet' group to access key (Foreman + proxy)
    privatekeydir = $ssldir/private_keys { group = service }
    hostprivkey = $privatekeydir/$certname.pem { mode = 640 }

    # Puppet 3.0.x requires this in both [main] and [master] - harmless on agents
    autosign       = $confdir/autosign.conf { mode = 664 }

    show_diff     = false

### Next part of the file is managed by a different template ###
## Module:           'puppet'

[agent]
    # The file in which puppetd stores a list of the classes
    # associated with the retrieved configuratiion.  Can be loaded in
    # the separate ``puppet`` executable using the ``--loadclasses``
    # option.
    # The default value is '$statedir/classes.txt'.
    classfile = $vardir/classes.txt

    # Where puppetd caches the local configuration.  An
    # extension indicating the cache format is added automatically.
    # The default value is '$confdir/localconfig'.
    localconfig = $vardir/localconfig

    # Disable the default schedules as they cause continual skipped
    # resources to be displayed in Foreman - only for Puppet >= 3.4
    default_schedules = false

    report        = true
    pluginsync    = true
    masterport    = 8140
    environment   = production
    certname      = handsoff.dc0.mynetwork.de
    server        = handsoff.dc0.mynetwork.de
    listen        = false
    splay         = false
    runinterval   = 300
    noop          = false
    configtimeout = 120

### Next part of the file is managed by a different template ###
## Module:           'puppet'

[master]
    autosign       = $confdir/autosign.conf { mode = 664 }
    reports        = foreman
    external_nodes = /etc/puppet/node.rb
    node_terminus  = exec
    ca             = true
    ssldir         = /var/lib/puppet/ssl
    certname       = handsoff.dc0.mynetwork.de
    strict_variables = false

[production]
    modulepath     = /etc/puppet/environments/production/modules:/etc/puppet/environments/common:/usr/share/puppet/modules
    config_version =
[testing]
    modulepath     = /etc/puppet/environments/testing/modules:/etc/puppet/environments/common:/usr/share/puppet/modules
    config_version =


Trying to create two way login form in Laravel - 'Array to string conversion'

Question: I have normal login form which work great. Now I'm trying to make second simple step when user enter his password and user name and if they are correct to redirect him to new page where he must enter pass phrase in order to continue.
I'm not sure if this is correct what I have make so far. This is my route:
Route::get ('/users/login', ['uses' => 'UsersController@login', 'before' => 'guest']);
Route::post('/users/login', ['uses' => 'UsersController@loginSubmit', 'before' => 'guest']);

// new
Route::get('/users/auth', ['uses' => 'UsersController@loginAuth', 'before' => 'guest']);
Route::post('/users/auth', ['uses' => 'UsersController@loginSubmitAuth', 'before' => 'auth|csrf']);

This is my auth.blade.php
{{ Form::open(['class' => 'form-horizontal']) }}

 {{ Form::textarea('key', ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}

        <button type="submit" class="btn btn-primary col-xs-4 col-xs-offset-4">Login</button>

{{ Form::close() }}

This is my controller
public function login() {
    return View::make('site.users.login');
}

public function loginSubmit() {
    $validatorRules = array(
        'captcha'  => 'required|captcha',
        'username' => 'required|alpha_dash',
        'password' => 'required|min:6'
    );

    Input::merge(array_map('trim', Input::all()));
    $validator = Validator::make(Input::all(), $validatorRules);

    if ($validator->fails()) {
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    if (!Hash::check(Input::get('password'), $user->password)) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    //$user->last_login = \Carbon\Carbon::now();
    //$user->save();
    //Session::put('user', ['user_id' => $user->user_id]);
    return Redirect::to('/users/auth');
}
public function loginAuth() {
    return View::make('site.users.auth');
}
public function loginSubmitAuth() {
    $validatorRules = array(
        'key'  => 'required',
        'captcha'  => 'required|captcha'
    );

    Input::merge(array_map('trim', Input::all()));
    $validator = Validator::make(Input::all(), $validatorRules);

    if ($validator->fails()) {
        return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('key', Input::get('key'))->first();
    if (!$user) {
        $validator->messages()->add('key', 'Invalid Key.');
        return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);
    return Redirect::to('/');
}

Current error is 'Array to string conversion'
Any help is appreciated. Thank's
Comment: On which row do you get the error. I suppose Input::merge(array_map('trim', Input::all()));
Comment: I've got this in my log and can't see where exactly in the source is this: `'ErrorException' with message 'Array to string conversion' in /vendor/laravel/framework/src/Illuminate/Html/FormBuilder.php:343`
Comment: I've got this when I click on Login after enter username/password and I've got blank page. Can't reach `auth.blade.php`
Answer: The issue of second parameter in Form::textarea you need to pass null to make it empty in second parameter and array in third parameter like,

  {{ Form::textarea('key',null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}

You can refer to Creating a Textarea Input Field
Comment: Yes, this fixed the blank page error. Now the problem is that when I enter the key it's redirecting me to login page.
Comment: I gave the solution for which you ask the question, but now the error comes because of your logic. I think on pressing `enter`, the validations fails and you are redirecting to login page. For this, if you check it manually then you will definitely find the solution for it.
Comment: You're right. You gave me the solution of initial question and I accept it. Now the error is in comparing logic in the controller. I will try to fix it or will post new question. Thank's!
Comment: No problem, I think you can fix it yourself in a better way. Just see the flow of you routes and functions calls.
Answer: Can you try if this fixes your problem:
{{ Form::textarea('key', null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}

It's this way because the value argument comes second and it is mandatory in difference with the third one which is optional


Writing alternative File Widget

Question: Okay, so I looked inside of the Managed File element and the FileWidget code and I am pretty overwhelmed.  I don't think I need anything quite so complex, but it seems like there is so much that can be done with a file widget that I don't want to do things in a way that could cause problems in the future.
I have some javascript that will upload a file to a remote server and return a url, so I want to send that url to a custom controller and save it in Drupal.  Is writing a file widget the right way to go here?
Any guidelines on where to go to find a good example of a file widget, or an explanation of how it works?
Comment: The existing file widget is probably the best example of a file widget. If you are planning on writing a custom widget then don't forget drupal 8 is object oriented and you should extend the file widget provided by core.
Answer: I've found that at the moment, there is no example more helpful than the Plupload module.  It integrates with the Plupload_widget module and extends the FileWidget from core and also has a lot of comments that I wish core would have included, explaining what the core file widget does.

Writing alternative File Widget


After gradle update to 2.10, can't run app

Question: I'm running on Android Studio 2.1.1 and was recently asked to update the gradle plugin to 2.10 (form 2.2.1) to have the ability of instant runs, which needles to say I did.
Right after that only one particular project can't build and I've tried everything that's available on the subject as question on stackoverflow.
Here are my settings

project build.gradle:

gradle/gradle-wrapper.properties:

After I try to run I get the following:

via terminal

gradle clean --stacktrace

The last thing is pretty strange since I've set the version to 2.10

Any ideas?
Answer: I did my search too on this.Some said to delete the file manually but it gave me a new file everytime i did that.Try reimporting your project and rebuilding it.
Comment: Eventually this is what I ended up doing. Regardless, I hope someone has solution for this that deals with the issue more elegantly


Do I have to normalise the data for PERMANOVA?

Question: Why do I have to normalise my dataset to do a PERMANOVA?
What is the difference between Euclidean distance and Bray-Curtis similarity? Which is the most suitable for CPUE (abundance) data?
Comment: What is "PERMANOVA"?
Answer: In general, permutation-based approaches are not as closely tied to distributional assumptions. In the case of the ill-named permanova, or analysis of variance using distance matrices, at least sensu adonis {vegan}, it is the distance matrices that you need to check for compliance with linearity assumptions. This may be a good reference to check.
A rather philosophical question of the difference between a distance and a similarity has a surprising number of bizarre answers if you google it. But it is rather simple: BC is 1-Sorensen index, which gives double weight to double presences in an effort to increase information content of species presence vs. absence (because absences are so ambivalent in ecology: maybe it was not there or maybe you could not catch it in your UE, imo less to do with 'unimodal distribution to environmental gradient' then with the fact that our sampling effort usually sucks). Because it is weighted, it is usually non-Euclidean.
Species matrices such as CPUE are zero-heavy, skewed data, not really special in any other way. Decision on how to treat them is more of an a priori assumption of how valuable your zero data are (hence, whether you should down-weight them), and the general paradigm in that respect in your sub-field at the moment.


Chave Estrangeira Circular

Question: Frequentemente vejo banco de dados modelados de forma que as chaves estrangeiras fecham uma referência circular, para exemplificar utilizei um modelo com cidade,bairro e cliente. Segue o modelo ER:

Entendo que nesse formato, pode haver inconsistência dos dados.
As perguntas são:
Há alguma documentação que define essa modelagem como certa ou errada?
Referência Circular é o termo correto para definir essa situação?
Answer:
Há alguma documentação que define essa modelagem como certa ou errada?

O que existe não é certo ou errado, mas sim o modelo ideal para cada aplicação. Em certos casos, a utilização de normalização é ideal para prevenir que sejam geradas inconsistências na base, devido a repetição de dados. Já em outros casos (e.g. Aplicações que respondem em tempo real), a normalização pode ser nociva pois aumenta o número de tabelas consequentemente aumentando o número de joins e tornando assim as consultas mais lentas. As vezes é aceitável replicar alguns dados em diferentes tabelas visando otimizar consultas no sistema, mas isso aumenta o risco de geração de inconsistências, e por isso essas decisões precisam ser bem pensadas. No fim das contas é um trade-off.

Referência Circular é o termo correto para definir essa situação?

Esse termo pode ser usado para definir essa situação. O grande risco é quando aplicações que usam o JPA, por exemplo, mapeiam os objetos sem usar lazy-loading. Implementando de forma correta o sistema e dependendo dos requisitos da aplicação, esse comportamento cíclico é aceitável.

Chave Estrangeira Circular


Como colocar variavel php em link JS

Question: Olá galera tudo bem? estou com problema de colocar variável PHP em link JS, o que preciso saber disso pois estou tentando fazer um u sistema de login no meu site... vêem a linha de código r conseguem uma suposta solução. Desde já agradeço!!!!!!!!

O meu problema é que tenho essa linha de comando no JavaScript que etá dentro do arquivo:
<?
$opts = uniqid(rand(), true);
echo ";
?>

porém essa linha de código simplesmente não ocorre nada... Como proceder?
Comment: Experimente `"";` ou `"";`.
Answer: Tente o seguinte bloco:
<?
$opts = uniqid(rand(), true);
echo "";
?>

Você não esta fechando a " após a tag

Como colocar variavel php em link JS


Can we move a module from the directory "/modules" to the directory "/modules/contrib" without uninstalling it?

Question: We have a Drupal 8 application which has modules directly in the directory "/modules" on the file system. I want to move a contributed module from the directory "/modules" to the directory "/modules/contrib". Do I need to uninstall the module before doing it?
Are there any steps that need to be performed before and after moving the module?
Comment: You probably have to regenerate the autoloader files and dump any running memory cache.
Comment: @Kevin How can we regenerate the autoloader files? And would clearing the cache through the admin interface by going to '/admin/config/development/performance', dump the running memory cache?
Comment: `composer dump-autoload` @MartinBorugadda, and yes (or run `drush cr`)
Comment: Why don't you simply try it out yourself on your local machlne?
Comment: @leymannx I tried it on my dev and nothing seems to be broke. But, I am not very sure of how the internals of Drupal behave. Wanted to be sure if something gets broke in the future
Comment: That' important info you must add to your question.
Answer: As with most things, I suggested testing it out on a development/test site before trying on the live site. It's likely that the specific set of contribs and the libraries they use will affect the success of this operation.
How did you install the modules? Do you use a composer workflow?
In general, some paths stored in different places are going to be wrong. To fix that, you will need to edit those paths or have Drupal figure out the new paths. I believe doing a cache rebuild (e.g. drush cr) will fix that problem.


Does Google BigQuery and Google cloud storage share files between them?

Question: I have created a BigQuery table by loading CSV file from Google cloud storage.
In this case, does BigQuery table reference the CSV file in cloud storage or it copies data to its own storage?
Answer: When you load file from Cloud Storage to BigQuery - this loads data into BigQuery "own" storage that is totally different from Cloud Storage.
Note: BigQuery supports querying data directly from Google Cloud Storage and Google Drive.  See details at Creating and Querying Federated Data Sources


Predicting Co-Ordinate Data

Question: This is on a prediction model we were trying out among a bunch of us trying out ML for the first time. Basically I have a training data set of network user ID's with their location (latitude and longitude). Also tracked are a couple of features such as the time of their first post, second post etc and a few details on their friends. My goal is to use these features to predict the location (latitude/ longitude) for a test set of data. Any ideas on what kind of model to use here and what ML technique to try out? At the moment we are using basic multiple regression to predict the latitude and longitude separately using independent models.  But I was hoping to see if it is possible to approach the problem differently.
Any thoughts?
Comment: Were unable to find a working R package for anything similar like the Curds and Whey algorithm.
Comment: see [Kriging](https://en.wikipedia.org/?title=Kriging#Geostatistical_estimator) maybe
Comment: Currently we are doing basic multiple regression using the given predictors and predicting the latitude separately and the longitude separately. My belief is that there must be a better option available where i can predict both the lat and long in pairs using one unified model. Or some other approach to the  problem all together. I did google a bit on current research in "Multivariate mutiple regression" as this seems to be an appropriate description of the problem, but I'm unable to find any effective solutions.
Answer: Its hard to give you a precise set of algorithms to treat this question, but many classical algorithms can be tweaked to accomodate for multidimensional responses. You may want to look into multivariate regression.
That being said, using two separate models to predict the coordinates is not ideal. Indeed, you will be ditributing variance accross both models, and combining them will result in higher variance. It is a better idea to use models which can handle both variables simultaneously, and hopefully exploit correlations between both coordinates.
For example, rather than running linear regression on each coordinate separately, you could formulate your regression differently : treat your vector $(y_1,y_2)$of coordinates as a vector response $Y$, and if your variables are a vector $X$, your parameters, instead of being a vector, could now be a matrix $A$ such that
$$Y = AX + \epsilon$$
Where $\epsilon$ follows a hypothesis of your choice. If you make both components of $\epsilon$ independent, you'll fall back to independent regressions. But you may also choose the components to be indentical. You could also impose relations on $A$, forcing to look for correlations between both coordinates.
A detailed account can be found here.
Comment: Thanks for that! Yes, that was the kind of approach I was hoping for but my current expertise doesnt cover how to take that route. I did lookup options to do multivariate regression in R/ Sas etc but I'm unable to find any notes anywhere. Thanks again!
Comment: I just edited my answer with a link to an article by Friedman with techniques for multivariate linear regression, as an example.

Predicting Co-Ordinate Data


ISP "hide" packet trace route

Question: Yesterday , i've discovered changes in my network , our ISP hides trace route .
ie :
<code>traceroute to 188.8.131.52 (22.214.171.124), 30 hops max, 60 byte packets
 1  192.168.88.1 (192.168.55.1)  0.256 ms  0.251 ms  0.314 ms
 2  google-public-dns-a.google.com (126.96.36.199)  102.336 ms  102.477 ms  114.432 ms
</code>
Now i can't verify packets route ,or check ISP fault . Is there any chance to discover where packets are sent ?
it's normal ISP behaving nowadays ?
Comment: `188.8.131.52` is an anycast address. Could you try looking up a unicast address of that DNS server. You can use `dig -t aaaa mydnsv6.kasperd.net @220.127.116.11` to look it up. And what does the route look like if you specify a unicast address rather than an anycast address?
Answer:
Now i can't verify packets route, or check ISP fault.

Yes.

Is there any chance to discover where packets are sent ?

No, not without access to the ISPs systems (or access to the system killing your TTL information, like firewalls sometimes do). The routers on the way do have to increment the TTL of ICMP packets, if the don't do that, they behave completely transparent - just like switches (which you kannot detect by traceroute).

it's normal ISP behaving nowadays ?

No, and it shouldn't be. The header TTL is vital for the network, as it kills paket that travel for too long. Thats the same for all protocol types, including ICMP.

ISP "hide" packet trace route


Ruby on Rails 6 custom JavaScript file Uncaught ReferenceError: Rellax is not defined

Question: Descriptions of issue
It supposes to add Parallax effect on .rellax elements according to https://github.com/dixonandmoe/rellax
If you are familiar with Ruby on Rails 6 and Webpacker, would you please explain why rails can't read rellax.js properly and what can I do to make it work? Thank you!
Terminal
$ rails s
=> Booting Puma
=> Rails 22.214.171.124 application starting in development
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.5 (ruby 2.6.6-p146), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
* Listening on tcp://[::1]:3000
Use Ctrl-C to stop
Started GET "/" for ::1 at 2020-07-15 18:34:48 -0700
   (1.0ms)  SELECT sqlite_version(*)
Processing by WelcomeController#index as HTML
  Rendering welcome/index.html.erb within layouts/application
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered welcome/index.html.erb within layouts/application (Duration: 4.8ms | Allocations: 2428)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 47ms (Views: 39.7ms | ActiveRecord: 0.0ms | Allocations: 13263)

index.html.erb

Welcome#index

Find me in app/views/welcome/index.html.erb

data-rellax-speed = default

With Percentage (0.5)

#1#1

#2#2

#3#3

#4#4

#5#5

#6#6

Without Percentage

#1#1

#2#2

#3#3

#4#4

#5#5

#6#6

<%= javascript_pack_tag 'rellax' %>

app/javascript/packs/rellax.js
// ------------------------------------------
// Rellax.js
// Buttery smooth parallax library
// Copyright (c) 2016 Moe Amaya (@moeamaya)
// MIT license
//
// Thanks to Paraxify.js and Jaime Cabllero
// for parallax concepts
// ------------------------------------------

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.Rellax = factory();
  }
}(typeof window !== "undefined" ? window : global, function () {
  var Rellax = function(el, options){
    "use strict";

    var self = Object.create(Rellax.prototype);

    var posY = 0;
    var screenY = 0;
    var posX = 0;
    var screenX = 0;
    var blocks = [];
    var pause = true;

    // check what requestAnimationFrame to use, and if
    // it's not supported, use the onscroll event
    var loop = window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      function(callback){ return setTimeout(callback, 1000 / 60); };

    // store the id for later use
    var loopId = null;

    // Test via a getter in the options object to see if the passive property is accessed
    var supportsPassive = false;
    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function() {
          supportsPassive = true;
        }
      });
      window.addEventListener("testPassive", null, opts);
      window.removeEventListener("testPassive", null, opts);
    } catch (e) {}

    // check what cancelAnimation method to use
    var clearLoop = window.cancelAnimationFrame || window.mozCancelAnimationFrame || clearTimeout;

    // check which transform property to use
    var transformProp = window.transformProp || (function(){
        var testEl = document.createElement('div');
        if (testEl.style.transform === null) {
          var vendors = ['Webkit', 'Moz', 'ms'];
          for (var vendor in vendors) {
            if (testEl.style[ vendors[vendor] + 'Transform' ] !== undefined) {
              return vendors[vendor] + 'Transform';
            }
          }
        }
        return 'transform';
      })();

    // Default Settings
    self.options = {
      speed: -2,
        verticalSpeed: null,
        horizontalSpeed: null,
      breakpoints: [576, 768, 1201],
      center: false,
      wrapper: null,
      relativeToWrapper: false,
      round: true,
      vertical: true,
      horizontal: false,
      verticalScrollAxis: "y",
      horizontalScrollAxis: "x",
      callback: function() {},
    };

    // User defined options (might have more in the future)
    if (options){
      Object.keys(options).forEach(function(key){
        self.options[key] = options[key];
      });
    }

    function validateCustomBreakpoints () {
      if (self.options.breakpoints.length === 3 && Array.isArray(self.options.breakpoints)) {
        var isAscending = true;
        var isNumerical = true;
        var lastVal;
        self.options.breakpoints.forEach(function (i) {
          if (typeof i !== 'number') isNumerical = false;
          if (lastVal !== null) {
            if (i < lastVal) isAscending = false;
          }
          lastVal = i;
        });
        if (isAscending && isNumerical) return;
      }
      // revert defaults if set incorrectly
      self.options.breakpoints = [576, 768, 1201];
      console.warn("Rellax: You must pass an array of 3 numbers in ascending order to the breakpoints option. Defaults reverted");
    }

    if (options && options.breakpoints) {
      validateCustomBreakpoints();
    }

    // By default, rellax class
    if (!el) {
      el = '.rellax';
    }

    // check if el is a className or a node
    var elements = typeof el === 'string' ? document.querySelectorAll(el) : [el];

    // Now query selector
    if (elements.length > 0) {
      self.elems = elements;
    }

    // The elements don't exist
    else {
      console.warn("Rellax: The elements you're trying to select don't exist.");
      return;
    }

    // Has a wrapper and it exists
    if (self.options.wrapper) {
      if (!self.options.wrapper.nodeType) {
        var wrapper = document.querySelector(self.options.wrapper);

        if (wrapper) {
          self.options.wrapper = wrapper;
        } else {
          console.warn("Rellax: The wrapper you're trying to use doesn't exist.");
          return;
        }
      }
    }

    // set a placeholder for the current breakpoint
    var currentBreakpoint;

    // helper to determine current breakpoint
    var getCurrentBreakpoint = function (w) {
      var bp = self.options.breakpoints;
      if (w < bp[0]) return 'xs';
      if (w >= bp[0] && w < bp[1]) return 'sm';
      if (w >= bp[1] && w < bp[2]) return 'md';
      return 'lg';
    };

    // Get and cache initial position of all elements
    var cacheBlocks = function() {
      for (var i = 0; i < self.elems.length; i++){
        var block = createBlock(self.elems[i]);
        blocks.push(block);
      }
    };

    // Let's kick this script off
    // Build array for cached element values
    var init = function() {
      for (var i = 0; i < blocks.length; i++){
        self.elems[i].style.cssText = blocks[i].style;
      }

      blocks = [];

      screenY = window.innerHeight;
      screenX = window.innerWidth;
      currentBreakpoint = getCurrentBreakpoint(screenX);

      setPosition();

      cacheBlocks();

      animate();

      // If paused, unpause and set listener for window resizing events
      if (pause) {
        window.addEventListener('resize', init);
        pause = false;
        // Start the loop
        update();
      }
    };

    // We want to cache the parallax blocks'
    // values: base, top, height, speed
    // el: is dom object, return: el cache values
    var createBlock = function(el) {
      var dataPercentage = el.getAttribute( 'data-rellax-percentage' );
      var dataSpeed = el.getAttribute( 'data-rellax-speed' );
      var dataXsSpeed = el.getAttribute( 'data-rellax-xs-speed' );
      var dataMobileSpeed = el.getAttribute( 'data-rellax-mobile-speed' );
      var dataTabletSpeed = el.getAttribute( 'data-rellax-tablet-speed' );
      var dataDesktopSpeed = el.getAttribute( 'data-rellax-desktop-speed' );
      var dataVerticalSpeed = el.getAttribute('data-rellax-vertical-speed');
      var dataHorizontalSpeed = el.getAttribute('data-rellax-horizontal-speed');
      var dataVericalScrollAxis = el.getAttribute('data-rellax-vertical-scroll-axis');
      var dataHorizontalScrollAxis = el.getAttribute('data-rellax-horizontal-scroll-axis');
      var dataZindex = el.getAttribute( 'data-rellax-zindex' ) || 0;
      var dataMin = el.getAttribute( 'data-rellax-min' );
      var dataMax = el.getAttribute( 'data-rellax-max' );
      var dataMinX = el.getAttribute('data-rellax-min-x');
      var dataMaxX = el.getAttribute('data-rellax-max-x');
      var dataMinY = el.getAttribute('data-rellax-min-y');
      var dataMaxY = el.getAttribute('data-rellax-max-y');
      var mapBreakpoints;
      var breakpoints = true;

      if (!dataXsSpeed && !dataMobileSpeed && !dataTabletSpeed && !dataDesktopSpeed) {
        breakpoints = false;
      } else {
        mapBreakpoints = {
          'xs': dataXsSpeed,
          'sm': dataMobileSpeed,
          'md': dataTabletSpeed,
          'lg': dataDesktopSpeed
        };
      }

      // initializing at scrollY = 0 (top of browser), scrollX = 0 (left of browser)
      // ensures elements are positioned based on HTML layout.
      //
      // If the element has the percentage attribute, the posY and posX needs to be
      // the current scroll position's value, so that the elements are still positioned based on HTML layout
      var wrapperPosY = self.options.wrapper ? self.options.wrapper.scrollTop : (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
      // If the option relativeToWrapper is true, use the wrappers offset to top, subtracted from the current page scroll.
      if (self.options.relativeToWrapper) {
        var scrollPosY = (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
        wrapperPosY = scrollPosY - self.options.wrapper.offsetTop;
      }
      var posY = self.options.vertical ? ( dataPercentage || self.options.center ? wrapperPosY : 0 ) : 0;
      var posX = self.options.horizontal ? ( dataPercentage || self.options.center ? self.options.wrapper ? self.options.wrapper.scrollLeft : (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft) : 0 ) : 0;

      var blockTop = posY + el.getBoundingClientRect().top;
      var blockHeight = el.clientHeight || el.offsetHeight || el.scrollHeight;

      var blockLeft = posX + el.getBoundingClientRect().left;
      var blockWidth = el.clientWidth || el.offsetWidth || el.scrollWidth;

      // apparently parallax equation everyone uses
      var percentageY = dataPercentage ? dataPercentage : (posY - blockTop + screenY) / (blockHeight + screenY);
      var percentageX = dataPercentage ? dataPercentage : (posX - blockLeft + screenX) / (blockWidth + screenX);
      if(self.options.center){ percentageX = 0.5; percentageY = 0.5; }

      // Optional individual block speed as data attr, otherwise global speed
      var speed = (breakpoints && mapBreakpoints[currentBreakpoint] !== null) ? Number(mapBreakpoints[currentBreakpoint]) : (dataSpeed ? dataSpeed : self.options.speed);
      var verticalSpeed = dataVerticalSpeed ? dataVerticalSpeed : self.options.verticalSpeed;
      var horizontalSpeed = dataHorizontalSpeed ? dataHorizontalSpeed : self.options.horizontalSpeed;

      // Optional individual block movement axis direction as data attr, otherwise gobal movement direction
      var verticalScrollAxis = dataVericalScrollAxis ? dataVericalScrollAxis : self.options.verticalScrollAxis;
      var horizontalScrollAxis = dataHorizontalScrollAxis ? dataHorizontalScrollAxis : self.options.horizontalScrollAxis;

      var bases = updatePosition(percentageX, percentageY, speed, verticalSpeed, horizontalSpeed);

      // ~~Store non-translate3d transforms~~
      // Store inline styles and extract transforms
      var style = el.style.cssText;
      var transform = '';

      // Check if there's an inline styled transform
      var searchResult = /transform\s*:/i.exec(style);
      if (searchResult) {
        // Get the index of the transform
        var index = searchResult.index;

        // Trim the style to the transform point and get the following semi-colon index
        var trimmedStyle = style.slice(index);
        var delimiter = trimmedStyle.indexOf(';');

        // Remove "transform" string and save the attribute
        if (delimiter) {
          transform = " " + trimmedStyle.slice(11, delimiter).replace(/\s/g,'');
        } else {
          transform = " " + trimmedStyle.slice(11).replace(/\s/g,'');
        }
      }

      return {
        baseX: bases.x,
        baseY: bases.y,
        top: blockTop,
        left: blockLeft,
        height: blockHeight,
        width: blockWidth,
        speed: speed,
        verticalSpeed: verticalSpeed,
        horizontalSpeed: horizontalSpeed,
        verticalScrollAxis: verticalScrollAxis,
        horizontalScrollAxis: horizontalScrollAxis,
        style: style,
        transform: transform,
        zindex: dataZindex,
        min: dataMin,
        max: dataMax,
        minX: dataMinX,
        maxX: dataMaxX,
        minY: dataMinY,
        maxY: dataMaxY
      };
    };

    // set scroll position (posY, posX)
    // side effect method is not ideal, but okay for now
    // returns true if the scroll changed, false if nothing happened
    var setPosition = function() {
      var oldY = posY;
      var oldX = posX;

      posY = self.options.wrapper ? self.options.wrapper.scrollTop : (document.documentElement || document.body.parentNode || document.body).scrollTop || window.pageYOffset;
      posX = self.options.wrapper ? self.options.wrapper.scrollLeft : (document.documentElement || document.body.parentNode || document.body).scrollLeft || window.pageXOffset;
      // If option relativeToWrapper is true, use relative wrapper value instead.
      if (self.options.relativeToWrapper) {
        var scrollPosY = (document.documentElement || document.body.parentNode || document.body).scrollTop || window.pageYOffset;
        posY = scrollPosY - self.options.wrapper.offsetTop;
      }

      if (oldY != posY && self.options.vertical) {
        // scroll changed, return true
        return true;
      }

      if (oldX != posX && self.options.horizontal) {
        // scroll changed, return true
        return true;
      }

      // scroll did not change
      return false;
    };

    // Ahh a pure function, gets new transform value
    // based on scrollPosition and speed
    // Allow for decimal pixel values
    var updatePosition = function(percentageX, percentageY, speed, verticalSpeed, horizontalSpeed) {
      var result = {};
      var valueX = ((horizontalSpeed ? horizontalSpeed : speed) * (100 * (1 - percentageX)));
      var valueY = ((verticalSpeed ? verticalSpeed : speed) * (100 * (1 - percentageY)));

      result.x = self.options.round ? Math.round(valueX) : Math.round(valueX * 100) / 100;
      result.y = self.options.round ? Math.round(valueY) : Math.round(valueY * 100) / 100;

      return result;
    };

    // Remove event listeners and loop again
    var deferredUpdate = function() {
      window.removeEventListener('resize', deferredUpdate);
      window.removeEventListener('orientationchange', deferredUpdate);
      (self.options.wrapper ? self.options.wrapper : window).removeEventListener('scroll', deferredUpdate);
      (self.options.wrapper ? self.options.wrapper : document).removeEventListener('touchmove', deferredUpdate);

      // loop again
      loopId = loop(update);
    };

    // Loop
    var update = function() {
      if (setPosition() && pause === false) {
        animate();

        // loop again
        loopId = loop(update);
      } else {
        loopId = null;

        // Don't animate until we get a position updating event
        window.addEventListener('resize', deferredUpdate);
        window.addEventListener('orientationchange', deferredUpdate);
        (self.options.wrapper ? self.options.wrapper : window).addEventListener('scroll', deferredUpdate, supportsPassive ? { passive: true } : false);
        (self.options.wrapper ? self.options.wrapper : document).addEventListener('touchmove', deferredUpdate, supportsPassive ? { passive: true } : false);
      }
    };

    // Transform3d on parallax element
    var animate = function() {
      var positions;
      for (var i = 0; i < self.elems.length; i++){
        // Determine relevant movement directions
        var verticalScrollAxis = blocks[i].verticalScrollAxis.toLowerCase();
        var horizontalScrollAxis = blocks[i].horizontalScrollAxis.toLowerCase();
        var verticalScrollX = verticalScrollAxis.indexOf("x") != -1 ? posY : 0;
        var verticalScrollY = verticalScrollAxis.indexOf("y") != -1 ? posY : 0;
        var horizontalScrollX = horizontalScrollAxis.indexOf("x") != -1 ? posX : 0;
        var horizontalScrollY = horizontalScrollAxis.indexOf("y") != -1 ? posX : 0;

        var percentageY = ((verticalScrollY + horizontalScrollY - blocks[i].top + screenY) / (blocks[i].height + screenY));
        var percentageX = ((verticalScrollX + horizontalScrollX - blocks[i].left + screenX) / (blocks[i].width + screenX));

        // Subtracting initialize value, so element stays in same spot as HTML
        positions = updatePosition(percentageX, percentageY, blocks[i].speed, blocks[i].verticalSpeed, blocks[i].horizontalSpeed);
        var positionY = positions.y - blocks[i].baseY;
        var positionX = positions.x - blocks[i].baseX;

        // The next two "if" blocks go like this:
        // Check if a limit is defined (first "min", then "max");
        // Check if we need to change the Y or the X
        // (Currently working only if just one of the axes is enabled)
        // Then, check if the new position is inside the allowed limit
        // If so, use new position. If not, set position to limit.

        // Check if a min limit is defined
        if (blocks[i].min !== null) {
          if (self.options.vertical && !self.options.horizontal) {
            positionY = positionY <= blocks[i].min ? blocks[i].min : positionY;
          }
          if (self.options.horizontal && !self.options.vertical) {
            positionX = positionX <= blocks[i].min ? blocks[i].min : positionX;
          }
        }

        // Check if directional min limits are defined
        if (blocks[i].minY != null) {
            positionY = positionY <= blocks[i].minY ? blocks[i].minY : positionY;
        }
        if (blocks[i].minX != null) {
            positionX = positionX <= blocks[i].minX ? blocks[i].minX : positionX;
        }

        // Check if a max limit is defined
        if (blocks[i].max !== null) {
          if (self.options.vertical && !self.options.horizontal) {
            positionY = positionY >= blocks[i].max ? blocks[i].max : positionY;
          }
          if (self.options.horizontal && !self.options.vertical) {
            positionX = positionX >= blocks[i].max ? blocks[i].max : positionX;
          }
        }

        // Check if directional max limits are defined
        if (blocks[i].maxY != null) {
            positionY = positionY >= blocks[i].maxY ? blocks[i].maxY : positionY;
        }
        if (blocks[i].maxX != null) {
            positionX = positionX >= blocks[i].maxX ? blocks[i].maxX : positionX;
        }

        var zindex = blocks[i].zindex;

        // Move that element
        // (Set the new translation and append initial inline transforms.)
        var translate = 'translate3d(' + (self.options.horizontal ? positionX : '0') + 'px,' + (self.options.vertical ? positionY : '0') + 'px,' + zindex + 'px) ' + blocks[i].transform;
        self.elems[i].style[transformProp] = translate;
      }
      self.options.callback(positions);
    };

    self.destroy = function() {
      for (var i = 0; i < self.elems.length; i++){
        self.elems[i].style.cssText = blocks[i].style;
      }

      // Remove resize event listener if not pause, and pause
      if (!pause) {
        window.removeEventListener('resize', init);
        pause = true;
      }

      // Clear the animation loop to prevent possible memory leak
      clearLoop(loopId);
      loopId = null;
    };

    // Init
    init();

    // Allow to recalculate the initial values whenever we want
    self.refresh = init;

    return self;
  };
  return Rellax;
}));

Error: Uncaught ReferenceError: Rellax is not defined
Comment: I see, the reason why I'm asking is because I think you are getting the error because probably Rellax is not loaded when the call to new Relax is made, the usual pattern using webpacker to avoid this is to install the required library to the node_modules folder, load it the application.js pack and wait for turbolinks to load. Although if you are looking for a different approach I think another option you can try is to add an event listener in the window `load` event and then call Relax when that event is fired, if that make sense I can elaborate a detailed answer
Comment: I see you copied the rellax.js file from github, does that mean that you are not looking to install it trough yarn?
Comment: Thanks for your question @IvanGarcia! I did "npm install rellax --save" too. It does the same with "yarn add relax" and loads rellax.js in the node_modules/rellax/ but getting the same error. I thought it's better to put rellax.js inside app/javascript/packs for simplicity sake.
Comment: Make sense. I guess Rails loading rellax.js later than index.html.erb for some reason?
Answer: I just realized that the package you are trying to import is intended to be included as an AMD or as a node module, without entering in much detail what does that mean is that you should include your module either by using
import Rellax from 'rellax' or let Rellax = require('rellax'), the thing is that by using this kind of import, your packages are not included in the Window objcet, which is the main object where all the global modules and variables are attached, so if you try to access Rellax from outside of the scope where rellax is imported, you are not going to be able to access that object, getting the error message you mentioned:
Rellax is not defined
Because is actually not defined in that scope.
TLDR;
So in order to fix the issue, you have to include the library and use that library in the same scope, you can achieve that by creating a new js file within your pack directory for example:
parallax_init.js
import Rellax from 'rellax'

let rellax = new Rellax('.rellax');

And then include it in your html template using <%= javascript_pack_tag 'parallax_init' %>
Note:
As you are now using webpacker to handle the js dependencies, you have to use yarn to install the packages as webpacker works with yarn.
You can get more information about the JS scope stuff in the AMD documentation: https://requirejs.org/docs/whyamd.html and in the webpack documentation: https://webpack.js.org/concepts/module-federation/
I also recommend you to read the webpacker documentation, which has a bit more information than the rails guide for the moment(Until the rails guide gets updates): https://github.com/rails/webpacker#usage
Comment: I've replaced app/javascript/packs/rellax.js with app/javascript/packs/parallax_init.js and deleted references on line 42, 43 in index.html and did "$ yarn add rellax". This worked well. Thank you!
Comment: Using the `import Rellax from 'rellax'` option, you'll have to run the following `npm i --save-dev @types/rellax`
Answer: You can have two approachs to achieve your goal. Install the library or add manually the js files.
If you want to install the library, use yarn (not npm) for that. yarn add rellax. Then just import it in application.js by doing: import 'rellax'; This file is located in app/javascript/packs.
If you want to add the files manually, put these js files in a folder called components or plugins inside app/javascript. Then import all js files in application.js. Having done this correctly, all js files will be available in your views.
It's highly recommended that you read the Rails Guide: The Asset Pipeline to understand how to deal with any kind of assets in rails applications.


New version of h2o in R still produces additional row when calling as.h2o on column names with special characters

Question: I am still having the problem outlined by another user in this question: as.h2o produces additional row when column names contain special characters
Currently, h2o is on version 220.127.116.11, and it looks like this issue has only been resolved up to 3.18.0.08. I have tried to downgrade the installation of h2o on my computer but I got an error when trying to run this.
Is there any way to circumvent this problem? Might it work on a different computer (if I can get access to one)?
Edit: I am using RStudio on a laptop running Windows 7, and the version of R is 3.4.4.
Edit: Here is an example of what causes this bug.
df <- replicate(3, rnorm(5))
colnames(df) <- c("–coliform", "''append", "dog")
df.h2o <- as.h2o(df)

The output from this code is:
�coliform ��append         dog
1            NaN                NaN         NaN
2      1.3680317         0.33229608 -0.82884927
3     -0.8913680         2.79798207  0.21854663
4     -0.1836785        -0.07519385  1.44215138
5      1.6093652         0.79405964  0.07038501
6     -0.5938197        -0.10297580  0.36824972

Comment: can you post an example code snippet like this one `df <- replicate(3, rnorm(5)) ; colnames(df) <- c('A', 'B', 'Č'), df_h2o <- as.h2o(df)`. Thanks!
Comment: can you provide your environment information (i.e. version of R, type of OS).
Comment: @Lauren added to my question.
Comment: @Lauren added it.
Answer: I tested out the special character issue from the post you specified, using the corresponding Jira Ticket code snippet. I was not able to reproduce an issue; the rendering of the character is correct, for both version 22.214.171.124 and 3.18.0.08. I used Mac OS X El Capitan, with R version 3.4.2.
To install version 220.127.116.11, first make sure h2o isn't running somewhere then run the following code found in h2o's download instructions
# The following two commands remove any previously installed H2O packages for R.
if ("package:h2o" %in% search()) { detach("package:h2o", unload=TRUE) }
if ("h2o" %in% rownames(installed.packages())) { remove.packages("h2o") }

Next, we download packages that H2O depends on.
pkgs <- c("RCurl","jsonlite")
for (pkg in pkgs) {
  if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) }
}

# Now we download, install and initialize the H2O package for R.
install.packages("h2o", type="source", repos="http://h2o-release.s3.amazonaws.com/h2o/rel-wolpert/11/R")

If you want to downgrade to 3.18.08, shutdown h2o, shutdown R and then rerun the above but specify the link for 3.18.08 install.packages("h2o", type="source", repos="http://h2o-release.s3.amazonaws.com/h2o/rel-wolpert/8/R").
Comment: Could you try using one or both of these special characters:  "–" and "''" in your column names?


Como salvar/recuperar imagem na memória no android?

Question: Olá, tenho um Array de Bytes que é  uma imagem, apartir dele, como posso salvar na memória externa e caso não exista salvar na memória interna do android? e depois como posso estar recuperando essa imagem?
Preciso salvar em um local que essas imagens não apareçam na galeria do celular, somente na aplicação.
Comment: Crie uma tabela no banco de dados sqlite e salve o array de bytes como um objeto Blob. http://developer.android.com/training/basics/data-storage/databases.html http://developer.android.com/reference/java/sql/Blob.html
Comment: Mas é isso que estou fazendo no momento, mas as imagens com um tamanho de 2MB estão dando erro na hora de fazer a leitura. Acho que se eu persistir no BD imagens com esse tamanho pode ficar mt pesado o sqlite.
Answer: Vamos primeiro escrever um método que verifique a existência do SDCard e se é possível escrever nele:
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

O método retorna true se é possível escrever no SDCard ou false caso não exista ou por qualquer razão não é possível escrever nele.
Necessitamos de dois métodos para salvar o byte[], um para salvar na memória interna e outro para salvar no SDCard.
Salvar na memória interna:
public void saveArrayToInternalStorage(String fileName, byte[] imagem){
    try{
        FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(imagem);
        fos.close();
    }catch (IOException e) {
        Log.w("InternalStorage", "Error writing", e);
    }
}

Salvar no SDCard:
Para que o MediaStore não veja as imagens usaremos getExternalFilesDir() para obter o Path ao SDCard.
public void saveArrayToSDCard(String fileName, bytes[] imagem){
    File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File file = new File(path, fileName);
    try{
        OutputStream os = new FileOutputStream(file);
        os.write(imagem);
        os.close()
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing", e);
    }
}

Como usar:
if(isExternalStorageWritable(){
   saveArrayToSDCard("nomeDaImagem", imagemEmBytes);
}else{
    saveArrayToInternalStorage("nomeDaImagem", imagemEmBytes);
}

Se a aplicação for para correr em versões anteriores ao Android 4.4, é neccessário obter a permissão WRITE_EXTERNAL_STORAGE, adicione o seguinte ao Manifest
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18" />
    ...
</manifest>

Nota: As imagens gravadas por estes métodos serão apagadas quando a aplicação for desinstalada.
Fonte: Android Storage Options
Comment: Muito obrigado, amanhã testarei essa solução. e referente a nota "As imagens gravadas por estes métodos serão apagadas quando a aplicação for desinstalada. " é um grande alivio, pois as imagens que estou trabalhando são um tanto "pesadas".
Answer: Pelo que eu li nesse tópico do SOEn o limite é 1 MB, mais do que isso você teria que utilizar o NDK.
Nesse mesmo tópico também existe outra abordagem que utiliza o sqlite4java.
Dê uma olhada, pode ser útil.
Comment: Muito bom saber que o erro ocorre pois ultrapassou o limite estabelecido, fiquei preocupado inicialmente achando que fosse algum erro no código. Interessante o sqlite4java, vou estudar a chance de coloca-lo nesse meu projeto, mas futuramente concerteza  posso estar utilizando em outro projeto. Obrigado Bruno


Integrar leitor de QRCode no sistema Delphi!

Question: Gostaria de saber se é possivel integrar ao delphi um leitor de QRCode que use a WebCam para efetuar a leitura. Ou um leitor de codigo de barras. Não tenho nem idéia de como começar, por isso não fiz nada ainda!
Comment: Como eu não vou ter tempo de redigir uma resposta, veja esse link: http://blog.marcocantu.com/blog/qr_codes_delphi.html
Answer: Tanto os leitores simples quanto os mais complexos utilizam a entrada do teclado ou usb para imputar os dados no seu sistema.
Para ler QRCode costuma-se utilizar um leitor 2d. Este imputa no campo com foco a string do QRCode(ou o tipo de código 2d que for) e por default envia uma quebra de linha ao final.
Na programação nada muda, vai ser como se o usuário tivesse digitado o código e apertado enter. Por exemplo:
Lendo este QRCode:

Com o leitor 2d, você vai adicionar 12345678901234567890 no campo com foco.


VBA Adicionar "-" a cada dois caracteres para formar MAC Address

Question: Gostaria de formar um endereço MAC a partir dos dados coletados de um leitor de código de barras.
Preciso que a cada dois caracteres seja adicionado um "-".
Texto de entrada:
A9B8C7D6E5F4
Texto de saída:
A9-B8-C7-D6-E5-F4
Até agora cheguei até o seguinte ponto de tentativa de resolução:
Function MACADddress(macaddress As String) As String
    Dim i As Integer

    Dim C As Integer
    Set C = 0

    Dim k As Integer
    Set k = macaddress.lenght

    Dim NewMac As String
    Set NewMac = ""

    For i = 0 To k
        C = C + 1

        If C = 2 Then
            NewMac = NewMac & macaddress(i) & "-"
            C = 0
        Else
           NewMac = NewMac & macaddress(i)
        End If

        MsgBox (NewMac)
    Next i

    MACADddress = NewMac
End Function

Answer: Código
Function MACADddress(macaddress As String) As String
    Dim i As Long, C As Long, k As Long
    Dim NewMac As String
    NewMac = ""
    C = 0
    k = Len(macaddress)

    For i = 1 To k
        C = C + 1
        If C = 2 And i <> k Then
            NewMac = NewMac & Mid(macaddress, i, 1) & "-"
            C = 0
        Else
            NewMac = NewMac & Mid(macaddress, i, 1)
        End If
        'MsgBox (NewMac)
    Next i
    MACADddress = Trim(NewMac)
End Function

Observações
A função que você tentou fazer é para vetores e matrizes e não string.
Para strings utilize a função Len() para obter o tamanho da string e um loop para iterar sobre cada letra desta string.
Depois a sua lógica estava correta, somente foi adicionado a condição And i <> k, pois estava adicionando "-" após o último caractere.
Comment: Daniel, muito obrigado. Funcionou certinho aqui!


What is the maximal path of a tree?

Question: Could anyone explain obviously what the maximal path is ? Is it necessary for a tree that has two maximal paths that share no common vertex ?
Comment: This question is rather unclear. A single vertex is a tree, Or two vertices with one edge joining them. Or a star - a single vertex joined by an edge to as many vertices as you like, and no other edges exist. And a graph with more than one component can have maximal paths in each component. Please clarify the question.
Comment: @MarkBennet I meant a connected graph that graph has two maximal paths that share no common vertex ? And, I had two questions, first whatis the maximal path of a tree, second, is it possible for a graph that has two maximal paths that share no common vertex.
Answer: I will assume that you meant a connected tree. Also, I am using maximal to mean "of maximal length," which may not be what you meant.
A path in a tree is a sequence of vertices, with no repeats, where successive vertices in the sequence are adjacent. If a path $P$ is at least as long as any other path, then that path is maximal. It is possible for there to be more than one maximal path. For example, in this tree,
<code>     C
    /
A--B
    \
     D
</code>
both of the paths $A,B,C$ and $A,B,D$ are maximal, since they are of length $3$, and there are no paths of length $4$ or greater.
Note that these two paths share a common vertex. This is always true: any two maximal paths will share a common vertex.
Why? Suppose you had two disjoint paths, $P_1=v_1,v_2\dots,v_n$ and $P_2=w_1,w_2\dots, w_n$. Consider the pair $v_i,w_j$ for which the distance between $v_i$ and $w_j$ is minimal (here, distance means the length of the shortest path connecting them). Then there is a path $v_i,p_1,p_2,\dots,p_k,w_j$ which connects $v_i$ and $w_j$. None of the intermediate vertices $p_1,\dots,p_k$ can be in $P_1$ or the $P_2$, because of the minimality when we chose $v_i$ and $w_j$. This implies that $P_1$ and $P_2$ weren't maximal, since at least one of the following paths are longer:
$$
v_1,\dots,v_i,p_1,\dots,p_kw_j,\dots,w_n
$$
$$
w_1,\dots,w_j,p_k,\dots,p_1,v_i,\dots,v_n
$$
We have shown that disjoint paths are not maximal, which means that any two maximal paths intersect.
Comment: From your answer, I concluded that any two maximal paths have to share a  common vertex.
Comment: @Rinzler That is correct, as long as "maximal" means what I think it means. There are two definitions of maximal, one given in my answer, one given in Theophile's. By my definition, what you said is correct, by his definition, what you said is not correct.
Answer: It depends what you mean by maximal. Usually maximal is different from maximum in the following sense: a maximal path can mean a path that cannot be made any longer; in other words, at each end there is a vertex all of whose neighbours are already on the path.
Note that under this definition, a maximal path is not necessarily a path of maximum length. Here is one such example ($A-B-C$):
<code>  A
  |
o—B—o—o—o—o—o
  |
  C
</code>
Comment: Oh wow, I was way off. This is usually what is meant by maximal path.
Comment: @MikeEarnest I think your answer is helpful too, though, because it's not entirely clear what the OP is asking ...
Comment: @Théophile thanks for answering. I meant a conncected graph, and your explanation is so clear.
Comment: @Rinzler Okay, I'm glad the explanation helped. In that case, you can see that two maximal paths won't necessarily intersect.
Answer: I think it is possible for that a tree that has two maximal paths that share no common vertex .
<code>      o
      |
      o
      |
o     o         o
 \    |        /
  o - o - o - o
 /        |    \
o         o     o
          |
          o
          |
          o
</code>
As shown above, the graph of a tree has two maximal paths that share no common vertex. The length of the maximal paths is 5.
Comment: It depends on what you mean by *maximal path*.  There is a path of length $7$ (the two vertical lines and their connection).  On the other hand the are several paths which cannot be extended and do not share a vertex, such as the two of length $2$ which have sloping edges.
Answer: Maximal path in a graph G is a path P in G that is not contained in a longer path.
When a graph is finite, no path can extend forever, so maximal(non-extendible) paths exist.
Comment: Welcome to MSE. Your answer adds nothing new to the already existing answers.

What is the maximal path of a tree?


Problems getting Default Content module to work with Features

Question: I'm trying to export some Default Content when creating a drupal 7 distribution.  Noticed that Phase II is using Default Content module to set default content for OpenPublic.  I can't find any documentation on how to get the module to work.
How do you get the Default Content Module to work?
Answer: Figured this out.
After you enable the Default Content Module, there will be a new setting for each Node by where you can select Revision information, URL path settings, Comment settings, etc.
This new setting is Machine Name.  You make a machine name for the node of the default content.
Then when you make a new feature (I guess it is best practice to have all of the default content nodes in one feature so when you deactivate the feature all of the default content will turn off and the features will still work) there will be a new component "Content Item".
This will have all of the machine names that you made while creating/editing nodes.
Hopefully someone will find this useful so they don't bang their heads against the wall like I did.


Unsure about these operators being used in this way

Question: This code example comes from http://www.cplusplus.com/doc/tutorial/templates/ :
template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}

What I am confused about is the "a>b?a:b" section part of the code which is being returned. Can somebody help me to understand what is going on here? Thanks.
Answer: This is the ternary operator. It evaluates the expression before the ?, and if it's true, the value before the : is returned. Otherwise, the value after the : is returned.
It is basically a concise way of expressing the following if/else statement:
if ( a>b)
{
    return a;
}
else
{
    return b;
}

Comment: I understand the part about checking to see if what is before the ternary operator is true, but why the a before the : ? <- (That's a regular question mark, btw!)
Comment: @angrytoad Because that's where you put the value to return if the expression is true.
Answer: It's known as the ternary operator:
http://www.cplusplus.com/articles/1AUq5Di1/
You can think of return (a > b) ? a : b; as:
if(a>b) {
  return a;
} else {
  return b;
}

Keep in mind that the ternary operator actually produces a value, which is either a or b (which is why it works in the return statement).
So you can do things like
myType c = (a>b) ? a : b, which is roughly equivalent to
myType c;
if(a > b) {
  c = a;
} else {
  c = b;
}


How to make voip calls from java web application

Question: Following is my use case:
I am developing a web application using Java/J2EE. My application will have registered users and any one of them should call each other at any time. I don't have any problem even if i have to use some proprietary solution/API, but i don't want user to install anything like skype on their systems. What can be the possible solution?
Regarding calls:

Laptop - Mobile phone calls
Can it be possible that one user uses his laptop/system to place calls to the other users mobile?
Laptop - Laptop (voip calls). In this case, both will use headsets, like we do in GTalk.

Please suggest.
Answer: I am not a J2EE developer, I'm more into .NET. If I have a web app and I need to have a voip functionality there are several ways this can be achieved: 1) Use a 3rd-party component like Netviewer. 2) If you would like to develop the component yourself and you want it to be interoperable then use one of the open source protocol stacks available out there (there are many) that is based on SIP or may be H323, surely there are some for Java. 3) If you don't need inter-operability then you can create your own protocol stack on top of TCP.
I will do case 2 and 3 as ActiveX components to be embedded in the web page.
For VoIP calls the 3 solutions above are suitable. However, if you need to make VoIP to mobile calls then you need a PBX data switch like one of those from Cisco that can route your VoIP traffic to the telephone network. Checkout Asterisk, it's open source.
Netviewer link
http://www.netviewer.com/en/
Java SIP
https://github.com/usnistgov/jsip
Asterisk Opensource Telephony Projects
http://www.asterisk.org/
Comment: Small amendment: a servlet interface for SIP is available (javax.servlet.sip.*). [JSR116](http://jcp.org/en/jsr/detail?id=116).


Showing a vector field is not conservative

Question: Let $f: R^n \to R^n$. $||x||$ is Euclidean norm. Define $f(x) = g(||x||)$. where $g: [0, \infty) \to R^n$ is differentiable on $(0, \infty)$. I want to show that $f$ is not conservative on $R^n$. ($g$ is not constant)
MY Effort:
Write $f(x) = (f_1(x),...,f_n(x))$ and $g(||x||) = (g_1(||x||),...,g_n(||x||))$ Hence,
$$ f_i = g_i(||x||) $$. In particular
$$ \frac{ \partial f_i}{\partial x_j} = \frac{x_j}{\sqrt{x_1^2+...+x_n^2}} \cdot \frac{d g_i }{d x_j}(||x||)$$
and
$$ \frac{ \partial f_j}{\partial x_i} = \frac{x_i}{\sqrt{x_1^2+...+x_n^2}} \cdot \frac{d g_j }{d x_i}(||x||)$$
Is this enough to conclude that mixed partials are not equal, therefore $f$ is not conservative?
Comment: @GiuseppeNegro: It seems that we cannot write the field as something like $f(x) = g(||x||)$. The magnitude are the same but the direction are different
Comment: How do you know that they are not equal? $g$ might be constant.
Comment: Also, is $F=f$?
Comment: I have edited. yes, $f =F$. Also, I assume $g$ is not constant.
Comment: Also, it should be $\frac{dg_i}{dt}$ instead.
Comment: But $f$ might very well be conservative. Take a uniformly charged sphere centered at the origin and consider the electrostatic field it generates.
Comment: @John what is $t$ is this case?
Comment: @MathcanbeFun: Each $g_i$ are functions $\mathbb R \to \mathbb R$, so $t$ is the variable of the domain.
Comment: or maybe it should be $\frac{d g_i}{d ||x||} $? since im applying chain rule.
Comment: @MathcanbeFun: Yes that's also fine. It is just a personal preference to me to use $t$.
Comment: So, how can I argue that indeed the mixed partials are different?
Comment: @MathcanbeFun: Note when $x_i \neq x_j$, they are indeed different.
Answer: We are given a vector-valued function
$${\bf g}:\qquad t\mapsto{\bf g}(t)=\bigl(g_1(t),\ldots,g_n(t)\bigr)\qquad(t>0)$$
and define a vector field ${\bf F}=(F_1,\ldots,F_n)$ on $\dot{\mathbb R}^n$ by
$${\bf F}({\bf x}):={\bf g}\bigl(|{\bf x}|\bigr)\ .$$
The integrability condition for this field reads
$$F_{i.j}({\bf x})-F_{j.i}({\bf x})\equiv 0\qquad \forall i\ne j\ .\tag{1}$$
Now according to the chain rule we have
$$F_{i.j}({\bf x})=g_i'\bigl(|{\bf x}|\bigr)\>{\partial|{\bf x}|\over\partial x_j}=g_i'\bigl(|{\bf x}|\bigr){x_j\over{|\bf x}|}\ .$$
The condition $(1)$ can therefore be interpreted as follows: The matrix
$$\left[\matrix{g_1'\bigl(|{\bf x}|\bigr)&g_2'\bigl(|{\bf x}|\bigr)&\ldots&g_n'\bigl(|{\bf x}|\bigr)\cr
x_1&x_2&\ldots&x_n\cr}\right]\tag{2}$$
must have all subdeterminants of order $2$ equal zero, in other words: have rank $\leq1$, for all ${\bf x}\in\dot{\mathbb R}^n$.
Assume now that ${\bf g}'(r)\ne{\bf 0}$ for some $r>0$. Then the rank condition on the matrix $(2)$ would imply that all vectors ${\bf x}$ on the sphere $S^{n-1}_r$ of radius $r$ are multiples of ${\bf g}'(r)$, which is absurd.
Answer: This is a comment with unwieldy formulas.
The correct formulas:
$$
\frac{ \partial f_i}{\partial x_j} = \frac{x_j}{\sqrt{x_1^2+...+x_n^2}} \cdot g_i'(||x||)
$$
($g$ is a  vector-valued 1-var function)
Comment: the derivative of $g_i$ with respect to what variable ?
Comment: Respect to the *only* variable. Isn't a partial derivative.