Trabalhar com dois forms diferentes no mesmo local

Question: Estou fazendo alguns algoritmos básicos com php, e então de curiosidade decidi fazer um html com um form, input text e um botão para enviar. no PHP.Se a variável que coloquei no input text for igual a 1, o php exibe outro form abaixo. Tentei digitar algo nesse input text e enviar, mas não aconteceu nada, mesmo eu tendo criado um algorítmo que iria exibir o número na tela.
Segue o código:

<form method="POST">
Valor:<input type="text" name="n1">

<input type="submit" name="Enviar" value="Enviar"></form>
<input type="hidden" name="n2" value="0">

<?php
if(isset($_POST['n1']) || isset($n1))
{
    if(isset($_POST["valor1"]))
    {
        $n1=$_POST['valor1'];
    }
    else
    {
        $n1 = $_POST['n1'];
    }
    if(isset($_POST["valor2"]))
    {
        $n2=$_POST['valor2'];
    }
    else
    {
        $n2 = $_POST['n2'];
    }
    if($n1 == 1)
    {
    echo '<form method="POST">Valor:<input type="text" name="n2">

<input type="submit" name="Enviar" value="Enviar"></form>
<input type="hidden" name="valor1" value="'.$n1.'">
<input type="hidden" name="valo2" value="'.$n2.'">';
}
if(isset($_POST['n2']) || isset($n2))
{
    echo $n2;
}

}
?>

Comment: Não consigo identificar a variavel do`textarea`, nem mesmo encontrei um [textarea](https://www.w3schools.com/tags/tag_textarea.asp), explica um pouco mais sobre sua dúvida e verifica se esta tudo no exemplo
Comment: Perdão, confundi `text area` com `input text`. E eu gostaria de saber se tem algum jeito de criar um `form` à partir do php que funcione
Comment: que consiga ser lido pelo algorítmo e que exiba seu valor na tela
Answer: Montei a partir do seu código um exemplo, existem formas mais diretas e menos verbosa de fazer a mesma coisa, porém, procurei deixar mais legível.

    <?php
    $n1 = "";
    if(isset($_POST['n1']))
    {
        $n1 = $_POST['n1'];
    }
    $n2 = "";
    if(isset($_POST['n2']))
    {
        $n2 = $_POST['n2'];
    }

    ?>
    <form method="POST">
        Valor1:<input type="text" name="n1" value="<?php echo $n1; ?>">

        <?php

        if($n1 != "")
        {
            echo 'Valor2:<input type="text" name="n2" value="' . $n2 . '">
';
        }
        ?>
        <input type="submit" name="Enviar" value="Enviar">
    </form>

    Valor 1 = <?php echo $n1; ?>

    Valor 2 = <?php echo $n2; ?>

Comment: Tive que corrigir algumas partes do código pois onde estou testando ele não consegue ler alguns comandos. Mas funcionou perfeitamente, obrigado


ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. ... Maximum length is 63 characters

Question: I'm writing a GitHub Action to deploy my application to Cloud Run (a GCP service) with action deploy-cloudrun. It successfully create and push my application image to the artifact registry, but it failed to deploy to Cloud Run.
And I don t know what name is too long or how to change it ?
From Github Action console :
Running: gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json
Error: failed to execute gcloud command `gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json`: This command is equivalent to running `gcloud builds submit --tag [IMAGE] .` and `gcloud run deploy xxxxxxxxxxxxx --image [IMAGE]`

Building using Dockerfile and deploying container to Cloud Run service [xxxxxxxxxxxxx] in project [xxxxxxxx] region [xxxxxxxxxxx]
Building and deploying...
Uploading sources.........done
Building Container..................................done
failed
Deployment failed
ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters.

My workflow :
name: Deploy to production

...

jobs:
  deployment-job:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v2
      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v0
        with:
          ...
      - name: Deploy to Cloud Run
        uses: google-github-actions/deploy-cloudrun@v0
        with:
          service: ${{ env.SERVICE_NAME }}
          image: ${{ env.RUN_REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/cloud-run-source-deploy/${{ env.SERVICE_NAME }}:latest
          project_id: ${{ env.PROJECT_ID }}
          region: ${{ env.RUN_REGION }}
          tag: ${{ env.PACKAGE_VERSION }}

Comment: I see you are using uppercase letters and spaces in your names.Can you try deploying it by changing the name by following the convention i.e, using lowercase letters, numbers and '_'. Let me know if that works!
Comment: How did you solve the error? I got same error following this tutorial: https://www.youtube.com/watch?v=t5EfITuFD9w
Answer: According to your error message:
ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters

You can check what contains your env var env.SERVICE_NAME and make it compliance with the requirements of the error.

Resource name must use only lowercase letters, numbers and '-'.
Must begin with a letter and cannot end with a '-'.
Maximum length is 63 characters

The aforementioned is defined in this GCP documentation which points to This K8s reference about RFC 1035 Label Names. This is in similar to the GCP Docs
..This means the name must:

contain at most 63 characters
contain only lowercase alphanumeric characters or '-'
start with an alphabetic character
end with an alphanumeric character


UIImage+RoundedCorner with SDWebImage

Question: I am using SDWebImage to load images into my table view. I would like the images in my table view to be resized and have round corners. I found UIImage+Resize and UIImage+RoundedCorner to do this. Both libraries works great seperately but I have not been abl to combine them. I could resize and round the corners of the image SDWebImage returns but I have found this to be fairly resource heavy and therefore I would like to have the images resized before saving them to the cache.
When an image is loaded from the net for the first time it is probably shown before being saved to the cache therefore I would also like to resize the image when it is loaded for the first time.
I have not been able to do this as I cannot figure out which method of SDWebImage to manipulate the image in. All I need is to call the following on the right UIImage in SDWebImage.
UIImage *image = [image thumbnailImage:50 transparentBorder:0 cornerRadius:5 interpolationQuality:kCGInterpolationHigh];

Can anyone tell me where in SDWebImage I should place this piece of code to have the image manipulated before being saved to the cache and have a manipulated image sent to the image view when it is loaded from the internet and not the cache?
Answer: For the resize image part, I don't have a good answer.
For the round corners feature, you are completely going to the wrong way, this is what I try to do before... try to resize and round every image and save it to the disk...... too complex, too many things to do...
the correct and simple way is to set the UIImageView cornerRadius of your table cell:
cell.imageView.layer.cornerRadius = 8;
cell.imageView.layer.masksToBounds = YES;

Comment: Fast and easy way, but affects performance. Rendering images with cut corners is better in terms of tableview performance
Answer: I figured this out.
You should manipulate the image in the following methods in SDImageCache.m:
 1. - (void)storeImage:(UIImage *)image forKey:(NSString *)key;
 2. - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
 3. - (void)storeImage:(UIImage *)image imageData:(NSData *)data forKey:(NSString *)key toDisk:(BOOL)toDisk;

In the third method you must remember to convert your UIImage to NSData using the code below. This should be done if toDisk is true.
NSData *croppedRoundedImageData = UIImageJPEGRepresentation(croppedRoundedImage, 1.0);
if (croppedRoundedImageData) data = croppedRoundedImageData;

Using if (croppedRoundedImageData) data = croppedRoundedImageData; your app will not crash if your data is NULL when you try to save it.
In SDWebImageDownloader.m you must add your code for manipulating in - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection This is used for the first load of the image (when not in cache)
Answer: The SDWebImageManagerDelegate protocol is what you're looking for.
https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDWebImageManager.h#LC96
I implemented the method we need in my AppDelegate class.
#pragma mark - SDWebImageManagerDelegate

-(UIImage*) imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL{

    UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale);

    CGRect box = CGRectMake(0, 0, image.size.width, image.size.height);
    // Add a clip before drawing anything, in the shape of an rounded rect
    [[UIBezierPath bezierPathWithRoundedRect:box
                                cornerRadius:15.f] addClip];
    // Draw your image
    [image drawInRect:box];

    // Get the image, here setting the UIImageView image
    UIImage* ret = UIGraphicsGetImageFromCurrentImageContext();

    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();
    return ret;

}

You can tell the sharedManager to use your delegate like this.
SDWebImageManager* imageManager = [SDWebImageManager sharedManager];
imageManager.delegate = self;

I did this in didFinishLaunchingWithOptions.
Keep in mind that this approach clips along the bounds of the image at it's native size. If the bounds of your image are being rendered outside the bounds of your view (aspect-fill, etc), you will not see the rounded corners.
This approach is more performant than clipping the image every time it's rendered, but be aware of the above disadvantage.
Answer: This is a great find, but I find that by adding your image manipulation code in SDWebImageDownloader.m it makes thumbnails for all images using SDWebImage. What I did was create an SDWebImageManager instance and used the method:
- (void) webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image;

to create the images, the only problem is because the images come in different times I'm trying to find a way to link them properly with an action.
Great answer nonetheless.
Answer: Im using SDWebImage framework which doesn't give me the ability to modify the files but i have a global function like this:
     + (UIImage*)circleImageWithImage:(UIImage*)image
      {
          UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
          CALayer *layer = [imageView layer];
          [layer setMasksToBounds:YES];
          [layer setCornerRadius:imageView.frame.size.width / 2];

          UIGraphicsBeginImageContext(image.size);
          [layer renderInContext:UIGraphicsGetCurrentContext()];
          UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
          return newImage;
      }

and global funtion to scale image like this:
      + (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
      {
          UIGraphicsBeginImageContext(newSize);
          [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
          UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
          return newImage;
      }

UIImage+RoundedCorner with SDWebImage


Angular2. Can I use ViewChild and @Input at the same time?

Question: I need to transfer some data into child element and run function in it.
I use ViewChild for access to the function. But in child childParam still undefined.
Parent template:
<my-modal #myModal [childParam]="parentParam"></my-modal>

Parent component:
@ViewChild('myModal') myModal;
parentParam: any;

onSubmit(value: any){
  this.parentParam = value;
  this.myModal.modalShow();
}

Child component:
@Input() childParam: any;

modalShow(){
  console.log(this.childParam);
}

Why childParam is undefined?
What is better: change directly childParam by ViewChild:
this.myModal.childParam = 'test string';

or send data through function parameters:
this.myModal.modalShow('test string');

Comment: I guess `parentParam` is not yet set when `modalShow()` is called, but hard to tell, because the code doesn't allow to derive what might be going one.
Comment: I create plunker [link](https://plnkr.co/edit/ZcZaJ0Wbu9CAobxkd2LJ?p=preview). When I first time clicked on the button - didn't show anything, second time clicked -  string was shown.
Answer: You don't need to set the child parameter through a @ViewChild reference.
Try this instead. Parent template:
<my-modal #myModal [childParam]="parentParam"></my-modal>

Parent component:
private parentParam: any;

onSubmit(value: any){
  this.parentParam = value;
  this.myModal.modalShow();
}

The value of parentParam will bind to the childParam value directly in this way so whenever the parentParam value is updated it will be available in the child component.
If that does not work then try and add ngOnChanges to the child component since you will then be able to debug (set a breakpoint) for whenever the value is updated from the parent:
Import OnChanges (add this in addition to the other imports you have from @angular/core):
import { OnChanges} from '@angular/core';

Add NgOnChanges to your child component class:
export class MyChildComponent implements OnChanges {

Implement method ngOnChanges. This method will be called whenever an input parameter is changed:
 ngOnChanges(changes: any) {
     debugger; //set breakpoint
 }

Answer:
When this.parentParam = value; is executed in onSubmit() then Angular first needs to run change detection for bindings to get updated.
Angular runs change detection when an event handler has completed. Which in your case is onSubmit() which means that childParam will get the value passed after onSubmit() was executed.
What you could do is to run change detection explicitely
  constructor(private cdRef:ChangeDetectorRef) {}

  onSubmit(value: any){
    this.parentParam = value;
    this.cdRef.detectChanges();
    // here `value` is assigned to `childParam`
    this.myModal.modalShow();
  }

Plunker example


Bass fret board position knowledge

Question: I`ve been playing 6 string bass for quite a while now, but during live performances with low light, l sometimes find it difficult to find the right notes on the fretboard, esp C on the E string getting mixed up with Bb and D,
I've put a small bit of tape under neck at the correct position on G of the B string, this has helped heaps,
Any more ideas???
Also fret knowledge,
Because Ive got a great ear,
Im lazy at learning all the notes on my massive fretboard,
I play by patterns a lot of the time,
Any Ideas on getting my fret knowledge better.
Starting on a 6 string with 144 notes is probably a bad idea...
Anyway I have what i have and have to deal with it.
Comment: Do you have fret markers on the fingerboard, either under the strings or on the top edge?  What style of music are you most often playing?
Comment: As a fellow six-string bassist, I have the same problem. I can generally find the right fret (although I'll occasionally have off-by-one errors closer to the nut, since I can't always see the frets) but often, I'll accidentally fret the wrong string or something like that.
Comment: I played a 6 for about year - MM Bongo. Great sounding bass, not hard to play. I finally put it aside because the strings were too close together and my accuracy was constantly compromised. You definitely should not start with a 6. A good 4 is all you really need, and you'll learn you way around the neck much better with a 4, because you'll **have to** use more positions to get the notes you need, instead of just playing the same positions on a different string.
Answer: Its all about practice, just how some guitarists play their instruments behind their backs, all you have to do is practice memorizing your fretboard without looking. With time you will see that you don't need any lighting, you just need to feel the guitar(bass) in your hand and you will know just where everything is at.
Answer: Learning scales and arpeggios is a great way to improve your fretboard knowledge. Try and learn scales and arpeggios all over the fretboard and say out loud the notes as you play them.
Don't worry about playing fast whilst doing this. Taking the time to get this in your head is the key here.
Answer: I guess you mean the 8th fret getting mixed up with 6th and 10th. Play standing up whenever you play, and try to hit that 8th fret without looking. After a while, your arm muscle memory will have learned how far to stretch. Eyes then come into play, as they know the target fret is between dots. Do it many times a day - just wear the bass, play 8th fret without looking, take it off again, repeat 10 times at least. You may need to peek at first, but eventually, it'll pay off. Learning all the notes is, for me, a waste, as the guitar works on patterns which are transferable key to key. I doubt whether many players who were stopped in mid stream would tell you what note they were on - our brains, in most cases, don't work that way: 'now I'm playing a C, then an Eb, after which it'll be a Gb and a G'. Do players really think like that ?
Comment: Cheers Tim, good stuff

Bass fret board position knowledge


Ajax - problem with response inside a div

Question: I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.
The div:

Ajax:
 $(document).ready(function() {
 $('#submit').click(function() {

 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

if(response == 'success')
{
    alert('success');
}
if(response == 'empty')
{
    alert('empty');

}
if(response == 'bad')
{
     $("#result").html(response);

}
}

 });
});
});

save.php:
<?php
$co= 'aaa';

if(!empty($_POST['tosave']))
{

    if($_POST['tosave'] == $co)
{
    $foo = fopen("plik.txt","a+");

            flock($foo, 2);
            fwrite($foo,$_POST['tosave']."\r\n");
            flock($foo ,3);
            fclose($foo);
echo "success";
exit();
} else {

    echo 'bad';
    exit;
}

} else {

echo "empty";
exit;

}
?>

Comment: I think all you need is put response in nested if else may be that will work
Answer: This might be because you don't prevent the default behavior on the submit button which is to send the form's data to the specified link, maybe in your case the link is on the same page than your PHP leading to only see the message in the div for a split second before the page reloads itself.
So to prevent this default behavior, you have to catch the event and use the preventDefault() function like so :
$('#submit').click(function(event) { //we pass the event as an attribute
event.preventDefault(); //we prevent its default behavior so we can do our own stuff below
 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

    if(response == 'success')
    {
       alert('success');
    }
    if(response == 'empty')
    {
       alert('empty');

    }
    if(response == 'bad')
    {
        $("#result").html(response);

    }
}

  });
 });
 });

Comment: event.preventDefault(); fixed problem. Thank you so much :)
Comment: Ok ,no probs. Done :)
Answer: First of all there is a mistake in your Ajax call code you have write your submit.click() submit function under document.ready().remove document.ready() because submit.click()will run when you submit the form. Second thing is you should add
event.preventDefault() to prevent the default behabiour of your submit form otherwise it will display for short time and then it will disappeared.See my code below it is working.
AJAX WITH HTML FORM:
 <!DOCTYPE html>

        <title></title>

    <form id="action">
        <input type="text" name="tosave" value="bbb">
        <button type="submit">clickme</button>>
    </form>

PHP:
<?php
$co = 'aaa';

if (!empty($_POST['tosave'])) {

    if ($_POST['tosave'] == $co) {
        $foo = fopen("plik.txt", "a+");

        flock($foo, 2);
        fwrite($foo, $_POST['tosave'] . "\r\n");
        flock($foo, 3);
        fclose($foo);
        echo "success";
        exit();
    } else {

        echo 'bad';
        exit;
    }

} else {

    echo "empty";
    exit;

}
?>
**OUTPUT DISPLAY IN DIV: bad**


predict y variable that is only available as a sum by group

Question: I would like to fit a model in order to predict a y variable, however in the training data the y variable is only available for groups of items (the x variables are available for each individual iteam).
Here's an example of such a dataset created in R:
<code>library(dplyr)
data("marketing", package = "datarium")
data_original <- tibble(marketing) %>% mutate(id = row_number()) %>% select(id, everything())
set.seed(10)
data_original$group_id <- sample.int(50, size = nrow(data_int), replace = T)

data_for_prediction <- data_original %>%
  group_by(group_id) %>%
  mutate(group_n = n(),
         group_sales = sum(sales)) %>% ungroup() %>%
  select(-sales)
data_for_prediction
</code>
The data looks like this:
<code>> data_for_prediction
# A tibble: 200 x 7
      id youtube facebook newspaper group_id group_n group_sales
   <int>   <dbl>    <dbl>     <dbl>    <int>   <int>       <dbl>
 1     1   276.     45.4       83.0       26       6       141.
 2     2    53.4    47.2       54.1       16       2        25.4
 3     3    20.6    55.1       83.2       22       6        96.4
 4     4   182.     49.6       70.2       35       3        40.7
 5     5   217.     13.0       70.1        5       3        52.4
 6     6    10.4    58.7       90         12       7       122.
 7     7    69      39.4       28.2       14       6       114.
 8     8   144.     23.5       13.9       14       6       114.
 9     9    10.3     2.52       1.2       31       4        70.3
10    10   240.      3.12      25.4       22       6        96.4
# … with 190 more rows
</code>
What is the proper way to estimate the sales for each individual line, while one only has the information of the sum of sales for each group ?
Comment: Do you have some prior information on distribution of $Y$? Can values be negative? Some external sample of individual $Y$ observations? ... Maybe EM-algorithm? Group testing might be an application  https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3841014/
Answer: It depends on how you conceive of the original variables and what your model is.
In the commonest case, the response value $Y_i$ for each item $i$ is considered a random variable whose mean depends on the explanatory variables $x_{1i},\ldots, x_{pi},$ where (a) the responses are independent and (b) have a common variance $\sigma^2.$  That is, there are regression parameters $\beta_0, \beta_1, \ldots, \beta_p$ for which
$$E[Y_i] = \beta_0 + \beta_1 x_{1i} + \cdots + \beta_p x_{pi}\tag{*}$$
and $\operatorname{Var}(Y_i) = \sigma^2$ (which may be unknown; the point is that it doesn't vary between items).
Let $g(i)$ be the group in a set $\mathfrak G$ to which item $i$ is assigned.  (Limit $\mathfrak G$ to the existing groups so that every group has at least one item in it.)
Suppose, as in the question, the group assignment is independent of all the variables. (This is crucial: in many applications, the individual responses $Y_i$ may be correlated within each group, in which case you need to supply information about that correlation in order to make progress.) What is the "group response"?  Often it is a total (as in the question) or average of the responses of all the items in the group.  Both are analyzed similarly, so for each $\gamma \in \mathfrak G$ let us set
$$\bar Y_\gamma = \sum_{i\mid g(i) = \gamma} Y_i$$
to be the total response for the items in group $\gamma$ (having $|\gamma|$ items).  The basic laws of expectation and variance along with the model $(*)$ imply
$$\begin{aligned}
E[\bar Y_\gamma] &= \sum_{i\mid g(i) = \gamma} E[Y_i]\\
&= \sum_{i\mid g(i) = \gamma} \left(\beta_0 + \beta_1 x_{i1} + \cdots + \beta_p x_{pi}\right)\\
&= |\gamma| \beta_0 + \beta_1 \bar{x}_{\gamma 1} + \cdots + \beta_p \bar{x}_{\gamma p}
\end{aligned}$$
and
$$\begin{aligned}
\operatorname{Var}[\bar Y_\gamma] &= \sum_{i\mid g(i) = \gamma} \operatorname{Var}[Y_i]\\
&= \sum_{i\mid g(i) = \gamma} \sigma^2\\
&=\sigma^2|\gamma|
\end{aligned}$$
where
$$\bar x_{\gamma j} = \sum_{i\mid g(i) = \gamma} x_{ij}$$
are the sums of the explanatory variable values in the group.  Moreover, assuming there is no overlap among separate groups, the independence of the $Y_i$ implies the independence of the $\bar Y_\gamma.$
With $|\gamma|\beta_0$ now playing the role of the constant term, this model is identical to $(*)$ except for one twist: the group responses $\bar Y_{\gamma}$ potentially have different variances, depending directly on the sizes of their groups.  This makes it a classic Weighted linear regression model with weights proportional to $|\gamma|.$  (When all the group sizes are the same, this again is an ordinary regression.)
Using standard algorithms, you can fit (that is, estimate) the group mean responses $\bar Y_\gamma$ as well as the $\beta_j$ and $\sigma^2$ itself, provided you retain information about the group sizes $|\gamma|.$  Then, armed with an estimate of $\sigma^2,$ you can predict (a) individual $Y_i$ for $i\in\gamma;$ (b) individual $Y,$ independent of the data; or (c) responses for other groups (not in the data), provided you have values for their explanatory variables.  "Prediction" in this sense involves erecting prediction limits around the estimated values: see What is the difference between prediction and estimation?
Comment: "in which case you need to supply information about that correlation in order to make progress" Could you clarify how this correlation should be considered / included in the model? Thanks,
Comment: @jesse An example would be in time series analysis where, for instance, you might posit that the correlation between variables $Y_t$ and $Y_s$ is some given function of the *lag* $|t-s|,$ perhaps with some unknown parameters also to be estimated. A simple example of this (the AR-1 model) is that this correlation equals $\rho^{|s-t|}$ for some unknown $\rho \in [-1,1].$  I have just posted a picture of a general time series correlation structure at https://stats.stackexchange.com/a/550314/919.


Preprocess a twig template file

Question: I don't fully understand how preprocessing works
I have a twig template /themes/custom/client/templates/content/node--myfile.html.twig that I want to alter
I want to show/hide a part of that template depending on a field display with the machine name field_display stored in the matching content type called Project and with the machine name project_machine_name.
So I well understand I have to use hooks in order to do this, but I don't understand how I am supposed to name the hook functionnality neither how I'm supposed to access the data stored from the content type into the hook to alter the template view.
I know the hooks goes into the .module file. Actually I already have some of them, but I don't understand them properly. The only things I know for sure is that the function name must start by the module name
function my_module_SOMETHING_SOMETHINGELSE() {

}

So the issue is: how to name the hook function in order to alter the template ? I guess I understand the name is some kind of standard structure which will tell drupal if the function needs to be called before a specific action.
How to retrieve data stored from the display field of the content-types Project?
Thanks for your assistance.
Answer: Preprocess hooks are named MY_MODULE_preprocess_TEMPLATE_NAME, in your case:
function my_module_preprocess_node__myfile(&$variables) {}

Notice how I replace the template's dashes with underscores in the function name.
Now you can get the display variable from $variables['node']->field_display->value.
Comment: Have you cleared the cache?
Comment: Thanks but I wonder if there isn't something to do in order to make the hook effective. I've just set a var_dump in the my_module_preprocess_node__myfile but nothing is triggered when I go to the page.
Comment: I didn't. It's fine now, thank you. I still need to look how i'm going to really alter the resulting html but that's an other issue.
Comment: Cool, glad it helped :)

Preprocess a twig template file


Why is this C++ array template class initialized with garbage values?

Question: Using Visual Studio 2019, I'm attempting to create a template array class where Tis the type of the array and S its size:
// Array.hpp
#include <iostream>
template<typename T, int S> class Array {

    T m_array[S];

public:

    Array() : Array(0) {}

    Array(const T& val) {
        for (int i = 0; i < S; i++) { m_array[i] = val; }
    }

    template<typename E> Array(const E& val) {
        for (int i = 0; i < S; i++) { m_array[i] = static_cast<T>(val); }
    }

    int size() const { return S; }
    T operator[](int position) const { return m_array[position]; }
    T& operator[](int position) { return m_array[position]; }

    friend std::ostream& operator<<(std::ostream& os, const Array& a) {
        os << '[';
        if (a.size() > 0) { os << a[0]; }
        for (int i = 1; i < a.size(); i++) {
            os << ', ' << a[i];
        }
        return os << ']';
    }
};

However, when I create an object of Array and print it, I find weird values mixed into the output:
// main.cpp
#include "Array.hpp"

using namespace std;

int main()
{
    Array<int, 10> a1(3);
    Array<double, 10> a2(3.14);
    Array<int, 10> a3(5.9);

    cout << a1 << endl;
    cout << a2 << endl;
    cout << a3 << endl;
}

Gives me this output:
Comment: `', '` -> `", "`
Comment: Please, don't post text as image.
Answer: This:
', '

Is a multi-character literal.  That's not at all what you want.  Replace it with:
", "

And if you can, turn on the warning in your compiler for multi-character literals.  In GCC that is -Wmultichar.


github_conf/branch_protection_rules.json keeps on showing up

Question: I am using GitHub Codespaces and try to run pre-commit run --all-files on its terminal. I have pasted the pre-commit configuration below for reference.
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.4.0
    hooks:
      - id: check-added-large-files
      - id: check-yaml
      # - id: end-of-file-fixer
      - id: mixed-line-ending
        args: [--fix=lf]
      - id: requirements-txt-fixer
      - id: trailing-whitespace
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.74.1
    hooks:
      - id: terraform_fmt
      - id: terraform_checkov
        args:
          - --args=--quiet
          - --args=--skip-check CKV_GCP_83 # We rely on Google-managed encryption keys
          - --args=--skip-check CKV_GCP_45 # Extensive privileges are actually required
          - --args=--skip-check CKV_GCP_90 # We rely on Google-managed encryption keys
      - id: terraform_tflint
      - id: terraform_docs
        args:
          - --hook-config=--path-to-file=README.md
          - --hook-config=--add-to-existing-file=true
          - --hook-config=--create-file-if-not-exist=true
      - id: terraform_tfsec
      - id: tfupdate

When I run it initially, there is no github_conf folder in the repository. However, after running the pre-commit command, a folder github_conf is created, and it contains a file branch_protection_rules.json. It looks like this:
{
    "message": "Not Found",
    "documentation_url": "https://docs.github.com/rest"
}

We have indeed a branch-protection rule enabled, but this is a completely different branch and I am not even trying to commit or push, just running the pre-commit is causing the issue. Basically I don't want to keep the file (branch_protection_rules.json) in my repo as it also interferes with at least one pre-commit hook, which is otherwise required.
At this point, I don't get what is going on, as the "message" is not that descriptive. Can anyone help?
Additional information: After further investigation, this is definitely related to the hook terraform_checkov... Do let me know if you have experienced issues with this hook.
Comment: sounds like a codespaces problem -- none of the hooks you've configured do this
Answer: Had the same issue. It turns out that terraform_checkov hook does not set --framework=terrraform parameter when running checkov (as one might expect). That means it will run all possible checks - also github one.
There are two solutions:

Set the argument yourself to run only terraform check:

    - id: terraform_checkov
      args:
        - --args=--framework=terraform

Set environmental variable CKV_GITHUB_CONFIG_FETCH_DATA=False to ignore github checks (as in here).
Comment: That's the solution (particularly the first solution is useful). Thank you!


Fluent NHibernate Order by Property in related Entity

Question: I have 2 tables in my database:
CREATE TABLE [items](
    [item_id] [int] IDENTITY(1,1) NOT NULL,
    [item_name] [varchar](50) NOT NULL,
    [group_id] [int] NOT NULL
)

CREATE TABLE [itemgroup](
    [group_id] [int] IDENTITY(1,1) NOT NULL,
    [group_name] [varchar](50) NULL
)

and here are mapping classes for these entities:
    public class ItemMap : ClassMap<Item>
    {
        public ItemMap()
        {
            Table("items");
            Id(x => x.Id).Column("item_id");
            Map(x => x.Name).Column("item_name");
            References(x => x.ItemGroup).Column("group_id").Fetch.Join();
        }
    }
    public class ItemGroupMap : ClassMap<ItemGroup>
    {
        public ItemGroupMap()
        {
            Table("itemgroup");
            Id(x => x.Id).Column("group_id");
            Map(x => x.Name).Column("group_name");
        }
    }

How can I get all items from the database ordered by group name?
Just in case I'm using Fluent NHibernate v126.96.36.1992.
Comment: What method of querying are you using Criteria, QueryOver, Linq, or HQL?
Comment: @Vadim I use Criteria for getting all items, here is an example of my code:
`using (var session = SessionFactory.OpenSession())
 {
   return session.CreateCriteria(typeof(TEntity)).AddOrder(CreateOrder(sortedBy, sortDirection)).SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List();
}`
Comment: Sorry, forgot to add
`private static Order CreateOrder(string sortedBy, string sortDirection)
{
   return new Order(sortedBy, true);
}`
sortedBy is the property name.
Answer: You just need to add a join to your criteria.
var criteria = Session.CreateCriteria<Item>()
                      .CreateAlias("ItemGroup", "group")
                      .AddOrder(Order.Asc("group.Name"));

Answer: in your ItemGroup you must have a list of Item, suppose you call it Items
Then in ItemGroupMap add
mapping.HasMany(x => x.Items)
            .Cascade.All()
            .Inverse()
            .SetAttribute("order-by", "item_name");

Now you can have a list of ItemGroup with all children ordered by item_name
Comment: This will get all items for a group ordered by name. OP wants all items from the db ordered by item group name.


Motivation/Intuition behind Lorentz spaces

Question: My current understanding is that the Lorentz spaces $L^{p,q}$ arise naturally as interpolation spaces between $L^1$ and $L^\infty$, but then people often describe them heuristically by saying something along the lines of "Lorentz spaces provide a finer control than $L^p$ spaces", and this is where I'm lost - what does that really mean?
It certainly seems like a reasonable claim, if only because you now have an extra parameter to tweak, and since $L^{p,p}=L^p$, well the Lorentz spaces are simply a larger class of spaces amongst which your classical $L^p$ spaces live, so sure, they are "better" because there's more of them, so I can give more nuanced descriptions, but I don't really understand where the nuance lies, I don't understand what extra control the Lorentz spaces provide you that the usual $L^p$ spaces do not.
I feel like my question is very vague overall, so feel free to ask for clarifications. As an example of the type of answer that I think there might be to what I am asking is the following cryptic (to me anyway) comment on the wikipedia page for "Lorentz spaces": "The Lorentz norms provide tighter control over both qualities than the $L^{p}$ norms, by exponentially rescaling the measure in both the range (p) and the domain (q)". I have no idea what that means, if anyone does, please let me know, but it seems like, after clarification, it would provide a nice intuitive explanation for precisely how Lorentz spaces provide finer control than $L^p$ spaces do.
Answer: Note that if $F$ is the distribution function of $f$, and $f = H \cdot \mathbf{I}_E$, where $E$ is a measurable set with $|E| = W$, then $F = W \cdot \mathbf{I}_{[0,H]}$. Thus, in some sense, the distribution function switches the domain and range of a function, so that the 'range' of $f$, is the 'domain' of $F$, and vice versa. In particular, the $L^p$ norms
$$ \| f \|_p = \left( \int |f(x)|^p\; dx \right)^{1/p} \sim \left( \int_0^\infty F(t) t^p \frac{dt}{t} \right)^{1/p} $$
try to understand the distribution of $f$ by scaling it's range, or by scaling the `domain' of $F$ (changing the power of $t$ in the equation). Conversely, the Lorentz norm
$$ \| f \|_{p,q} \sim \left( \int_0^\infty (tF(t)^{1/p})^q \frac{dt}{t} \right)^{1/q} $$
have two separate powers $p$ and $q$. Here $p$ scales the domain of $f$, and $q$ scales the domain and range of $f$ simultaneously. We changed $F(t)$ from being linear to being a power of $1/p$, but this is only slightly confusing because
$$ \left( \int_0^\infty (t^pF(t))^{1/q} \frac{dt}{t} \right)^{1/q} \sim \| f \|_{p,q/p} $$
The reason that $q$ needs to scale the domain and range simultaneously is so that it acts as a second order parameter for the family of quasinorms, when compared to the primary exponent, which is $p$.
Answer: Maybe, it is related the embedding $L^{p,p} \subseteq L^{p,q}$ for every $q\ge p$ with
$$
\|f\|_{L^{p,q}}
\lesssim
\|f\|_{L^{p,p}}.
$$


GitLab all repository ssh clone url shows wrong path

Question: GitLab Web all repository SSH clone URL shows wrong path.
Wrong path: ssh://firstname.lastname@example.com:443/test_group/test30-jan-2020.git
After modified With following command able to clone on terminal.
git clone email@example.com:test_group/test30-jan-2020.git

To correct the same Under Admin--> Settings---> couldn't find option to change it to proper clone url. Any workaround will be highly appreciated.
Comment: Hi Kenster, Yes I have updated the question.
Answer: It should be, as documented in "Configuring the external URL for GitLab" in external_url or your /etc/gitlab/gitlab.rb
Check first  Admin Area > Settings > General > Sign-in restrictions
Or, for omnibus, in gitlab-config-template/gitlab.rb.template.
The OP Kishore mentions in the comments:

In /etc/gitlab.rb file, Gitlab_rails['gitlab_shell_ssh_port'] = was enabled.
I have disabled and restarted. It is showing correct path.

(You could see that setting used in sameersbn/docker-gitlab issue 38 )
Comment: Thanks VonC,  In /etc/gitlab.rb file. Gitlab_rails['gitlab_shell_ssh_port'] = was enabled. I have disabled and restarted. It is showing correct path.
Comment: @Kishore Great! Well done. I have included your comment in the answer for more visibility.


Why cannot std::stol be converted to a std::function object?

Question: #include <functional>
#include <string>

using namespace std;

int main()
{
    function<long(const string&, size_t, int)> fn = stol;
}

The code above cannot be compiled as expected with the following error:

error : no matching constructor for initialization of 'std::function<long (const std::string &, std::size_t, int)>' (aka 'function<long (const basic_string<char, char_traits<char>, allocator<char> > &, unsigned long long, int)>')
Comment: To begin with, [this `std::stol` reference](http://en.cppreference.com/w/cpp/string/basic_string/stol) should be helpful. Note the arguments, and compare them with yours.
Comment: The second parameter of `std::stol()` is a `size_t*` pointer, not a `size_t` value like you have it.
Answer: Two reasons:

The second argument of std::stol has type std::size_t*, not std::size_t.
std::stol is overloaded to also accept const std::wstring& as its first argument.

You would have to write:
function<long(const string&, size_t*, int)> fn =
  static_cast<long(*)(const string&, size_t*, int)>(stol);

Addendum (July, 2019): In C++20, the solution described above becomes invalid (see comments). You have to use a lambda instead.
Comment: @L.F. It seems that new wording was added in C++20, so this answer was correct at the time when it was written. I'll add a note about how it breaks in C++20.
Comment: There is *slightly* less repetition if you write it as: `typedef long sig(const std::string&, size_t*, int);
    const auto pstoll = static_cast(std::stol);
    const std::function fn = pstoll;`  - but it is still pretty nasty.
Comment: Oh, I suppose: `typedef long sig(const std::string&, size_t*, int); const std::function fn = static_cast(std::stol);` also works.


Get table ID after insert with ColdFusion and MySQL

Question: My normal process for inserting into one table and then getting the ID back so that I can insert into another table is like this in MSSQL:
DECLARE @transactionKey uniqueidentifier
SET @transactionKey = NEWID()

INSERT INTO transactions(transactionKey, transactionDate, transactionAmount)
    VALUES(@transactionKey, '#transactionDate#', '#transactionAmount#')

DECLARE @transactionID int
SELECT @transactionID = transactionID
    FROM transactions
    WHERE transactionKey = @transactionKey

INSERT INTO transactionItems(transactionID, itemID, itemAmount)
    VALUES(@transactionID, '#itemID#', '#itemAmount#')

SELECT @transactionID as transactionID

My question is 2 parts. First, is this the best way to do this? I read that there is a chance that the GUID changes on me and I end up with a invalid GUID in the second table. I am assuming the chances of that are very slim and I have been doing this for years on various projects and have never had a problem.
The second part of my question is does something like this work in MySQL? I am starting to work on a new project using MySQL and I am not exactly sure the best way to do this. I have normally only worked on MSSQL in the past.
I am using CF9 and MySQL on this new project.
Any help on this would be great.
Thanks in advance.
Comment: Re: *I read that there is a chance that the GUID changes on me* Where did you read that?
Answer: Part 1:
I would personally not batch multiple statements within a single query to reduce the risk of SQL injection. This is a setting within your datasource on the ColdFusion administrator. Executing a stored procedure, which might be what you are doing(?), is another story, but, you should rephrase your question to "Get primary key after insert with mySQL Stored Procedure" if that is your intention.
Part 2:
ColdFusion, like many things, makes getting the primary key for a newly inserted record very easy--even if you are using auto-increment keys, GUIDs or something like Oracle's ROWNUM. This will work on any almost every database supported by Adobe ColdFusion including MSSQL or MySQL. The only exception is the version of the databse--for example, MySQL 3 will not support this; however, MySQL 4+ will.
<cfquery result="result">
  INSERT INTO myTable (
      title
  ) VALUES (
    <cfqueryparam value="Nice feature!" cfsqltype="cf_sql_varchar">
  )
</cfquery>

<--- get the primary key of the inserted record --->
<cfset NewPrimaryKey = result.generatedkey>

As of CF9+, you can access the new ID (for any database) using the generic key name:
result.GENERATEDKEY    // All databases

For CF8, different databases will have different keys within the results value. Here is a simple table to help I copied from the cfquery documentation.
result.identitycol    // MSSQL
result.rowid          // Oracle
result.sys_identity   // Sybase
result.serial_col     // Informix
result.generated_key  // MySQL

If you have any questions you can see a pretty dump as follows:
<cfdump var="#result#" />

Comment: For MSSQL it's not identifycol... it's identitycol
Comment: +1 for the "result" attribute, using cfqueryparam, and splitting up the queries into more granular calls.
Comment: @aaron Thanks! I don't know why I I have been doing it the other way for so long. This is a lot easier.
Comment: I dont know why, but i've never been able to get result.generatedKey to work for me. using result.generated_key works fine.
Comment: Depending on the database you are using, the primary key is named differences. Guess the driver authors were 'almost' on the same convention.
Comment: Something to look out for, I'm not sure if it applies only to MSSQL or not but the value is NOT part of result if you have any t-sql comments in the query (e.g. --this is a comment.)
Comment: For MSSQL it's result.identitycol (with a T) not identifycol (with an F). SO won't let me edit and fix just one character.
Answer: Here is a quick solution for MSSQL. It uses the SCOPE_IDENTITY() function that returns the ID of the last row inserted in the previous insert statement.
http://msdn.microsoft.com/en-us/library/ms190315.aspx
<cfquery>
    DECLARE @iNewGeneratedID INT

    INSERT INTO transactions
        (
            transactionDate,
            transactionAmount
        )
    VALUES
       (
            <cfqueryparam value="#transactionDate#" type="cf_sql_date">,
            <cfqueryparam value="#transactionAmount#" type="cf_sql_integer">
       )

    SET @iNewGeneratedID = SCOPE_IDENTITY()

    INSERT INTO transactionItems
        (
            transactionID,
            itemID,
            itemAmount
        )
    VALUES
        (
            @iNewGeneratedID,
           <cfqueryparam value="#itemID#" type="cf_sql_integer">,
           <cfqueryparam value="#itemAmount#" type="cf_sql_integer">
        )

    SELECT @iNewGeneratedID AS iNewGeneratedID
</cfquery>

Comment: thanks! I like this way also better than the other way I was doing it. This will be good for stored procedures.
Answer: As per the answer of @aaron-greenlee, The result variable of INSERT queries contains a key-value pair that is the automatically generated ID of the inserted row; this is available only for databases that support this feature.
And the below is possible way to return the inserted record for all databases.
<cfquery result="result">
   INSERT INTO myTable (
      title
   )
   OUTPUT INSERTED.*
   VALUES (
   <cfqueryparam value="Nice feature!" cfsqltype="cf_sql_varchar">
   )
</cfquery>

You will get the inserted record details in result.
Hope this helps. Thanks.
Answer: The getGeneratedKey function at cflib.org can be used with most databases:

Example:
<cfquery name="insertArtist" datasource="cfartgallery" result="r">
    insert into artists (firstName, lastName)
    values('todd','sharp')
</cfquery>
<cfquery name="getArtists" datasource="cfartgallery">
    select *
    from   artists
</cfquery>
<cfdump var="#getArtists#">
<cfoutput>#getGeneratedKey(r)#</cfoutput>

<cffunction name="getGeneratedKey"
    hint="I normalize the key returned from cfquery" output="false">

      <cfargument name="resultStruct" hint="the result struct returned from cfquery" />
      <cfif structKeyExists(arguments.resultStruct, "IDENTITYCOL")>
          <cfreturn arguments.resultStruct.IDENTITYCOL />
      <cfelseif structKeyExists(arguments.resultStruct, "ROWID")>
          <cfreturn arguments.resultStruct.ROWID />
      <cfelseif structKeyExists(arguments.resultStruct, "SYB_IDENTITY")>
          <cfreturn arguments.resultStruct.SYB_IDENTITY />
      <cfelseif structKeyExists(arguments.resultStruct, "SERIAL_COL")>
          <cfreturn arguments.resultStruct.SERIAL_COL />
      <cfelseif structKeyExists(arguments.resultStruct, "GENERATED_KEY")>
          <cfreturn arguments.resultStruct.GENERATED_KEY />
      <cfelse>
          <cfreturn />
      </cfif>
</cffunction>


Como adicionar um iframe por meio do JS?

Question: Estou tentando adicionar um iframe simples em uma página html, mas não está funcionando:
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://www.google.com.br/");
document.getElementsByClassName('col-12 col-md-4').appendChild(ifrm);

HTML:

Answer: O trecho de código document.getElementsByClassName traz um array de informação para funcionar com o seu código precisa indicar a posição, nesse exemplo eu sei que tem uma posição por isso [0] e após appendChild:

var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://www.google.com.br/");
document.getElementsByClassName('col-12')[0]
     .appendChild(ifrm);

Observe no console.log

console.log(document.getElementsByClassName('col-12'));

que demonstra a quantidade de elementos que são selecionados.
Comment: Excelente. E como eu faria para estilizar esse iframe direto do js?
Comment: @DiegoCândido https://stackoverflow.com/questions/5927012/javascript-createelement-style-problem dá uma olhada!
Answer:

Olá! Essa seria uma forma de fazer também.


Domain clients can't reach website with same name as domain

Question: I know this is a very basic question but I need some help.
I'm setting up a domain controller on Zentyal with the domain name example.com. But I need the domain users to be able to get to our company website with the same name (http://example.com) that's hosted out there on a third party's server.
I know this has something to do with adding a DNS record, but I don't know what type. I would experiment, but I don't want to break the whole works!
Answer: Do not name your Active Directory Domain the same as your existing domain. It will cause all sorts of trouble.
Take an unused subdomain for example ad.example.com .

If the organization has an Internet presence, use names that are relative to the registered Internet DNS domain name. For example, if you have registered the Internet DNS domain name contoso.com, use a DNS domain name such as corp.contoso.com for the intranet domain name.
  --http://support.microsoft.com/kb/909264
Comment: @Moses Yes. You have to apply the appropriate mapping via group policy. (If you've got an existing Kerberos REALM, you'll also need to setup a trust.)
Comment: I was hoping to take advantage of SSO. Can SSO be configured if they are different?
Comment: http://serverfault.com/questions/76715/windows-ad-domain-naming-recommendations/473530#473530
Comment: @84104 I'll have to do my homework on that one. What problems can occur if they are the same, out of curiosity?
Comment: @Moses It mostly has to due with running two different master name servers. The least ugly kludge is to import the zone information from your public NS's SOA, into AD, which is still quite an ugly kludge esp. as there's no standard mechanism for it.
Answer: Domain controller hostname should not be equal to web server hostname if they are at different hosts. It's like trying to access two computers using single ip address :)
If having different hostnames is not an option for some reason, you may use solutions listed below.
The idea is to setup port forwarding (destination NAT) at domaing controller.
You may forward all traffic to port 80 of your domain controller to port 80 of web server.
The same effect may be achieved by using reverse proxy software like NGINX.
Be aware of drawback that without proper handling (e.g. adding proxy-forwarded-for header at nginx) you will not have real client ip addresses at your web server's logs.
Comment: That's workable but awful. It involves installing IIS on every DC, for one thing.
Comment: The issue itself is awkward :) If changing domain controller hostname is not an option, it may be the only possible solution. Will update the answer to mention that.
Answer: The most basic solution is to add a www DNS entry with the external IP address, so users on the domain can just type www.example.com to get to the external website.


"initdb: encoding mismatch" when running gitlab-ctl reconfigure

Question: I am installing Gitlab-ce Omnibus in a Vagrant box (Debian 18.04 LTS).
In my provisioning script, I run gitlab-ctl reconfigure. I get an error:

initdb: encoding mismatch

Console output:
default: * execute[/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8] action run
default:
default:     [execute] The files belonging to this database system will be owned by user "gitlab-psql".
default:               This user must also own the server process.
default:
default:               The database cluster will be initialized with locale "en_US".
default:               initdb: encoding mismatch
default:               The encoding you selected (UTF8) and the encoding that the
default:               selected locale uses (LATIN1) do not match.  This would lead to
default:               misbehavior in various character string processing functions.
default:               Rerun initdb and either do not specify an encoding explicitly,
default:               or choose a matching combination.
default:
default:
default:
default: ================================================================================
default:
default: Error executing action `run` on resource 'execute[/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8]'
default:
default: ================================================================================
default:
default:
default:
default:
default: Mixlib::ShellOut::ShellCommandFailed
default:
default: ------------------------------------
default:
default: Expected process to exit with [0], but received '1'
default:
default:
default: ---- Begin output of /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 ----
default:
default:
default: STDOUT: The files belonging to this database system will be owned by user "gitlab-psql".
default:
default:
default: This user must also own the server process.
default:
default:     The database cluster will be initialized with locale "en_US".
default:     STDERR: initdb: encoding mismatch
default:     The encoding you selected (UTF8) and the encoding that the
default:     selected locale uses (LATIN1) do not match.  This would lead to
default:     misbehavior in various character string processing functions.
default:     Rerun initdb and either do not specify an encoding explicitly,
default:     or choose a matching combination.
default:     ---- End output of /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 ----
default:     Ran /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 returned 1
default:
default:     Resource Declaration:
default:     ---------------------
default:     # In /opt/gitlab/embedded/cookbooks/cache/cookbooks/postgresql/recipes/enable.rb
default:
default:      80: execute "/opt/gitlab/embedded/bin/initdb -D #{postgresql_data_dir} -E UTF8" do
default:      81:   user postgresql_username
default:      82:   not_if { pg_helper.bootstrapped? }
default:      83: end
default:      84:
default:
default:     Compiled Resource:
default:     ------------------
default:     # Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/postgresql/recipes/enable.rb:80:in `from_file'
default:
default:     execute("/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8") do
default:       action [:run]
default:       default_guard_interpreter :execute
default:       command "/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8"
default:       backup 5
default:       returns 0
default:       user "gitlab-psql"
default:       declared_type :execute
default:       cookbook_name "postgresql"
default:       recipe_name "enable"
default:       domain nil
default:       not_if { #code block }
default:     end
default:
default:     System Info:
default:     ------------
default:     chef_version=13.6.4
default:     platform=ubuntu
default:     platform_version=18.04
default:     ruby=ruby 2.3.7p456 (2018-03-28 revision 63024) [x86_64-linux]
default:     program_name=/opt/gitlab/embedded/bin/chef-client
default:     executable=/opt/gitlab/embedded/bin/chef-client
default:
default: Recipe: gitlab::gitlab-rails
default:
default: * execute[clear the gitlab-rails cache] action run
default:
default:     - execute /opt/gitlab/bin/gitlab-rake cache:clear
default:
default:
default: Recipe: gitlab::redis
default:   * ruby_block[restart redis svlogd configuration] action create
default:
default:     - execute the ruby block restart redis svlogd configuration
default:   * ruby_block[reload redis svlogd configuration] action create
default:
default: - execute the ruby block reload redis svlogd configuration
default:
default:
default:
default: Running handlers:
default: There was an error running gitlab-ctl reconfigure:
default: execute[/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8] (postgresql::enable line 80) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
default: ---- Begin output of /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 ----
default: STDOUT: The files belonging to this database system will be owned by user "gitlab-psql".
default: This user must also own the server process.
default:
default: The database cluster will be initialized with locale "en_US".
default: STDERR: initdb: encoding mismatch
default: The encoding you selected (UTF8) and the encoding that the
default: selected locale uses (LATIN1) do not match.  This would lead to
default: misbehavior in various character string processing functions.
default: Rerun initdb and either do not specify an encoding explicitly,
default: or choose a matching combination.
default: ---- End output of /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 ----
default: Ran /opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data -E UTF8 returned 1
default: Running handlers complete
default:
default: Chef Client failed. 141 resources updated in 01 minutes 00 seconds
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

Already tried, didn't help:
cat > /etc/default/locale <<EOF
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
EOF

localedef -v -c -i en_US -f UTF-8 en_US.UTF-8 || true

Answer: I was able to bypass this problem by running the command it died at manually:

SU to the user that'll own the database file, (mentioned in the error output):
su gitlab-psql
Run the command manually, removing the hard-coded -E UTF8 parameter
/opt/gitlab/embedded/bin/initdb -D /var/opt/gitlab/postgresql/data

That should then run with your own locale encoder, create the database etc, then you can exit the SU shell and re-run: gitlab-ctl reconfigure which completed fine afterwards for me.


2 funções no javascript na mesma div

Question: Tenho divs no meu código em html (são 3 barras de menu), quando eu clico, ela se transforma (como se fosse uma animação) em um x, porém, quero que quando ela se transforme e eu clique nela ela execute outra função diferente da primeira. Um "openNav()" na primeira e um "closeNav()" na segunda, alguem sabe um jeito? Usando o "onClick="
  function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.getElementById("t").onClick="closeNav()";

 }

 function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
 }

 function myFunction(x) {
  x.classList.toggle("change");
 }

Answer: Pode ser facilmente resolvido definindo uma variavel global.

Exemplo da Lógica: https://jsfiddle.net/u4rqyfxz/
Comment: Variáveis globais são uma péssima solução. Use de atributos do elemento para fazer a manipulação ou encapsule isso em uma `IIFE`. Uma solução sem variáveis globais: https://jsfiddle.net/u4rqyfxz/1/
Comment: Ele da esse erro "Uncaught TypeError: openNav is not a function" apesar de estar logo antes
Comment: @PedroFreitas Acho que por causa da variavel e a function ter o mesmo nome. Alterei e exemplifiquei com um exemplo.
Comment: Valeu! era isso mesmo, muito obrigado

2 funções no javascript na mesma div


In R, pacf() function not consistent with arima()$coef

Question: Is my understanding off with what to expect from the following functions output:
arima(Y_t.TS.Residuals, order = c(2, 0, 0), include.mean=FALSE)$coef[2]

pacf(Y_t.TS.Residuals, plot=F)[2]

Shouldn't these values be identical?
When I compute them I get -0.045 from the pacf amd -0.3376156 from the arima()$coef[2].
The data being inputted is obviously identical.
Thank you,
Christopher
Answer: arima() uses full maximum likelihood estimation, while pacf() uses the Durbin-Levinson algorithm. So the objective functions are different, hence the estimates are different.
You should get the same result as pacf() if you use ar().
pacf(lynx, plot=FALSE)[2]
#>
#> Partial autocorrelations of series 'lynx', by lag
#>
#>      2
#> -0.588
ar(lynx, order=2)$ar[2]
#> [1] -0.5878918


Returning and accessing array of object of structure in jna

Question: I have a structure that contains some char pointers in C:
struct inputsheet
{
    char* TestCaseID[MAX_TEST_CASES];
    char*  Description[MAX_TEST_CASES];
};

I have a function that is returns array of object of structure:
struct inputsheet* getapi(char *docname);

Now I want to use this in Java. How can I handle this array of object of structure? I am able to handle a single object but not the array.
For single object my code in C is here:
public class str3 extends com.sun.jna.Structure implements com.sun.jna.Structure.ByReference {
   public Pointer a1;
   public Pointer b2;
   public Pointer c3[]=new Pointer[10];
}

Accessing it:
str2 s2=CLibrary.INSTANCE.parseid(xmlFile1);
for(Pointer p1:s2.testCaseID) {
    if(p1!=null)
    {
        System.out.println(p1.getString(0));
    }
}

EDIT
\\c code
struct str3{
char *a;
char *b;
char *ab[10];
}

\\jna implementation

package parser;
import com.sun.jna.Pointer;
public class str3 extends com.sun.jna.Structure implements     com.sun.jna.Structure.ByReference{
public Pointer a1;
public Pointer b2;
public Pointer c3[]=new Pointer[10];
}

\\calling it
import com.sun.jna.Native;
import com.sun.jna.Pointer;
 class ab{
    interface CLibrary extends Library{
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary("chardll",
    CLibrary.class);
    str3 getStruct();
    }

public static void main(String[] args) {
    int size = 5;
    str3 a=CLibrary.INSTANCE.getStruct();
    str3[] ab=(str3[])a.toArray(size);
    System.out.println(ab[0].a1.getString(0));
    }
}

It is giving Garbage value as output,, where I have to update my code to get the right output..
Answer: From the javadoc:

Returning an Array of struct
Declare the method as returning a Structure of the appropriate type, then invoke Structure.toArray(int) to convert to an array of
  initialized structures of the appropriate size. Note that your
  Structure class must have a no-args constructor, and you are
  responsible for freeing the returned memory if applicable in whatever
  way is appropriate for the called function.
// Original C code
struct Display* get_displays(int* pcount);
void free_displays(struct Display* displays);

// Equivalent JNA mapping
Display get_displays(IntByReference pcount);
void free_displays(Display[] displays);
...
IntByReference pcount = new IntByReference();
Display d = lib.get_displays(pcount);
Display[] displays = (Display[])d.toArray(pcount.getValue());
...
lib.free_displays(displays);

EDIT
Nominally, your structure would look like this (based on your native definition):
class inputsheet extends Structure {
    public Pointer[] TestCaseID = new Pointer[MAX_TEST_CASES];
    public Pointer[] Description = new Pointer[MAX_TEST_CASES];
}

public inputsheet getapi(String docname);

int size = ...; // whatever you do to figure out the size of your returned array
inputsheet sheet = INSTANCE.getapi("some-doc");
inputsheet[] sheets = (inputsheet[])sheet.toArray(size);

If the caller doesn't need to write to the inputsheet fields, you should use String instead of Pointer.
Comment: After using this i am still not able to get the desired result either it is giving me garbage value(in case I use BYREFERENCE),else it is giving NULL Pointer exception (in case of ByValue)
Comment: String can be used when my pointer is const but it is not in my case
Comment: It is incorrect to use `Structure.ByValue`, since your native function returns `struct*`, not `struct`.  You'll need to be a little more explicit about what you've tried; your question references `inputsheet`, `str3`, and `str2`, with no obvious relation between them.
Comment: Actually Input sheet is used in my main project, I was just trying to implement a dummy first,
In that str3 is my Structure,
Comment: How is your native code returning an "array of struct"?  According to your spec, the returned pointer must be a heap-allocated block of size `N*sizeof(str3)`, where `N` is the number of structures.
Comment: my native code is returning pointer to the array of struct,
    struct nit a[6];
    return a;
Comment: That's stack-allocated memory, which is invalid as soon as your function returns.  Do `malloc(6*sizeof(struct nit))` instead.
Comment: Hey Its done some problem was dere related to scope ,,the struct array that i was returning was not in Global scope .


Joik - traditional Sami songs from northern Sweden and Finland

Question: I have some questions about the traditional Sami singing, Joiken, which is practiced in the northern parts of Sweden, Finland and Norway.
I learned that you don't joik about something, but you joik something, i.e. express your feelings and make them appear in front of you and the audience - which sounds a similar to the alpine "Jodeln".
What I want to know for a Joik is

are syllables tied to certain meanings like sadness, joy, love, animals?
are there any syllables that are prefered over others, such as ley-la, o-ley - or can anything be used that sounds right at the moment of performing?
does the concept of a major or minor scale have any meaning like in Western music e.g.minor/sad, major/happy?
is a Joik purely improvised i.e. is it possible/impossible to do it again another time in the same way, other than recording it on a CD? In other words: does a performer try to remember that Joik and try to do it the same way the next time?
Comment: A recording that might be of interest: [Pseudo-Yoik](https://www.youtube.com/watch?v=yJwO3uHIgNc), by Jaakko Mänteyjärvi
Answer: Thank you for your question - it introduced me to the idea of "Joik", and since I have admired the Sami for years, my world is a little bit richer for now having heard some of it...
As far as answering goes - I have a Finnish friend that was good enough to reply to your questions, and I include her words below - her perspective is fascinating, and a good addition to material that I could find elsewhere on the net.

"I came across the yoik in research I did on Sami traditions and their
  reindeer husbandry. A yoik, as far as I understand it, is not a song
  in the way that we would describe or analyze something musically.
  There are no rules on notes, intonations,
  minor/major/key/sharp/flat/etc. And, one does not sing a yoik, or
  create one, but a 'yoik' is an 'identifier'. For instance, in
  traditional animal husbandry for the Sami, each reindeer is called by
  his/her yoik that the herder sings. The animals come to their yoik
  when they hear it. In the same way, a person develops their 'yoik' for
  a way to articulate who and what they are in the world. These change
  depending on their circumstances, what they experience... and,
  importantly, do not contain actual words, just sounds. A Finnish folk
  group, The Girls of Angeli, have made the 'yoik' popularized, and it
  is for this reason that people somehow equate it to an actual song.
  (info on them here:
  http://www.answers.com/topic/the-new-voice-of-the-north)
My understanding is that while it can feel and sound like a song, it
  should not be understood as such. That would be like calling what
  Buddhist singing bowls do exact notes. No, it is more like an aura, an
  energy of tonal inflection that paints itself into a representation of
  another physical being. A tonal ghost, if you will.
Oh, and not much has been studied on tonal inflection related to
  emotion in other cultures that I know of, apart from some interesting
  work in psychology on emotion words (linguistics). While the western
  mind might associate a minor note to sadness, this does not mean a
  non-western mind would do the same. Sami, and their Northern European
  counterparts, cannot be classified 'Western' in the way that the
  American public can claim it. Culturally, even the Northern countries
  are complete different beasts from each other. :) And, 'positive' and
  'negative' emotion words are also subjective, based on environment,
  meaning, cultural context. A 'negative' word in our culture is exactly
  what is helpful and considerate in another."

Hope this helps!


Comparing 2 models with very different R2 values but with very close RMSE values

Question: In my prediction model, there are 20 independent variables, and the dependent variable [y] has a range of 0-4. In the first approach I use LASSO to make a prediction [I have separate training and test sets]. Here is the result of the model evaluation:
METHOD      MAE    R2     RMSE
LASSO       0.561  0.141  0.985

In the second approach, first I train a classification model to identify records whose y value is 0 [y0] and whose y value is non-zero [ynon0]. After the classification, I run the LASSO regression model to predict the ynon0. At the end, I combine the items classified as y0 with the predicted ynon0 to evaluate the performance of ensembling two methods. Here are the results:
METHOD      MAE    R2     RMSE
CLASS+LASSO 0.536  0.437  0.971

I see that the second model explains much more variability in the outcome variable (given the R2 values) whereas the MAE and RMSE has improved slightly. Based on these results, I wonder if I should pay attention to R2, and should still consider the ensembling approach more effective, if my goal is to make an accurate prediction. Or, more generally, in what situation, I am supposed to favour the second approach or the first approach? Any ideas?
Comment: I don't think you can have higher $R^2$ and lower RMSE at the same time, in sample. There must be something fishy going on in the calculations. But if you mean out of sample, then $R^2$ is pretty useless in general as it totally neglects forecast bias and only reflects forecast variance.
Comment: Sounds like the second approach, apart form being better on all metrics, is also a better model for the data! (sounds like there's some zero-inflation going on there?)
Answer: Both $R^2$ and RMSE are calculated from the sum of squared errors (SSE), but they are scaled differently. $R^2=1-\frac{SSE}{n \cdot Var[y]}$ and $RMSE=\sqrt{\frac{1}{n}SSE}$.
The effect of this scaling is that if the $R^2$ value is small (like for your first model), then a small improvement in the RMSE results in a large improvement in $R^2$. For instance, if $R^2$ was 0.1, and the RMSE decreased by 30%, then the R^2 value would improve to 0.55!
I'm a little confused about your discussion about which approach is better. The second approach (the more complex model) is better by all three metrics. Recall that for RMSE and MAE lower is better.
Comment: Thanks for the answer! What I meant was, if I consider that the improvement was very minor in RMSE (in a given context), then why would not follow the simple model which is easier to train? Whereas, if I consider that the improvement was large in R2, I would definitely prefer the more complex model. But, I guess if my focus is on the prediction accuracy, RMSE and MAE are better metrics to use in my case. What do you think?
Comment: I generally use RMSE, and take the ratio to the RMSE of a simple baseline model (such as predicting the mean value). This gives a reasonable notion of relative improvement. The only advantage to $R^2$ is that it has a clearer scaling.


What is the purpose of a Brick workout?

Question: For triathlon, it is often recommended to do a Brick workout.  Bike, Run, Ick.
That is run right after finishing a distance bike ride.
What benefit does this provide?
Comment: What does "ick" mean?
Comment: @J.Winchester Clearly you have never done a hard Brick workout.  :)  Parts of it can really suck.  Thus the 'ick' is appropriate.
Answer: The performance benefit of brick workouts is widely debated. One thing that is much less argued is the importance of doing some brick workouts prior to your first race(s) to get used to running off the bike.  It can be quite disorienting the first couple of times.  You can help this phenomenon by synchronizing your bike and run cadences as much as possible.  Riding at 90rpm, then jumping off the bike and trying to run at 60 (or vice-versa), your legs will feel lost for 5-15 minutes.  But riding at 90 and taking off running at 90 can smooth things out.
Comment: I had never considered specifically synching cadences.  Interesting idea!
Comment: I do not agree - at the end of the riding phase you MUST loosen your legs. A lot of blood has accumulated in your thighs, you need a high cadence, id say 100+ for the last 150-200 meters, to help cause the blood to flow. If you go too slow towards T2 - your legs will feel exactly like the name of th exercise: BRICKS - or wood legs - and it's hard to run with Wooden Legs (Ask Pinocchio). Than you should start to run at a speed, that is not your fastest, but is indeed fast with the legs - yes, it's hard - but that's why most  people don't do tri's.
Answer: To build on Mike's answer, this triathlon workout article gives this as the reason for doing brick workouts to train for triathlons (key points highlighted):

So why should you do brick workouts? I bet you have an idea, but just
  in case you don't I will answer it anyway. Brick workouts are used
  to simulate race conditions because if you aren't training like you
  race then you will more than likely fail (unless your goal is simply
  to finish, and that's okay too). Simply put, if you want to optimize
  your triathlon performance, then you will need to implement brick
  workouts as part of your triathlon prep.
Another benefit to brick workouts is that you learn how to mentally
  overcome the pain of moving on to the next event. Sure, with enough
  training you will learn how to run with jelly legs going from the bike
  to the run, but mentally you need to be ready for the pain. If you
  know what to expect during each transition, then you will know how
  fast and how far to push yourself during each event. Pacing is
  incredibly important during a triathlon, and brick workouts help you
  best identify how to handle each event.

According to this training article, bricks are commonly bike/run combos, but there there are also training scenarios for swim/bike combos.
Comment: Good point about the swim/bike brick. For me, it's not so much the actual bike part, but being horizontal (swimming) doing an arm-centric exercise, and then transitioning to getting vertical and running to the transition area is something to get used to.  At the end of the swim in a race I consciously kick harder and with more knee movement to wake up my legs and get the blood flowing.

What is the purpose of a Brick workout?


Countability of $E_1 \times E_2 \times ...$

Question: True or False: If $E_1, E_2,...$ are finite sets and $$E:= E_1 \times E_2 \times ...\,\, := \left\{(x_1,x_2...): x_j \in E_j\,\,\forall j \in \mathbb{N}\right\}$$ then $E$ is countable.
Attempt:  Each $E_j$ is finite so there exists a $1-1$ function taking $\mathbb{N} \rightarrow  E_j$.  Hence each $E_j$ is at most countable.  This means that for any two of the $E_j$, $E_i \times E_j$ is also countable.  The Cartesian Product of infinitely many $E_j$ can be counted in a similar way to Cantor's Diagonal Argument. So I conclude that the statement is True.  Yet in my answer scheme, it says False.
Can someone clarify my mistake?
Thank you.
Comment: If $E_i$ is finite then there is **no** injection from $\Bbb N$ into $E_i$.
Comment: Cantor's [diagonal argument](http://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument) shows that infinite products **are not** countable!
Comment: So I have the right reasoning but made the wrong conclusion simply?
Answer: Let $\{0,1\}=E_1=E_2=\cdots$ Then $E$ is simply the set of all sequences of zeros and ones. Suppose the set were countable and $e_1,e_2,e_3,\ldots$ an enumeration. Then the sequence $(d_n)$ given by $d_n=1-e_n(n)$ differs from each element in the sequence $e_1,e_2,e_3,\ldots$. So $E$ can't be countable. This is simply the Cantor diagonal argument.
Comment: @CAF What you wrote can be done in a similar way cannot be done. If you try to fill in the details, you will see that. There is always a functionf from $\mathbb{N}$ to a finite nonempty set. But a 1-1-function maps different elements to different elements, and this would require the function to take on infinitely many values.
Comment: When I said Cantor's diagonal argument, I meant the 'array' method used to show that the rationals are countable.  What is the mistake in my answer?
Comment: @CAF "The Cartesian Product of infinitely many $E_j$ can be counted in a similar way to Cantor's Diagonal Argument." is simply not true. Try to write out what "similar way" is supposed to mean. Btw: There is a surjection from $\mathbb{N}$ to $E_j$, but no 1-1-function.
Comment: Yes, sorry, I reliased that.  What I meant to say was they can be counted via the same way as was used to show that the rationals are countable (e.g using arrows in a grid like structure).  Doesn't a finite set $E$ imply there exists a function from $\mathbb{N} \rightarrow E$?
Comment: I see. It makes sense.  How does it conform with my defintion in my book:  Let $E$ be a set.  $E$ is said to be finite if and only if either $E = \emptyset$ or there exists a $1-1$ function which takes $\left\{1,2,...n\right\}$ onto $E$, for some $n \in \mathbb{N}$.  Is it because here we restict $n$ to some value within $\mathbb{N}$?
Comment: @CAF Exactly. If you do not restrict the set, you have to map lots of numbers to the same element.
Comment: Ok, thanks.  In your answer, what are the $e_i$?
Comment: @CAF They are the elements of $E$. I assume he elements in $E$ can be ordered in asequence (so they are countable) and then show that I can fin an element not in this sequence. This contradiction proves that $E$ is not countable.
Comment: That is what I thought but then how does $1-e_i$ make sense?  (Since an element of $E$ is of the form $(x_1,x_2...)$ where each $x_i = 0,1$.  Thanks.
Comment: @CAF You are right, it should be $d_n=1-e_n(n)$. I've changed it.


How do I populate a SharePoint list with data from an external SQL database?

Question: This is a tossup between whether it belongs on Stack Overflow or Server Fault (but since I am not a developer, and am looking for a no-code solution, I'm starting with SF).
Is there an easy way to populate a SharePoint list with data from an external SQL database?  In SharePoint designer, it is a simple matter to create a connection to a SQL database for using the data view web part, but I need the data from a SQL table to populate a SharePoint list.  Is there a no-code way to do so?
Edit: Although there are certainly ways of exporting data from the SQL table and importing it into my list, I am looking to have the connection be live so that a column in my SharePoint list is always up-to-date with a master data source stored in a different SQL database.
Answer: Another option that you can look into is the Business Data Catalog. While this is more complicated it does allow you to have a SharePoint view of the data. The downside to this is that it does require the Enterprise edition and pretty advanced skills to get the BDC configured to point to your custom database.
Since you said you are not a developer, I would tend to lead away from the BDC unless you are able to hire someone to configure this for you.
Comment: I am not a programmer. I have done this. It is not easy, nor is it fun.
After a good long while I was able to populate data from our MSCRM into a sharepoint list. I used the Meta-man, it's a good tool, as it the Microsoft BDC software. It takes a while to get everything in order.
Comment: Thanks Aaron-

I think that is my only real choice.  It looks like there are some good tools to generate the BDC application definition file, namely Lightning Tool's BDC Meta Man (http://www.lightningtools.com/bdc-meta-man/default.aspx) or Simego's BDC Design Studio (http://www.simego.com/products/MOSS-BDC-Design-Studio).  I think I'll start with the MOSS SDK (the price is right) which comes with the Microsoft Business Data Catalog Definition Editor and some sample BDC connection files.  We'll see if it's simple enough for an admin to figure out ;)
Answer: I would think you could:

Create an Excel spreadsheet that has the SQL query to the database
Execute the query and do a Copy Values copy in Excel and paste that to a new workbook
Import that workbook when creating the Sharepoint list

For displaying data live using a query, you need the Sharepoint Designer and you add a Data View to the list.  See:
http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
Comment: Thanks Kevin-

That would certainly work for a one-time population, but the reason I am doing this is to keep a column in my list always synced with an external master data source.  I will update my question to reflect that :)
Comment: I added a link that should guide you through adding a Data View to your Sharepoint list.  Should work also in WSS or MOSS
Answer: I took some time investigating this.  In SP 2010 it is easy to import a table as an EXTERNAL SharePoint list.  The data in the db and the list and is syncronized dynamically when someone modifies the table in the DB or the List in SP.
But trying to create a workflow that writes data to and external SharePoint list...well you can do it but it involves a convoluted process that utilizes DB triggers and SQL CLR Assembly Stub.
See:  http://blogs.msdn.com/b/chaks/archive/2011/05/02/concept-leverage-sharepoint-workflows-with-external-lists-part-1.aspx for information on External Lists ans workflows.
Answer: If specifically wanting to populate info from SQL Server 2008.  You can use SQL Server's Integration Services (SSIS)
http://www.onlinetechblog.com/blog/index.php/2009/07/how-import-data-to-sharepoint-list-using-ssis/


Let $(G,∗,I)$ be a group and let $g \in G$ satisfy $g^{n} = I$ for some odd number n. Prove that there is an $h \in G$ such that $g = h^{2}$.

Question: This was an exam question I was unable to answer. I've been thinking about it for hours now and am still unable to figure out how to approach this problem. Any help will be much appreciated :).
It's been made clear to me that I should note my own efforts so here it is:
We have that $g \in G$ and $g^{n} = I$ where $n$ is an odd number. If there exists a $g = h^{2}$ then $h^{2n} = I$. And this is as far as I got.
Comment: Set $h:=g^{\frac{n+1}2}$.
Comment: Welcome to MSE. Here's [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). It's particularly important that you show your own work and efforts on the problem, otherwise it will be probably downvoted and eventually closed.
Answer: Since $n$ is odd, $\frac{n+1}{2}$ is well defined. Just take $h:=g^{\frac{n+1}{2}}$. So $h^2=g^{n+1}=g^ng=g$, since $g^n=1$
Comment: 1) $n+1$ is even, but not necessarily ${n+1\over 2}$, 2) $g^n=1$ doesn't mean it has *order* $n$ – it could be a divisor of $n$.
Comment: You are right, edited it
Comment: A small nitpick: Technically, the first sentence should read: "Since $n$ is odd, $\frac{n+1}{2}$ is a nonnegative integer and so $g^{\frac{n+1}{2}}$ is well-defined." [Note that $i=\frac{n+1}{2}$ is well-defined for any integer $n$, what we need is for $g^i$ to be well-defined...] But overall your answer is clear.


"IdleStart" function starts again even after timeout. "Angular Js"

Question: I am beginner in angular. I am trying to implement timeout. I display a model if user is idle for more than 5 seconds. When I successfully logout on timeout. This dialog box keeps on appearing. How can I fix this.

This is my configurations.
     IdleProvider.idle(5);
     IdleProvider.timeout(30); // after 30 seconds idle, time the user out
     KeepaliveProvider.interval(5*60);

These are my events:
 $scope.$on('IdleEnd', function() {
      Idle.unwatch();
      $uibModal.close();
    });

    $scope.$on('IdleTimeout', function() {
      Idle.unwatch();
      $scope.SignOut();
      $uibModal.close();
    });

   $scope.$on('IdleStart', function() {
     $scope.warning = $uibModal.open({
      templateUrl: 'warning-dialog.html',
      windowClass: 'modal-danger'
    });
  });

UPDATED
Code of my view:
   ****

In this div

If I remove idle-countdown="countdown" then model does not appear again and logs me out but me side bar keeps showing. I cant figure it out.
Side bar contains menus and drop downs but after login out those menu disapperas but this plain side bar keeps on showing just by removing "idle-countdown"
Comment: can you give us a fiddle or plunker of this...
Comment: Its not possible cause its a lot of code.
Answer: Probably you need to invoke Idle.unwatch(); before signing out.
Comment: where are you invoking `$uibModal.close()`  ? You would need to close the modal so that it disappears.
Comment: $uibModal.close(); I have also added this after Idle End and Idle timeout. did not worked.
Comment: I have an observation so I have updated my question can u please look at it?
Answer:    $scope.$on('IdleEnd', function() {
     $timeout(function() {
                        $scope.$apply(function() {
                                     Idle.unwatch();
                                      $uibModal.close();
                        });
                    }, 100);
       });

Try this one.
Comment: Nop it did not work. Instead not model does not close after logout.
Comment: Please share your demo code at email@example.com


Prevent dialogs appearing in unattended builds

Question: I was wondering is there is a fool-proof way to run a program on windows such that I'm guaranteed that no interactive dialogs of any kind are displayed.
I've tried the registry ErrorMode hack, calling _CrtSetReportMode(), etc., but they all have holes in them or require you to modify the program.
I need a way to run an arbitrary program and practically force Windows to execute them such that there is no possibility for them to open a window. It is perfectly ok for the program to crash if it attempts to open a window.
Would running the program as a service solve the problem?
Answer: I'm not aware of any other ways that might possibly work. Running as a service won't solve the problem either as the dialog will be displayed on the service's desktop, which you generally don't have access to.
Comment: What does that mean? Does the application still wait for the dialog to complete? I can accept that I'm not seeing the dialog (I can always rerun the build manually), as long as the application does not wait for the dialog.
Comment: Even when running a program on the nonvisible service desktop, it will still wait for the nonexistent user to press a nonvisible button to dismiss the dialog box. This is probably not what you want.
Comment: How meaningless. As usual, the lack of design can be seen in every corner of Windows.
Comment: Yes, as Greg mentioned, the application will still wait for a user response which is why running as a service won't solve your problem either.
Answer: You could use a library such as Detours to intercept all calls to functions that might display a dialog box (this might in fact be nearly everything in user32.dll).


Calling exe with input and output file paths matlab

Question: I want to use an exe in matlab in a way that I could also mention input and output path of the input and output files as follows:
file.exe (parameter) (input_file_path) (output_file_path)
The above line shows how I write my command in DOS prompt.
Mushi
Answer: You can use system command to achieve this.
system(['file.exe ' parameter ' ' input_file_path ' ' output_file_path ]);

If arguments are fixed you can simply run
>>!file.exe parameter input_file_path output_file_path

Comment: I found it like this --> system(['file.exe parameter ' input_file_path ' ' output_file_path]);. Anyway, it worked perfectly. Thanks a loads.


How do I use this code?

Question: I have this code, but I don't know how to wrap it in Drupal.
<code>$(document).scroll(function () {

  var y = $(this).scrollTop();
  if (y > 100) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }

});
</code>
I've already activated the .js file and added the detail in .info, I can see it from the firebug that is OK, but from the Firebug console I can see that I have syntax errors.
From Drupal website I can see this example.
<code>(function ($) { // Here code javascript })(jQuery);
</code>
Can someone show me how the code above should look like into Drupal? Thanks.
Answer: Here you go:
<code>(function($) {
  Drupal.behaviors.yourCustomName = {
    attach: function (context, settings) {

      $(document, context).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 100) {
          $('.bottomMenu').fadeIn();
        } else {
          $('.bottomMenu').fadeOut();
        }
      });

    }
  };
})(jQuery);
</code>
Be sure to read the docs.
Comment: You should always use jQuery once to avoid re-attaching behavior to the same element. And yes, something behaviors are attached multiple time using the root element (ie. document) as context.
See https://coderwall.com/p/kd-4cg for a bit more information on JavaScript in Drupal 7.
Comment: @PierreBuyle *always* is a bit strong word here. In this case, only on first page load document should be in context. But good hint anyway :)
Comment: There is no guarantee that only the page load will apply the behaviors to a context containing the document element. So you can't assume it will never happen. Unless you are ready to review all JavaScript files from all the added modules.

How do I use this code?


byte[] encodeBase64(byte[] binaryData) equvalent in c#

Question: In Java, Apache provides a encoding library namely apache-commons and there is a method that's signiture is
byte[] encodeBase64(byte[] binaryData)

In C#, we try to do the same thing. however, we couldn't find any library or method like this. How we can encode our byte array to Base64 byte array?
Answer: You can leverage the Convert.ToBase64String method. This will however not return a byte[] but a string type. To get it in bytes, you will have to perform a text encoding.
string base64 = Convert.ToBase64String(binaryData);
byte[] base64bytes = System.Text.Encoding.ASCII.GetBytes(base64);

Comment: I only have byte array and i don't want to use string type in this operation. Additionally, none of encoding types(UTF8, ASCII) work while i trying to encode to base64.
Comment: IIRC, encoding to base 64 is _essentially_ like encoding to an ASCII string anyway. If this isn't working for you, can you post the code that you've tried and how the output isn't what you expect or need?
Comment: var byteArray = Encoding.ASCII.GetBytes(Convert.ToBase64String(byteArray));

This one doesn't work.
Comment: How does it "not work"? Does it throw an error? Does it give you incorrect byte data? (Also, what you posted won't compile; you're redeclaring the `byteArray` while trying to use it in the same line)


Why do I get different results after shuffling data using DBSCAN

Question: Sometimes, by simply shuffling my data, not changing the parameters, I get a different cluster result using sklearn.DBSCAN. Why this happens?
I mean, by shuffling data, the data distribution is the same, so I should get the same result. Is this related to the implementation of DBSCAN algorithm, or internal mechanism? Thanks.
Answer: DBSCAN is not entirely deterministic, because the order in which the data are processed can change DBSCAN results. From wikipedia:

From wikipedia: "DBSCAN is not entirely deterministic: border points that are reachable from more than one cluster can be part of either cluster, depending on the order the data are processed. For most data sets and domains, this situation does not arise often and has little impact on the clustering result:[4] both on core points and noise points, DBSCAN is deterministic. DBSCAN*[8] is a variation that treats border points as noise, and this way achieves a fully deterministic result as well as a more consistent statistical interpretation of density-connected components."

Erich Schubert, Jörg Sander, Martin Ester, Hans Peter Kriegel, and Xiaowei Xu. 2017. DBSCAN Revisited, Revisited: Why and How You Should (Still) Use DBSCAN. ACM Trans. Database Syst. 42, 3, Article 19 (September 2017), 21 pages. https://doi.org/10.1145/3068335
Campello, Ricardo J. G. B.; Moulavi, Davoud; Zimek, Arthur; Sander, Jörg (2015). "Hierarchical Density Estimates for Data Clustering, Visualization, and Outlier Detection". ACM Transactions on Knowledge Discovery from Data. 10 (1): 1–51
Closely related: Why is DBSCAN deterministic?


Widget confirmação de ação é possível?

Question: Tenho que colocar um AlertDialog para confirmar se o usuário quer mesmo realizar determinada ação, é simples fazer isso em uma activity ou fragment só que estou com problemas para fazer isso no widget, tentei fazer mas só estou obtendo erros como retorno.
Tenho o seguinte código:
<code>  AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Alert message to be shown");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();
</code>
Que me retorna o seguinte erro:

java.lang.RuntimeException: Unable to start receiver
android.view.WindowManager$BadTokenException: Unable to add window --
  token null is not for an application
Caused by: android.view.WindowManager$BadTokenException: Unable to add
  window -- token null is not for an application
Answer: Achei a solução para o meu problema a todos que tiverem o msm problema aqui esta a solução.

Widget confirmação de ação é possível?