Where are the logs for Exchange 2010 stored?

Question: Where are the logs stored for Exchange 2010. Specifically error logs.
Cheers, Dean
Answer: Unlike Exchange Server 2003/2000, you have to enable logging separately for Send Connectors (used to send mail outside the Exchange organization, Send Connectors are equivalent of SMTP Connectors in Exchange 2003/2000), using the following command:
<code>Set-SendConnector "Send Connector Name" -ProtocolLoggingLevel verbose
</code>
To enable protocol logging on a Send Connector using the EMC:
Expand the Organization Configuration | Hub Transport node
On the Send Connectors tab, select the Send Connector -> properties
On the General tab, change the Protocol logging level to verbose.
The logs can be found in
<code>\Exchange Server\V14\TransportRoles\Logs\ProtocolLog\SmtpReceive
</code>
and
<code>\Exchange Server\V14\TransportRoles\Logs\ProtocolLog\SmtpSend
</code>
Answer: There aren't error logs per se. There are the event logs and if configured there are Message Tracking logs, Send connector logs, Receive connector logs, etc. What are you looking for?
Comment: I was looking for send connector logs. Would they be in the event log viewer or would it be an actual log file?
Comment: It's in a log file. You have to make sure that logging is enabled on the Send connector and then the logs will be at: C:\Program files\Microsoft\Exchange Server\TransportRoles\ProtocolLog\SmtpSend


Using matrices and 3 rotation angles for $x,y,z$ axes, how can you compute the final position of a point in 3D?

Question: Seeing that the three individual rotation matrices for each axis are not commutative, I was wondering how a point (e.g. $[1,2,3]$) could be rotated in 3D space with a single matrix as to avoid the "commutative" issue.
Comment: Have you considered how does it should be in 2D?
Comment: Well, 3D rotations are inherently non-commutative, unlike 2D rotations. If you imagine a solid object instead of a single point, you can imagine that the final orientation of that object would depend on the order of the rotations. So really the question is this: how do you want the object to be oriented after the rotation? You can always rotate straight from start to finish, but you'll have no control over the final orientation.
Comment: For this rotation to be well-defined, you also have to specify in which of the six possible orders the primitive rotations should be applied.
Answer: A point is rotation can be described with either of two scenarios, each requiring three pieces of information to fully describe:

Three sequential rotations about fixed axes. For example $$ \mathrm{R} = \mathrm{RZ}(\varphi)\,\mathrm{RY}(\psi)\,\mathrm{RZ}(\theta)$$
This is described by the three angles $\varphi$, $\psi$ and $\theta$. These are called Euler angles.

A single rotation about an arbitrary axis. For example $$ \mathrm{R} = \mathrm{Rot}(\hat{u}, \theta)$$ where the unit direction vector $\hat{u}$ needs two quantities for description (like longitude and latitude) and the third quantity is the angle $\theta$. This is the Rodrigues rotation formula.

There is an alternative scenario to the last one using quaternions where four quantities $x$, $y$, $z$ and $w$ are used to represent this axis and angle. There is a constraint that $\sqrt{x^2+y^2+z^2+w^2}=1$ for this scenario to work
$$ \begin{aligned}
  \hat{u} & = \frac{ (x,y,z) }{ \sqrt{x^2+y^2+z^2} } & &\text{axis} \\
  \theta & = 2 \,\mathrm{atan}\left( \frac{ \sqrt{x^2+y^2+z^2}}{w} \right) & & \text{angle}
\end{aligned}$$


Diferença entre o evento (submit) e (ngSubmit)

Question: Bom, vi alguns artigos explicando que o "ngSubmit garante que o formulário não é enviado quando o código do manipulador é lançado (que é o comportamento padrão de envio) e causa uma solicitação de postagem http real."
Sinceramente não entendi nada.
Qual é a diferença entre esses dois eventos?
Comment: submit causa postBack, ou seja, recarrega a página. ngSubmit basicamente impede o compartamento padrão do submit, tendo maior controle em uma aplicação SPA.
Answer: O problema está na tradução que você mencionou. O trecho original diz:

ngSubmit ensures that the form doesn't submit when the handler code throws (which is the default behaviour of submit) and causes an actual http post request.

A parte que importa é "handler code throws", isso se refere à exceptions, exemplo:
if (this.formControls.sellingDate > today) {
    throw new Error("Campo data não pode ser maior que hoje.");
}

A tradução "é lançado" realmente não é uma boa tradução para "throws", e é onde está causando dúvidas.
No entanto, não aconselho você a validar formulários usando exceptions, tente usar Validators nos seus formControls ou então até mesmo usar toastr para notificar o usuário sobre o problema com os dados informados de forma mais amigável.
Outro ponto é que para evitar reloads, caso esse seja seu problema, você tem duas opções que eu considero melhor:

passar o $event pro seu método ("handler") e chamar $event.preventDefault(); logo na primeira linha; ou
quando entrar num "if" que seja impeditivo, usar return false; logo depois de dar a mensagem ao usuário.

Espero ter ajudado.
Answer: A parte final do comportamento padrão do evento Submit() de um formulário é o envio do conteúdo do formulário para o destino especificado no atributo action, seguindo de uma recarga da página.
Esta recarga vai contra o comportamento desejado em uma aplicação de página única - no caso sua aplicação Angular deve apenas enviar o conteúdo e aguardar o retorno sem reload.
Comment: Sim, mas no Angular2+ existem dois eventos, o submit e o ngSubmit. Os dois submetem os dados e os dois não recarregam a página. Queria saber a diferença entre esses events binding


Ao se fazer uma repetição em caso de não haver resposta, alteração nenhuma esta sendo realizada! pq?

Question: É um código simples, mas com base no que vi e andei estudando sobre estrutura de repetição aqui mesmo, cheguei a um modo de faze-lo, porém estou lidando com o seguinte problema: o valor não está sendo acrescido após a opção dada pelo programa estar sendo realizada! sempre me dando como retorno o valor de 0 (zero)!.
segue:
valor = int(input('Valor Solicitado: '))
valor1 = int(0)

while True:
    parcelax = input('Qual formato de parcelamento?  \n 1) Á Vista \n 2) 12x  \n 3) 30x \n 4) 60x  \n' )
    if parcelax not in {'1','2','3','4'}:
        print('Digito incorreto!')
        continue
    if parcelax == 1:
        valor1 = 20
    break
print('Olha: {}'.format(valor1))

Comment: Vale comentar que `0` já é um valor inteiro, então fazer `int(0)` é redundância. Pode fazer apenas `valor1 = 0`.
Answer: É que o método input retorna uma string.
Você estava testando if parcelax == 1: como se parcelax  fosse um inteiro.
Opção 1: Então ou você muda para if parcelax == '1': testar o valor como string.
Opção 2: Você converte parcelax para inteiro desta forma if int(parcelax) == 1:
Segue a solução com a opção 1:
valor = int(input('Valor Solicitado: '))
valor1 = int(0)

while True:
    parcelax = input('Qual formato de parcelamento?\n 1) Á Vista \n 2) 12x  \n 3) 30x \n 4) 60x  \n' )
    if parcelax not in {'1','2','3','4'}:
        print('Digito incorreto!')
        continue
    if parcelax == '1':
        valor1 = 20
    break
print('Olha: {}'.format(valor1))


Content element inside Toolbar component doesn't work

Question: I'm trying to build a table with button on table's header. I'm guiding from here.
This is my code:
<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"
        xmlns="sap.m"
        xmlns:l="sap.ui.layout"
        xmlns:f="sap.ui.layout.form"
        xmlns:t="sap.ui.table"
        height="100%"
        controllerName="xxxxx"
        xmlns:html="http://www.w3.org/1999/xhtml">
    <Page title="CONFIGURACIÓN DE LA CUENTA" navButtonPress="onCancel" showNavButton="true">

        <content>
            <f:SimpleForm id="form_requerimiento_datos_generales" minWidth="1024"
                          maxContainerCols="2" editable="true" layout="ResponsiveGridLayout"
                          labelSpanL="4" labelSpanM="4"
                          emptySpanL="0" emptySpanM="0" columnsL="2" columnsM="2"
                          validateFieldGroup="onValidateFieldGroup">
                <f:content>

                    <core:Title text="Suscripciones"/>
                    <t:Table
                        rows="{/Subscriptions?$filter=UserSystem eq '1'}"
                        selectionMode="None"
                        visibleRowCount="7">
                        <t:toolbar>
                            <content>
                                <Title id="title" text="Listado de Suscripciones" />
                                <ToolbarSpacer/>
                                <Button
                                    icon="sap-icon://add"
                                    tooltip="Agregar Suscripciones"
                                    press="addSuscription"/>
                            </content>
                        </t:toolbar>
                        <t:columns>

                        </t:columns>
                    </t:Table>
                </f:content>
            </f:SimpleForm>
        </content>
    </Page>
</core:View>

I have following error message:
Uncaught Error: failed to load 'sap/m/content.js' from https://sapui5.netweaver.ondemand.com/resources/sap/m/content.js: 0 - NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://sapui5.netweaver.ondemand.com/resources/sap/m/content.js'.

I don't know why I get this error. I think that It's in this part of code:
<t:toolbar>
    <content>
        <Title id="title" text="Listado de Suscripciones" />
        <ToolbarSpacer/>
        <Button
            icon="sap-icon://add"
            tooltip="Agregar Suscripciones"
            press="addSuscription"/>
    </content>
</t:toolbar>

I don't know why content label is not accepted inside toolbar label (In example this works). When I take off content label of my page. I don't get error messages.
I would like to know what doing for to solve my problem.
Thanks for help me!
UPDATE 1
I solved already my problem but Now I have another problem. I have a problem with CSS of table header (This is overlapped with table body):
Answer: The label <t:toolbar> is the aggregation name and it expects a toolbar inside it.
So, ideally <t:toolbar> is followed by a sap.m.Toolbar control.
As to why it is throwing: sap/m/content error is because,  it is expecting a control after the <t:toolbar>. Also, since your default namespace is sap.m so it looks for control ( in this case you have specified content) in the default namespace.There is no such control as sap.m.content. Thus, an error.
If you will check your guiding source, you will see they have an <m:Toolbar> after <toolbar> aggregation
Here is the updated code:
                      <t:toolbar>
                            <Toolbar>
                                <content>
                                    <Title id="title" text="Listado de Suscripciones" />
                                    <ToolbarSpacer/>
                                    <Button
                                        icon="sap-icon://add"
                                        tooltip="Agregar Suscripciones"
                                        press="addSuscription"/>
                                </content>
                            </Toolbar>
                        </t:toolbar>


Postions of Divs in Desktop and mobile view

Question:

              <gm-conversation-list language-code="{{languageCode}}"
                                    first-result="{{firstResult}}"
                                    results="{{results}}">
              </gm-conversation-list>

        <template is="dom-if" if="{{!filtered}}">

              <template is="dom-if" if="{{openConversation}}">
                <gm-conversation
                  id="conversation1"
                  conversation="{{conversation}}"
                  show-tool-tip="{{showToolTip}}"
                  tool-tip-step="{{toolTipStep}}"
                  base-url="{{baseUrl}}"
                ></gm-conversation>
              </template>

        </template>

I have left div and right div in desktop view. Left div has chat list. Right div has one selected chat details. (The chat Selected from left chat list div) In mobile view, it should display Left chat list div. After selecting the specific chat from the chat list div(Left div) it should display the selected chat details in separate mobile UI. Please help me to explain with simple code.
Comment: please show us your code
Comment: what you had done so far.
Comment: please create a code snippet of your working code. thanks
Answer: Given the lack of information, this is the simplest piece of code I can come up with(Change the width to see the mediaquery effect):

document.getElementById('btn').addEventListener('click',function(e) {
 let rightSide = document.getElementById('right');
 let leftSide = document.getElementById('left');
 rightSide.style.display = 'block';
 leftSide.style.display = 'none';
 e.preventDefault();
})
.container {
 display: flex;
 color: #fff;
}

.left {
 flex: 3;
 background: red;
}

.right {
 flex: 1;
 background: blue;
}

/* Viewport */
@media (max-width: 576px) {
 .right {
  display: none;
  flex-basis: 100%;
 }
}

  Click here

Right


PivotViewer: Trading Card Visibility

Question: I'm developing a PivotViewer (Silverlight 5) control that makes use of Semantic Zoom.  There are two trading card templates, a "small" template displaying a low-resolution image, and a "big" template displaying a higher-resolution version of the same image and some text.
The low-resolution images are bundled in the XAP file.  I'd like to dynamically download and display a trading card's higher-resolution image when the high-res version of that template becomes visible.  But the best I've been able to do thus far is downloading the image when the trading card is selected through SelectionChanged, as seen here:
http://www.beerolf.com/pivottest/SilverlightLoadTest.html
(When you click a trading card, you should see text saying "Big!!!" indicating that the high-res image is being used.  If you zoom into a trading card before clicking it, the original image remains.)
This is okay, but I don't want to force users to click trading cards to see higher-resolution images.  Is there any way to determine which trading cards are currently visible?
Answer: The trick with multiple templates is to get the sizing right.
In the example that you gave, the templates are loading fairly large since there are not that many of them. In a case like that, you are most likely going straight to the larger template.
I would put the source url of the high-res in your larger templates, so they will load automatically. Is there a reason you aren't doing this?

PivotViewer: Trading Card Visibility


Values from $node object in Views Contexual Filter

Question: I'd like to create a PHP contexual filter for a view.
This code isn't right, but I want something like this:
<code>global $node;
if ($node->type=="ABC") {
return 5880;
}

if ($node->type=="XYZ") {
return 6200;
}
</code>
How do I access the $node object in a PHP contexual filter?
Also, is there a better way to debug/troubleshoot this? I feel like I'm operating in complete darkness.
Comment: Please post it as an answer.
Answer: You can access the $node object by doing this in the filter:
<code>$node = menu_get_object()
</code>


Slatejs reset element type after line-break

Question: I'm working with slatejs ,and I want to know :
If my current Element.type is title , looks like

 ,
but when I click enter,  it will create a new
 tag.
If I want the line-break after title type and the new element type will become default,
what shoud I do ?
Answer: Assuming your node looks something like: {children : [{text: ''}], type: 'title'}
or something on the lines of this.
When you press enter, it adds an empty node like {children : [{text: ''}], type: 'title'}
You should be able to modify the insertBreak behaviour this way to modify the kind of node that it adds:
const { insertBreak } = editor

  editor.insertBreak = () => {
    const { selection } = editor

    if (selection) {
      const [title] = Editor.nodes(editor, {
        match: n =>
          !Editor.isEditor(n) &&
          Element.isElement(n) &&
          (n.type === 'title')
      })

      if(title){
        Transforms.insertNodes(editor, {
          children: [{text: ""}],
          type: 'default'
        })
        return
      }
    }
    insertBreak()
  }


Get Rspec example tags

Question: :I'm developing framework to interract Rspec and Testrail. I decided to unite tests to groups by using tags. After finishing test I parse example variable, which is Rspec::Example object and here I need to get its tags to ignore this test, if it contains specific tag, then set 'blocked' status to it in Testrail. So is there any method, like example.get_tags for my case?
It should looks like:
it 'test', tag1: true, tag2: true do
  true.should == true
end

after :each do
  example.get_tags #  tag1: true, tag2: true
end

Answer: Found it in example.metadata, question closed.

Get Rspec example tags


Regex search and replace with optional plural

Question: I'm a novice at regex, so hopefully some expert can just yawn at my question with an easy answer. I'm trying to find and replace words that start with a certain letter and keep them plural if they are plural.
So, for example, I want to replace replace the word "boy" with "band", and "boys" with "bands"
text.replace( /\b(b)[\w]+(s?)\b/gi, "$1and$2<\/span>" );

However, $2 isn't coming up with the optional "s".
Thanks ahead of time!
Answer: Simply change [\w]+ to [\w]+?.
This changes
from "greedy" (match as many characters as possible and only give characters up if forced to)
which means s? will not match because [\w]+ already did it for us. (wrong behavior)
to "lazy" (match as few characters as possible, only adding to the match if absolutely necessary)
which gives s? an opportunity to match. (correct behavior)
By the way: You can change [\w]+? to \w+? and it will work exactly the same.
Comment: This solution falls a little short on some plurals. _kiss_ to _kisses_, _lady_ to _ladies_ are two examples. Less obvious examples are also _leaf_ to _leaves_, _life_ to _lives_. You could extend the regular expression above with an or condition, e.g. `^\b[\w]+(s|i?es|ves)\b$` it falls short a little on `kiss` which matches, but most other cases it appears to match reasonably well.
Comment: Perfect! I figured the \w was grabbing it, but I didn't know about this option! Thanks!
Answer: [\w]+ has already matched the "s". The solution is to make [\w]+ match as few as possible, instead of as many as possible, with the "?" modifier. Thus:
\b(b)[\w]+?(s?)\b

Answer: Just use the pattern like /\b(([A-Za-z]{3,})+(s))\b/
$text="boys";
echo preg_replace('/\b(([A-Za-z]{3,})+(s))\b/','$2',$text); //output "boy"

Answer: Continuing from the PHP question Regex - How to search for singular or plural version of word
If you know what your search term is, it can be pretty simple. Here's a simple example I use in PHP to highlight all occurrences of a search term whether it is singular, simple plural (s), all lowercased or first letter uppercased:
function add_highlight($content,$term)
{
    //always remove last s if it exists
    //and could use similar strategy to test other endings such as -es and -ies
    //by conditionally building the regex test string based on term's ending
    $term_no_s = rtrim($term,"s");
    return preg_replace("/({$term_no_s}s)|({$term_no_s})/i", "$0", $content);
}


How can I be notified when a control becomes key? I want t o have my custom warning popover NSWindow autohide and show; only the hide part works

Question: I have a custom NSWindow subclass that's used to display a pop-out warning on NSTextFields. I want the warning to automatically hide when the NSTextField loses key status, and to show again when it gains key. So I have
    self.onBegin = [[NSNotificationCenter defaultCenter] addObserverForName:NSControlTextDidBeginEditingNotification
        object:self.textfield
        queue:nil
        usingBlock:^(NSNotification *note){
            [self orderFront:self];
        }];
    self.onEnd = [[NSNotificationCenter defaultCenter] addObserverForName:NSControlTextDidEndEditingNotification
        object:self.textfield
        queue:nil
        usingBlock:^(NSNotification *note){
            [self orderOut:self];
        }];

onEnd works fine: the custom window hides itself when I tab away from the text field or do something else, etc. But onBegin doesn't seem to fire until I start actually changing the contents of the text field.
Is there some other option I can use? Should I not be using notifications for this, or is there some API (must be 10.7+) that I don't know about? Thanks.
Comment: That (or rather, its Mac equivalent) still only triggers when I start typing.
Answer: You can use Key-Value Observing (KVO) to monitor the firstResponder property of the window containing the text fields. When you get notified that the first responder has changed, you can check if it's one of the text fields you're interested in. Note, though, that the window's firstResponder won't be the text field itself, it will be the text view that serves as the field editor for the text field. To determine which text field the field editor serves, you check the field editor's delegate.
See Cocoa Event Handling Guide: Event Handling Basics – Determining First-Responder Status.
if ([window.firstResponder isKindOfClass:[NSTextView class]] &&
    [window fieldEditor:NO forObject:nil] != nil)
{
    NSTextField *field = [window.firstResponder delegate];
    // Do something with 'field', which is the text field that has focus
}

Comment: Hm,... either I'm doing something wrong somewhere, or the `[[self.parent firstResponder] delegate]` is always nil? Either way this does get me the message I want at the right time, so that's closer...
Comment: What is `self.parent`? Is it the window *containing* the text fields? Are you sure that it is not itself `nil`? Also, are you using a custom field editor?
Comment: Yes, it's the window containing the text fields (I checked). It is not nil, nor is the first responder. The field editor is not custom, but I did modify it to turn off autocorrect. I also checked to make sure the instances of the field editor are the same; they are. Only the delegate pointer is nil (as is the delegate of the field editor if I grab it from there).
Comment: `tv = (NSTextView *) [window fieldEditor:YES forObject:nil]; [tv setEnabledTextCheckingTypes:0]; [tv setAutomaticDashSubstitutionEnabled:NO]; [tv setAutomaticSpellingCorrectionEnabled:NO]; [tv setAutomaticTextReplacementEnabled:NO];`
Comment: In what context do you have the above code for modifying the field editor? I wonder if requesting it and passing `nil` for the object is clearing the delegate. I would recommend that you do this in a different way. Option 1: use a custom subclass of `NSTextFieldCell` and override `-setUpFieldEditorAttributes:` to, well, set the field editor's attributes. Option 2: use a custom window subclass and override `-fieldEditor:forObject:`. Call through to `super` and then, depending on `anObject`, modify it before returning it.
Comment: The field editor modifications are created as part of the window creation process. Wouldn't the nil in my observer code also have the same effect, though? Whatever the case, I can try the override NSWindow option and report back how that goes.
Comment: Update: nope, subclassing NSWindow didn't fix it. I also disabled the changes entirely; still a nil delegate.
Comment: Very strange. It's clearly documented that the field editor's `delegate` will be the text field. What is the window's `firstResponder`? What is it's field editor? Are they the same object?
Comment: Yep; they're the same. I'm actually starting to think the delegate simply isn't set when the KVO observer is signaled. I'm not sure how to check (dispatch_async()?).
Comment: Yep, that was it. I'm now observing the field editor's delegate instead, and everything works correctly. Thanks!
Comment: I'm glad you found the reason. I'm not sure it's safe to observe the delegate. It's not documented as KVO-compliant. A delayed check like you suggested may be safest.


Python local variable initialization

Question: I'm rather new to python and I'm wondering how local variables work. Let's start with an example of a simple method:
def do_sth():
    local_dict = { 'a': 1, 'b': 2, 'c': 3, ... }
    ...

Let's assume that local_dict is used like a sort of const variable. And here's the question: it is created every time when do_sth() is invoked or it is created once and is kept somewhere in do_sth() internals?
Comment: In general, things that aren't changed are optimized to only be initialized once in most languages unless you direct the compiler to do otherwise (where you are able to).
Comment: In Python, in general, nothing is ever optimized by the interpreter ;-)
Comment: http://stackoverflow.com/questions/12590058/python-performance-with-global-variables-vs-local gives you some answers
Answer: You can look at what the interpreter does using the dis module:
def do_sth():
    d = {'a':2, 'b':3}
    print(id(d))

import dis
dis.dis(do_sth)

will print
  2           0 BUILD_MAP                2
              3 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 ('a')
              9 STORE_MAP
             10 LOAD_CONST               3 (3)
             13 LOAD_CONST               4 ('b')
             16 STORE_MAP
             17 STORE_FAST               0 (d)

  3          20 LOAD_GLOBAL              0 (id)
             23 LOAD_FAST                0 (d)
             26 CALL_FUNCTION            1
             29 PRINT_ITEM
             30 PRINT_NEWLINE
             31 LOAD_CONST               0 (None)
             34 RETURN_VALUE

which shows that the interpreter is rebuilding the value every time the function is called.
Answer: Every time do_sth() is invoked. This is important because it allows you to make modifications to local_dict inside the function and it won't have any effect on other calls. The interpreter is not smart enough to see if you won't change it, especially because Python is so dynamic that there are some very roundabout ways you can cause it to change.
Here's how you can prove to yourself that the dictionary keeps getting recreated:
def print_3():
    print(3)

def do_sth():
    local_dict = {'a': print_3()}

do_sth()
do_sth()
do_sth()

This prints 3 ... 3 times.
I think global variables are fine for optimising this, but if you really want, how about this:
def do_sth():
    return do_sth.local_dict

do_sth.local_dict = {'a': print_3()}

Technically this can still be accessed by everyone but it's clearer what it belongs to.
Comment: You guys are overthinking this.
Comment: @TadhgMcDonald-Jensen I just did but there's really not that much to say. It's a very simple question.
Comment: @thebjorn indeed, it was just a little fun. I cannot believe how much thought everyone has put into this.
Comment: @m3diumendi4n just keep it where you have it (these are not the kinds of optimizations you should worry about in Python).
Comment: I really hope you plan on expanding this answer.
Comment: I liked it better without the second sentence. Perhaps a "It's created .." before the first sentence to give the sentence a subject..?
Comment: It took me a second read to figure out why this answer does answer the question. @AlexHall you mention modification but you're not really modifying anything (so it's confusing). The fact that it `print`s every time you call the function shows that it's creating the `dict` anew every time, that's just not clear from your wording around it.
Comment: @dwanderson I'm very sorry for your second.
Comment: No need for condescending sarcasm - people are saying your answer, while correct, isn't clear. Part of the point of these answers is to be as clear as possible.
Comment: @dwanderson I think it was just good-natured sarcasm (at least that's how I read it).
Comment: @dwanderson I meant no harm. I did edit the question after your comment, even before my reply.
Comment: Thank you for your answer. Could you share with me any tips on where I should place such "const" (hardcoded) dict to avoid creating it every time? Placing it as a global variable doesn't sound good to me because it's used in only one method.
Comment: @m3diumendi4n Also thebjorn is right, don't over-optimise.
Answer: Local variable are always created in the scope of a function. There are collected by the garbage collector once the program counter quits function (scope of the local variable).
global_dict = []

def do_sth():
    local_dict = { 'a': 1, 'b': 2, 'c': 3, ... }
    ...

def do_other_task():
   #local_dict not visible. It's outside of scope.
   global global_dict # fetch memory address of previously declared global_dict
   global_dict = { 'a': 1, 'b': 2, 'c': 3, ... }

Answer: it would be easy to check with the is operator:
def test():
    return {'a': 1, 'b': 2, 'c': 3}

>>> test() is test() #did both produce the same object in memory space?
False

This makes a lot of sense for mutable objects or the mutable default argument trap would come up everywhere.
However there are values that are stored as constants and those can be seen using dis as constants are loaded with the LOAD_CONST byte code:
>>> dis.dis(lambda:1)
  1           0 LOAD_CONST               1 (1)
              3 RETURN_VALUE
>>> dis.dis(lambda:(1,True, 10*1000, "a"))
  1           0 LOAD_CONST               7 ((1, True, 10000, 'a'))
              3 RETURN_VALUE
>>> dis.dis(lambda:[1,2,3]) #list is mutable
  1           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 LOAD_CONST               3 (3)
              9 BUILD_LIST               3
             12 RETURN_VALUE
>>> dis.dis(lambda:{"a":1}) #dict is also mutable
  1           0 LOAD_CONST               1 ('a')
              3 LOAD_CONST               2 (1)
              6 BUILD_MAP                1
              9 RETURN_VALUE

Answer: The other answers are correct, I would just add this.
I would rather do, in such case, either:
constant_dict = { 'a': 1, 'b': 2, 'c': 3, ... }
def do_sth():
    # do something reading constant_dict

do_sth()

or but less preferable:
def do_sth(local_dict = { 'a': 1, 'b': 2, 'c': 3, ... }):
    # do something reading local_dict

do_sth()

In both cases, python would not have to reallocate the memory for the variable, because it got declared and allocated when the interpreter reads the python file.
Correct me if I'm wrong.
Comment: It's the right thing to do when using it for memoization -- but use care with multiple threads, and again, with a comment, to let the next person know that you understood what you were doing.
Comment: you're wrong ;-)   don't use dicts as default arguments (at least not without a comment).  Python is also exceedingly fast at dicts, and comparably slow at using global variables, so I'm unsure if you would be saving any time...
Comment: I know that using dicts or lists as default args can be dangerous, and indeed do_smth() would have to be always called without args ;-)
Comment: It's not so much that it is dangerous, but the semantics are generally surprising to anyone who's used default arguments anywhere else. If the comment doesn't say something like "...is used to memoize.." most Python programmers would be concerned.
Comment: Yeah, I also would be concerned but I saw this many times in some famous third-party modules source code. Especially for memoizing a tree level during recursion, or iteration numbers, things like that.

Python local variable initialization


Custom commerce payment methods based on item

Question: In my Drupal commerce website, I have 2 payment methods, Payment Method #1, Payment Method #2
This is working just fine but the thing is I need to make it custom for a specific product type, for example if I'm selling Asus products, I want to get 40% pay with Payment Method #1 and the rest via Payment Method #2.
I'm not a module developer so I thought I can make it happen with some customization and/or rules.
I'd like to know if it's possible without module development,what's the best approach and how to do it properly.
thanks in advance.
Answer: An administrator can add two payment transactions to an order using different payment methods from the admin > order > payment area.
However an end-user normally selects a single payment method from the radio button form during checkout.
To support multiple payment methods you may need to send the customer through the payment step of the checkout twice, each time with a different amount and a different payment method selected.
Payment method selection is controlled by Rules logic and can be configured there.
The order status controls whether it can be sent through checkout again so may need to be set to the relevant checkout status.
The order amount to be paid may need to be set in custom code during the payment step process.
Comment: So what I get from your answer is that I send the user through Payment method #1, then redirect it back to paymenth method #2, am I correct? using rules and setting two payment transactions.

and for setting the percentage to be used for each of these payment methods must be done with custom code?
Comment: Yes, without knowing more about the payment methods and business logic, the two payment pages approach with Rules and some custom code is a reasonable solution and should work.


Puppet: Test if Resource is defined, or create it

Question: I've been trying to figure out a way to test if a resource is already defined in another file, and if not create it?  A quick example:
  if File[$local_container] {
    alert("Testing - It existed $local_container")
  } else {
    file{ "$local_container":
      ensure => directory,
    }
  }

However - File[$local_container] always seems to evaluate to true.  Is there a way to do this?
Answer: Do you mean "test if a resource is already defined"? If you define a resource (ie, file {}, etc) Puppet will create what you're describing if doesn't already exist (assuming you pass ensure => present, of course).
To check if a resource is already defined in the catalog or not:
mark-draytons-macbook:~ mark$ cat test.pp
file { "/tmp/foo": ensure => present }

if defined(File["/tmp/foo"]) {
  alert("/tmp/foo is defined")
} else {
  alert("/tmp/foo is not defined")
}

if defined(File["/tmp/bar"]) {
  alert("/tmp/bar is defined")
} else {
  alert("/tmp/bar is not defined")
}

mark-draytons-macbook:~ mark$ puppet test.pp
alert: Scope(Class[main]): /tmp/foo is defined
alert: Scope(Class[main]): /tmp/bar is not defined
notice: //File[/tmp/foo]/ensure: created

Note: defined() is dependent on parse order.
Comment: That "depends on parse order" part makes it almost useless.
Answer: The better way of doing this is by making use of ensure_resource function from puppetlabs stdlib
It takes a resource type, title, and a list of attributes that describe a resource as parameters.
say you have test case to only create the resource if it does not already exist-
ensure_resource('package', 'test-pkg', {'ensure' => 'present'})

Comment: This seems much cleaner, passing the checkmark this way.  Thanks for the tip!
Answer: Or....
unless File["${local_container}"] {
  file{ "${local_container}":
     ensure => directory,
  }
}

And do keep an eye on those quotes and curly braces....
Answer: simply,
file{ "$local_container":
  ensure => directory,
  replace => false,
}

Comment: Nope, if the `"$local_container"` file was already defined somewhere else (like say by something that wanted to control the permissions/owner) you can't define the same resource twice.


Find $\lim_{n\to\infty} 16^{(n/2) }/ 3^{2n+1}$

Question: I have problems with the following task: Find $\lim_{n\to\infty} 16^{(n/2) }/ 3^{2n+1}$.
I would start with taking the log an then dividing by n, however, then  I would end up with a false solution:
$$\lim_{n\to\infty} 16^{(n/2) }/ 3^{2n+1}$$  $$\lim_{n\to\infty}   (n/2)\ln(2) - (2n+1)\ln(3)= $$ $$\lim_{n\to\infty}   (1/2)\ln(2) - (2)\ln(3) - (1/n)\ln(3)= $$
$$ (1/2)\ln(2) - (2)\ln(3) $$
Thanks for your help!
Comment: the limit is $0$ because we can write the expression as $(1/3)(4/9)^{n}$.
Comment: How did you make $n$ disappearing (third expression) ?
Answer: Simplifying the expression,
$$\frac{16^{n/2}}{3^{2n+1}} = \frac{\left(16^{1/2}\right)^n}{3 \cdot \bigl(3^{2}\bigr)^n} = \frac{4^n}{3\cdot9^n} = \frac{1}{3}\left(\frac{4}{9}\right)^n$$
Therefore,
$$\lim_{n\to\infty}\frac{16^{n/2}}{3^{2n+1}} = \frac{1}{3} \lim_{n\to\infty}\left(\frac{4}{9}\right)^n = 0$$
since $0 < 4/9 < 1$.

Using logs isn't as nice, but if you suppose the limit is $L$, you'll get to an expression similar to this:
$$\lim_{n\to\infty} n(\ln 4 - 2 \ln 3) = \lim_{n\to\infty} n \ln (4/9) = \ln (3L).$$
Since $4/9 < 1$, it's natural log is negative and hence the left side goes to $-\infty$. Since
$$\lim_{x \to 0^+} \ln (x) = -\infty$$
we can conclude $3L = 0$, which implies $L = 0$.
Comment: Thanks! But woult it also possible to solve it with using ln?
Comment: @Methamortix I've edited in a log version.
Answer: Via logarithm:
$$\lim_{n \to \infty} \ln \left( \frac{16^{n/2}}{3^{2n+1}} \right) = \lim_{n \to \infty} \left( \frac{n}{2} \ln(16) - (2n+1) \ln(3) \right)
=\lim_{n \to \infty} n \left(\frac{\ln(16)}{2}-2\ln(3)\right)-\ln(3)=-\infty$$
since $\frac{\ln(16)}{2}-2\ln(3)<0$ and therefore $$\lim_{n \to \infty} \frac{16^{n/2}}{3^{2n+1}} = 0$$
Answer: Even if there are simpler solutions (as shown in answers and comments), you were almost on the right track.
Let me do it using you way considering $$a_n= \frac n 2\ln(2) - (2n+1)\ln(3)$$ and, as you almost did, factor the $n$ to get $$a_n= n\left(\frac 1 2\ln(2) - (2+\frac 1n)\ln(3)\right)$$ When $n$ become very large $\frac 1n$ becomes negligible when comared to $2$. This means that $$a_n \sim n\left(\frac 1 2\ln(2) - 2\ln(3)\right)$$ and the quantity inside brackets is negative. So $$\lim_{n\to\infty}a_n=-\infty\implies\lim_{n\to\infty}e^{a_n}=0$$
Comment: Thanks that really helped me to understand my mistake :)
Comment: @Methamortix. You are very welcome ! I am happy if you understood where was the mistake. Don't worry : you made it once; try to never repeat. Cheers :-)
Answer: $16^{n/2}/3^{2n+1}=4^n/9^n*3=\frac 13\frac  49 ^n $
So the limit is $0$


Piano: How to Internalize a Beat in One Hand?

Question: I am learning an to play this accompaniment while I sing "Counting Stars". I am having trouble internalizing the beat in one section, and as such I keep losing rhythm. Not just for this song, it is a more broad problem; a very common pattern in accompaniments is to syncopate the vocal melody (and often the chord) in a similar manner. The section in question is is this:

I haven't been able to internalize the beat and play four steady quarter notes in the left hand. I'm so focused playing and singing the sixteenth notes and off-beat eighth notes, that the bass just becomes another sixteenth division in my mind. And so the inflections are all wrong and the  unintended feel is that the beat is chasing the melody, rather than there being a steady beat.
I recorded the beat separately, and when I play that on loop I can play just the right hand and sing in perfect rhythm. Also, I can play the beat accurately while I sing, if I don't play the right hand. But when I actively have to play the [very simple] beat, with the rest, I get all messed up.
My question: what are some exercises I can do, or advise you could offer me, to improve on this?
Answer: I think your problem has to do with apposition. Once you've got the feel of the thing you shouldn't encounter this difficulty again. You need to know how it feels to play this kind of syncopation.
So.
Forget about your right hand for a minute.
1) Get your foot tapping in crotchets. Tap with the heel, not the toe.
2) Keep the foot going. Make all the LH notes crotchets. Don't bother with the C#s below the stave: leave them out for now. So you're just playing pinky - thumb - pinky - thumb. Loop that for a while.
Now your foot's tapping and your LH is playing pinky - thumb - pinky - thumb.
Keep that going and...
3) play and sing ||: "Take that"  2   3   4  :|| Play that for quite a while.
Now work your way through the music below, always counting the beats as shown. Do the repeats till you are both accurate and relaxed!
Then try the original again.
Your foot should never syncopate. It should stay regular and boring at all times!
Comment: What's the foot tapping for, wouldn't the left hand quarter note pulse be enough for dividing the other rhythms to manageable pieces? My first idea would have been just to do steady quarter notes with the left hand and then getting the right hand to learn more complicated rhythms as short split-down phrase segments. Doesn't the foot tapping add an extra distraction? Or is it for getting a metronome pulse, so an actual metronome could do the same? I tap my foot too when practicing, but I'm not sure if it actually helps ... I just do it for some reason.
Comment: I appreciate the effort you put into to creating that sheet bar by bar with all the components of the original. Great answer!
Comment: @piiperi Reinstate Monica I was thinking very specifically about this apposition thing. It is interesting. I've come across it in quite accomplished classical musicians and seen them determinedly stressing syncopated notes: throwing their whole weight into them and losing the pulse as a result. If the pulse can't be felt, passages like the OP's can be impossible to play. Maybe I over-emphasized the foot, but I was keen for him to feel the pulse as physically as possible, and keen to stop him tapping his foot in eighth notes in that fifth bar.
Comment: This is a great, great post. What's the reason for tapping with the heel instead of the toe? Seems like a marginal difference to me, and if you practice tapping with the toe, you are better preparing yourself to play the kick drum if you ever decide to take up drumset.
Comment: @Max Thank you, Max. It seems to me the heel has more thump and it makes the beat more solid and authoritative. The upper part of the leg lifts: not just the lower part. So it feels more physical. And if, by mistake, you tap on on a *syncopated* note, hopefully you'll *feel* something going wrong. [But all this could just be me: I've got quite small feet! They don't make a lot of noise.] Once the OP's got the problem solved he can tap with anything he likes. [If he switches to kit after all this I'll be livid!]
Answer: As cliche as it sounds, just start small, then build.
First, get the left hand perfectly down that you can do it in your sleep. Just practice it over and over again. This will help you internalize where the beat is.
Next, learn to sing the melody to a metronome. You can find a metronome online, which ticks at a steady beat. Figure out all the subdivisions and be able to sing it perfectly.
Then, play the left hand and sing at the same time. This should not be too different than the step before as the left hand is almost always playing quarter notes.
Then, learn to play the right hand perfectly to a metronome. Then add the voice.
Now, finally, after you can do all the above perfectly, set the metronome extremely slow, and play all the parts together. Just keep practicing it extremely slow until you have it perfect. Then start slowly speeding it up, and voila! You can play all of them together!
I hope that helps! Let me know if you need more clarification or help.


Product MarkUp with Excel Formula

Question: I have a list of product price that i need to markup.
I've tried using with Regular Formula

=A1*10%+A1+5,000 = 36,130 (A1 = 28,300)

Is there any way to remove the last 2 Digit and adjust the price if the price result is 36,130 it will remove the 30 (36,100) but if the price 36,160 it will adjust to 36,200 ?
Answer: Use:
=MROUND(<YourExpression>,100)

Comment: i tried but it didnt change anything, can you tell me in detail how that formula works please
Comment: If the outcome of your current expression is `36.130` then `MROUND()` will round that to it's nearest multiple of `0.100` so the outcome becomes `36.100`. @rullymnh. We are talking decimals though aren't we?
Comment: Not decimal, its a thousand. My bad for using (.)
Comment: Then just use `MROUND` and round to it's nearest `100`. @rullymnh
Comment: Alright now i understand, thanks for the help again!
Comment: Btw is there any way to combine both Formula =A1*10%+A1+5,000 and =MROUND(A1,100)
Comment: Offcourse Just use the first parameter to build your expression
Answer: In order to round up to a certain number of digits, this is what I usually do (example of 2 digits):
multiply by 100
round to the nearest integer
divide by 100 again
(use 1000 for 3 digits, ...)

For rounding, you might use the ROUND() worksheet function.
Comment: That would totally negate the fact that you could just use `MROUND()`. Sorry but I fail to see the logic here (with no ill intent)

Product MarkUp with Excel Formula


Porque a função após o map executa primeiro?

Question: Estou aprendendo um pouso sobre React, e esse tipo de situação já me ocorreu várias vezes, já procurei sobre async/await, promisses e coisas semelhantes, porém eu gostaria de entender o porque isso acontece e a maneira correta de se fazer.
Nesse código de exemplo eu quero montar um objeto onde um dos campos é um array de veiculos, no banco tenho 2 tabelas separadas, somente depois do map finalizado quero exeutar o res, deixei uns console.log para ver como esta sendo executado e a parte 2 executa primeiro que a 1, e eu acho que a forma que está o codigo está síncrono.
codigo:
app.get("/clientes", function(req, res){
   let filtro = [];
   let clientes = [];
   let ssql = 'SELECT * FROM CLIENTES';

   executeQuery(ssql, filtro, function(err, result){
       if(err){
           res.status(500).json(err);
       } else{
           clientes = result;
           clientes.map(cliente => {
               let ssql2 = 'SELECT * FROM VEICULOS WHERE CLIENTE_ID = '+ cliente.id;
               executeQuery(ssql2, filtro, function(err, result2){
                   if(err){
                       res.status(500).json(err);
                   } else{
                       cliente.veiculos = result2
                       console.log(1)
                   }
               });
           })
           console.log(2)
           res.status(200).json(clientes)
       }
   });

});

Porque o resultado fica 2,1,1 no console e não 1,1,2? No caso me retornando clientes vazio pois ainda nao executou o map
Answer: Porque o map é uma Promise e voce nao está aguardando ela terminar para continuar.
para executar na ordem que voce quer:

Colocar o map em volta de uma Promise e declarar o iterador como async.

Ficaria mais ou menos assim:
else{
       clientes = result;
      await Promise.all(clientes.map(async cliente => {
           let ssql2 = 'SELECT * FROM VEICULOS WHERE CLIENTE_ID = '+ cliente.id;
           executeQuery(ssql2, filtro, function(err, result2){
               if(err){
                   res.status(500).json(err);
               } else{
                   cliente.veiculos = result2
                   console.log(1)
               }
           });
       }))
       console.log(2)
       res.status(200).json(clientes)
   }

Mas, sendo sincero, voce nao deveria estar usando Array.map, deveria estar usando for...of: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/for-await...of
map só deve ser usado quando o retorno do map vai ser utilizado.
Comment: Obrigado pelo retorno, mas mesmo com o await continua executando o res primeiro que o map, colocando um timeout apos o map resolve, por isso me confundo ainda com essas promise, pra mim com o await seria obrigado esperar o map terminar, vou ver sobre o for await of, obrigado.
Comment: **map é uma Promise?** Você tem certeza disso? Poderia por favor mostrar na documentação [`Array.prototype.map()`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map) onde está escrito o que afirma?
Comment: O map async retorna um array de promises na verdade. Colocando esse array dentro de um Promise.all(), o problema do rapaz é solucionado.
Comment: O await só declara que é uma Promise. É necessário o Promise.all() em volta do map.


Get label names from loaded model in sklearn

Question: Is it possible to get the label names from an sklearn SGDClassifier model that is loaded from a pickle file?
model = pickle.load(open("saved_model.pkl", 'rb'))
y_pred = model.predict(x)

Because all the labels may not be present in the input vector, x, how can I know what the possible labels are?
Answer: model.classes_ will show the labels in the model. This is a public attribute of SGDClassifier object.
Reference
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Populate $form_state['values'] with defaults from drupal_get_form()

Question: I'm looking to resave a form's defaults values. In core the test module uses drupalPost() to test the form so I'm thinking this will be custom code.
Answer: This is the function I've come up with.
<code>/**
 * Given a form get the default values from it.
 *
 * @param array $defaults
 *   An empty array used to populate the default values.
 * @param array $form
 *   The form returned from drupal_get_form().
 * @param string $parent_key
 *   The key name of the parent.
 */
function get_defaults_from_form(array &$defaults, array $form, $parent_key = '') {
  foreach (element_children($form) as $key) {
    $values = $form[$key];
    if (isset($values['#value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#value'];
      }
    }
    elseif (isset($values['#default_value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#default_value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#default_value'];
      }
    }
    elseif (is_array($values)) {
      // Go deeper if needed.
      get_defaults_from_form($defaults, $values, $key);
    }
  }
}
</code>
Use it like this:
<code>$theme_name = 'seven';
// Load the required file for the form functionality.
$router_item = menu_get_item('admin/appearance/settings/' . $theme_name);
if ($router_item ['include_file']) {
  require_once DRUPAL_ROOT . '/' . $router_item ['include_file'];
}
// Get the form for this theme.
$form = drupal_get_form('system_theme_settings', $theme_name);
// Get the defaults.
defaults = array();
get_defaults_from_form($defaults, $form);
print_r($defaults);
</code>
Comment: +1 for nice approach. But why is there a str_replace? Also, shouldn't it be looking up the `#parents` prop to add data?
Comment: I thought I would have needed the str_replace but with further testing it was not needed. I've removed that from the answer. I could use #parents instead of $parent_key; is that what you mean?
Comment: Sorry my bad (about the #parents). Your answer handles it well. In drupal_get_form()'d form array contains #parents with all the nested with #tree and everything processed.


How to call an external API url with parameter in flask?

Question: I'm a bit struggling while calling an external URL including a parameter from my flask application (route) to external web application.
In a terminal window I call the API using CURL (which is working):
curl https://api.mytimestation.com/v1.1/employees/{emp_yj7n80o} -u myapikey:

I try to use this in a Flask route to get data from that external URL in order to process it and use it in my own Flask application.
Started using REQUESTS module but can't get it working due to:

HTTPS error
data field seems to be faulty

Tried so far:
import requests

r = requests.post('https://api.mytimestation.com/v1.1/employees/{emp_yj7n80o}', data={'-u myapikey:'})

Anyone that can help me with some tips on how to progress?
Many thanks in advance!
Answer: It turns out I was already heading to the solution. Had to make some changes in order to make it work.
Sharing the solution, so anyone searching for same problem this post can be helpful.

-

To start with I have to:
1. replace the POST with GET, kind of obvious since I intent to retrieve information. (https wasn't any problem originally)

Add BASIC HTTP authentication to the REQUESTS object. And replace the user object with the API key.

Code then looks like:
import requests
url = 'https://api.mytimestation.com/v1.1/employees'
x = requests.get(url, auth = ('myAPIkey', ''))
print(x.text)


UIScrollView With next and previous button Action

Question: i am new in iphone,i am using horizontal scrollview these are horizontally scrolling properly
  but i want these horizontally scrolling on previous and next button action.please help me asap.
Thanks:)
Comment: What do the next and previous buttons do?
Comment: I guess he means scroll buttons.
Answer: Here are the steps that was worked for me
in .h file write following code.
int scrollMove;
UIScrollView *aScrView;

-(IBAction)nextBtnAction:(id)sender;
-(IBAction)previousBtnAction:(id)sender;

in .m file
- (void)viewDidLoad
{
[super viewDidLoad];

scrollMove=50;

aScrView=[[UIScrollView alloc]init];
aScrView.frame=CGRectMake(25,50, 270, 50);
aScrView.delegate=self;
aScrView.contentSize=CGSizeMake(1200, 0);

[self.view addSubview:aScrView];

// Do any additional setup after loading the view from its nib.
}

-(IBAction)nextBtnAction:(id)sender{

 float coordinate = 2.0f;
 //scrollMove=50;
 [aScrView setContentOffset:CGPointMake(scrollMove * coordinate, 0) animated:YES];
 scrollMove=scrollMove+50;

 }
-(IBAction)previousBtnAction:(id)sender{
float coordinate = 1.0f;

[aScrView setContentOffset:CGPointMake(scrollMove * coordinate, 0) animated:YES];
scrollMove=scrollMove-50;
}

Hope this helps you!!!
Answer: Use this one when you want to go on next visible content of Scroll view:
(Put this one inside next button method)
float coordinate = 2.0f;
[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];

move on previous visible content view:
float coordinate = 1.0f;

[nodeScrollView setContentOffset:CGPointMake(460 * coordinate, 0) animated:YES];

(Put this one inside previous button method)
**You need some mathematical calculation with coordinate
Comment: Thanks i have implemented ur code that was successful, button actions are performed only one time and i want after one time click go to one page and again click go second page and same thing on previous button action.so plz help me asap. thanks in advance.
Answer: CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];

Answer: - (void)viewDidLoad
{
    x=0;
    y=320;
}

- (IBAction)next:(id)sender

{
    y=320;
    [scrl_Knot setContentOffset:CGPointMake(x+320,0) animated:YES];
    x+=320;

}

- (IBAction)pre:(id)sender

{

    x=0;
    [scrl_Knot setContentOffset:CGPointMake(y,0) animated:YES];
    y-=320;

}

Answer: - (IBAction)pre:(id)sender
{
    btnNext.enabled = TRUE;
    imageID--;
    [scrl_venuelist setContentOffset:CGPointMake(imageID*273, 0) animated:YES];
    pagecontrol.currentPage=imageID;
    if(imageID <= 0)
    {
        btnPrevious.enabled = FALSE;
    }
}
- (IBAction)next:(id)sender
{
    btnPrevious.enabled = TRUE;
    imageID++;
    [scrl_venuelist setContentOffset:CGPointMake(imageID*273, 0) animated:YES];
    pagecontrol.currentPage=imageID;
    if(imageID >= imageArr.count-1)
    {
        btnNext.enabled = FALSE;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
{
    imageID = scrollView.contentOffset.x / scrollView.frame.size.width;
    pagecontrol.currentPage=imageID;

    if(imageID <= 0)
    {
        btnPrevious.enabled = FALSE;
        imageID = 0;
    }
    else
    {
        btnPrevious.enabled = TRUE;
    }

    if(imageID >= imageArr.count-1)
    {
        btnNext.enabled = FALSE;
        imageID = imageArr.count-1;
    }
    else
    {
        btnNext.enabled = TRUE;
    }
}

- (void)viewDidLoad
{
    scrl_venuelist.delegate=self;
    scrl_venuelist.contentSize =CGSizeMake(273 * [imageArr count], 137);
    if(imageID == 0)
    {
        btnPrevious.enabled = FALSE;
        if(imageID == imageArr.count-1)
        {
            btnNext.enabled = FALSE;
        }
    }
    else if(imageID == imageArr.count-1)
    {
        btnNext.enabled = FALSE;
    }
    else if(imageID > imageArr.count-1)
    {
        imageID = [imageArr count]-1;
    }
    scrl_venuelist.pagingEnabled=YES;
    pagecontrol.numberOfPages=[imageArr count];
    pagecontrol.currentPage=0;
}

Answer: If Any one Looking for way of doing in C# for Xamarin
    public int CurrentIndex
    {
        get => (int)Math.Round(this.scrollView.ContentOffset.X / this.scrollView.Frame.Width);
        set => this.scrollView.ScrollRectToVisible(new CGRect(new CGPoint(this.scrollView.Frame.Size.Width * value, 0), this.scrollView.Frame.Size), true);
    }

This getter and Setter should provide you current page as well let you scroll to the specified page
On Button Actions Just Update Current Index to new Values, Which could current Index +1/-1.


Load Balancing VPN servers (Ubuntu)

Question: I am trying to load balance two VPN servers, that are located quite far from one another.
I am using Ubuntu with pptpd, is there anyway to load balance those two servers? So user connects pptp to the load balancer then that routes it to one of the other two servers?
Answer: Since HAProxy only has layer 4 (TCP) and layer7 (HTTP) modes, it can't handle the GRE tunnels that PPTP controls.
So in short, you can load-balance the control channel (with TCP mode), but not the actual tunnels.

Load Balancing VPN servers (Ubuntu)


In my checkboxes if i have a 0 value it select this checkbox

Question: I have in my form a type 'checkboxes' form.
<code>    // Form for the severity checkboxes.
    $kkkk_severity_levels = variable_get('kkkk_severity_levels', array());

    // Declare empty options array.
    $kkkk_severity_options = array();

    // Loop through each severity level and push to options array for form.
    foreach (watchdog_severity_levels() as $number_select => $severity) {
      $kkkk_severity_options[$number_select] = drupal_ucfirst(
        $severity);
    }

    // Checkboxes form.
    $form['kkkk_severity_levels'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Type of log messages'),
      '#options'       => $kkkk_severity_options,
      '#default_value' => array_values($kkkk_severity_levels),
      '#required'      => TRUE,
    );
</code>
In these lines of code the watchdog_emergency has a key 0 so when i select something from checkboxes i take selected also emergency always as it gets me out : e.g if i select 'info' with key 6 it gets me out:
<code>6 (String, 1 characters ) 6
0 (Integer) 0
1 (Integer) 0
2 (Integer) 0
3 (Integer) 0
4 (Integer) 0
5 (Integer) 0
</code>
7 (Integer) 0
and so it selects also the 'emergency' with key as 0... How I can solve this problem?
Answer: That's how the form API handles multiple selections for form elements.
You can easily solve it with standard language features:
<code>$selected = array_filter($form_state['values']['kkkk_security_levels']);
</code>
Comment: where i will do that line of code?
Comment: In the submit handler.
Comment: i did it but it also selects the emergency :'(
Comment: Nope, it doesn't. `array_filter()` will remove all elements that have a value of zero, which every element in the array you put in your question has. I suspect your issue is somewhere else


Git submodules commit

Question: I have an android project thats has a submodule inside.Its all under GitHub.
I am making changes on the main as well as on the sumbmodule.
What is the best strategy to use?
1.Create a new branch (do I have to make a new branch on both the main as on the submodule )
2.Do changes.
3.Commit&Push.
I would like to commit all changes at the same time main and submodule.
Comment: Commit first in you submodule. Then commit in your project. The parent project stores the commit of the submodule, so if you pull the parent project in another directory, you will always game the same version of the submodule, even if there are new commits in the submodule. Until you commit the parent module.
Answer: It's better to ensure that each commit includes and expresses only single changes you've made, so if there aren't actual connections between the changes of both modules, I suggest that you don't commit only once, but make multiple commits - at least twice - instead.

Git submodules commit


Meteor: set context inside template if context exists

Question: I have the problem that I want to render the same form template for a /edit/:id-route and a /add-route. Latter should provide the form with empty inputs, the first should populate the input fields with existing attributes of an object, let's say it's a Post.
Keeping it DRY I don't want to copy paste the template into a new one.
To achieve this I did the following:
<template name="addOrEditPost">
  {{#if this.post}}
    {{#with this.post}}
  {{/if}}
  <form>
    <input type="text" value={{#if name}}{{name}}{{/if}} ...>
    ...
  </form>
  {{#if this.post}}
    {{/with}}
  {{/if}}
</template>

My idea was, to only give the template a context, if the context itself exists (if it exists, we're in 'edit'. If not, we're in 'add').
But this leads into
=> Errors prevented startup:

While building the application:
client/views/admin/addPost.html:6: Expected tag to close with, found if
...{#with this.post}}   {{/if}}   <form id="...
^

So how can I achieve this without duplicating the whole template and form? Thanks in advance!
EDIT:
I have to mention that it is working without {{with}}-context: When I write
<input type="text" value={{#if this.post.name}}{{this.post.name}}{{/if}} ...>

it is working. But still, a context would be much cleaner since the form has about 50 input fields...
Answer: Ok, I came up with a solution by my own:
<template name="addOrEditPost">
  {{#if this.post}}
    {{> form this.post}}
  {{else}}
    {{> form}}
  {{/if}}
</template>

If there is a Post, I can call its attributes with {{whatever}} inside the form-template because this.post is passed as an argument to the template and serves as its context.
If you have ideas how to still improve this, please share your thoughts. Thanks.


Is it bad to create different classes for REST request and response?

Question: I'm working in a Spring Boot project, as my implement at the moment, almost for each API I have request and response classes.
For example:
@RequestMapping(value = "/notice", method = RequestMethod.POST)
public AddNoticeResponse addNotice(@Valid @RequestBody AddNoticeRequest){
    Notice notice = ... // creating new notice from AddNoticeRequest
    noticeRepository.save(notice);
    AddNoticeResponse response = ... // creating new response instance from Notice
    return response;
}

The request and response classes look like:
@Data
@AllArgsConstructor
public class AddNoticeRequest{
    private String subject;
    private String message;
    private Long timeToLive;
}

// Ommiting some annotations for brevity
public class AddNoticeResponse{
    private String subject;
    private String message;
    private Long timeToLive;
    private Date createTime;
    private String creator;
}

I have two problems.

Creating too many classes and naming them some times made me nuts.
Some request and response have common fields.

For example: There's two kind of Notice: Email and Notification:
public class Email {
    private String subject;
    private String message;
    private String receiver;
}

So, should I use an inner class that extends the common class or just put all the fields into one class? Which is better?
public class AddNoticeRequest {

    private String subject;
    private String message;

    class Email extends AddNoticeRequest{
        private String receiver;
    }
}

public class AddNoticeRequest{
    private String subject;
    private String message;
    private Long timeToLive;
    private String receiver;
}

Then when the client performs a request to add an Email notice, will some fields be null?
Answer: Using tailored DTOs for request and response will give you more flexibility in the long run. Actually, nothing prevents you from using inheritance and inner classes, but I would just avoid it.
I already answered a similar question here, highlighting the benefits of using DTOs over persistence entities in REST APIs. Below you'll find a few benefits of this approach:

DTOs can be tailored to your needs and they are great when exposing only a set of attributes of your persistence entities. You won't need annotations such as @XmlTransient and @JsonIgnore to avoid the serialization of some attributes.
By using DTOs, you will avoid a hell of annotations in your persistence entities, that is, your persistence entities won't be bloated with non persistence related annotations;
You will have full control over the attributes you are receiving when creating or updating a resource;
If you are using Swagger to document your REST API, you can use @ApiModel and @ApiModelProperty annotations to document your API models without messing your persistence entities;
You can have different DTOs for each version of your API;
You'll have more flexibility when mapping relationships;
Your DTOs can have a list of links for HATEOAS. That's the kind of thing that shouldn't be added to persistence objects.
You can use mapping frameworks such as MapStruct to map your REST API DTOs from/to your persistence objects.
Answer: Don't subclass the req/resp objects.
Use an auto de/serialiser like Jackson in your frame work to convert message payloads into business object.
However, you will still end up with a large number of business objects.
Answer: I will suggest you to use JSON format instead of creating class and returning its instance every time. But still if you need a class hierarchy you can create a class and put a variable which will store JSON.


Kafka Streams: Delay processing after rebalancing

Question:
I have Kafka Streams Application that reads from a topic with 50 partitions. The application aggregates data for a specific key and writes it into a state store. Therefore it is important, that the same key is always written to the same partition. This works well. When the traffic is high, I create n new instances of my app. Then, of course, rebalancing happens and the consumer-to-partition assignment changes. The problem is, that the rebalancing is happening multiple times within seconds, each time when a new consumer is added to the consumer group.
<code>{"timestamp":"2023-03-24T08:30:25.779Z","message":"Application state changed from RUNNING to REBALANCING"}
{"timestamp":"2023-03-24T08:30:37.438Z","message":"Application state changed from REBALANCING to RUNNING"}
{"timestamp":"2023-03-24T08:30:37.471Z","message":"Application state changed from RUNNING to REBALANCING"}
{"timestamp":"2023-03-24T08:30:37.598Z","message":"Application state changed from REBALANCING to RUNNING"}
{"timestamp":"2023-03-24T08:30:40.897Z","message":"Application state changed from RUNNING to REBALANCING"}
{"timestamp":"2023-03-24T08:30:41.073Z","message":"Application state changed from REBALANCING to RUNNING"}
{"timestamp":"2023-03-24T08:30:41.270Z","message":"Application state changed from RUNNING to REBALANCING"}
{"timestamp":"2023-03-24T08:30:41.333Z","message":"Application state changed from REBALANCING to RUNNING"}
</code>
Problem: After the first rebalancing, the consumer starts to consume and aggregate messages from the new partition. A short time after that it is again rebalanced and the consumer is allocated to another partition. Then the aggregation for a specific key is "lost" and the new consumer (and state store) allocated to this partition starts from beginning.
Question: Is it possible to tell kafka "delay processing of new messages after rebalancing for n seconds, to make sure that the whole rebalancing process in finished"?
Answer: The only configuration that comes close to what you're looking for is the
group.initial.rebalance.delay.ms, but this configuration only takes effect for a new group, not an existing one where more members have been added.
But you need to remember that Kafka Streams uses a changelog to back state stores.  This means that when a task gets assigned to a new host, that host will restore the state store to the last record in the changelog, so it's not starting over from scratch but from the latest record in the changelog.
Comment: Thank you. Unfortunately I cannot make use of the state store logging functionality because I disabled it to speed up startup time of the app as I have a lot of data.


ValueError: unsupported format character 'a' (0x61) at index 55 with URL string

Question: Attempting to send a URL and hostName into a database with the following code:
def sendToDatabase(self, case, filename):
103         ext = os.path.splitext(filename)[1]
104         filenoext = filename.strip(ext)
105         url = "https://apses4859.ms.ds.uhc.com:10943/rest/download/C%3A/IBM/ISA5/ISA5/isa/cases/%s/%s-analyzer_ISA_PD/%s_Leak_Suspects/index.html" % (case, filename,filenoext)
106         cursor = connection.cursor()
107         m = re.search(r"([^.]*)", filename)
108         hostname = m.group(1)
109         query = "INSERT INTO StoryData (hostName, reportName) VALUES (%s, %s)"
110         cursor.execute(query , (hostname, url))
111         connection.commit()
112         cursor.close()

It's not liking the A next to %3A for some reason. I've tried adding an extra % in and it still doesn't affect it. Not quite understanding why I'm getting this error.
Comment: I tried it, too, and it worked OK for me. (`%%3A` instead of `%3A`)
Answer: %3A is being interpreted as a formatting string, and there's no A format. Better switch to new-style formatting, ie. using format method instead of % operator:
url = "https://apses4859.ms.ds.uhc.com:10943/rest/download/C%3A/IBM/ISA5/ISA5/isa/cases/{}/{}-analyzer_ISA_PD/{}_Leak_Suspects/index.html".format(case, filename,filenoext)


teamcity github ssh connection hangs

Question: Using windows 8.1, teamcity 8.1.1, and github.
Used instructions from here in conjunction with git extensions (git bash).
Uploaded the id_rsa.pub to my github account, uploaded the id_rsa to teamcity.
In the VCS setup screen, I used the ssh clone url, selected uploaded key, entered in my github username, and my passcode (same as my github password).
The test connection will always hang, and trying to go ahead and run a build will cause the agent to hang.
Answer: To make this work, use git as the username.

teamcity github ssh connection hangs


Is there any way to add the css class to tinymce inside wysiwyg editor

Question: I have several classes defined inside style.css, I want tinymce to recognize these classes. Below is the popup to configure hyperlinks. It also provide a way to use css styles defined already.

I am looking for a way to add the css class to tinymce inside wysiwyg editor in Drupal 7.
Comment: Which module you are using? tinymce or wysiwyg?
Comment: @JimmyKo: module is `wysiwyg` and library is `tinymce`
Comment: What is the version of tinymce?
Comment: @JimmyKo: Version 3.5.11
Comment: I have updated my answer. Please try.
Answer: As you are using wysiwyg module with tinymce library. You should implement the alter function provided by wysiwyg module to add the editor settings.
For tinymce 4.x:
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['link_class_list'] = array(
      "Class Example" => "class-example",
    );
  }
}

For tinymce 3.x:
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['theme_advanced_styles'] = array(
      "Class Example" => "class-example",
    );
  }
}

References

documentation of tinymce 4.x
documentation of tinymce 3.x
API of wysiwyg


Laravel banco de dados

Question: Fala galera blz gostaria se é possível configurar no arquivo .env do laravel, colocar dados de um banco de dados que está no firebase e trabalhar localmente no projeto?
Answer: O laravel por default não suporta conexões com o firebase, não é igual fazemos a conexão pelos drivers do próprio laravel para mysql por exemplo.
Aconselho que utilize o pacote "kreait/firebase-php" (https://firebase-php.readthedocs.io/en/latest/), com ele você conseguirá fazer a conexão com o firebase e trabalhar normalmente. Na própria documentação te ensina um passo a passo para configurar.

Laravel banco de dados


What does the great common divisor mean for this proof?

Question: Theorem 1:  $\sqrt {2}\notin \mathbb{Q}$ .
Proof.
Suppose for a contradiction that $\sqrt {2}\in \mathbb{Q}$. So we have $Q = p/ q \ $ for $p\in \mathbb N$ and $q\in \mathbb N^{\ast}$.
with $\mathrm{gcd}(p, q) = 1$, because we can always represent a fraction so that the numerator and the denominator share no common factor.
Now, $$p/q=\sqrt {2}=p^{2}/q^{2}=2\Rightarrow p^{2}=2q^{2}$$
and $p^2$ is an even number. We have then that p is also even, by well known theroem (We take it for granted here). Let $k \in N$ be such that $p = 2k$.
Because $p^{2}=2q^{2}$ and $p = 2k$, we have $\left( 2k\right) ^{2}=2q^{2}\Rightarrow 4k^{2}=2q^{2}\Rightarrow 2k^{2}=q^{2}$  and $q^2$ is even. We now have that $q$ is even, by the same theorem we take for granted here. As a consequence, $\gcd(p, q) \geq 2$ and $p, q$ are not relatively prime, for a contradiction. ■
I am not sure I understand where the proof is getting at. My intuition is that because the gcd is not = 1 therefore we can't have a rational number. Can someone explain what the gcd (great common divisor) means for the proof?
Comment: Any rational number can written in the form $\frac{p}{q}$ where $p\in\mathbb{Z},q\in\mathbb{N}$ and $\gcd(p,q)=1$. So we assume $\sqrt{2}$ is rational and write it in that form. But then we get that it implies that both $p$ and $q$ are divisible by $2$. This is a contradiction to their $\gcd$ being $1$.
Comment: It means $\frac pq$ is in "lowest terms"  So if $p$ is even then $q$ can not be (and vice versa).  If $\frac {p^2}{q^2}= 2$ then $p^2 = 2q^2$ and so $p$ is even.  So $p = 2p'$ and $4p'^2 = 2q^2$ and so $2p'^2 = q^2$.  So $q$ is also even.  But that's impossible if $\frac pq$ were in lowest terms.  So it is impossible to have $(\frac pq)^2 = 2$ for any fraction in lowest terms. But *all* rationals can be put in lowest terms.  So $q^2 = 2$ is impossible if $q$ is rational.
Comment: "My intuition is that because the gcd is not = 1 therefore we can't have a rational number."  You *can*, but if $\gcd(p,q)\ne 1$ then $\frac pq$ is not in "lowest terms".  So we have $p=k\gcd(p,q)$ and $q=j\gcd(p,q)$ and we should use $\frac pq=\frac kj$ instead.  *NOW* we have a rational in lowest terms.  And yet... if $(\frac kj)^2=2$ we can prove they *aren't* in lowest terms.
Answer: The idea behind the proof is that you assume that $gcd(p,q) = 1$ and that leads to a contradiction since you show that the $gcd(p,q) \geq 2$.
Answer:
Now, $$p/q=\sqrt {2}=p^{2}/q^{2}=2\Rightarrow p^{2}=2q^{2}$$

The second equality sign should be implies
$$\frac pq=\sqrt {2}\implies \frac{p^2}{q^2}=2 \implies p^{2}=2q^{2}$$

My intuition is that because the gcd is not $= 1$ therefore we can't have a rational number. Can someone explain what the gcd (great common divisor) means for the proof?

As the start of the proof you assume that $\sqrt {2}\in \mathbb{Q}$. This means that there exists $p\in\mathbb Z,q\in\mathbb N$ such that
$$\sqrt{2}=\frac p q$$
where $\frac pq$ is in the lowest possible terms and $q\neq 0$. Now, what does lowest possible terms mean? Consider the rational number
$$\frac{36}{10}$$
this rational number is not in lowest possible terms as it can be rewritten as
$$\frac{36}{10}=\frac{18}{5}$$
therefore, by our assumption that $\frac p q$ is in lowest possible terms we also satisfy the condition that
$$\text{gcd(p,q)}=1$$
since if this wasn't true we would reduce $\sqrt{2}=\frac{p}{q}$ down to a $\tilde{p}\in\mathbb Z,\tilde{q}\in\mathbb N$ such that $${\text gcd(\tilde{p},\tilde{q})}=1$$

Because $p^{2}=2q^{2}$ and $p = 2k$, we have $\left( 2k\right) ^{2}=2q^{2}\Rightarrow 4k^{2}=2q^{2}\Rightarrow 2k^{2}=q^{2}$  and $q^2$ is even. We now have that $q$ is even, by the same theorem we take for granted here. As a consequence, $gcd(p, q) \geq 2$ and $p, q$ are not relatively prime, for a contradiction.

Your proof shows that both $p$ and $q$ are even and therefore the greatest common divisor between them is greater than or equal to 2.
$$\text{gcd(p,q)}\ge 2$$
By definition, if $p$ is even then
$$p=2k,~~k\in\mathbb Z$$
and if $q$ is even then
$$q=2m,~~m\in\mathbb Z$$
so that
$$\text{gcd(p,q)}=\text{gcd(2k,2m)}\ge2>1$$
which is a direct contradiction to the initial assumption that
$$\text{gcd(p,q)}=1$$
Answer: The thing is that if $\gcd(p,q) = d\ne 1$ then we will have $p=kd$ and $q = jd$ for some $k,j$.  And so $\frac {p}{q} = \frac {kd}{jd} = \frac kj$ and $\frac pq$ was not in "lowest terms".
So we might as well assume that $\gcd(p,q) =1$ and that $\frac pq$ is lowest term.
The assumption is every rational $q$ can be expressed as $\frac {p}{q}$ where $p$ and $q$ are in lowest terms.  The text is taking that for granted.[1]
So if $m^2 =2$ and $m =\frac pq$ and $p,q$ are integers AND $\frac pq$ is in lowest terms then........
$\frac {p^2}{q^2} =2$
$p^2 = 2q^2$
$2|p^2$ and so $2|p$ so there is a $k$ so that $p = 2k$ so
$4k^2 =2q^2$
$2k^2 =q^2$
$2|q^2$ and so $2|q$.  So $2|p$ and $2|q$ so..... $\frac pq$ wasn't in lowest terms.
So we either have a rational that can never be expressed in lowest terms [1], or there's some other type of "irrational" number that $m$ could be, or there's no possible number so that $m^2 = 2$[2].
....
[1] We can prove it.  If $r$ is rational there are two integers,$p,q$ so that $r = \frac {p}{q}$ if $\gcd(p,q)=d\ne 1$ then $p=kd$ and $q=jd$ for some $k,j$ and $m = \frac pq =\frac kj$.  And $\gcd(k,j)$ DOES equal $1$.
Why.  Because $\gcd(k,j)|k$ and $\gcd(k,j)|j$ so $d*\gcd(k,j)$ divides $p$ and divides $q$.  So $d*\gcd(k,j) \ge \gcd(k,j)$ and a common divisor.  But $d$ was the greatest common divisor.  So $\gcd(k,j) =1$.
And $m =\frac kj$ and is in  "lowest terms".
[2]  But if we take square of side $1$.  That's got to be possible.  And we take its diagonal.  That's got to be possible.  ANd we call the length of the diagonal $m$. The diagonal has to have some length. And we use the Pythagorian Theorem.  That P.T. is true, isn't it.  Then $1^2 + 1^2 = m^2$ or in other words: $m^2 =2$.
Hmmmm.


Windows Server 2008 Migration - Did I miss something?

Question: I'm running in to a few complications in my migration process. My main role has been a Linux / Sun administrator for 15 yrs so Windows server 2008 environment is a bit new to me, but understandable.
Here's our  situation and reason for migrating...
We have a group of developers that develop VERY low-level software in Visual C with some inline assembler.  All the workstations were separate from each other which cased consistency problems with development libraries, versions, etc...
Our goal was to throw them all on to a Windows domain were we can control workstation installations, hot fixes (which can cause enormous problems), software versions, etc...
All Development Workstations are running Windows XP x32 (sp3) and x64 (sp2)
I running in to user permission problems and I was wondering maybe I missed one, tWO or a handful of things during my deployment.
Here is what I have currently done:

Installed and Activated Windows Server 2008
Added Roles for DNS and Active Directory
Configured DNS with WINS for netbios name usage
Added developers to AD and mapped their shared folders to their profile
Added roles for IIS7 and configured the developers SVN
Installed MySQL Enterprise Edition for development usage

Not having a firm understanding of Group Policy I haven't delved deeply in to that realm yet.
Problems I'm encountering:
1. When I configure any XP workstations to logon our domain, once a user uses their new AD login, everything goes well, except they have very restrictive permissions. (Eg: If a user opens any existing file, they don't have write access, except in their documents folder.) Since these guys are working on low system level events, they need to r/w all files. All I'm looking to restrict in software installations.

Am I correct to assume that I can use WSUS to maintain the domains hot fixes and updates pushed to the workstations?
I need to map a centralized shared development drive upon the users login. This is open to EVERYONE. Right now I have the users folders mapped upon login through their AD profile. But how do I map a share if I've already defined one within their profile in AD?

Any responses would be very grateful.

Do I have to configure and define a group policy for the domain users?
Can I use Volume Mirroring to mirror / sync two drives on two separate servers or should I just script a rsync or MS Synctool?  The drives simply store nightly system images.
Answer: I don't see anything wrong with what you have done to setup the domain. It seems like you just need a fairly basic setup, and that is what you have running right now.
First your problem with the developers:
The behavior of them having very restricted access is AD working as designed. By default when you join a domain the following happens to your local computer groups:

AD Domain & Enterprise admin groups are added to the local admins group
AD Domain Users are added to the local users group

So all of your users are (correctly) in the Domain Users group, and only have normal user level access to the workstations.
As far as a solution. That gets a little bit tough, especially when dealing with low level access on a windows system and could depend on when they have issues. Is it when they try to test run the program? Is it when they try to access certain files on the drive while developing?
A few possible solutions I can think of:

Make them part of the "Power Users" group on their local machines. That would allow them to have a higher level of access without being full administrators
Use Process Explorer to figure out what files/directories they are getting hung up on and give them permissions to just those items
Install VMWare workstation, and give them a base image that they can make a copy of then get rid of the copy after they done so they are always working off the same base image (awkward and probably not too feasible but i can't remember if VMWare workstation lets you do snapshotting)

Now on to your questions. I'll take them a little bit out of order, mostly because the answer to 3 or the 4 of them is to learn to use and love group policy. IMHO Group Policy is the killer app in a windows network. I'm not going to delve too deeply in how to set these things up in group policy as that is a little to far reaching for this question - but please search around this site, and ask questions there are a lot of smart people and good information on group policy here.
As far as WSUS goes yes, it will allow you to configure just about every aspect how how WSUS delivers updates to the machines. The actual authorizations for the patches are done via the WSUS interface.
For the drive mappings, my personal preference is to not use the the setting in their AD user object. As you have already found out it is very inflexible. You can do one of two things, both with group policy:

Setup a batch file that maps all of the users drives that you want to map and put it in <code>\\<domain>\NETLOGON\<script_name></code> and assign it as a logon script in group policy.
Use the managed preferences (I apologize i forget the exact name off the top of my head) user policies in the GPO to set the mapped drives

With your system images i would go ahead and use rsync if you are comfortable with it DeltaCopy is a windows port that is a little bit more windows friendly. I would stay away from sync toy as i've found it to be pretty slow at large copies. If you want another option you could use robocopy or richcopy and script a scheduled task to copy the files over each night.
Comment: Thank for your comments as well.  With both of you guys experienced help I been able to resolve a couple issues as well as targeting what needs to be done next.  Thank you very much, your help is very appreciated and MERRY CHRISTMAS!
Comment: DeltaCopy is a great solution.  Being a *nix guy rsync is a preferred option however I'm generally skeptical on application ports from platform to platform.  I think I'm going with Deltacopy.  Thanks for the suggestion.
Answer: Ok so... I'm just going to tackle things as I see them.  The first thing is add a group for all of your developers, and obviously put them all in it.  Then on the local machines add that group to the appropriate local group.  What I mean is - if you want them to be administrators add the Developer group you created in AD to the local administrator group (or power users, or wherever you want it).  If you want to drill even further down as to what they do/don't have control over you'd have to use group policies for it.
You are correct to assume that you can use WSUS to maintain all the hotfixes and use it to push them down - however you need to set the policy so that the local machines apply the updates, etc.
Can you explain the centralized shared development drive reasoning?  Are they all developing out of the same directory?  You can accomplish a second share with login scripts - however I'd HIGHLY recommend using source control and let them develop locally, such as subversion.
As far as your volume mirroring you could check into DFS (distributed file system) to synch up those two drives as long as both machines are windows servers.
I'm sure I've missed things but those are just some thoughts at first glance.
Comment: I do have two SVN servers both on Redhat Ent . The shared resources drive is for testing new libraries, build processes and various and file shares.
Answer: You're well on the right track.
For doing most of the things you want to do, you will need to learn about Group Policies. They will allow you to do everything.
First, create an Organisation Unit (OU) in your Active Directory to dump all these administrators in. GPOs are most usually applied to an OU, so it means that everyone outside of the OU will not get all their settings.
Secondly, you need to set a GPO for that OU. The GPO will allow you to:

Specify WSUS server to use (for forced updates)
Map network drives in addition to the one specified in their profile
Permit or restrict access rights to the local system
Permit or restrict access to install software
Even force installation of certain pieces of software (with other appropriately configured services)

If you want to sync two drives on two seperate servers, and they're both running Windows Server, investigate Distributed File System (DFS). It will keep the specified folders on both servers up to date, provides a single point of access, and will failover or load balance depending on how you configure it between the two (or more) servers.
Comment: THANK YOU VERY, VERY much for you comments and suggestions.  I'll be following your instructions exactly as you mentioned.  Given that your reply was so concise I'm pretty sure you have the experience (which I lack) as an Windows Administrsator. It's a big jump for me taking over a Windows environment when I've dealt entirely in a RHEL and *nix networks for so long.   Thanks again for your help!
Comment: Not a problem. If I had to set up a *nix network I'm sure I would be in a much larger state of confusion than you are!
Answer: For your developers, you may find it reasonable to make them administrators (or power users) of their computer. You can use a GPO to override "Restricted Groups" for "Administrators" or "Power Users" or "XXXX Group".

Create a security group in AD
Add the developers to this security group
Apply a GPO over the computers that the developers use so that under "Restricted Groups" you have "Administrators" with

Administrator
YOURDOMAIN\Enterprise Administrators
YOURDOMAIN\Domain Administrators
YOURDOMAIN\Developer Security Group


Writing a function that take the sum of all numbers in and between two inputs

Question: Help! I'm trying to write a function that take the sum of all numbers in and between two inputs.
So far I have,
<code>(define (sum-between x y)
  (cond
    [(= x y) x]
    [((- x y) 0) 0]
    [else (+ (+ x y) (sum-between (sub1 x) (sub1 y)))]))
</code>
This should return:
<code>(check-expect (sum-between 0 2) 3)

(check-expect (sum-between -1 1) 0)

(check-expect (sum-between 7 7) 7)

(check-expect (sum-between 1 10) 55)
</code>
I'm not sure how to call the recursive case so it doesn't run in an infinite loop. Any suggestions? Thanks!
Comment: What kind of a procedure is `(- x y)` going to make? By decrementing both `x` and `y` they will stay the same apart forever. By adding the sum of the first and last at each step you will add one of them `(- y x 1)` times too much. Tell me, how would you have done it on paper?
Answer: How about using built-in procedures? this is easier:
<code>(define (sum-between x y)
  (apply + (range x (add1 y))))
</code>
But I guess you want to implement this from scratch. The main idea here is that one of the values must get closer and closer to the other, your error is that you're decrementing both of them. Try this instead:
<code>(define (sum-between x y)
  (cond
    [(= x y) x]
    [else (+ x (sum-between (add1 x) y))]))
</code>
Comment: Oh, okay. That makes a lot of sense, thank you! I'm also trying to think about it as an accumulator function, but how would that work when I'm trying to take in two inputs as opposed to two lists?
Answer: For/sum can also be used here:
<code>(define (sum-between x y)
  (for/sum ((i (in-range x (add1 y))))
    i))

(sum-between 0 2)
(sum-between -1 1)
(sum-between 7 7)
(sum-between 1 10)
</code>
Output:
<code>3
0
7
55
</code>


Como adicionar um header a uma imagem capturada com html2canvas?

Question: estou tentando emitir um comprovante de assinatura em uma pagina, e nela tem a opção de salvar o comprovante como imagem, na pagina do comprovante NÃO tem o header com a logo da empresa e o nome da assinatura, eu quero adicionar isso na imagem mas sem que isso apareça para meu usuário,o código abaixo e o que tenho e gera a imagem perfeitamente do jeito que eu quero, so preciso adicionar um header na imagem com a logo e uma escrita qualquer na frente.

function gerarImagem() {
  html2canvas(document.getElementById('telaPrint')).then(function(canvas) {
    var name = 'img-print';
    let xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      let a = document.createElement('a');
      a.href = window.URL.createObjectURL(xhr.response);
      a.download = name + '.png';
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      a.remove()
    };
    xhr.open('GET', canvas.toDataURL("image/png", 1.0));
    xhr.send();
  });

}
<!doctype html>

  <meta charset="utf-8">
  <title>34571073</title>

        dsadadadada
        asdadadsada

        adadada

        adadadasdada

  <button onClick="gerarImagem()">img</button>

caso o codigo acima nao fucione pelo cdn tem esse codepen.
desculpem pela inexperiência aqui no editor do stackoverflow
Answer: Podemos adicionar o header antes de converter e colocar a imagem codificada em base64.
function gerarImagem() {

    var telaPrint = document.getElementById('telaPrint');
    var header = document.createElement("h1");
    header.textContent = "Título";
    telaPrint.prepend(header);
    var img = new Image();
    img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWgAAADICAYAAADFjnuPAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozQjA2NTY4MzdEMzQxMUU0QUVBMkIwQThFRUM1NzY0RCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozQjA2NTY4NDdEMzQxMUU0QUVBMkIwQThFRUM1NzY0RCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjNCMDY1NjgxN0QzNDExRTRBRUEyQjBBOEVFQzU3NjREIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjNCMDY1NjgyN0QzNDExRTRBRUEyQjBBOEVFQzU3NjREIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+nkznnQAABrJJREFUeNrs3Y9t2koAwGHzlAVYgRXoCGSEdIBUSkYgIyQjBKkZIBkBRohHSFZgBIr1DsWNAJ//UXN8n2SpfQF8ubz+chhjRpvNJgNgeEYCDSDQAAg0gEADINAAAg2AQAMg0AACDYBAAwg0AAINgEADCDQAAg0g0AAINIBAAyDQAAg0gEADINAAAg2AQAMg0AACDYBAAwg0AAININAACDQAAg0g0AAINIBAAyDQAAg0gEADINAAAg2AQAMItEADCDQAAg0g0AAINIBAAyDQAKQW6N8vL9//k980wF99K//l1+3t2X0DVwn8EIQZONaG0bl+A/+JM3AhoRZoAATa6hlIuhdW0AACDYBAAwg0AAININAACDQAAg0g0AAINIBAAyDQAAg0gEADINAAAg2AQAMINAACDYBAAwg0AAININAACDQAAg0g0AA0dWUKzt7TdnuouM3mxGP63G5v2y3fbuvttvr29dl2G2+36Xa72W6TE49vN6a8tK1LX5+WttkJxjf0+UKgScAq/LLII26XhSg9hPDMQ3z6Hl+xz0XF7fJv38Nd2KYXNl/8Yw5x0IUiMNdhyxve/2eL+8esUHePv2hw/+I+P0Ic1xcwXwg0iViEUKw6WlE2jWhVXN86eKyn8Fh5wvOFQJNQnO87WlXurMNjLgY6vs8WK9ehzxcCTWJx7kvb6Dz0OL51gxX50OcLgSYReVZ95kgXYl5AOxTDpx7HVbxI95jQfDFQzuKgaQjqPE2fZF+nhn2GLXalWuxrWfMQRJMYzkp/PnZ8eFxzPEOfL6ygScgii3+BqzgN7H27fYRoLMOf37P4U8RWNZ+61znGW0T5Nfv/PPFladv9fd8YlyHSqcwXAk1CYg8dPIf4TQ8cIngNt+lyn6vIGI7D/pdHwjcrjXFc+p6mCc0XAk1C3iKfbhfHZ+8ibncXGZ3dO+26CNO4Isz7xljcfh75PZ3TfCHQJCRmdToLMYt1l/19/LfpvvPI8T02WAXXfVHwHOYLgSbBFXSVeYPHfexg3zHHXWcNVsGpzhcCTWKr56oX36aRq7t996ta1a6z46eQxawY5+YLgSZFMf/Y21y8J+a+qyNjqzrW2zSGKc4XAk1iYl7sanO1t2mLMfQdw9TmC4HmAgPdZoU6azGGvmOY2nwh0CSm6nhqFxeRnzQcQ8wKema+ODfe6k2sqgh2FZzPBmOoClHMO/9WDcc7OcP5QqBhML88Yg5vXDfYb3G629z00xeHOAAEGgCBBhBoLkjVWRBdfcZemzEcsjZfCDSXbv2P7lsVotx8IdCkLOZMiDYhzFuMYdzz2FKbLwSaxMSct9vmafuqxRimHTz+5sCW4nwh0CQm5nhmm0tcvrUYw7TnsaU2Xwg0Ca6gq1ZkTT/JY5VVXzfi2P6LEFUd5oi9oP8lzBcCTYJirgjX5PPwHjrY96yj/VzKfCHQXGCg85rRecq6uVzoXeTY7s0XAk2KYi96X6zwYj6CahG5Gpxl1ceZZ5FP6Yt9XmenuRTnkOcLgSZBsRcHKlaqPw+s9vLwtfuO9/kcebviGO6PELtDq9HPhocfzmm+GDhXs7sMbUIz37M6K54+x7y49Ra2cWlFV8SmzpssbrL4sxHqjG0d5uWpdN9ynLtaYQ95vhBoBqDNi2PzAyvVmA9FLcewyRkU4xqr4vLYYj6jcN+qui9Dni8c4iAxRQiWJ9jPaxb3LsHvY2tyv0udLwSaBE17Xq09t3iqPg1B7DNW45rjG/J8IdAkqDi17b3jEO5Wm3ctH2caxtZHtIrH/Mjqnykx5PlCoEl0JV3EqovzbmcdR3US4vXYURQnYaXaZnU+5PlCoEnQ7rjvsmF4bsJ9l1k/b0+ehyg+Nnz83eGJj45WqkOfLwbCWRx0/dS/2IozKIqzEPLSn7/fbly6/SkiMw6hnmdf1+XYncK2b3yT7OuNJpMLnC8GYLTZbM5y4L9fXjZ+fECsX7e3o3Mbs0McAAINgEADCDQAAg0g0AAINAACDSDQAAg0gEADINAACDSAQAMg0AACDYBAAwg0AAINgEADCDQAAg0g0AAINACpBHrkxwek3AsraACB9lsR0Ik6rhKa/I3/D4GUFnCjzUbXAAQaAIEGEGgABBpAoAEQaAAEGkCgARBoAIEGQKABEGgAgQZAoAEEGgCBBhBoAAQaAIEGEGgABBpAoAEQaAAEGkCgARBoAIEGQKABBBoAgQZAoAEEGgCBBhBoAAQaAIEGEGgABBpAoAEQaACBNgsAAg2AQAMINAACDSDQAAg0AAININAAtPZHgAEASgSjajGP/6kAAAAASUVORK5CYII="
    img.onload = function() {
        telaPrint.prepend(img);
        converter();
        header.remove();
        img.remove();
    }

}

function converter(){

    html2canvas(document.getElementById('telaPrint')).then(function (canvas) {
    var name = 'img-print';
    let xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        let a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhr.response);
        a.download = name + '.png';
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        a.remove()
    };
    xhr.open('GET', canvas.toDataURL("image/png", 1.0));
    xhr.send();
    });

}


Winform clone DataGridViewRow along with DataBoundItem

Question: I have a list of pocos like this:
List alist;
public class A {
    public string M { get; set; }
    public string N { get; set; }
    public Bs List { get; set; }
}
public class B {
    public string X { get; set; }
    public string Y { get; set; }
}

I can bind this to a dataGridView dgv no problem.
Now I want to clone a row, along with a copy of A in that row.
var row = dgv.SelectedCells[0].OwningRow;
var alist= (List)((BindingSource)dgv.DataSource).DataSource;
var a = (A)row.DataBoundItem;
var clone = (DataGridViewRow)row.Clone(); //only copied a blank row, no content
dgv.Rows.Add(clone);
var copya = (A)clone.DataBoundItem;
as.Add(copya); // This 'copya' is NULL, because dataBoudItem is not copied.

How do I make that happen so that clone row has clone data?
I prefer a simpe work around, not going into NotifyPropertyChanged, BindingList and all that if possible?
Answer: Add the new "row" in the data instead for binded DataGridView.
var currentCell = dgv.CurrentCell;
var bs = (BindingSource)dgv.DataSource;
var data = (List)bs.DataSource;
var currentSelection = (A)row.DataBoundItem;
data.Add(currentSelection);

bs.ResetBindings(false); // This should refresh the grid
dgv.CurrentCell = currentCell; // Put back the current cell

Comment: Got my head around it, it works, thanks. just by the way last line dgv.CurrentCell = currentCell will hit exception saying "currentCell doesn't belong to dgv' because binding has been reset. Easy fix to remember colindex and rowindex instead of cell reference.