How to keep graph format in Excel when data changes?

Question: I have a series of graphs in Excel that I previously formatted. The data to be graphed comes from a dynamic series where user selects an element and then graphs show the concentration of the selected element.

When I select another element I don't want the format to change as it currently does:

I have already tried to lock formating for all my charts with:
         .ProtectFormatting = True
The sheet is protected and users can only select the element they want to graph. By selecting the element, the lines to be plotted update (using a dynamic pointer) but so does the format.
I've tried to save the graph as a template and then use the template for every graph but I am not sure if this is the right thing to do. The funny thing is that when I reselect the formatted graph (Cu) I get back the format I saved! Do I have to manually (or with a macro) format all 25 possibles graphs? I have 3 different graphs for every element...
Answer: There are several ways to achieve dynamic charts. It appears that you apply a technique where there are several series in a chart and you use VBA to show/hide series based on the user's selection.
An alternative would be to have a chart with only ONE series and let the user selection change the data for the chart.
If you want more precise advice you will need to share your code/approach.
Comment: Hello Teylyn, I am not using VBA for this specific part. Only using formulas to graph a scatter plot with a line.
Comment: Current formula is: =SERIES(Scenarios!$N$2,Scenarios!$A$3:$A$7,'J2.xlsm'!ele1data,1) where ele1data1 is a dynamic range that comes from the element selection. The element selection changes the column so new data draws a new graph.
Comment: I would like to know if there is a command in VBA that I could use to make the graph looks the same no matter where the dynamic range data is being pointed. Thanks in advance :D
Comment: Then, when I export this sheets to a new document format changes again! How do I preserve the graphs as they are? I am doing all the calculations with vba and I just want to export selected sheets to a new Excel file that user can work with. Could you please advice regarding graph formating?
Answer: This might be a case where unchecking the obscure property "Properties Follow Chart Data Point" would help.
This obscure setting means that if you customize your chart, then change the data, the customization is lost because the chart no longer points to the original data, for which you made the customizations.
So format your chart. Co to File > Options > Advanced, scroll down the the Charts section, and UNCHECK Properties Follow Chart Data Point for Current Workbook.
Then change the chart's source data.
See Properties Follow Chart Data Point for a detailed description of this setting.


SMS gateway for Dynamics 365

Question: First of all, I have to say that I am NET developer (C#) and my knowledge on Dynamics 365 is pretty limited. Nevertheless my employer thought that I am good enough to make that thingy from post title :)

After couple of hours researching and reading, I found this video https://www.youtube.com/watch?v=6LwZLoXS6jo which address on how to create and send SMS from Dynamics. I am aware that this require me to create new Dynamics entities, at least SMSMessage and SMSMessageTemplate, but at least I found out how to do this :)

I understood everything stated there, but as i  already said, due to my lack of knowledge on Dynamics 365, I got problems with (probably) basic things regarding Dynamics.

Here are those problems:

1. As far as I can tell, in order to build SMS gateway, first thing I need to do is to add new menu item inside Dynamics 365. I presume that this new menu item should reside inside 'Contacts' menu (contacts.jpg, marked with red box) but I am not sure on how to achieve this. Please note, I do not want someone to provide me with some magic solution, I just need someone to provide me with valid links that I can use to learn about this and solve my own problem :)

2. When new menu item is in place, and user click on it, I would like to open up a form for user to select SMS template that will be used and maybe setup some other values. Same again, U do not need to help me with exact code, just with some usable links :)

3. Inside that form that user will open on menu click, I would like to know how to get list of selected contacts (from grid at contact.jpg)

When I (finally) have that list of contacts, I will create SMS entities mentioned above (video link) and everything will fall in place and (hopefully) work.

I am aware that this is probably too much to ask, cause Dynamics 365 is rather complex, and people are spending great amounts of money and their time learning to became Dynamics developers, but without help, Dynamics is making me running in circles chasing my own tail :) and getting nowhere.

Also, I will be using online Dynamics 365 so bare in mind that any solution should work with it.

if any of U think that I missed or got something wrong, please let me know.enter image description here
Answer: So basically to get you started, you should:
1) Create a solution in Settings => Customizations => Solutions
2) Add contact entity to that solution (by choosing "Add existing" under Entities pane). Don't click "Add all assets" you will need only contact metadata to get going
3) Create jScript file and add a web resource to CRM (nothing really complicated, just go to web resources in you solution and click "Add new" and specify type of your web resource as jScript and target your file).
4) Now download http://www.xrmtoolbox.com
5) For now you are interested only in plugin "Ribbon Workbench"
6) Now simply choose your solution and contact - you will see command bars for contact homepage, list and form. This is pretty strainghtforward - simply drag and drop a button wherever you like, create a command using workbench and bind the button with the command (simply choose it from a drop-down). The command you are interested in is Custom Javacript. Here you specify your web resource and name of the function that you want to call. You can also specify parameters that should be passed inside your function for example ids of selected items (if you are on the list of records).
There are many approaches to fulfil your specific needs, but being able to call a custom javascript function from a button should be a good starting point, the rest is simply the knowledge of CRM SDK, so how to create an entity using API or open a form or open a web resource - everything is very well documented and you can get it simply by asking google, so I will not post any blog here, not to advertise too much. Also I's suggest downloading latest CRM SDK (https://www.microsoft.com/en-us/download/details.aspx?id=50032) - you have many sample code there, regarding plugins and some form modifications, you should also check this out.
To make it easier for you, you should refer to this "menu" as "Command bar" or "Ribbon", so rather look for "adding custom button to command bar CRM 2016" and you will be all good. Also to make a form for choosing a template, you will probably need some custom web resource, so "creating custom html5 web resource CRM 2016" should give you some good examples.

SMS gateway for Dynamics 365


How to add reset button to forms?

Question: I've been researching this matter for a while with no clear answer yet.
So, here are a few questions ...

I'm assuming (correct me if I'm wrong) that Drupal 7 doesn't support reset buttons. It appears, according to the form API (as discussed in Pro Drupal 7 Development), that all the buttons (input type="submit", button, and image_button) are by default submit buttons. There doesn't appear to be a way to override the defaults either.
So, if I wanted to add functionality to my forms for my users to clear forms (if they choose), would I have to create a module?

Would I be able to pull this off by using the general button type with executes_submit_callback set to false and by adding some type of Ajax function to the mousedown event?

** EDIT: I added the following to my hook_form_alter() **
$form['reset'] = array(
'#input' => TRUE,
'#name' => 'reset',
'#button_type' => 'reset',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => TRUE,
'#process' => '',
'#theme_wrappers' => array('button'),
);

I got the following error message & warning:

Notice: Undefined index: #type in _form_builder_handle_input_element() (line 1949 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).
Warning: Invalid argument supplied for foreach() in form_builder() (line 1763 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).

Is there a way to add the "reset" button type to the types of buttons without crashing the entire form.inc?
Answer: My preferred way to do this is.
Add the button to your form like so:
$form['options']['reset'] = array(
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('MY_MODULE_FORM_ID_reset'),
);

Then create the reset function like so:
function MY_MODULE_FORM_ID_reset($form, &$form_state) {
  $form_state['rebuild'] = FALSE;
}

No Javascript, no markup.
Answer: Don't know of support in Form API for a reset button, but simple enough to add a form alter to add one.
MYMODULE_form_alter($form, $form_state, $form_id) {
  $form['resetbutton'] = array(
    '#markup' => '<button type="reset"/>',
    '#weight' => 1000
  );
  return $form;
}

Comment: Nevermind, I figured it out: `$form['actions']['reset'] = array('#markup' => '', '#weight' => 1000);`
Comment: @user785179 form reset button resets the form fields to their original values, so after submit those fields will have `value="something"`, and that value will be restored. **Reset does not blank all fields**.
Comment: That was an awesome answer!!!!
Comment: Do you know if there is a way to add that reset button to the actions div?
Comment: What is weird, however, is that after I hit SUBMIT on my form, the reset button no longer works.  It works if a user has not hit the SUBMIT button.  Weird
Answer: function mymodule_form_alter(&$form, &$form_state, $form_id) {

switch ($form_id) {

case 'myform':
  $form['buttons']['reset_button'] = array(
    '#type' => 'markup',
    '#value' => '<input class="form-button" value="Reset" type="reset">',
    '#weight' => 2000,
  );
  break;
 }
 return $form;
}

Answer: This is 100% working:
$form['reset'] = array(
    '#type' => 'markup',
    '#markup' => '<input type="reset" value="Reset All Values" class="form-submit">',
);

Answer: Usually I give reset hyperlink which is pointing to current page URL using Markup form type.
When ever we click this link, it will refresh the page & will reset all the form elements. Else using javascript / Jquery we can reset the form elements by providing specific CSS Class / ID to that link.
Answer: None of the previous answers worked in the case I've been facing (views_exposed_form with BEF and ajax enabled). I had set up the reset button from BEF, but it was working only for one of my two views displays, whatever I tried...
I purpose another approach, in case it could help.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function moduleName_form_views_exposed_form_alter(&$form, &$form_state) {

  if (isset($form_state['view']->current_display) && 'some_display' == $form_state['view']->current_display ) {

    $submit_btn_id = $form['submit']['#id'];
    if (!empty($submit_btn_id) && !empty($form['reset'])) {
      //avoid the know issue redirecting views resets to /node
      $form['#action'] = '/' . $_GET['q'];
      // Add own reset button
      $form['submit']['#suffix'] = '<input type="reset" onclick="javascript:jQuery(this.form).clearForm();jQuery(this.form).find(\'#' . $submit_btn_id . '\').trigger(\'click\');return false;">' . t('Reset') . '</input>';
      $form['submit']['#attributes']['class'][] = 'my-views-filter-submit';
      // Remove the original RESET button.
      unset($form['reset']);
    }
  }
}

About the issue redirecting views resets to /node... onclick="history.go(0); is an alternative.
This was inspired by Julian blog add ajaxified reset button for views exposed filters but I had to adapt it substantially.
Answer: This is my way to add Reset button, hope you like it :D
$form['reset'] = array(
'#markup'   => '<input type="reset" class="form-submit" />',
'#title'    => 'Reset',
);

Comment: No - never do this. Always use the Form API.

How to add reset button to forms?


Varnish Error Log Files

Question: I upgraded to version 4.1 from 4.0 and everything was working fine until I restarted the service and it shows Starting or Started, but when I check the status or go to a website the services shows stopped and I cannot access any of my web sites. With some Google'in I was able to get the access log going, but I cannot find how to get a log going of what happens when I go to start the Varnish service. If there is no way to log service start errors from Varnish what log should I use to figure out the issue of the service starting then stopping right away? System: CentOS 6, Varnish 4.1.0, I upgraded via the package manager.
Answer: You could probably run strace (signal trace) to see where exactly it fails. strace /etc/init.d/varnishd start should provide some helpful information.

Varnish Error Log Files


Custom libraries and dependency injection

Question: I have been using D7 for a while, new to D8; also have a fair amount of experience with Laravel/Lumen and dependancy injection (DI).  One of the big sell's of D8 is the new OO structure, and specifically the Symphony DI system.
So to test this out, I want to develop (port some of my old D7 code) to a D8 custom library, that will 'inject' when needed, and I do not want to do this as a module (I got that right; the objective is to have a PHP library class).
Given some of the documentation I read, I created a folder called /libraries/my_library, and for the hell of it I added a PSR4 mapping to /composer.json like so:
"Drupal\\CustomLib\\": "libraries"
For the record, I tried it without Drupal\\ as well - makes no difference.
In /libraries/my_library/scr/myClass.php I have a single class myClass.  I also added a my_library.services.yml
services:
  myClass:
    class:   CustomLib\mylibrary\myClass

And in my custom theme file I simply tried
use CustomLib\mylibrary;

function quirk_preprocess_html(&$vars) {
  $tools = Drupal::service('myClass');
}

which results in

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service

Can someone point me in the right direction please.  What am I missing.  I am assuming Drupal is not scanning the /libraries/my_library folder for the services definition - but how do I get it to do so?
Comment: In Symfony you always(maybe "traditionally" is the better word?) need a bundle to register a library as a service, they don't register themselves. I imagine it's the same for Drupal with a module (or maybe theme), in that you'll need a module to make the service available to Symfony. Makes sense when you think about it - your library shouldn't "know" that it's going to be eventually used in a Symfony service, it should just do what it does and do it well.
Comment: I think you might be right.  Found this post :  http://achilleskal.com/blog/service-container-for-drupal-geeks.  This does beg the question - how will we be able to use PHP libraries that are not available through composer.
Comment: Which libraries would those be though? Composer can download any GitHub project which surely covers 99.99% of cases, and for anything else it's pretty configurable. If you mean an offline library that for some reason can't be made available over a network or the local disk, then yeah, you're going to struggle. But that would be true of any php project
Answer: OK people, I played around with a couple of options, but the bottom line is, if you want to create your own 'services' class, specifically for dependancy injection, it has to be tied to a module.
So - I created a custom module.  The actual module file is empty
<?php

Also created the services definition / config file my_module.services.yml and then critically, your services class files should go in a sub-folder /src.  Since it is a service, you will need an interface and implementation class.
Comment: You don't technically need an interface. It is also possible to define the class in a separate library, pull in the library via composer, and write a module that just defines a service pointing to that class.
Comment: @mradcliffe: please tell me more.
Comment: Here are a couple of examples: http://cgit.drupalcode.org/currency/tree/currency.services.yml#n21, http://cgit.drupalcode.org/xero/tree/xero.services.yml#n11. The service definition is set to a class that is not packaged with the module, but is brought in via composer dependency. In the first case, @Xano maintains a generic PHP library for currency metadata and then also maintains a drupal module with drupal-specific implementations. In the second case, I do the same thing, and the XeroClient class does not specifically implement an interface, it extends a class (but that's irrelevant).


Is there a simple way to rewrite the PHP code attached (using arrays as a lookup table perhaps)?

Question: switch ($hiBid) {
case ($hiBid > 0 && $hiBid <= 1):
    $minIncrement = .01;
    break;
case ($hiBid > 1 && $hiBid <= 5):
    $minIncrement = .25;
    break;
case ($hiBid > 5 && $hiBid <= 25):
    $minIncrement = 1;
    break;
case ($hiBid > 25 && $hiBid <= 100):
    $minIncrement = 5;
    break;
case ($hiBid > 100 && $hiBid <= 500):
    $minIncrement = 10;
    break;
case ($hiBid > 500 && $hiBid <= 1000):
    $minIncrement = 25;
    break;
}

Looking for way to simplify this code more like a database lookup table, primarily to allow many more range comparisons that will be easier to read like a spreadsheet, where they will be initially defined.
Comment: This might be better suited to the Code Review stackexchange site
Comment: Use an array whose keys are the upper limits of each range and values are the increments, in descending order. Loop through the array until `$hibid` is less than the key, then assign the increment and break out of the loop.
Answer: Every time you find yourself writing repetitive code like this you can probably re-envision it as a loop and an array.
function getIncrement($bid, $tholds, $min=0) {
    $max = max(array_keys($tholds));
    if( $bid <= $min || $bid > $max ) {
        throw new \Exception("Bid outside threshold range");
    }

    $prev = $min;
    foreach( $tholds as $thold => $increment ) {
        if( $bid > $prev && $bid <= $thold ) {
            return $increment;
        }
        $prev = $thold;
    }
}

$tholds = [
       1 =>  0.01,
       5 =>  0.25,
      25 =>  1.00,
     100 =>  5.00,
     500 => 10.00,
    1000 => 25.00
];

var_dump(getIncrement(256, $tholds));

Ouput:
float(10)

Comment: @HashimAziz Because it answers the question that was asked. Because you can change the thresholds without rewriting swaths of boilerplate code. Because it's not really that hard to read. Because it has bounds checking and error reporting. Because the amount that this _might_ be slower would be difficult to measure even if you looped it a billion times.
Comment: Ty. Was aware of the looping method. Was wondering if there was a faster way to do it, perhaps some PHP array range-compare methods that I did not know about...
Comment: No. There's no builtin for this. A person _could_ rewrite this using a more efficient lookup and/or data structure, but unless you're planning to have several _thousand_ threshold values it would take more time to write the code than you would ever save in CPU cycles.
Comment: What are the advantages to refactoring code like this when it's slightly longer, harder to understand, and likely slower?


can I change a parent's async piped properties?

Question: To give you some more context:

Red is the parent and Blue is the child component.
The parent just assigns the Observable in the ngOnit
this.user$ = this.userService.getUser(this.userId);

it doesn't do anything else with it, it's used in the template this way:
<ng-container *ngIf="user$ | async as usr; else loading">

The child receives the two values that can be changed as @Input properties:
  <ew-edit-user
    *ngIf="edit===true"
    [(xBox)]="usr.xBox"
    [discord]="usr.discord">
  </ew-edit-user>

In the Submit-Handler, it calls the API to save the changes.
this.userService.changeProfile(this.frm.xBox.value, this.frm.discord.value).subscribe(() => { });

After saving, I'd like to refresh the parent.
Tried the two-way-bindings as shown above, but it has no effect. So before I re-write the Parent and subscribe to the reading-service in the component, I'm asking here for ideas...
Answer: Providing an example code with your problem would help but if i'm understanding your problem right, you should be able to resolve this with the two-way data binding.
Without seeing the code I can only assume that you forgot to add the EventEmitter to the child class. Here's a small example how it could be implemented.
In the HelloComponent I've wrapped the input into an object instead of passing in two values for convenience and notice how the @Output dislayItemChange has the same name as the @Input but with Change in the end - thats necessery for Angular to pick up the change event in the parent. Read more about it from the Angular docs
Comment: You're cool. Adding that event (and firing it) did the trick.


How to ensure that chaincodes managed by different organizations remain compatible

Question: In the car lease demo, the national regulator owns and operates a chaincode that corresponds to a "car" object. It defines relevant attributes and its lifecycle. Everyone is always on the same page and life is beautiful.
But, to me, it appears inevitable that we will soon see an explosion of "Car" chaincodes by:

other countries with their regulators
insurers that come up with their own blockchain solution
individual car manufacturers that want to capture more attributes of their cars on a blockchain
etc

Unless there is a way to link these different "Car" chaincodes, a Car manufacturer will quickly find itself having to integrate into dozens of different blockchain networks which might not always be in sync with each other.
With my Object-Oriented background it seems obvious that it would be very valuable if the concepts of subclasses or interfaces could apply here. The insurer could define a "Car" interface and every manufacturer that  implements that interface in their own "Car" chaincode could automatically be plugged into the insurers solution.
But I don't think such concepts exist in Hyperledger Fabric.
So, hence my question: what are the best practices to ensure chaincodes managed by different organizations can talk to each other in such a situation?
Answer: It is quite an old question. But the idea would be that the insurer would create a chaincode for a "Car" with certain methods which can then be invoked by the manufacturers without the manufacturer having to create any chaincode themselves.


How can we interchange the colors of districts in 4 color problem

Question: In the paper On the geographical problem of the Four Colors by Kempe, at the end of page 194, it is stated that

It will readily be seen that we can interchange the colours of the
  districts in one or miore of the red and green regions without doing
  so in any others, and the map will still be properly coloured. The
  same remarks apply to the regions composed of districts of any other
  pair of colour. Now if a region composed of districts of any pair of
  colours, say red and green as before, be of either of the forms shown
  in Figures 3 and 4, it will separate the surface into twvo parts, so
  that we map be quite certain that no yellow or blue districts in one
  part can belong, to the same yellow and blue region as any yellow or
  blue district in the other part

But I'm having trouble understading his argument. I mean as far as I understood, those lines in the figures are the boundaries of regions which contain districs, and if we change the colors of district, say blue and green, in one region only, there will be no problem, but can't a district of blue color in the inner region have a neighbour with green color in the outer region ?
Comment: I'm not sure why you think we'll take the time to think about that quote if you don't even take the time to proofread it to make it understandable.
Comment: I haven't read that paper in a long time, but as I recall, it was very difficult to follow the argument in terms of maps.  That is, I think, why an error that jumps off the page at you if stated in terms of graphs, went unnoticed for ten years when stated in terms of maps.
Comment: @joriki Because nobody (including me) answers question because they want to "help" people; This is not a charity. If the question interesting for you, you take to challenge to answer, if not, you do not have to. I have put the link of the article into the question, for in case situations also. Plus, I have proofread the quote, but right now, I'm still trying to understand the argument and the article, so I'm not sorry if the quote contains a typo like "twvo", and you do not answer to the question just because of that.
Comment: It contains more serious typos than that; it says "so that we map be" and dozens (currently $20$) people have to stop and figure out what that means instead of one person (you) taking a second to check it against the text. I do sometimes answer questions to help people, and I don't see a reason to put scare quotes around that word. Of course, if you're not interested in such people answering your questions, that's OK. Perhaps you could indicate it at the top in order not to waste our time. (It would still be efficient and kind towards the non-charitable non-helpers if you proofread the text.)
Comment: Of course, the title of the paper is *On the Geographical Problem of the Four Colours*.
Comment: "but can't a district of blue color in the inner region have a neighbour with green color in the outer region ?" No. If the inner region consists of blue and green districts, the adjacent outer region consists entirely of red and yellow districts. "Those regions [of red and green districts] will be surrounded by and surround regions composed of blue and yellow regions ..." Each region consists of all contiguous districts of the appropriate colors.
Comment: @SteveB Why does the adjacent outer region has to contain only red and yellow districts ?
Comment: In the middle of the paragraph on page 194, while still discussing red/green regions, Kempe wrote, "Those regions [of red and green districts] will be surrounded by and surround regions composed of blue and yellow regions ..." You might have read my comment that prematurely posted. It did not contain Kempe's statement about regions being surrounded by regions of the opposite colors.
Answer:
I couldn't figure out how to post an image in a comment, so ...
The map has two red/green regions, A and D. It has two blue/yellow regions, B and C. Region B consists of a single blue district. If green and red were switched in region A, the other regions would be unaffected. Every district in A is adjacent to other districts in A or blue/yellow districts in B or C.
The single district in region B can be blue or yellow.
If we wanted blue/green regions and red/yellow regions instead, there would be a single blue/green region and 4 red/yellow regions.


Can we use a likert scale of 0 to 5 for SEM analysis?

Question: I am learning to do SEM analysis and have finished the data collection. In my questionnaire I have scales measured from $0$ to $5$ which measure emotions ($0$ = not feeling it at all to $5$ feeling it strongly). Now someone told me I SEM cannot use a scale with $0$ in it.
He is using AMOS. I heard Mplus can accommodate it. Does anybody know if this is correct?
Answer: Because you are using a Likert-scale test, your variable here is inherently ordinal, though often they are treated as continuous. Zero probably doesn't have an actual meaningful value here, so it could just as easily be $1$ to $6$ and the outcomes wouldn't change much so long as you are not treating them as continuous in estimation. I'm guessing that their issue is that they are treating your variable here as continuous, which is anyway wrong per Kline (2023):

Results from computer simulation studies generally indicate that use
of estimators for continuous variables to analyze measurement models
with Likert items as indicators is potentially problematic. For
example, Rhemtulla et al. (2012) reported that for Likert items with
fewer than 5 response categories, the robust ML method for continuous
variables generated biased estimates of factor correlations and it
generated standard errors that were generally too small. This
distortion generally inflates the rate of Type I errors in
significance tests of parameter estimates. Values of model test
statistics, such as mean-and-variance adjusted chisquares that correct
for nonnormality (Chapter 10), were generally too high when (1)
population response distributions were marked skewed, or asymmetrical,
and (2) patterns of asymmetry alternated over items in the same model.
Under these conditions, the chi-square test rejected too many
correctly specified models.

The reason I bring this up is because structural equation modeling is built to deal with different types of data, and the ordinal case is certainly manageable. I am not as familiar with Mplus or AMOS for SEM, but I am familar enough with lavaan in R to note that the ordered argument in the typical SEM functions treats the data as ordinal, as shown here and below in R syntax (w/ my own annotations):
#### Convert Data to Ordered ####
Data[,c("item1",
        "item2",
        "item3",
        "item4")] <-
    lapply(Data[,c("item1",
                   "item2",
                   "item3",
                   "item4")], ordered)

#### Fit Model ####
fit <- cfa(myModel, data = myData,
           ordered = c("item1","item2",
                       "item3","item4"))

Some discussion on how to do this in Mplus can be found here.
Reference
Kline, R. B. (2023). Principles and practice of structural equation modeling (5th ed.). The Guilford Press.
Answer: With ordinal data, you would typically use polychoric correlations and DWLS/WLSMV estimation (rather than covariances and maximum likelihood estimation) in CFA and SEM. Both lavaan and Mplus automate the process when indicators are defined as (ordered) categorical (ordinal). Here are some additional references:
Finney, S. J., & DiStefano, C. (2006). Non-normal and categorical data in structural equation modeling. In G. R. Hancock & R. O. Mueller (Eds.), Structural equation modeling: A second course. Greenwich, CT: Information Age Publishing.
Li, C.-H. (2016). The performance of ML, DWLS, and ULS estimation with robust corrections in structural equation models with ordinal variables. Psychological Methods, 21(3), 369–387. https://doi.org/10.1037/met0000093
Rhemtulla, M., Brosseau-Liard, P. É., & Savalei, V. (2012). When can categorical variables be treated as continuous? A comparison of robust continuous and categorical SEM estimation methods under suboptimal conditions. Psychological Methods, 17(3), 354-373.


Calculating $2^{9999 }$ mod $100$ using Fermats little Theorem

Question: By a modified version of the Fermat's little theorem we obtain that $a^{\phi(n)} \equiv 1$ mod $n$ whenever $(a,n)=1$. But my professor accidentally gave this question to calculate $2^{9999 }$ mod $100$. So everyone in the class calculated it using the theorem since they forgot to check that $(a,n)=1$. But to my surprise everyone got $88$ as the answer which is actually the correct answer.
So I first saw what happens in the case of mod $10$. Here $2^4 \equiv 6$ mod $10$. But magically enough this number multiplies with powers of $2$ as if it were identity i.e.
$$2\cdot6 \equiv 2 \pmod {10}$$
$$4\cdot6 \equiv 4 \pmod {10}$$
$$6\cdot6 \equiv 6 \pmod {10}$$
$$8\cdot6 \equiv 8 \pmod {10}$$
After seeing this I checked what happens in the case of $100$. Similar thing happens even here instead $2^{40} \equiv 76\pmod{100}$. Now $76 $ acts like $6$ just that $76*2 \neq 2$ but otherwise $76*4=4$ and $76*8=8$ and so on. Can anyone explain as to why it is happening here and does it happen in other cases as well.
Comment: To comment on the pattern you noticed: $6 = 5+1$, and $10 = 2\cdot 5$. So for any even number $n$: $6\cdot n\equiv 5\cdot n + 1\cdot n\equiv 0 + n\equiv n\pmod{10}$. $76$ behaves in a similar way because $76 = 75+1 = 3\cdot 25 + 1$ and $100 = 4\cdot 25$. If you multiply $76$ by a number divisible by $4$, it'll cancel off the $3\cdot 25$, but multiplying by even numbers that aren't divisible by $4$ doesn't cancel it completely (try $6$).
Comment: Hint: $2^{9999}\equiv 0\pmod 4$. So you only need to solve $2^{9999}\pmod {25}$, and then solve the Chinese Remainder Theorem question.
Comment: @ThomasAndrews $2^{20} \equiv 1 \pmod{25}$ So using that I solved it but I was amazed at how $76$ acted like $1$ and I want to know whether it happens with other numbers as well
Comment: @Stahl thanks so when all can I do this kind of a trick?
Comment: I'll add a comment about that to the answer I just wrote up.
Comment: Fermat's little theorem is a special case of Euler's theorem.
Answer: What's going on here is a direct result of the prime factorizations of $10 = 2\cdot 5$ and $100 = 2^2\cdot 5^2$. Try writing it like this:
\begin{align*}
2\cdot 6\equiv 2\cdot(5+1)&\equiv 2\cdot 5 + 2\cdot 1\equiv 0 + 2\pmod{10}\\
4\cdot 6&\equiv4\cdot 5 + 4\cdot 1\equiv 0 + 4\pmod{10}
\end{align*}
and so on. Since $6 = 5+1$, multiplying by an even number will "cancel out" the $5$, and you'll just be left with the $1$, acting like an identity. Same thing is going on with $76 = 75 + 1 = 3\cdot 25 + 1$. To cancel out the $3\cdot 25$, you need an even number that's divisible by $4$ ($4\cdot 25 = 100$). If you test $76\cdot 6\pmod{100}$, you should find that the result is nonzero.
This sort of thing will happen whenever you're calculating mod $n = \prod_{i = 1}^m p_i^{e_i}$ (here $\prod_{i = 1}^m p_i^{e_i}$ is the prime factorization of $n$) and you look at multiplication by a number $k$ of the form $1 + (\textrm{anything})(\textrm{product of some of the }p_i\textrm{'s})$. Whenever you multiply $k$ by any number whose factorization includes the $p_i$'s not appearing in the "product of some of the $p_i$'s" (counted with multiplicity), you'll cancel off the second term of $k$ and be left essentially multiplying by $1$. As an easy example, look mod $6$. Multiplication by $3$ acts like the identity for $3$ and $0$ because $3 = 1 + 2$ and $6 = 2\cdot 3$.
Answer: If  $x\equiv 1\pmod{5^k}$, then $x\cdot (2^ka)\equiv 2^ka\pmod{10^k}$ for any integer $a$.
That's because $2^kax-2^ka=2^ka(x-1)$ is divisible by $2^k$ and by $5^k$, hence divisible by $10^k$.
More generally, if $x\equiv 1\pmod {m}$ then $x(nk)\equiv nk\pmod{mn}$ for any $n,k$.


Strong mathematical induction to prove $n=4x+5y$

Question: Use the principle of strong mathematical induction to prove that if $n\in\mathbb N, n\geq12$ , then there exist non-negative integers $x$ and $y$ such that $n=4x+5y$.
Comment: I suggest this should be closed as a duplicate. All you have to do is search for "postage stamp".
Answer: Let's suppopse $n=4x+5y$,
then we have
$$n+1=4(x-1)+5(y+1) = 4(x+4)+5(y-3) $$
The only problematic case for these is when both $x<1$ and $y<3$, i.e. for $n\le 10$.
Start: $12=3\cdot 4+0\cdot 5$.
Comment: Dang, Berci. Beat me by 3 seconds. Still, we've presented slightly different solutions: yours is more elegant, mine is more general.
Answer: Start with $13 = 4\cdot2+5\cdot1, 14 = 4\cdot1+5\cdot2,15 = 4\cdot0+5\cdot3,16 = 4\cdot6+5\cdot0$ as your base case. For the inductive step, let $n$ be a natural number greater than $16$ and assume that all numbers $13\le k < n$ may be written as $k=4x+5y$ for nonnegative $x, y$. Then by the inductive hypothesis $n-4$ can be written as $4a+5b$ and so $n=4(a+1)+5b$, thus showing that $n$ can be expressed in the desired form. Done.


Topology on $\mathbb{R}$ strictly coarser (resp. finer) than the usual one which is still Hausdorff (resp. connected)

Question: The following are simple observations.

Suppose $\mathcal{T}_1,\mathcal{T}_2$ are two topologies on a set $X$ such that $\mathcal{T}_1$ is finer than $\mathcal{T}_2$.

If $( X ,\mathcal{T}_2 )$ is Hausdorff, then so is $( X ,\mathcal{T}_1 )$.
If $( X ,\mathcal{T}_1 )$ is connected,  then so is $( X ,\mathcal{T}_2 )$.

The real numbers with the usual topology is both Hausdorff and connected, which leads to the following two questions.

Is there a topology on the real numbers strictly coarser than the usual one, which makes it still Hausdorff?

Is there a topology on the real numbers strictly finer than the usual one, which makes it still a connected space?
Comment: K-topology is finer and connected on $\mathbb R$. http://en.wikipedia.org/wiki/K-topology
Comment: [This previous question](http://math.stackexchange.com/q/135639) gives a necessary condition for a topology to be "minimally Hausdorff" (_i.e._, no strictly coarser topology is Hausdorff). The reals with the usual topology clearly don't satisfy this condition ($\mathbb{R}$ is homeomorphic to $(0,1)$ which is not closed in $[0,1]$).
Answer: People suggesting that you can't make a coarser, still Hausdorff topology are wrong. Their proofs are invalid, and so is the conclusion. I construct a coarser topology that is still Hausdorff. You can think of this space as adding a point at $+\infty$ and gluing it to 0.
Let $\tau$ be the usual topology of open sets on $\mathbb{R}$. Define $\tau' \subset \tau$ as the collection of sets in $\tau$ that, if they contain 0, contain some interval $(\alpha,+\infty)$. That is, the open sets in our new topology are the old open sets, but, if they contain the point 0, we also require them to be a neighborhood of $+\infty$. By definition $\tau'$ is coarser than $\tau$, and it is immediate that it is closed under finite intersection and arbitrary union. To show it's Hausdorff, say we're trying to separate two points $x$ and $y$. If $x,y \neq 0$, just choose some small intervals around $x$ and $y$, making sure you don't include 0 in either of them. If one of them is zero, just pick intervals as usual, and throw in some $(\alpha,+\infty)$ to the neighborhood of 0, with $\alpha$ large enough not to include the other point.
Someone already provided a working example for a finer topology that's still connected.
Edit: I'll provide some informal rationale about why the compactness of closed intervals is not enough to get what people seem to want, and shouldn't be. Morally, you can think of Hausdorff as meaning "sequences can't converge to more than one point", and a coarser topology as being one in which "more converging happens." The reason that you can't make a coarser Hausdorff topology on a compact space is that there is already lots of converging going on. To get more converging, you would have to make a sequence converge to something new, when it already converges to something else (breaking Hausdorff). The key way we're using compactness here is that we know that "everything that could converge already does"; that's a global property of compactness, and we can't recover it from local compactness, or knowing that our space is a countable union of compact sets, or anything like that. In the construction I gave, we added "more convergence" by saying that sequences that tend to $+\infty$, which ordinarily diverge, should instead be considered converging to 0.
Comment: @Gamamal : It's like defining a continuous map from $\mathbb R$ to the figure 8 in $\mathbb R^2$ and take the pullback topology.
Comment: Stefan might be saying this more rigorously (too lazy to figure it out), but: this solution is like assigning to $\mathbb R$ the topology obtained by identifying it with a subspace of $\mathbb R^2$ given by a circle and a tail. The fact that a 1-1 continuous path from $\mathbb R$ onto such a figure should be pretty intuitive, which is what makes the topology coarser.
Comment: @Gamamal The open sets are just the usual open sets, with an additional non-vacuous restriction. It therefore has "fewer" open sets, so is coarser.
Comment: @Gamamal No. The underlying set is still $\mathbb{R}$ in the explicit construction. In the "gluing" way of thinking about it, there is not *really* a new point, since the "new point" at $+\infty$ gets glued to 0.
Comment: It's like equipping $\Bbb R$ with the initial topology with respect to the map from $\Bbb R$ to $X=(-\infty,-1]\cup S^1$ which sends any $x\le0$ to $x-1$, and $x\ge0$ to $e^{i\pi+2\pi i(1-1/(1+x))}$. The initial topology for the map from $\Bbb R$ to $\large\infty$ is even coarser and still Hausdorff.
Comment: Why is it coarser by definition?
Comment: But didn't you add a new point to the topology?
Comment: oh ok, thank you for clearing that up for me.
Comment: This construction can be sen as a specific case of [this previous answer](http://math.stackexchange.com/a/135744), taking $ X^\prime = (-\infty, +\infty ]  = \mathbb{R} \cup \{ +\infty \}$ with the natural order topology.
Comment: Beautiful answer, especially the last paragraph on intuition!
Comment: Is there a coarsest topology in the euclidean topology which is hausdorff?
Answer: For your second question, yes.
Let $\tau$ be the topology on $\mathbb R$ generated by $X\cup \mathbb Q$ or $X$, where $X$ is open in $\mathbb R$ in the usual topology. Then it is connected.
To see this, let $\mathbb R = Y_1 \cup Y_2$ be two disjoint union, where $Y_i \in \tau$. Then either one of them, say $Y_1$, is not open in the usual topology. By definition,
$$Y_1 = X_1 \cap (W_1 \cup \mathbb Q),$$
where $X_1, W_1$ are open (in the usual sense). As this is not open in the usual topology, there is $p \in Y_1\cap \mathbb Q$ such that $Y_1$ does not contain any open interval around $p$, but $Y_1$ does contain all rational numbers sufficiently close to $p$.  But then it is impossible for $Y_2$ to be open in $\tau$: $Y_2$ must contain irrational numbers arbitrarily close to $p$, but then openness would force it to also contain rational numbers arbitrarily close to $p$.
Answer: In addition to the counterexamples, the true statement should be that for a compact Hausdorff space, you cannot weaken it without losing the $T_2$ axiom and you cannot strengthen it without losing the compactness (see Functional Analysis by Rudin). To see that, suppose $\tau_1\subseteq\tau_2$ are two topologies defined on the same space such that $\tau_1$ is Hausdorff and $\tau_2$ is compact. If $F$ is a $\tau_2$-closed set, then it is compact as is in a compact space. Then any $\tau_1$-open cover of $F$ is automatically a $\tau_2$-open cover. Since $\tau_2$ is compact, there should be a finite sub-cover. Thus $F$ is a $\tau_1$ compact set. Note that $\tau_1$ is Hausdorff. This means $F$ is $\tau_1$-closed. In a word, a $\tau_2$-closed set is $\tau_1$-closed, showing that the two topologies are actually equal.


Is a function to convert an object copying the return value?

Question: In C++, I have a rectangle parameter coming into a function.
Since i'm keeping my system abstract, I made my own Rectangle class.
The function I pass it into (for SFML graphics library) uses its own RectangleShape object.
So, I need to convert my Rectangle into a RectangleShape.
I went to make a function to do this, but I got confused as to what objects are being created, who is getting copied, and what's fastest. Here is the situation:
RectangleShape MyClass::ConvertRectangleToRectangleShape(const Rectangle& inRectangle)
{
    Vector2f size(inRectangle.GetWidth(), inRectangle.GetHeight());
    RectangleShape convertedRectangle(size);
    Vector2f position(inRectangle.GetPosition.GetX(), inRectangle.GetPosition.GetY());
    returnShape.SetPosition(position);

    return convertedRectangle;
}

void MyClass::DrawShape(const Rectangle& inRectangle)
{
    // Convert the shape
    RectangleShape convertedShape = ConvertRectangleToRectangleShape(inRectangle);
    // Rest of code here
}

So, as you can see, none of my objects come in as pointers. So I don't need to deal with that.
The object I return is on the stack, but not a reference. It gets copied when I return it, right? That line
return convertedRectangle;

it copies the rectangle shape into the variable I create in the second function
RectangleShape convertedShape = ConvertRectangleToRectangleShape(inRectangle);

right?
I can't return it as a reference variable, because it gets de-allocated once I leave the scope of the function, right?
RectangleShape& MyClass::ConvertRectangleToRectangleShape(const Rectangle& inRectangle)

If I can't return it as a reference, and I wouldnt want a copy, would I just have to paste the code into the function? Or #define it? What's the correct way here, or where am I wrong? Thanks!
Comment: I'd go with an explicit conversion operator and a `static_cast` when the conversion needs to happen.
Comment: Why don't you want a copy? Performance? Sounds like premature optimization.
Comment: @chris as I mentioned below, what happens if I don't have access to the RectangleShape class? Otherwise, thanks for the cool solution!
Comment: @GManNickG It is, but i'm creating this more to learn C++ better
Comment: @chris what if the classes are unrelated?
Comment: @MintyAnt I couldn't understand why chris' suggestion wouldn't work, since if you're able to create a new RectangleShape, it should be do-able in the conversion operator too, no? Since KarthikT's solution also expects you to call the ctor of RectangleShape.
Answer: Your case is more neatly expressed as a conversion constructor
class RectangleShape{
    ....
    RectangleShape(const Rectangle&);
    ...
};

Then you would write
RectangleShape convertedShape = inRectangle;

And it would work as you would expected, without any unnecessary copies or constructions .
This would be similar to such a style.
RectangleShape convertedShape;
convertedShape.InitFrom(inRectangle);

Which would also not need a copy, since it is directly called as a method on the final object.
What chris suggested (if i understand it properly) would require a change on the class Rectangle, to allow it to convert itself to a RectangleShape.
class Rectangle{
    ....
    operator RectangleShape();
    ...
};

It would allow for a similarly elegant assignment code, but I am not sure how he intended to convert from one to another without a copy, if they are unrelated classes.
If you are not able to modify RectangleShape, the closest I can think of is doing something like this.
InitRectangleShape(convertedShape, inRectangle);
....
void InitRectangleShape(RectangleShape& convertedShape,const Rectangle& inRectangle);

Unless I am much mistaken, this is similar to how Return Value optimization is typically implemented. Which brings us to the points that other commenters have brought out, It is possible the compiler has already optimized the copy out for you.
Comment: @MintyAnt it is similar to a copy constructor yes, it only differs in name, it is more strictly refered to as a [conversion constructor](http://publib.boulder.ibm.com/infocenter/compbgpl/v9v111/topic/com.ibm.xlcpp9.bg.doc/language_ref/cplr384.htm)
Comment: @legends2k SFML is open source, so I can, but i'd rather keep my changes to my side of the code, and was curious what you'd do without an API. Karthik supplied the last solution as a good one
Comment: @MintyAnt: Of course, one should never return a reference to a local object, since it'll get destroyed once the function unwinds/returns. So, yes, in your example, `return convertedRectangle;` will be a disaster if the function's return type is by reference.
Comment: @MintyAnt Im glad i was able to help. As to the returning reference to a local variable, that I believe is Undefined behavior, which means its not expected to work by the standard, but it might work, based on implementation, configuration, phase of the moon etc. **Basically**, dont do it.
Comment: So it's just a copy constructor using a rectangle reference? Cool. What if the RectangleShape is part of an API I cannot access? What are my options then?
Comment: @MintyAnt If you cant change RectangleShape, you can pass an instance of `RectangleShape` within your converter to directly be used.
Comment: @KarthikT: But `RectangleShape` is part of SFML, right? How could one add a new ctor to it?
Comment: @legends2k My answer did not take that into consideration (i had no idea that it was a library class) which is what the OP also mentioned.
Comment: @KarthikT I think i'll go with your last suggestion, thank you for explaining out everything, it makes this a lot clearer. I have one quick question: I mentioned, in my example, returning a reference to the variable I created in the convert function. That DOES NOT work, because the object goes out of scope, right?
Comment: @KarthikT, You got my suggestion, minus the fact that you can stick the `explicit` keyword in there since C++11 to avoid implicit conversions from `Rectangle` to `RectangleShape` happening. I was not concerning myself with the extra copy, and with RVO, you'll most likely only ever have one `Rectangle` (which you start with) and one `RectangleShape` (rather than it being copied out of the function) when converting.


Using cookies to alter currency with scrapy request

Question: I am trying to extract data from this url. And below is the code which I've written to get this done.
cookies = {'.AspNetCore.Antiforgery.M6FGfmlbnTQ': 'CfDJ8A-eCRip5cVAs8-wkFU1H8dmFA0OIoxp6pQh1dcRvnpdNHKpKwFF2EhHSg5c-yqb-DriS6AIiwgnIpzyMiiphd42Un2v0-X6l8ePR4KkjG_CR2a_u6qrFOZNrRg0jrhliPOhyV6TKCtu6k-rn92lVMI',
 'uCurr': 'EUR'}

header = {'User-Agent': 'APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)',
 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
 'X-Requested-With': 'XMLHttpRequest'}

formdata = {'query': 'AR-LCAAAAAAAAApNjr0KwkAQhN9l6gvsXn5M1iqohZUSkweImqjgD6LYhLy7c0UgcMUcM7PzDXjBBrSwRByOMHjxGkkWSVKrmggfHE4zR3XunGGxjwuHbhI9LE8K73CZxJXtVblm-ka1aSqqO8znDg-YZqkLGBo7vOmL0m7DYveMmgM_Hx7imS8rWpDzB1swQmqU22q_q-rQCPSBYBlGw0IqzOk4_gFLkZV45QAAAA2',
 'discount': 'AG51bGw1',
 '__RequestVerificationToken': 'CfDJ8A-eCRip5cVAs8-wkFU1H8fDgaTCPGKJ6FVhqBSItqEvJHfZlsE0bsh4EKYxRKIpb3CDhue0bRj0jOgsLjyHTIvvEolzWwGt1CDfRlgnXrfO8NZiEE3ZQhIyeVShd5-AxG-QhQp4zSE3WeWo7Fr40DI'}

url = 'https://www.carflexi.com/data/getDeals'

In [47]: fetch(scrapy.FormRequest(url, method='POST', headers=header, formdata=formdata,cookies = cookies))
2021-04-25 19:21:11 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://www.carflexi.com/data/getDeals> (referer: None)

The problem is with currency parameter which is not working. I am trying to get data in EUR but it's giving me an output in my local currency.
In [48]: deal = json.loads(response.text).get('result').get('deals')[0]
In [49]: deal.get('priceString')
Out[49]: '57,622'

Comment: This is called geofencing. The web server is checking the IP address of the client that connects to it and compares that to a list of known IP ranges located inside that country. You are not gonna get the euro currency you have to use VPN or Proxy. If you would like to use proxy, I will help you to provide a free selenium proxy script.
Comment: Sure let me prepare for you
Comment: @MuratDemir please share the script. Also is there anyway to change the local computer's currency/country to get around this?
Comment: You can do it with proxy again
Comment: @MuratDemir would you please share the script you've?
Answer: Proxy nova is a free proxy provider we are trying to get the proxy address from that website before yielding the request. I used selenium to get the proxy IP.
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
class CarflexiSpider(scrapy.Spider):
    name = 'carflexi'
    allowed_domains = ['www.carflexi.com']
    start_urls = ['https://www.carflexi.com/data/getDeals']

    def __init__(self):
        self.proxy_adress_is = self.proxy_adress()

    def proxy_adress(self):
        url = "https://www.proxynova.com/proxy-server-list/country-de/"
        opts = Options()
        opts.add_argument('--headless')
        driver = webdriver.Chrome(options=opts,executable_path="chromedriver")
        driver.get(url)
        time.sleep(3)
        proxy_ip = driver.find_element_by_xpath('//*[@id="tbl_proxy_list"]/tbody[1]/tr[1]/td[1]/abbr').text
        proxy_ip = proxy_ip.replace(",","").strip()
        proxy_port = driver.find_element_by_xpath('//*[@id="tbl_proxy_list"]/tbody[1]/tr[1]/td[2]').text
        proxy_port = proxy_port.replace(",","").strip()
        driver.close()
        return proxy_ip+":"+proxy_port

    def parse(self, response):
        url = 'https://www.carflexi.com/data/getDeals'
        request = scrapy.Request(
                url, callback=self.parse_product)
        request.meta['proxy'] = self.proxy_adress_is
        yield request

    def parse_product(self,response):
        pass

The proxy_adress function will let you connect to a Germany IP then you can scrape EURO prices.
I didn't use the form request. You will change it depend on your script.


Utilizar variáveis externas ao Route do Laravel 5 para enviar à view

Question: Olá, estou trabalhando com o Laravel, e no meu arquivo de Rotas, eu gostaria de deixar criada uma variável que quero usar em todas as rotas, assim:
/routes/web.php

$foo = "ola mundo";

Route::get('/', function () {
    return view('page1', ["title" => "teste - $foo"]); //concatenação direta
});
Route::get('/page2', function () {
    return view('page2', ["title" => "bar - ".$foo]);  //concatenação por mesclagem
});

Meu problema é que (o que não faz sentido...) o Laravel não está conseguindo encontrar a variável $foo, mesmo ela estando declarada antes das estruturas de rotas e no próprio arquivo de configuração.
Independente do tipo de concatenação que uso, o Laravel não entende e me apresenta o erro:

ErrorException (E_NOTICE). Undefined variable: foo

Como resolver?
EDIT:
Fiz um teste definindo uma variável customizada dentro do arquivo .env e chamando ela através do método env('CUSTOM_FOO') que o Laravel disponibiliza e não tive nenhum problema, mas em uma variável criada no próprio arquivo (e que pelo meu entender de PHP deveria ter sido encontrada) não funciona...
Answer: As variáveis externas a uma função anônima não são visíveis dentro delas, para que você possa utilizar esta variável dentro de uma função anônima você precisa utilizar o use() após a chamada da função, veja:
$foo = 'foo';
Route::get('/', function () use ($foo) {
    return view('page1', ["title" => "bar - ".$foo]);
});

Desta maneira, a variável será acessada somente para leitura

Caso você precise alterar a variável externa à uma função anônima, você precisará passa-la por referência:
$foo = 'foo';
Route::get('/', function () use (&$foo) {
    return view('page1', ["title" => "bar - ".$foo]);
});

Comment: excelente, muito obrigado!!! acabou que eu preferi deixar dentro do arquivo `.env` mesmo porque assim posso usar essa declaração estática em outros locais do sistema, mas muito obrigado mesmo assim...
Comment: sim, eu recomendaria isso mesmo @LeandroLuk


question about transitive relation

Question: can any one explain these answer
1)we have set $X={1,2,3,4}$,the relation set is given as
$R={(1,2),(3,4)}$
it is transitive
also, $r={(4,4)} $
it is transitive
why the sets R,r have achieved the property of transitive ?
thanks
Answer: Transitive relation:
For all $a,b,c \in R \times R$:
$$ aRb \land bRc \space \implies aRc$$
Meaning: if $a$ relates to $b$ and $b$ relates to $c$, transitivity demands that $a$ relates to $c$ as well.
${(1,2)(3,4)}$ is transitive because it is not given the opportunity not to be :-). Notice that the 2nd element of each couple never appears as a 1st element. So the IF of transitivity is always false, and hence the implication is always true, and we have a transitive relation!
$r$ satisfies the above: $4R4$ and $4R4$ indeed, but we also have $4R4$. :-P
$R \cup r$ indeed is transitive. check it!
Answer: Recall that a set is transitive if (and only if) whenever we take two ordered pairs of the form $(x,y)$ and $(y,z)$ from the relation, we are guaranteed that $(x,z)$ is also in the relation.
Both the examples that you gave satisfy that simply because if we take $(x,y)$ and $(y,z)$ then it is necessarily the case that $(x,y)=(y,z)$ and therefore $x=y=z$, so $(x,z)$ is also in the relation.
Note that nowhere we request that $x\neq y$ and $y\neq z$ in the definition.

question about transitive relation


NSURLSessionDownloadTask file removed before reading contents

Question: I have the following piece of code which has been working for several months and has just started becoming intermittently broken.
I am making changes to the way that it is being called, so it's not totally unsurprising, but the symptoms are baffling me.  The temporary file being downloaded by some requests, is seemingly being deleted before the data is read.
I have attributes about the file, it's location, and when running in a simulator I've even confirmed the file contains the correct data, while in a breakpoint.  However as soon as [NSData dataWithContentsOfFile:[location path]] or [NSData dataWithContentsOfURL:location] is called, the file is removed from the filesystem and if I use the method with an NSError passed in, the error I get is Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn't be completed.
My Code:
- (void)makeSoapRequest:(NSURL *)url soapRequest:(NSString *)soapRequest completionBlock:(void (^)(NSData *xmlToParse, int error))completionBlock attemptNumber:(int)attemptNumber
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:nil delegateQueue:nil];
    NSData *bodyData = [soapRequest dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"" forHTTPHeaderField:@"SOAPAction"];
    [request addValue:[NSString stringWithFormat:@"%d",(int)[bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:bodyData];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    if (!(location == nil))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                NSLog(@"nsurl error was: %@", error);
            }
            else
            {
                NSError* errorObj;
                NSString *path = [location path];

                NSDictionary* attribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&errorObj];
                NSData *xmlData= [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&errorObj];
                if (errorObj != nil) {
                    NSLog(@"Attributes of file: %@", attribs);
                    NSLog(@"Error reading the downloaded data, error was: %@", errorObj);
                }
                completionBlock(xmlData, 0);
                return;
            }
        });
    }
    else
    {
        if (error)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
    }
}];
[downloadTask resume];
}

My Attributes printout:
Attributes of file: {
NSFileCreationDate = "2016-11-23 13:15:00 +0000";
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 501;
NSFileGroupOwnerAccountName = mobile;
NSFileModificationDate = "2016-11-23 13:15:00 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName = mobile;
NSFilePosixPermissions = 384;
NSFileReferenceCount = 1;
NSFileSize = 947;
NSFileSystemFileNumber = 534146;
NSFileSystemNumber = 16777218;
NSFileType = NSFileTypeRegular;
}

Error log:
2016-11-23 13:27:43.285 GCMMobile[2780:829109] Error reading the downloaded data, error was: Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn't be completed. (Cocoa error 260.)" UserInfo=0x1704605c0 {NSFilePath=/private/var/mobile/Containers/Data/Application/BF6BE574-AA1A-492E-A1DD-04334F33E2D7/tmp/CFNetworkDownload_VHyKp6.tmp, NSUnderlyingError=0x17024ce10 "The operation couldn't be completed. No such file or directory"}

Any help most appreciated...
Answer: The problem is that you are returning from the NSURLSessionDownloadTask completion handler before moving or opening the downloaded file. As the documentation states:

You must move this file or open it for reading before your completion
  handler returns. Otherwise, the file is deleted, and the data is lost.

By dispatching to the main queue and returning you are postponing your file-reading code to some indefinite time in the future. You should move or open the file in the completion handler itself, and only then dispatch to another queue for subsequent processing.
Comment: Thanks for this - I moved everything except for the `completionBlock()` outside of the `dispatch_async` and my problem went away.  I guess I was just lucky when I started developing this that I never encountered the issue before.  I clearly didn't twig that by calling `dispatch_async` I would be returning from my method, and thus the file would be deleted.


How can a scale sound sadder/darker than the scale with the same key signature?

Question: There is a general principle used to describe the intensity of a mode. The more flat notes there are in the formula of the mode, the darker it sounds. So the Locrian scale is the saddest/darkest mode, because it has 5 flats: 1 b2 b3 4 b5 b6 b7.
Then how can for example A Locrian sound dark and sad, but it has the same key signature as Bb major? Major keys are the same as the Ionian mode, and the Ionian mode has no sharps and flats in the formula: 1 2 3 4 5 6 7. So the major key sounds happy and bright. So if the tonic is A, it sounds sad, but if the tonic is Bb it suddenly sounds bright and happy? How is this possible ?
An easier example : C Major and A Minor.
Answer: It's all about context and emphasis.  When we say that something is in a particular key or mode, we are describing what sounds like the home or most important note.  So the reason we would say we're in C major instead of B locrian is that the emphasis is placed on C and everything is compared to that.  When we look at keys/modes, we can look at how the other notes within the mode sound compared to the root.  The flat scale degrees are more dissonant when played with the root than would be the natural/major scale degrees found in a major mode.
You can also consider this in terms of chords.  It may be easier to recognize that the combination of some notes sounds more bright/consonant or dark/dissonant.  If you take those chords and consider a scale/mode that goes with them, then consider that being your tonic, you should be able to see how that set of notes, within the context of that chord, sounds more dissonant than the same set of notes against a major chord derived from them.
So it's all about context.  You have to consider what is happening in the music and what is the focal point of the melody and harmony.
Comment: @Stallmp - Glad to provide some insight for you.  I'd also point out that there are other modes, some of which you may think of as darker, that don't come from the notes of the major scale.  Harmonic Minor and Melodic Minor modes are pretty fun and some are quite dark sounding.
Comment: Yes and no.  If you look at them as modes, you will see that not all of them are brighter.  For instance, the altered scale, which is built off of the 7th degree of ascending melodic minor, is very dissonant.  This would also be an example of flat scale degrees not necessarily being the key factor in determining dissonance.
Comment: Arent harmonic and melodic minor scales brighter than the natural minor scale, since it lowers less notes than the natural minor scale?
Comment: Great answer, +1! I'm used to thinking about darkness/brightness of a scale in terms of color (e.g., A major is brighter and Db major is darker). Does dissonance also translate into *that* type of darkness vs. brightness? Or are you more thinking more about "happy" and "sad"?
Comment: @jdjazz - It's a little subjective when you start talking about "brightness" and "darkness", in the same way that "happy" and "sad" are very subjective. People tend to say major is happy and minor is sad but it's fairly easy to find examples of that not being the case, even just playing a major 7 chord compared to a minor 7 chord changes that a bit for me.  I don't tend to find that particular keys are brighter or darker inherently but you can find some tendencies based on the instruments playing them.
Comment: It seems that the lower the bass note, the darker a piece will sound, so if you're on guitar, E will usually sound darker than Eb.  Different instruments also have different timbres in different registers as well, so the perceived brightness/darkness of a song may be very much impacted by the register of the instrument as well.  When we talk about consonance and dissonance, we step outside of the realm of subjectivity, as it can be measured.
Comment: @Basstickler, check out this other interpretation of brightness/darkness, which depends on how many flats vs. sharps a key has: https://music.stackexchange.com/questions/43168/are-sharp-keys-bright-and-flat-keys-dark
Comment: @jdjazz - Yes and I've heard it elsewhere, most recently it was Jacob Collier speaking about it (who you should definitely check out if you're a theory geek).  I think it's really all relative.  When you modulate up, it tends to sound brighter and vice versa, but due to the arbitrary nature of our naming system, this gets sticky.  If I modulate from C# to Ab, I'm going from 7 sharps to 4 flats, which should be darker but that's enharmonically equivalent to G# (8 sharps), so what happens there? Even the answers from the question you linked to mention that it is subjective.
Comment: @Basstickler, I haven't heard a ton of Jacob Collier, but I love his recording of Fascinating Rhythm! I definitely agree that some aspects are definitely relative (and there are some gray areas as you point out--C#Maj obviously isn't brighter than DbMaj). But I also have the feeling that there's something objective given how many people experience, e.g., the difference between Amaj and EbMaj. I wonder if the particular mode is another fact that impacts this perceived quality of brightness/darkness.
Comment: @Basstickler, I've posed the question here: **https://music.stackexchange.com/questions/65619/are-all-modes-scales-in-a-given-key-signature-equally-bright-dark** and would be interested in your thoughts
Comment: @jdjazz - Common doesn't necessarily mean objective.  People commonly thought that alcohol warms you up and would give it to people dying of hypothermia, only to later realize that the warming sensation was your blood thinning, along internal heat to rise to the surface and actually expedite their loss of heat and therefore death.  If we can't find a definitive way to measure it, it's subjective.  Happy/major and minor/sad is the best musical example because it is incredibly relatable but easily debunked.  Look up Jacob Collier talking about theory. His music is cool but the theory is insane.
Answer: Every mode shares a key signature and a pitch set with some major key.  But the different 'tonic' gives its scale a different colour, as you state.  That's the whole POINT of modes!
Comment: Thank you for this. There's really nothing more to say here.


Cannot assign a string value to typescript enum (Initializer type string not assignable to variable type)

Question: It seems that from TypeScript 2.4 onwards String Enums  are a feature.
However the following does not work:
enum Foo {
    A = "A",
    B = "B"
}

var foo : Foo = "A";

Initializer type string not assignable to variable type Foo

String literals work:
type Foo = "A" | "B";

But what if I want to use an enum? Is there a way around this?
Comment: it seems to me that no answer provides explanation to why this won't work. From a similar issue on github:
"The intent of string enums is that the values of the enum are opaque (i.e. they can be changed behind the scenes without breaking consumers). If you don't want that behavior, it's easy enough to use the pre-string-enum workarounds to create similar union types.

Numeric enums allow assignments from arbitrary numbers because we need to support bitflag enums and the | / & / etc operators return number. There's no corresponding behavior for string enums that needs to be supported."
Answer: You can use an index expression to get the value of the enum:
enum Foo {
    A = "A",
    B = "BB"
}

var foo : Foo = Foo["A"];
var fooB : Foo = Foo["B"];

Note that the key will be the name of the member not the value.
You could also use a type assertion, but you will not get errors if you assign a wrong value:
var foo : Foo = "A"  as Foo;
var foo : Foo = "D"  as Foo; // No error

Comment: Though you won't get compile errors on attempt to use a value that does not exist in this enum with such approach
Comment: This won't work if enum is private and never exposed. Need a better solution for tests.
Answer: As Foo is the enum so you can use the . as well to accesss the value of enum like below
var foo : Foo = Foo.A;

Answer: While not a direct answer to the question per se (as it doesn't assign to enum but a derivative type), I discovered this which does solve my problem of allowing me to assign a string and guarantees that it's a part of the enum, and even allows me to avoid the redundant A = "A" when all that really matters is A.
You can use keyof [1] to enumerate the properties on the typeof the enum (Foo)
enum Foo {
    A,
    B
}

var foo : keyof typeof Foo = "A"; // OK
var foo : keyof typeof Foo = "C"; // ERROR

Or on objects:
interface Bar {
    type: keyof typeof Foo
}

let obj: Bar = {
    type: "A" // OK
}

[*] I'll mark one of the other answers as accepted and keep this here for reference
Answer: As described into the typescript enum documentation
you can use it in different ways :
Enum.A // Good way

Enum["A"] // Bad way

Enum[variable] // Good way

In your case
enum Foo {
    A = "A",
    B = "B"
}

// Bad way
const example1 : Foo = Foo["A"];

// Good way
const example2 : Foo = Foo.A;

// Good way
const example3 : Foo = Foo[variable];

You should AVOID the use of example1 and focus on example2 and example3. In any case, there is no point to write "A".
Always prefer Enum.A and if you want to cast a variable as an enum use Enum[variable].


Android gradle build includes jni libs twice

Question: I've been trying to solve a problem about Android build, but couldn't figure out how to solve it.
Basically, I am trying to build an Android project using Gradle. It works perfect, but the size of the final apk is 7MB more than when I builded with Eclipse.
When I unzip the apk, I see that the JNI Libs are included twice. Which is different from the Eclipse build that includes it only one time. Here is the paths I can find them in the APK:

lib/armeabi
lib/armeabi-v7a
main/jniLibs/armeabi
main/jniLibs/armeabi-v7a

In my project, those two files are in:

android/app/src/main/jniLibs/armeabi
android/app/src/main/jniLibs/armeabi-v7a

I have two different build.graddle files in:

android/
android/app/

None of them contains anything related to the JNI Libs.
To build a release, I use the command:
<code>./gradlew assembleRelease
</code>
And everything works fine. I use Gradle 1.10.
I was wondering if someone ever encountered the problem and find a solution to avoid to the JNI Libs to be included twice in the APK.
Thanks :)
Answer: Put .so files in...
/src/main/jniLibs/armeabi-v7a
/src/main/jniLibs/x86
directories and gradle will correctly package the .so files into the correct app and it won't include the duplicates
This is a good reference..
http://www.shaneenishry.com/blog/2014/08/17/ndk-with-android-studio/


Sphinx indexer slows down the database: How to give it low priority?

Question: All my tables use InnoDB, and I have set sphinx sql_range_step to the minimum, which is 128. This improved the performance a lot, but it is still very slow if you make a request right after a new step begins.
I'm sure it would work just fine if I could reduce the range step to 10 or something, but someone found that the min value is hardcoded and there is no way to change it (other than editing the source).
So I was wondering if there was a way to deal with this directly from MySQL. When I am indexing a database, the other databases aren't affected, so it's not the whole server which has been slowed down, but only the database I am indexing.
Is there a way to give less priority to a user or query, or something?
Answer: Take a look at this similar post from StackOverflow. You may be able to use those strategies to give sphinx a lower priority.
Answer: Have a look at this
The idea is to insert some code in your query that is throttling down query execution.
For a quickest approach you can use a query like this:
<code>select <your stuff> from <your table where <your condition> and (sleep (0.1) or 1)
</code>
That will make sphinx query to wait for 0.1 seconds before finishing.


Show a ProgressDialog when I crop a photo

Question: I have a picture that I can change.
I can choose a picture in my gallery or capture a photo.
When I capture a photo, I crop the image.
But the application takes time to crop my photo so I want to show a progressDialog.
My progressDialog appears on my application but it is hidden by the screen where I crop my photo.
How can I make the progressDialog appear inside the screen where I crop my photo ?
Sorry for my bad english...
My code :
public class FragmentMonCompte extends Fragment {

    private ImageView ivAvatar;
    // YOU CAN EDIT THIS TO WHATEVER YOU WANT
    private static final int CAPTURE_PICTURE = 0;
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    // ADDED
    private String filemanagerstring;

    private Uri mCapturedImageURI;

    ProgressDialog mProgressDialog = null;
    boolean isPDShow;
    Navigation navigation;
    Intent data;
    Bitmap photo;
    Bundle extras;

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

        ivAvatar = (ImageView) rootView.findViewById(R.id.iv_avatar);

        ivAvatar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                final Navigation navigation = (Navigation) getActivity();

                mProgressDialog = new ProgressDialog(navigation);
                mProgressDialog.setMessage("Opération en cours...");
                mProgressDialog.setTitle("Patientez");

                final CharSequence[] items = {"Prendre une photo",
                        "Choisir une image", "Annuler"};

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        getActivity());

                // set title
                alertDialogBuilder.setTitle("Avatar :");

                // set dialog message
                alertDialogBuilder.setCancelable(false).setItems(items,
                        new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int item) {

                        if (item == 0) {
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Images.Media.TITLE,
                                    "");
                            mCapturedImageURI = navigation
                                    .getContentResolver()
                                    .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            values);

                            Intent intent = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);

                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    mCapturedImageURI);
                            intent.putExtra("crop", "true");
                            intent.putExtra("aspectX", 170);
                            intent.putExtra("aspectY", 170);
                            intent.putExtra("outputX", 5000);
                            intent.putExtra("outputY", 5000);
                            startActivityForResult(Intent
                                    .createChooser(intent,
                                            "Appareil photo"),
                                            CAPTURE_PICTURE);
                        }

                        if (item == 1) {
                            Intent intent = new Intent(
                                    Intent.ACTION_GET_CONTENT);

                            intent.setType("image/*");
                            intent.putExtra("crop", "true");
                            intent.putExtra("aspectX", 170);
                            intent.putExtra("aspectY", 170);
                            intent.putExtra("outputX", 5000);
                            intent.putExtra("outputY", 5000);
                            startActivityForResult(Intent
                                    .createChooser(intent,
                                            "Choisir une application"),
                                            SELECT_PICTURE);
                        }

                        if (item == 2) {
                            dialog.cancel();
                        }

                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // afficher
                alertDialogBuilder.show();

            }
        });

        return rootView;
    }

    /**
     * Méthode qui permet d'ouvrir la gallery d'images ou l'appareil photo
     *
     * @param requestCode CAPTURE ou SELECT
     * @param resultCode RESULT_OK or not
     * @param data Intent
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Navigation navigation = (Navigation) getActivity();

        this.navigation = navigation;
        this.data = data;

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAPTURE_PICTURE) {

                isPDShow = true;

                if( mProgressDialog!=null && !mProgressDialog.isShowing()) {
                    mProgressDialog.show();
                }

                new Thread() {
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            handler.sendEmptyMessage(0);
                        }

                        start();
                    }
                };

                Bitmap photo = null;
                Bundle extras = data.getExtras();

                new CapturePhotoAsyncTask().execute((Void) null);

            }

            if (requestCode == SELECT_PICTURE) {

                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ivAvatar.setImageBitmap(photo);

                }

            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if( mProgressDialog!=null & mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    /**
     * Méthode qui retourne un bitmap compressé
     *
     * @param c Context de l'application
     * @param uri Photo capturée
     * @param requiredSize Taille requise
     * @return Photo convertie en Bitmap
     * @throws FileNotFoundException Fichier non trouvé
     */
    public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize)
            throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri),
                null, o);

        int widthTmp = o.outWidth, heightTmp = o.outHeight;
        int scale = 1;

        while (true) {
            if (widthTmp / 2 < requiredSize || heightTmp / 2 < requiredSize) {
                break;
            }
            widthTmp /= 2;
            heightTmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(c.getContentResolver()
                .openInputStream(uri), null, o2);
    }

    class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPostExecute(Boolean result)
          {
              super.onPostExecute(result);

              ivAvatar.setImageBitmap(photo);

              mProgressDialog.dismiss();
          }

        @Override
        protected Boolean doInBackground(Void... params) {
                try {
                    photo = decodeUri(navigation.getApplicationContext(),
                            mCapturedImageURI, 1000);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            return null;
        }

    }//fin AsyncTask

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            new CapturePhotoAsyncTask().execute((Void) null);
            isPDShow = false;
        }
    };

}

Comment: share your effort with us!
Comment: For that you have to show us your code.
Comment: Add some code for more direction..
Comment: you cam use framelayout to show your progressDialog over the screen
Comment: In your `ProgressDialog` are you using `AlertDialog` in it???
Comment: No, the AlertDialog is used for choose "Capture photo" or "Select image"
Answer: class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(FragmentMonCompte.this);
        pDialog.setMessage("Downloading data");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected void onPostExecute(Boolean result)
      {
          super.onPostExecute(result);

          ivAvatar.setImageBitmap(photo);

          pDialog.dismiss();
      }

    @Override
    protected Boolean doInBackground(Void... params) {
            try {
                photo = decodeUri(navigation.getApplicationContext(),
                        mCapturedImageURI, 1000);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return null;
    }

}//fin AsyncTask

Comment: This is the same.
I see progressDialog when the screen of crop is close.


How to make a Data Selector a negative value in a rule action?

Question: I create a rule and inside it I added a action, this action involves a data selector: node:field-labpoints. I need to make this data selector a negative value.
I tried with -node:field-labpoints and -[node:field-labpoints] but it is not accepted.
look my capture:
Answer: You have two ways to do this.
Either you use PhP filter, which will add under "data selector" and "add offset" a new option, "php evaluation", which will allow you to post-treat this value. Then you'll just have to set return intval(- $value);
Or you can use whole Rules, by :

Action: Add a value, and select your [node:field-labpoints]
Action: Calculate a value, and make it negative
In your action, use this value instead of the one you selected with the selected.
Comment: I don't have the `Add a value` action. Do you have any other rules module to have this action?
Comment: for those of you looking for a link to PHP Filter (like me):  PHP Filter is a module included in core!  It's already there (like magic).
Comment: PHP Filter it's bad practice. http://drupal.stackexchange.com/a/2512/6309


Assign existing SNS Topic to Alarm in Terraform

Question: I have an existing SNS topic that isn't managed with Terraform that I want to reference so I can assign it within an aws_cloudwatch_metric_alarm.alarm_actions list. When trying to run plan or apply I'm getting the following message:

unknown resource 'aws_sns_topic.my-alerts' referenced in variable aws_sns_topic.my-alerts.arn

Judging by the message I'm guessing I have to create an SNS resource somehow but I'm not sure how to attach/reference it with the existing topic.
I'm referencing the existing topic in a data block:
data "aws_sns_topic" "my-alerts" {
  name = "my-alerts"
}

Then trying to use later in an alarm like:
resource "aws_cloudwatch_metric_alarm" "app-health-alarm" {
  alarm_name                = "app-health-alarm"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  evaluation_periods        = "2"
  metric_name               = "ApplicationComponetHealthRequestFailing"
  namespace                 = "ApplicationComponetHealth"
  period                    = "300"
  statistic                 = "Average"
  dimensions                = {
                                component="my-app"
                              }
  threshold                 = "1"
  alarm_description         = "Checks the health of the app"
  datapoints_to_alarm       = "2"
  alarm_actions             = ["${aws_sns_topic.my-alerts.arn}"]
}

Answer: When referencing a data source you need to prefix it with data.
So in your case it should be:
resource "aws_cloudwatch_metric_alarm" "app-health-alarm" {
  alarm_name                = "app-health-alarm"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  evaluation_periods        = "2"
  metric_name               = "ApplicationComponetHealthRequestFailing"
  namespace                 = "ApplicationComponetHealth"
  period                    = "300"
  statistic                 = "Average"
  dimensions                = {
                                component="my-app"
                              }
  threshold                 = "1"
  alarm_description         = "Checks the health of the app"
  datapoints_to_alarm       = "2"
  alarm_actions             = ["${data.aws_sns_topic.my-alerts.arn}"]
}

Comment: Thanks @ydaetskcoR. That also uncovered another issue though, you're not allowed to define the `arn` field in the `data.aws_sns_topic` block. Removing that and just referencing by name did the trick.


How does pseudoreplication differ from resampling

Question: I wonder how pseudoreplication (https://en.wikipedia.org/wiki/Pseudoreplication) differs from resampling (which is simply resampling with replacement from a given sample).
On the one hand, resampling methods offer a convenient way to assess the distribution of statistics (which is good).
On the other hand, pseudoreplication seems to have a really bad reputation and is stated to be a problem. I understand that pseudoreplication was pointed out as a problem because of repeated measurements of an individual which are clearly correlated, while performing statistical tests etc. which assume uncorrelated data. ("Pseudoreplication occurs when observations are not statistically independent, but treated as if they are" https://bmcneurosci.biomedcentral.com/articles/10.1186/1471-2202-11-5#:~:text=Pseudoreplication%20occurs%20when%20observations%20are,correlated%20in%20time%20or%20space.)
However, I found wordings like

"pseudoreplication techniques, especially bootstrap ..." https://www.google.de/books/edition/Practical_Methods_for_Design_and_Analysi/reYkGe9PLMQC?hl=de&gbpv=1&dq=%22pseudoreplication%22%20%22bootstrap%22&pg=PA149&printsec=frontcover&bsq=%22pseudoreplication%22%20%22bootstrap%22
"The next step in the logic is that of pseudoreplication. This involves
resampling the data after they are collected but in a way that
reflects the sampling procedures"  https://support.sas.com/resources/papers/proceedings/proceedings/sugi22/STATS/PAPER279.PDF

which suggest that resampling techniques produce pseudoreplications.
Additionally, I found this book which seems to discuss pseudoreplication due to boostrapping on page 272 (but I do not get the point of the argument)
https://books.google.de/books?id=B9PDDQAAQBAJ&lpg=PA272&ots=Doj3ob14Jn&dq=%22pseudoreplication%22%20%22resampling%22&hl=de&pg=PA272#v=onepage&q&f=false
If pseudoreplication is such a big problem, then why doesn't this imply that resampling always has to suffer from this problem of pseudoreplication? And if this pseudoreplication is a problem in the bootstrap, is there a nice illustration showing the problem of psueodreplication and when do I know that I am running into the problem of pseudoreplication when applying the bootstrap?
I am struggling with "pseudoreplication" being branded as an incredible huge problem whenever you search for it, but also resampling (which is really cool) being called a pseudoreplication method. I want to get the implications right here.
PS: having a set of paired feature vectors and labels, i.e. ((feature_1, feature_2, ...), label) it is clear to me that it only makes sense to do a pair bootstrap and resample the whole tuple (feature vector, label) because each feature_i might be correlated to another feature. But applying the bootstrap here to resample single feature values is an obvious application error.
PPS: This post has more literature on pseudoreplication: Is Hurlbert 1984 the best introductory overview to pseudoreplication?
Answer: I coined the term pseudoreplication for a class of statistical errors in the late 1970s not realizing it had occasionally been used in the past (CJ MCCarthy 1969)for completely different concepts or practices. The wikipedia article (which I had no role in) is focused on my first paper on the topic but is unclear, out of date and reflects unawareness of a large body of post-1984 papers on the topic. Below is a list of my own on the topic. I can send a pdfs; just contact me at firstname.lastname@example.com. I suggest the 2009 paper as an introduction to this literature.
Hurlbert, S.H.  1990.  Pastor binocularis:  Now we have no excuse [review of Design of Experiments by R. Mead]. Ecology 71: 1222-1228.
Hurlbert, S. H. and M. D. White.  1993.  Experiments with freshwater invertebrate zooplanktivores: Quality of statistical analyses.  Bull. Mar. Sci. 53: 128-153.
Lombardi, C.M. and S.H. Hurlbert. 1996.  Sunfish cognition and pseudoreplication.  Animal Behaviour 52:419-422
Hurlbert, S.H., 1997.  Experiments in ecology [Review of book by same title by A.J. Underwood].  Endeavour 21:172-173.
Hurlbert, S.H., and C.M. Lombardi. 2003. Design and analysis: uncertain intent, uncertain result [review of Experimental design and data analysis for biologists by G. Quinn and M. Keough]. Ecology 83:810-812.
Hurlbert, S.H. and W.G. Meikle. 2003. Pseudoreplication, fungi, and locusts. Journal of Economic Entomology 96:533-535.
Hurlbert, S.H. 2004. On misinterpretations of pseudoreplication and related matters: a reply to Oksanen. Oikos 104: 591-597.
Kozlov, M. and S.H. Hurlbert. 2006. Pseudoreplication, chatter, and the international nature of science. Journal of Fundamental Biology 67(22):128-135. [In Russian; English translation available as pdf].
Hurlbert, S.H. 2009. The ancient black art and transdisciplinary extent of pseudoreplication.   Journal of Comparative Psychology 123: 434-443.
Hurlbert, S.H. 2010. Pseudoreplication capstone: Correction of 12 errors in Koehnle & Schank    (2009). Department of Biology, San Diego State University, San Diego, California. 5 pp.
Hurlbert, S.H. 2012. Pseudofactorialism, response structures, and collective responsibility. Austral Ecology 38: 646-663 + suppl. inform.
Hurlbert, S.H. 2013. Affirmation of the classical terminology for experimental design via a critique of Casella's Statistical Design. Agronomy Journal 105: 412-418 + suppl. inform.
Hurlbert, S.H. 2021. Pseudoreplication revisited: Some little-known history of an ancient big problem. Manuscript in revision.
Answer: If I understand correctly, pseudoreplication is for example about treating highly correlated data as if it was independent data.
In such a case also the bootstrap would have trouble because (with insufficient sample size) the empirical distribution function would not match the population distribution function. If we would apply the bootstrap in such a case (where the empirical distribution function differs from the population distribution function due to small sample size and high correlation), we would also run into the problem of pseudoreplication with the bootstrap method.
However, given the empirical distribution function is a good representation of the population distribution function, then the bootstrap does not have a problem of pseudoreplication.