qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
while all the listed solutions are valid, in my case, what what causing my multiple form submission was the e i was passing to the function called on submit. i had ``` $('form').bind('submit', function(e){ e.preventDefault() return false }) ``` but i changed it to ``` $('form').bind('submit', function(){ event.preventDefault() return false; }) ``` and this worked for me. not including the return false should still not stop the code from working though
As you are using AJAX request to send data to the server there's no reason even to use `form` tag and `<input type="submit" .../>` (you can use simple button instead). Also I think Cumbo's answer should work. If it doesn't you can also try `event.stopPropagation()`.
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
while all the listed solutions are valid, in my case, what what causing my multiple form submission was the e i was passing to the function called on submit. i had ``` $('form').bind('submit', function(e){ e.preventDefault() return false }) ``` but i changed it to ``` $('form').bind('submit', function(){ event.preventDefault() return false; }) ``` and this worked for me. not including the return false should still not stop the code from working though
Underneath your click function, add a `preventDefault()` to the event. ``` $("#addpayment_submit").click(function(event) { event.preventDefault(); // Code here return false; }); ``` This may solve your problem. `preventDeafult()` stops the default event from triggering. In this case, your form is triggering when clicked on, then triggering again when you send it using your ajax function. It also helps to add `return false;` at the end of the click function (see above).
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
Try adding the following lines. ``` event.preventDefault(); event.stopImmediatePropagation(); ``` This worked for me.
I ended up changing the script upon the recommendations of @user2247104 unfortunately the form still submitted twice. However @Cumbo, @Barmar were also on the right track, except that to get it to work `event.preventDefault();` Needed to be placed at the bottom of the script: ``` }); event.preventDefault(); return false; ``` Thanks to all for their help :)
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
while all the listed solutions are valid, in my case, what what causing my multiple form submission was the e i was passing to the function called on submit. i had ``` $('form').bind('submit', function(e){ e.preventDefault() return false }) ``` but i changed it to ``` $('form').bind('submit', function(){ event.preventDefault() return false; }) ``` and this worked for me. not including the return false should still not stop the code from working though
I ended up changing the script upon the recommendations of @user2247104 unfortunately the form still submitted twice. However @Cumbo, @Barmar were also on the right track, except that to get it to work `event.preventDefault();` Needed to be placed at the bottom of the script: ``` }); event.preventDefault(); return false; ``` Thanks to all for their help :)
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
Some times you have to not only prevent the default behauviour for handling the event, but also to prevent executing any downstream chain of event handlers. This can be done by calling [`event.stopImmediatePropagation()`](https://api.jquery.com/event.stopimmediatepropagation/) in addition to [`event.preventDefault()`](https://api.jquery.com/event.preventDefault/). Example code: ``` $("#addpayment_submit").on('submit', function(event) { event.preventDefault(); event.stopImmediatePropagation(); }); ```
Try adding the following lines. ``` event.preventDefault(); event.stopImmediatePropagation(); ``` This worked for me.
15,823,756
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance. Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once. The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem. jQuery Code: ``` $(document).ready(function(){ $('.form_error').hide(); $('a.launch-1').click(function() { var launcher = $(this).attr('id'), launcher = launcher.split('_'); launcher, launcher[1], $('td .'+launcher[1]); $('.'+launcher[1]).each(function(){ var field = $(this).attr('data-name'), fieldValue = $(this).html(); if(field === 'InvoiceID'){ $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() { $("#previouspaymentsloader").hide(); }); } else if(field === 'InvoiceNumber'){ $("#addinvoicenum").html(fieldValue); } $('#'+field).val(fieldValue); }); }); $("#addpayment_submit").click(function(event) { $('.form_error').hide(); var amount = $("input#amount").val(); if (amount == "") { $("#amount_error").show(); $("input#amount").focus(); return false; } date = $("input#date").val(); if (date == "") { $("#date_error").show(); $("input#date").focus(); return false; } credit = $("input#credit").val(); invoiceID = $("input#InvoiceID").val(); by = $("input#by").val(); dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by; $.ajax({ type: "POST", url: "functions/invoicing_payments_make.php", data: dataString, success: function(result) { if(result == 1){ $('#payment_window_message_success').fadeIn(300); $('#payment_window_message_success').delay(5000).fadeOut(700); return false; } else { $('#payment_window_message_error_mes').html(result); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); return false; } }, error: function() { $('#payment_window_message_error_mes').html("An error occured, form was not submitted"); $('#payment_window_message_error').fadeIn(300); $('#payment_window_message_error').delay(5000).fadeOut(700); } }); return false; }); }); ``` Here is the html form: ``` <div id="makepayment_form"> <form name="payment" id="payment" class="halfboxform"> <input type="hidden" name="InvoiceID" id="InvoiceID" /> <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" /> <fieldset> <label for="amount" class="label">Amount:</label> <input type="text" id="amount" name="amount" value="0.00" /> <p class="form_error clearb red input" id="amount_error">This field is required.</p> <label for="credit" class="label">Credit:</label> <input type="text" id="credit" name="credit" /> <label for="amount" class="label">Date:</label> <input type="text" id="date" name="date" /> <p class="form_error clearb red input" id="date_error">This field is required.</p> </fieldset> <input type="submit" class="submit" value="Add Payment" id="addpayment_submit"> </form> </div> ``` Hope someone can help as its driving me crazy. Thanks.
2013/04/04
[ "https://Stackoverflow.com/questions/15823756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513473/" ]
Also, you're binding the action to the submit button 'click'. But, what if the user presses 'enter' while typing in a text field and triggers the default form action? Your function won't run. I would change this: ``` $("#addpayment_submit").click(function(event) { event.preventDefault(); //code } ``` to this: ``` $("#payment").bind('submit', function(event) { event.preventDefault(); //code } ``` Now it doesn't matter **how** the user submits the form, because you're going to capture it no matter what.
As you are using AJAX request to send data to the server there's no reason even to use `form` tag and `<input type="submit" .../>` (you can use simple button instead). Also I think Cumbo's answer should work. If it doesn't you can also try `event.stopPropagation()`.
311,206
In the below config I want to remove the body field from **content** and add it in **hidden** as **body: true** when I uninstall the layout module. *Basically when I install the layout module the fields in manage display should get disabled/hidden and when I uninstall the module the fields should be displayed.* How can I achieve this programatically? This config code is of `entity_view_display.node.article.default` ``` uuid: eedc35e4-0592-4f1a-bdc6-47dbf60fa929 langcode: en status: true dependencies: config: - field.field.node.article.body - field.field.node.article.comment - field.field.node.article.field_image - field.field.node.article.field_media - field.field.node.article.field_sample_text - field.field.node.article.field_tags - node.type.article module: - layout_builder - text - user third_party_settings: layout_builder: enabled: false allow_custom: false id: node.article.default targetEntityType: node bundle: article mode: default content: body: type: text_default label: above settings: { } third_party_settings: { } weight: 0 region: content hidden: comment: true field_image: true field_media: true field_sample_text: true field_tags: true langcode: true links: true search_api_excerpt: true ```
2022/05/18
[ "https://drupal.stackexchange.com/questions/311206", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/106781/" ]
I have solved the issue. Instead of `\Drupal::entityTypeManager()` I used ``` $articleDefaultLayout = LayoutBuilderEntityViewDisplay::load( 'node.article.default' ); $articleDefaultLayout->setComponent('body'); ```
To disable the body field when you install the custom module: *mymodule.install* ``` /** * Implements hook_install(). */ function mymodule_install() { \Drupal::entityTypeManager() ->getStorage('entity_view_display') ->load('node.article.default') ->removeComponent('body') ->save(); } ``` How to enable the field see [8 - How do i programmatically enable a user field under manage form display and manage display?](https://drupal.stackexchange.com/questions/224686/8-how-do-i-programmatically-enable-a-user-field-under-manage-form-display-and)
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
You don't need to filter for each event at a time. `dplyr` is able to process all rows at once, one by one. Also when using `dplyr`, you don't need to assign to a variable outside of its context, such as `data$average <- (something)`. You can use `mutate()`. So the intuitive syntax for `dplyr` would be: ``` data <- data %>% mutate(average = mean(c(R1, R2, R3, R4), na.rm = TRUE)) ```
You can use `rowMeans` to calculate means for each row of a dataframe. Specify in the input which columns you want to include. To ignore the `NA` set `na.rm=TRUE`. ``` data$Average <- rowMeans(data[,c("R1", "R2", "R3", "R4")], na.rm=TRUE) ``` If you had lots of columns to average and didn't want to type them all out, you could use `grep` to match the names of `data` to any pattern. Say for example you want to average all the rows containing an "R" in their name: ``` data$Average <- rowMeans(data[,grep("R",names(data))], na.rm=TRUE) ```
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
You don't need to filter for each event at a time. `dplyr` is able to process all rows at once, one by one. Also when using `dplyr`, you don't need to assign to a variable outside of its context, such as `data$average <- (something)`. You can use `mutate()`. So the intuitive syntax for `dplyr` would be: ``` data <- data %>% mutate(average = mean(c(R1, R2, R3, R4), na.rm = TRUE)) ```
Just to complete all previous answers, if you have multiple values named `R1`, `R2`, .... `R100`, instead of writing all of them into the `mean` function, you could be interested by reshaping your dataframe into a longer format using `pivot_longer` function and then group by Event and calculate the mean. Finally, using `pivot_wider`, you could get your dataframe into the initial wider format. ```r library(dplyr) library(tidyr) df %>% mutate_at(vars(contains("R")), as.numeric) %>% pivot_longer(cols = starts_with("R"), names_to = "R", values_to = "Values") %>% group_by(Event) %>% mutate(average = mean(Values, na.rm = TRUE)) %>% pivot_wider(names_from = R, values_from = Values) # A tibble: 2 x 8 # Groups: Event [2] Subject Event Average average R1 R2 R3 R4 <int> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 A 2.5 1.67 1 2 2 NA 2 1 B 1 1 1 1 1 1 ``` As mentioned by @TTS, there is something wrong in your calculation of the average of the event A. **Reproducible example** ```r structure(list(Subject = c(1L, 1L), Event = c("A", "B"), R1 = c(1L, 1L), R2 = 2:1, R3 = 2:1, R4 = c("N/A", "1"), Average = c(2.5, 1)), row.names = c(NA, -2L), class = c("data.table", "data.frame" ), .internal.selfref = <pointer: 0x5555743c1310>) ```
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
The following doesn't include the NA value as part of the mean calculation (*na.rm=TRUE*). Also, I think grouping by Event is important. When run without group\_by, the calculations combine all events and the resulting value is 1.285714 (=9/7 obs). ``` data <- data.frame( Subject=c(1,1), Event=c('A', 'B'), R1=c(1,1), R2=c(2,1), R3=c(2,1), R4=c(NA,1) ) df <- data %>% group_by(Event) %>% mutate(Average = mean(c(R1,R2,R3,R4), na.rm=TRUE)) ``` Output: ``` Subject Event R1 R2 R3 R4 Average <dbl> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 A 1 2 2 NA 1.67 2 1 B 1 1 1 1 1 ```
You can use `rowMeans` to calculate means for each row of a dataframe. Specify in the input which columns you want to include. To ignore the `NA` set `na.rm=TRUE`. ``` data$Average <- rowMeans(data[,c("R1", "R2", "R3", "R4")], na.rm=TRUE) ``` If you had lots of columns to average and didn't want to type them all out, you could use `grep` to match the names of `data` to any pattern. Say for example you want to average all the rows containing an "R" in their name: ``` data$Average <- rowMeans(data[,grep("R",names(data))], na.rm=TRUE) ```
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
The following doesn't include the NA value as part of the mean calculation (*na.rm=TRUE*). Also, I think grouping by Event is important. When run without group\_by, the calculations combine all events and the resulting value is 1.285714 (=9/7 obs). ``` data <- data.frame( Subject=c(1,1), Event=c('A', 'B'), R1=c(1,1), R2=c(2,1), R3=c(2,1), R4=c(NA,1) ) df <- data %>% group_by(Event) %>% mutate(Average = mean(c(R1,R2,R3,R4), na.rm=TRUE)) ``` Output: ``` Subject Event R1 R2 R3 R4 Average <dbl> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 A 1 2 2 NA 1.67 2 1 B 1 1 1 1 1 ```
Just to complete all previous answers, if you have multiple values named `R1`, `R2`, .... `R100`, instead of writing all of them into the `mean` function, you could be interested by reshaping your dataframe into a longer format using `pivot_longer` function and then group by Event and calculate the mean. Finally, using `pivot_wider`, you could get your dataframe into the initial wider format. ```r library(dplyr) library(tidyr) df %>% mutate_at(vars(contains("R")), as.numeric) %>% pivot_longer(cols = starts_with("R"), names_to = "R", values_to = "Values") %>% group_by(Event) %>% mutate(average = mean(Values, na.rm = TRUE)) %>% pivot_wider(names_from = R, values_from = Values) # A tibble: 2 x 8 # Groups: Event [2] Subject Event Average average R1 R2 R3 R4 <int> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 A 2.5 1.67 1 2 2 NA 2 1 B 1 1 1 1 1 1 ``` As mentioned by @TTS, there is something wrong in your calculation of the average of the event A. **Reproducible example** ```r structure(list(Subject = c(1L, 1L), Event = c("A", "B"), R1 = c(1L, 1L), R2 = 2:1, R3 = 2:1, R4 = c("N/A", "1"), Average = c(2.5, 1)), row.names = c(NA, -2L), class = c("data.table", "data.frame" ), .internal.selfref = <pointer: 0x5555743c1310>) ```
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
You can use `rowMeans` to calculate means for each row of a dataframe. Specify in the input which columns you want to include. To ignore the `NA` set `na.rm=TRUE`. ``` data$Average <- rowMeans(data[,c("R1", "R2", "R3", "R4")], na.rm=TRUE) ``` If you had lots of columns to average and didn't want to type them all out, you could use `grep` to match the names of `data` to any pattern. Say for example you want to average all the rows containing an "R" in their name: ``` data$Average <- rowMeans(data[,grep("R",names(data))], na.rm=TRUE) ```
Just to complete all previous answers, if you have multiple values named `R1`, `R2`, .... `R100`, instead of writing all of them into the `mean` function, you could be interested by reshaping your dataframe into a longer format using `pivot_longer` function and then group by Event and calculate the mean. Finally, using `pivot_wider`, you could get your dataframe into the initial wider format. ```r library(dplyr) library(tidyr) df %>% mutate_at(vars(contains("R")), as.numeric) %>% pivot_longer(cols = starts_with("R"), names_to = "R", values_to = "Values") %>% group_by(Event) %>% mutate(average = mean(Values, na.rm = TRUE)) %>% pivot_wider(names_from = R, values_from = Values) # A tibble: 2 x 8 # Groups: Event [2] Subject Event Average average R1 R2 R3 R4 <int> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 A 2.5 1.67 1 2 2 NA 2 1 B 1 1 1 1 1 1 ``` As mentioned by @TTS, there is something wrong in your calculation of the average of the event A. **Reproducible example** ```r structure(list(Subject = c(1L, 1L), Event = c("A", "B"), R1 = c(1L, 1L), R2 = 2:1, R3 = 2:1, R4 = c("N/A", "1"), Average = c(2.5, 1)), row.names = c(NA, -2L), class = c("data.table", "data.frame" ), .internal.selfref = <pointer: 0x5555743c1310>) ```
10,367,957
I have noticed a high memory and CPU usage during mvn-gwt operation especially during compile phase. Memory usage just soars. I just wanna know if this is normal and if anyone else is experiencing this. My current JVM setting is `-Xms64m -Xmx1280m -XX:MaxPermSize=512m` ![Memory usage during GWT Compile](https://i.stack.imgur.com/KGqCy.png)
2012/04/28
[ "https://Stackoverflow.com/questions/10367957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680915/" ]
I think it's normal. Because the phase of compilation in GWT is really very resource-intensive. GWT provides a larger library (in gwt-user.jar) that must be analyzed during compilation and a number of compiler optimizations that require much memory and processing power. Thus, the GWT compiler use much memory internally.
Yes, it's normal. It derives from the awsome CPU utilization Google made when they've written the gwtc command (gwtc = GWT Compile). I consider it good since the tradeoff for the CPU would typically be memory usage which is far more valuable for me. (I do not work for Google :-))
10,367,957
I have noticed a high memory and CPU usage during mvn-gwt operation especially during compile phase. Memory usage just soars. I just wanna know if this is normal and if anyone else is experiencing this. My current JVM setting is `-Xms64m -Xmx1280m -XX:MaxPermSize=512m` ![Memory usage during GWT Compile](https://i.stack.imgur.com/KGqCy.png)
2012/04/28
[ "https://Stackoverflow.com/questions/10367957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680915/" ]
I think it's normal. Because the phase of compilation in GWT is really very resource-intensive. GWT provides a larger library (in gwt-user.jar) that must be analyzed during compilation and a number of compiler optimizations that require much memory and processing power. Thus, the GWT compiler use much memory internally.
The GWT compiler has a localWorkers setting that tells it how many cores to use. The more cores, the more memory it will use. If you are using the Eclipse plugin it defaults to just using one (I believe). But the Maven plugin defaults to using all core on your machine (ie if you have a quad core, it will use `localWorkers 5`. Interestingly I've been following the advice found here: <http://josephmarques.wordpress.com/2010/07/30/gwt-compilation-performance/> which says that `localWorkers 2` is an ideal setting for memory usage and speed. That way my machine doesn't lock up during the compile, and the speed difference is very minor.
43,590
I'm planning to travel from Osaka to Tokyo and back, and since the ride will be long, I think it's the perfect time to make friends. However, I'm unsure how the Japanese see this kind of behaviour - a stranger suddenly conversing with them who is a foreigner. Is it considered rude? Is it a case-to-case basis? --- Additional info : I can speak Japanese. I've been studying it for a year. I am at a conversational level but still not as good as locals and I may not know some words they might throw at me.
2015/02/20
[ "https://travel.stackexchange.com/questions/43590", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/18310/" ]
I haven't found Japanese as chatty as Europeans or Americans, but there are some friendly people who would want to chat with a foreigner. You won't know until you try. Old ladies and people with families tend to be the most chattiest -- young women and businessmen tend to be the least. There's a stereotype (that I've found to be true) that folks from Osaka tend to be much friendlier than those from Tokyo. You should be aware that it's only 2 hours on the Shinkansen, which in Japan is not considered a very long train ride (some people have daily 2 hour train ride commutes). But still, you might strike up a conversation. I'd suggest riding in the regular car (not Green Car), maybe taking the Hikari instead of the Nozomi, and asking to get your seat in the non-reserved section so you can deliberately sit near someone who looks friendly.
It is not rude as such, but unusual for strangers to talk on the shinkansen except to ask something specific like if it's okay to recline the seat (asked to the person sitting behind you.) Usually it's very quiet in there except for groups travelling together. I live and work in Tokyo and take the shinkansen to and from Osaka about once a month. I am a visibly white woman but I don't have the usual apparel or luggage of a foreign tourist. People take the shinkansen for the same reasons as a domestic plane flight. Some people are using it to take a fun and rare trip, others are commuting, some are going to weddings or funerals. It's my perception that most lone riders do not expect to talk with anyone, with the majority putting up some sort of barrier to conversation such as putting headphones on or closing their eyes. It would be rude to disrupt these people after they have already put up that barrier. Otherwise, there is no harm in trying to talk to your seatmate, but I would test the waters first by saying hello and smiling when you sit down, then seeing whether they greet you back, just smile, or not even make eye contact. Perhaps you could then ask them a question that gives them a chance to help you out. You could ask them which side of the train Mt. Fuji will appear on. How they answer will give you a clue if they want to talk more, and you can go from there. I have ONCE in six years had a person sitting next to me spontaneously talk to me and we ended up productively chatting about where we are from, our jobs etc. for the whole trip back to Tokyo. He was a bubbly Osakan in line with the stereotype, and I felt he wasn't trying to pick me up but was just curious and wanted to fill the time. This was on the way back from the Obon summer holiday. He even gave me one of his many boxes of Horai pork buns as a thank you -- I guess he felt he could part with one. So you never know!
68,336,320
I'm currently trying to write a simple C#-WPF-Application that functions as a simple universal 'launcher'. For different applications we program. It's purpose is to check the current software version of the 'real' software and if a new one is available it starts to copy the installer from a network share and runs the installer afterwards. Then it starts the 'real' application and thats it. The user Interface mainly consists of a startup window which shows the user the currently executed action (version check, copy, installation, startup, ...). Now I create my view and my viewModel in the overridden StartUp method in App.cs ``` public override OnStartup(string[] args) { var viewModel = new StartViewModel(); var view = new StartView(); view.DataContext = viewModel; view.Show(); // HERE the logic for the Launch starts Task.Run(() => Launch.Run(args)); } ``` The problem is that if I don't go async here the Main Thread is blocked and I cannot update the UI. Therefore I got it working by using the `Task.Run(...)`. This solves my problem of blocking the UI thread, but I have some problems/questions with this: 1. I cannot await the task, because that would block the UI again. Where to await it? 2. Is my concept of starting this workflow here ok in the first place? --- Some update to clarify: After I show the UI to the user my logic starts to do heavy IO stuff. The possible calls I came up with are the following 3 variants: ``` view.Show(); // v1: completely blocks the UI, exceptions are caught DoHeavyIOWork(); // v2: doesn't block the UI, but exceptions aren't caught Task.Run(() => DoHeavyIOWork()); // v3: doesn't block the UI, exceptions are caught await Task.Run(() => DoHeavyIOWork()); ``` Currently I'm not at my work PC so i apologies for not giving you the original code. This is an on the fly created version. I guess v1 and v2 are bad because of exceptions and the UI blocking. I thought v3 didn't work when I tried it in my office. Now it seems to work in my local example. But I'm really not sure about v3. Because I'm using `async void StartUp(...)` there. Is it okay here?
2021/07/11
[ "https://Stackoverflow.com/questions/68336320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12165174/" ]
> > I cannot await the task, because that would block the UI again. Where to await it? > > > `await` doesn't block the UI. Using `await` here is fine. > > Is my concept of starting this workflow here ok in the first place? > > > I usually recommend that *some* UI is shown immediately when doing any asynchronous operation. Then when the async operation is complete, you can update/replace the UI.
Thanks for all the replys. After reading all your comments and combining some of your answers I came up with the following example. It is working under all circumstances I tested. Hopefully there is not to much wrong in your opinion. **Code behind from App.xaml.cs** ```cs public partial class App : Application { readonly StartViewModel viewModel = new StartViewModel(); protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); var view = new StartWindow { DataContext = viewModel }; view.Show(); // alternative: Run(view); // alternative: instead of calling it here it is possible // to move these calls as callback into the Loaded of the view. await Task.Run(() => DoHeavyIOWork()); } private string GenerateContent() { var content = new StringBuilder(1024 * 1024 * 100); // Just an example. for (var i = 0; i < 1024 * 1024 * 2; i++) content.Append("01234567890123456789012345678901234567890123456789"); return content.ToString(); } private void DoHeavyIOWork() { var file = Path.GetTempFileName(); for (var i = 0; i < 20; i++) { File.WriteAllText(file, GenerateContent()); File.Delete(file); Dispatcher.Invoke(() => viewModel.Info = $"Executed {i} times."); } } } ``` **Code in StartViewModel.cs** ```cs class StartViewModel : INotifyPropertyChanged { private string info; public event PropertyChangedEventHandler PropertyChanged; public string Info { get => info; set { info = value; OnPropertyChanged(); } } private void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ```
36,515,177
So I'm fooling around a bit with Haskell, trying to learn it by myself. I'm trying to solve a certain question where I'm supposed to create a list of random numbers and then sum them up. I have the code to generate them - using `getStdRandom` and `randomR`. Using them both returns a list of `IO Float`: `[IO Float]` Now, when I try to sum up the list using say foldl or foldr, or even trying a simple recursion summation, I get errors and such - to my understanding this is because `IO Float` is a monad, so I need to do some Haskell magic to get it to work. I've been googling around and haven't found something that works. Is there any way to sum up the list? or even convert it into a list of floats so that its easier to work around in other parts of the code?
2016/04/09
[ "https://Stackoverflow.com/questions/36515177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475680/" ]
Note that a list with type `[IO Float]` is **not** a list of numbers. It is a list of I/O actions that *generate* numbers. The I/O wasn't executed yet, so in your case the random number generator hasn't actually generated the numbers. You can use the [`sequence :: Monad m => [m a] -> m [a]`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:sequence) function to combine the list of IO actions into a single IO action that provides a list of results: ``` do the_numbers <- sequence your_list return $ sum the_numbers ``` Alternatively you could use the [`foldM`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Control-Monad.html#v:foldM) function to write a monadic fold: ``` sumIONumbers :: [IO Float] -> IO Float sumIONumbers xs = foldM f 0.0 xs where f acc mVal = do val <- mVal -- extract the Float from the IO return $ acc + val ``` --- As noted in the comments you can also make use of the fact that every `Monad` is also a `Functor` (this is enforced in newer versions) and thus you can use [`fmap :: Functor f => (a -> b) -> f a -> f b`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:fmap) to apply a function inside the IO: ``` fmap sum (sequence your_list) ``` Or use the infix synonym [`<$>`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:-60--36--62-): ``` sum <$> sequence your_list ```
How about something like the following using liftM: ``` import System.Random import Control.Monad rnd :: IO Float rnd = getStdRandom (randomR (0.0,1.0)) main = do let l = map (\_ -> rnd) [1..10] n <- foldl (liftM2 (+)) (return (0 :: Float)) l print n ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
If your file contains empty lines, neither of the posted solutions will work. For correct handling of empty lines try this: ``` $ cat f.awk BEGIN{getline;min=max=$6} NF{ max=(max>$6)?max:$6 min=(min>$6)?$6:min } END{print min,max} ``` Then run this command: ``` sed "/^#/d" my_file | awk -f f.awk ``` At first it catches the first line of the file to set min and max. Than for each non-empty line it use the ternary operator check, if a new min or max was found. At the end the result ist printed. HTH Chris
``` awk 'BEGIN {max = 0} {if ($6>max) max=$6} END {print max}' yourfile.txt ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
``` awk 'BEGIN {max = 0} {if ($6>max) max=$6} END {print max}' yourfile.txt ```
Use the `BEGIN` and `END` blocks to initialize and print variables that keep track of the min and max. e.g., ``` awk 'BEGIN{max=0;min=512} { if (max < $1){ max = $1 }; if(min > $1){ min = $1 } } END{ print max, min}' ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
If your file contains empty lines, neither of the posted solutions will work. For correct handling of empty lines try this: ``` $ cat f.awk BEGIN{getline;min=max=$6} NF{ max=(max>$6)?max:$6 min=(min>$6)?$6:min } END{print min,max} ``` Then run this command: ``` sed "/^#/d" my_file | awk -f f.awk ``` At first it catches the first line of the file to set min and max. Than for each non-empty line it use the ternary operator check, if a new min or max was found. At the end the result ist printed. HTH Chris
The min can be found by: ``` awk 'BEGIN {min=1000000; max=0;}; { if($2<min && $2 != "") min = $2; if($2>max && $2 != "") max = $2; } END {print min, max}' file ``` This will output the minimum and maximum, comma-separated
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
If your file contains empty lines, neither of the posted solutions will work. For correct handling of empty lines try this: ``` $ cat f.awk BEGIN{getline;min=max=$6} NF{ max=(max>$6)?max:$6 min=(min>$6)?$6:min } END{print min,max} ``` Then run this command: ``` sed "/^#/d" my_file | awk -f f.awk ``` At first it catches the first line of the file to set min and max. Than for each non-empty line it use the ternary operator check, if a new min or max was found. At the end the result ist printed. HTH Chris
``` awk 'BEGIN{first=1;} {if (first) { max = min = $2; first = 0; next;} if (max < $2) max=$2; if (min > $2) min=$2; } END { print min, max }' file ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
You can create two user defined functions and use them as per your need. This will offer more generic solution. ``` [jaypal:~/Temp] cat file a 212 b 323 c 23 d 45 e 54 f 102 [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} {a[$2]=$2;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' file Maximum = 323 and Minimum = 23 ``` In the above solution, there are 2 user defined functions - `max` and `min`. We store the column 2 in an array. You can store each of your columns like this. In the `END` statement you can invoke the function and store the value in a variable and print it. Hope this helps! **Update:** Executed the following as per the latest example - ``` [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} /^#/{next} {a[$6]=$6;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' sample Maximum = 222 and Minimum = 3.01 ```
``` awk 'BEGIN {max = 0} {if ($6>max) max=$6} END {print max}' yourfile.txt ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
You can create two user defined functions and use them as per your need. This will offer more generic solution. ``` [jaypal:~/Temp] cat file a 212 b 323 c 23 d 45 e 54 f 102 [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} {a[$2]=$2;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' file Maximum = 323 and Minimum = 23 ``` In the above solution, there are 2 user defined functions - `max` and `min`. We store the column 2 in an array. You can store each of your columns like this. In the `END` statement you can invoke the function and store the value in a variable and print it. Hope this helps! **Update:** Executed the following as per the latest example - ``` [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} /^#/{next} {a[$6]=$6;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' sample Maximum = 222 and Minimum = 3.01 ```
Use the `BEGIN` and `END` blocks to initialize and print variables that keep track of the min and max. e.g., ``` awk 'BEGIN{max=0;min=512} { if (max < $1){ max = $1 }; if(min > $1){ min = $1 } } END{ print max, min}' ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
``` awk 'BEGIN {max = 0} {if ($6>max) max=$6} END {print max}' yourfile.txt ```
``` awk 'BEGIN{first=1;} {if (first) { max = min = $2; first = 0; next;} if (max < $2) max=$2; if (min > $2) min=$2; } END { print min, max }' file ```
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
You can create two user defined functions and use them as per your need. This will offer more generic solution. ``` [jaypal:~/Temp] cat file a 212 b 323 c 23 d 45 e 54 f 102 [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} {a[$2]=$2;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' file Maximum = 323 and Minimum = 23 ``` In the above solution, there are 2 user defined functions - `max` and `min`. We store the column 2 in an array. You can store each of your columns like this. In the `END` statement you can invoke the function and store the value in a variable and print it. Hope this helps! **Update:** Executed the following as per the latest example - ``` [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} /^#/{next} {a[$6]=$6;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' sample Maximum = 222 and Minimum = 3.01 ```
If your file contains empty lines, neither of the posted solutions will work. For correct handling of empty lines try this: ``` $ cat f.awk BEGIN{getline;min=max=$6} NF{ max=(max>$6)?max:$6 min=(min>$6)?$6:min } END{print min,max} ``` Then run this command: ``` sed "/^#/d" my_file | awk -f f.awk ``` At first it catches the first line of the file to set min and max. Than for each non-empty line it use the ternary operator check, if a new min or max was found. At the end the result ist printed. HTH Chris
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
``` awk 'BEGIN {max = 0} {if ($6>max) max=$6} END {print max}' yourfile.txt ```
The min can be found by: ``` awk 'BEGIN {min=1000000; max=0;}; { if($2<min && $2 != "") min = $2; if($2>max && $2 != "") max = $2; } END {print min, max}' file ``` This will output the minimum and maximum, comma-separated
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
You can create two user defined functions and use them as per your need. This will offer more generic solution. ``` [jaypal:~/Temp] cat file a 212 b 323 c 23 d 45 e 54 f 102 [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} {a[$2]=$2;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' file Maximum = 323 and Minimum = 23 ``` In the above solution, there are 2 user defined functions - `max` and `min`. We store the column 2 in an array. You can store each of your columns like this. In the `END` statement you can invoke the function and store the value in a variable and print it. Hope this helps! **Update:** Executed the following as per the latest example - ``` [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} /^#/{next} {a[$6]=$6;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' sample Maximum = 222 and Minimum = 3.01 ```
The min can be found by: ``` awk 'BEGIN {min=1000000; max=0;}; { if($2<min && $2 != "") min = $2; if($2>max && $2 != "") max = $2; } END {print min, max}' file ``` This will output the minimum and maximum, comma-separated
3,927
I've been wanting to post on this for some time, but don't want to post something just to have it shut down as a duplicate because it talks about disabilities and someone else has already posted about disabilities. Autism Spectrum has some fairly unique problems specific to the workplace that other disabilities do not, because we seem relatively normal, especially on the high end, but our communication skills and behaviors can cause trouble for us. In short, we can come across as jerks when we don't intend to, and that's something that other disabilities don't have to face. You don't consider someone who is deaf to be rude for not hearing you for example. I would like to pose a question or two asking for advice on how to deal with AS in the workplace, but would like to ensure it's on topic. What is the best way to do so?
2016/09/21
[ "https://workplace.meta.stackexchange.com/questions/3927", "https://workplace.meta.stackexchange.com", "https://workplace.meta.stackexchange.com/users/46894/" ]
I deal with aspbergers as well so please do not think that I am dismissing your needs or concerns. SE is designed around providing answers to questions that will potentially help many people. So when asking any question it is important to make sure that your question is as broadly applicable as possible. If your question is only applicable to your specific situation at a specific point in time then it is better to ask in Chat or elsewhere. But if your situation can be generalized into one that you deal with often or even just a few times chances are that other people deal with that same general situation so your question could be helpful. But make sure when generalizing the question that you do not go so generic that the solutions provided are not useful because they miss important parts. Right now you are probably thinking boy that's a tough ask, and it is. These types of questions can work here but the vast majority of them will either be too broad or too specific. We can save some of them with edits but the more the OP can do to make it a better question in the first place the more helpful the answers are likely to be to them. Second you have to make sure you provide a goal that you want to achieve. "This is my situation, what should I do?" How many hundreds of these have we seen in the last few months. They get closed usually and just as often as not end up with a lot of useless answers. Instead make sure you have a "This is my situation, I want to achieve X, how can I do that given these conditions" question. And make sure that X is in the scope of the workplace. This is not a Q&A about special needs and situations, it is about the workplace. Make sure that the context of the question is clearly in the scope of that. Finally, try to stay out of comment wars. I struggle with this as well. But if an answer is not helpful just down vote it and move on. Questions that generate lots of comments get more attention in a bad way. Questions that are borderline are more likely to get closed if they are controversial than if they just get answers but no comment wars. When the OP of the question gets involved in comment wars I have noticed the questions tend to get closed quickly.
Handling disabilities on workplace is a real matter nowadays, they're laws to enforce that they're provided an adequate environment to work and to not get discriminated. So I can't see why this won't be on-topic as long as it is related to problems that affect the workplace. However I guess that in some specific issues you might have an hard time to get an answer, because not a lof of people on the site will know how exactly to deal with, possibly neither your manager or a RH. Finnaly some people here could ask questions about a coworker being rude when they don't know he's in the AS either because he's didn't check it with a doctor or he won't reveal it. This is probably the hardest part about it. Probably the best answer there would be just for peoples to try to figure out if he meant to be jerk or if he's just like this "naturally", which can be a problem when this look like unprofessional. Having differents answer for two apparent similar problems, when one is caused by an (possibly not known) AS and one is not is really tricky.
3,927
I've been wanting to post on this for some time, but don't want to post something just to have it shut down as a duplicate because it talks about disabilities and someone else has already posted about disabilities. Autism Spectrum has some fairly unique problems specific to the workplace that other disabilities do not, because we seem relatively normal, especially on the high end, but our communication skills and behaviors can cause trouble for us. In short, we can come across as jerks when we don't intend to, and that's something that other disabilities don't have to face. You don't consider someone who is deaf to be rude for not hearing you for example. I would like to pose a question or two asking for advice on how to deal with AS in the workplace, but would like to ensure it's on topic. What is the best way to do so?
2016/09/21
[ "https://workplace.meta.stackexchange.com/questions/3927", "https://workplace.meta.stackexchange.com", "https://workplace.meta.stackexchange.com/users/46894/" ]
Just post the question(s), either we can deal with them or we can't. But there's a host of keen, intelligent and observant people here with a lot of experience in all sorts of things, I reckon someone will be able to answer you. Just not me, because I never even heard of it before coming here except some maths wizard guy in a movie. Who I would hire like a shot and treat like he's made of gold.
Handling disabilities on workplace is a real matter nowadays, they're laws to enforce that they're provided an adequate environment to work and to not get discriminated. So I can't see why this won't be on-topic as long as it is related to problems that affect the workplace. However I guess that in some specific issues you might have an hard time to get an answer, because not a lof of people on the site will know how exactly to deal with, possibly neither your manager or a RH. Finnaly some people here could ask questions about a coworker being rude when they don't know he's in the AS either because he's didn't check it with a doctor or he won't reveal it. This is probably the hardest part about it. Probably the best answer there would be just for peoples to try to figure out if he meant to be jerk or if he's just like this "naturally", which can be a problem when this look like unprofessional. Having differents answer for two apparent similar problems, when one is caused by an (possibly not known) AS and one is not is really tricky.
3,927
I've been wanting to post on this for some time, but don't want to post something just to have it shut down as a duplicate because it talks about disabilities and someone else has already posted about disabilities. Autism Spectrum has some fairly unique problems specific to the workplace that other disabilities do not, because we seem relatively normal, especially on the high end, but our communication skills and behaviors can cause trouble for us. In short, we can come across as jerks when we don't intend to, and that's something that other disabilities don't have to face. You don't consider someone who is deaf to be rude for not hearing you for example. I would like to pose a question or two asking for advice on how to deal with AS in the workplace, but would like to ensure it's on topic. What is the best way to do so?
2016/09/21
[ "https://workplace.meta.stackexchange.com/questions/3927", "https://workplace.meta.stackexchange.com", "https://workplace.meta.stackexchange.com/users/46894/" ]
I deal with aspbergers as well so please do not think that I am dismissing your needs or concerns. SE is designed around providing answers to questions that will potentially help many people. So when asking any question it is important to make sure that your question is as broadly applicable as possible. If your question is only applicable to your specific situation at a specific point in time then it is better to ask in Chat or elsewhere. But if your situation can be generalized into one that you deal with often or even just a few times chances are that other people deal with that same general situation so your question could be helpful. But make sure when generalizing the question that you do not go so generic that the solutions provided are not useful because they miss important parts. Right now you are probably thinking boy that's a tough ask, and it is. These types of questions can work here but the vast majority of them will either be too broad or too specific. We can save some of them with edits but the more the OP can do to make it a better question in the first place the more helpful the answers are likely to be to them. Second you have to make sure you provide a goal that you want to achieve. "This is my situation, what should I do?" How many hundreds of these have we seen in the last few months. They get closed usually and just as often as not end up with a lot of useless answers. Instead make sure you have a "This is my situation, I want to achieve X, how can I do that given these conditions" question. And make sure that X is in the scope of the workplace. This is not a Q&A about special needs and situations, it is about the workplace. Make sure that the context of the question is clearly in the scope of that. Finally, try to stay out of comment wars. I struggle with this as well. But if an answer is not helpful just down vote it and move on. Questions that generate lots of comments get more attention in a bad way. Questions that are borderline are more likely to get closed if they are controversial than if they just get answers but no comment wars. When the OP of the question gets involved in comment wars I have noticed the questions tend to get closed quickly.
Just post the question(s), either we can deal with them or we can't. But there's a host of keen, intelligent and observant people here with a lot of experience in all sorts of things, I reckon someone will be able to answer you. Just not me, because I never even heard of it before coming here except some maths wizard guy in a movie. Who I would hire like a shot and treat like he's made of gold.
16,443,223
I am working n getting the source code of remote page the url of that remote page it got dynamically from the url the user click according to the arrays `array('event_id', 'tv_id', 'tid', 'channel')` : i use the code below to get the who;e page source and it works great. ``` <?php $keys = array('event_id', 'tv_id', 'tid', 'channel'); // order does matter $newurl = 'http://lsh.streamhunter.eu/static/popups/'; foreach ($keys as $key) $newurl.= empty($_REQUEST[$key])?0:$_REQUEST[$key]; $newurl.='.html'; function get_data($newurl) { $ch = curl_init(); $timeout = 5; //$userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.X.Y.Z Safari/525.13."; $userAgent = "IE 7 – Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"; curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch,CURLOPT_URL,$newurl); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $html = get_data($newurl); echo $html ?> ``` the trick here is that i want to echo only line no 59 of the code how to do so?
2013/05/08
[ "https://Stackoverflow.com/questions/16443223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2362208/" ]
The dump from ncdump -k gives the netcdf file format as netCDF-4. I was able to open the file with the `ncdf4` package since ncdf does not seem to be backwards compatible with version 4 files: > > "However, the ncdf package does not provide an interface for netcdf > version 4 files." > > > from the `ncdf4` documentation. ``` library(ncdf4) mycdf <- nc_open(file.choose(), verbose = TRUE, write = FALSE) timedata <- ncvar_get(mycdf,'time') lat <- ncvar_get(mycdf,'latitude') long <- ncvar_get(mycdf,'longitude') harvestdata <- ncvar_get(mycdf,'harvest') str(harvestdata) ``` gives ``` num [1:79, 1:78, 1:32, 1:199] NA NA NA NA NA NA NA NA NA NA ... ```
I think that the harvest maize netcdf file is simply corrupt, or not even a netcdf file (file name does not say anything about the real contents). Try and open it in [NCView](http://meteora.ucsd.edu/~pierce/ncview_home_page.html) or dump using [ncdump](https://www.unidata.ucar.edu/software/netcdf/docs/ncdump-man-1.html), if those tool also fails your file is corrupt or incomplete. In addition, if you want us to help, you need to make your file available.
33,644,839
I am having an issue in Visual Studio 2015 (VB.Net) where the Navigation Bar is not showing. I have set the settings in Tools > Options > Text Editor > All Languages and set the "Navigation Bar" setting to checked. The bar will show up for a second and then disappear. I have tried it in Safe Mode and still the same. I have tried editing the CurrentSettings.vssettings and it shows when you load but again it then disappears. Any Thoughts?
2015/11/11
[ "https://Stackoverflow.com/questions/33644839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549372/" ]
Try this: **uncheck** the checkbox in tools\options\text editor\all languages\general\navigation bar and click OK. This is unintuitive, but then--come back to the same checkbox, which should now be Unchecked, check it, and click OK. This has worked for me. Why the navigation bar disappears randomly is a mystery.
Try Clicking on the Build Menu > Clean Solution then click Build Menu > Rebuild Solution
33,644,839
I am having an issue in Visual Studio 2015 (VB.Net) where the Navigation Bar is not showing. I have set the settings in Tools > Options > Text Editor > All Languages and set the "Navigation Bar" setting to checked. The bar will show up for a second and then disappear. I have tried it in Safe Mode and still the same. I have tried editing the CurrentSettings.vssettings and it shows when you load but again it then disappears. Any Thoughts?
2015/11/11
[ "https://Stackoverflow.com/questions/33644839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549372/" ]
Try this: **uncheck** the checkbox in tools\options\text editor\all languages\general\navigation bar and click OK. This is unintuitive, but then--come back to the same checkbox, which should now be Unchecked, check it, and click OK. This has worked for me. Why the navigation bar disappears randomly is a mystery.
for me such issue happens in the scenario that in one file the navigation bar disappeared but in other files it is still there. my solution is: 1) find the project that the missing navigation bar file located; 2) unload the project(in solution explorer->right click project name->in popup dialog, select unload project). Logically then the file will be closed and the project will be gray; 3) load the project again(in solution explorer->right click project name->in popup dialog, select load project). Then the navigation bar will appear again in this file. Such solution also help for Intelisense doesn't work for some files.
30,350,208
My models CAR BRANDS MODEL ``` class CarBrand < ActiveRecord::Base has_many :car_ads end ``` CAR ADVERTISEMENTS MODEL ``` class CarAd < ActiveRecord::Base has_one :car_brand end ``` my controller: ``` def index @car_ads = CarAd.all.order("car_ads.created_at DESC") end ``` car ads migrations: ``` class CreateCarAds < ActiveRecord::Migration def up create_table :car_ads do |t| t.integer "user_id" t.integer "car_brand_id" t.integer "car_model_id" t.integer "state_id", :limit => 2 t.integer "vin_id" t.integer "year_manufac", :precision => 4 t.integer "km_age" t.integer "price_usd", :limit => 7 t.integer "car_tel_number", :precision => 8 t.float "motor_volume", :limit => 10 t.string "transmission" t.integer "horse_power", :limit => 3 t.text "description" t.boolean "visible", :default => true t.boolean "active", :default => true t.string "photo_file_name" t.string "photo_content_type" t.integer "photo_file_size" t.datetime "photo_updated_at" t.timestamps null: false end add_index :car_ads, :user_id add_index :car_ads, :car_brand_id add_index :car_ads, :car_model_id add_index :car_ads, :state_id add_index :car_ads, :vin_id end def down drop_table :car_ads end end ``` Car brands migratiions ``` class CreateCarBrands < ActiveRecord::Migration def up create_table :car_brands do |t| t.string "brand", :limit => 20 t.timestamps null: false end end def down drop_table :car_brands end end ``` so the problem is that i cant get car brand form car ads, please help, i wanted to get that like iterating ``` <% @car_ads.each do |carad|%> <%= carad.car_brand %> <%end%> ```
2015/05/20
[ "https://Stackoverflow.com/questions/30350208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4666863/" ]
Put `ng-cloak` at your controller definition (or wherever you don't want to see the template rendering... specs recommend placing it in small portions of the page): ``` <div ng-controller="MyCtrl" ng-cloak> ``` <https://docs.angularjs.org/api/ng/directive/ngCloak>
You can also try to work with `ng-bind` instead of `{{}}` in your view. It is always possible, even in your code : ``` <select ng-model="invoice.inCurrency"> <option ng-repeat="c in invoice.currencies" ng-bind="c"></option> </select> ``` Please refer to [this topic](https://stackoverflow.com/questions/16125872/why-ng-bind-is-better-than-in-angular) to see the advantages of `ng-bind`
58,452,256
I recently update my spring boot app 2.1.9 to 2.2.0 and i'm facing a problem. When i'm calling "configprops" from actuator endpoint, an exception is throw : Scope 'job' is not active for the current thread I reproduce the bug : <https://github.com/guillaumeyan/bugspringbatch> (just launch the test). Original project come from <https://github.com/spring-guides/gs-batch-processing/tree/master/complete> I tried to add : ```java @Bean public StepScope stepScope() { final StepScope stepScope = new StepScope(); stepScope.setAutoProxy(true); return stepScope; } ``` but it does not work (with spring.main.allow-bean-definition-overriding=true) Here is my configuration of the spring batch ``` @Bean @JobScope public RepositoryItemReader<DossierEntity> dossierToDiagnosticReader(PagingAndSortingRepository<DossierEntity, Long> dossierJpaRepository, @Value("#{jobParameters[origin]}") String origin) { RepositoryItemReader<DossierEntity> diagnosticDossierReader = new RepositoryItemReader<>(); diagnosticDossierReader.setRepository(dossierJpaRepository); diagnosticDossierReader.setMethodName("listForBatch"); // doing some stuff with origin return diagnosticDossierReader; } ``` ```java ExceptionHandlerExceptionResolver[199] - Resolved [org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dossierToDiagnosticReader': Scope 'job' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for job scope] ```
2019/10/18
[ "https://Stackoverflow.com/questions/58452256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178038/" ]
I downloaded your project and was able to reproduce the case. There are two issues with your example: * You are defining a job scoped bean in your app but the `JobScope` is not defined in your context (and you are not using `@EnableBatchProcessing` annotation that adds it automatically to the context). If you want to use the job scope without `@EnableBatchProcessing`, you need to add it manually to the context. * Your test fails because there is no job running during your test. Job scoped beans are lazily instantiated when a job is actually run. Since your test does not start a job, the bean is not able to be proxied correctly. Your test does not seem to test a batch job, I would exclude the job scoped bean from the test's context.
Bug resolve in spring boot 2.2.1 <https://github.com/spring-projects/spring-boot/issues/18714>
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain. The following query returns a result set of every column of every table in the database: ``` SELECT table_name, column_name FROM INFORMATION_SCHEMA.COLUMNS; ``` In this [sqlfiddle](http://sqlfiddle.com/#!2/d41d8/1073), it returns the following result set (truncated here for brevity): ``` TABLE_NAME COLUMN_NAME ----------------------- CHARACTER_SETS CHARACTER_SET_NAME CHARACTER_SETS DEFAULT_COLLATE_NAME CHARACTER_SETS DESCRIPTION CHARACTER_SETS MAXLEN COLLATIONS COLLATION_NAME COLLATIONS CHARACTER_SET_NAME COLLATIONS ID COLLATIONS IS_DEFAULT COLLATIONS IS_COMPILED COLLATIONS SORTLEN ``` Now I know that I can select the column CHARACTER\_SET\_NAME from the table CHARACTER\_SETS like this: ``` SELECT CHARACTER_SET_NAME FROM CHARACTER_SETS; ``` Use [`mysqli::query`](http://www.php.net/manual/en/mysqli.query.php) to execute these queries.
Use `mysql_query()` and execute this query: ``` SHOW COLUMNS FROM table ``` Example: ``` <?php $result = mysql_query("SHOW COLUMNS FROM sometable"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
For unknown query fields, you can just use this code. It gives you every row fields name=>data. You can even change the key to `''` to get ordered array columns by num following the columns' order in the database. ``` $data = array(); while($row = mysql_fetch_assoc($query)) { foreach($row as $key => $value) { $data[$row['id']][$key] = $value; } } print_r($data); ```
Use `mysql_query()` and execute this query: ``` SHOW COLUMNS FROM table ``` Example: ``` <?php $result = mysql_query("SHOW COLUMNS FROM sometable"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
If I understand what you are asking, you probably want to use MySQLIi and the the fetch\_fields method on the result set: <http://us3.php.net/manual/en/mysqli-result.fetch-fields.php> See the examples on that page.
use `DESC table` or **Example** ``` SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table'; ``` **output** ``` column1,column2,column3 ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
For unknown query fields, you can just use this code. It gives you every row fields name=>data. You can even change the key to `''` to get ordered array columns by num following the columns' order in the database. ``` $data = array(); while($row = mysql_fetch_assoc($query)) { foreach($row as $key => $value) { $data[$row['id']][$key] = $value; } } print_r($data); ```
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain. The following query returns a result set of every column of every table in the database: ``` SELECT table_name, column_name FROM INFORMATION_SCHEMA.COLUMNS; ``` In this [sqlfiddle](http://sqlfiddle.com/#!2/d41d8/1073), it returns the following result set (truncated here for brevity): ``` TABLE_NAME COLUMN_NAME ----------------------- CHARACTER_SETS CHARACTER_SET_NAME CHARACTER_SETS DEFAULT_COLLATE_NAME CHARACTER_SETS DESCRIPTION CHARACTER_SETS MAXLEN COLLATIONS COLLATION_NAME COLLATIONS CHARACTER_SET_NAME COLLATIONS ID COLLATIONS IS_DEFAULT COLLATIONS IS_COMPILED COLLATIONS SORTLEN ``` Now I know that I can select the column CHARACTER\_SET\_NAME from the table CHARACTER\_SETS like this: ``` SELECT CHARACTER_SET_NAME FROM CHARACTER_SETS; ``` Use [`mysqli::query`](http://www.php.net/manual/en/mysqli.query.php) to execute these queries.
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
For unknown query fields, you can just use this code. It gives you every row fields name=>data. You can even change the key to `''` to get ordered array columns by num following the columns' order in the database. ``` $data = array(); while($row = mysql_fetch_assoc($query)) { foreach($row as $key => $value) { $data[$row['id']][$key] = $value; } } print_r($data); ```
If I understand what you are asking, you probably want to use MySQLIi and the the fetch\_fields method on the result set: <http://us3.php.net/manual/en/mysqli-result.fetch-fields.php> See the examples on that page.
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
If you want to get column names for any query in all cases it's not so easy. In case at least one row is returned you can get columns directly from this row. But when you want to get column names when there is no result to display table/export to CSV, you need to use PDO functions that are not 100% reliable. ``` // sample query - it might contain joins etc. $query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id'; $statement = $pdo->query($query); $data = $statement->fetchAll(PDO::FETCH_CLASS); if (isset($data[0])) { // there is at least one row - we can grab columns from it $columns = array_keys((array)$data[0]); } else { // there are no results - no need to use PDO functions $nr = $statement->columnCount(); for ($i = 0; $i < $nr; ++$i) { $columns[] = $statement->getColumnMeta($i)['name']; } } ```
use `DESC table` or **Example** ``` SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table'; ``` **output** ``` column1,column2,column3 ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
If I understand what you are asking, you probably want to use MySQLIi and the the fetch\_fields method on the result set: <http://us3.php.net/manual/en/mysqli-result.fetch-fields.php> See the examples on that page.
Use `mysql_query()` and execute this query: ``` SHOW COLUMNS FROM table ``` Example: ``` <?php $result = mysql_query("SHOW COLUMNS FROM sometable"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
For unknown query fields, you can just use this code. It gives you every row fields name=>data. You can even change the key to `''` to get ordered array columns by num following the columns' order in the database. ``` $data = array(); while($row = mysql_fetch_assoc($query)) { foreach($row as $key => $value) { $data[$row['id']][$key] = $value; } } print_r($data); ```
use `DESC table` or **Example** ``` SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table'; ``` **output** ``` column1,column2,column3 ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain. The following query returns a result set of every column of every table in the database: ``` SELECT table_name, column_name FROM INFORMATION_SCHEMA.COLUMNS; ``` In this [sqlfiddle](http://sqlfiddle.com/#!2/d41d8/1073), it returns the following result set (truncated here for brevity): ``` TABLE_NAME COLUMN_NAME ----------------------- CHARACTER_SETS CHARACTER_SET_NAME CHARACTER_SETS DEFAULT_COLLATE_NAME CHARACTER_SETS DESCRIPTION CHARACTER_SETS MAXLEN COLLATIONS COLLATION_NAME COLLATIONS CHARACTER_SET_NAME COLLATIONS ID COLLATIONS IS_DEFAULT COLLATIONS IS_COMPILED COLLATIONS SORTLEN ``` Now I know that I can select the column CHARACTER\_SET\_NAME from the table CHARACTER\_SETS like this: ``` SELECT CHARACTER_SET_NAME FROM CHARACTER_SETS; ``` Use [`mysqli::query`](http://www.php.net/manual/en/mysqli.query.php) to execute these queries.
use `DESC table` or **Example** ``` SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table'; ``` **output** ``` column1,column2,column3 ```
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
If you want to get column names for any query in all cases it's not so easy. In case at least one row is returned you can get columns directly from this row. But when you want to get column names when there is no result to display table/export to CSV, you need to use PDO functions that are not 100% reliable. ``` // sample query - it might contain joins etc. $query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id'; $statement = $pdo->query($query); $data = $statement->fetchAll(PDO::FETCH_CLASS); if (isset($data[0])) { // there is at least one row - we can grab columns from it $columns = array_keys((array)$data[0]); } else { // there are no results - no need to use PDO functions $nr = $statement->columnCount(); for ($i = 0; $i < $nr; ++$i) { $columns[] = $statement->getColumnMeta($i)['name']; } } ```
Use `mysql_query()` and execute this query: ``` SHOW COLUMNS FROM table ``` Example: ``` <?php $result = mysql_query("SHOW COLUMNS FROM sometable"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> ```
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
You can do it in the same way you normally [tell Maven to run from a POM that's somewhere else](http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html#running-sect-custom-locations-option): the `-f` option. `mvn --help` describes it thusly: ``` -f,--file <arg> Force the use of an alternate POM file. ``` To do that in a release, you just need to pass the appropriate option to the release plugin. You can use the [perform goal's "arguments" property](http://maven.apache.org/plugins/maven-release-plugin/perform-mojo.html#arguments) to do that. This property just tells the release plugin some additional arguments to append to the `mvn` command it runs when doing the release. You can set it from the command line by appending `-D arguments="-f path/to/pom"` or set it permanently in the pom in the release plugin's configuration, something like ``` <plugin> <artifactId>maven-release-plugin</artifactId> <version>2.3</version> <configuration> <arguments>-f path/to/pom</arguments> </configuration> </plugin> ```
The first thing is to understand git which has it's convention that every project has it's own repository. The next thing is that Maven has it's conventions and putting the pom.xml into the root of it's project is the most obvious one. Furthermore you are trying to fight against Maven and i will predict that you will lose the combat and make your life not easy. If your projects A and B are related (same versio number or same release times) in some kind you should think about a multi-module build which results in a structure like this: ``` root (Git Repos) +-- pom.xml +--- projectA (pom.xml) +--- projectB (pom.xml) ``` and you can do a release of both projectA (better calling it a module) and module b in a single step from the root.
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
This should do the trick: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.3.2</version> <executions> <execution> <id>default</id> <goals> <goal>perform</goal> </goals> <configuration> <pomFileName>your_path/your_pom.xml</pomFileName> </configuration> </execution> </executions> </plugin> ```
You can do it in the same way you normally [tell Maven to run from a POM that's somewhere else](http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html#running-sect-custom-locations-option): the `-f` option. `mvn --help` describes it thusly: ``` -f,--file <arg> Force the use of an alternate POM file. ``` To do that in a release, you just need to pass the appropriate option to the release plugin. You can use the [perform goal's "arguments" property](http://maven.apache.org/plugins/maven-release-plugin/perform-mojo.html#arguments) to do that. This property just tells the release plugin some additional arguments to append to the `mvn` command it runs when doing the release. You can set it from the command line by appending `-D arguments="-f path/to/pom"` or set it permanently in the pom in the release plugin's configuration, something like ``` <plugin> <artifactId>maven-release-plugin</artifactId> <version>2.3</version> <configuration> <arguments>-f path/to/pom</arguments> </configuration> </plugin> ```
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
You can do it in the same way you normally [tell Maven to run from a POM that's somewhere else](http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html#running-sect-custom-locations-option): the `-f` option. `mvn --help` describes it thusly: ``` -f,--file <arg> Force the use of an alternate POM file. ``` To do that in a release, you just need to pass the appropriate option to the release plugin. You can use the [perform goal's "arguments" property](http://maven.apache.org/plugins/maven-release-plugin/perform-mojo.html#arguments) to do that. This property just tells the release plugin some additional arguments to append to the `mvn` command it runs when doing the release. You can set it from the command line by appending `-D arguments="-f path/to/pom"` or set it permanently in the pom in the release plugin's configuration, something like ``` <plugin> <artifactId>maven-release-plugin</artifactId> <version>2.3</version> <configuration> <arguments>-f path/to/pom</arguments> </configuration> </plugin> ```
This question was asked over 10 years ago so I wanted to provide a more up-to-date answer. As of Oct 2022, the current/modern Maven works without any problems in a sub-directory. The current version of the maven plugin release is [version: 3.0.0-M6](https://maven.apache.org/maven-release/maven-release-plugin/index.html) All that is needed is the normal elements defined in your POM that the maven release plugin needs: * The `<scm>` element to point to the git repo (at top of repo, like you normally would). [See Maven docs here, scm](https://maven.apache.org/pom.html#scm) * The `<distributionManagement>` element [See Maven docs here, distributionManagement](https://maven.apache.org/pom.html#repository). *NOTE: It's also possible to pass these arguments via a command line, but I prefer having them in a file (in pom.xml, parent for `<distributionManagement>`, or even settings.xml to better document the process and make it easier for other devs on the team to deploy.* *NOTE: I used maven version 3.8.5 with Java 11, but AFAIK the version of Java does not matter. The latest version of maven is 3.8.6 (at this time). I believe it would work with Java 8. And at this time, maven 4 is in alpha.* How it works ============ ### Assumptions In this example the following is used: * GitHub Repo: <https://github.com/user123/proj456> * Apps: app1, app2, lib1, lib2 * NEXUS/Maven Repos: <https://mynexus.example.com/repository/>\* Each of the apps or libraries are in a separate directory with no parent POM being used (in this example). So you can't type `mvn clean install` from the top level directory. This is similar to the original OP question. As one commenter said, this is type of problem happens in a polyglot repo where multiple languages and technologies are used. ### Explanation of POM configuration needed In `lib1`, the pom has the following defined (only showing settings for maven release plugin). **NOTE: This is the *SAME* information that will be in all of the POMs for this repository.** ``` <scm> <connection>scm:[email protected]:user123/proj456.git</connection> <developerConnection>scm:[email protected]:user123/proj456.git</developerConnection> <tag>HEAD</tag> </scm> <distributionManagement> <downloadUrl>https://mynexus.example.com/repository/maven-public</downloadUrl> <repository> <id>proj456-release</id> <name>proj456 release distro</name> <url>https://mynexus.example.com/repository/proj456-release</url> </repository> <snapshotRepository> <uniqueVersion>true</uniqueVersion> <id>proj456-snapshot</id> <name>proj456 snapshot</name> <url>https://mynexus.example.com/repository/proj456-snapshot</url> </snapshotRepository> </distributionManagement> ``` NOTE: Your settings.xml file needs to contain your login or auth-credentials so that might look like: ``` <servers> <server> <id>proj456-releases</id> <username>user123</username> <password>not-shown</password> </server> <server> <id>proj456-snapshot</id> <username>user123</username> <password>not-shown</password> </server> </servers> ``` When you have a separate git repo for each maven artifact you are working on, the `<scm>` tag will be different for each of them. ### Creating a release The normal maven release commands are used, just from the sub-directory: ``` cd $HOME/work/proj456 ls -1 app1 app2 lib1 lib2 # Now CD to the directory you want to create a release for cd lib1 mvn release:clean mvn release:prepare release:perform ``` At the end of this process, the maven release plugin will do all the things it normally does. For example, 1. The -SNAPSHOT version in the POM is replaced with a release version (that you specify). 2. A git commit is created with the release version. 3. A maven build and package is created with that release. 4. The maven package is pushed (uploaded) to the NEXUS repo (or maven central). 5. The pom.xml is bumped to the next version (with -SNAPSHOT added) and git commit is made so future development occurs on next SNAPSHOT version. See [maven docs for maven release plugin](https://maven.apache.org/maven-release/maven-release-plugin/examples/prepare-release.html#prepare-a-release) for a complete list of the steps.
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
This should do the trick: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.3.2</version> <executions> <execution> <id>default</id> <goals> <goal>perform</goal> </goals> <configuration> <pomFileName>your_path/your_pom.xml</pomFileName> </configuration> </execution> </executions> </plugin> ```
The first thing is to understand git which has it's convention that every project has it's own repository. The next thing is that Maven has it's conventions and putting the pom.xml into the root of it's project is the most obvious one. Furthermore you are trying to fight against Maven and i will predict that you will lose the combat and make your life not easy. If your projects A and B are related (same versio number or same release times) in some kind you should think about a multi-module build which results in a structure like this: ``` root (Git Repos) +-- pom.xml +--- projectA (pom.xml) +--- projectB (pom.xml) ``` and you can do a release of both projectA (better calling it a module) and module b in a single step from the root.
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
This question was asked over 10 years ago so I wanted to provide a more up-to-date answer. As of Oct 2022, the current/modern Maven works without any problems in a sub-directory. The current version of the maven plugin release is [version: 3.0.0-M6](https://maven.apache.org/maven-release/maven-release-plugin/index.html) All that is needed is the normal elements defined in your POM that the maven release plugin needs: * The `<scm>` element to point to the git repo (at top of repo, like you normally would). [See Maven docs here, scm](https://maven.apache.org/pom.html#scm) * The `<distributionManagement>` element [See Maven docs here, distributionManagement](https://maven.apache.org/pom.html#repository). *NOTE: It's also possible to pass these arguments via a command line, but I prefer having them in a file (in pom.xml, parent for `<distributionManagement>`, or even settings.xml to better document the process and make it easier for other devs on the team to deploy.* *NOTE: I used maven version 3.8.5 with Java 11, but AFAIK the version of Java does not matter. The latest version of maven is 3.8.6 (at this time). I believe it would work with Java 8. And at this time, maven 4 is in alpha.* How it works ============ ### Assumptions In this example the following is used: * GitHub Repo: <https://github.com/user123/proj456> * Apps: app1, app2, lib1, lib2 * NEXUS/Maven Repos: <https://mynexus.example.com/repository/>\* Each of the apps or libraries are in a separate directory with no parent POM being used (in this example). So you can't type `mvn clean install` from the top level directory. This is similar to the original OP question. As one commenter said, this is type of problem happens in a polyglot repo where multiple languages and technologies are used. ### Explanation of POM configuration needed In `lib1`, the pom has the following defined (only showing settings for maven release plugin). **NOTE: This is the *SAME* information that will be in all of the POMs for this repository.** ``` <scm> <connection>scm:[email protected]:user123/proj456.git</connection> <developerConnection>scm:[email protected]:user123/proj456.git</developerConnection> <tag>HEAD</tag> </scm> <distributionManagement> <downloadUrl>https://mynexus.example.com/repository/maven-public</downloadUrl> <repository> <id>proj456-release</id> <name>proj456 release distro</name> <url>https://mynexus.example.com/repository/proj456-release</url> </repository> <snapshotRepository> <uniqueVersion>true</uniqueVersion> <id>proj456-snapshot</id> <name>proj456 snapshot</name> <url>https://mynexus.example.com/repository/proj456-snapshot</url> </snapshotRepository> </distributionManagement> ``` NOTE: Your settings.xml file needs to contain your login or auth-credentials so that might look like: ``` <servers> <server> <id>proj456-releases</id> <username>user123</username> <password>not-shown</password> </server> <server> <id>proj456-snapshot</id> <username>user123</username> <password>not-shown</password> </server> </servers> ``` When you have a separate git repo for each maven artifact you are working on, the `<scm>` tag will be different for each of them. ### Creating a release The normal maven release commands are used, just from the sub-directory: ``` cd $HOME/work/proj456 ls -1 app1 app2 lib1 lib2 # Now CD to the directory you want to create a release for cd lib1 mvn release:clean mvn release:prepare release:perform ``` At the end of this process, the maven release plugin will do all the things it normally does. For example, 1. The -SNAPSHOT version in the POM is replaced with a release version (that you specify). 2. A git commit is created with the release version. 3. A maven build and package is created with that release. 4. The maven package is pushed (uploaded) to the NEXUS repo (or maven central). 5. The pom.xml is bumped to the next version (with -SNAPSHOT added) and git commit is made so future development occurs on next SNAPSHOT version. See [maven docs for maven release plugin](https://maven.apache.org/maven-release/maven-release-plugin/examples/prepare-release.html#prepare-a-release) for a complete list of the steps.
The first thing is to understand git which has it's convention that every project has it's own repository. The next thing is that Maven has it's conventions and putting the pom.xml into the root of it's project is the most obvious one. Furthermore you are trying to fight against Maven and i will predict that you will lose the combat and make your life not easy. If your projects A and B are related (same versio number or same release times) in some kind you should think about a multi-module build which results in a structure like this: ``` root (Git Repos) +-- pom.xml +--- projectA (pom.xml) +--- projectB (pom.xml) ``` and you can do a release of both projectA (better calling it a module) and module b in a single step from the root.
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
This should do the trick: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.3.2</version> <executions> <execution> <id>default</id> <goals> <goal>perform</goal> </goals> <configuration> <pomFileName>your_path/your_pom.xml</pomFileName> </configuration> </execution> </executions> </plugin> ```
This question was asked over 10 years ago so I wanted to provide a more up-to-date answer. As of Oct 2022, the current/modern Maven works without any problems in a sub-directory. The current version of the maven plugin release is [version: 3.0.0-M6](https://maven.apache.org/maven-release/maven-release-plugin/index.html) All that is needed is the normal elements defined in your POM that the maven release plugin needs: * The `<scm>` element to point to the git repo (at top of repo, like you normally would). [See Maven docs here, scm](https://maven.apache.org/pom.html#scm) * The `<distributionManagement>` element [See Maven docs here, distributionManagement](https://maven.apache.org/pom.html#repository). *NOTE: It's also possible to pass these arguments via a command line, but I prefer having them in a file (in pom.xml, parent for `<distributionManagement>`, or even settings.xml to better document the process and make it easier for other devs on the team to deploy.* *NOTE: I used maven version 3.8.5 with Java 11, but AFAIK the version of Java does not matter. The latest version of maven is 3.8.6 (at this time). I believe it would work with Java 8. And at this time, maven 4 is in alpha.* How it works ============ ### Assumptions In this example the following is used: * GitHub Repo: <https://github.com/user123/proj456> * Apps: app1, app2, lib1, lib2 * NEXUS/Maven Repos: <https://mynexus.example.com/repository/>\* Each of the apps or libraries are in a separate directory with no parent POM being used (in this example). So you can't type `mvn clean install` from the top level directory. This is similar to the original OP question. As one commenter said, this is type of problem happens in a polyglot repo where multiple languages and technologies are used. ### Explanation of POM configuration needed In `lib1`, the pom has the following defined (only showing settings for maven release plugin). **NOTE: This is the *SAME* information that will be in all of the POMs for this repository.** ``` <scm> <connection>scm:[email protected]:user123/proj456.git</connection> <developerConnection>scm:[email protected]:user123/proj456.git</developerConnection> <tag>HEAD</tag> </scm> <distributionManagement> <downloadUrl>https://mynexus.example.com/repository/maven-public</downloadUrl> <repository> <id>proj456-release</id> <name>proj456 release distro</name> <url>https://mynexus.example.com/repository/proj456-release</url> </repository> <snapshotRepository> <uniqueVersion>true</uniqueVersion> <id>proj456-snapshot</id> <name>proj456 snapshot</name> <url>https://mynexus.example.com/repository/proj456-snapshot</url> </snapshotRepository> </distributionManagement> ``` NOTE: Your settings.xml file needs to contain your login or auth-credentials so that might look like: ``` <servers> <server> <id>proj456-releases</id> <username>user123</username> <password>not-shown</password> </server> <server> <id>proj456-snapshot</id> <username>user123</username> <password>not-shown</password> </server> </servers> ``` When you have a separate git repo for each maven artifact you are working on, the `<scm>` tag will be different for each of them. ### Creating a release The normal maven release commands are used, just from the sub-directory: ``` cd $HOME/work/proj456 ls -1 app1 app2 lib1 lib2 # Now CD to the directory you want to create a release for cd lib1 mvn release:clean mvn release:prepare release:perform ``` At the end of this process, the maven release plugin will do all the things it normally does. For example, 1. The -SNAPSHOT version in the POM is replaced with a release version (that you specify). 2. A git commit is created with the release version. 3. A maven build and package is created with that release. 4. The maven package is pushed (uploaded) to the NEXUS repo (or maven central). 5. The pom.xml is bumped to the next version (with -SNAPSHOT added) and git commit is made so future development occurs on next SNAPSHOT version. See [maven docs for maven release plugin](https://maven.apache.org/maven-release/maven-release-plugin/examples/prepare-release.html#prepare-a-release) for a complete list of the steps.
56,833,298
I have multiple buttons (with the ids 'a', 'b', ...) and if you click them, they should display their corresponding image ('a.JPG', 'b.JPG', ...) at a fixed point on the website. The idea is to listen for when a button is clicked and change the code inside the output to include its id. ``` 'use strict'; var bild = '', i, j, k; function gedrueckt(k) { bild = '<img src="img/' + k + '.JPG" width="1600" hight="900" alt="Vergroessertes Bild"></img>'; document.querySelector('output').innerHTML = bild; } for (i = 1; i < 8; i = i + 1) { j = String.fromCharCode(97 + i); document.getElementById(j).addEventListener('click', gedrueckt(j)); } ``` The problem is that an image already appears before any button is clicked and pressing a different button does not change the displayed image.
2019/07/01
[ "https://Stackoverflow.com/questions/56833298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11723122/" ]
This code should change the src on each button click, changing the picture according the the ID of the button: ```js let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` } ``` ```html <img id="img" src=""> <br> <button onclick="change(this.id)" id="a">A</button> <button onclick="change(this.id)" id="b">B</button> <button onclick="change(this.id)" id="c">C</button> ``` > > If there no `src` and no `alt` property provided, the image will not be displayed. > > > I might've misunderstood you, in that you want the image to change on keyboard button press, which this code should do the trick: ```js let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` } const list = ['a','b','c'] document.addEventListener('keydown', e => list.includes(e.key) && change(e.key)) ``` ```html <img id="img" src=""> ```
Get all the buttons and attach an `click` listener to it. Create `img` element on `button` click and append it to the element with `id` output. ```js const buttons = document.querySelectorAll('button') const output = document.querySelector('#output'); buttons.forEach((button) => { button.addEventListener('click', function() { const img = document.createElement('img'); img.src = this.id + '.jpg'; output.innerHTML = ""; output.appendChild(img); }); }); ``` ```html <button id="a">one</button> <button id="b">two</button> <button id="c">three</button> <div id="output"></div> ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
Using @cs95 idea of `last_valid_index`: ``` test.apply(lambda x: x[:x.idxmax()].eq(1)[lambda i:i].last_valid_index()) ``` Output: ``` col1 6 col2 2 dtype: int64 ``` Expained: Using index slicing to cut each column to start to max value, then look for the values that are equal to one and find the index of the last true value. Or as @QuangHoang suggests: ``` test.apply(lambda x: x[:x.idxmax()].eq(1).cumsum().idxmax()) ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
Here's a mixed `numpy` and `pandas` solution: ``` (test.eq(1) & (test.index.values[:,None] < test.idxmax().values)).cumsum().idxmax() ``` which is a bit faster than the other solutions.
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
I would use `dropna` with `where` to drop duplicated `1` keeping the last `1`, and call `idxmin` on it. ``` test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) Out[1433]: col1 6 col2 2 dtype: int64 ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
### Overkill with Numpy ``` t = test.to_numpy() a = t.argmax(0) i, j = np.where(t == 1) mask = i <= a[j] i = i[mask] j = j[mask] b = np.empty_like(a) b.fill(-1) np.maximum.at(b, j, i) pd.Series(b, test.columns) col1 6 col2 2 dtype: int64 ``` --- ### `apply` ``` test.apply(lambda s: max(s.index, key=lambda x: (s[x] == 1, s[x] <= s.max(), x))) col1 6 col2 2 dtype: int64 ``` --- ### `cummax` ``` test.eq(1).where(test.cummax().lt(test.max())).iloc[::-1].idxmax() col1 6 col2 2 dtype: int64 ``` --- Timing ====== I just wanted to use a new tool and do some bechmarking [see this post](https://stackoverflow.com/a/56398618/2336654) Results ------- ``` r.to_pandas_dataframe().T 10 31 100 316 1000 3162 10000 al_0 0.003696 0.003718 0.005512 0.006210 0.010973 0.007764 0.012008 wb_0 0.003348 0.003334 0.003913 0.003935 0.004583 0.004757 0.006096 qh_0 0.002279 0.002265 0.002571 0.002643 0.002927 0.003070 0.003987 sb_0 0.002235 0.002246 0.003072 0.003357 0.004136 0.004083 0.005286 sb_1 0.001771 0.001779 0.002331 0.002353 0.002914 0.002936 0.003619 cs_0 0.005742 0.005751 0.006748 0.006808 0.007845 0.008088 0.009898 cs_1 0.004034 0.004045 0.004871 0.004898 0.005769 0.005997 0.007338 pr_0 0.002484 0.006142 0.027101 0.085944 0.374629 1.292556 6.220875 pr_1 0.003388 0.003414 0.003981 0.004027 0.004658 0.004929 0.006390 pr_2 0.000087 0.000088 0.000089 0.000093 0.000107 0.000145 0.000300 fig = plt.figure(figsize=(10, 10)) ax = plt.subplot() r.plot(ax=ax) ``` [![enter image description here](https://i.stack.imgur.com/QZ32z.png)](https://i.stack.imgur.com/QZ32z.png) Setup ----- ``` from simple_benchmark import BenchmarkBuilder b = BenchmarkBuilder() def al_0(test): return test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) def wb_0(df): return (df.iloc[::-1].cummax().eq(df.max())&df.eq(1).iloc[::-1]).idxmax() def qh_0(test): return (test.eq(1) & (test.index.values[:,None] < test.idxmax().values)).cumsum().idxmax() def sb_0(test): return test.apply(lambda x: x[:x.idxmax()].eq(1)[lambda i:i].last_valid_index()) def sb_1(test): return test.apply(lambda x: x[:x.idxmax()].eq(1).cumsum().idxmax()) def cs_0(test): return (lambda m: test.mask(m).apply(pd.Series.last_valid_index))(test.eq(test.max()).cumsum().gt(0) | test.ne(1)) def cs_1(test): return pd.Series((test.eq(1) & test.eq(test.max()).cumsum().eq(0)).values.cumsum(axis=0).argmax(axis=0), test.columns) def pr_0(test): return test.apply(lambda s: max(s.index, key=lambda x: (s[x] == 1, s[x] <= s.max(), x))) def pr_1(test): return test.eq(1).where(test.cummax().lt(test.max())).iloc[::-1].idxmax() def pr_2(test): t = test.to_numpy() a = t.argmax(0) i, j = np.where(t == 1) mask = i <= a[j] i = i[mask] j = j[mask] b = np.empty_like(a) b.fill(-1) np.maximum.at(b, j, i) return pd.Series(b, test.columns) import math def gen_test(n): a = np.random.randint(100, size=(n, int(math.log10(n)) + 1)) idx = a.argmax(0) while (idx == 0).any(): a = np.random.randint(100, size=(n, int(math.log10(n)) + 1)) idx = a.argmax(0) for j, i in enumerate(idx): a[np.random.randint(i), j] = 1 return pd.DataFrame(a).add_prefix('col') @b.add_arguments('DataFrame Size') def argument_provider(): for exponent in np.linspace(1, 3, 5): size = int(10 ** exponent) yield size, gen_test(size) b.add_functions([al_0, wb_0, qh_0, sb_0, sb_1, cs_0, cs_1, pr_0, pr_1, pr_2]) r = b.run() ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
A little bit logic here ``` (df.iloc[::-1].cummax().eq(df.max())&df.eq(1).iloc[::-1]).idxmax() Out[187]: col1 6 col2 2 dtype: int64 ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Using @cs95 idea of `last_valid_index`: ``` test.apply(lambda x: x[:x.idxmax()].eq(1)[lambda i:i].last_valid_index()) ``` Output: ``` col1 6 col2 2 dtype: int64 ``` Expained: Using index slicing to cut each column to start to max value, then look for the values that are equal to one and find the index of the last true value. Or as @QuangHoang suggests: ``` test.apply(lambda x: x[:x.idxmax()].eq(1).cumsum().idxmax()) ```
I would use `dropna` with `where` to drop duplicated `1` keeping the last `1`, and call `idxmin` on it. ``` test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) Out[1433]: col1 6 col2 2 dtype: int64 ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Here's a mixed `numpy` and `pandas` solution: ``` (test.eq(1) & (test.index.values[:,None] < test.idxmax().values)).cumsum().idxmax() ``` which is a bit faster than the other solutions.
I would use `dropna` with `where` to drop duplicated `1` keeping the last `1`, and call `idxmin` on it. ``` test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) Out[1433]: col1 6 col2 2 dtype: int64 ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
### Overkill with Numpy ``` t = test.to_numpy() a = t.argmax(0) i, j = np.where(t == 1) mask = i <= a[j] i = i[mask] j = j[mask] b = np.empty_like(a) b.fill(-1) np.maximum.at(b, j, i) pd.Series(b, test.columns) col1 6 col2 2 dtype: int64 ``` --- ### `apply` ``` test.apply(lambda s: max(s.index, key=lambda x: (s[x] == 1, s[x] <= s.max(), x))) col1 6 col2 2 dtype: int64 ``` --- ### `cummax` ``` test.eq(1).where(test.cummax().lt(test.max())).iloc[::-1].idxmax() col1 6 col2 2 dtype: int64 ``` --- Timing ====== I just wanted to use a new tool and do some bechmarking [see this post](https://stackoverflow.com/a/56398618/2336654) Results ------- ``` r.to_pandas_dataframe().T 10 31 100 316 1000 3162 10000 al_0 0.003696 0.003718 0.005512 0.006210 0.010973 0.007764 0.012008 wb_0 0.003348 0.003334 0.003913 0.003935 0.004583 0.004757 0.006096 qh_0 0.002279 0.002265 0.002571 0.002643 0.002927 0.003070 0.003987 sb_0 0.002235 0.002246 0.003072 0.003357 0.004136 0.004083 0.005286 sb_1 0.001771 0.001779 0.002331 0.002353 0.002914 0.002936 0.003619 cs_0 0.005742 0.005751 0.006748 0.006808 0.007845 0.008088 0.009898 cs_1 0.004034 0.004045 0.004871 0.004898 0.005769 0.005997 0.007338 pr_0 0.002484 0.006142 0.027101 0.085944 0.374629 1.292556 6.220875 pr_1 0.003388 0.003414 0.003981 0.004027 0.004658 0.004929 0.006390 pr_2 0.000087 0.000088 0.000089 0.000093 0.000107 0.000145 0.000300 fig = plt.figure(figsize=(10, 10)) ax = plt.subplot() r.plot(ax=ax) ``` [![enter image description here](https://i.stack.imgur.com/QZ32z.png)](https://i.stack.imgur.com/QZ32z.png) Setup ----- ``` from simple_benchmark import BenchmarkBuilder b = BenchmarkBuilder() def al_0(test): return test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) def wb_0(df): return (df.iloc[::-1].cummax().eq(df.max())&df.eq(1).iloc[::-1]).idxmax() def qh_0(test): return (test.eq(1) & (test.index.values[:,None] < test.idxmax().values)).cumsum().idxmax() def sb_0(test): return test.apply(lambda x: x[:x.idxmax()].eq(1)[lambda i:i].last_valid_index()) def sb_1(test): return test.apply(lambda x: x[:x.idxmax()].eq(1).cumsum().idxmax()) def cs_0(test): return (lambda m: test.mask(m).apply(pd.Series.last_valid_index))(test.eq(test.max()).cumsum().gt(0) | test.ne(1)) def cs_1(test): return pd.Series((test.eq(1) & test.eq(test.max()).cumsum().eq(0)).values.cumsum(axis=0).argmax(axis=0), test.columns) def pr_0(test): return test.apply(lambda s: max(s.index, key=lambda x: (s[x] == 1, s[x] <= s.max(), x))) def pr_1(test): return test.eq(1).where(test.cummax().lt(test.max())).iloc[::-1].idxmax() def pr_2(test): t = test.to_numpy() a = t.argmax(0) i, j = np.where(t == 1) mask = i <= a[j] i = i[mask] j = j[mask] b = np.empty_like(a) b.fill(-1) np.maximum.at(b, j, i) return pd.Series(b, test.columns) import math def gen_test(n): a = np.random.randint(100, size=(n, int(math.log10(n)) + 1)) idx = a.argmax(0) while (idx == 0).any(): a = np.random.randint(100, size=(n, int(math.log10(n)) + 1)) idx = a.argmax(0) for j, i in enumerate(idx): a[np.random.randint(i), j] = 1 return pd.DataFrame(a).add_prefix('col') @b.add_arguments('DataFrame Size') def argument_provider(): for exponent in np.linspace(1, 3, 5): size = int(10 ** exponent) yield size, gen_test(size) b.add_functions([al_0, wb_0, qh_0, sb_0, sb_1, cs_0, cs_1, pr_0, pr_1, pr_2]) r = b.run() ```
I would use `dropna` with `where` to drop duplicated `1` keeping the last `1`, and call `idxmin` on it. ``` test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) Out[1433]: col1 6 col2 2 dtype: int64 ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
A little bit logic here ``` (df.iloc[::-1].cummax().eq(df.max())&df.eq(1).iloc[::-1]).idxmax() Out[187]: col1 6 col2 2 dtype: int64 ```
I would use `dropna` with `where` to drop duplicated `1` keeping the last `1`, and call `idxmin` on it. ``` test.apply(lambda x: x.where(x[:x.idxmax()].eq(1)).drop_duplicates(keep='last').idxmin()) Out[1433]: col1 6 col2 2 dtype: int64 ```
39,897,670
I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. This is the basics of my service and the object it uses ``` export class deviceObj { device_Id:number; deviceGroup_Id:number; name:string; favoriteFlag:boolean; visibleFlag:boolean; } export class Favorite { favorite_Id: number; device: deviceObj; constructor(){this.device = new deviceObj()}; } @Injectable() export class FavoriteService { private headers = new Headers({'Content-Type': 'application/json'}); private favoritesURL = 'URL THAT FEETCHES DATA'; favorites: Favorite[]; constructor(private http: Http) { this.getFavorites().then(favorites => this.favorites = favorites); } getFavorites(): Promise<Favorite[]> { return this.http.get(this.favoritesURL).toPromise().then(response => response.json() as Favorite[]).catch(this.handleError); } protected handleError2(error: Response) { console.error(error); return Observable.throw(error.json().error || 'server error'); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // return Promise.reject(error.message || error); } } ``` And here is one of the components that gets the array of favorites. ``` import {FavoriteService} from'../../services/favorite/favorite.service'; declare var jQuery: any; @Component({ selector: '[sidebar]', directives: [ ROUTER_DIRECTIVES, SlimScroll ], template: require('./sidebar.html') }) export class Sidebar implements OnInit { constructor(config: ConfigService, el: ElementRef, router: Router, location: Location, private favoriteService:FavoriteService) { } getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favorites = favorites); } ``` In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.
2016/10/06
[ "https://Stackoverflow.com/questions/39897670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1710501/" ]
While it can probably be done with Promises, I can answer in the form of Observables at the very least, if you're of a mind to read about them... Given `ComponentA` and `ComponentB` both looking at a `SharedService` for their source of `SomeObject[]` data: The service: ``` import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import 'rxjs/add/operator/share'; import { SomeObject } from './some-object'; @Injectable() export class SomeService{ SharedList$: Observable<SomeObject[]>; private listObserver: Observer<SomeObject[]>; private sharedList: SomeObject[]; constructor(private http: Http){ this.sharedList = []; this.SharedList$ = new Observable<SomeObject[]>(x => this.listObserver = x).share(); } getList(){ // Get the data from somewhere, i.e. http call this.http.get(...) .map(etc) .subscribe(res => { this.sharedList = res; this.listObserver.next(this.sharedList); }); // the important part is after getting the data you want, observer.next it } addItem(item: SomeObject): void { this.sharedList.push(item); this.listObserver.next(this.sharedList); } } ``` Components then have: ``` import { Component, OnInit } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import { SharedService } from './some.service'; import { SomeObject } from './some-object'; @Component({...}) export class CommponentA implements OnInit { private list: SomeObject[]; constructor(private service: SharedService){ this.list = []; } ngOnInit(){ this.service.SharedList$.subscribe(lst => this.list = lst); this.service.getList(); } private onClick(item: SomeItem): void { this.service.addItem(item); } } ``` `ComponentB` would look similar - subscribing to the same `SharedList$` property on the service. When the service's `getList()` method is called, and it pushes a new `SomeObject[]` through the observables (`this.listObserver.next(..)`), the components subscribed to that property will be able to read the value pushed to it. Edit: Exposed an `addItem` method on the service that the components can call to push items to the list. The service then pushes it through the observable, (`this.listObserver.next(...)`) in the same style as when getting the data through x other method (i.e. http).
In your component ``` //set favorites getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favoriteService.favorites = favorites); } // get favorite this.favorites = this.favoriteService.favorites;//access it from service ```
39,897,670
I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. This is the basics of my service and the object it uses ``` export class deviceObj { device_Id:number; deviceGroup_Id:number; name:string; favoriteFlag:boolean; visibleFlag:boolean; } export class Favorite { favorite_Id: number; device: deviceObj; constructor(){this.device = new deviceObj()}; } @Injectable() export class FavoriteService { private headers = new Headers({'Content-Type': 'application/json'}); private favoritesURL = 'URL THAT FEETCHES DATA'; favorites: Favorite[]; constructor(private http: Http) { this.getFavorites().then(favorites => this.favorites = favorites); } getFavorites(): Promise<Favorite[]> { return this.http.get(this.favoritesURL).toPromise().then(response => response.json() as Favorite[]).catch(this.handleError); } protected handleError2(error: Response) { console.error(error); return Observable.throw(error.json().error || 'server error'); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // return Promise.reject(error.message || error); } } ``` And here is one of the components that gets the array of favorites. ``` import {FavoriteService} from'../../services/favorite/favorite.service'; declare var jQuery: any; @Component({ selector: '[sidebar]', directives: [ ROUTER_DIRECTIVES, SlimScroll ], template: require('./sidebar.html') }) export class Sidebar implements OnInit { constructor(config: ConfigService, el: ElementRef, router: Router, location: Location, private favoriteService:FavoriteService) { } getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favorites = favorites); } ``` In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.
2016/10/06
[ "https://Stackoverflow.com/questions/39897670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1710501/" ]
@Krenom's answer was corrrect. with one import needing to be changed on my setup. I needed `import { Observable, Observer } from 'rxjs/Rx';import { Observable, Observer } from 'rxjs/Rx';`
In your component ``` //set favorites getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favoriteService.favorites = favorites); } // get favorite this.favorites = this.favoriteService.favorites;//access it from service ```
39,897,670
I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. This is the basics of my service and the object it uses ``` export class deviceObj { device_Id:number; deviceGroup_Id:number; name:string; favoriteFlag:boolean; visibleFlag:boolean; } export class Favorite { favorite_Id: number; device: deviceObj; constructor(){this.device = new deviceObj()}; } @Injectable() export class FavoriteService { private headers = new Headers({'Content-Type': 'application/json'}); private favoritesURL = 'URL THAT FEETCHES DATA'; favorites: Favorite[]; constructor(private http: Http) { this.getFavorites().then(favorites => this.favorites = favorites); } getFavorites(): Promise<Favorite[]> { return this.http.get(this.favoritesURL).toPromise().then(response => response.json() as Favorite[]).catch(this.handleError); } protected handleError2(error: Response) { console.error(error); return Observable.throw(error.json().error || 'server error'); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // return Promise.reject(error.message || error); } } ``` And here is one of the components that gets the array of favorites. ``` import {FavoriteService} from'../../services/favorite/favorite.service'; declare var jQuery: any; @Component({ selector: '[sidebar]', directives: [ ROUTER_DIRECTIVES, SlimScroll ], template: require('./sidebar.html') }) export class Sidebar implements OnInit { constructor(config: ConfigService, el: ElementRef, router: Router, location: Location, private favoriteService:FavoriteService) { } getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favorites = favorites); } ``` In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.
2016/10/06
[ "https://Stackoverflow.com/questions/39897670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1710501/" ]
While it can probably be done with Promises, I can answer in the form of Observables at the very least, if you're of a mind to read about them... Given `ComponentA` and `ComponentB` both looking at a `SharedService` for their source of `SomeObject[]` data: The service: ``` import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import 'rxjs/add/operator/share'; import { SomeObject } from './some-object'; @Injectable() export class SomeService{ SharedList$: Observable<SomeObject[]>; private listObserver: Observer<SomeObject[]>; private sharedList: SomeObject[]; constructor(private http: Http){ this.sharedList = []; this.SharedList$ = new Observable<SomeObject[]>(x => this.listObserver = x).share(); } getList(){ // Get the data from somewhere, i.e. http call this.http.get(...) .map(etc) .subscribe(res => { this.sharedList = res; this.listObserver.next(this.sharedList); }); // the important part is after getting the data you want, observer.next it } addItem(item: SomeObject): void { this.sharedList.push(item); this.listObserver.next(this.sharedList); } } ``` Components then have: ``` import { Component, OnInit } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import { SharedService } from './some.service'; import { SomeObject } from './some-object'; @Component({...}) export class CommponentA implements OnInit { private list: SomeObject[]; constructor(private service: SharedService){ this.list = []; } ngOnInit(){ this.service.SharedList$.subscribe(lst => this.list = lst); this.service.getList(); } private onClick(item: SomeItem): void { this.service.addItem(item); } } ``` `ComponentB` would look similar - subscribing to the same `SharedList$` property on the service. When the service's `getList()` method is called, and it pushes a new `SomeObject[]` through the observables (`this.listObserver.next(..)`), the components subscribed to that property will be able to read the value pushed to it. Edit: Exposed an `addItem` method on the service that the components can call to push items to the list. The service then pushes it through the observable, (`this.listObserver.next(...)`) in the same style as when getting the data through x other method (i.e. http).
@Krenom's answer was corrrect. with one import needing to be changed on my setup. I needed `import { Observable, Observer } from 'rxjs/Rx';import { Observable, Observer } from 'rxjs/Rx';`
25,961,140
I have two table and first named **table1**: ``` ID | Name | Type | isActive | isDeleted | ----------------------------------------------- 1 | item 1 | 4 | 1 | 0 | 2 | item 2 | 2 | 1 | 0 | 3 | item 3 | 1 | 1 | 1 | 4 | item 4 | 1 | 1 | 0 | 5 | item 5 | 1 | 1 | 0 | 6 | item 6 | 3 | 1 | 0 | 7 | item 7 | 1 | 1 | 0 | 8 | item 8 | 2 | 1 | 0 | 9 | item 9 | 1 | 1 | 0 | 10 | item 10 | 1 | 1 | 0 | ``` AND second named **table1\_meta**: ``` ID | table1_id | options | value ------------------------------------ 1 | 1 | dont_ask | 1 2 | 2 | dont_ask | 1 3 | 5 | dont_ask | 1 4 | 6 | dont_ask | 1 5 | 8 | alwasys_ask| 1 6 | 9 | alwasys_ask| 1 7 | 1 | is_flagged | 1 8 | 2 | is_flagged | 0 9 | 3 | is_flagged | 0 10 | 4 | is_flagged | 0 11 | 5 | is_flagged | 0 12 | 6 | is_flagged | 1 13 | 7 | is_flagged | 0 14 | 8 | is_flagged | 0 15 | 9 | is_flagged | 0 16 | 10 | is_flagged | 0 ``` I'm trying to count rows in **table1** where certain specific criteria is met, some of these conditionals. The WHERE condition must contain these criteria: ``` table1.type = 1 and table1.isActive = 1 and table1.isDeleted = 0 and table1_meta.options = 'is_flagged' and table1_meta.value = 0 ``` and this: ``` table1_meta.options = 'dont_ask' and table1_meta.value = 1 ``` and this: ``` table1_meta.options = 'always_ask' and table1_meta.value = 1 ``` so, how can I do that? SQLFiddle link: <http://sqlfiddle.com/#!2/2eb27b> Thanks.
2014/09/21
[ "https://Stackoverflow.com/questions/25961140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1720048/" ]
When using `CASE` the syntax is `WHEN "00" =>`, thus no use of `THEN`. The code is therefore: ``` CASE input24 IS WHEN "00" => output0 <= '1' ; output1 <= '0' ; output2 <= '0' ; output3 <= '0' ; ... ``` If `input24` is `std_logic_vector` you must when the case with a `WHEN OTHERS =>` to handle the remaining encodings of `input24`. The code is: ``` WHEN OTHERS => output0 <= 'X' ; output1 <= 'X' ; output2 <= 'X' ; output3 <= 'X' ; ``` For writing the assignment in a single like, still use `;` as statement separator, thus not `,` as shown in the question code, and then just remove the whitespace. The code is: ``` WHEN "01" => output0 <= '0'; output1 <= '1'; ... ``` For assign to multiple signals in one statement, the VHDL-2008 supports aggregate assignment, so if you are using VHDL-2008, you can write: ``` WHEN "10" => (output3, output2, output1, output0) <= std_logic_vector'("0100"); ``` For VHDL-2003, a solution may be to create an intermediate `output` signal as `std_logic_vector`, and then assign to this. Code can then be: ``` ... signal output : std_logic_vector(3 downto 0); begin ... WHEN "11" => output <= "1000"; ... output0 <= output(0); output1 <= output(1); output2 <= output(2); output3 <= output(3); ``` If the `output` is used, then the exact implementation where the `case` is just used to set the bit with number given in `input24` can be made with: ``` LIBRARY IEEE; USE IEEE.NUMERIC_STD.ALL; ARCHITECTURE syn OF mdl IS SIGNAL output : STD_LOGIC_VECTOR(3 DOWNTO 0); BEGIN PROCESS (input24) IS BEGIN output <= (OTHERS => '0'); output(TO_INTEGER(UNSIGNED(input24))) <= '1'; END PROCESS; output0 <= output(0); output1 <= output(1); output2 <= output(2); output3 <= output(3); END ARCHITECTURE; ``` Otherwise, if the `output` signal is not used, then the `case` can still be simplified through a default assign as '0' to the outputs, thus with the code: ``` ARCHITECTURE syn OF mdl IS BEGIN PROCESS (input24) IS BEGIN output0 <= '1' ; output1 <= '0' ; output2 <= '0' ; output3 <= '0' ; CASE input24 IS WHEN "00" => output0 <= '1' ; WHEN "01" => output1 <= '1'; WHEN "10" => output2 <= '1' ; WHEN "11" => output3 <= '1' ; WHEN OTHERS => output0 <= 'X'; output1 <= 'X'; output2 <= 'X'; output3 <= 'X'; END CASE; END PROCESS; END ARCHITECTURE; ```
I think the issue is the "then" ``` CASE input24 IS WHEN "00" => output0 <= '1' ; output1 <= '0' ; output2 <= '0' ; output3 <= '0' ; WHEN "01" => output0 <= '0' ; output1 <= '1' ; output2 <= '0' ; output3 <= '0' ; WHEN "10" => output0 <= '0' ; output1 <= '0' ; output2 <= '1' ; output3 <= '0' ; WHEN "11" => output0 <= '0' ; output1 <= '0' ; output2 <= '0' ; output3 <= '1' ; END CASE; ```
47,591,425
I am trying to place a button after an already existing button on another website. I'm trying to test it out in Chrome console, but can't figure it out. ``` var buttonPosition = document.getElementById('<button class="button black ">Black</button>'); ``` This is the button that I want to place my button behind. I then tried using the `.insertAdjacementHTML` function to get the button placed behind "button black" ``` buttonPosition.insertAdjacentHTML("afterend", "<button>Hello</button"); ``` Then I get the error message > > "Uncaught TypeError: buttonPosition.insertAdjacentHTML is not a > function > at :1:16" > > > This could be a rookie error, as I am very new to coding. Any help at all will be greatly appreciated. Thanks.
2017/12/01
[ "https://Stackoverflow.com/questions/47591425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9038538/" ]
That's because the value of your `getElementById()` is not an element's ID name but an element. Try adding an ID on your button then pass its ID name to `getElementById()` as the value, like this: HTML ``` <button class="button black" id="btn">Your button with an ID</button> ``` Javascript ``` var btn = document.getElementById('btn'); // The button itself with an ID of 'btn' var newButton = '<button>New button</button>'; // New button to be inserted btn.insertAdjacentHTML('afterend', newButton); ```
**"document.getElementById"** itself clarify that it want "id" of the element. As per your snippet `var buttonPosition = document.getElementById('<button class="button black ">Black</button>');` I can say that you are missing the "id" but the element itself. **Solution 1::** Provide the id to the button and then try to use that id like: ``` <button class="button black " id="btn">Black</button> ``` Javascript: ``` var buttonPosition = document.getElementById('btn'); ``` **Solution 2::** If you are not able to provide the id, then use the class name. ``` var buttonPosition = document.getElementsByClassName('button')[0]; var newButton = '<button>Button</button>'; buttonPosition.insertAdjacentHTML('afterend', newButton); ```
55,940,758
I have a components.js file that looks like this: ``` import { lookCoordinate } from './tools.js'; // I get: SyntaxError: Unexpected token { Vue.component('coordform', { template: `<form id="popup-box" @submit.prevent="process" v-if="visible"><input type="text" autofocus refs="coordinput" v-model="coords"></input></form>`, data() { { return { coords: '', visible: false } } }, created() { window.addEventListener('keydown', this.toggle) }, destroyed() { window.removeEventListener('keydown', this.toggle) }, methods: { toggle(e) { if (e.key == 'g') { if (this.visible) { this.visible = false; } else this.visible = true; } }, process() { lookCoordinate(this.coords) // Tried to import from tools.js } } }); ``` But I'm getting: `Uncaught SyntaxError: Unexpected token {` How do I import a function from another plain JS file and use it within a Vue component? Thanks.
2019/05/01
[ "https://Stackoverflow.com/questions/55940758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162414/" ]
You will get this error if trying to load a Javascript file without ES6 support enabled. The parser does not understand the syntax of `import` is as it begins parsing the file. Check your webpack or vue-cli settings to make sure that you are transpiling the code. For instance, a browser does not know what `import` means, and neither does plain old node unless enabling experimental support. You can also change it to: ``` const lookCoordinate = require('./tools.js').lookCoordinate; ``` and see if that gives you an error. That format does almost exactly the same thing. If using `import` from a browser, also enable module support, as suggested by Orkhan Alikhanov in the comments. ``` It is supported if you add script with type="module". e.g: <script type="module" src="main.js"></script> ```
Can you please try this without `{}`. ``` import { lookCoordinate } from './tools.js' ``` `{}` is used when you define multiple functions inside tools.js like, ``` import { lookCoordinate, lookCoordinate2 } from './tools.js' ```
55,940,758
I have a components.js file that looks like this: ``` import { lookCoordinate } from './tools.js'; // I get: SyntaxError: Unexpected token { Vue.component('coordform', { template: `<form id="popup-box" @submit.prevent="process" v-if="visible"><input type="text" autofocus refs="coordinput" v-model="coords"></input></form>`, data() { { return { coords: '', visible: false } } }, created() { window.addEventListener('keydown', this.toggle) }, destroyed() { window.removeEventListener('keydown', this.toggle) }, methods: { toggle(e) { if (e.key == 'g') { if (this.visible) { this.visible = false; } else this.visible = true; } }, process() { lookCoordinate(this.coords) // Tried to import from tools.js } } }); ``` But I'm getting: `Uncaught SyntaxError: Unexpected token {` How do I import a function from another plain JS file and use it within a Vue component? Thanks.
2019/05/01
[ "https://Stackoverflow.com/questions/55940758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162414/" ]
It is supported if you add script with `type="module"`: ``` <script type="module" src="main.js"></script> ```
Can you please try this without `{}`. ``` import { lookCoordinate } from './tools.js' ``` `{}` is used when you define multiple functions inside tools.js like, ``` import { lookCoordinate, lookCoordinate2 } from './tools.js' ```
22,750,482
I am writing a program that converts strings to linked lists, and alters them, in C. For some reason after I call my reverse function, and then print the list, it will print a new line before printing the reversed list. for example, say my 'list' contains... a->p->p->l->e->NULL in main() if i call... `print(list); print(list);` my output: ``` apple apple ``` BUT, in main() if i call... `print(list); list=reverse(list); print(list);` my output: ``` apple /*empty line*/ elppa ``` here is my rev() ``` node *rev(node *head){ node *r_head = NULL; while (head) { node *next = head->next; head->next = rev_head; r_head = head; head = next; } return r_head; } ```
2014/03/30
[ "https://Stackoverflow.com/questions/22750482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755244/" ]
[`Proc#curry`](http://ruby-doc.org/core-2.0/Proc.html#method-i-curry) > > Returns a curried proc. If the optional arity argument is given, it determines the number of arguments. A *curried* `proc` receives some arguments. If a *sufficient number* of arguments are supplied, it passes the supplied arguments to the original `proc` and *returns the result*. Otherwise, returns another curried proc that takes the rest of arguments. > > > Now coming to your code : ``` def f(x, y=2) x**y end a = method(:f).to_proc b = a.curry.curry[4] b.class # => Fixnum b # => 16 print 1.upto(5).map(&b) # wrong argument type Fixnum (expected Proc) (TypeError) ``` Look the documentation now - A *curried* `proc` receives some arguments. If a s\*ufficient number\* of arguments are supplied, it passes the supplied arguments to the original `proc` and *returns the result*. In your code, when you did `a.curry`, it returns a *curried proc*. Why? Because your method `f` has *one optional* and *one required* argument, but you didn't provide any. Now you call again `a.curry.curry[4]`, so on the previous *curried proc* which is still waiting for at-least one argument, this time you gave to it by using `curry[4]`. Now *curried* `proc` object gets called with `4, 2` as arguments, and evaluated to a `Fixnum` object `8` and assigned to `b`. **b is not a proc object**, rather a `Fixnum` object. Now, `1.upto(5).map(&b)` here - `&b` means, you are telling convert the `proc` object assgined to `b` to a block. But **NO**, `b` is not holding `proc` object, rather `Fixnum` object `8`. So Ruby **complains** to you. Here the message comes as **wrong argument type Fixnum (expected Proc) (TypeError)**. Now coming to your second part of code. Hold on!! :-) Look below : ``` def f(x, y) x**y end a = method(:f).to_proc b = a.curry.curry[4] b.class # => Proc b # => #<Proc:0x87fbb6c (lambda)> print 1.upto(5).map(&b) # >> [4, 16, 64, 256, 1024] ``` Now, your method `f` needs 2 mandatory argument `x, y`. `a.curry`, nothing you passed so a **curried proc** is returned. Again `a.curry.curry[4]`, humm you passed one required argument, which is `4` out of 2. So again a **curried proc** returned. Now `1.upto(5).map(&b)`, same as previous `b` expects a `proc`, and you fulfilled its need, as now b is `proc` object. `&b` converting it to a block as below : ``` 1.upto(5).map { |num| b.call(num) } ``` which in turn outputs as - `[4, 16, 64, 256, 1024]`. **Summary** Now suppose you defined a `proc` as below : ``` p = Proc.new { |x, y, z = 2| x + y + z } ``` Now you want to make `p` as *curried proc*. So you did `p.curry`. Remember you didn't pass any *arity* when called `curry`. Now point is a *curried proc* will wait to evaluate and return the result of `x + y + z`, unless and until, you are giving it all the required arguments it needs to produce it results. That means `p.curry` gives you a *curried proc* object, then if you do `p.curry[1]` ( mean you are now passing value to `x` ), again you got a *curried proc*. Now when you will write `p.curry[1][2]`, all required arguments you passed ( mean you are now passing value to `y` ), so now `x + y + z` will be called.
You are using `.map`, it requires a `block` of type `proc`. In your first case `b` returns `16` as `y=2` uses default value `2` for exponent when you are sending single argument using `curry`. `b` returning `16` is not a `proc` `object` and can not be used with `.map`. `Curry` when used with a proc with `sufficient arguments`, it executes original proc and returns a result. Which is happening in OP's first case with curried proc passed with 4 as only argument and default `y=2 in f(x, y=2)` getting used and resulting in `16` as return value. 16 being `Fixnum` can not be used with enumerator `map` method. `Curry` when used with insufficient arguments return a `proc`. So in case 2 when `f(x, y)` is used curried `a` is passed only single argument resulting in a `proc` object `{|e| 4 ** e}` being returned and which gets executed by `map` method.
2,509,233
Part of a complex query that our app is running contains the lines: ...(inner query) ``` SELECT ... NULL as column_A, NULL as column_B, ... FROM ... ``` This syntax of creating columns with **null** values is not allowed in DB2 altough it is totally OK in **MSSQL** and **Oracle** DBs. Technically I can change it to: ``` '' as column_A, '' as column_B, ``` But this doesn't have exactly the same meaning and can damage our calculation results. How can I create columns with null values in DB2 using other syntax??
2010/03/24
[ "https://Stackoverflow.com/questions/2509233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242389/" ]
DB2 is strongly typed, so you need to tell DB2 what kind of column your NULL is: ``` select ... cast(NULL as int) as column_A, cast(NULL as varchar(128)) as column_B, ... FROM ... ```
For Db2 LUW, since version 9.7, you can (if you like) use the `NULL` value without explicitly casting it to a particular data type. `NULL` on it's own will be implicitly cast to `VARCHAR(1)`. This knowledge center page will show what happens in other cases: [Determining data types of untyped expressions](https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0053561.html "https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0053561.html") Examples ``` db2 "describe values ( NULL, + NULL, NULL || NULL )" Column Information Number of columns: 3 SQL type Type length Column name Name length -------------------- ----------- ------------------------------ ----------- 449 VARCHAR 1 1 1 997 DECFLOAT 16 2 1 449 VARCHAR 508 3 1 ``` and ``` db2 "describe values NULL, 1" Column Information Number of columns: 1 SQL type Type length Column name Name length -------------------- ----------- ------------------------------ ----------- 497 INTEGER 4 1 1 ```
12,823
I've been trying to create a short-cut key for grabbing part of the screen. If I run the command `/usr/bin/gnome-screenshot --area` the program I want runs and does what I want. When I createa a custom action in the keyboard shortcuts menu, and I activate the command (using ctrl-prnscr) the command fires up but behaves as though the `--area` option isn't there (it grabs the whole screen instead of giving me a cursor to choose with). If I run `ps -eaf |grep screen` I get: ``` $ ps -eaf |grep screen yfarjoun 2082 1 0 Oct29 ? 00:00:21 gnome-screensaver yfarjoun 17730 1 0 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17735 17730 1 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17741 2599 0 17:34 pts/0 00:00:00 grep --color=auto screen ``` So the option is definitely transfered to the command.... Why is it not honoring the option? How can I fix this?
2010/11/12
[ "https://askubuntu.com/questions/12823", "https://askubuntu.com", "https://askubuntu.com/users/4863/" ]
It works for me when pressing the shortcut twice (fast). This seems to have worked at some point but doesn't anymore (see [this thread](http://ubuntuforums.org/showthread.php?t=1199669) at ubuntuforums.org - it doesn't work for me, with or without the '-i' switch). There's already a bug report opened: <https://bugs.launchpad.net/ubuntu/+source/gnome-utils/+bug/549935>
An alternative is to use [Shutter](http://shutter-project.org/) and: 1. Set Preferences -> Advanced to start with the selection size and location you want. 2. Set Preferences -> Keyboard to Capture with Selection. When you press your shortcut key the screen will freeze and the default selection will be made. You can either press Enter to accept the screenshot, Esc to cancel or adjust the selection manually. You can save different default selections as profiles. It has other nice features, such as basic editing and configurable filenames too.
12,823
I've been trying to create a short-cut key for grabbing part of the screen. If I run the command `/usr/bin/gnome-screenshot --area` the program I want runs and does what I want. When I createa a custom action in the keyboard shortcuts menu, and I activate the command (using ctrl-prnscr) the command fires up but behaves as though the `--area` option isn't there (it grabs the whole screen instead of giving me a cursor to choose with). If I run `ps -eaf |grep screen` I get: ``` $ ps -eaf |grep screen yfarjoun 2082 1 0 Oct29 ? 00:00:21 gnome-screensaver yfarjoun 17730 1 0 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17735 17730 1 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17741 2599 0 17:34 pts/0 00:00:00 grep --color=auto screen ``` So the option is definitely transfered to the command.... Why is it not honoring the option? How can I fix this?
2010/11/12
[ "https://askubuntu.com/questions/12823", "https://askubuntu.com", "https://askubuntu.com/users/4863/" ]
It works for me when pressing the shortcut twice (fast). This seems to have worked at some point but doesn't anymore (see [this thread](http://ubuntuforums.org/showthread.php?t=1199669) at ubuntuforums.org - it doesn't work for me, with or without the '-i' switch). There's already a bug report opened: <https://bugs.launchpad.net/ubuntu/+source/gnome-utils/+bug/549935>
In 12.04 (at least), the default shortcut is `Shift`+`PrtScr`.
12,823
I've been trying to create a short-cut key for grabbing part of the screen. If I run the command `/usr/bin/gnome-screenshot --area` the program I want runs and does what I want. When I createa a custom action in the keyboard shortcuts menu, and I activate the command (using ctrl-prnscr) the command fires up but behaves as though the `--area` option isn't there (it grabs the whole screen instead of giving me a cursor to choose with). If I run `ps -eaf |grep screen` I get: ``` $ ps -eaf |grep screen yfarjoun 2082 1 0 Oct29 ? 00:00:21 gnome-screensaver yfarjoun 17730 1 0 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17735 17730 1 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17741 2599 0 17:34 pts/0 00:00:00 grep --color=auto screen ``` So the option is definitely transfered to the command.... Why is it not honoring the option? How can I fix this?
2010/11/12
[ "https://askubuntu.com/questions/12823", "https://askubuntu.com", "https://askubuntu.com/users/4863/" ]
In 12.04 (at least), the default shortcut is `Shift`+`PrtScr`.
An alternative is to use [Shutter](http://shutter-project.org/) and: 1. Set Preferences -> Advanced to start with the selection size and location you want. 2. Set Preferences -> Keyboard to Capture with Selection. When you press your shortcut key the screen will freeze and the default selection will be made. You can either press Enter to accept the screenshot, Esc to cancel or adjust the selection manually. You can save different default selections as profiles. It has other nice features, such as basic editing and configurable filenames too.
10,724,253
This should be pretty simple, yet it's blowing up. Any ideas? ``` d = BigDecimal.new("2.0") YAML::load({:a => d}.to_yaml) TypeError: BigDecimal can't be coerced into BigDecimal from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `block in <module:IRB>' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `call' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `inspect_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/context.rb:260:in `inspect_last_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:311:in `output_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:160:in `block (2 levels) in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:273:in `signal_status' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:156:in `block in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:243:in `block (2 levels) in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:155:in `eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:70:in `block in start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'Maybe IRB bug! ```
2012/05/23
[ "https://Stackoverflow.com/questions/10724253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507718/" ]
This is a bug that has been [reported](https://github.com/tenderlove/psych/issues/31) and [fixed](https://github.com/tenderlove/psych/commit/33ce8650bac29190dde937b1b7d3e21fd06926e7). The best solution would be upgrade to the latest Ruby (the fix is in patch level 194 onwards). If you can’t upgrade your Ruby version, you can get the fix by installing the [Psych gem](https://rubygems.org/gems/psych). If you do this you’ll need to add `gem 'psych'` before you `require 'yaml'` (or add it to your `Gemfile` if you’re using Bundler) to load the code from the gem rather than from the standard library..
Yeah, I ran into that once. Here's a version of what I did: [YAML & BigDecimal workaround](http://blog.induktiv.at/archives/6-YAML-and-BigDecimal-a-temporary-solution.html)
10,724,253
This should be pretty simple, yet it's blowing up. Any ideas? ``` d = BigDecimal.new("2.0") YAML::load({:a => d}.to_yaml) TypeError: BigDecimal can't be coerced into BigDecimal from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `block in <module:IRB>' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `call' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `inspect_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/context.rb:260:in `inspect_last_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:311:in `output_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:160:in `block (2 levels) in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:273:in `signal_status' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:156:in `block in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:243:in `block (2 levels) in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:155:in `eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:70:in `block in start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'Maybe IRB bug! ```
2012/05/23
[ "https://Stackoverflow.com/questions/10724253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507718/" ]
This is a bug that has been [reported](https://github.com/tenderlove/psych/issues/31) and [fixed](https://github.com/tenderlove/psych/commit/33ce8650bac29190dde937b1b7d3e21fd06926e7). The best solution would be upgrade to the latest Ruby (the fix is in patch level 194 onwards). If you can’t upgrade your Ruby version, you can get the fix by installing the [Psych gem](https://rubygems.org/gems/psych). If you do this you’ll need to add `gem 'psych'` before you `require 'yaml'` (or add it to your `Gemfile` if you’re using Bundler) to load the code from the gem rather than from the standard library..
Here's David's answer, updated to work in 1.9.3 thanks to [this related question](https://stackoverflow.com/questions/6530412/cant-define-singleton-method-encode-with-for-bigdecimal): ``` require 'yaml' require 'bigdecimal' YAML::ENGINE.yamler= 'syck' class BigDecimal def to_yaml(opts={}) YAML::quick_emit(object_id, opts) do |out| out.scalar("tag:induktiv.at,2007:BigDecimal", self.to_s) end end end YAML.add_domain_type("induktiv.at,2007", "BigDecimal") do |type, val| BigDecimal.new(val) end x = BigDecimal.new("2.0") puts x.to_yaml y = YAML.load(x.to_yaml) puts x == y ```
32,878,678
Currently incredibly confused about how I would go about moving the logic for determining if a string is a palindrome from the main method into a method named checkPalindrome? My method should have a single String argument and return a boolean value, but I'm still unsure of how to do this. ``` import java.util.Scanner; public class PalindromeCheckMethod { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a String: "); String s = input.nextLine(); boolean isPalindrome = checkPalindrome(s); String msg = "not a palindrome"; if (isPalindrome) { msg = "a palindrome"; } System.out.printf("%s is %s.%n", s, msg); s = s.toLowerCase(); String resultString = ""; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) resultString += s.charAt(i); } s = resultString; int low = 0; int high = s.length() - 1; if (high >= 0) { while (low < high) { if (s.charAt(low) != s.charAt(high)) { isPalindrome = false; break; } low++; high--; } } else { isPalindrome = false; } if (isPalindrome) System.out.println(s + " is a palindrome. "); else System.out.println(s + " is not a palindrome. "); } private static boolean checkPalindrome(String s) { return false; } } ```
2015/10/01
[ "https://Stackoverflow.com/questions/32878678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016178/" ]
``` static boolean checkPalindrome(String str) { int strEndPoint=str.length()-1; int strStartPoint=0; boolean isPalindrome=true; while(strStartPoint<=strEndPoint) { if(str.charAt(strStartPoint)!=str.charAt(strEndPoint)) { isPalindrome=false; break; } strStartPoint++; strEndPoint--; } return isPalindrome; ``` }
Well, I would use a [`StringBuilder`](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) and implement a method of that description with something like, ``` static boolean checkPalindrome(final String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString().equalsIgnoreCase(s); } ``` But you could certainly replace my implementation with your implementation (I did not validate your implementation). To call the method (and perhaps take advantage of formatted io) you could use something like ``` public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a String: "); String s = input.nextLine(); boolean isPalindrome = checkPalindrome(s); String msg = "not a palindrome"; if (isPalindrome) { msg = "a palindrome"; } System.out.printf("%s is %s.%n", s, msg); } ```
32,878,678
Currently incredibly confused about how I would go about moving the logic for determining if a string is a palindrome from the main method into a method named checkPalindrome? My method should have a single String argument and return a boolean value, but I'm still unsure of how to do this. ``` import java.util.Scanner; public class PalindromeCheckMethod { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a String: "); String s = input.nextLine(); boolean isPalindrome = checkPalindrome(s); String msg = "not a palindrome"; if (isPalindrome) { msg = "a palindrome"; } System.out.printf("%s is %s.%n", s, msg); s = s.toLowerCase(); String resultString = ""; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) resultString += s.charAt(i); } s = resultString; int low = 0; int high = s.length() - 1; if (high >= 0) { while (low < high) { if (s.charAt(low) != s.charAt(high)) { isPalindrome = false; break; } low++; high--; } } else { isPalindrome = false; } if (isPalindrome) System.out.println(s + " is a palindrome. "); else System.out.println(s + " is not a palindrome. "); } private static boolean checkPalindrome(String s) { return false; } } ```
2015/10/01
[ "https://Stackoverflow.com/questions/32878678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016178/" ]
``` static boolean checkPalindrome(String str) { int strEndPoint=str.length()-1; int strStartPoint=0; boolean isPalindrome=true; while(strStartPoint<=strEndPoint) { if(str.charAt(strStartPoint)!=str.charAt(strEndPoint)) { isPalindrome=false; break; } strStartPoint++; strEndPoint--; } return isPalindrome; ``` }
Why dont you think simple. Precisely, mirror image of the chars would be same and if it is not it is not palindrome. When you cross middle of the array without finding a difference it is an absolute palindrome. Check this out. ``` int len = str.getLenght(); int i = 0; do { if (str.get(i) == str.get(len-1-i)) i++; else { print("NOT a palindrome"); break; } } while (i < len-1-i) ; if (i < len-1-i) print("NOT a palindrome"); ```
33,421
I have a acquaintance who lives in the United States with a young daughter who will be starting Kindergarten next year. However, her preschool feels she should be "held back", because among other things, she does not appear to be interested in writing her name. I do not live in the United States, so perhaps I am in the wrong, but is this a scam? It certainly sounds like a scam. Preschools are paid institutions, while Kindergarten is free (public school system). In my country, you do not need to "graduate" kindergarten to be accepted into 1st grade. Thus, holding someone back from kindergarten sounds ridiculous. Even if she performs poorly, I don't see how this would harm her academic career. I do feel that delaying her education by a year will be detrimental. I am advising this acquaintance that this sounds like a scam, but I could be in the wrong. What is consensus on this?
2018/03/07
[ "https://parenting.stackexchange.com/questions/33421", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/14007/" ]
I'd say in this case the preschool is offering advice and not necessarily perpetrating a scam, at least by a simple definition. Preschool is optional in the USA. It can be free if you meet some wage requirements, or if you're part of a church, work, or academic program that offers it as incentive or grace. You can't fail per say, but part of their job is to evaluate growth and maturity. In our district, the Kindergarten entry requirement is you must be at least 5 years old with a cut off birthday of something like September 1st. If you don't meet that you can take an early entrance exam which involves writing your name, following simple instructions, ability to walk single file from point A to point B, etc. I saw a kid fail in the lobby because he cried when it came time to separate from family. They're looking for a certain maturity level as well, and a preschool will have some idea of the expectations. The USA, which is ranked something like 14th in the world for education, allows for districts like ours to have zero say in whether or not a child is held back in one of the K-12 levels. You can get straight F's and the parents can still advance their child. So even in official education levels the idea of being held back is more of a suggestion than anything. Unless the preschool advisor also happens to own the institution, I'd say they probably have no real benefit from trying to scam you into staying longer. In your case, I would say that if they meet the age requirements, then enroll them in Kindergarten. Kinder is not a daycare. They have an actual curriculum and writing your name is a part of it.
Technically, no, you can't fail pre-school in the US. If you are of age and your parents want to enroll you, there's nothing a pre-school can do to prevent that. However, that does NOT mean that this is a scam. There are plenty of good reasons to hold a child back a year before they start kindergarten if you suspect they are not ready. Children who are born just before the cutoff and end up being on the extreme young end of the age range for their class are significantly more likely to get [diagnosed with ADHD](https://www.livescience.com/54007-birthdate-adhd-diagnosis.html). They are also less likely to do well in sports. If a parent has a good reason to believe that their child is not ready for Kindergarten, there's little harm and potentially much good to be had in holding the child back a year. A personal anecdote. When my son was two, he was enrolled in a pre-school program for three year olds. The entire year, we kept hearing about how he was delayed. The next year, my wife was on maternity leave and so he stayed at home. The year after, he was in a class that was right for his age. The way his birthday lined up, he ended up being the oldest in the class. All that year, we heard about how advanced and smart he was.
23,123,035
Ideally I'd like `ctrl`+`space` to bring up "search everywhere" from anywhere in windows (8.1) and also dismiss it if it's already active (with something like #IfWinActive ...). So far I've been able to make `ctrl`+`space` simulate pressing the `winkey` with the following AutoHotKey script: ``` <^Space:: KeyWait Ctrl Send {RWin} return ``` ...but not `winkey`+`s`. It feels sort of hackish anyway because it doesn't initiate "on press." It only initiates once I've released the `ctrl` key. P.S. If I can't get this figured out I'm taking suggestions for a good third party launcher application --- EDIT: Thanks to Robert. Here is the result: ``` <^Space:: SendInput {RWin Down}s{RWin Up} return ```
2014/04/17
[ "https://Stackoverflow.com/questions/23123035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/624041/" ]
One way to do this is through: ``` SendInput, {RWin Down}s{RWin Up} ```
Really simple: ``` ^Space::SendInput, #s ```
55,062,489
I have queries that can return large resultsets (> 100K rows). I need to display the number of results to the user and the user is able to page through the results in our application. However, nobody is going to page through 100K items when 25 are displayed on a page. So I want to limit the number of pageable results to 5K while still displaying the total number of results to the user. Of course, I can fire two seperate queries to the database: one counting all results, one returning the TOP(5000). But the queries can be expensive. Is there a smart way to combine these two queries into one? The queries below are over simplified: ``` SELECT COUNT(*) FROM TABLE WHERE field = 1; SELECT TOP(5000) * FROM TABLE Where field = 1; ``` Can anyone help?
2019/03/08
[ "https://Stackoverflow.com/questions/55062489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207701/" ]
Add max rating programmatically , It should fix the issue ``` ratingBar.setMax(5); ``` **Edit:** replace your rating bar with and check ``` <LinearLayout android:layout_width="wrap_content" android:layout_height="45dp" android:layout_alignParentEnd="true" android:layout_below="@+id/eventsubtitle"> <RatingBar android:layout_width="wrap_content" android:layout_height="45dp" android:id="@+id/ratingbar" android:stepSize="1.0"/> </LinearLayout> ```
ratingBar.setStepSize(1f); worked for me
10,876,621
Consider a simple example like this which links two sliders using signals and slots: ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) vbox.addWidget(sone) stwo = QSlider(Qt.Horizontal) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ``` How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values: ``` sone.setRange(0,99) sone.setValue(0) ``` And slider two would be initialized with these values: ``` stwo.setRange(0,99) stwo.setValue(99) ``` And then the value of stwo would be `99 - sone.sliderPosition`. How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.
2012/06/04
[ "https://Stackoverflow.com/questions/10876621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463994/" ]
You can connect signals to functions that do things. Your code isn't structured to do that easily and required refactoring, so you can do it the easy way: ``` stwo.setInvertedAppearance(True) sone.valueChanged.connect(stwo.setValue) ```
Here's the way I did it. I added this class which reimplements setValue. (I got the idea from <http://zetcode.com/tutorials/pyqt4/eventsandsignals/>) ``` class MySlider(QSlider): def __init__(self): QSlider.__init__(self, Qt.Horizontal) def setValue(self, int): QSlider.setValue(self, 99-int) ``` Here's the complete code. Is this a good approach? ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MySlider(QSlider): def __init__(self): QSlider.__init__(self, Qt.Horizontal) def setValue(self, int): QSlider.setValue(self, 99-int) class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) sone.setRange(0,99) sone.setValue(0) vbox.addWidget(sone) stwo = MySlider() stwo.setRange(0,99) stwo.setValue(0) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) self.setLayout(vbox) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ```
10,876,621
Consider a simple example like this which links two sliders using signals and slots: ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) vbox.addWidget(sone) stwo = QSlider(Qt.Horizontal) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ``` How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values: ``` sone.setRange(0,99) sone.setValue(0) ``` And slider two would be initialized with these values: ``` stwo.setRange(0,99) stwo.setValue(99) ``` And then the value of stwo would be `99 - sone.sliderPosition`. How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.
2012/06/04
[ "https://Stackoverflow.com/questions/10876621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463994/" ]
Your example is a bit broken, because you forgot to set the parent of the layout, and also to save the slider widgets as member attributes to be accessed later... But to answer your question, its really as simple as just pointing your connection to your own function: ``` class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout(self) self.sone = QSlider(Qt.Horizontal) self.sone.setRange(0,99) self.sone.setValue(0) vbox.addWidget(self.sone) self.stwo = QSlider(Qt.Horizontal) self.stwo.setRange(0,99) self.stwo.setValue(99) vbox.addWidget(self.stwo) self.sone.valueChanged.connect(self.sliderChanged) def sliderChanged(self, val): self.stwo.setValue(self.stwo.maximum() - val) ``` Note how `sliderChanged()` has the same signature as the original `setValue()` slot. Instead of connecting one widget directly to the other, you connect it to a custom method and then transform the value to what you want, and act how you want (setting a custom value on `stwo`)
You can connect signals to functions that do things. Your code isn't structured to do that easily and required refactoring, so you can do it the easy way: ``` stwo.setInvertedAppearance(True) sone.valueChanged.connect(stwo.setValue) ```
10,876,621
Consider a simple example like this which links two sliders using signals and slots: ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) vbox.addWidget(sone) stwo = QSlider(Qt.Horizontal) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ``` How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values: ``` sone.setRange(0,99) sone.setValue(0) ``` And slider two would be initialized with these values: ``` stwo.setRange(0,99) stwo.setValue(99) ``` And then the value of stwo would be `99 - sone.sliderPosition`. How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.
2012/06/04
[ "https://Stackoverflow.com/questions/10876621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463994/" ]
Your example is a bit broken, because you forgot to set the parent of the layout, and also to save the slider widgets as member attributes to be accessed later... But to answer your question, its really as simple as just pointing your connection to your own function: ``` class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout(self) self.sone = QSlider(Qt.Horizontal) self.sone.setRange(0,99) self.sone.setValue(0) vbox.addWidget(self.sone) self.stwo = QSlider(Qt.Horizontal) self.stwo.setRange(0,99) self.stwo.setValue(99) vbox.addWidget(self.stwo) self.sone.valueChanged.connect(self.sliderChanged) def sliderChanged(self, val): self.stwo.setValue(self.stwo.maximum() - val) ``` Note how `sliderChanged()` has the same signature as the original `setValue()` slot. Instead of connecting one widget directly to the other, you connect it to a custom method and then transform the value to what you want, and act how you want (setting a custom value on `stwo`)
Here's the way I did it. I added this class which reimplements setValue. (I got the idea from <http://zetcode.com/tutorials/pyqt4/eventsandsignals/>) ``` class MySlider(QSlider): def __init__(self): QSlider.__init__(self, Qt.Horizontal) def setValue(self, int): QSlider.setValue(self, 99-int) ``` Here's the complete code. Is this a good approach? ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MySlider(QSlider): def __init__(self): QSlider.__init__(self, Qt.Horizontal) def setValue(self, int): QSlider.setValue(self, 99-int) class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) sone.setRange(0,99) sone.setValue(0) vbox.addWidget(sone) stwo = MySlider() stwo.setRange(0,99) stwo.setValue(0) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) self.setLayout(vbox) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ```
67,782,043
First of all ============ I searched for it for a long time, and I have **already seen** many questions including the two: [How to draw Arc between two points on the Canvas?](https://stackoverflow.com/questions/11131954/how-to-draw-arc-between-two-points-on-the-canvas) [How to draw a curved line between 2 points on canvas?](https://stackoverflow.com/questions/37432826/how-to-draw-a-curved-line-between-2-points-on-canvas/37446243#37446243) Although they seem like the same question, I'm very sure they are **not** the same. In the first question, the center of the circle is known, and in the second, it draws a Bezier curve not an arc. Description =========== Now we have two points `A` and `B` and the curve radius given, how to draw the arc as the image shows? [![image](https://i.stack.imgur.com/RMxUP.png)](https://i.stack.imgur.com/RMxUP.png) Since `Path.arcTo`'s required arguments are `RectF`, `startAngle` and `sweepAngle`, there seems hardly a easy way. My current solution =================== I now have my solution, I'll show that in the answer below. Since the solution is so complex, I wonder if there is a easier way to solve it?
2021/06/01
[ "https://Stackoverflow.com/questions/67782043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12611441/" ]
Probably there is no easier way. All what can do would be to refine your solution by geometrical approach. Since the center of circle is always on the perpendicular bisector of the chord, it's not required to solve so generalized equations. By the way, it's not clear how you defined Clockwise/Counter-clockwise. Arc's winding direction should be determined independently of node-placements (=A, B's coordinates). As is shown in the figure below, on the straight path from A to B, the center O is to be placed righthandside(CW) or lefthandside(CCW). That's all. [![Path.ArcTo with radius and end-points](https://i.stack.imgur.com/tqDep.png)](https://i.stack.imgur.com/tqDep.png) And, some more aspects to be altered: 1. It's better to calculate startAngle by atan2(). Because acos() has singularity at some points. 2. It's also possible to calculate sweepAngle with asin(). After all the code can be slightly simplified as follows. ``` @Throws(Exception::class) private fun Path.arcFromTo2( x1: Float, y1: Float, x2: Float, y2: Float, r: Float, clockwise: Boolean = true ) { val d = PointF((x2 - x1) * 0.5F, (y2 - y1) * 0.5F) val a = d.length() if (a > r) throw Exception() val side = if (clockwise) 1 else -1 val oc = sqrt(r * r - a * a) val ox = (x1 + x2) * 0.5F - side * oc * d.y / a val oy = (y1 + y2) * 0.5F + side * oc * d.x / a val startAngle = atan2(y1 - oy, x1 - ox) * 180F / Math.PI.toFloat() val sweepAngle = side * 2.0F * asin(a / r) * 180F / Math.PI.toFloat() arcTo( ox - r, oy - r, ox + r, oy + r, startAngle, sweepAngle, false ) } ```
**1. find the center of the circle** This can be solved by a binary quadratic equation, as the image shows: [![center](https://i.stack.imgur.com/kNXZw.png)](https://i.stack.imgur.com/kNXZw.png) Though there are other solutions, anyway, now the position of circle center is known. **2. calculate start angle and sweep angle** According to the circle center, `RectF` is easy to know. Now calculate `startAngle` and `sweepAngle`. [![calculate angle](https://i.stack.imgur.com/x9Lgd.png)](https://i.stack.imgur.com/x9Lgd.png) Via geometric methods, we can calculate the `startAngle` and `sweepAngle`: ```kotlin val startAngle = acos((x1 - x0) / r) / Math.PI.toFloat() * 180 val endAngle = acos((x2 - x0) / r) / Math.PI.toFloat() * 180 val sweepAngle = endAngle - startAngle ``` In this case, `x1` is the x-coordinary of point A, `x2` if the x-coordinary of point B, and `r` is the curve radius of the arc. (*There are possible results, the other is `[-startAngle, startAngle - endAngle]`. Choose one according to actual situation.*) Thus, we get all the required arguments for `Path.arcTo` method and we can draw the arc now. **3. kotlin code** the entire code of the help function: ```kotlin /** * Append the arc which is starting at ([x1], [y1]), ending at ([x2], [y2]) * and with the curve radius [r] to the path. * The Boolean value [clockwise] shows whether the process drawing the arc * is clockwise. */ @Throws(Exception::class) private fun Path.arcFromTo( x1: Float, y1: Float, x2: Float, y2: Float, r: Float, clockwise: Boolean = true ) { val c = centerPos(x1, y1, x2, y2, r, clockwise) // circle centers // RectF borders val left = c.x - r val top = c.y - r val right = c.x + r val bottom = c.y + r val startAngle = acos((x1 - c.x) / r) / Math.PI.toFloat() * 180 val endAngle = acos((x2 - c.x) / r) / Math.PI.toFloat() * 180 arcTo( left, top, right, bottom, if (clockwise) startAngle else -startAngle, if (clockwise) endAngle - startAngle else startAngle - endAngle, false ) } // use similar triangles to calculate circle center @Throws(Exception::class) private fun centerPos( x1: Float, y1: Float, x2: Float, y2: Float, r: Float, clockwise: Boolean ): Point { val ab = ((x1 - x2).p2 + (y1 - y2).p2).sqrt if (ab > r * 2) throw Exception("No circle fits the condition.") val a = ab / 2 val oc = (r.p2 - a.p2).sqrt val dx = (oc * (y2 - y1) / ab).absoluteValue.toInt() val dy = (oc * (x2 - x1) / ab).absoluteValue.toInt() val cx = ((x1 + x2) / 2).toInt() val cy = ((y1 + y2) / 2).toInt() return if (x1 >= x2 && y1 >= y2 || x1 <= x2 && y1 <= y2) if (clockwise) Point(cx + dx, cy - dy) else Point(cx - dx, cy + dy) else if (clockwise) Point(cx - dx, cy - dy) else Point(cx + dx, cy + dy) } ```
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
If you want to use Groovy on the server-side and GWT for the UI, that is certainly possible. You can use Grails (a Groovy web framework on the server), and the [Grails GWT plugin](http://www.grails.org/plugin/gwt) to help you integrate GWT with this framework.
I don't think so, because the GWT compiler is basically a [Java to JavaScript *source*](http://java.dzone.com/news/understanding-gwt-compiler) compiler (it would be possible if the GWT compiler needed Java bytecode). You can use Groovy on the server side though.
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
I don't think so, because the GWT compiler is basically a [Java to JavaScript *source*](http://java.dzone.com/news/understanding-gwt-compiler) compiler (it would be possible if the GWT compiler needed Java bytecode). You can use Groovy on the server side though.
I have also wondered this, as it would be very nice. Vaadin essentially does this and you can use their plugin: <http://grails.org/plugin/vaadin> Doing it this model, though, it is compiling components into Javascript and delivering from the server. But unlike GWT components, these are calling back to the server every time you touch the API (though of course with Vaadin you can use GWT components as well).
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
If you want to use Groovy on the server-side and GWT for the UI, that is certainly possible. You can use Grails (a Groovy web framework on the server), and the [Grails GWT plugin](http://www.grails.org/plugin/gwt) to help you integrate GWT with this framework.
Right now you cant use Groovy on the client side. One big reason is that Groovy relies a lot on introspection, and this is not available on GWT.
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
If you want to use Groovy on the server-side and GWT for the UI, that is certainly possible. You can use Grails (a Groovy web framework on the server), and the [Grails GWT plugin](http://www.grails.org/plugin/gwt) to help you integrate GWT with this framework.
I have also wondered this, as it would be very nice. Vaadin essentially does this and you can use their plugin: <http://grails.org/plugin/vaadin> Doing it this model, though, it is compiling components into Javascript and delivering from the server. But unlike GWT components, these are calling back to the server every time you touch the API (though of course with Vaadin you can use GWT components as well).
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
Right now you cant use Groovy on the client side. One big reason is that Groovy relies a lot on introspection, and this is not available on GWT.
I have also wondered this, as it would be very nice. Vaadin essentially does this and you can use their plugin: <http://grails.org/plugin/vaadin> Doing it this model, though, it is compiling components into Javascript and delivering from the server. But unlike GWT components, these are calling back to the server every time you touch the API (though of course with Vaadin you can use GWT components as well).
55,466,506
I'm new to Hibernate and I've a basic question. I have two entity classes User and Comments with the relationship defined as One toMany from user to comments and manytoOne from comments to user. Now, if my UI sends me back some comments with comment\_text and user\_id what is the best way to save it? By defining @ManyToOne Private User user; I need to use the whole user object to store this information however, all I need is to store comment with user\_id in the table and query user information when I need it. I'm new to Hibernate so it may be really just basics but can someone please help me?
2019/04/02
[ "https://Stackoverflow.com/questions/55466506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11296633/" ]
The relationship between users and comments is many-to-many, so you can try to create a table with the following fields: * key * commenter * commented * comment-text
You question touches 2 very big points. Having a fully connected database model is a recipe for low performance and quite some entanglement. From a design point of view, you probably don't want to change a user when a comment is created, updated or deleted. So from Hibernate, probably you can skip the relationship between `Comment` and `User` and get the user information in another way when you load the comments (as I assume that you want to show a user name next to the comment). So when you receive a piece of text and a user id, you can store that straight away, but do remember to check that the user id is actually the one posting the comment, and not someone sending fabricated data. Now thinking from the user point of view. Do you always need the comment information when you load a user? (Hibernate will load the comment data lazily, as all \*toMany relationships are lazy by default). From a design point of view, the more connected your entities are the more chances you have something will break when you do a small change. Something that helps me in this situations is to find out what data is changed together or has interdependent constrains. If there are none, then those objects can be separated. And in the case you need to improve the performance, you could have some read-only entities that map all of the data you need for some of your views. I'll suggest you to read the book [Implementing Domain-Driven Design](http://www.informit.com/store/implementing-domain-driven-design-9780321834577) as it touches on these topics and it's a fantastic source of good advice about design and happens to use Java+Hibernate in the examples!
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
When Queenie met with Grindelwald earlier in the movie, he swayed her by hinting that the current laws banning marriage between Muggles and Wizards/Witches would no longer exist and that if she were to follow him, that she would be free to marry who she wished.
This is just my opinion. Think about what time period we're talking about. It's the 1920s. If Queenie were perhaps pregnant, that would explain her despair on the streets of Paris, her frustration at Jacob refusing to marry her and her feeling like she didn't matter. Women in pre 1970s were treated horribly if they were pregnant without being married and Queenie finds herself wanting to marry a man she would be imprisoned for dating, let alone having a child with. She cannot go back to America and Jacob won't marry her for fear she'll get in trouble. That makes her motivation more understandable at least to me.
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
Because she heard what she wanted to hear ----------------------------------------- ***To avoid a spoiler-formatting "hell", this post contains unprotected spoiler information*** In *Crimes of Grindelwald* > > Queenie > > > join forces with Grindelwald at the end. As others have suggested before, Queenie was in love with a Non-Wizard and by the standards of the late 20's Wizarding Society, marrying between Muggles and Wizards was considered a taboo; maybe it was also forbidden. Quoting a dialogue from the movie, > > **JACOB:** Okay, wait. We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail, sweetheart. I can’t have that. They don’t like people like me marrying people like you. I ain’t a wizard. I’m just me. > > > -Fantastic Beasts: The Crimes of Grindelwald - The Original Script > > > For this sole reason, at the beginning of the movie, she left him and throughout it, she seemed to be deeply affected by her choice. Later, when she met Grindelwald in Paris, she surrendered all her defenses. She heard what she wanted to hear. Of a world that she can leave freely without the "limitations" of the past. Grindelwald, after all, is mentioned to have been an **extremely charismatic** man, who not only persuaded thousands to join him, but persuaded none other than **Albus Dumbledore himself** in his quest to rule Muggles for the *Greater Good*. If Albus Dumbledore was deceived that easy, what chances did poor Queenie had? The real question would be *why* Grindelwald was so hesitant in making her join him. For that I guess, we will have to wait to find out.
It’s unclear exactly but it would appear to be either because Grindelwald persuaded or enchanted her. I’ll detail reasons for both below: Both ==== Grindelwald is described as being very persuasive and having a silver tongue. This could be a reason to say he is either very persuasive or is enchanting people. > > **PICQUERY** It was necessary. He’s extremely powerful. We’ve had to change his guard three times—he’s very... persuasive. So we removed his tongue. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **SPIELMAN** No more silver tongue, eh? > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Persuasion ========== Grindelwald appears to have persuaded Abernathy to join his cause, this shows how persuasive he is and lays some foreshadowing down for persuasion, like he does to Credence at the end of the film too. > > *GRINDELWALD appears at the door and nods to ABERNATHY. He throws the door open so the water pours out—along with the two remaining AURORS. GRINDELWALD clambers inside and retrieves the vial from ABERNATHY’S mouth by the chain, casting a spell that grants ABERNATHY a new forked tongue.* > > > **GRINDELWALD** You have joined a noble cause, my friend. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > *NAGINI grabs CREDENCE and tries to drag him away with her, but he is staring at GRINDELWALD.* > > > **CREDENCE** He knows who I am. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Like with Credence, Grindelwald says what Queenie wants to hear to get her to join him. Here he picks at her wanting to marry Jacob, a Muggle, which is currently illegal. > > **QUEENIE** Oh well, you know, she found out about Jacob and I seeing each other and she didn’t like it, ’cause of the “law.” *(miming quotation marks)* Not allowed to date No-Majs, not allowed to marry them. Blah, blah, blah. Well, she was all in a tizzy anyway, ’cause of you. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **GRINDELWALD** I would never see you harmed, ever. It is not your fault that your sister is an Auror. I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely. > > > *GRINDELWALD’S hand touches her wand-tip and lowers it.* > > > **GRINDELWALD** You are an innocent. So go now. Leave this place. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Enchanted ========= Of course earlier on we have the foreshadowing of people being enchanted when Queenie has enchanted Jacob. > > **NEWT (V.O.)** *(speaking telepathically)* You’ve enchanted him, haven’t you? > > > **QUEENIE** *(reading his mind)* What? I have not. > > > **NEWT** Will you stop reading my mind *speaking telepathically)* Queenie, you’ve brought him here against his will. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > It would also appear that Jacob believes she is enchanted, however, this could just be in desperation. > > *ANGLE ON QUEENIE AND JACOB, who are pressed up against a different stretch of wall.* > > > **JACOB** Queenie. You gotta wake up. > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > **JACOB** No, no, no, no, no, no. > > > **QUEENIE** Yeah. > > > **JACOB** No. > > > [...] > > > *ANGLE ON QUEENIE AND JACOB.* > > > **QUEENIE** Walk with me. > > > **JACOB** Honey, no! > > > **QUEENIE** *(screams)* Walk with me! > > > **JACOB** You’re crazy. > > > *She reads his mind, turns, hesitates, then walks into the black fire.* > > > **JACOB** *(desperate, disbelieving)* No! Queenie, don’t do it!” > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > >
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
**SPOILER ALERT** An obvious reason (properly described by @Valorum) is being able to marry Jacob. It's her greatest desire, and she sees Grindelwald's way is the only way to achieve that. It's like the last resort for her: either that or nothing. She doesn't seem to think deeply about the possible consequences. But there is more to it. **She really shares Grindelwald's views, though in a more naive way.** Although Queenie looks like a nice person, she already showed that the idea of using magic over muggles "for greater good" is fine with her. She put a spell on Jacob to make him stay with her, which is a pure violation of an individual's free will, but she thought she had the right to decide what is best, exactly because she had the power to benefit them both (as she saw it). Apparently using such methods on a no-maj seems legit to her, though she would probably think twice if Jacob was a wizard himself. She also doesn't ever seem to think she should limit her mind reading to respect others' privacy. It's quite straightforward for her: you've got the power, you use it. If you are a good person, then everybody will just benefit from it, right? Queenie is shown as a sweet, but rather naive person who does not think deeply about a problem, which makes her see right and wrong in a very narrow way. That's also the reason she can be easily persuaded. It didn't seem to take much effort from Newt to persuade her she shouldn't have put the spell on Jacob; in the same way, it was easy enough for Grindelwald to persuade her into his ideas. So it is possible Queenie genuinely shares Grindelwald's views that wizards are allowed to use their powers if this is for "greater good."
It’s unclear exactly but it would appear to be either because Grindelwald persuaded or enchanted her. I’ll detail reasons for both below: Both ==== Grindelwald is described as being very persuasive and having a silver tongue. This could be a reason to say he is either very persuasive or is enchanting people. > > **PICQUERY** It was necessary. He’s extremely powerful. We’ve had to change his guard three times—he’s very... persuasive. So we removed his tongue. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **SPIELMAN** No more silver tongue, eh? > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Persuasion ========== Grindelwald appears to have persuaded Abernathy to join his cause, this shows how persuasive he is and lays some foreshadowing down for persuasion, like he does to Credence at the end of the film too. > > *GRINDELWALD appears at the door and nods to ABERNATHY. He throws the door open so the water pours out—along with the two remaining AURORS. GRINDELWALD clambers inside and retrieves the vial from ABERNATHY’S mouth by the chain, casting a spell that grants ABERNATHY a new forked tongue.* > > > **GRINDELWALD** You have joined a noble cause, my friend. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > *NAGINI grabs CREDENCE and tries to drag him away with her, but he is staring at GRINDELWALD.* > > > **CREDENCE** He knows who I am. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Like with Credence, Grindelwald says what Queenie wants to hear to get her to join him. Here he picks at her wanting to marry Jacob, a Muggle, which is currently illegal. > > **QUEENIE** Oh well, you know, she found out about Jacob and I seeing each other and she didn’t like it, ’cause of the “law.” *(miming quotation marks)* Not allowed to date No-Majs, not allowed to marry them. Blah, blah, blah. Well, she was all in a tizzy anyway, ’cause of you. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **GRINDELWALD** I would never see you harmed, ever. It is not your fault that your sister is an Auror. I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely. > > > *GRINDELWALD’S hand touches her wand-tip and lowers it.* > > > **GRINDELWALD** You are an innocent. So go now. Leave this place. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Enchanted ========= Of course earlier on we have the foreshadowing of people being enchanted when Queenie has enchanted Jacob. > > **NEWT (V.O.)** *(speaking telepathically)* You’ve enchanted him, haven’t you? > > > **QUEENIE** *(reading his mind)* What? I have not. > > > **NEWT** Will you stop reading my mind *speaking telepathically)* Queenie, you’ve brought him here against his will. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > It would also appear that Jacob believes she is enchanted, however, this could just be in desperation. > > *ANGLE ON QUEENIE AND JACOB, who are pressed up against a different stretch of wall.* > > > **JACOB** Queenie. You gotta wake up. > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > **JACOB** No, no, no, no, no, no. > > > **QUEENIE** Yeah. > > > **JACOB** No. > > > [...] > > > *ANGLE ON QUEENIE AND JACOB.* > > > **QUEENIE** Walk with me. > > > **JACOB** Honey, no! > > > **QUEENIE** *(screams)* Walk with me! > > > **JACOB** You’re crazy. > > > *She reads his mind, turns, hesitates, then walks into the black fire.* > > > **JACOB** *(desperate, disbelieving)* No! Queenie, don’t do it!” > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > >
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
At the start of the film we see that Queenie is struggling with the idea that Jacob can't/won't marry her because she'd become an outcast in wizarding society (essentially exiled from her home country) and he'd either be killed or obliviated. > > **JACOB:** *Okay, wait. **We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail,** sweetheart. I can’t have that. **They don’t like people like me marrying people like you.** I ain’t a wizard. I’m just me.* > > > [Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay](https://www.waterstones.com/book/fantastic-beasts-the-crimes-of-grindelwald-the-original-screenplay/j-k-rowling/9781408711705) > > > When she meets Grindelwald, not only does he not turn out to be the psychopathic monster she's been told he is, but he also spins her a convincing lie about being free to love and marry muggles after the rebellion's completed. > > **GRINDELWALD:** *I would never see you harmed, ever. It is not your fault that your sister is an Auror. **I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely.*** > > > What's not clear (and may be explained later) is whether he's merely highly persuasive or whether his "silver tongue" is literally a form of magical enchantment. Either way, she makes her choice as a result of this conversation. > > **QUEENIE:** [a decision] *Jacob, he’s the answer. **He wants what we want.*** > > > --- In an interview, the actress who portrays Queenie Alison Sudol says that it breaks down to three main elements; That those close to her don't value her magical gifts, that she feels abandoned by her sister (and by Jacob) and that Grindelwald appears to be promising a world in which those with her kinds of views will be valued. > > *“I feel like in some ways she’s too there and that’s part of the problem. **She’s tapping into all human beings at all times and that’s a lot for one person to hold and everybody closest to her is always going, ‘Don’t read my mind.’ So she has a huge power and yet is made to feel like she’s nothing and that’s bad**. That could make anyone feel crazy. And women historically have this huge intuition and have been punished for that intuition forever. How many women have been in a mental institution because they’ve been called crazy when they’re just not allowed to be honest or be who they are?”* > > > *“Jacob doesn’t come with her,” she explains. **“It’s not so much about Jacob not coming with her to the dark side, it’s like, ‘Jacob, walk with me, we’re in this together.’ And she doesn’t have those two, so who does she have?** Newt’s kind of betrayed her — he called her out, it was embarrassing. What does she have?”* > > > *“I still believe in her heart of hearts she’s going over to fight what she believes in,” Sudol says. **“Grindelwald is saying, ‘we’re creating a different world’ and the world that she is in is broken. I don’t believe she’s turning evil. It’s more like she’s trying to find somebody who is giving her an option. He’s manipulating her but he’s manipulating everybody**. He even did that with Dumbledore.”* > > > [EW.COM - Interview](https://ew.com/movies/2018/11/20/crimes-of-grindelwald-alison-sudol-queenie/) > > >
**SPOILER ALERT** An obvious reason (properly described by @Valorum) is being able to marry Jacob. It's her greatest desire, and she sees Grindelwald's way is the only way to achieve that. It's like the last resort for her: either that or nothing. She doesn't seem to think deeply about the possible consequences. But there is more to it. **She really shares Grindelwald's views, though in a more naive way.** Although Queenie looks like a nice person, she already showed that the idea of using magic over muggles "for greater good" is fine with her. She put a spell on Jacob to make him stay with her, which is a pure violation of an individual's free will, but she thought she had the right to decide what is best, exactly because she had the power to benefit them both (as she saw it). Apparently using such methods on a no-maj seems legit to her, though she would probably think twice if Jacob was a wizard himself. She also doesn't ever seem to think she should limit her mind reading to respect others' privacy. It's quite straightforward for her: you've got the power, you use it. If you are a good person, then everybody will just benefit from it, right? Queenie is shown as a sweet, but rather naive person who does not think deeply about a problem, which makes her see right and wrong in a very narrow way. That's also the reason she can be easily persuaded. It didn't seem to take much effort from Newt to persuade her she shouldn't have put the spell on Jacob; in the same way, it was easy enough for Grindelwald to persuade her into his ideas. So it is possible Queenie genuinely shares Grindelwald's views that wizards are allowed to use their powers if this is for "greater good."
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
**SPOILER ALERT** An obvious reason (properly described by @Valorum) is being able to marry Jacob. It's her greatest desire, and she sees Grindelwald's way is the only way to achieve that. It's like the last resort for her: either that or nothing. She doesn't seem to think deeply about the possible consequences. But there is more to it. **She really shares Grindelwald's views, though in a more naive way.** Although Queenie looks like a nice person, she already showed that the idea of using magic over muggles "for greater good" is fine with her. She put a spell on Jacob to make him stay with her, which is a pure violation of an individual's free will, but she thought she had the right to decide what is best, exactly because she had the power to benefit them both (as she saw it). Apparently using such methods on a no-maj seems legit to her, though she would probably think twice if Jacob was a wizard himself. She also doesn't ever seem to think she should limit her mind reading to respect others' privacy. It's quite straightforward for her: you've got the power, you use it. If you are a good person, then everybody will just benefit from it, right? Queenie is shown as a sweet, but rather naive person who does not think deeply about a problem, which makes her see right and wrong in a very narrow way. That's also the reason she can be easily persuaded. It didn't seem to take much effort from Newt to persuade her she shouldn't have put the spell on Jacob; in the same way, it was easy enough for Grindelwald to persuade her into his ideas. So it is possible Queenie genuinely shares Grindelwald's views that wizards are allowed to use their powers if this is for "greater good."
Because she heard what she wanted to hear ----------------------------------------- ***To avoid a spoiler-formatting "hell", this post contains unprotected spoiler information*** In *Crimes of Grindelwald* > > Queenie > > > join forces with Grindelwald at the end. As others have suggested before, Queenie was in love with a Non-Wizard and by the standards of the late 20's Wizarding Society, marrying between Muggles and Wizards was considered a taboo; maybe it was also forbidden. Quoting a dialogue from the movie, > > **JACOB:** Okay, wait. We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail, sweetheart. I can’t have that. They don’t like people like me marrying people like you. I ain’t a wizard. I’m just me. > > > -Fantastic Beasts: The Crimes of Grindelwald - The Original Script > > > For this sole reason, at the beginning of the movie, she left him and throughout it, she seemed to be deeply affected by her choice. Later, when she met Grindelwald in Paris, she surrendered all her defenses. She heard what she wanted to hear. Of a world that she can leave freely without the "limitations" of the past. Grindelwald, after all, is mentioned to have been an **extremely charismatic** man, who not only persuaded thousands to join him, but persuaded none other than **Albus Dumbledore himself** in his quest to rule Muggles for the *Greater Good*. If Albus Dumbledore was deceived that easy, what chances did poor Queenie had? The real question would be *why* Grindelwald was so hesitant in making her join him. For that I guess, we will have to wait to find out.
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
At the start of the film we see that Queenie is struggling with the idea that Jacob can't/won't marry her because she'd become an outcast in wizarding society (essentially exiled from her home country) and he'd either be killed or obliviated. > > **JACOB:** *Okay, wait. **We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail,** sweetheart. I can’t have that. **They don’t like people like me marrying people like you.** I ain’t a wizard. I’m just me.* > > > [Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay](https://www.waterstones.com/book/fantastic-beasts-the-crimes-of-grindelwald-the-original-screenplay/j-k-rowling/9781408711705) > > > When she meets Grindelwald, not only does he not turn out to be the psychopathic monster she's been told he is, but he also spins her a convincing lie about being free to love and marry muggles after the rebellion's completed. > > **GRINDELWALD:** *I would never see you harmed, ever. It is not your fault that your sister is an Auror. **I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely.*** > > > What's not clear (and may be explained later) is whether he's merely highly persuasive or whether his "silver tongue" is literally a form of magical enchantment. Either way, she makes her choice as a result of this conversation. > > **QUEENIE:** [a decision] *Jacob, he’s the answer. **He wants what we want.*** > > > --- In an interview, the actress who portrays Queenie Alison Sudol says that it breaks down to three main elements; That those close to her don't value her magical gifts, that she feels abandoned by her sister (and by Jacob) and that Grindelwald appears to be promising a world in which those with her kinds of views will be valued. > > *“I feel like in some ways she’s too there and that’s part of the problem. **She’s tapping into all human beings at all times and that’s a lot for one person to hold and everybody closest to her is always going, ‘Don’t read my mind.’ So she has a huge power and yet is made to feel like she’s nothing and that’s bad**. That could make anyone feel crazy. And women historically have this huge intuition and have been punished for that intuition forever. How many women have been in a mental institution because they’ve been called crazy when they’re just not allowed to be honest or be who they are?”* > > > *“Jacob doesn’t come with her,” she explains. **“It’s not so much about Jacob not coming with her to the dark side, it’s like, ‘Jacob, walk with me, we’re in this together.’ And she doesn’t have those two, so who does she have?** Newt’s kind of betrayed her — he called her out, it was embarrassing. What does she have?”* > > > *“I still believe in her heart of hearts she’s going over to fight what she believes in,” Sudol says. **“Grindelwald is saying, ‘we’re creating a different world’ and the world that she is in is broken. I don’t believe she’s turning evil. It’s more like she’s trying to find somebody who is giving her an option. He’s manipulating her but he’s manipulating everybody**. He even did that with Dumbledore.”* > > > [EW.COM - Interview](https://ew.com/movies/2018/11/20/crimes-of-grindelwald-alison-sudol-queenie/) > > >
It’s unclear exactly but it would appear to be either because Grindelwald persuaded or enchanted her. I’ll detail reasons for both below: Both ==== Grindelwald is described as being very persuasive and having a silver tongue. This could be a reason to say he is either very persuasive or is enchanting people. > > **PICQUERY** It was necessary. He’s extremely powerful. We’ve had to change his guard three times—he’s very... persuasive. So we removed his tongue. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **SPIELMAN** No more silver tongue, eh? > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Persuasion ========== Grindelwald appears to have persuaded Abernathy to join his cause, this shows how persuasive he is and lays some foreshadowing down for persuasion, like he does to Credence at the end of the film too. > > *GRINDELWALD appears at the door and nods to ABERNATHY. He throws the door open so the water pours out—along with the two remaining AURORS. GRINDELWALD clambers inside and retrieves the vial from ABERNATHY’S mouth by the chain, casting a spell that grants ABERNATHY a new forked tongue.* > > > **GRINDELWALD** You have joined a noble cause, my friend. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > *NAGINI grabs CREDENCE and tries to drag him away with her, but he is staring at GRINDELWALD.* > > > **CREDENCE** He knows who I am. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Like with Credence, Grindelwald says what Queenie wants to hear to get her to join him. Here he picks at her wanting to marry Jacob, a Muggle, which is currently illegal. > > **QUEENIE** Oh well, you know, she found out about Jacob and I seeing each other and she didn’t like it, ’cause of the “law.” *(miming quotation marks)* Not allowed to date No-Majs, not allowed to marry them. Blah, blah, blah. Well, she was all in a tizzy anyway, ’cause of you. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **GRINDELWALD** I would never see you harmed, ever. It is not your fault that your sister is an Auror. I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely. > > > *GRINDELWALD’S hand touches her wand-tip and lowers it.* > > > **GRINDELWALD** You are an innocent. So go now. Leave this place. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Enchanted ========= Of course earlier on we have the foreshadowing of people being enchanted when Queenie has enchanted Jacob. > > **NEWT (V.O.)** *(speaking telepathically)* You’ve enchanted him, haven’t you? > > > **QUEENIE** *(reading his mind)* What? I have not. > > > **NEWT** Will you stop reading my mind *speaking telepathically)* Queenie, you’ve brought him here against his will. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > It would also appear that Jacob believes she is enchanted, however, this could just be in desperation. > > *ANGLE ON QUEENIE AND JACOB, who are pressed up against a different stretch of wall.* > > > **JACOB** Queenie. You gotta wake up. > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > **JACOB** No, no, no, no, no, no. > > > **QUEENIE** Yeah. > > > **JACOB** No. > > > [...] > > > *ANGLE ON QUEENIE AND JACOB.* > > > **QUEENIE** Walk with me. > > > **JACOB** Honey, no! > > > **QUEENIE** *(screams)* Walk with me! > > > **JACOB** You’re crazy. > > > *She reads his mind, turns, hesitates, then walks into the black fire.* > > > **JACOB** *(desperate, disbelieving)* No! Queenie, don’t do it!” > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > >
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
It’s unclear exactly but it would appear to be either because Grindelwald persuaded or enchanted her. I’ll detail reasons for both below: Both ==== Grindelwald is described as being very persuasive and having a silver tongue. This could be a reason to say he is either very persuasive or is enchanting people. > > **PICQUERY** It was necessary. He’s extremely powerful. We’ve had to change his guard three times—he’s very... persuasive. So we removed his tongue. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **SPIELMAN** No more silver tongue, eh? > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Persuasion ========== Grindelwald appears to have persuaded Abernathy to join his cause, this shows how persuasive he is and lays some foreshadowing down for persuasion, like he does to Credence at the end of the film too. > > *GRINDELWALD appears at the door and nods to ABERNATHY. He throws the door open so the water pours out—along with the two remaining AURORS. GRINDELWALD clambers inside and retrieves the vial from ABERNATHY’S mouth by the chain, casting a spell that grants ABERNATHY a new forked tongue.* > > > **GRINDELWALD** You have joined a noble cause, my friend. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > *NAGINI grabs CREDENCE and tries to drag him away with her, but he is staring at GRINDELWALD.* > > > **CREDENCE** He knows who I am. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Like with Credence, Grindelwald says what Queenie wants to hear to get her to join him. Here he picks at her wanting to marry Jacob, a Muggle, which is currently illegal. > > **QUEENIE** Oh well, you know, she found out about Jacob and I seeing each other and she didn’t like it, ’cause of the “law.” *(miming quotation marks)* Not allowed to date No-Majs, not allowed to marry them. Blah, blah, blah. Well, she was all in a tizzy anyway, ’cause of you. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **GRINDELWALD** I would never see you harmed, ever. It is not your fault that your sister is an Auror. I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely. > > > *GRINDELWALD’S hand touches her wand-tip and lowers it.* > > > **GRINDELWALD** You are an innocent. So go now. Leave this place. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > Enchanted ========= Of course earlier on we have the foreshadowing of people being enchanted when Queenie has enchanted Jacob. > > **NEWT (V.O.)** *(speaking telepathically)* You’ve enchanted him, haven’t you? > > > **QUEENIE** *(reading his mind)* What? I have not. > > > **NEWT** Will you stop reading my mind *speaking telepathically)* Queenie, you’ve brought him here against his will. > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > > It would also appear that Jacob believes she is enchanted, however, this could just be in desperation. > > *ANGLE ON QUEENIE AND JACOB, who are pressed up against a different stretch of wall.* > > > **JACOB** Queenie. You gotta wake up. > > > **QUEENIE** *(a decision)* Jacob, he’s the answer. He wants what we want. > > > **JACOB** No, no, no, no, no, no. > > > **QUEENIE** Yeah. > > > **JACOB** No. > > > [...] > > > *ANGLE ON QUEENIE AND JACOB.* > > > **QUEENIE** Walk with me. > > > **JACOB** Honey, no! > > > **QUEENIE** *(screams)* Walk with me! > > > **JACOB** You’re crazy. > > > *She reads his mind, turns, hesitates, then walks into the black fire.* > > > **JACOB** *(desperate, disbelieving)* No! Queenie, don’t do it!” > > > *Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay* > > >
This is just my opinion. Think about what time period we're talking about. It's the 1920s. If Queenie were perhaps pregnant, that would explain her despair on the streets of Paris, her frustration at Jacob refusing to marry her and her feeling like she didn't matter. Women in pre 1970s were treated horribly if they were pregnant without being married and Queenie finds herself wanting to marry a man she would be imprisoned for dating, let alone having a child with. She cannot go back to America and Jacob won't marry her for fear she'll get in trouble. That makes her motivation more understandable at least to me.
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
At the start of the film we see that Queenie is struggling with the idea that Jacob can't/won't marry her because she'd become an outcast in wizarding society (essentially exiled from her home country) and he'd either be killed or obliviated. > > **JACOB:** *Okay, wait. **We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail,** sweetheart. I can’t have that. **They don’t like people like me marrying people like you.** I ain’t a wizard. I’m just me.* > > > [Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay](https://www.waterstones.com/book/fantastic-beasts-the-crimes-of-grindelwald-the-original-screenplay/j-k-rowling/9781408711705) > > > When she meets Grindelwald, not only does he not turn out to be the psychopathic monster she's been told he is, but he also spins her a convincing lie about being free to love and marry muggles after the rebellion's completed. > > **GRINDELWALD:** *I would never see you harmed, ever. It is not your fault that your sister is an Auror. **I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely.*** > > > What's not clear (and may be explained later) is whether he's merely highly persuasive or whether his "silver tongue" is literally a form of magical enchantment. Either way, she makes her choice as a result of this conversation. > > **QUEENIE:** [a decision] *Jacob, he’s the answer. **He wants what we want.*** > > > --- In an interview, the actress who portrays Queenie Alison Sudol says that it breaks down to three main elements; That those close to her don't value her magical gifts, that she feels abandoned by her sister (and by Jacob) and that Grindelwald appears to be promising a world in which those with her kinds of views will be valued. > > *“I feel like in some ways she’s too there and that’s part of the problem. **She’s tapping into all human beings at all times and that’s a lot for one person to hold and everybody closest to her is always going, ‘Don’t read my mind.’ So she has a huge power and yet is made to feel like she’s nothing and that’s bad**. That could make anyone feel crazy. And women historically have this huge intuition and have been punished for that intuition forever. How many women have been in a mental institution because they’ve been called crazy when they’re just not allowed to be honest or be who they are?”* > > > *“Jacob doesn’t come with her,” she explains. **“It’s not so much about Jacob not coming with her to the dark side, it’s like, ‘Jacob, walk with me, we’re in this together.’ And she doesn’t have those two, so who does she have?** Newt’s kind of betrayed her — he called her out, it was embarrassing. What does she have?”* > > > *“I still believe in her heart of hearts she’s going over to fight what she believes in,” Sudol says. **“Grindelwald is saying, ‘we’re creating a different world’ and the world that she is in is broken. I don’t believe she’s turning evil. It’s more like she’s trying to find somebody who is giving her an option. He’s manipulating her but he’s manipulating everybody**. He even did that with Dumbledore.”* > > > [EW.COM - Interview](https://ew.com/movies/2018/11/20/crimes-of-grindelwald-alison-sudol-queenie/) > > >
Because she heard what she wanted to hear ----------------------------------------- ***To avoid a spoiler-formatting "hell", this post contains unprotected spoiler information*** In *Crimes of Grindelwald* > > Queenie > > > join forces with Grindelwald at the end. As others have suggested before, Queenie was in love with a Non-Wizard and by the standards of the late 20's Wizarding Society, marrying between Muggles and Wizards was considered a taboo; maybe it was also forbidden. Quoting a dialogue from the movie, > > **JACOB:** Okay, wait. We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail, sweetheart. I can’t have that. They don’t like people like me marrying people like you. I ain’t a wizard. I’m just me. > > > -Fantastic Beasts: The Crimes of Grindelwald - The Original Script > > > For this sole reason, at the beginning of the movie, she left him and throughout it, she seemed to be deeply affected by her choice. Later, when she met Grindelwald in Paris, she surrendered all her defenses. She heard what she wanted to hear. Of a world that she can leave freely without the "limitations" of the past. Grindelwald, after all, is mentioned to have been an **extremely charismatic** man, who not only persuaded thousands to join him, but persuaded none other than **Albus Dumbledore himself** in his quest to rule Muggles for the *Greater Good*. If Albus Dumbledore was deceived that easy, what chances did poor Queenie had? The real question would be *why* Grindelwald was so hesitant in making her join him. For that I guess, we will have to wait to find out.
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
**SPOILER ALERT** An obvious reason (properly described by @Valorum) is being able to marry Jacob. It's her greatest desire, and she sees Grindelwald's way is the only way to achieve that. It's like the last resort for her: either that or nothing. She doesn't seem to think deeply about the possible consequences. But there is more to it. **She really shares Grindelwald's views, though in a more naive way.** Although Queenie looks like a nice person, she already showed that the idea of using magic over muggles "for greater good" is fine with her. She put a spell on Jacob to make him stay with her, which is a pure violation of an individual's free will, but she thought she had the right to decide what is best, exactly because she had the power to benefit them both (as she saw it). Apparently using such methods on a no-maj seems legit to her, though she would probably think twice if Jacob was a wizard himself. She also doesn't ever seem to think she should limit her mind reading to respect others' privacy. It's quite straightforward for her: you've got the power, you use it. If you are a good person, then everybody will just benefit from it, right? Queenie is shown as a sweet, but rather naive person who does not think deeply about a problem, which makes her see right and wrong in a very narrow way. That's also the reason she can be easily persuaded. It didn't seem to take much effort from Newt to persuade her she shouldn't have put the spell on Jacob; in the same way, it was easy enough for Grindelwald to persuade her into his ideas. So it is possible Queenie genuinely shares Grindelwald's views that wizards are allowed to use their powers if this is for "greater good."
This is just my opinion. Think about what time period we're talking about. It's the 1920s. If Queenie were perhaps pregnant, that would explain her despair on the streets of Paris, her frustration at Jacob refusing to marry her and her feeling like she didn't matter. Women in pre 1970s were treated horribly if they were pregnant without being married and Queenie finds herself wanting to marry a man she would be imprisoned for dating, let alone having a child with. She cannot go back to America and Jacob won't marry her for fear she'll get in trouble. That makes her motivation more understandable at least to me.
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
**SPOILER ALERT** An obvious reason (properly described by @Valorum) is being able to marry Jacob. It's her greatest desire, and she sees Grindelwald's way is the only way to achieve that. It's like the last resort for her: either that or nothing. She doesn't seem to think deeply about the possible consequences. But there is more to it. **She really shares Grindelwald's views, though in a more naive way.** Although Queenie looks like a nice person, she already showed that the idea of using magic over muggles "for greater good" is fine with her. She put a spell on Jacob to make him stay with her, which is a pure violation of an individual's free will, but she thought she had the right to decide what is best, exactly because she had the power to benefit them both (as she saw it). Apparently using such methods on a no-maj seems legit to her, though she would probably think twice if Jacob was a wizard himself. She also doesn't ever seem to think she should limit her mind reading to respect others' privacy. It's quite straightforward for her: you've got the power, you use it. If you are a good person, then everybody will just benefit from it, right? Queenie is shown as a sweet, but rather naive person who does not think deeply about a problem, which makes her see right and wrong in a very narrow way. That's also the reason she can be easily persuaded. It didn't seem to take much effort from Newt to persuade her she shouldn't have put the spell on Jacob; in the same way, it was easy enough for Grindelwald to persuade her into his ideas. So it is possible Queenie genuinely shares Grindelwald's views that wizards are allowed to use their powers if this is for "greater good."
When Queenie met with Grindelwald earlier in the movie, he swayed her by hinting that the current laws banning marriage between Muggles and Wizards/Witches would no longer exist and that if she were to follow him, that she would be free to marry who she wished.