Formatar CEP na Consulta - Mysql

Question: Na minha coluna do banco tenho o campo CEP varchar(20), e um registro: "92820142" existe alguma forma de formatar no padrão: 92.820-142 durante a consulta?
Tentei utilizar o format, mas conflitou no tipo de dados.
Comment: Sim Jefferson, é proposital, um trabalho de faculdade
Comment: Normalmente isso é tratado na camada de apresentação. Tem certeza que quer tratar a nível de consulta?
Answer: Utilize esta função:
DELIMITER //

CREATE FUNCTION mask (unformatted_value BIGINT, format_string CHAR(32))
RETURNS CHAR(32) DETERMINISTIC

BEGIN
# Declare variables
DECLARE input_len TINYINT;
DECLARE output_len TINYINT;
DECLARE temp_char CHAR;

# Initialize variables
SET input_len = LENGTH(unformatted_value);
SET output_len = LENGTH(format_string);

# Construct formated string
WHILE ( output_len > 0 ) DO

SET temp_char = SUBSTR(format_string, output_len, 1);
IF ( temp_char = '#' ) THEN
IF ( input_len > 0 ) THEN
SET format_string = INSERT(format_string, output_len, 1, SUBSTR(unformatted_value, input_len, 1));
SET input_len = input_len - 1;
ELSE
SET format_string = INSERT(format_string, output_len, 1, '0');
END IF;
END IF;

SET output_len = output_len - 1;
END WHILE;

RETURN format_string;
END //

DELIMITER ;

Como utilizar:
mysql> select mask(123456789,'###-##-####');
+-------------------------------+
| mask(123456789,'###-##-####') |
+-------------------------------+
| 123-45-6789                   |
+-------------------------------+
1 row in set (0.00 sec)

mysql> select mask(123456789,'(###) ###-####');
+----------------------------------+
| mask(123456789,'(###) ###-####') |
+----------------------------------+
| (012) 345-6789                   |
+----------------------------------+
1 row in set (0.00 sec)

mysql> select mask(123456789,'###-#!##@(###)');
+----------------------------------+
| mask(123456789,'###-#!##@(###)') |
+----------------------------------+
| 123-4!56@(789)                   |
+----------------------------------+
1 row in set (0.00 sec)

Fonte: https://stackoverflow.com/questions/10112718/mysql-output-masking-i-e-phone-number-ssn-etc-display-formatting
Answer: A forma mais simples acredito que é utilizando CONCAT() junto com SUBSTRING:
SELECT CONCAT(SUBSTRING(CEP,1,2),'.',SUBSTRING(CEP,3,3),'-',SUBSTRING(CEP,6,3)) FROM {suatabela} WHERE ...

Vai funcionar se todos estiverem no padrão de 8 dígitos sem nenhum outro caracter, como "." ou "-".

Formatar CEP na Consulta - Mysql


Why huge gap between keyboard events?

Question: I'm writing an input control function for a small javascript game. There seems to be a significantly longer delay between the first and second keydown events than the subsequent events. Consider the following:
let lastPress = 0;

const keydownHandler = (event) => {
  console.log(event.keyCode + ', delta time: ' + (Date.now() - lastPress));
  lastPress = Date.now();
}

document.addEventListener("keydown", keydownHandler, false);

If I run this and hold the right arrow key down I'll see a listing like this (in formatted version):

Keycode
Delta time

39
142129

39
492

39
82

39
87

39
82

39
83

39
82

39
84

39
82

39
86

Now, the first delta is obviously huge (since I'm looking at the difference between the previous call to the event handler). What I don't understand is the value 492 ms compared to the 82 - 87 ms on the following calls.
Why is there such a significant gap between the first two events? And is there a way to narrow that gap?
Comment: Auto-repeat doesn't start until you've held the key down for a little while. There should be a system setting that controls this delay.
Comment: Keyboard settings?
Comment: Have you tried using the `input` event, rather than keyboard events? A keyboard event like `keydown` isn't going to work on a touch device anyway.
Comment: To expand @Barmar 's answer, this first-letter delay is implemented intentionally to decrease the probability of duplicating characters while user types a text. There's indeed a system setting just for that in each OS. You could also consider this answer to simulate continuous keydowns: https://stackoverflow.com/a/29191638/504474
Answer: Based on the comments I gathered that this is by design. I ended up with the following (sort of similar to the SO post linked in the comments):
currentKeys = [];

const findKey = (keyCode) => {
  return currentKeys.indexOf(keyCode);
}

const keydownHandler = (event) => {
  if (findKey(event.keyCode) === -1) {
    currentKeys.push(event.keyCode);
  }
}

const keyupHandler = (event) => {
  const index = findKey(event.keyCode);
  if (index >= 0) {
    currentKeys.splice(index, 1);
  }
}

Then, in the game update function I moved the player according to the input.
Comment: You should use a `Set` to track currently pressed keys.
Comment: `const currentKeys = new Set(); currentKeys.add(event.keyCode); currentKeys.has(event.keyCode); currentKeys.delete(event.keyCode);`
Comment: You don't even need the other checks then: you can add the same value again without issues, and attempt to remove a non-present value without issue.
Comment: `const currentKeys = new Set(); const keydownHandler = (event) => { currentKeys.add(event.keyCode) }; const keyupHandler = (event) => { currentKeys.delete(event.keyCode) }`
Comment: Your other code can then iterate over the present values using `currentKeys.keys()` or `currentKeys.values()` (they're equivalent with `Set`).

Why huge gap between keyboard events?


How to synchronize OpenGL drawing with UIKit updates

Question: In our app we have UIScrollView above CAEAGLLayer. UIScrollView contains some UIViews (red rectangles). In CAEAGLLayer we draw white rectangles. Centers of white rectangles are the same as the centers of red rectangles. When UIScrollView scrolls, we update positions of white rectangles in CAEAGLLayer and render them.
We are getting the expected result: centers of white rectangles are always the same as centers of red rectangles.
But we can't synchronize updates of the CAEAGLLayer with the movement of the views inside UIScrollView.
We have some kind of mistiming – red rectangles lag behind white rectangles.
Speaking roughly, we really want to make CAEAGLLayer lag together with the UIScollView.
We have prepared sample code. Run it on the device and scroll, and you will see that white rectangles (drawn by OpenGL) are moving faster than red ones (regular UIViews). OpenGL is being updated within scrollViewDidScroll: delegate call.
https://www.dropbox.com/s/kzybsyu10825ikw/ios-opengl-scrollview-test.zip
It behaves the same even in iOS Simulator, just take a look at the video: http://www.youtube.com/watch?v=1T9hsAVrEXw
Red = UIKit, White = OpenGL
Code is:
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    // reuses red squares that are gone outside thw bounds
    [overlayView updateVisibleRect:CGRectMake(...)];
    // draws white squares using OpenGL under the red squares
    [openGlView updateVisibleRect:CGRectMake(...)];
}

Edit:
The same issue can easily be demonstrated in a much simplified sample. The working xcodeproj can be find at:
https://www.dropbox.com/s/vznzccibhlf8bon/simple_sample.zip
The sample project basically draws and animates a set of WHITE squares in OpenGL and does the same for a RED set of UIViews. The lagging can easily be seen between the red and white squares.
Comment: +1 for excellent (reduced) sample project.
Comment: Using Xcode 6+, to get the sample project working it's necessary to: `#import ` in ViewController.mm
Answer: In iOS 9 CAEAGLLayer has presentsWithTransaction property that synchronizes the two.
Comment: This was very hard to find. Thank you.
Answer: In fact, you can't synchronize them using current APIs. MobileMaps.app and Apple Map Kit use private property on CAEAGLLayer asynchronous to workaround this issue.
Here is related radar: http://openradar.appspot.com/radar?id=3118401
Comment: I know it's not iOS, but is this related? [link](http://www.techques.com/question/1-7610117/Layer-backed-OpenGLView-redraws-only-if-window-is-resized) I've mentioned that not using displaylink improves the refreshrate allot! I'm using Openframeworks v0.74 for this, 0.80 has displaylink and there's a big difference.
Answer: After digging around a little I'd like to extend my previous answer:
Your OpenGL rendering is immediately done from within the scrollViewDidScroll: method while the UIKit drawing is performed later, during normal CATransaction updates from the runloop.
To synchronize UIKit updates with the OpenGL rendering just enclose both in one explicit transaction and flush it to force UIKit to commit the changes to backbaordd immediately:
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    [CATransaction begin];
    [overlayView updateVisibleRect:CGRectMake(...)];
    [openGlView updateVisibleRect:CGRectMake(...)];
    [CATransaction flush]; // trigger a UIKit and Core Animation graphics update
    [CATransaction commit];
}

Comment: @NikolaiRuhe This is excellent, thanks for posting it. We had a requirement to sync an OpenGL view with a CA view and this worked beautifully. I cannot comment on performance - in our case performance was not an issue as the synchronised draw was not required frequently.
Comment: Thanks for help! We have found this solution, and the drawing is synchronized. But the performance is very poor (I'm talking about our app, not the sample code). Unfortunately, this is not the way for us.
Comment: Had the performance issue too. Fixed it by refreshing everything exept the the scrollViewDidScroll, so it's viewForZoomingInScrollView,gestureRecognizer,gestureRecognizerShouldBegin, gestureRecognizer
Answer: In lack of a proper answer I'd like to share my thoughts:
There are two ways of drawing involved: Core Animation (UIKit) and OpenGL. In the end, all drawing is done by OpenGL but the Core Animation part is rendered in backboardd (or Springboard.app, before iOS 6) which serves as a kind of window server.
To make this work your app's process serializes the layer hierarchy and changes to its properties and passes the data over to backboardd which in turn renders and composes the layers and makes the result visible.
When mixing OpenGL with UIKit, the CAEAGLLayer's rendering (which is done in your app) has to be composited with the rest of the Core Animation layers. I'm guessing that the render buffer used by the CAEAGLLayer is somehow shared with backboardd to have a fast way of transferring your application's rendering. This mechanism does not necessarily has to be synchronized with the updates from Core Animation.
To solve your issue it would be necessary to find a way of synchronizing the OpenGL rendering with the Core Animation layer serialization and transfer to backboardd. Sorry for not being able to present a solution but I hope these thoughts and guesses help you to understand the reason for the problem.
Comment: "...passes the data over to backboardd which in turn renders and composes the layers and makes the result visible." - That's awesome! How do you know this and where can I read more about this?
Comment: @BartoszCiechanowski I'm afraid I do not have a reference for the statements I made in both of my answers. Most of the information is derived from observations made while debugging or analyzing apps or is just pure guesswork. Doing some reverse-engeneering on Core Animation also helped to understand the private serialization of a layer tree and changes therein.
Comment: At WWDC Apple stuff were telling that Core Animation rendering is going in backboardd in iOS 6. In iOS 5 and earlier rendering performed in springboardd.
Answer: I am trying to solve exactly same issue. I tried all method described above but nothing was acceptable.
Ideally, this can be solved by accessing Core Animation's final compositing GL context. But we  can't access the private API.
One another way is transferring GL result to CA. I tried this by reading frame-buffer pixels to dispatch to CALayer which was too slow. About over 200MB/sec data should be transferred. Now I am trying to optimize this. Because this is the last way that I can try.
Update
Still heavy, but reading frame-buffer and setting it to a CALayer.content is working well and shows acceptable performance on my iPhone 4S. Anyway over 70% of CPU load is used only for this reading and setting operation. Especially glReadPixels I this most of them are just waiting time for reading data from GPU memory.
Update2
I gave up last method. It's cost is almost purely pixel transferring and still too slow. I decided to draw every dynamic objects in GL. Only some static popup views will be drawn with CA.
Comment: Eonil, if you know any _private_ API that allows to archive the result, please let me know.
Comment: @beefon Unfortunately, I don't know either. It's just my guess. Sorry for not clarifying it as guess. I requested a technical support to Apple about this, and I will update this answer as I get their response.
Comment: I have requested Apple DTS too, they told me that there is no way to fix our issue now. They proposed to fill a bug report requesting an API.
Comment: @beefon Wow. Thanks for letting me know that. I will file the bug too.
Answer: In order to synchronize UIKit and OpenGL drawing, you should try to render where Core Animation expects you to draw, i.e. something like this:
- (void)displayLayer:(CALayer *)layer
{
    [self drawFrame];
}

- (void)updateVisibleRect:(CGRect)rect {
    _visibleRect = rect;
    [self.layer setNeedsDisplay];
}

Comment: CAEGLLayer is not support calling setNeedsDisplay.
Comment: Currently (iOS 6.0) it support calling `setNeedsdisplay` and dispatches `-displayLayer:` message properly, but GL rendering is still happen earlier than CA rendering.


Proving a union by using the laws of algebra of sets and a new operator

Question: So I am given a new opeator A * B = complement of (A intersect B).  I apologize for not being able to post this with the correct syntax.
Using this new operator, I am to prove, algebraically, that the following is true:
(A * A) * (B * B) = A U B
I've gotten this far:

2nd part:
Comment: It's better do not use an image, or at least rotate it.
Answer: You are almost there! Remember De Morgan's Law:
$${\overline {A\cap B}}={\overline {A}}\cup {\overline {B}}$$
I will use two different notations for complement so you can see it better in the next line. Continuing from what you had,
$$\overline{A} * \overline{B} = \overline{(\overline{A} \cap \overline{B})} = \overline{A^c} \cup \overline{B^c}$$
Note that the complement of the complement of a set is just that set ($\overline{A^c} = A$) and hence you have:
$$(A * A) * (B * B) = A \cup B$$
Let me know if you need further explanation!
Comment: Use the same law as above. To avoid notational difficulties, I would recommend letting $C = A \cap B$. Then you get: $$(A * B) * (A * B) = \overline{C} * \overline{C} = \overline{\overline{C} \cap \overline{C}} = \overline{\overline{C}} \cup \overline{\overline{C}} = C \cup C = C = A \cap B$$
Comment: Thanx man.  So I'm kinda stuck on the 2nd part.  I have (A * B ) * (A * B ) = A intersect B and so far I got to: Complement(A intersect B) * Complement(A intersect B) = Complement(Complement(A intersect B) intersect Complement(A intersect B).)
Comment: Check the post edit
Answer: The exercice mainly aims at testing your knowledge of (1) idempotency of the intersection operation and of  (2) De Morgan's law for sets.
Note : here I use  " X' "  to denote the complement of a set X and the symbol " X ''  " to denote the complement of the complement of X
x belongs to (A*A) * (B * B)
is equivalent to
(1) x belongs to [ (A * A) Inter (B * B)]'
(2) x belongs to [ (A Inter A)' Inter (B Inter B)' ] '
(3) x belongs to [      A '     Inter      B'      ]'
(4) x belongs to        A ''      Union    B ''
(5) x belongs to        A         Union    B
Reasons
For (1) : definition of the * operator
For (2) : again, definition of the * operator
For (3) : idempotency of the Intersection operation ( for all X, X Inter X = X)
For (4) : De Morgan's law for sets ( The complement of X Inter Y is X' Union Y')
For (5) : law of involution ( the complement of the complement of X is X itself)


Why should an API return 'void'?

Question: When writing an API or reusable object, is there any technical reason why all method calls that return 'void' shouldn't just return 'this' (*this in C++)?
For example, using the string class, we can do this kind of thing:
string input= ...;
string.Join(input.TrimStart().TrimEnd().Split("|"), "-");

but we can't do this:
string.Join(input.TrimStart().TrimEnd().Split("|").Reverse(), "-");

..because Array.Reverse() returns void.
There are many other examples where an API has lots of void-returning operations, so code ends up looking like:
api.Method1();
api.Method2();
api.Method3();

..but it would be perfectly possible to write:
api.Method1().Method2().Method3()

..if the API designer had allowed this.
Is there a technical reason for following this route? Or is it just a style thing, to indicate mutability/new object?
(x-ref Stylistic question concerning returning void)

EPILOGUE
I've accepted Luvieere's answer as I think this best represents the intention/design, but it seems there are popular API examples out there that deviate from this :
In C++ cout << setprecision(..) << number << setwidth(..) << othernumber; seems to alter the cout object in order to modify the next datum inserted.
In .NET, Stack.Pop() and Queue.Dequeue() both return an item but change the collection too.
Props to ChrisW and others for getting detailed on the actual performance costs.
Comment: See http://stackoverflow.com/questions/3124001/fluent-interface-pattern-in-objective-c/3126305#3126305 and @bbum's answer for experience from Objective-C
Comment: The pattern you are describing is also known as *method chaining* (http://martinfowler.com/dslwip/MethodChaining.html).
Comment: Method chaining, or fluent interfaces (though purists claim something more's required for the latter, I believe!).
Comment: Ahhh - it has a name! It seems quite readable, and popular in things like JQuery
Comment: @Mark: Great link - I didn't know of the 'fluent' name, so my initial search didn't bring this up.
Answer: Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.
Comment: @JBRWilkinson The semantic definition of a stack, given in VDM, describes the following operations:

  init: -> Stack;
  push: N x Stack -> Stack;
  top: Stack -> (N U ERROR);
  remove: Stack -> Stack;
  isempty: Stack -> Boolean

none of which removes AND returns something. This tells me that the original intent was to clearly distinguish between side-effect inducing calls and pure calls. The Pop() method is therefore a syntactic convenience, rather than a formal practice.
Comment: In C++, there are other ways to express this - const member functions, for example..?
Comment: @JBRWilkinson The question's scope is broader than C++, it also has a C# tag. What I've said was meant as a language-agnostic API practice.
Comment: Stack.Pop() (http://msdn.microsoft.com/en-us/library/system.collections.stack.pop.aspx) is an example of an API that returns a value yet also changes the object. Is this bad design (should've been : use Peek() to read, use Pop() to remove) or a legitimate exception to the rule?
Answer: If you had Reverse() return a string, then it wouldn't be obvious to a user of the API whether it returned a new string or the same-one, reversed in-place.
string my_string = "hello";
string your_string = my_string.reverse(); // is my_string reversed or not?

That is why, for instance, in Python, list.sort() returns None; it distinguishes the in-place sort from sorted(my_list).
Answer:
Is there a technical reason for following this route?

One of the C++ design guidelines is "don't pay for features you don't use"; returning this would have some (slight) performance penalty, for a feature which many people (I, for one) wouldn't be inclined to make use of.
Comment: JBRWilkinson Wherever the this pointer is, it ought to be the this pointer of the calling process by the time it returns to the calling process. Actually, using MSVC, the `this` pointer is in the `ecx` register, and return code is in the `eax` register: so the performance penalty would be an extra `mov ecx,eax` instruction at the end of the/every called subroutine.
Comment: @JBRWilkinson The extra opcode could be optimized away when it's not used, only when the called routine knows where it's being called from, i.e. when it's inlined (but inlining everything would have performance problems of its own).
Comment: What's the performance penalty in C++? Isn't the this pointer on the stack anyhow?
Comment: thanks for the detail. This is reason enough in a high-performance API.
Answer: The technical principal that many others have mentioned (that void emphasizes the fact the function has a side-effect) is known as Command-Query Separation.
While there are pros and cons to this principle, e.g., (subjectively) clearer intent vs. more concise API, the most important part is to be consistent.
Comment: The Wiki article seems a bit muddy.  It is entirely normal for commands to return an indication of whether something unexpected happened.  Something like the incrementAndReturnValue function behaves as a command, but returns a value for the purpose of allowing the caller to know what happened.  One could pass an "expected" value and have the function return a boolean saying whether things were "as expected", but it's easier for the caller to do the comparison itself.
Answer: I'd imagine one reason might be simplicity. Quite simply, an API should generally be as minimal as possible. It should be clear with every aspect of it, what it is for.
If I see a function that returns void, I know that the return type is not important. Whatever the function does, it doesn't return anything for me to work with.
If a function returns something non-void, I have to stop and wonder why. What is this object that might be returned? Why is it returned? Can I assume that this is always returned, or will  it sometimes be null? Or an entirely different object? And so on.
In a third-party API, I'd prefer if that kind of questions just never arise.
If the function doesn't need to return anything, it shouldn't return anything.
Comment: +1. It'd be easy enough to write a method chaining wrapper over it if a convenient syntax is desired. I'd prefer that to pessimizing all kinds of functions by returning this/*this when not necessary in favor of a debatable stylistic shorthand.
Answer: If you intend your API to be called from F#, please do return void unless you're convinced that this particular method call is going to be chained with another nearly every time it's used.
If you don't care about making your API easy to use from F#, you can stop reading here.
F# is more strict than C# in certain areas - it wants you to be explicit about whether you're calling a method in order to get a value, or purely for its side-effects. As a result, calling a method for its side-effects when that method also returns a value becomes awkward, because the returned value has to be explicitly ignored in order to avoid compiler errors. This makes "fluent interfaces" somewhat awkward to use from F#, which has its own superior syntax for chaining a series of calls together.
For example, suppose we have a logging system with a Log method that returns this to allow for some sort of method chaining:
let add x y =
    Logger.Log(String.Format("Adding {0} and {1}", x, y)) // #1
    x + y                                                 // #2

In F#, because line #1 is a method call that returns a value, and we're not doing anything with that value, the add function is considered to take two values and return that Logger instance. However, line #2 not only also returns a value, it appears after what F# considers to be the "return" statement for the function, effectively making two "return" statements. This will cause a compiler error, and we need to explicitly ignore the return value of the Log method to avoid this error, so that our add method has only a single return statement.
let add x y =
    Logger.Log(String.Format("Adding {0} and {1}", x, y)) |> ignore
    x + y

As you might guess, making lots of "Fluent API" calls that are mainly about side-effects becomes a somewhat frustrating exercise in sprinkling lots of ignore statements all over the place.
You can, of course, have the best of both worlds and please both C# and F# developers by providing both a fluent API and an F# module for working with your code. But if you're not going to do that, and you intend your API for public consumption, please think twice before returning this from every single method.
Comment: Interesting to see how other languages actually kind of depend on this pattern. Thanks for the great answer!
Comment: This reminds me of Yegge's "Rhinos and Tigers", which discusses (among other things) if and how VMs can support calling between multiple languages.  "And they're like (waving hands) 'Ooooh, we'll gloss over it, gloss over it, smooth it over.' And the reply is: 'You can't. This is fundamental. These languages work differently!'"
Answer: Besides the design reasons, there is also a slight performance cost (both in speed and space) for returning this.
Comment: ChrisW provided some great comments in his answer. Every language/platform should be pretty similar in this respect. For example, in C#/.NET, the compiler will have to add an IL return instruction to the asssembly and the JIT compiler should in most cases convert that to a `mov eax,ecx` instruction just like the C++ compiler in his example.

Why should an API return 'void'?


What happened to the front of this guitar?

Question: It has 4 marks, fairly similar though the two above being smaller than those below, on the front, like it had something attached to it at some point or something - anyone know what it was or how these marks have come about otherwise? And must these have been holes which have been filled in, or is it just cosmetic damage? Many thanks!
(Also feel free to tell me this should be posted on a different site, cheers)
Comment: Only a guess - a Roland hexatonic pick up was attached at some time, to go with the Roland synth.
Comment: @Tim that's exactly what it looks like. My Roland hexaphonic pickup has exactly the same footprint.
Answer: There's a Roland hexaphonic pickup, that more often is fitted to Strats, from my experience (I used to own one). It's a special pup that converts to sort of MIDI, and connects via a multi core cable to the Roland 'brain' - a synth, providing every sound one could imagine. Some worked well with this arrangement, some not so. The guitar could still be plugged in via a jack, so the 'best of both worlds'. It never really took off, and fitting was quite finnicky to get the adjustment right.
Seems that could be what's left, as the 'pup' needed to be screwed onto the body, close to the bridge. The other marks are probably from where the socket was fitted.


How to get a machine name of a custom block

Question: I have a custom "Slider Items" field type, as well as the custom "Channel Slider Block Type" type block (created using "Custom block library").

Also, I have several "Channel Slider Block Type" blocks.  I need to somehow determine the machine name of a block that this field displays in @FieldFormatter of my field. How can this be implemented? Perhaps there is a special service for this?

/**
 * @FieldFormatter(
 *   id = "channel_slider_formatter",
 *   label = @Translation("Channel Slider Formatter"),
 *   field_types = {
 *     "channel_slider"
 *   }
 * )
 */
class ChannelSliderFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Here I need to get a block that reflects this field.
    $blockMachineName = '...';
    ...
    return [
      '#theme' => 'channel_slider',
      '#items' => $itemsData,
    ];
  }

}

Answer: A custom content block has no unique machine name, only a bundle type, an UUID and an ID. Only custom content blocks placed in a region have a machine name, but this is NOT the machine name of the block, it is the machine name of the block placement (configuration)
Comment: Thank you very much for your reply! This brought clarity.
Answer: Custom blocks do not have machine name since they are content entities. What you can do is to check the bundle of the block in your field formatter.
public function viewElements(FieldItemListInterface $items, $langcode) {
  if ($items->isEmpty()) {
    return NULL;
  }

  $entity = $items->first()->getEntity();
  if ($entity->getTargetEntityTypeId() === 'block_custom') {
     // Heres my great block type.
     $block_type = $entity->bundle();
     // Do something with it.
  }

  // The usual sutff.
}

Comment: Thank you very much for your reply! Bundle is what I need.. Incredibly grateful to you.


System.Web.resources.dll não encontrado

Question: Temos um projeto mvc3/dotnet4, que consome servidores DCOM (c++) através de intertops.
Tanto os servidores DCOM (c++) como o projeto mvc3 (c#) eram compilados com visual studio 2013.
Os projetos foram migrados para visual studio 2015.
No windows 2012/8 em diante, tudo funciona perfeitamente.
Mas no windows 2008r2 (x64), quando tenta carregar os sistema feito em mvc3 (c#) dotnet4, ocorre o erro:

System.Web.resources.dll não encontrado.

Não conseguimos encontrar o problema, já atualizamos os windows 2008r2 com todas as atualizações, foi instalado o visual c redist 2015, reiniciado o servidor, e nada.
Alguém já passou por um problema parecido?
Comment: Experimentou copiar ela manualmente? Tentou instalar com Nuget? https://www.nuget.org/packages/Microsoft.AspNet.Mvc/3.0.20105.1
Comment: Não tentei, mas vou testar.
Comment: Sabes me dizer por que isso aconteceu? Antes de converter os projetos para vs2015 funcionava, inclusive no windows 2008r2, parou de funcionar depois que foram convertidos.
Comment: Não sei, mas é provável que houve algum problema de compatibilidade de versão que você não percebeu. Resolveu?
Comment: Infelizmente não funcionou.
Comment: É estranho já que isto instala esta DLL. O problema pode ser outro e este problema é apenas colateral. Mas é difícil a gente ajudar sem ver toda a situação.
Answer: @Hains,
Para você descobrir qual a versão e onde ele está procurando esta DLL, sugiro que ative o Fusion log, as instruções sobre ativação estão na página de erro, mesmo assim, segue como fazer:

Crie um diretório em C: com o nome Logs
Crie uma chave de registro em HKLM\Software\Microsoft\Fusion\ com o nome LogPath e valor C:\Logs, outra ForceLogcom o valor 1 e mais uma LogFailures com o valor 1

Feito isso, reinicie o IIS.
A partir de agora serão exibidos os caminhos e as versões dos arquivos que falharam em serem carregadas.

Para ajudar na depuração de erros, veja este artigo publicado na MSDN com mais detalhes sobre como utilizar/interpretar os logs do Fusion.
Link

System.Web.resources.dll não encontrado


Is it appropriate/acceptable to do planned comparisons for data that will be submitted to a scientific journal?

Question: I am currently analyzing data for an age-related neuroscience study with a 2x2 factorial design (treatment (2 levels) x age (2 levels)) yielding 4 total groups: Young untreated, Young treated, Aged untreated, Aged treated.  The hypothesis is that the two aged groups would be different, while young animals show no difference. My first thought is to perform a factorial ANOVA (test for main effect of genotype and age, as well as test for an interaction effect). However, if there is no interaction effect of the two variables, I'd still like to test that original hypothesis (i.e., compare just the aged groups and just the young groups).  I've recently learned that some researchers employ planned comparisons (I've also seen it called planned contrasts) to examine differences between specific groups that were selected a priori instead of doing an ANOVA and running post-hoc tests that examine all possible comparisons.
This makes sense to me, but I've heard that scientific journals "don't like" when researchers use planned comparison, so getting published with planned comparisons would be difficult if not near impossible. On the other hand, through very cursory internet searching, I found 2 papers that seem to advocate for the use of planned comparisons since every study should have a hypothesis that predicts specific effects anyway (The papers can be found here and here).
Given all this, my question is as follows: Is it generally acceptable to do planned comparisons if there's a rational justification for it, or is this approach frowned upon by journals and peer reviewers?
Comment: This was posted on Academia.SE earlier, and I said that it should be here, as it ends up being a statistical question. // My take on this is that prespecified hypotheses are preferable, as post-hoc hypotheses because "oh, what's going on there?" means that there are issues with adjusting for multiple comparisons. (That's true for prespecified hypotheses, too, but you go into the work knowing how many hypotheses there are.)
Answer:
I've heard that scientific journals "don't like" when researchers use planned comparison, so getting published with planned comparisons would be difficult if not near impossible.

I haven't heard that myself. There is much to be said statistically for starting with clear, pre-planned hypotheses to test rather than just blindly jumping into ANOVA with all paired comparisons evaluated post-hoc. I suspect that journals who "don't like" pre-planned comparisons have pretty poor statistical review. (Or perhaps they fear that the "pre-planned" hypotheses were really developed post-study.)
With this 2 x 2 design, however, there won't be much of a difference. Under the principle of marginality, if there is an interaction there aren't well-defined unique "main effects" for either age or treatment. If you find a significant interaction, then the planned within-age-group comparisons of the treatment effect make sense. If, however, the interaction term is not significant, then there is no evidence that the effect of treatment differs with age so you should just stop there.
Comment: Thank you for this answer and the link. I am still a bit confused, however, because I'm interpreting your second paragraph to suggest that pre-planned comparisons in this instance are essentially no different than post-hoc tests (i.e., without a main effect of interaction you can't do the pre-planned within-age comparison). Is that correct? Also, what if one factor shows a main effect while there is no main effect of of the other nor interaction? Would a pre-planned comparison be suitable to parse that out in the context of the original hypothesis?
Comment: @user120818 if the overall ANOVA isn't significant you should stop, as there is no evidence that anything you've examined is associated with outcome. If there is a significant ANOVA but not a significant interaction, you could report the marginal means for each of `age` and `treatment` as their "effects"; the R [`emmeans` package](https://cran.r-project.org/package=emmeans) makes that easy. If there is a significant interaction too, then any pre-planned comparisons would be OK. Beyond that, "won't be much of a difference" meant there are only 6 pairwise differences in a 2 X 2 design, anyway.
Comment: Thank you for the clarification. Just to make sure I have a handle on pre-planned comparisons vs. post-hoc analyses, I have a couple more questions. Essentially, what separates post-hoc from pre-planned comparisons if both require a significant interaction via ANOVA to assess the groups of interest? Is it simply that pre-planned comparisons don't necessarily need to correct for multiple comparisons?  I'm mainly getting tripped up on what the purpose of a planned comparison is if the scenarios in which you would run them are the same as a post-hoc. Is it to increase the statistical power?
Comment: I think I may have found the answer to in another question posted to this forum:  https://stats.stackexchange.com/questions/342638/why-do-planned-comparisons-and-post-hoc-tests-differ, but I'm still interested to get your thoughts, @EdM
Comment: @user120818 yes, that's a very helpful link, glad you found it. The main issue is how many multiple comparisons you need to correct for. In a 2 X 2 design, there are 6 potential pairwise comparisons. If you pre-plan fewer comparisons/contrasts, there is _less stringent_ multiple-comparison correction needed and thus potentially higher power.


Conditions on non-divisibilty of a product

Question: Let $m,n\in \mathbb{N}$. What should be the conditions on $m,n$ such that $d\nmid mn$ for all $m+n\leq d< mn$. Is there an easy way to describe such natural numbers?
Note: If $m,n$ are distinct prime numbers, then they satisfy the above conditions. Similarly one can find some other special cases easily, but it seems one needs to consider a lot of cases.
Note: Requiring $(m,n)=1$ is not enough, for example $105=21\times 5$ but 35 divides 105.
Answer: Without loss of generality, $n \leqslant m$. Let $p$ be the smallest prime divisor of $mn$. Then the condition is precisely
$$\frac{mn}{p} < m+n \iff \frac1p < \frac1n + \frac1m.$$
Since $$\frac1n + \frac1m \leqslant \frac2n,$$
we must have $n < 2p$, and thus either $n = p$ - in which case the condition holds - or $n$ is a prime between $p$ and $2p$. If $p$ is odd, we have
$$\frac{2}{p(p+2)} = \frac1p - \frac{1}{p+2} \leqslant \frac1p - \frac1n \overset{!}{<} \frac1m = \frac{1}{kp},$$
which means $k < \frac{p+2}{2} < p$, and that contradicts the minimality of $p$. So the only further possibility is $p = 2$ and $n = 3$, which leads to m = 4.
So the condition is satisfied if and only if $\{m,n\} = \{3,4\}$, or one of $\{m,n\}$ is the smallest prime divisor of $mn$.


The exit status code '1' says something went wrong:\nstderr: \"The system cannot find the path specified. - Laravel Snappy

Question: I am trying to export data to pdf using laravel-snappy. I have
Installed wkhtmltopdf-windows
composer require wemersonjanuario/wkhtmltopdf-windows 0.12.2.3

Install laravel-snappy
composer require barryvdh/laravel-snappy

Added service provider in config/app.php
Barryvdh\Snappy\ServiceProvider::class,

Added aliases
'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

Published Config file
php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"

Updated config/snappy.php
'pdf' => [
        'enabled' => true,
        'binary'  => base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
        'timeout' => false,
        'options' => [],
        'env'     => [],
        ],

Got Error:
    "message": "The exit status code '1' says something went wrong:\nstderr: \"The system cannot find the path specified.\r\n\"\nstdout: \"\"\ncommand: /usr/local/bin/wkhtmltopdf --lowquality \"C:\\WINDOWS\\TEMP\\knp_snappy5dcd3b81559d67.45448784.html\" \"C:\\WINDOWS\\TEMP\\knp_snappy5dcd3b8155c8a2.62799911.pdf\".",

In this error, I noticed it is looking the .exe file at /usr/local/bin/wkhtmltopdf. However, I have not mentioned this path in config/snappy.php.
So, I tried by updating the path directly into the vendor/barryvdh/laravel-snappy/config/snappy.php
Surprisingly, this works. So, I could not figure out why this laravel-snappy is not reading the path from config/snappy.php and instead reading from the vendor file.
Is there something, I am missing?
Comment: I did the same , but It just load and then show timeout error..
Answer: I had faced similar issues, instead it was related to another package. Basically, this type of issues occurs because of some cache issue.
SO, you can try the following commands.
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan config:clear
php artisan clear-compiled
composer dump-autoload
php artisan vendor:publish

especially, cache:clear and config:clear should fix your issue.
Comment: not worked this
Answer: Try after installing WKHTMLTOPDF from here:
https://wkhtmltopdf.org/downloads.html
Comment: Why? How would this solve the issue? What are the exact steps to perform the installation?
Comment: @mozway depending on OS version that you are using, you can install it. When installed correctly, the programming/installer adds command "wkhtmltopdf" to the command line or shell. If "wkhtmltopdf --version" command runs correctly, that means it is installed correctly. So please follow the steps on their website to do the installation depending on your OS.


Firefox not displaying WebVTT captions on video

Question: I have a basic example of using the track element to load captions. In Firefox, the captions render sometimes, but not other times. Things that I have checked:

CSS positioning of video element (still see the issue with no positioning change)
Opening a private window (sometimes makes them show)
Disabling cache
CORS headers of mp4/vtt server (they are set to Access-Control-Allow-Origin: *) and the video tag has crossorigin="anonymous"
Changing autoplay and muted attributes

Reproduced intermittently in Firefox versions 97.0 and 98.0b4. I haven't noticed this issue in other browsers.
Edit: I added some CSS to this snippet that makes the issue repro for me now. So it's pointing to CSS, but weirdly, once I reproduce it, the captions continue to remain hidden even when I remove all styles.

.modal {
  display: flex;
  flex-direction: column;
}

.video-wrap {
  flex-grow: 1;
  height: 480px;
  position: relative;
}

video {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: black;
}

::cue {
  color: pink;
}

Video w/ VTT

    <video controls muted crossorigin="anonymous">
      <source
        src="https://cuttle-learning.netlify.app/onboarding-sketch/videos/onboarding2.mp4?cachebreak=001"
        type="video/mp4"
      />
      <track
        label="English"
        kind="captions"
        srclang="en"
        src="https://cuttle-learning.netlify.app/onboarding-sketch/videos/onboarding2.vtt?cachebreak=001"
        default=""
      />
    </video>

Demo also here: https://h05uh.csb.app/
Comment: For me, this snippet _is_ showing the captions in Firefox (97)
Comment: Yeah, me too. This is partially to list the _potential_ fixes I have found in various SO posts and bugzilla.
Comment: I added some CSS that makes the issue repro in the snippet.
Answer: Sounds like it's this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1733232

That's currently the most minimal example I have which consistently
fails. Some (basic) examples fail after a couple of reloads. I assume
that's because of caching and layout complexity.


Conservative Field

Question: I need help with the following question . I have this vector field:
$$F(x,y):=y\frac{x^2\cos(xy)+y^2\cos(xy)-1}{x^2+y^2}\vec{i}+x\frac{x^2\cos(xy)+y^2\cos(xy)+1}{x^2+y^2}\vec{j}$$
and 2 domains:
$$D_1:=B_1(0) , D_2:=\{(x,y):(x-5)^{^2/_3}+(y-7)^{^2/_3}<1\}$$
I need to determine over which one the given F is a conservative field (of course prove it) and find its' potential function , and over which it is not conservative , in which case I need to supply a path within the domain that isn't equal to 0 .
Now, intuitively i figure that the first domain must be the non-conservative one because F won't be continuous at point (0,0) , other than that I have a hard time figuring out how to approach this question . I'd be grateful for some help !
Comment: This is the second time I've seen this exact same question: http://math.stackexchange.com/questions/492017/q-determine-of-vector-field-is-conservative/

Is this homework?
Answer: Recall the definition of a conservative vector field.  A vector field $F(x, y) = \langle P(x, y), Q(x, y) \rangle$ is conservative on some domain $D$ if $P_y = Q_x$, and the first order partial derivatives of $P$ and $Q$ are continuous on $D$.
To find the potential function for a conservative vector field $F$, you are looking for a scalar function $f$ such that $\nabla f = F$.  So in your case you would set
$$ f_x = y\frac{x^2 \cos(xy) + y^2 \cos(xy) - 1}{x^2 + y^2} = y \cos(xy) - \frac{y}{x^2 + y^2}, $$ and
$$ f_y = x\frac{x^2 \cos(xy) + y^2 \cos(xy) + 1}{x^2 + y^2} = x \cos(xy) + \frac{x}{x^2 + y^2}. $$
Can you solve for $f$ from here?
Comment: Should that not be $P_y=Q_x$?
Comment: @Daron Thank you.  Edited to fix.
Comment: so showing that $$F\in C^1$$ and $$P_y=Q_x$$ over a given domain should be enough to prove it's conservative?

Conservative Field


Big IP orphaned connections

Question: Let me state up-front that I know just enough about networking at this level to be dangerous, so if I say something stupid, please be kind.
I am using a Big IP load balancer in front of 3 Apache servers.  The 3 Apache servers are all on the same physical machine (running Linux), bound to port 80 on 3 different virtual IP addresses, but I don't think that's playing a part in this problem.  We have the LB configured so that the same client gets the same WEB server each time, controlled via a cookie provided by the LB.
If I go through the LB to access our application, I will occasionally (5-15% of the time) get a page where the browser just spins, never returning.  If I hit each of the WEB servers directly, I never get that.  Using WireShark I looked at what was happening on my PC, the LB and the WEB server I was hitting through the LB, and I saw the following:
1) Most times, the port that the PC used to hit the LB was the port the LB used to hit the WEB server, which I thought was "normal"; all 3 times I've replicate my issue, the ports were different (e.g. 1234 between PC/LB and 2345 between LB/WEB).  But not all of the times that they were different did I see an issue.  This may be a red herring....
2) The PC <-> LB communications are with packets that are 1260 bytes long; the LB -> WEB packets are 1260 bytes, but the LB <- WEB packets are some multiple of 1260.  When the WEB sends 2520 bytes to the LB, the LB receives it in 2x1260 byte packets, and only sends one ACK.  It then sends back to the PC 2x1260 byte packets, and receives one ACK from the PC.  I don't understand why the 2520 is broken into 2x1260, nor do I understand why the PC knows to only send one ACK.  This may also be a red herring....
3) At some point the WEB server sends data to the LB for which it receives no ACK, then resends the packet that started this data sequence.  I don't know why the re-transmission happens, though, as only 0.6 seconds have passed, so it can't be that it's timed out (well, I suppose it can be, but it does seem unlikely). Further, the original WEB -> LB packet was 5040 bytes (4x1260), but the re-transmission is only 1260. The LB received all 4 packets from the original 5040 sending, but never sent an ACK for whatever reason. I see other times when the LB has been able to handle the 5040 bytes being sent to it, that it acknowledged just fine, so it doesn't seem as if the length of the sent packet is an issue.  None of these packets were sent from the LB back to the PC, though.
4) Only the first 1260 chunk of data is resent from the WEB to the LB, though.  There is a small delay (0.4 seconds) and then there is a second re-transmission of data, starting with the first 1260 chunk, bu this time all 4x1260 packets are resent.  The ACK sent back by the LB, however, is for all 5 of the resent packets, even though one of them was clearly resent twice (I base this on the relative seq number shown by WireShark; the ACK sent back is equal to the seq number of the first resent packet + 5x1260, even though the seq number of the second resent packet is the same as the first resent packet). This seems really bad.
5) Worst of all, I think, is that the ports get all messed up.  The original conversation ports are as follows:
PC <-> LB == 2723
LB <-> WEB == 2722

Co-mingled among that conversation is one looking like this:
PC <-> LB == 2722
LB <-> WEB == 2723

It was enough to make me cross-eyed, but I did verify that the conversations were happening on the ports I thought they were, based on content of the packets (ugh).  The second conversation completes successfully (in fact, there are two conversation on this set of ports, both of which complete successfully).  After the first (aborted?) re-transmission packet is sent, but before the second set of 4x1260 re-transmissions are sent, there is a conversation:
PC <-> LB == 2722
LB <-> WEB == 2722

So, the original LB <-> WEB conversation on port 2722 is interrupted. I didn't think this was allowed under the protocol.  There is no FIN or SYN sent in either direction on this port.  The sequence number sent from LB -> WEB for this newly initiated conversation is what I expect it to be.  The ACK from the WEB to the LB has the right sequence number, but the ACK is off (by exactly 1260).
This second conversation never seems to take place, as after the 4x1260 are re-transmitted, the WEB sends another, new, 1260 chunk of data, and all of it is the response from the original request (determined by examining the data in the packets).  The LB then sends an ACK back, and it is what I would expect from the original conversation (last ACK + 4x1260 + 1260).
So, I have clues as to what's happening, but no idea why it would happen, and certainly no clues as to how to fix it.  Where do I go from here?
EDIT: I just remembered something; during the middle of the 4x1260 resend from the WEB to the LB, the LB sends back an ACK that is exactly 100 bytes more than I would expect.  After the first 1260 packet of new data is sent, though, the LB sends back an ACK that is exactly what it should be (i.e. it corrected itself).  I have no clue how that could happen or what that means, or even if it's meaningful.
Comment: In the end we switched from the hardware LB to Pound (http://www.apsis.ch/pound/) and we've never had a problem since.  Pound itself is really good for our use; my only complaint is that you have to restart the service to reload the config file.
Comment: F5 support can help you with this and it should be covered by your support contract.
Answer: One thing that sticks out at me is that your web servers are on the same machine using different IP addresses. You're not really gaining anything with load balancing if you go and put all the servers on one box.
Some of what you describe with the packets seems normal; have you used the 'Expert Info' and 'Follow TCP Stream' features of Wireshark? Those will show higher-level views of the TCP connections. Also keep in mind that Wireshark might not be capturing all packets (especially if you're on gigabit ethernet).
As for the problem, it's possible you're seeing a bug in the LB, exposed by the fact that all your web services are on the same box, which means that your three IP addresses all have the same MAC address. If the LB tracks connections using the MAC address, it could be confusing your three server IP addresses and directing packets to the wrong place.
Comment: Also, those packet sizes do seem a bit small. Normally, I expect packet sizes in the 1400's. Double-check the MTU settings on all your boxes (normal MTU for ethernet is 1500)
Comment: It's a test environment, that's why all 3 WEB servers are on the same box.  I'll look into the Follow TCP Stream option -- thanks!
Answer:
The tcp port will change as necessary on the client, and on the server side of the BIG-IP, which is now the client to the web server. This is expected behavior as the BIG-IP handles a completely separate TCP connection to the client and to the server.
Because the proxy handles separate connections between the client and the server, the normal TCP behaviors will act differently on the clientside and serverside of the connection. What TCP profile you apply and to which side of the proxy (you can apply different profiles to client and server side of the connection or the same to both, up to you depending on your use cases and network environments) will alter what data is actually on the wire at what time and how many and how frequently acknowledgements are sent.
retransmits are common, and how the tcp stack handles network congestion depends on the stack in place, both on client and server side of the connection. Again, you have two clients and two servers for any client->BIG-IP->server scenario.
would need to see the entire capture to diagnose the behavior you saw.
don't think the tcp port is a concern here.

Without details, my guess is that you had stock tcp profile enabled instead of a custom profile and it behaved badly with your application. I highly recommend utilizing custom profiles and engaging someone with knowledge of how TCP flow and congestion control algorithms work, and what settings in the TCP profile act poorly with certain applications. We wrote a 10-part series on the BIG-IP TCP profile several years ago (could use a refresh with all the changes since but it's still a good source of information) that I think will help: https://devcentral.f5.com/articles/investigating-the-ltm-tcp-profile-nagles-algorithm

Big IP orphaned connections


Converge / Diverge $\sum_{n=1}^{\infty}\big( \frac{1}{\sqrt[n]{n!}}\big)^2$

Question: $$\sum_{n=1}^{\infty}\big( \frac{1}{\sqrt[n]{n!}}\big)^2$$
$$2^n\leq n!$$
As $2\cdot 2 \cdots2\leq 1 \cdot 2 \cdots n!$
Therefore:
$$2\leq \sqrt[n]{n!}$$
$$2^2\leq \sqrt[n]{n!}^2$$
So:
$$\frac{1}{\sqrt[n]{n!}^2}\leq \frac{1}{4}$$
$$\sum_{n=1}^{\infty}\frac{1}{\sqrt[n]{n!}^2}\leq \sum_{n=1}^{\infty}\frac{1}{4}=\frac{1}{4}\cdot \frac{1}{1-\frac{1}{4}}=\frac{1}{3}$$
Is it correct?
Comment: Strictly speaking, $2^n<n!$ only for $n\ge4$
Comment: I think you should try to use the ratio test to show that the series converges.
Comment: @HagenvonEitzen yes sorry for no writing it
Answer: Since
$$
e^n  = 1 + n +  \cdots  + \frac{{n^n }}{{n!}} +  \cdots  > \frac{{n^n }}{{n!}},
$$
it holds that
$$
\sum\limits_{n = 1}^\infty  {\left( {\frac{1}{{\sqrt[n]{{n!}}}}} \right)^2 }  < \sum\limits_{n = 1}^\infty  {\frac{{e^2 }}{{n^2 }}}  = \frac{{(\pi e)^2 }}{6}.
$$
Answer: No, it is not correct, since $\sum_{n=1}^\infty\frac14=\infty$.
Comment: Correct it was correct for $\frac{1}{4^n}$
Answer: Since $n! >  (n/e)^n$,
$(n!)^{1/n} >n/e$
so
$\dfrac1{(n!)^{1/n}} < e/n$
so, for any $c > 0$ we have
$\dfrac1{((n!)^{1/n})^{1+c}}
 < (e/n)^{1+c}
= (e^{1+c}/n^{1+c})
$
and the sum of this converges.
This question is the case
$c=1$.


when i type letter like m i get number like 0 value in laptop how to fix

Question: My dads laptop has a problem. The keys on the keyboard that have a second symol on the key example the letter m has a 0. The letter L has a 3 and so on.
It seems that some how it is set as default to write the secondary symbol. Any body know how to set as it was before.
Comment: ask a question, self answering the same minute? I do not see many ppl having the same problem - and if - it is a hardware problem, not programming related so its OT for SO.
Comment: i think this forms is for helping people i counter problem then i found solution for help others i share it here, this is not hadware problem
Answer: i see there are many people having this trouble
please note that many laptops not have num keys so the letter keys are worked for both alphabet as well as numeric key many people turn on these numeric keys without knowing.
So you just need to turn off numlock in many laptops numlock key not work lonely it will work with combination like fn+numlock i will give most common below:
<code>Fn + F11 (Acer, Toshiba, Samsung)
Shift + Num Lock
Fn + Num Lock (Sony, Gateway)
Fn + F11 + Scroll lock
Fn + F8 (HP)
Ctrl + F11
Fn + Shift + Num Lock
Fn + F4 (Dell)
Fn + Nmlk (Lenovo, ASUS)
</code>
hope it will help you


Irreducible polynomials in $\mathbb F_q[T]$

Question: Let $q$ be a power of a prime $p$. Is there an infinite set $S$ of $\mathbb N$ such that for every $l\in S$, the polynomial $T^{q^l}-T-1$ is irreducible in $\mathbb F_q[T]$.
It looks like Artin-Schreier theory can not handle that.
Answer: No, the set of such natural numbers $\ell$ is always finite. In fact, it always has at most two elements, and that only in the case $q=\ell=2$. Furthermore, unless $q$ is a prime, the set $S$ is empty.

The key to arriving at such conclusions is the simple Galois theory of finite fields, much like when studying Artin-Schreier polynomials. Let $q=p^n$, $p$ a prime number. Let us fix an algebraic closure $k$ of $\Bbb{F}_q$. Let $\alpha\in k$ be a zero of the polynomial
$$
f_\ell(T):=T^{q^\ell}-T-1.
$$
Let $F$ be the Frobenius automorphism $F(z)=z^q$ for all $z\in k$ that topologically generates the Galois group of $k/\Bbb{F}_q$. Galois theory tells us that the zeros of the minimal polynomial $m(T)$ of $\alpha$ over $\Bbb{F}_q$ are the iterated images $\alpha, F(\alpha), F(F(\alpha)),\ldots$. If $F^n$ stands for the $n$th iterate, we have
$$F^{\ell}(\alpha)=\alpha^{q^\ell}=\alpha^{q^\ell}-f_{\ell}(\alpha)=\alpha+1.$$
By induction on $j$ this implies $F^{j\ell}(\alpha)=\alpha+j\cdot1$ for all natural numbers $j$. Because we are in characteristic $p$, it follows that
$$
F^{p\ell}(\alpha)=\alpha.
$$
We have just shown that the number of Galois conjugates of $\alpha$ is a factor of $p\ell$ (and also that it is not a factor of $\ell$). Therefore
$$\deg m(T)\le p\ell.$$
It is easy to see that $p\ell$ is strictly less that $\deg f_\ell(T)=q^\ell$ except when

either $q=p,\ell=1$, or
$q=p=\ell=2$.

In all the other cases $m(T)$ is a proper factor of $f_{\ell}(T)$, and hence the latter cannot be irreducible.

This reasoning (albeit in the insignificantly simpler context of the prime field) has appeared earlier here. The techniques I described here will say more about the factors of $f_\ell(T)$ — nominally only over the prime field and over the extension field $\Bbb{F}_{q^\ell}$, but it should not be difficult to describe the factors over the intermediate field $\Bbb{F}_q$ either.


java.io.EOFException: Premature EOF: no length prefix available in Spark on Hadoop

Question: I'm getting this weird exception. I'm using Spark 1.6.0 on Hadoop 2.6.4 and submitting Spark job on YARN cluster.
16/07/23 20:05:21 WARN hdfs.DFSClient: DFSOutputStream ResponseProcessor exception  for block BP-532134798-184.108.40.206-1469321545728:blk_1073741865_1041
java.io.EOFException: Premature EOF: no length prefix available
    at org.apache.hadoop.hdfs.protocolPB.PBHelper.vintPrefixed(PBHelper.java:2203)
    at org.apache.hadoop.hdfs.protocol.datatransfer.PipelineAck.readFields(PipelineAck.java:176)
    at org.apache.hadoop.hdfs.DFSOutputStream$DataStreamer$ResponseProcessor.run(DFSOutputStream.java:867)
16/07/23 20:49:09 ERROR server.TransportRequestHandler: Error sending result RpcResponse{requestId=4719626006875125240, body=NioManagedBuffer{buf=java.nio.HeapByteBuffer[pos=0 lim=81 cap=81]}} to ms0440.utah.cloudlab.us/184.108.40.206:58944; closing connection
java.nio.channels.ClosedChannelException

I was getting this error when running on Hadoop 2.6.0 and thought the exception might be kind of a bug like this but after even changing this to Hadoop 2.6.4 I'm getting the same error. There is not any memory problem, my cluster is good with HDFS and memory. I went through this and this but no luck.
Note: 1. I'm using Apache Hadoop and Spark not any CDH/HDP. 2. I'm able to copy data in HDFS and even able to execute another job on this cluster.
Comment: i get similar issues. Did you find a solution ?  @ChikuMiku
Comment: @harpribot not yet.
Comment: I think Hadoop version was the issue. No issues in 2.7.2, which I updated later; Also, check your firewall rules.
Answer: Check file permissions of dfs directory:
find /path/to/dfs -group root

In general, the user permission group is hdfs.
Since I started HDFS service with root user, some dfs block file with root permissions was generated.
I solved the problem after change to right permissions:
sudo chown -R hdfs:hdfs /path/to/dfs


JavaScript -TypeError: Cannot read property 'children' of undefined

Question: I am trying to create a tree and calculate its height.
The map array is initialised properly in the for loop but console.log(map+"  this is map"); shows
 [object Object],[object Object],[object Object],[object Object],[object Object]  this is map. I am having problems accesing the children property in the second for loop at
map[list[i]]["children"].push(node);

The error is TypeError: Cannot read property 'children' of undefined
How to resolve this ??
The input is -
5
4 -1 4 1 1

The first line contains the number of nodes . The second line contains  integer numbers
from −1 to  − 1 — parents of nodes. If the -th one of them (0 ≤  ≤  − 1) is −1, node  is the root,
otherwise it's 0-based index of the parent of -th node. It is guaranteed that there is exactly one root.
It is guaranteed that the input represents a tree.
Code -
var readline = require('readline');

var input = [];
enter image description here
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.prompt();

rl.on('line', function (cmd) {
    input.push(cmd);
});

rl.on('close', function (cmd) {
   input=input[1].split(" ");
    console.log(list_to_tree(input));
    let tree1=list_to_tree(input);
    console.log("this   "+height(tree1));
    process.exit(0);
});

function list_to_tree(list) {
    var map = [], node, roots = [], i;
    for(i=0;i<list.length;i++){
        map.push({[i] :list[i],
            children:[]
        });
        console.log(map);

    }
    console.log(map+"  this is map");
    for(i=0;i<list.length;i++){
        node=map[i];
        if(list[i]!==-1){
            console.log(map[list[i]]);
            map[list[i]]["children"].push(node);

        }
        else {
            roots.push(node);}
    }
    return roots;
}

function height(tree){
    if(tree===null){return 0;}

   let h=0;
    for(let x in tree){
        for (let y in tree[x]["children"]){
            h=Math.max(h,height(y));

        }
         return h+1;
    }

}

Comment: @PrashantGupta i have added the input format and the ss of output is https://i.stack.imgur.com/gRNbm.jpg and which json are u exactly asking for ??
Answer: declare 'map' as array of object. Then use like this.
map.push({node})

I experienced the same issue and I did like this. list declared as array of object.
Comment: that would work but how would I access the children property to add children to the node.  map.push({node}) would simply push a node into map but I want to add that node as a child node to another node. Am i missing something in ur hint ??


Is the open ball path-connected in metric space

Question: Suppose in metric space $X$, B(x) is an open ball around $x$, is it path-connected or connected?

In normed space, it is obviously true, but I don't know if it is true in general?
Answer: On any set $X$, the discrete metric
$$
d(x,y) = \begin{cases}
0 &\text{if $x = y$,}\\
1 &\text{if $x\ne y$}\\
\end{cases}$$
defines the discrete topology, and if $X$ is not a singleton, then for any $x\in X$ the open ball $B(x,2) = X$ is neither connected nor path-connected.
Answer: No. $\Bbb Q$ is a metric space (with standard metric).
Regarding your "obviously true": $\Bbb Q$ is also a normed vector space over $\Bbb Q$.
Comment: I think his notion of normed space is over the reals, in which case the open ball is a star-shaped set, which explains the "obvious" part.


Primitive roots modulo odd prime p

Question: For an odd prime $p$, show that:
(a) Any primitive root of $p^2$ is also a primitive root of $p$
(b) Any primitive root of $p^n$ is also a primitive root of $p$

For part (a):
$r$ is a primitive root $\pmod {p^2}$
Suppose $r$ is not a primitive root $\pmod p$. Then there is
some $n$ with $n|p−1$ by lagranges theorem. But then, $r^{np} \equiv 1 \pmod {p^2}$. Contradiction.
Is this okay? I Didn't use the p being odd assumption here!
I have the general idea for (b):
Let $r$ be a primitive root of $p^n$ then: for $(a,p)=1$:
$r^k\equiv a \pmod{p^n}$ $\Rightarrow r^k\equiv a \pmod{p}$
But how do we show the existence of $r$ & complete the proof?
Comment: "I can show the opposite directions of both (a) & (b)".  But in the opposite direction both claims are **false**.  You should consider providing your proofs of the converses, we might be able to identify a key misconception you're harboring.
Comment: Only two such [odd "non-generous primes" are know](https://oeis.org/A055578), so granted, it doesn't seem to happen often, but that still shows the claim is false even under that more stringent interpretation.
Comment: The argument for (a) is incomplete. There is a bit of magic happening in "But then, $r^{np}\equiv 1\pmod{p^2}$." In addition, the prior statement is incorrect as written, as you don't exclude $n=p-1$. For (b) you *don't need to prove there is a primitive root!* The problem asks you to show that **if** you already have a primitive root modulo $p^n$., then it is a primitivie root modulo $p$. Why do you think you need to show one exists?
Comment: Welcome to MSE. Remember to include your work on the problem, otherwise it looks like you are trying to get others to do your homework.
Comment: The "opposite direction" of (a) would state that a primitive root modulo $p$ is also a primitive root modulo $p^2$. But this is false: $8$ is a primitive root modulo $3$, but not modulo $9$.  Even if you require the root to be between $1$ and $p$, it still is not true:  [for example](https://primes.utm.edu/curios/page.php/40487.html) the smallest primitive root modulo $p=40487$ is not a primitive root modulo $40487^2$
Comment: @ArturoMagidin Yes. In the opposite direction I found out where I was doing wrong. There would be two cases & only at one of the case such would happen.
Comment: @jjagmath I have added my work with an edit.
Comment: @ArturoMagidin I get it now. I didn't understand the question properly.
Answer: I'll do (a), and leave (b) to you.
If $r=1+ap$, then $r^p=(1+ap)^p$. Expand to verify that every term except for the first is divisible by $p^2$.
Thus, if $x$ has multiplicative order $k$ modulo $p$, so that $x^k = 1+ap$ for some $a$, then $x$ has order dividing $kp$ modulo $p^2$; and the order modulo $p^2$ must be a multiple of $k$. Thus, the order of $x$ modulo $p^2$ will be either $k$ or $kp$, since $p$ is a prime.
In particular, if the order of $x$ modulo $p^2$ is $p(p-1)$, then the order of $x$ modulo $p$ must be $p-1$.

Primitive roots modulo odd prime p


The spectrum of $(\alpha I + T)$, where $T$ is a compact operator, accumulates at $\alpha$?

Question: I am aware that the spectrum of a compact operator $T$ accumulates at $0$. Now say we have the operator $(\alpha I+ T)$ where $\alpha$ is some real number. I believe I read somewhere that the spectrum of this operator accumulates at $\alpha$ and this is desirable situation in numerical analysis as matrices will have better conditioning.
So how can it be shown that the spectrum of the operator $(\alpha I + T)$ accumulates at \alpha?
Comment: The spectral mapping theorem gives $\sigma(\alpha I+T)=\alpha+\sigma(T)$.
Comment: I think it is better to say that this follows directly from the definition of the spectrum.
Answer: Given $\lambda\in\mathbb C$,
$$
(\alpha I+ T) -\lambda I=T-(\lambda-\alpha)I.
$$
The above equality implies that $$\lambda\in\sigma(\alpha I+T)\iff \lambda-\alpha\in\sigma(T).$$
So $$ \sigma(\alpha I+T)=\alpha+\sigma(T).$$
In particular, when $T$ is compact, then spectrum of $\alpha I+T$ is either finite or it consists of a sequence that converges to $\alpha$.


service file for golang app

Question: So I wrote a golang app which I want initialized by systemd whenever my server gets a reboot.
Here's the service file:-
[Unit]
Description=golang wiki initialization

[Service]
Type=forking
PIDFile=/tmp/gowiki.pid-3030
User=root
Group=root
WorkingDirectory=/var/www
ExecStart=/bin/bash -c 'daemonize -o stdout.log -e stderr.log /var/www/wiki'

[Install]
WantedBy=multi-user.target

It appears to work well whenever I reboot the server but I am still running into slightly irritating problem when I am manually starting or restarting gowiki like this in terminal:-
systemctl start gowiki

or
systemctl restart gowiki

This does get my gowiki process running; however, after I execute my systemctl start gowiki command, I am frozen in my terminal and the command does not seem to exit until I manually force a Ctrl-C.
What am I doing wrong to be causing this problem?
Answer: This worked.
[Unit]
Description=golang wiki initialization

[Service]
PIDFile=/tmp/gowiki.pid-4040
User=root
Group=root
WorkingDirectory=/var/www
ExecStart=/bin/bash -c '/var/www/wiki'

[Install]
WantedBy=multi-user.target

Because the Type=forking services expect the parent service to exit before the service has actually started. If the parent never exits, then systemctl start will not give you back a prompt because it doesn't think that it's done executing.
Answer: If you don't mind adjusting your code a little for systemd the cleanest solution I've found thus far is using the SDNotify-signal.
import "github.com/coreos/go-systemd/daemon"

func main() {
    // Important init stuff here
    ....

    // Notify systemd that we're ready
    sent, e := daemon.SdNotify(false, "READY=1")
    if e != nil {
        log.Fatal(e)
    }
    if !sent {
        log.Printf("SystemD notify NOT sent\n")
    }

    // And do something blocking like listening for HTTP(s)

It has no CGO-deps
The code also works on non-systemd systems (in this case it emits a warning notify not sent)
If you want a working example: https://github.com/mpdroog/dnsleak

Your corresponding systemd unit-file:
[Unit]
Description=golang wiki initialization
After=network.target
Requires=network.target

[Service]
Type=notify

Restart=always
RestartSec=30
TimeoutStartSec=0

WorkingDirectory=/var/www
ExecStart=/var/www/wiki
User=www-data
Group=www-data
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

service file for golang app


tento executar o comando javac mais não executa

Question: eu ja tentei de toda , forma concertar , ja fui no google , youtube , quando vou tentar executar o cmd "javac" ele nao executa fala o seguinte erro " javac " nao é reconhecido como um comando interno ou externo um programa operável ou um a arquivo em lotes. me ajuda por favor
Comment: P.s.: da próxima vez que escrever `mais` quando queres dizer "mas" eu não ajudo ;)
Comment: Veja se a resposta dessa pergunta ajuda em algo: http://pt.stackoverflow.com/q/31465/6454
Comment: Só para deixar claro, eu e o @stderr votamos como duplicata de "http://pt.stackoverflow.com/q/31465/6454" - Ocorre que o sistema do SO dá como razão de fechamento apenas o voto da maioria (os demais três votantes).
Comment: A pergutna vai ser eventualmente excluída, pois não encaixa no formato do nosso site (veja a seção de ajuda). Porém, vou deixar uma dica aqui: verifique se você tem o Java instalado na máquina e configurado no seu PATH. O que o prompt está lhe dizendo é que esse executável que você está tentando usar NON ECZISTE na tua máquina.
Comment: @VictorStafusa eu votei antes da duplicata aparecer, senão teria votado duplicata também, infelizmente o sistema também não me permite troca de voto.
Answer: A sua JDK não foi instalada corretamente. Você pode baixar o instalador aqui.
Comment: Não pode ser só a variável de ambiente faltando? Isto é, se o AP usa Windows.


Creating a responsive long form submit

Question: I have a rather long procedure on form submit (need to send several email to different addresses); when the use submits the form, the application seems to hang while it is doing a lot of work. Is there a Drupal way to show a "operation in progress" (better showing an indicator) without using Ajax and/or Ahah?
Comment: this module looks like similar to you query http://drupal.org/project/hide_submit
Answer: This module looks like similar to your query Hide Submit

Creating a responsive long form submit


Permanently Hide UISearchDisplayController

Question: I'm trying to hide the searchDisplay controller attached to a UITableView in an iOS 7 Table View Controller.  I don't want to temporarily scroll it off the top; I want it to be completely disabled.
In my table view controller code (which, FWIW is set to grouped style because of this), I've got:
self.searchDisplayController.searchBar.hidden = YES;
This does hide the search bar, but unfortunately results in a blank box sitting at the top of my table:

This blank will scroll off screen just like the search bar.  self.searchDisplayController.searchBar.hidden = NO; will bring back the search bar as expected.
I've tried to use suggestions from both the question and answer of this question to shift my table view 44 pixels up, which kind of works except it has the side effect of hiding the pull-to-refresh indicator at the top of my table.
I've also tried setting the frame of my search bar to have no height like so:
self.searchDisplayController.searchBar.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 0);

but this doesn't get rid of the blank space at the top of my table either.
How do I hide a the search bar from a UISearchDisplayController and actually make the space it would occupy collapse as if it wasn't there in the first place?
Comment: have you thought of checking if the search display is actually hidden? Something such as if(self.searchDisplayController.searchBar.hidden) { // make the frame = 0; } else { // make frame = 44} and then set the frame below that
Comment: I set the hidden property in a if-statement based on a standardUserDefaults value.  I did try setting the frame for the searchBar in the same if-statement while setting the hidden property; I still had the side effect of the missing pull-to-refresh indicator.
Answer: I eventually dealt with this by chaining the app's behavior circumvent the conditions for this weird behavior.  I'm not sure if this behavior was ever fixed in later OS releases.


apache2: /etc/apache2/sites-available is missing on macos

Question: I am trying to configure apache2 so that it communicates with django and I am unable to the 'sites-available' directory where I believe a 'defaults' directory should reside.
The following is my file structure under the 'etc/apache2/' directory:
├── extra
│   ├── httpd-autoindex.conf
│   ├── httpd-dav.conf
│   ├── httpd-default.conf
│   ├── httpd-info.conf
│   ├── httpd-languages.conf
│   ├── httpd-manual.conf
│   ├── httpd-mpm.conf
│   ├── httpd-multilang-errordoc.conf
│   ├── httpd-ssl.conf
│   ├── httpd-userdir.conf
│   ├── httpd-vhosts.conf
│   └── proxy-html.conf
├── httpd.conf
├── httpd.conf.bak
├── httpd.conf.pre-update
├── magic
├── mime.types
├── original
│   ├── extra
│   │   ├── httpd-autoindex.conf
│   │   ├── httpd-dav.conf
│   │   ├── httpd-default.conf
│   │   ├── httpd-info.conf
│   │   ├── httpd-languages.conf
│   │   ├── httpd-manual.conf
│   │   ├── httpd-mpm.conf
│   │   ├── httpd-multilang-errordoc.conf
│   │   ├── httpd-ssl.conf
│   │   ├── httpd-userdir.conf
│   │   ├── httpd-vhosts.conf
│   │   └── proxy-html.conf
│   └── httpd.conf
├── other
│   └── php5.conf
└── users
    ├── Guest.conf
    ├── aphexlog.conf
    └── secops.conf

If anyone knows if there is a possibility of a alternative config file with the same properties or some other solution... maybe I am just being dumb but everything that I have found online indicates that I should have this properties file.
Any and all help is appreciated :)
Answer: sites-available is a concept from Debian-derived distributions of Linux. MacOS does not have it, and neither do most other Linux flavours.
Instead you need to put your configuration directly in httpd.conf.
(Note, it's unusual to run a production system on a Mac; if you're just doing this for development, you can use the built-in runserver rather than messing around with Apache.)
Comment: Thank you, this help a lot. I am of coarse not planning on running prod on my mac lol but testing some things out and hopefully porting it over to a ubuntu server for further testing once i get thing working on my machine.
Comment: what is the `the built-in runserver` you are referring to ?


Exclude temporary files using glob

Question: Is there a way to exclude temporary files without writing more lines of code?
for file in glob.glob("C\user1\*.xlsx"):
    print(file)

C\user1\apple.xlsx
C\user1\~$apple.xlsx

I tried:
for file in glob.glob("C\user1\[^\w]*.xlsx"):
    print(file)

Comment: Globs are not regular expressions, they don't understand escape sequences like `\w`
Comment: Why does ```[^~]*```work in printing only temporary files?
Comment: Because `[character list]` is part of globbing syntax, too.
Answer: You can't use regular expression escape sequences in globs. You also have it backwards -- you want the first character to be a word character, not exclude them.
In filename wildcards, use [!characters] to exclude characters, not [^characters]. See the fnmatch module.
for file in glob.glob(r"C\user1\[!~]*.xlsx"):
    print(file)

Comment: this seems to print only the temporary files. Am i doing something wrong?
Comment: Glob uses `!`, not `^`, to negate a character set.
Answer: You could do something like this:
for file in filter(lambda x: x[0] != '~', glob.glob('C\user1\*.xlsx')):
    print(file)

Exclude temporary files using glob


spring-cloud load datasource bean earlier than parse property placeHolder

Question: After I import spring-cloud-context jar into my spring-boot2 project, it failed to parse property placeHolder in my datasource bean "org.apache.tomcat.jdbc.pool.DataSource" config. But the same property placeHolder in other bean config is parsed successfully.
Other datasource bean like "com.alibaba.druid.pool.DruidDataSource" also has the same problem. Which configuration class in spring-cloud-context cause the spring load datasource bean so eagerly?

spring config:
<bean id="dataSourceTarget" class="org.apache.tomcat.jdbc.pool.DataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${mysql.url}" />
    <property name="username" value="${mysql.username}" />
    <property name="password" value="${mysql.password}" />

    <property name="testWhileIdle" value="true" />
    <property name="testOnBorrow" value="true" />
    <property name="testOnReturn" value="false" />
    <property name="validationInterval" value="60000" />
    <property name="validationQuery" value="select 1 from dual" />
    <property name="maxActive" value="100" />
    <property name="minIdle" value="1" />
</bean>
<bean id="configTest1" class="wzp.rest.service.ConfigTest"
    primary="true">
    <property name="password" value="${mysql.password}" />
</bean>

pom.xml:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
        <version>1.4.4.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-archaius</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-netflix-archaius</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-netflix-ribbon</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.github.openfeign</groupId>
                <artifactId>feign-hystrix</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.github.openfeign</groupId>
        <artifactId>feign-httpclient</artifactId>
    </dependency>

Answer: I used MapperFactoryBean of mybatis to load mapper, and MapperFactoryBean load sqlSessionFactory and datasource bean earlier than PropertySourcesPlaceholderConfigurer changing the placeholder.
When I use org.mybatis.spring.mapper.MapperScannerConfigurer to load mapper, the problem gone.
@ConditionalOnMissingBean makes all factory beans and their dependent beans initialed early, and their getObjectType function called before placeholders in their definition was parsed. Then spring cloud config client in spring-cloud-context jar makes normal PropertySourcesPlaceholderConfigurer can not parse and update placeholders of these beans. This behavior can be forbade by setting for whom do not use cloud config:
spring.cloud.config.enabled=false
spring.cloud.refresh.enabled=false


How to record a log message when saving a Commerce Order via Drupal EntityWrapper?

Question: I'm modifying a set of orders programmatically and want to record a log message when doing so.
Is there an existing method to add a revision and log when doing so?
$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('email@example.com');
// $order_wrapper->log->set('Changed order owner and mail');
// $order_wrapper->revision->set(true);
$order_wrapper->save();

Currently if I try $order_wrapper->log->set('x'); I see EntityMetadataWrapperException: Unknown data property log., but I believe this is a property of the order (based on getPropertyInfo() etc).
Does Commerce Order + Entity Metadata Wrappers have support for creating a new revision on save, or recording an order log message?
Answer: You may need to set the revision and log properties on the default order object, instead of the wrapper.
e.g:
$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('firstname.lastname@example.com');
// Set revision details on order object
$order->revision = TRUE;
$order->log = t('Changed order owner and mail');
$order_wrapper->save();

As the order object is passed by reference, from memory the revision log info can be set that way.
Comment: Seems you're right! I'd tried this earlier (amongst other things!) and thought it hadn't worked, but it does. Thanks so much.
Comment: You're welcome, all the best with the project.


POP connector Exchange Server 2010

Question: An old server with Exchange 2003 is being replaced with a new 2008 R2 server (x64) running Exchange 2010.
On that 2003 machine we had a tool called EFS (Email Forwarding System) but the tool is old and doesn't have Exchange 2010 listed as a supported environment.
The website itself has also a warning for Exchange 2010:

(* NOTE: Some users have reported issues with blank HTML formatted emails sent to Exchange 2010. Earlier versions of Exchange are unaffected. The fault is not actually EFS, but a 3rd party mail control that we use. We are trying to track down the source code from that vendor so that the problem can be fixed. We do not have a time frame that this will be fixed by yet. We apologise for any inconvenience caused)

Does this POP connector functionality come out of the box with Exchange Server 2010 or do you still need such tool?
If so: how do you configure it or what (free?) tool would you recommend that has the same or more options like EFS.
Thanks in advance
Answer: Are you using this to retrieve emails from a pop server? Exchange does not have this ability built-in.
There are lots of competitors for this product, but we do not recommend commercial products on this site.
A better idea would be to rethink mail delivery. If you need a third party to hold your email for you because your internet connection is unreliable, then look for an mx host instead of a mailbox host.

POP connector Exchange Server 2010


Error running a PHPUnit test only under run-tests.sh

Question: I'm working on an 8.x module that uses PHPUnit tests.  I've been running these from the command line using the embedded phpunit script that's installed with Drupal 8:
../vendor/bin/phpunit PATH/TO/MY/FILE.php

Both of my tests work w/o any problems under both PHP 5.5 and PHP 5.6.
But the Drupal testbot is failing both of my tests with the error
Fatal error: Trait 'Drupal\Tests\my_module\MockSessionTrait' not found in /var/www/.../PATH/TO/MY/FILETest.php

Using phpunit from the command line, this same trait is found w/o any trouble.
If I run the tests myself from the command line, but this time using run-tests.sh, I get the same error the testbot gets:
php scripts/run-tests.sh --url http://192.168.88.42/drupal --class 'Drupal\Tests\my_module\Unit\FILETest'

The stack trace looks like this:
PHP Stack trace:
PHP   1. {main}() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   2. simpletest_script_get_test_list() /var/www/drupal/core/scripts/run-tests.sh:76
PHP   3. class_exists() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   4. spl_autoload_call() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   5. Symfony\Component\ClassLoader\ApcClassLoader->loadClass() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   6. require() /var/www/drupal/vendor/symfony/class-loader/ApcClassLoader.php:114

I'm guessing that I need to help run-tests.sh to find my files, somehow.
Any advice from anyone as to why run-tests.sh behaves differently here from stock phpunit?
Comment: Please add the exact location of your test class and trait. I'm not sure but you might not be able to have a non-test class in the tests/src location, try moving that to module/src/... and change the namespace accordingly (Drupal\module\...
Comment: @Berdir: one class is at drupal/modules/custom/examples/file_example/tests/src/Kernel/StreamWrapperTest.php, and the trait at drupal/modules/custom/examples/file_example/tests/src/MockSessionTrait.php.  You can see the patch at https://www.drupal.org/node/2102651#comment-10495064.
Comment: @Berdir: I BOW BEFORE YOUR SUPERIOR INTELLECT :-) I moved the trait to Drupal\file_example\StreamWrapper\MockSessionTrait, and damned if everything now works both under run-tests.sh _and_ ../vendor/bin/phpunit.  Yes, run-tests.sh will spit up if a PHPUnit test class references a trait that is also a Drupal\Tests class.  Who knew? Well, you did, anyway.
Answer: @Berdir is completely correct here:

I'm not sure but you might not be able to have a non-test class in the tests/src location, try moving that to module/src/... and change the namespace accordingly (Drupal\module...

While PHPUnit doesn't mind if a test class uses a trait that's in a Drupal\Tests namespace, the simpletest test runner run-tests.sh will be unable to find the trait if you do this.
So don't do that.
Even if a trait is used only with your test classes, if you want your code to get past the Drupal testbot, the trait needs to live somewhere in your Drupal\your_module\ namespace. Do this, and both phpunit and run-tests.sh will be happy.


Equivalent of Symfony 2's path() or url() in Symfony 1.4

Question: Is there an equivalent of Symfony 2's path() or url() in Symfony 1.4, where you could use the name of the route (in the routing.yml) in the template to get the associated url
Answer: In Symfony 1.4 you can use the url_for() and link_to() helper functions. Using a combination of the two you can use route names to generate URLs quite easily...
Example usage:
Symfony2:
Home

Symfony 1.4:
<a href="<?php echo url_for('@welcome');?>">Home

A slightly more complication example:
Symfony2:
View Blog Post

Symfony 1.4:
<?php echo link_to('View Blog Post', '@blog_show', array('slug' => $blog->getSlug()); ?>

Comment: Thanks for the answer, when I do url_for('@route_name'); , the url has index.php added to it (like http://www.xxxx.com/index.php/). Do you know why the index.php shows up ? and how can I suppress that.
Comment: What you're interested in is [the no_script_name option in apps/appname/config/settings.yml](http://symfony.com/legacy/doc/reference/1_4/en/04-Settings#chapter_04_sub_no_script_name).


If $x$ is an ordinal, then so is $x\,\bigcup\,\{x\}$

Question: I wish to show that $x$ is an ordinal, then so is $x\,\bigcup\,\{x\}$ (with $y<x$ for all $y\in x$).
I have seen a proof in Cameron's Sets, Logic and Categories (p.41), but I find it unsatisfactory. He writes:

The set $a = x\,\bigcup\,\{x\}$ (with order as specified in the the statement of the theorem) has as sections all the sections of $x$ and one additional one, namely $a_x$. But since all the elements of $x$ are smaller than $x$, we have $a_x = x$.

I don't see why it necessarily follows from this that $a_x = x$. By definition, $a_x = \{y\in a : y\subset x\}$, so $a_x\subseteq x$, but this is different than $a_x = x$.
Comment: You can see that $x\subseteq a_x\subsetneq x\cup\{x\}$. Then what must $a_x$ be?
Comment: Cameron defines a section $a_y$ ($y\in a$) to consist in all the elements of $a$ which are less than $y$ (ordered by inclusion)
Comment: If $\subset$ is a *proper* inclusion, then Cameron is right.
Comment: @HanulJeon Can you explain?
Comment: @HanulJeon In my original post, I wrote $a_x=\{y\in a:y\subset x\}$, but the definition Cameron actually gives is $a_x=\{y\in a:y < x\}$. Does this make a difference?
Comment: If $\subset$ is a proper inclusion, then no.
Answer: Suppose $y\in x$.  Since $x$ is an ordinal, this implies $y\subset x$.  So, $y$ is an element of $a$ such that $y\subset x$, which by definition means that $y\in a_x$.
Comment: I'm happy to mark this as correct, but can you see if my more formal answer (below) works?
Comment: Yep, it looks good.
Answer: In my original post, I wrote $a_x=\{y\in a:y\subset x\}$, but the definition Cameron actually gives is $a_x=\{y\in a:y < x\}$. Does this make a difference?
Either way, it seems that:
$$\begin{align}
a_x &= \big\{y\in a:y<x\big\} \\
&= \big\{y\in x\cup\{x\}:y<x\big\} \\
&= \big\{y\in x:y<x\big\}\cup\big\{x\in\{x\}:y<x\big\} \\
&= x\,\cup\,\varnothing \\
&= x
\end{align}$$
where $\big\{x\in\{x\}:y<x\big\} = \varnothing$ because $x\nless x.$
Comment: It is not an actual answer but a question. You should add it to your question or write a new question rather than posting it as an answer.


Find a the density function for Y(1) = min(Y1, Y2, . . . , Yn).

Question: Suppose that the length of time Y it takes a worker to complete a certain task has the probability density function given by
$f(y)=\begin{cases} e^{-(y-\theta)} &, y>\theta\\ 0 & ,elsewhere \end{cases}$
where θ is a positive constant that represents the minimum time until task completion. Let
$Y_1, Y_2, . . . , Y_n$ denote a random sample of completion times from this distribution. Find
a the density function for Y(1) = min(Y1, Y2, . . . , Yn).
b E(Y(1)).
Could anyone get me started on this since the random sample is not independent?
Comment: Let $j = \min_i(Y_i)$.  What's the likelihood that the (independent of $Y_j$) samples are all greater than $Y_j$?  (This is the intersection of the conditions that each of the $n-1$ samples is $ \geq Y_j$.)
Answer: Hints:

The sample times are presumably independent.
Find the probability $Y_i \le x$ for a particular $i$
Find the probability $Y_i \gt x$ for a particular $i$
Find the probability $Y_i \gt x$ for all $i$
Find the probability $\min_i(Y_i) \gt x$
Find the probability $\min_i(Y_i) \le x$
Find the density function for $\min_i(Y_i)$
Find the expectation of $\min_i(Y_i)$
Comment: could you show me how to find the probability for $ Y_i \le x$ for a particular i ?
Comment: $\displaystyle P(Y_i \le x) = \int_{y=\theta}^x e^{-(y-\theta)} dy = 1-e^{-(y-\theta)}$ for $x \gt \theta$
Comment: just want to put the right position for all your hints, is it going to be let $U = min (Y_1, Y_2, ..., Y_n)$. $P[U \le t] = 1 - P[U > t] = 1 - P[Y_1 > t, Y_2 > t ,..., Y_n > t] = 1 - [1-F_Y (t)]^n $ Then we take the derivatives of $P[U \le t] = 1 - [1-F_Y (t)]^n$ to find the density function for $min_i (Y_i)$?
Comment: Yes, but $1 - [1-F_Y (t)]^n$ is not difficult to express in terms of $e,y,\theta,n$.  Try it.
Comment: $P[U > t] = 1 - [-e^{-(y-\theta)}]^n$ Is this right?
Comment: density for $Y_{(1)}$ is $n[-e^{-(y-\theta)}]^{n-1} e^{-(y-\theta)}, y > 0$    for $E(Y_{(1)}) = 1-ye^{-(y-\theta)}-e^{-(y-\theta)} + y $, right?
Comment: You have a sign error or two at the start and can simplify: $P[Y_{(1)} \gt y] = e^{-n(y-\theta)}$, while the density  for  $Y_{(1)}$ is $ne^{-n(y-\theta)}$.  Your statement for the expectation is very wrong as it should not include $y$
Comment: The way I calculate density for $Y_{(1)}$ is $f_U (t) = n [F_y(t)]^{n-1} f_y(t) = n [1-e^{-(y-\theta)}]^{n-1} e^{-(y-\theta)}$, for $y > \theta$...does it look right to you...if you could you show me how to get to your density answer?
Comment: You should have $$P[Y_i \le y] = 1-e^{-(y-\theta)},$$ $$P[Y_i \gt y] = e^{-(y-\theta)},$$ $$P[Y_{(1)} \gt y] = [e^{-(y-\theta)}]^n = e^{-n(y-\theta)},$$ $$F_{Y_{(1)}}(y)= P[Y_{(1)} \le y] = 1 - e^{-n(y-\theta)},$$ $$f_{Y_{(1)}}(y)=  ne^{-n(y-\theta)}$$
Comment: Got it...before getting to the detail of my calculation for $E(Y_{(1)})$ ... I just want to check with my setup matches with yours first....$$
\int_\theta^y xe^{-(x-\theta)} dx
$$? If this is different from yours, could you show yours?
Comment: Two points: (1) you have the original density there when you should have the density for the minimum; and (2) $y$ is not the correct top limit of the integration
Comment: For (1), after looking at your comment, I am a bit confused as to how to write out the density for the minimum. Could you show it?..For (2), what is the top limit is going to be .... since my thinking is for the support $ y > \theta $...so it should integrate up to t.
Comment: The density is $ne^{-n(y-\theta)}$ and the integral should go to infinity
Comment: if I integral this, my answer is infinity through...if not, could you show me your answer?
Comment: No.  $\displaystyle \int_\theta^\infty ne^{-n(x-\theta)} dx = 1$ and $\displaystyle \int_\theta^\infty xne^{-n(x-\theta)} dx$ is also finite.
Comment: so your answer for $E(Y_{(1)})$ is what?
Comment: The shifted expectation of an [exponential random variable](http://en.wikipedia.org/wiki/Exponential_distribution) with rate $n$
Comment: this info does not relate to this problem though...
Comment: I did not see why $\int_\theta^\infty ne^{-(x-\theta)} dx $is 1. Could you explain that?
Comment: You are missing an $n$ in the exponent as in $\displaystyle \int_\theta^\infty ne^{-n(x-\theta)} dx = \left. -e^{-n(x-\theta)} \right|_\theta^\infty = 0 -(-1)= 1$.
Comment: you have to multiply by x inside this integral right?
Comment: For the expectation, yes: $\displaystyle \int_\theta^\infty xne^{-n(x-\theta)} dx$.  Integration by parts will do it
Comment: However, when I integrate this, I got $x - \frac{1}{n}$...which does not make much sense to me... if that is different from yours, could you show me how did you get your answers?
Comment: You should have $\left. -\left(x+\frac1n\right) e^{-n(x-\theta)} \right|_\theta^\infty $ and your result should have $n$ and $\theta$ but not $x$
Comment: The answer is $\theta - \frac{1}{n}$?
Comment: Close: $\theta + \frac{1}{n}$
Comment: you are right as I mess up with one of the sign...finally...


IntelliJ 13 not picking up build.sbt changes

Question: I'm using IntelliJ 13.1.2 on OS-X Mavericks.
I added a new dependency to my build.sbt inside an IntelliJ project. I synced my project as well as my build.sbt but I cannot import classes from this new library in my Scala classes.
However, when I do a sbt clean complile; sbt console on a terminal (outside of IntelliJ) I can successfully import classes from this new library.
Can anyone help me resolve this ?
Thanks
Comment: Usually when you change the SBT file a message appears asking you if you want to refresh the imports does this not happen to you?Alternatively you can set SBT to do it automatically into preferences -> SBT -> use auto import.
Comment: I don't see that error message. and I don't see the "use auto import" option when I go to "preferences -> SBT -> Use auto import"
Comment: this is the plugin I'm using. https://github.com/orfjackal/idea-sbt-plugin/wiki (Version 1.5.1)
Comment: @SoumyaSimanta it has nothing to do with *automatic* picking of changes -- you have to be happy with stock IntelliJ *scala* plugin, which understands sbt project files since 13.x IDEA release (don't remember exact version)
Comment: @om-nom-nom - so should I uninstall/disable the sbt plugin ?
Comment: @SoumyaSimanta you should not, what I am saying is that mentioned sbt plugin has nothing more to propagating dependency changes to IDEA than, say, jenkins or JSP plugins (in other words, nothing) -- it's just a terminal shortcut. The relevant plugins are: 1) in pre-13.x era [sbt-idea](https://github.com/mpeltonen/sbt-idea) which has to be invoked manually every time you made changes to project description 2) currently, ordinary *scala* plugin, supplied by JetBrains is capable of tracking all changes and exporting them back to IDEA, in automatic fashion (by-default, via popup, but anyways)
Comment: So, do you have [scala plugin](http://plugins.jetbrains.com/plugin/?id=1347) installed? Is it [fresh enough](http://blog.jetbrains.com/scala/2013/11/18/built-in-sbt-support-in-intellij-idea-13/)?
Comment: I've Version: 0.36.431 of [this plugin](http://confluence.jetbrains.com/display/SCA/Scala+Plugin+for+IntelliJ+IDEA)
Comment: Can you please elaborate, do you have one or more projects you're trying to get working? How does your `build.sbt` looks like. If you have more than one project, are they built by the same build.sbt? Does the build work from console?
Comment: I just have one project and yes it works correctly from the console.
Answer: In preferences -> SBT (in Project Settings section) -> check the box next to 'Use auto-import' and that should keep IDEA synced with your build.sbt