Alterar "Step" no "printing progress" do Quickreport

Question: Estou desenvolvendo um sistema para impressão de cartelas, por isso envio arquivos extensos para impressão, algo em torno de 25000 paginas por vês. Devido a essa grande quantidade páginas o "printing progress" do Quickreport demora 2 minutos para avançar os 5% de passo. Como faço para alterar o passo/avanço (também chamado de stepIt no progressBar) no Quickreport?
Answer: Eu não encontrei uma forma "convencional", mas é possível alterar o avanço diretamente no arquivo do próprio Quickreport.
A unit se chama "qrprgres.pas" e fica na pasta raiz de instalação do Quickreport. Basta ir até o método procedure TQRProgressForm.CMQRPROGRESSUPDATE(var Message); e alterar a linha if (FQRPrinter.Progress mod 5) = 0 then para if (FQRPrinter.Progress mod 2) = 0 then e recompilar, assim o avanço passará a ser de 2%.


How to find the Green's function

Question: Consider a domain $$D= \{(x,y) : x>0, y>0 \}$$ Let $\textbf x = (x,y)$ and $\xi =(\xi_x , \xi_y)$. Find the Green's function, $G(\textbf x , \xi)$ such that $$\nabla ^2 G=\delta (\textbf x - \xi), \, \, \, \, \, \, \textbf x \in D$$ subject to $$\frac{\partial G}{\partial x}(0,y,\xi)=0, \, \, \, \, \, \text{for} \, \, \, \, y>0$$
and $$G(x,0,\xi)=0, \, \, \, \, \, \text{for} \, \, \, \, x>0$$

Using method of images:
We have the source $\xi=(\xi_{x},\xi_{y})$ and images sources:
$\xi_1=(-\xi_{x},\xi_{y})$, $\xi_2=(\xi_{x},-\xi_{y})$, $\xi_3=(-\xi_{x},-\xi_{y})$
So we have $\nabla ^2 G=\delta ( \textbf x - \xi )\pm \delta ( \textbf x - \xi_1 ) \pm \delta ( \textbf x - \xi_2 )\pm \delta ( \textbf x - \xi_3 )$
Can someone please clearly explain how you determine if the plus/minus signs are in fact plus or minus please.
I know that it is to do with the boundary conditions but don't understand how.
Answer: The correct extension is
$$\nabla^2G = \delta(\mathbf{x}-\xi) + \delta(\mathbf{x}-\xi_1) - \delta(\mathbf{x}-\xi_2) - \delta(\mathbf{x}-\xi_3)$$
To see why, interpret $G$ as electric potential.  Then, the delta functions correspond to point charges, and we have the conditions that (i) the potential is symmetric across $x=0$, and (ii) the potential is zero along $y=0$.  The first condition implies that the sign on the delta function at $\xi_1$ should be the same as the sign on the delta function at $\xi$, while the second condition implies that the sign on delta function at $\xi_2$ should be opposite the sign at $\xi$.  Then, since $\xi_3$ is the reflection of $\xi_2$ over $x=0$, the delta function there should have the same sign as $\xi_2$ (alternatively, since it is the reflection of $\xi_1$ over $y=0$, it should have the opposite sign from the delta function at $\xi_1$).
Solving for $G$ yields
$$G = \ln\frac{1}{|\mathbf{x} - \xi|} + \ln\frac{1}{|\mathbf{x} - \xi_1|} - \ln\frac{1}{|\mathbf{x} - \xi_2|} - \ln\frac{1}{|\mathbf{x} - \xi_3|}$$
and we can verify that $G$ satisfies the required boundary conditions.
Comment: Remember that the Green's function is defined such that the solution to
$$\Delta u = f$$ is $u(x) = (G(x,\cdots) * f(\cdot))(x)$.  In other words, the Greens function tells you how the differential equation responds to an impulse of one unit at the point $\xi$.  The points $\xi_1$, $\xi_2$, and $\xi_3$ are obtained by reflecting $\xi$ over the boundary lines $x=0$ and $y=0$.
Comment: I'm also really not sure what you mean by an 'informal' way to find the Greens function.  What do you mean by 'informal'?
Comment: (1): $\xi_x$ and $\xi_y$ are positive real numbers, but they are not fixed.  Remember that for
$$\Delta u = f$$
with the given boundary conditions, we have
$$u(\mathbf{x}) = \iint_{x>0,y>0} G(\mathbf{x}, \xi) f(\xi)\;d\xi_x d\xi_y$$

(2): Sorry, I meant to write $\xi_2$.

(3): Well, you've already noticed that if you reflect over a line with Neumann boundary conditions, you don't change the sign of the delta function.  Why would that change when you reflect a second time?
Comment: Does $\xi$ basically mean an arbitrary point anywhere on the xy plane? And does $\xi_1$ mean an arbitrary point anywhere on left quadrants? And $\xi_2$ etc...?
Comment: Is there an informal way to do this? I still don't get it...
Comment: I have 3 questions. (1) Are $\xi_x$ and $\xi_y$ strictly positive numbers that are fixed? Or nonnegative or any real number? (2) You mentioned $x_2$ in your answer, what is this? (3) If we had conditions of $\partial G(0,y,\xi)/\partial x=\partial G(x,0,\xi)/\partial y =0$ instead, then it would be all addition for the delta functions, but why? I would have thought we would add $xi_1$ and $\xi_2$ but not the $\xi_3$...
Comment: Thanks, so if we had $\partial G(x,0,\xi)/\partial y$ and $G(0,y,\xi)$ conditions instead, then would it be, writing informally, $\xi +\xi_2 - \xi_1 - \xi_3$?
Comment: That's correct!
Comment: Hi again. Our lecturer said that we should be able to work out in 2 or 3 dimensions. I didn't know what he meant. Because finding the plus or minus stuff we did here in three dim would be so hard. And I am sure with greens second identity, it is only for 2 dim... What do you tthink?
Comment: @Strants would if the boundary conditions are dg/dx=0 and dg/dy=0?
Comment: Is there mathematical approach for someone without knowledge in physics?  thank you

How to find the Green's function


log4j creates log file but does not write the messages that I am creating

Question: Log file is getting created and logs are getting written into it.But , it doesn't write the things that i specify in
LOG.trace("") and LOG.error("") etc.
log4j.rootLogger=INFO,R

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%-5p %c{1}:%L - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.MaxFileSize=20MB
log4j.appender.R.File= /home/raremile/Documents/logsInfer/InferlyticsConsumerStorm.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %r [%t] %-5p %c - %m%n
log4j.appender.R.MaxBackupIndex=10

log4j.appender.Con=org.apache.log4j.ConsoleAppender
log4j.appender.Con.layout=org.apache.log4j.PatternLayout
log4j.appender.Con.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %r [%t] %-5p %c - %m%n

Answer: log4j.rootLogger=TRACE,error,R

TRACE is the lowest level of logging, while your current configuration is on INFO which is the highest.
Answer: Log4j Logging levels are enabled based on the order
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL

So, if you enable INFO logging level WARN, ERROR, FATAL log statements will also get logged to file or console. But TRACE log statements will not be logged.


How to theme webform elements (radio buttons etc.)?

Question: I would like to know how to theme Drupal 7 Webform elements?
I want to change the HTML structure of every element, not just wrap form with div or something like that. And I want to leave theme's elements as they were.
EDIT:
I would like to add class to label and input type radio button.
Comment: see this answer http://drupal.stackexchange.com/questions/73713/how-to-theme-a-webform-d7/73716#73716 and also web form theming http://drupalcode.org/project/webform.git/blob/HEAD:/THEMING.txt
Comment: I have already checked those threads. The theming.txt doesn't say anything about form elements, just whole form, etc.. So does the first link you gave. Example: i would like to edit label's style .
Comment: then what the problem you are facing?
Comment: I don't know how to do that :) Style form element just for webforms, not the whole theme ..
Comment: +1 useful question - and answer below. Thank you. In my case I needed to insert `autocomplete=off` in the confirm email field, so that the user *had* to type out the email again, rather than rely upon pre-fill from previous form submissions.
Answer: Each webform element has it's own file in the "components" sub-directory of the webform module folder.
If you look in those files there is a _webform_theme_COMPONENTTYPE() function, for example _webform_theme_date() for the date fields.
This function defines the theme functions for that field type.
These theme functions are what you can use to override the themeing of the fields.
For exmaple theme_webform_date() can be overridden as THEMENAME_webform_date(&$variables) and you can change the output.
If it is things like the field wrappers or labels you want, then look at overriding the theme_webform_element() function.
That will let you do things like change where the label is printed in relation to the field.
You can use $element['#type'] to single out specific field types in that theme function.
Note: Webform components are a special case. Normally you can find themeable things by looking in the MODULENAME_theme() function. In this case webform_theme().
Specifically, to set classes on radio button fields:
You requirement of adding the class to a radio button is unfortunately a bit different.
This is because webform doesn't use it's own themeing, it uses drupal core's
So what you want is theme_radios() and/or theme_radio() and/or theme_form_element_label().
Something like these (there are comments to tell you what has changed):
/**
 * Theme a set of radio buttons.
 */
function THEMENAME_radios($variables) {
  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }

  // Add custom classes.
  // To target specific elements you can use the $element variable.
  // You can target the label using:
  // .your-custom-class label
  $attributes['class'] .= 'your-custom-class another-custom-class';

  return '
' . (!empty($element['#children']) ? $element['#children'] : '') . '
';
}

/**
 * Theme a single radio button.
 */
function THEMENAME_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  // Set custom classes.
  // Use $element to target specific fields.
  $element['#attributes']['class'][] = 'your-custom-class';
  $element['#attributes']['class'][] = 'another-custom-class';

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

Unfortunately it is not possible to add classes to a label except for overriding theme_form_element_label() because of this bug.
The are two possible ways to address this in the theme layer.
One is to add the class to the field wrapper and then target the labels via that in your css or js.
The other is to override theme_form_element_label() like this:
/**
 * Theme a form element label.
 */
function THEMENAME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    // Changed to make class an array.
    $attributes['class'][] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    // Changed to make class an array.
    $attributes['class'][] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // Add your classes here.
  // If you are using variables to make the class use the drupal_html_class()
  // function.
  // To target specific elements you can use the $element variable.
  // For example, based on field type:
  if ($element['#type'] == '') {
    $attributes['class'][] = 'your-custom-class';
    $attributes['class'][] = 'another-custom-class';
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' ' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "\n";
}

Comment: Added a little note to the end of the answer.
Comment: It looks to me that everything is connected to form's theme and i don't see where i could change the output html.
Comment: Radio buttons, for example..
Comment: Anything is possible :) What specifically do you want to do? (maybe add it to the question instead of a comment here.)
Comment: Update coming shortly.
Comment: +1 Thanks for this definitive answer to this useful question.I found this to work for my case. In my case, I needed to insert `autocomplete=off` in the confirm email field, so that the user *had* to type out the email again, rather than rely upon pre-fill from previous form submissions.
Comment: Your answer was ideal: based on its advice I copied the `theme_webform_email` function into my theme's template.php and renamed the function to `mythemename_webform_email` (where `mythemename` is the name of my theme). I then added the following within that function before the `foreach` statement: `if ( $variables['element']['#id'] == 'edit-submitted-confirm-email' ) { $element['#attributes']['autocomplete'] = 'off'; }` and observed that this attribute/value now appears in the `input` html element for the confirm_email field that I had setup.
Comment: I note that `autocomplete=off` in html5 is (still) non-standard and not guaranteed but it seems to be the best we've got so far. Thanks again.


Workflow - sms/email notifications

Question: Is there a way to set up sms/email notifications to be sent out to site users responsible for each workflow stage? Also, is there a way of automatically "assigning" a node to the correct resource for managing the workflow stage?
Comment: Which modules are you using for workflow? Rules? Workbench? Moderation? And for which version of Drupal?
Comment: I am using drupal 7 @choster

Also, I am using the workflow module.
Answer: Check out the rules module. You can set up a rule that accesses other module (search for a sms module), or core features (like mail).

Workflow - sms/email notifications


MATLAB Match a row in a cell array, provided a sample cell array

Question: I need to return matches from a large cell array given one row to match. I wrote this code, but it seems like it shouldn't be this challenging - the code feels overwrought. What's the right way to do this?
function locations= MatchRowInHaystack(haystack,needle)
%Returns array locations: where needle matches haystack
%Where Needle is a cell array of identifiers
%And Haystack is a cell array of rows that may match needle.
%Split haystack into cell arrays by row:
rows=mat2cell(haystack,ones(size(haystack,1),1),size(haystack,2));
%Find row in haystack that matches needle row.
locations=find(cellfun(@isequal,rows,repmat({needle},[numel(rows) 1])));
end

Answer: How about
locations = find( ...
    arrayfun(@(ii) isequal(haystack(ii,:), needle), 1:size(haystack,1)) );

not simpler per se, but it prevents a repmat :)
In short, I don't think there is a "short" way to do what you want, because what you want is actually already really specific and hard to capture in generic operators. It's normal that under such circumstances, you'll need to do some more coding yourself.
By the way, it looks like your inputs are not cells at all -- why else would you need {needle} and mat2cell()? If they're not cells, there are much simpler methods to get where you want (bsxfun, intersect, etc.)


Yarn encore prod failing

Question: Im trying to deploy a symfony application on my Ubuntu server.
Mind the following details.
It is a simple application but some yarn packages seem to be failing.
What can I do?
Im working with Symfony 5.
My package.json
{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.30.2",
    "bootstrap": "^4.5.2",
    "jquery": "^3.5.1",
    "node-sass": "^4.14.1",
    "popper.js": "^1.16.1",
    "webpack-notifier": "^1.6.0"
  },
  "dependencies": {
    "add": "^2.0.6",
    "copy-webpack-plugin": "^6.0.3",
    "sass-loader": "^8.0.0",
    "yarn": "^1.22.4"
  },
  "name": "fluid-cms",
  "version": "1.0.0",
  "main": "index.js",
  "repository": "---",
  "author": "---",
  "license": "MIT"
}

The following output comes out.
I have tried many things.
Ubuntu 18.04.
alpha@ovhBrains:/var/www/fluid-cms$ sudo yarn encore prod
yarn run v1.22.4
$ /var/www/fluid-cms/node_modules/.bin/encore prod
Running webpack ...

/var/www/fluid-cms/node_modules/copy-webpack-plugin/node_modules/p-limit/index.js:30
        } catch {}
                ^

SyntaxError: Unexpected token {
    at NativeCompileCache._moduleCompile (/var/www/fluid-cms/node_modules/v8-compile-cache/v8-compile-cache.js:242:18)
    at Module._compile (/var/www/fluid-cms/node_modules/v8-compile-cache/v8-compile-cache.js:186:36)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (/var/www/fluid-cms/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/var/www/fluid-cms/node_modules/copy-webpack-plugin/dist/index.js:10:38)
    at Module._compile (/var/www/fluid-cms/node_modules/v8-compile-cache/v8-compile-
d.

---

Another error:
@email@example.com: The engine "node" is incompatible with this module. Expected version ">= 10.13.0". Got "8.10.0"

Answer: Once I found out the second error log it was easy to fix.
My nodejs -v was not matching with the requirements.

Yarn encore prod failing


Sorting arraylist in correct order in Objective C

Question: I have a list of array keys that i am getting from a dictionary by using below code :
    NSArray*keys=[dictionary allKeys];

Value of keys are coming like this :
Fact tags - 1                                     ,
Fact tags - 14                                    ,
Brochure                                          ,
Balloon                                           ,
Fact tags - 10                                    ,
Fact tags - 2                                     ,
Fact tags - 12                                    ,
Fact tags - 3                                     ,
Booklet                                           ,
Fact tags - 15                                    ,
Fact tags - 5                                     ,
Fact tags - 13                                    ,
Fact tags - 4                                     ,
Fact tags - 11                                    ,
Fact tags - 6                                     ,
Fact tags - 9                                     ,
Fact tags - 8                                     ,
Fact tags - 7                                     ,

So, for array list sorting. i am using below code:
keys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Now, my keys output is :
Balloon                                           ,
Booklet                                           ,
Brochure                                          ,
Fact tags - 1                                     ,
Fact tags - 10                                    ,
Fact tags - 11                                    ,
Fact tags - 12                                    ,
Fact tags - 13                                    ,
Fact tags - 14                                    ,
Fact tags - 15                                    ,
Fact tags - 2                                     ,
Fact tags - 3                                     ,
Fact tags - 4                                     ,
Fact tags - 5                                     ,
Fact tags - 6                                     ,
Fact tags - 7                                     ,
Fact tags - 8                                     ,
Fact tags - 9                                     ,

Here it is sorting an array alphabetically, But i want my array list output like below list:
Balloon                                          ,
Booklet                                          ,
Brochure                                         ,
Fact tags - 1                                    ,
Fact tags - 2                                    ,
Fact tags - 3                                    ,
Fact tags - 4                                    ,
Fact tags - 5                                    ,
Fact tags - 6                                    ,
Fact tags - 7                                    ,
Fact tags - 8                                    ,
Fact tags - 9                                    ,
Fact tags - 10                                   ,
Fact tags - 11                                   ,
Fact tags - 12                                   ,
Fact tags - 13                                   ,
Fact tags - 14                                   ,
Fact tags - 15                                   ,

Can you please tell me that what changes i need to do in my code for such type of sorting ?
Answer: Best way to do...
 keys = [keys sortedArrayUsingComparator:^(NSString* first, NSString* second){

         return [first compare:second options:NSNumericSearch | NSCaseInsensitiveSearch];
            }
        ];

You can also use custom objects instead of NSString
Answer: Have you try with sortedArrayUsingComparator,
try Like,
keys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];

Comment: @AnandGautam: I got thought on this, **Tester aur Developer ki sirf Dushmani ho sakti he** - Dhoom Style. ha ha ha.
Comment: mcaYeah sure..but i can accept this answer after 8 minutes only. now 5 min is remaining accrdng to stackoverflow.


Evaluate $\int \cos^2x\sin^4x\mathrm{d}x$

Question:
Evaluate integral $$\int \cos^2x\sin^4x\mathrm{d}x.$$

Attempt. Setting $\tan x=t$, gives:
$$\int \cos^2x\sin^4x\mathrm{d}x =\int \frac{1}{1+t^2} \,\left(\frac{t^2}{1+t^2}\right)^2 \frac{\mathrm{d}t}{1+t^2}=\int \frac{t^4}{(1+t^2)^4} \mathrm{d}t,$$
which does not seem to be elementary.
Thank in advance for the help.
Comment: Substitute $\sin^2 x $ for $ 1 - \cos^2 x $

$$\int \cos^2 x (1 - \cos^2 x)^2 dx$$
Comment: Why isn't it elementary? The integral of any rational function is elementary. In particular, they can always be written in terms of logarithms (probably complex, which may be written as arctangents and so forth).
Comment: The last one may not be elementary, but it can be solved using partial fractions, though.
Comment: Alternatively, replace $\cos^2x$ with $1-\sin^2 x$, and use the [reduction formula](https://en.wikipedia.org/wiki/Integration_by_reduction_formulae#Transcendental_functions)
Comment: https://math.stackexchange.com/questions/1034579/prove-reduction-formula-for-int-cosn-x-sinm-x-dx
Comment: The substitution of $\tan x=t$ is beneficial only if the sum of powers of cosine and sine is a negative even integer
Answer: Use that $$\cos^2(x)=1-\sin^2(x)$$ and your integral will be
$$\int\sin^4(x)-\sin^6(x)dx$$
For your work:
$$\int \sin(x)^4dx=-1/4\, \left(  \left( \sin \left( x \right)  \right) ^{3}+3/2\,\sin
 \left( x \right)  \right) \cos \left( x \right) +3/8\,x
+C$$
and
$$\int\sin(x)^6dx=-1/6\, \left(  \left( \sin \left( x \right)  \right) ^{5}+5/4\,
 \left( \sin \left( x \right)  \right) ^{3}+{\frac {15\,\sin \left( x
 \right) }{8}} \right) \cos \left( x \right) +{\frac {5\,x}{16}}
+C$$
Answer: Expanding on @Dr.SonnhardGraubner's answer, since $\sin^2x=\frac{1-\cos 2x}{2}$ we have $$\sin^4x=\frac{1-2\cos 2x+\cos^22x}{4}=\frac{3-4\cos 2x+\cos4x}{8}$$ while $$\sin^6x=\frac{1-3\cos 2x+3\cos^22x-\cos^32x}{8}=\frac{10-15\cos 2x+6\cos4x-\cos6x}{32}.$$Thus $$\int(\sin^4x-\sin^6x)dx\\=\int\frac{2-\cos2x-2\cos4x+\cos6x}{32}dx=\frac{12x-3\sin2x-3\sin4x+\sin6x}{192}+C.$$
Answer: The integral is elementary, that is, expressible as a combination of finitely many elementary functions. Thus, this doesn't say anything about how arduous or difficult the process of transforming the integral into recognizable form may be.
That said, there are other ways to proceed. One of them is described as follows, where we simplify the integrand.
So note that we have $\cos^2x\sin^2x=\frac14\sin^22x=\frac18(2\sin^22x)=\frac18(1-\cos 4x).$ It follows that $$\cos^2x\sin^4x=\frac18(1-\cos 4x)\frac12(1-\cos 2x)=\frac{1}{16}(1-\cos 2x-\cos 4x+\cos2x\cos 4x)=\frac{1}{16}[1-\cos 2x-\cos 4x+\frac12(\cos 6x+\cos 2x)],$$ from where you can continue.
Answer: Alternative solution:
$$\int \cos^2x\sin^4x\mathrm{d}x=\\
\int(\frac{1+\cos (2x)}{2})(\frac{1+\cos (2x)}{2})^2\mathrm{d}x=\\\frac{1}{8}
\int (1+\cos (2x))(1-2\cos (2x)+\cos^2(2x))\mathrm{d}x=
\\\frac{1}{8}
\int (1+\cos (2x))(1-2\cos (2x)+\frac{1+\cos(4x)}{2})\mathrm{d}x=$$
Answer: For trigonometric monomials, the standard method is linearisation when both exponents are even, substitution when an exponent is odd ($u=\sin x$ or $u=\cos x$, depending on which exponent is odd).
You can linearise either with trigonometry formulæ or via the complex exponential. I'll show both:

with trigonometry: use repeatedly the linearisation formulæ
$$\cos^2x=\tfrac12(1+\cos 2x),\qquad\sin^2x=\tfrac12(1-\cos 2x).$$
So
\begin{align}
\cos^2x\sin^4x&=\tfrac12(1+\cos 2x)\tfrac14(1-\cos 2x)^2=\tfrac 18(1+\cos 2x)(1-2\cos 2x+\cos^22x)\\
&=\tfrac 18(1+\cos 2x)\bigl(\tfrac32-2\cos 2x+\tfrac12\cos4x)\\
&=\tfrac1{16}(3-4\cos 2x+\cos 4x+3\cos 2x-4\cos^2 2x+\underbrace{\cos2x\cos 4x}_{\frac12(\cos 6x+\cos 2x)}) \\
&=\tfrac1{32}(2-\cos 2x-2\cos 4x+\cos 6x).
\end{align}
with the complex exponential: to have lighter computations, set $u=\mathrm e^{ix}$. We'll use the definitipn of sine and cosine in terms of $u$:
$$\sin x=\tfrac1{2i}(u-\bar u),\qquad \cos x =\tfrac 12(u+\bar u),$$
so that, taking into accoount that $u\bar u=1$,
\begin{align}
\cos^2x\sin^4x &=\tfrac14(u+\bar u)^2\cdot\tfrac1{16}(u-\bar u)^4=\tfrac1{64}(u^2+\bar u^2+2)(u^4-4^2+6-4\bar u^2+\bar u^4) \\
&=
\end{align}
Answer: Here is to integrate economically,
$$\cos^2x\sin^4 x = \frac 18 \sin^2 2x (1-\cos 2x)= \frac {1}{16}-\frac {1}{16}\cos 4x-\frac 18 \sin^22x\cos 2x$$
Thus,
$$\int \cos^2x\sin^4x\mathrm{d}x = \frac {x}{16}-\frac {1}{64}\sin4x-\frac{1}{48}\sin^32x +C$$
Answer: If you insist on the tangent substitution, I think you will be mildly disappointed... Taking $t=\tan x$ makes it so
$$\begin{cases}
\sin x=\frac t{\sqrt{1+t^2}}\\[1ex]
\cos x=\frac1{\sqrt{1+t^2}}\\[1ex]
\mathrm dt=\sec^2x\,\mathrm dx\implies\mathrm dx=\frac{\mathrm dt}{1+t^2}
\end{cases}$$
The integral becomes
$$\int\cos^2x\sin^4x\,\mathrm dx=\int\frac1{1+t^2}\frac{t^4}{(1+t^2)^2}\frac{\mathrm dt}{1+t^2}=\int\frac{t^4}{(1+t^2)^4}\,\mathrm dt$$
Decompose the integrand into partial fractions:
$$\frac{t^4}{(1+t^2)^4}=\frac1{(1+t^2)^2}-\frac2{(1+t^2)^3}+\frac1{(1+t^2)^4}$$
But then the obvious means of tackling these integrals is to undo the original one:
$$\int\frac{\mathrm dt}{(1+t^2)^2}=\int\frac{\sec^2x}{(1+\tan^2x)^2}\,\mathrm dx=\int\cos^2x\,\mathrm dx$$
$$-\int\frac2{(1+t^2)^3}\,\mathrm dt=-2\int\frac{\sec^2x}{(1+\tan^2x)^3}\,\mathrm dx=-2\int\cos^4x\,\mathrm dx$$
$$\int\frac{\mathrm dt}{(1+t^2)^4}=\int\frac{\sec^2x}{(1+\tan^2x)^4}\,\mathrm dx=\int\cos^6x\,\mathrm dx$$
so all that work to confirm what other answers have suggested: write the integrand in terms of powers of either $\cos x$ or $\sin x$, then use the well-known power reduction identities.


Can't discover endpoints url

Question: So today i started using spring-boot, and my point is to create a rest api with spring-boot.
I created just a small project with a rest controller and a simple model. And i'm trying to call the method from the rest controller (with no success)
Controller:
@RestController

    public class RestController {

            @RequestMapping(method = RequestMethod.GET,
                            produces = MediaType.APPLICATION_JSON_VALUE,
                            value = "/something")
            public @ResponseBody Something getSomething(){
                Something s = new Something ();
                return s;
            }
    }

Main:
@SpringBootApplication
public class SpringBootRestExampleApplication

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestExampleApplication.class, args);
    }
}

And an application properties:
server.port=8081
spring.data.rest.basePath=/micro

So if i have a basePath/port and a mapping.. normally i only need to use localhost:8081/micro/something . But for only reason when i use an API Client i got 404 not found for the endpoint /something. Anyone can point me if something is missing? (miss some declaration/..)?
I read other post from stack i tried to use (for example) RequestMappingHandlerMapping
Note: project running with tomcat 8. i already tried localhost:8081/something ; localhost:8081/micro, etc ; added some urlmapping annotation on the rest controller
Answer: According to the documentation:

spring.data.rest.base-path= # Base path to be used by Spring Data REST
  to expose repository resources.

Try to use base-path instead of basePath.
spring.data.rest.base-path=/micro

Or try to set dispatcherServlet path like:
server.contextPath=/micro

For SpringBoot 2.0+:
server.servlet.context-path=/micro

Search logs for:
o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [$URL]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/root/test],methods=[GET]}" onto public java.lang.String com.test.Rest.getSomething()

Comment: I tried both but still not working .. you tried :/micro/something (or something similiar, right?
Comment: @Tazz  search for `o.s.b.w.servlet.ServletRegistrationBean`  in logs, what is URL?
Answer: spring.data.rest.base-path will not work because it is specifically made for spring data-rest. You can check this ticket
https://github.com/spring-projects/spring-boot/issues/7816
As a workaround you can use what @oleg.cherednik has suggested or upgrade to spring boot 2.0 and use this
server.servlet.context-path=/micro

Answer: I would reccomend not to use server.contextPath or spring.data.rest.base-path. I faced with different beheviour of this.
Do declare a class with all paths of you API:
public static final class RequestPath {
    public static final String BASE = "/micro";

    public static final String SOMETHING = BASE + "/something";
}

And use it in your controllers:
@RestController
public class RestController {
    @RequestMapping(value = RequestPath.SOMETHING)
    @ResponseBody
    public Something getSomething() {}
}

Finally what you get:

All paths in one file. This could help see it at the same time
Documentation (in case you do not use Swagger or Raml)
You do not care about base path settings, that could works differently (+ you definetly know correct request path to required endpoint).

Can't discover endpoints url


finding probability function, bills and dice

Question: There are 2 white bills, and 4 green bills. We throw the dice, if it gives 6 - we take two bills, if it gives 1/2/3/4/5, we take one bill. X variable is the amount of white bills taken out. I need to find the probability function for X and draw the cumulative distribution function. How can I do this?
Answer: Hint:  $X$ can take the values $0,1,2$.  You need to find the probability of each.  For $2$, you have to roll a $6$ and then take two white bills.  Can you find the chance of that?  For zero, you have a certain chance of drawing one bill, and it has to be green, plus another chance of drawing one bill, which then both have to be green.  Can you do that?  The chance of $1$ is what is left.  Then look up what a cumulative distribution function means and apply the definition.
Answer: I suppose we draw the bills at random from the 6 bills you describe.
$P(X = 2) = \frac{1}{6} \cdot \frac{\binom{2}{2}}{\binom{6}{2}}$, because in order to get two white bills, we need to throw a 6, and then take the 2 white bills out of the 6 we have as well, and we multiply them, as they are independent events.
$P(X = 1) = \frac{1}{6}\cdot P(X = 1 | \mbox{6 thrown}) + \frac{5}{6} \cdot P(X = 1| \mbox{1,2,3,4 or 5 thrown})$ by a standard formula.
$P(X = 1 | \mbox{6 thrown}) = \frac{\binom{2}{1}\binom{4}{1}}{\binom{6}{2}}$, because we select 2 bills, and 1 one it is white, the other green.
$P(X = 1 | \mbox{1,2,3,4 or 5 thrown}) = \frac{2}{6}$ as we draw only one bill and it has to be white.
$P(X = 0) = 1 - P(X=2) - P(X= 1)$ as we only have 3 possible values.


Stabilization techniques for mobile builds?

Question: Please note: although I specifically mention AngularJS, Ionic and Cordova here, I'm really talking about any mobile app (hybrid and native alike) that produces binaries for iOS and Android platforms. As such, I believe that anybody with experience in mobile dev should be able to address the question!

I am building a mobile app for iOS and Android using AngularJS, Ionic and Cordova. My concern is that iOS and Android release updates all the time, some may be buggy or just might be outright breaking changes and all of the sudden become incompatible with the plugin/library versions that I'm using.
This will cause apps to crash spontaneously in production. But it sheds light on an even nastier problem under the hood: making the decision to pin your builds against specific dependency (plugins/libraries/etc.) versions or just always pull in the latest/stable versions of them!
Option 1: Pin your dependency versions
Here we specify the exact version of all dependencies to use. We then fight with the Ionic build to get the app built, but are now good to go. I can expect that if I don't change any of my code, that each subsequent build of the app against the exact same dependency versions will always result with a successful build.
However, when iOS/Android does release a breaking change or bug (or anything that prompts the library/plugin maintainers to go into a frenzy and publish new versions of themselves), because I've pinned my previous build to specific versions of dependencies, I may actually be running on very old dependency versions and it will now be a massive headache to get my app building again against all the latest versions.
Option 2: Use latest/stable versions at all times
If I don't specify dependency versions (and just let the build always use latest and greatest), then I could work fervently to get my app building, then wait a few days (and not change any of my own code) and then try building it again and the compile/build might fail! This is because in between those few days, some project upgraded itself and/or its own dependencies and introduced a build-breaking change.
However, when iOS/Android releases a breaking change that requires me to upgrade to latest dependencies, the headache would likely be considerably less then Option 1 since I'll be on a relatively much newer version of all my dependencies.
Are there any tools/strategies/techniques/etc. that the mobile community leverages to stabilize builds and make it so that I can have more consistent, repeatable builds?
Comment: You don't need a MAC server to do CI using Jenkins. You just need a Mac machine, which will act as Slave for your main Jenkins server( which could be running on Windows). Your mac machine will only build for iOS

In order to achieve build stability, you need to have good coverage of instrumentation and unit test. For Android you can make the targetSdkVersion configurable. Each time Google releases new preview version, you can change this value on CI and run your tests. It allows you to detect issues early and ensure stabilty. Same could be done for iOS
Comment: Why the DV? This is on topic, shows research and is not a dupe...
Comment: Are you familiar with Continious Integration?
Comment: Thanks @JoeriShoeby, I'm *very* familiar with CI! How do you suggest I leverage CI to solve this problem?
Comment: Also @JoeriShoeby -- I don't think CI is a possible solution for iOS, since iOS *must* compile inside of Xcode which requires Mac hardware. Unless you're suggesting having an on-premise Mac server used for CI purposes...
Comment: Meh, doesn't even look like Macs sell servers anymore. Yeah I'm not seeing how CI would solve this for iOS...
Answer: It is recommend to use specific version of your dependencies, you may consider using the notion * at the minor patch level X.Y.* to get the lastest bug fixes.
Your build should be automatic and consistent, there are products that do this for you, e.g BuddyBuild and Buddy support both Android and IOS.
Successful builds is not the whole thing, The app should pass all the functionality and QA tests before a release. So you need to write as much as UnitTests and FunctionalTest to cover the quality checks. There are other QC tools for even further assurance, For example static code analysis tools help you to discover potential bugs and failures, And test coverage tools let you know which parts of your code has not been tested yet.
Here is a Simple CI/CD workflow
Code -> Push -> CI Test -> CD Publish Release
You can set a job to build your project on a weekly basis on the CI server and Publish a Release only if it passes all the Quality Checks
Apps crashing on the new OS versions is not a catastrophic problem, it's common and has its solution, Google and Apple don't release new OS versions to users just like that, Developers are provided with preview builds of the OS and new APIs, Developers usually have more than 2 month to adopt thier apps with the new changes and even use the new API features.
And by the way you have access to crash reporting tools like Fabric.io and Firebase which helps you to discover problems at production.
Cheers
Comment: +1 for the the preview builds suggestion, definitely a gd strategy to catch bugs early on before an official OS update
Comment: Thanks @M.Reza (+1), I like what you are suggesting here, there are two main pushbacks I'm hearing from my mobile developers: **(1)** that while Android/iOS offer a "preview mode" for their new versions, that this doesn't apply when they need to publish emergency fixes/security patches without warning. **Can you speak to how often this happens and how your solution above could accommodate these unannounced/emergency fixes?**
Comment: And **(2)** my mobile developers tell me that once in a while certain platforms tools (especially Xcode) force developers to upgrade to latest dependencies.  **In your experience is this true, and if so how does your above solution handle this?** Thanks again so much!!!
Comment: @smeeb Emergency fixes are usually for security patches, Every big tech company knows if they're introducing breaking changes they have to release it under the major updates, even though it is a minor fix. So It goes through the same process of maunge it available to developers, Even for a short period ahead of public release. And don't get frightened by new releases, the new version won't hit to even 1 percentage of Android users for months, You have less time for IOS though.
Comment: @smeeb (2) It only forces you if you want to build for new OS versions or you have a really old instance.


Numpy array element identification

Question: I have the a nested array of the following type:
array = [[3,a],[3,b],[4,c],[7,d],[3,e]]

I would to be able to identify all elements with a given first index and create a new array. For example, for first index 3 I would get: [a,b,e].
Comment: Is `array` a numpy array or a list?  Looks like a list.  What have you tried?
Comment: Welcome back to Stack Overflow! Please take the [tour]. SO is a Q&A site, but there's no question here and it's not clear what you need help with. What have you tried and how are you stuck? For tips, check out [ask]. Also, are the letters supposed to be strings? then they need to be quoted.
Comment: If that really is a numpy array, simple indexing works: `arr[arr[:,0]=='3',1]`.  That selects the first column, tests for a value match, and uses the resulting boolean array so seleect values from the other column.
Answer: Assuming that each nested list has exactly 2 elements, it can be done this way:
def create_list(input: list, index: int) -> list:
    result = []
    for i in range(len(input)):
        if input[i][0] == index:
            result.append(input[i][1])
    return result

Numpy array element identification


Rig in which + distributes over *

Question: Let $A$ be a commutative rig (ring without additive inverses). Suppose that addition in $A$ distributes over multiplication in $A$, so that $A$ is a rig in $2$ ways, depending on which operation we think of as the multiplication.

Question: Are all such rigs distributive lattices?

This question is interesting to me because it contends to show a special property of distributive lattices: that they are precisely the sets with $2$ commutative monoidal operations which distribute over each other.
Note that it suffices to show that $\forall a \in A : a^2 = a$ and $\forall a \in A : a +a =a$.
Edit: One answer has shown that without a unit for $+$ and $\cdot$, my note above does not hold, and the answer is also false. I should have stated which meaning of "lattice" I am using, namely that a lattice is a poset with finite meets and joins, including the empty meet and empty join.
Comment: @coffeemath yes!
Comment: Thanks for the discussion and the pointers.
Comment: Do we assume $A$ is commutative under both $+$ and $\cdot$ ?
Comment: Perhaps I am simply uneducated in matters of rigs, but when I hear distributive, I think $a(b+c)=ab+ac$. This is not what's in the accepted answer: it says $a+bc=(a+b)(a+c)$. What's going on here?
Comment: @HankScorpio Good question, Hank. Your first axiom is $a(b+c) = ab + ac$, and this is true in every rig. However, this question specifies something extra that is not true of all rigs: "Suppose that addition in $A$ distributes...". What that means is that $a + bc = (a+b)(a+c)$, and this is the second equation you have written. In this way, both of the equations you have written are assumed here.
Comment: So the sentence "addition in $A$ distributes over multiplication" is the assumption $a+bc=(a+b)(a+c)$. Huh. I have never heard of this before - where do people talk about such things? Any attempt to google "distributes over" only brings up examples of the typical distributive property.
Comment: @HankScorpio The subject would be called "universal algebra", and a keyword is "variety" (but don't confuse that variety with the variety in algebraic geometry). This distributive property is really rare, though. As the problem shows, if two monoidal operations distribute over each other, then we have a distributive lattice.
Answer: Distributivity of addition over multiplication says $$a+bc=(a+b)(a+c)$$ for any $a,b,c$.  Setting $b=c=0$ gives $a=a^2$.  Setting $b=0$ and $c=1$ gives $a=a(a+1)=a^2+a=a+a$.
(Alternatively, assuming that by "addition distributing over multiplication" you include the case of nullary multiplication where it says $a+1=1$, then you can deduce $a=a+a$ by just dualizing the argument for $a=a^2$.  Actually, though, that nullary case does not have to be assumed, since it follows automatically.  Indeed, setting $a=1$ and $c=0$ in $a+bc=(a+b)(a+c)$ gives $1=(1+b)1=1+b$ for arbitrary $b$.)
Comment: Thanks Eric. You always give the best answers!

Rig in which + distributes over *


kNN randomization test in R?

Question: I am trying to determine significant differences between groups of data using a k-nearest neighbor randomization test in R. This test basically looks for similarity amongst homogenous groups and separates them out using random clustering. In the literature, this test is called a "K-nearest neighbor (kNN) randomization test," however, I'm not certain if it called by other names elsewhere.
For my specific data, I have isotopic ratios given for various prey items. I have already grouped together ecologically similar prey item types, and now want to see if those groups differ from one another in their isotopic signature. This is where the kNN test would come in.
Thanks for all of your answers - I'm new to this site, so I'll address your inquiries as applicable in the comments section.
Comment: @kwak: why not post your comment as an answer?
Comment: kmeans() (you can find it by typping ?? folowed by the name of what you want as in ??kmean)
Comment: Another useful way to find functions is the `apropos` function.
Comment: @all:> i propose to change the title of the post, so as to make it easier to find for someone looking for the R implementation of other procedures (beside k-means).
Comment: @kwak Yes, I think it's better to change the title because k-means vs. kNN seems ambiguous.
Comment: Did you figure out the code for this? Lots of journals articles mention using this test for isotopes but I can't find examples!
Answer: You appear to have confused "cluster analysis" with "classification". The former is where you don't know the groupings and wish to determine them from the training data to hand. Classification is where you know the groups and want to predict them.
There are a few packages in R that do this. For example, look at the results of this R Site Search for suitable packages.
Alternatively, perhaps you are looking for a multivariate analysis of variance? In which case lm() and aov() would be worth looking at for a start. This presumes you want to "model" your data as a function of the group variable?
Comment: I believe the k nearest-neighbors test is a multivariate analysis. Perhaps I have confused cluster analysis with classification, but I don't think either apply in this situation. I already have categorized the variables into groups, and now want to see if these groups statistically differ from one another. This test is different that an ANOVA or linear model. Any suggestions? Thanks.
Comment: @Sharon I'm a little bit puzzled about the term 'randomization test' (the only paper I found using this keyword, http://j.mp/9OCB9I, seems rather to focus on power considerations) -- I rest on my idea that you could use cross-validation to assess the classification accuracy in your data, e.g. leave-one-out or k-fold CV for this purpose (available in `kknn` and `class` packages). Now, I don't know on which basis your classes were defined, but it is generally meaningless to use ANOVA to test if the groups differ on the variables that were used to define class membership.
Comment: @Sharon; can you explain your data a bit better (I'm a (sort of) ecologist and use isotopes all the time so you can be quite technical if it helps)?
Answer: kmeans() (you can find it by typing ?? followed by the name of what you want as in ??kmean). In general, a good trick is to first look it up on a R specific search engine
Comment: You can also do `RSiteSearch("k-means")`
Answer: I am not sure to understand your question since you talk about k-means, which is basically an unsupervised method (i.e. where classes are not known a priori), while at the same time you are saying that you already identified groups of individuals. So I would suggest to look at classification methods, or other supervised methods where class membership is known and the objective is to find a weighted combination of your variables that minimize your classification error rate (this is just an example). For instance, LDA does a good job (see the CRAN task view on Multivariate Statistics), but look also at the machine learning community (widely represented on the stats.stackexchange) for other methods.
Now since you also talked of k-nearest neighbor, I wonder if you are not introducing a confusion between k-means and kNN. In this case, the corresponding R function is knn() in the class package (it includes cross-validation), or see the kknn package.
Answer: I wouldnt cluster or classify the data at all. Since youve got ratio scaled data (isotopes) my method of choice would be PCA (Principal Component Analysis). By colouring your points in the PCA diagram according to your "eco-type" you could see their dispersal within the isotope ratio variation. Further, you will see the influence of each parameter (isotope ratios) in the biplot - the result will contain much more information than a classification.
Comment: I sense the user is looking for a statistical test to determine the fit. PCA falls a bit short on that. I think LDA as suggested by @chl is the way to go here.

kNN randomization test in R?


Está selecionado texto ao abrir notificação

Question: Segue código:

        $("#click_notifications").click(function () {
            if ($('li.nav-item.dropdown.dropdown-notifications').hasClass('open')) {
                $('li.nav-item.dropdown.dropdown-notifications').removeClass('open');
            }
            else {
                $('li.nav-item.dropdown.dropdown-notifications').addClass('open');
            }
        });
/*!
 * bootstrap-dropmenu v0.9.0 (https://skywalkapps.github.io/bootstrap-dropmenu)
 * Copyright 2015 Martin Staněk
 * Licensed under MIT
 */
.dropdown-container {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  float: left;
  min-width: 200px;
  max-width: 330px;
  margin: 2px 0 0;
  list-style: none;
  font-size: 14px;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  background-clip: padding-box;
}
.dropdown-container > .dropdown-menu {
  position: static;
  z-index: 1000;
  float: none!important;
  padding: 10px 0;
  margin: 0;
  border: 0;
  background: transparent;
  border-radius: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
  max-height: 330px;
  overflow-y: auto;
}
.dropdown-container > .dropdown-menu + .dropdown-menu {
  padding-top: 0;
}
.dropdown-menu > li > a {
  overflow: hidden;
  white-space: nowrap;
  word-wrap: normal;
  text-decoration: none;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -webkit-transition: none;
  -o-transition: none;
  transition: none;
}
.dropdown-toggle {
  cursor: pointer;
}
.dropdown-header {
  white-space: nowrap;
}
.open > .dropdown-container > .dropdown-menu,
.open > .dropdown-container {
  display: block;
}
.dropdown-toolbar {
  padding-top: 6px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 5px;
  background-color: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px 4px 0 0;
}
.dropdown-toolbar > .form-group {
  margin: 5px -10px;
}
.dropdown-toolbar .dropdown-toolbar-actions {
  float: right;
}
.dropdown-toolbar .dropdown-toolbar-title {
  margin: 0;
  font-size: 14px;
}
.dropdown-footer {
  padding: 5px 20px;
  border-top: 1px solid #ccc;
  border-top: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 0 0 4px 4px;
}
.anchor-block small {
  display: none;
}
@media (min-width: 992px) {
  .anchor-block small {
display: block;
font-weight: normal;
color: #777777;
  }
  .dropdown-menu > li > a.anchor-block {
padding-top: 6px;
padding-bottom: 6px;
  }
}
@media (min-width: 992px) {
  .dropdown.hoverable:hover > ul {
display: block;
  }
}
.dropdown-position-topright {
  top: auto;
  right: 0;
  bottom: 100%;
  left: auto;
  margin-bottom: 2px;
}
.dropdown-position-topleft {
  top: auto;
  right: auto;
  bottom: 100%;
  left: 0;
  margin-bottom: 2px;
}
.dropdown-position-bottomright {
  right: 0;
  left: auto;
}
.dropmenu-item-label {
  white-space: nowrap;
}
.dropmenu-item-content {
  position: absolute;
  text-align: right;
  max-width: 60px;
  right: 20px;
  color: #777777;
  overflow: hidden;
  white-space: nowrap;
  word-wrap: normal;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
}
small.dropmenu-item-content {
  line-height: 20px;
}
.dropdown-menu > li > a.dropmenu-item {
  position: relative;
  padding-right: 66px;
}
.dropdown-submenu .dropmenu-item-content {
  right: 40px;
}
.dropdown-menu > li.dropdown-submenu > a.dropmenu-item {
  padding-right: 86px;
}
.dropdown-inverse .dropdown-menu {
  background-color: rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.9);
}
.dropdown-inverse .dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #2b2b2b;
}
.dropdown-inverse .dropdown-menu > li > a {
  color: #cccccc;
}
.dropdown-inverse .dropdown-menu > li > a:hover,
.dropdown-inverse .dropdown-menu > li > a:focus {
  color: #fff;
  background-color: #262626;
}
.dropdown-inverse .dropdown-menu > .active > a,
.dropdown-inverse .dropdown-menu > .active > a:hover,
.dropdown-inverse .dropdown-menu > .active > a:focus {
  color: #fff;
  background-color: #337ab7;
}
.dropdown-inverse .dropdown-menu > .disabled > a,
.dropdown-inverse .dropdown-menu > .disabled > a:hover,
.dropdown-inverse .dropdown-menu > .disabled > a:focus {
  color: #777777;
}
.dropdown-inverse .dropdown-header {
  color: #777777;
}
.table > thead > tr > th.col-actions {
  padding-top: 0;
  padding-bottom: 0;
}
.table > thead > tr > th.col-actions .dropdown-toggle {
  color: #777777;
}
.notifications {
  list-style: none;
  padding: 0; }

.notification {
  display: block;
  padding: 0.8em;
  border-width: 0 0 1px 0;
  border-style: solid;
  border-color: #e9ecef;
  background-color: #ffffff;
  color: #212529;
  text-decoration: none; }
  .notification:last-child {
    border-bottom: 0;
    border-radius: 0 0 0.25rem 0.25rem; }
  .notification:hover, .notification.active:hover {
    background-color: #f9f9f9;
    border-color: #dee2e6;
    text-decoration: none; }
  .notification.active {
    background-color: #efefef; }

.notification-title {
  font-size: 1em;
  margin-bottom: 0; }

.notification-desc {
  margin-bottom: 0;
  font-size: 0.94em; }

.notification-meta {
  color: #868e96; }

.dropdown-notifications > .dropdown-container,
.dropdown-notifications > .dropdown-menu {
  width: 450px;
  max-width: 450px; }

.dropdown-notifications > .dropdown-container {
  margin-top: 0.6rem; }

.dropdown-notifications .dropdown-menu {
  padding: 0; }

.dropdown-notifications .dropdown-toolbar,
.dropdown-notifications .dropdown-footer {
  padding: 0.8em; }

.dropdown-notifications .dropdown-toolbar {
  background: #ffffff; }

.dropdown-notifications .dropdown-footer {
  background: #ced4da; }

.dropdown-notifications .dropdown-toggle::after {
  display: none; }

.navbar .dropdown-notifications .dropdown-menu {
  position: static; }

.notification-icon {
  margin-right: 0.49125rem;
  vertical-align: middle;
  font-style: normal;
  }

.notification-icon:after {
  position: absolute;
  content: attr(data-count);
  margin-left: -0.49125rem;
  margin-top: -0.49125rem;
  padding: 0 4px;
  min-width: 0.9825rem;
  height: 0.9825rem;
  line-height: 0.9825rem;
  background: red;
  border-radius: 10px;
  color: #ffffff;
  text-align: center;
  vertical-align: middle;
  font-size: 0.786rem;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; }

.notification .media-body {
  padding-top: 0; }

.btn-lg .notification-icon:after {
  margin-left: -0.5895rem;
  margin-top: -0.5895rem;
  min-width: 1.179rem;
  height: 1.179rem;
  line-height: 1.179rem;
  font-size: 0.9825rem; }

.btn-xs .notification-icon:after {
  content: '';
  margin-left: -0.29475rem;
  margin-top: -0.147375rem;
  min-width: 0.4465909091rem;
  height: 0.4465909091rem;
  line-height: 0.4465909091rem;
  padding: 0; }

.btn-xs .notification-icon {
  margin-right: 0.245625rem; }

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.css" rel="stylesheet"/>

    Tasks

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

               View All

Recent (3)

                  <img data-src="holder.js/50x50?bg=cccccc" class="mr-2 img-circle" alt="50x50" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2250%22%20height%3D%2250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2050%2050%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_163b3713d4b%20text%20%7B%20fill%3A%23919191%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_163b3713d4b%22%3E%3Crect%20width%3D%2250%22%20height%3D%2250%22%20fill%3D%22%23cccccc%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%226.4765625%22%20y%3D%2229.55625%22%3E50x50%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true" style="width: 50px; height: 50px;">

                    Dave Lister commented on DWARF-13 - Maintenance

I totally don't wanna do it. Rimmer can do it.

                      27. 11. 2015, 15:00

                  <img data-src="holder.js/50x50?bg=cccccc" class="mr-2 img-circle" alt="50x50" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2250%22%20height%3D%2250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2050%2050%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_163b3713d4c%20text%20%7B%20fill%3A%23919191%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_163b3713d4c%22%3E%3Crect%20width%3D%2250%22%20height%3D%2250%22%20fill%3D%22%23cccccc%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%226.4765625%22%20y%3D%2229.55625%22%3E50x50%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true" style="width: 50px; height: 50px;">

                    Nikola Tesla resolved T-14 - Awesome stuff

Resolution: Fixed, Work log: 4h

                      27. 10. 2015, 08:00

                  <img data-src="holder.js/50x50?bg=cccccc" class="mr-2 img-circle" alt="50x50" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2250%22%20height%3D%2250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2050%2050%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_163b3713d4d%20text%20%7B%20fill%3A%23919191%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_163b3713d4d%22%3E%3Crect%20width%3D%2250%22%20height%3D%2250%22%20fill%3D%22%23cccccc%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%226.4765625%22%20y%3D%2229.55625%22%3E50x50%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true" style="width: 50px; height: 50px;">

                    James Bond resolved B-007 - Desolve Spectre organization

                      1. 9. 2015, 08:00

Dashboard

Projects

People

Problema:
Quando eu fecho e abro notificação, acontece isso:

O texto fica tudo selecionado na parte da notificação.
Alguma solução ?
Comment: Aqui no site funcionou normal.
Comment: Exatamente no chrome. Só tenho ele e o IE que não uso. Se vc der executar ali no seu código seleciona o texto da notificação? Pq aqui no meu não.
Comment: Cara o meu aqui fica selecionado se eu der dois cliques, senão abre e fecha a notificação normalmente.
Answer: Problema resolvido:
$("#click_notifications").click(function () {
    if ($('li.nav-item.dropdown.dropdown-notifications').hasClass('open')) {
        $('li.nav-item.dropdown.dropdown-notifications').removeClass('open');
    }
    else {
        $('li.nav-item.dropdown.dropdown-notifications').addClass('open');
    }
}).mousedown(function (e) { e.preventDefault(); });


JSON Customizado para DataAnnotations - Asp.Net Core Web Api

Question: Boa tarde!
Tenho uma Web API em .Net Core, em que tenho a seguinte classe de requisição para uma rota POST:
public class CreateAgentRequest
{
    [Required]
    public Agent Agent { get; set; }
}

Com a Annotation Required, se eu não mando um campo Agent, ele me retorna o erro na seguinte estrutura da chamada da API

Porém, eu tenho um Model customizado de validação, que são validações que eu não trato com Data Annotations, como por exemplo, que esse dado já existe na base de dados.

Eu tenho a necessidade de customizar esse retorno da Data Annotation (primeira imagem), para seguir o mesmo padrão da segunda imagem. Há alguma forma de customizar o retorno da validação de Data Annotation?
Comment: required é um ValidationAttribute. Uma opção seria implementar o seu atributo personalizado, por exemplo RepresentanteUnicoAttribute, e utilizá-lo no pipeline de validação. Exemplo: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2
Answer: Boa tarde
Você pode customizar uma mensagem de erro utilizando a DataAnnotation.ErrorMessage
public class CreateAgentRequest
{
    [Required(ErrorMessage="Mensagem de Erro")]
    public Agent Agent { get; set; }
}

Agora se você deseja retorno o mesmo objeto da segunda imagem tenta dar uma verificada em DataAnnotation.CustomValidation, eu sei que com ele tu consegue personalizar uma Validation, e imagino que o retorno dela também.


Same domain names internal and external issue

Question: UPDATE 1:
Basically, from a computer outside the network, I can access the website by typing into the browser address bar, either of the following, which is how it should be:
http://www.companyname.com
http://companyname.com

However, from within the company network, we can only access the external website by typing in
http://www.companyname.com

It will not work if I type
http://companyname.com

ORIGINAL QUESITON:
Our internal network has the same domain name as our external website, lets say it's companyname.com for both the website and for our internal network.
This is causing problems because I am unable to access the companyname.com website from within the network.  I have to use a computer from outside the network to see the website.
Is there a way around this issue, ideally without having to change the internal or external domain names?
Comment: look at my explanation in my answer.  That's what's happening.
Answer: You need a split DNS
http://www.isaserver.org/tutorials/You_Need_to_Create_a_Split_DNS.html
A hacky way to fix it would be to put an A record in your DNS that points to the IP of the website.  (So www.yourcompanyname.com resolves to the website address)
The best way to fix it would be a split DNS. And that about sums up my knowledge of it. You might get lucky and have someone else expound further on it.
What you're seeing is (based on my experience) *.yourcompanyname.com resolving to the SOA in DNS, which is why you're not able to get to the website internally.  Put in an explicit A record for www and that should fix it.
Comment: Where does this new A record go?  In our internal DNS server, or the external DNS server?
Comment: You're having the problem internally, so your internal DNS.
Comment: I should also say that you're not going to be able to do anything else but what you have already.  If you can resolve it internally by going to www.yourcompanyname.com that's about the best you can hope for with your current situation.
Comment: Even with the split dns solution?
Comment: well, no that would fix it.  sorry, I meant that comment to regard the A record fix.
Answer: Your terminology is little confused, so your description of the problem is not detailed enough to suggest a solution. And, in fact, if you clear up your wording, you may discover that a solution will then suggest itself to you.
Networks don't have domain names. Do you mean that a resource on your internal network has the same domain name as your website. And do you mean that it has a different host name within the same domain, maybe www.companyname.com for the website and intranet.companyname.com for the internal resource, or are they the exact same host name? Finally, do you need to be able to access both the internal and external resources at the same time from the same computer?
Comment: Really sorry about that.  I don't know anything about networking, I am a programmer, trying to make my life a little easier.
Answer: When referring to your external website as companyname.com, do you actually mean www.companyname.com?
If so, the solution is simple. Just create an A record in your DNS that points to the external IP address for your website.
If you are referencing your external website by companyname.com, then you can't redirect that name internally, as that DNS entry is required to point where it currently does for your AD to function. You only option is to change your web site to use www.companyname.com.
This is one of the very reasons why I always use companyname.local internally, and companyname.com externally.
Comment: Please see update 1 in the original question.
Answer: In your description of the problem you have not indicated if this is as Windows or Linux environment, if its Windows than in your DNS server you can add a new Host A record using your websites Public IP address.
Edit - Brians answer
Comment: The tags specify Windows
Comment: Yes, our internal network in Windows based, and our external website is Linux based.


Como funciona a atribuição de lista usando intervalo?

Question: Estava lendo uma documentação na internet quando me deparei com o seguinte código:
sys.path[:0] = new_sys_path

Fiquei curioso, pois nunca tinha visto intervalos serem usados no lado esquerdo de uma atribuição (pra mim eles criavam uma sublista, e só). Um teste rápido me mostrou que esse código estava prefixando uma lista a outra:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x[:0] = y
>>> x
[4, 5, 6, 1, 2, 3]

Mas continuo sem entender a lógica dos índices: por que usar [:0] colocou a outra lista no início? Que valores podem ser usados nesse intervalo, e o que eles significam? Há outras maneiras interessantes de se usar essa funcionalidade, além de pra prefixar?
Comment: A lógica é pegar todos valores anteriores ao primeiro item da lista `x[:0]` e substituir pelo `y`, assim como `x[:1]` irá substituir o intervalo (-infinito até 1) pela lista, o funcionamento é o mesmo que `x[0] = 1` ou `x[1:] = [2, 3]`.
Comment: Diferente mesmo. Se alguém se arriscar a tentar entender e adaptar, parece que tem uma explicação em inglês aqui: http://stackoverflow.com/a/30221031/1796236
Comment: Não conheço em Python mas já vi algumas coisas do tipo em outros linguagens, e dá para fazer uma coisas interessantes, inclusive com *strings* mutáveis. Nada que não dê para fazer de outra forma, mas simplifica.
Comment: Essa eu também não conhecia. Me fez lembrar o [Mid$ em VB6](http://www.vb6.us/tutorials/vb6-string-functions) :)
Answer: O intervalo do lado esquerdo da atribuição indica que aquele intervalo (antes da mudança) vai ser substituído pelo que quer que venha depois da atribuição (que deve ser uma sequência ou um iterável)
Assim, uma atribuição a x[:0] = ... vai inserir os valores da expressão à direita no intervalo "entre o começo da lista, e a posição zero" - ou seja, vai colocar novos valores antes do inicial.
Uma atribuição à fatia  [:]  vai trocar todo o conteúdo da lista "do começo" (vazio antes do :) até "o final" (indicado por vazio depois do :) pelo conteúdo gerado na iteração da expressção da esquerda.
E inclusive há um "idioma" que é bastante usado para esvaziar uma lista já existente inplace - isso é, o objeto lista, que pode ter referências em outros lugares continua o mesmo, mas todos os seus elementos são removidos: basta associar um iterável vazio à todo o conteúdo da lista:
x[:] = []

Exemplo:
>>>
>>> x = [1, 2, 3]
>>> y = x
>>> id(x)
140612754938440
>>> x[:] = []
>>> y
[]
>>> id(x)
140612754938440

Então, x[2] = [1,2,3] vai simplesmente colocar uma nova lista 1,2,3 na posição 2 da lista original. Mas, x[2:2] = [1,2,3]está dizendo: "substitua todo o conteúdo começando na posição 2 e indo até imediatamente antes da posição 2 (ou seja, um "ponto matemático vazio antes do terceiro elemento da lista") pelos elementos da sequência [1,2,3]:  isso vai inserir esses três elementos na posição imediatamente anterior ao terceiro elemento. O "1" se torna o novo terceiro elemento, e todo o restante da lista é empurrado 3 posições para a frente:
>>> a = list(range(10,20))
>>> a
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[2:2] = [1,2,3]
>>> a
[10, 11, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19]

É diferente do método insert de listas ele empurra todo o restante para frente, mas coloca o seu argumento como um único elemento na posição indicada:
>>> a = list(range(10,20))
>>> a
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a.insert(2, [1,2,3])
>>> a
[10, 11, [1, 2, 3], 12, 13, 14, 15, 16, 17, 18, 19]
>>>

Há ainda uma outra forma de uso do "assignment to slices" que usa o terceiro parâmetro dos slices, o passo (step). Nesse caso porém, a lista não aumenta ou diminuí de tamanho de acordo com o tamanho do iterável: o número de elementos da atribuição tem que ser exatamente igual ao número de elementos que será substituído.
Por exemplo, "substitua cada terceiro elemento da minha lista, do começo até o fim, pela string 'fizz'":
a = list(range(10))
a[::3] = ["fizz"] * 4

Por baixo do capô
E isso é mágica? Não  - qualquer objeto em Python pode entregar resultados quando é acionado pelo operador de [] - ele só precisa que sua classe implemente o método __getitem__ . Para aceitar atribuições usando o x[ ] = ...o objeto deve ser de uma classe que implemente __setitem__. Se vocẽolhar na documentação oficial dos métodos mágicos, em https://docs.python.org/3/reference/datamodel.html#emulating-container-types - vai perceber que esses métodos são métodos normaizinhos de Python - o __getitem__ tem uma assinatura do tipo:
def __getitem__(self, index):
     ....

O que acontece quando alguém usa a notação de : entre colchetes é que o Python cria um objeto slice e o envia no lugar do index - o slice tem os atributos start, stop e step (uma omissão de número antes ou depois de um : coloca um None no atributo respectivo).
Então se você quiser emular um container type que use a notação de fatias para seus próprios fins, basta detectar objetos do tipo slice vindo nesses parâmetros (com isinstance) e responder de acordo.
Mais usos dos índices entre colchetes
Uma forma que não é usada na biblioteca padrão, mas que tem uso extensivo em módulos 3rd party (em particular o Numpy - a biblioteca de facto para computação científica em Python) é separar índices com uma vírgula dentro do colchetes. Isso faz com que o parâmetro index seja uma tupla de Python, e pode ser usado normalmente para indexar objetos multimensionais (o NumPy usa para matrizes).  Mais ainda, você pode usar a notação de slices dentro das expressões separadas por vírcula, dentro do colchetes.
Por exemplo, vamos usar o Numpy para criar uma matriz  de 5 x 5 números inteiros, preenche-la com "1" e usar a sintaxe de slices para "limpar" uma janela 3x3 no centro da matriz, com zeros. Note que ao contrário das listas de Python, o Numpy aceita um elemento não iterável do lado esquerdo de uma atribuição com slices: ele coloca aquele elemento em todas as posiçoes descritas.
>>> import numpy as np
>>> a = np.zeros((10,), dtype=np.uint32)
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=uint32)
>>> a[:] = 5
>>> a
array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5], dtype=uint32)

E para o exemplo da "janela":
>>> a = np.zeros((5,5), dtype=np.uint32)
>>> a[:, :] = 1
>>> a
array([[1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]], dtype=uint32)
>>> a[1:4, 1:4] = 0
>>> a
array([[1, 1, 1, 1, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 1, 1, 1, 1]], dtype=uint32)

Também quero!
Se você quiser experimentar brincar com índices, basta implementar sua própria classe com __getitem__, __setitem__ e __delitem__ - você tanto pode criar uma subclasse de list como criar seu iterador do zero. Criar uma subclasse de list diretamente tem algumas contra-indicações: o Python tem algumas otimizações internas que podem fazer com que nem todos os métodos especiais  (os que tem __nomeassim__ ) sejam chamados para todas as operações conforme se espera.  Para isso existe a classe collections.UserList (from UserList import UserList em Python2) na biblioteca padrão. Ela se comporta exatamente como uma lista, mas é feita para ser herdada. Para criar do zero, herde uma classe de collections.abc.MutableSequence e implemente os respectivos métodos descritos em https://docs.python.org/3/library/collections.abc.html - (collections.MutableSequence em Python 2.x - sem o abc).
Então para ter uma lista que ao receber uma fatia simplesmente insira o valor da expressão à direita em todas as posições da fatia, sem tentar iterar o objeto, basta fazer:
from collections import UserList

class MyList(UserList):
    def __setitem__(self, index, value):
        if isinstance(index, slice):
            start = index.start if index.start is not None else 0
            stop = index.stop if index.stop is not None else len(self)
            step = index.step if index.step is not None else 1
            for i in range(start, stop, step):
                 self[i] = value
            return
        super().__setitem__(index, value)

E assim:
>>> a = MyList(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::3] = "fizz"
0 10 3
>>> a
['fizz', 1, 2, 'fizz', 4, 5, 'fizz', 7, 8, 'fizz']
>>>

(Para uma lista normal, fizz seria tratado como um iterável, e cada letra seria usada em um lugar - o resultado seria: ['f', 1, 2, 'i', 4, 5, 'z', 7, 8, 'z'])


PHP + POSTGRESQL (Begin, Commit, Rollback)

Question: Em minha aplicação tenho um determinado processo para realizar teste. Este envolve banco de dados com multi tabelas. Gostaria de saber se é possível iniciar um BEGIN; fazer todo o desenvolvimento manual, e em caso de erro, realizar um ROLLBACK;.
Obs: Lembrando que estarão em momentos separados, não no mesmo processo, apenas com a mesma conexão.
Exemplo:
passo 1: "BEGIN;".
passo 2: processor manuais com form em html
passo 3: "ROLLBACK;" para re-teste;

Não achei muitas coisa sobre este tipo se situação e em sua maioria era recomendado delete em cascata ou validação em Javascript, o que não é o possível.
Answer: Ola, você pode utilizar o PDO, veja este exemplo. Fonte php.net
Em alguns casos é necessário desabilitar o auto commit dos bancos de dados(mysql/postgres), pode ser feito utilizando a constante PDO::ATTR_AUTOCOMMIT
Tambem é interessante habilitar o modo debug para controle de erros com PDO::ATTR_ERRMODE e PDO::ERRMODE_EXCEPTION.
Mais constantes do PDO aqui: php.net
<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
} catch (Exception $e) {
  die("Unable to connect: " . $e->getMessage());
}

try {
  $dbh->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
  $dbh->setAttribute(PDO::ATTR_ERRMODE,1);
  $dbh->setAttribute(PDO::ERRMODE_EXCEPTION,1);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())");
  $dbh->commit();

} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

O real desafio deste modelo, seria ter tabelas de bases de dados distintas em uma mesma transação...acho q seria uma outra questão.
Comment: Muito instrutivo Willian, contudo a estrutura do Frameword, não permite a conexão persistente.
E em seu exemplo, você utilizou o padrão da Transaction, na qual o BEGIN esta no mesmo processo do COMMIT e ROLLBACK, que não aborda minha necessidade de processos separados.
Mas muito obrigado pela ajuda.
Comment: de nada, tamos ae


How to use token as a filter value in views

Question: I'm looking for a solution that would allow me to use tokens in views filter values. For example, if I have text field 'my_custom_text' I would like to have a filter that would allow me to use 'Is equal to' operator and a token value instead of hardcoded string.
Note that I can't use contextual filters because I have few filters that needs to be ORed.
Is there a module for that, or do I have to code that myself from ground up?
Answer: Use Contextual Filters instead of Filter Criteria.
In Drupal 8, at the time of writing this, you also have to install the views_argument_token module.
When adding a contextual filter, at the pop up window, select "Provide default value" option. From there on the remaining settings should be intuitive.
Answer: You can use hook_views_query_alter to done your job,
implement this hook in your custom module and with if statement restrict to your views name and edit views query,
Comment: That I'm aware of. I was rather looking for some robust existing solution. It's weird that it isn't possible to use tokens or at least PHP code to obtain filter value. After all views is one of the most popular modules.
Comment: yes, you can also use `cutom_php`  module and add `php GLOBAL` filter , and provide what you want
Comment: I don't want to use `GLOBAL` filter. I only want to provide custom PHP (or token) for the string filter value. This is for existing field.
Comment: I know, bu using `global php filter` you can add criteria on other field, I used this method sometimes and worked
Comment: unfortunately 'global' filter is kind a hack, not a real solution. It is used to filter data that is already loaded from the DB. This is useless if the returned result set is huge. And this is my case - the filter I want to implement will significantly limit number of rows returned, probably from approximately 1000 to just few. It would be really unwise to load 1000 rows from DB just to display only few of them :)
Comment: @SiliconMind , you also dont want use `hook_viwes_query_alter` ?
Comment: no I do not want to use hook_views_query_alter as this would require me to dig in the code every time someone wants to change or create a view. I ended up writing my own views handler that extends one of the exiting. Also used `hook_field_views_data_alter` hook up my handler instead of default. Works quite nice but I'm still curious if there is really no support for tokens in filter views.
Answer: So here is what I've came up with eventually.

I did not want to use global php filter because it only limits the results that are already loaded from the DB. In my case this would mean loading 1000 rows just to display 2 of them. Not too wise I'd say.
I did not want to use hook_views_query_alter as this would mean that I'd have to dig into the code every time someone wants to change or create a view.

I ended up writing my own views handler that extends one of the exiting. I've also used hook_field_views_data_alter to hook up my handler instead of default.
This solution works quite nice. Custom handler is very robust solution and quite simple to implement... once you know how to do it ;)
Answer: Would the Token Filter module be helpful? Here is a quote about it (from the module's project page):

... is a very simple module to make token values available as an input filter.
The module now supports native tokens (e.g. [site:name]) and all global tokens by default. It even allows some contextual tokens like node or user to be replaced, but currently does not encourage users to use them in the filter help text.
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: tokens cannot be used in views by design


Diferença entre .NET Framework para Entity Framework

Question: Tenho um projeto Asp.Net MVC que ao clicar em propriedades é exibida a seguinte informação:

Ao abrir o arquivo packages.config pude ver essa outra informação:

Afinal, o que seria exatamente o Target framework? Qual sua função? Altera-lo pode causar problemas na aplicação ou no servidor? Quais as desvantagens de estar desatualizado?
Qual a relação entre o Entity Framework e o Target framework? Qual a dependência entre eles? Atualizar um pode afetar o outro? Posso usar uma versão mais recente do EF em uma aplicação com o Framework antigo?
Answer:
Afinal, o que seria exatamente o Target framework?

É a versão do framework .NET para o projeto inteiro. Versões mais recentes possuem mais recursos, mais funcionalidades, e a especificação das linguagens, como C#, se torna mais avançada.

Qual sua função?

O framework é o conjunto de ferramentas implementado pela Microsoft. Basicamente, todas as classes não-primitivas fazem parte dele.

Altera-lo pode causar problemas na aplicação ou no servidor?

Depende. Alterar para uma versão antiga pode sim causar problemas. Alterar para uma versão nova, dificilmente, salvo raras exceções, mas cujas exceções são devidamente documentadas na Internet.

Quais as desvantagens de estar desatualizado?

Várias, eu diria. Recursos novos saem com alguma constância. A programação assíncrona, por exemplo, não existe nativamente na versão 4 do .NET. Precisa ser adicionada como um pacote extra. Versões mais novas tendem a ser melhores em desempenho e segurança de dados.

Qual a relação entre o Entity Framework e o Target framework? Qual a dependência entre eles?

O Entity Framework é dependente da versão do .NET que você está usando. A versão 6, por exemplo, depende do framework 4.5 para funcionar.

Atualizar um pode afetar o outro?

Pode.
Atualizar o .NET para uma versão mais recente não afeta o Entity Framework. Para uma versão mais antiga, pode sim afetar.
Atualizar o Entity Framework pode, em alguns casos, criar uma incompatibilidade com o .NET, mas isso só acontece se a versão do .NET for muito antiga.

Posso usar uma versão mais recente do EF em uma aplicação com o Framework antigo?

Também depende. A versão 6 ainda suporta o .NET 4.0. Veja este link para mais informações.
Answer: Jedaias, a cada evolução do Framework, ele trás novas funcionalidades, por exemplo, o 4.5 introduziou o async e o await e o Entity Framework 6 faz uso deles através do Async Query & Save. Então se deseja fazer uso das consultas assíncronas com o EF, terá de atualizar o Framework, caso contrário poderá continuar com a versão 4.0.
Por um outro lado, se o servidor/máquina onde vai ser executado a sua aplicação suporta uma versão mais recente do Framework, deve ser relativamente tranquilo fazer migrações do 2.0 -> 3.5 ou do 4.0 -> 4.5 (ou até mesmo para o 4.6.1), afinal o Framework evoluiu de forma incremental e manteve compatibilidade com versões anteriores.
Por um outro lado, o Entity Framework sofreu uma restruturação do EF4 para o EF5, houve a mudança de algums Namespaces, então você terá de fazer alguns ajustes manuais nos seus using, assim como no seu web.config. Se fizer a atualização usando o NuGet, boa parte destas adaptações será feita automaticamente.


Height da div total proporcional ao conteudo

Question: Tenho a seguinte estrutura:

        <

        >

     1
     2
     3

TESTE

Gostaria de saber se existe uma forma de fazer com que a altura da div.slideShow, seja automaticamente ajustada à altura das div's do seu interior.
A ideia aqui é de que o navegador seja ajustado (tamanhos de tela) e a proporção se mantenha.
Antes da div.slideShow, só existe o body.
O que eu quero fazer é que, à medida que a tela for sendo redimensionada, ou puxando as brodas do navegador ou mesmo através de telas predispostas (nb's, tablet's, celulares, etc...), a altura da div.slideShow, se ajuste à altura da do seu conteúdo interno que está já está sendo redimensionado corretamente.
Porém, se eu der altura fixa à div.slideShow, quando as imagens diminuírem de tamanho, vou ter problemas.
Imagine a seguinte situação: imagina que na div.img eu tenha uma imagem com 300px de altura e resolva trocar por outra de 400px de altura ou ainda de 200px. Mantendo altura fixa na div.slideShow, terei problemas. Daí a necessidade do ajuste automático.
Como resolver esse problema?
Abaixo o código rodando:

$(document).ready(function(e) {

  quantasImagens = $("div.slideShow div.boxSlide div.imagens img").length-1;
  contador = 0;

  $("div.slideShow div.boxSlide div.anterior").click(function() {
   contador = contador==quantasImagens ?  -1 : contador;
   contador++;
   $("div.slideShow div.boxSlide div.imagens img").css("opacity",0);
   $("div.slideShow div.boxSlide div.imagens img").eq(contador).css("opacity",1);
  });

  $("div.slideShow div.boxSlide div.proximo").click(function() {
   contador = contador==0 ? quantasImagens+1 :  contador;
   contador--;
   $("div.slideShow div.boxSlide div.imagens img").css("opacity",0);
   $("div.slideShow div.boxSlide div.imagens img").eq(contador).css("opacity",1);
  });

  $("div.slideShow div.contador span.contaSlide").click(function() {
   index = $(this).index();
   $("div.slideShow div.boxSlide div.imagens img").css("opacity",0);
   $("div.slideShow div.boxSlide div.imagens img").eq(index).css("opacity",1);
  });

});
 * {
  margin:0;
  padding:0;
 }

div.slideShow {
 position: relative;
 width: 100%;
 height:300px;
}
div.slideShow div.boxSlide,
div.slideShow div.contador {
 position: relative;
 display: block;
 width: 100%;
}
div.slideShow div.boxSlide{
 height:277px;
}
div.slideShow div.boxSlide div.imagens img {
 position: absolute;
 left: 0;
 top: 0;
 opacity: 0;
 width: 100%;
}
div.slideShow div.boxSlide div.imagens img:first-child {
 opacity: 1;
}
div.slideShow div.boxSlide div.anterior,
div.slideShow div.boxSlide div.proximo {
 position: absolute;
 display: block;
 top: 100px;
}
div.slideShow div.boxSlide div.anterior {
 left: 100px;
}
div.slideShow div.boxSlide div.proximo {
 right: 100px;
}
div.slideShow div.boxSlide div.anterior span,
div.slideShow div.boxSlide div.proximo span {
 position: absolute;
 display: block;
 width: 30px;
 height: 30px;
}
div.slideShow div.boxSlide div.anterior span.boxSpan,
div.slideShow div.boxSlide div.proximo span.boxSpan {
 background-color: rgb(200,200,200);
 opacity: .5;
 z-index: 1;
}
div.slideShow div.boxSlide div.anterior span.setaSpan,
div.slideShow div.boxSlide div.proximo span.setaSpan {
 line-height: 30px;
 text-align: center;
 font-weight: bolder;
 cursor: pointer;
 z-index: 2;
}
div.slideShow div.boxSlide div span.setaSpan:hover + span.boxSpan {
 opacity: 1;
}
div.slideShow div.contador {
 /*top:240px;*/
 background-color:rgba(240,240,240,.5);
}
div.slideShow div.contador span.contaSlide {
 display: inline-block;
 width: 30px;
 height: 30px;
 line-height: 30px;
 text-align: center;
 background-color: rgb(200,200,200);
 cursor: pointer;
 opacity: .5;
}
div.slideShow div.contador span.contaSlide:hover {
 opacity: 1;
}

        <

        >

     1
     2
     3

oi
Answer: O que faz isso é o position: absolute que tira o elemento do fluxo normal da página. Para resolver sem o position: absolute faça assim:
Primeiramente na sua classe .boxSlide deixe-a com o height: auto para ela se adaptar ao tamanho do conteúdo:
div.slideShow div.boxSlide {
    height:auto;
}

Depois remova o position: absolute das suas imagens para que elas voltem ao fluxo normal da página e esconda-as com o display: none ao invés de opacity: 0 pois assim as imagens que não estiverem a mostra não vão ocupar espaço abaixo:
div.slideShow div.boxSlide div.imagens img {
    width: 100%;
    height: auto;
    display: none;
}

E por fim deixamos a primeira imagem com display: block:
div.slideShow div.boxSlide div.imagens img:first-child {
    display: block;
}

Agora no seu Javascript ao invés de mudar o opacity das imagens mudamos o display (faça isso nos outros trechos):
  $("div.slideShow div.boxSlide div.imagens img").css("display", "none");
  $("div.slideShow div.boxSlide div.imagens img").eq(contador).css("display", "block");

Código completo funcionando:

$(document).ready(function(e) {

  quantasImagens = $("div.slideShow div.boxSlide div.imagens img").length-1;
  contador = 0;

  $("div.slideShow div.boxSlide div.anterior").click(function() {
   contador = contador==quantasImagens ?  -1 : contador;
   contador++;
   $("div.slideShow div.boxSlide div.imagens img").css("display", "none");
   $("div.slideShow div.boxSlide div.imagens img").eq(contador).css("display", "block");
  });

  $("div.slideShow div.boxSlide div.proximo").click(function() {
   contador = contador==0 ? quantasImagens+1 :  contador;
   contador--;
   $("div.slideShow div.boxSlide div.imagens img").css("display", "none");
   $("div.slideShow div.boxSlide div.imagens img").eq(contador).css("display", "block");
  });

  $("div.slideShow div.contador span.contaSlide").click(function() {
   index = $(this).index();
   $("div.slideShow div.boxSlide div.imagens img").css("display", "none");
   $("div.slideShow div.boxSlide div.imagens img").eq(index).css("display", "block");
  });

});
* {
  margin:0;
  padding:0;
 }

div.slideShow {
 position: relative;
 width: 100%;
 height:300px;
}
div.slideShow div.boxSlide,
div.slideShow div.contador {
 position: relative;
 display: block;
 width: 100%;
}
div.slideShow div.boxSlide{
 height:auto;
}
div.slideShow div.boxSlide div.imagens img {
 width: 100%;
 height: auto;
 display: none;
}
div.slideShow div.boxSlide div.imagens img:first-child {
 display: block;
}
div.slideShow div.boxSlide div.anterior,
div.slideShow div.boxSlide div.proximo {
 position: absolute;
 display: block;
 top: 100px;
}
div.slideShow div.boxSlide div.anterior {
 left: 100px;
}
div.slideShow div.boxSlide div.proximo {
 right: 100px;
}
div.slideShow div.boxSlide div.anterior span,
div.slideShow div.boxSlide div.proximo span {
 position: absolute;
 display: block;
 width: 30px;
 height: 30px;
}
div.slideShow div.boxSlide div.anterior span.boxSpan,
div.slideShow div.boxSlide div.proximo span.boxSpan {
 background-color: rgb(200,200,200);
 opacity: .5;
 z-index: 1;
}
div.slideShow div.boxSlide div.anterior span.setaSpan,
div.slideShow div.boxSlide div.proximo span.setaSpan {
 line-height: 30px;
 text-align: center;
 font-weight: bolder;
 cursor: pointer;
 z-index: 2;
}
div.slideShow div.boxSlide div span.setaSpan:hover + span.boxSpan {
 opacity: 1;
}
div.slideShow div.contador {
 /*top:240px;*/
 background-color:rgba(240,240,240,.5);
}
div.slideShow div.contador span.contaSlide {
 display: inline-block;
 width: 30px;
 height: 30px;
 line-height: 30px;
 text-align: center;
 background-color: rgb(200,200,200);
 cursor: pointer;
 opacity: .5;
}
div.slideShow div.contador span.contaSlide:hover {
 opacity: 1;
}

        anterior

        proximo

     1
     2
     3

Comment: então, mas isso não está resolvendo. Pois se eu coloco alguma coisa abaixo da div.total, esse conteúdo sobre pro incio da div.total. Bom, as imagens da div.img estão com position absolute e precisam se assim. Será isso?
Comment: Sim é exatamente isso, o postion: absolute faz com que o elemento 'saia' do fluxo normal, então ele não preenche o elemento pai
Comment: Existe algum recurso? Cheguei até colocar uma div com clear:both abaixo mas não resolveu
Comment: Faça o seguinte, edite sua resposta e no menu que aparece onde você edita o texto da pergunta clique em `Trecho Javascript/HTML/Css` e adicione o código html/css nos quadros que aparecerem, assim podemos 'ver' seu código rodando e fica mais fácil ajudar.
Comment: Mas quanto ao position: absolute não adianta o clear: both, isso funciona mais para floats, provavelmente terá que mudar esse position: absolute.
Comment: duvida completa aqui: https://pt.stackoverflow.com/questions/247185/slideshow-n%C3%A3o-funciona-direito-ap%C3%B3s-migra%C3%A7%C3%A3o, procurei minimizar o problema nesse nosso tópico. Código rodando aqui: http://hotplateprensas.com.br/estilos/slide.php
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/67369/discussion-between-bruno-romualdo-and-carlos-rocha).
Comment: feito conforme sua orientação. Observe que, como as imagens reduziram de tamanho acompanhando o browser, a div do menu desceu muito por causa da altura fix da div principal
Comment: ok entre no chat, pra não ficar muito longo aqui.
Comment: mais um probleminha: desta vez com as setas. Note que embora ambas estão posicionadas à 100px das margens, embora eu tenha trocado aqui para 10%, a margem direita meio que não está respeitando isso quando diminuímos muito o browser
Comment: Isso foge da pergunta principal mas vou te responder no chat.
Comment: Se puder dar a pergunta como respondida agradeço :)
Comment: certeza. Pela tua solução, o meu erro estava em não tornar display:none nas outras div's que não estavam sendo mostradas. Então, todas ficavam display:block, empurrando as demais para baixo. este era o meu erro. Muito obrigado!
Comment: Sobre as div's das setas, a ideia aqui era criar um quadrado com background e opacity:0 e quando passar o mouse sobre ele, ele aparece com oacity:1
Answer: Visto que as imagens teem position: absolute, eu sugeria que desse um height fixo às imagens, por exemplo 500px e depois desse à div esse height.
Comment: Não posso. Exatamente por causa do layout responsivo.


different ways of calculating laurent series of $\frac{1}{1+z^2}$ at $z=0$

Question: it seem to me that in that simple case there are different ways of doing this.
I have to wonder on the general case of $\dfrac{1}{a+z^2}$ at $z=0$.
edit: the interesting part of course is where $|z| > 1$
Answer: Try to differentiate:
$$\frac1a\frac{d}{dx}\arctan\frac xa=\frac1{a^2+x^2}$$
Use $$\arctan x=x-\frac{x^3}3+\frac{x^5}5-\frac{x^7}7+..$$
Comment: Well, I'm asking of different ways. and this is Taylor. I'm talking about Laurent were |x| also > 1
Comment: @d_e see edit..
Comment: thanks can you elaborate more ?
Comment: Series convergent for $|x|<1$.
Answer: The usual trick for this case:
$$\dfrac{1}{a+z^2} = \dfrac{1}{z^2}\dfrac{1}{1-(-a/z^2)} = \dfrac{1}{z^2}\sum_{n=0}^\infty(-1)^n\frac{a^n}{z^{2n}}.$$
Comment: i already tried to tell op that but he said what is the first comment on my post/answer


Simplification trick

Question: it is maybe at bit of a silly question, but one of our professors wrote the following equations and I would like to know what exactly he did. I'm sure it is something easy but I have no clue:
$$\frac{pc}{1+r} \approx \frac{c}{1+r+q}$$
Note: $p$ and $q$ are probabilities and $1-q = p$
Answer: My attempt is: $\dfrac{c}{1+r+q} = \dfrac{c}{1+r}\cdot \dfrac{1}{1+\dfrac{q}{1+r}} = \dfrac{c}{1+r}\cdot \left(1 - \dfrac{q}{1+r} + \left(\dfrac{q}{1+r}\right)^2 - \left(\dfrac{q}{1+r}\right)^3 + ....\right) \approx \dfrac{c}{1+r}\cdot \left(1 - q + q^2 - q^3 +...+ \right) \approx \dfrac{c}{1+r}\cdot \left(1 - q\right) = \dfrac{pc}{1+r}$
Comment: Assuming $q,r\ll 1$, and $q \gg r$...
Comment: @nbubis: I think so.

Simplification trick


Melhorar performance em iteração

Question: Tenho um método em C# que recebe um List<string> e eu devo retornar uma string com a listagem dos membros da List<string> ordenados por quantidade de ocorrências e depois por ordem alfabética.
Eu fiz e já funcionou, porém não com a performance esperada.
public string getMostOccuredString(IList<string> lista)
{
     var mostOccured = lista
                         .GroupBy(a => a)
                         .Select(g => new { g.Key, Count = g.Count() })
                         .OrderByDescending(c => c.Count)
                         .ThenBy(c => c.Key);

     string retorno = "";

     foreach (var item in mostOccured)
     {
          retorno = retorno + ";" + item.Key;
     }

     return retorno;
}

Comment: Usar "for" em vez de "foreach" e StringBuilder em vez de concatenaçao pode ajudar a melhorar a performance.
Comment: @LucasMiranda a diferença será brutal, só não faz o mesmo que esse laço. Pode até ser que ele queria mais o `Join()`que esse laço, mas não temos como saber.
Comment: embora seja uma diferença minima de performance você poderia trocar esse foreach por um string.join que é relativamente mais elegante e ligeiramente mais performático, exemplo:retorno  =  String.Join(";", mostOccured);
Comment: ah sim, eu não vi ali que ele tava pegando o key, bem observado
Answer: Se o desejo é performance esqueça o LINQ, ele não é rápido, ele deixa escrever de forma mais expressiva, ou bonitinho ou curto como alguns vão dizer, mas ele não é rápido. Ele não é trágico, mas não serve para velocidade, tire isso e faça na mão. Dá uma olhada na documentação.
Claro, teste, existem casos que pode não ser bem assim, até porque pode fazer manualmente e ficar pior do que deveria.
Mas o que é pior nesse código é o problema das criações de strings sem necessidade. Isso vai enchendo a memória e coloca pressão no coletor de lixo fazendo o sistema entrar em pausas. Isso está explicado em Por que devo usar a classe StringBuilder ao invés da classe String?. Também Qual o mais rápido na construção de texto?. Um exemplo.
Quem sabe possa usar o Join() no lugar do laço, a execução não dará o mesmo resultado, mas pode ser que seja até melhor para o que deseja.
Outra questão é ver se não consegue receber uma lista já classificada ou usar uma estrutura de dados que mantenha os dados classificados automaticamente. Não sei se pode fazer isso, mas é algo para se pensar. Muitas vezes a questão da performance não pode ser resolvida pontualmente, precisa pensar no todo. Ou aceitar que a velocidade é ruim, nem tudo pode ser melhorado, se não puder mexer em outros pontos. Só observe os itens anteriores que farão diferença, principalmente o do StringBuilder.
Comment: Show @maniero . Obrigado pelas dicas. Realmente a questão das string é bem válida.

Melhorar performance em iteração