text:
Q: How to pickle an class that inherits from collections.deque? The example is clear, I have a class that inherits to deque and a method of the module 'collections', sometimes I use defaultdict, others do not.
>>> from collections import deque, defaultdict
>>> import pickle
>>> class lista(deque):
...         def __init__(self):
...             deque.__init__(self)
...             self.lib = defaultdict(dict)
...
>>> p = lista()
>>> p.append("a")
>>> p.append("b")
>>> p.lib['t']=0
>>> p.__reduce__()
(<class '__main__.lista'>, (['a', 'b'], None), {'lib': defaultdict(<type 'dict'>, {'t': 0})})
>>> pik = pickle.dumps(p)
>>> unpik = pickle.loads(pik)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1382, in loads
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1133, in load_reduce
TypeError: __init__() takes exactly 1 argument (3 given)
>>>

The final question, how to serialize this object?

A: Deque is initialized with up to 3 args:
class collections.deque([iterable[, maxlen]])

While unpickling, all three (including self) are provided, while your __init__  do not accept them.
Change for example to
class lista(deque):
    def __init__(self, iterable=(), maxlen=None):
        deque.__init__(self, iterable, maxlen)
        self.lib = defaultdict(dict)


text:
Q: The connection was inactive for more than the allowed 60000 milliseconds and is closed by container I have an azure function that sends a message to the service bus queue. Since a recent deployment, I see an exception occurring frequently: The connection was inactive for more than the allowed 60000 milliseconds and is closed by container.

I looked into this GitHub post: https://github.com/Azure/azure-service-bus-java/issues/280 it says this is a warning. Is there a way to increase this timeout? Or any suggestions on how to resolve this? Here is my code:

namespace Repositories.ServiceBusQueue
{
    public class MembershipServiceBusRepository : IMembershipServiceBusRepository
    {
        private readonly QueueClient _queueClient;
        public MembershipServiceBusRepository(string serviceBusNamespacePrefix, string queueName)
        {
            var msiTokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
            _queueClient = new QueueClient($"https://{serviceBusNamespacePrefix}.servicebus.windows.net", queueName, msiTokenProvider);
        }
        public async Task SendMembership(GroupMembership groupMembership, string sentFrom = "")
        {
            if (groupMembership.SyncJobPartitionKey == null) { throw new ArgumentNullException("SyncJobPartitionKey must be set."); }
            if (groupMembership.SyncJobRowKey == null) { throw new ArgumentNullException("SyncJobRowKey must be set."); }
            foreach (var message in groupMembership.Split().Select(x => new Message
            {
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(x)),
                SessionId = groupMembership.RunId.ToString(),
                ContentType = "application/json",
                Label = sentFrom
            }))
            {
                await _queueClient.SendAsync(message);
            }
        }
    }
}

A: This could be due to deadlock in the thread pool, please check if you are calling an async method from a sync method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transforming a 3x3 two-dimensional array in a 6x6 symmetrical two-dimensional array I'm trying to solve an exercise that requires:
- fill randomly a 3x3 two-dimensional array
- transform the array in a second one with dimension 6x6:
1&nbsp 2&nbsp 3&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp1&nbsp 2&nbsp 3  &nbsp3 &nbsp2&nbsp 1&nbsp
4&nbsp 5&nbsp 6&nbsp&nbsp&nbsp&nbsp&nbsp->    4&nbsp 5&nbsp 6 &nbsp 6 &nbsp5 4&nbsp
7 &nbsp8&nbsp 9&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp7&nbsp 8&nbsp 9 &nbsp 9 &nbsp8&nbsp 7
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp7&nbsp 8&nbsp 9 &nbsp 9 &nbsp8 &nbsp7
              &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp 4&nbsp 5 &nbsp6 &nbsp 6&nbsp 5&nbsp 4
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp1&nbsp 2&nbsp 3 &nbsp 3&nbsp 2&nbsp 1
I can't get it working tho' I think the logic must be right.
#include <stdio.h>
#include <stdlib.h>

 #define DIM 3

int main()
{
int i, j, a[DIM][DIM],a1[DIM][DIM], a2[DIM][DIM], a3[DIM][DIM], b[2*DIM][2*DIM];
srand(time(NULL));

for (i = 0; i < DIM; i++)
{
    for (j = 0; j < DIM; j++)
    {
        a[i][j] = rand() % 10;
    }
}
for (i = 0; i < DIM; i++)
{
    for (j = 0; j < DIM; j++)
    {
    printf("%d ", a[i][j]);
    }
    printf("\n");
}

for (i = 0; i < DIM; i++)
{
    for (j = 0; j < DIM; j++)
    {
        a1[i][j] = a[i][DIM - 1 - j];
        a2[i][j] = a[DIM - 1 -j][j];
        a3[i][j] = a2[i][DIM - 1 - j];

        if(i < DIM && j < DIM)
            b[i][j] = a[i][j];
        if(i < DIM && j >= DIM)
            b[i][j] = a1[i][j];
        if(i >= DIM && j < DIM)
            b[i][j] = a2[i][j];
        if(i >= DIM && j >= DIM)
            b[i][j] = a3[i][j];
    }
}
for (i = 0; i < 2*DIM; i++)
{
    for (j = 0; j < 2*DIM; j++)
    {
    printf("%d ", b[i][j]);
    }
    printf("\n");
}

return 0;

}

A: Here are a few points that should help you to get where you want to go:

*

*You are making four copies of a three by three array.

*

*You need a nested for loop to iterate over the original array

*Inside the for loop you will be making four assignments, one for each copy

*Each copy has a different location

*

*When you make the copies you will need to add an offset to each index

*This is best done by just using the index of what was the value in the upper left corner

*Each copy goes in different directions

*

*Whenever a dimension is going in the wrong dimension, you can simply subtract the index

Anything else?

A: If you always fill the 6 X 6 matrix in the same way shown in the example, then you can use the following code,
m=0;
fl1=0;
for (i = 0; i < 6; i++)
{
    n=0;
    fl2=0;
    for (j = 0; j < 6; j++)
    {
       b[i][j] = a[m][n];
       if(n==3)
       {
          fl2=1;
       }
       if(fl2==0)
       {
          n++;
       }
       else
       {
          n--;
       }
    }
    if(m==3)
    {
       fl1=1;
    }
    if(fl1==0)
    {
       m++;
    }
    else
    {
       m--;
    }
}

A: for (i = 0; i < DIM*2; i++){
    for (j = 0; j < DIM*2; j++){
        b[i][j]=a[i-(i>=DIM)*((i-DIM)*2+1)][j-(j>=DIM)*((j-DIM)*2+1)];
    }
}


text:
Q: Block access between SharePoint Web Front and Servers and Database only allow WFE to Application Server access I am a developer with limited knowledge of SharePoint Administration. We have a SharePoint 2019 multi-tier farm.

*

*1 App with Central Admin

*1 App with Search

*1 F5 Firewall between App and Web Servers

*2 Web Front End Servers (WFE)

Everything was good until we have deployed a new Publishing Portal with Anonymous Access enabled. As we are going public our infra and infosec team raises concern over the Web Front End Servers' access to DB while the public-facing WFE server should have only access to the Application server and the application server should only have the right to communicate with DB, which I think is correct.
However, there is Microsoft documentation that suggests the required architecture but is only applicable to SharePoint 2013 farm. The below image shows that WFE servers have only App Server Access and no direct DB Access to WFE servers.
The image shows that WFE servers have only App Server Access and no direct DB Access to WFE servers.

This link suggested the above image architecture.
Simplifying the issue I have SharePoint 2019 Farm for which I want to block the WFE Server's access to the DB Servers, I want Web Front End Server can only access the SharePoint Application Server and not the DB Serevr. DB Serevr can only be access by Application serevr as suggested in the Image.
how to configure web front end server if we block the Db access, as you can see in below image we have to provide the Database details to configure the Web Front end Servers.

A: All SharePoint Servers require access to the SQL Servers. All SharePoint Servers communicate directly with the SQL Servers.
The architecture from 2013 applies to 2016, 2019, and SharePoint Subscription Edition.
It is recommended to not place FEs in a DMZ but rather host the entire farm internally, using a reverse proxy in the DMZ to terminate end user traffic. This limits the number of ports (Active Directory, SQL ports, ports between SharePoint Servers) that need to be opened in the back channel firewall.


text:
Q: is it possible to convert .exe file to java files Is it possible to convert .exe file to java files?How to provide security to my exe file,because my remote data base server password is in one of my java files.I dont want others to view that .class file too.
I do not want others to view jar file in my exe file.

A: No you cannot convert an exe to a java file ( i think you mean jar file). There are such things as executable jars, but I don't think that is what you are talking about.
You are asking to convert native code to java code from an EXE, which tells me you don't fully understand exactly how java works.
Check out these questions, which ask a similar question
how to convert exe file to .jar file?


text:
Q: CNAME: Mail address gets rewritten I have a problem with receiving mails. I do not know if my server or the server of the sender is wrong configured.
I have a domain daniel-marschall.de which has following DNS RR:
daniel-marschall.de.    86400   IN  CNAME   viathinksoft.com.

The domain viathinksoft.com has the MX RR to "mail.viathinksoft.com":
viathinksoft.com.   85651   IN  MX  0 mail.viathinksoft.com.

mail.viathinksoft.com runs Postfix, Cyrus and Debian Linux.
When I send an email to webmaster (at) daniel-marschall.de e.g. using GoogleMail, the user "Daniel Marschall" at our system receives the email, which is correct.
But when the server "startcom.org" sends an email to webmaster (at) daniel-marschall.de , the email gets "hard redirected" to webmaster (at) viathinksoft.com which is a different mail account.
The relevant parts of the email headers are:
Received: from viathinksoft.de ([unix socket])
     by viathinksoft.de (Cyrus v2.2.13-Debian-2.2.13-19+squeeze3) with LMTPA;
     Tue, 06 Nov 2012 02:15:02 +0100
Received: by viathinksoft.de (Postfix, from userid 5001)
    id AD83016CE112; Tue,  6 Nov 2012 02:15:01 +0100 (CET)
Received: from mta1.startcom.org (apache-7.startcom.org [192.116.242.7])
    (using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits))
    (No client certificate requested)
    by viathinksoft.de (Postfix) with ESMTPS id 90F5116CE107
    for <webmaster (at) viathinksoft.com>; Tue,  6 Nov 2012 02:14:55 +0100 (CET)
Received: from localhost (com.internal.startcom.org [192.168.0.180])
    by mta1.startcom.org (8.13.8/8.13.8) with ESMTP id qA61EbIS010233
    for <webmaster (at) daniel-marschall.de>; Tue, 6 Nov 2012 03:14:37 +0200
From: ...
To: webmaster (at) viathinksoft.com (<-- WRONG!!!)

As you can see, the email was initially intended for "webmaster (at) daniel-marschall.de", but now it has the field "To: webmaster (at) viathinksoft.com", so my MTA dropped the mail to the owner of viathinksoft.com .
I think the sender's MTA thinks that "CNAME" RR means that the address needs to be rewritten, but as far as I know, CNAME is only a soft redirect on DNS basis and should not force the MTA to rewrite the domain name. Or am I wrong?
PS: The log entries are showing that my server already has the wrong address when the mail is incoming:
$ cat /var/log/mail.log | grep '90F5116CE107'
Nov  6 02:15:00 viathinksoft postfix/smtpd[18184]: 90F5116CE107: client=apache-7.startcom.org[192.116.242.7]
Nov  6 02:15:00 viathinksoft postfix/cleanup[19928]: 90F5116CE107: message-id=<c76cb951ea724270c94ff1b0e8d4de4e (at) startcom.org>
Nov  6 02:15:00 viathinksoft postfix/qmgr[9843]: 90F5116CE107: from=<certmaster (at) startcom.org>, size=1583, nrcpt=1 (queue active)
Nov  6 02:15:01 viathinksoft postfix/pipe[20419]: 90F5116CE107: to=<info (at) viathinksoft.de>, orig_to=<webmaster (at) viathinksoft.com>, relay=spamassassin, delay=6.2, delays=5.5/0/0/0.76, dsn=2.0.0, status=sent (delivered via spamassassin service)
Nov  6 02:15:01 viathinksoft postfix/qmgr[9843]: 90F5116CE107: removed

A: As the comments indicated, you can't have your MX as a CNAME.  You can detect problems like this by using a site like intoDNS.  Here is the report for your domain -- I see from it that you've already fixed the problem.


text:
Q: Can c# windows form list view have item template with 2 rows and 2 columns I have a list of items that is constantly updated from live readings, the newest items should be added on the top of the list.
is it possible to have an item template for the list view with 2 rows and 2 column for each item. (like attached photo).
I searched online i could not find a solution.
my second approach was to create Main Panel and append Panels to it sub panels to it containing the labels.I am only able to add the items in the bottom of the Main panel since i can calculate the location of the last added item.
        Panel pan = new Panel();
        pan.Name = "panel" + counter;
        pan.BorderStyle = BorderStyle.FixedSingle;

        Label label1 = new Label();
        label1.AutoSize = true;
        label1.Location = new System.Drawing.Point(0, 0);
        label1.Name = "label" + counter;
        label1.Size = new System.Drawing.Size(35, 13);
        label1.TabIndex = 1;
        label1.Text = "label" + counter;

        Label label2 = new Label();
        label2.AutoSize = true;
        label2.Location = new System.Drawing.Point(0, 20);
        label2.Name = "label2" + counter;
        label2.Size = new System.Drawing.Size(35, 13);
        label2.TabIndex = 2;
        label2.Text = "label2" + counter;

        Label label3 = new Label();
        label3.AutoSize = true;
        label3.Location = new System.Drawing.Point(40, 0);
        label3.Name = "label3" + counter;
        label3.Size = new System.Drawing.Size(35, 13);
        label3.TabIndex = 3;
        label3.Text = "label3" + counter;

        Label label4 = new Label();
        label4.AutoSize = true;
        label4.Location = new System.Drawing.Point(40, 20);
        label4.Name = "label4" + counter; ;
        label4.Size = new System.Drawing.Size(35, 13);
        label4.TabIndex = 4;
        label4.Text = "label4" + counter;

        pan.Location = new Point(0, counter * 50);
        pan.Size = new Size(100, 50);
        pan.Controls.Add(label1);
        pan.Controls.Add(label2);
        pan.Controls.Add(label3);
        pan.Controls.Add(label4);

        MainPanel.Controls.Add(pan);
        counter++;

Thanks


text:
Q: How to remove/hide the predictive autocomplete popup when I type in the tag/term metabox When I start to type in a few letters in the tag or term metabox (in the post edit page) there is a predictive autocomplete popup thingy containing other tags/terms to choose from. How do I disable/hide this?

A: There is no filter or way to stop those Ajax calls. However, you can alter the response of Ajax call by using filter term_search_min_chars.
Which is actually to customize minimum number of characters after that Ajax will print the response. So we can make it 0 to never print the response!
/**
 * Remove tag search suggestions
 * @param int $tax The minimum number of characters required. Default 2.
 * @return int
 */
function remove_tag_suggestions($tax) {
    //You can place your condition if you want!
    return 0;
}
add_filter('term_search_min_chars', 'remove_tag_suggestions');

PS: I am not sure why do you want to remove this wonderful feature!


text:
Q: Forwarding InnerRef on a styled-component gives typescript error Forwarding innerRef to a styled-component as shown below gives the following type error in typescript:
interface MenuProps {
  isOpen: boolean
}

const BaseMenu = styled.ul<MenuProps>`
  padding: 0;
  /* ... styles ... */
  ${({ isOpen }) =>
    !isOpen &&
    css`
      border: none;
    `}
`

const Menu = React.forwardRef((props, ref) => <BaseMenu innerRef={ref} {...props} />)

No overload matches this call.
  Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & MenuProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type '{ children?: ReactNode; innerRef: ForwardedRef<unknown>; }' is not assignable to type 'IntrinsicAttributes & Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & MenuProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }'.
      Property 'innerRef' does not exist on type 'IntrinsicAttributes & Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & MenuProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"ul", DefaultTheme, MenuProps, never, "ul", "ul">): ReactElement<StyledComponentPropsWithAs<"ul", DefaultTheme, MenuProps, never, "ul", "ul">, string | JSXElementConstructor<...>>', gave the following error.
    Type '{ children?: ReactNode; innerRef: ForwardedRef<unknown>; }' is not assignable to type 'IntrinsicAttributes & Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & MenuProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }'.
      Property 'innerRef' does not exist on type 'IntrinsicAttributes & Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & MenuProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }'.ts(2769)

I have tried removing isOpen and type interface as well, but both result in same error.
Update
Codesandbox file with the error: https://codesandbox.io/s/purple-silence-idz52?file=/src/Menu.tsx

A: Because the ul tag don't have property innerRef. Just change innerRef to ref
You should add type for ref and props like this:
const Menu = React.forwardRef<HTMLUListElement, MenuProps>((props, ref) => (
  <BaseMenu ref={ref} {...props} />
));

https://codesandbox.io/s/nervous-violet-l7xb1?file=/src/Menu.tsx


text:
Q: What does 'Forward AND...' mean here? Here is the line from an Indian daily [photo caption text],

Argentina's forward and Lionel Messi prepares to kick the ball to score his team's second goal during the World Cup match against Bosnia Hercegovina at the Maracana Stadium in Rio de Janeiro. (AFP Photo)

I understand the meaning of the noun forward

forward - The person who plays the position of forward in certain games, such as basketball, soccer, or hockey.

But how does the former sentence take forward and...? Shouldn't it be Argentina's forward Lionel Messi... Not sure whether forward can go there as an adjective though.
Am I missing something?

A: This problem is due to a typo.  It was supposed to be "Argentina's forward and captain Lionel Messi".  I found the following (non-typo) sources using Google Search ("Argentina's forward" "Lionel Messi prepares to kick the ball to score"):

*

*www.sportsmole.co.uk: "Argentina's forward and captain Lionel Messi prepares to kick the ball ... during the 2014 FIFA World Cup..."

*www.gettyimages.com: "Caption:Argentina's forward and captain Lionel Messi prepares to kick the ball ... during the 2014 FIFA World Cup on June 15, 2014."
Note that standard, formal English would typically require commas, as follows:

Argentina's forward and captain, Lionel Messi, prepares to kick the ball.

However, news magazines will often eliminate grammatical and syntactical elements when it doesn't reduce clarity. In this case,

Argentina's forward and captain Lionel Messi prepares to kick the ball.

Now the above sentence, taken out of context, can seem a bit odd since it initially seems to suggest two different people.  But most people who would be reading this within it's natural context would be regular readers of sports and would understand the form.
It may be interesting that this is part of a general pattern in which some rules can be relaxed for shorter phrases (or perhaps conversely, some rules are required for longer phrases).  The following sentence would practically demand commas:

Argentina's forward and newly appointed captain of the team, Lionel Messi, prepares to kick the ball.

Credit to @Fantasier who actually predicted the answer before I (independently) researched it.

A: You're correct, the and is improper here, and you have the right definition of forward. Looking at the picture:

*

*There's only one Argentinian player

*That player is Lionel Messi

*He plays the position of forward

*He is the only one preparing to kick the ball

Clearly, both Lionel Messi and forward refer to the same person here.
Argentina's forward Lionel Messi is a valid grammatical construct. Forward is a noun and the subject of the sentence. Lionel Messi is a noun phrase functioning adjectivally to describe forward; it tells us which specific Argentinian forward, as they have more than one. It's added as a parenthetical remark or aside, and you can insert some commas into the sentence to make the meaning more obvious:

Argentina's forward, Lionel Messi, prepares to kick the ball to score his team's second goal during the World Cup match against Bosnia Hercegovina at the Maracana Stadium in Rio de Janeiro. (AFP Photo)

If you wanted to name both the player and position in a compound subject, you could use forward Messi, though this construction is quite rare in American English. I assume you mean using forward as a title, similar to Doctor Connors or Mister Smith. The forward Messi or Tendulkar the striker are much more common phrasings and function grammatically the same as Argentina's forward Lionel Messi from the sentence in question. Names of sports positions aren't generally given the same level of credence as employment or honorific titles.

A: I think the editor of the hindustantimes is the one that missed something. It looks like this sentence was intended to be written differently, and ended up mangled.
The editor saw "x"and "y", saw two people on the picture, and moved on, I guess.


text:
Q: Add handler to runtime-created control I found in StackOverflow some vb.net code written by "PaRiMaL RaJ". i want the same think but i must convert this code to work on VB6.
can you help me please???
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' creating control
    Dim btn1 As Button = New Button()
    Dim btn2 As Button = New Button()

    btn1.Parent = Me
    btn1.Name = "btn1"
    btn1.Top = 10
    btn1.Text = "Btn1"

    btn2.Parent = Me
    btn2.Name = "btn2"
    btn2.Top = 50
    btn2.Text = "Btn2"

    'adding handler for click event
    AddHandler btn1.Click, AddressOf HandleDynamicButtonClick
    AddHandler btn2.Click, AddressOf HandleDynamicButtonClick

End Sub

Private Sub HandleDynamicButtonClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = DirectCast(sender, Button)

    If btn.Name = "btn1" Then
        MessageBox.Show("Btn1 clicked")
    ElseIf btn.Name = "btn2" Then
        MessageBox.Show("Btn2 Clicked")
    End If

End Sub

A: The easiest way is to use a control array. Add a button to your form in the designer and set its Index property to 0. You can hide the button if you don't want it to be visible.
Then, when you want to dynamically add more buttons at run-time, just use the Load statement.
For example, if your button was named Command1:
Load Command1(1)                     ' Create a new button
Command1(1).Move 50, 50, 1500, 500   ' Set its size and position
Command1(1).Caption = "New Button"   ' Give it a caption
Command1(1).Visible = True           ' Make it visible

The button will use the same event handlers as your original button:
Private Sub Command1_Click(Index As Integer)

    ' Print the caption of the clicked button...
    Debug.Print Command1(Index).Caption

End Sub


text:
Q: Multiple instances of an object/class I'm making a simple game in VBA excel that's like Rogue or Nethack. It takes place in a gui window. I've got an array to hold the playing field etc. and a class for the player, which has their coordinates stored and some subs to move around etc.
I then created an NPC class that moves around at random. I declared it the usual way, Dim NPC as NPCclass (inside the declarations) and then Set NPC = New NPCclass (inside a sub, which seems to be necessary but none of the tutorials mention that?) So far so good, the NPC is represented by an ASCII character and does what I want it to.
However, now I want to create more NPCs after intervals of a few turns. But I can't figure out how to do it. It seems like for every additional instance of my NPC, I have to do another Dim NPCxyz as NPCclass.
So I tried to generate a string, say "npc_name" that holds the name of the next NPC to be generated, as in NPC1 or NPC2 and so on. Unsurprisingly, if I then try Dim npc_name As NPCclass VBA doesn't understand that I want to create another instance of NPCclass with the string inside npc_name as its name. Instead it thinks I want to declare npc_name again, like when I said Dim npc_name As String earlier.
How can I create more NPCs that use the same class but move independently around the array/playfield? I feel like I'm misunderstanding something obvious because none of the tutorials I looked at went into this.

A: Just create an array of objects...
Dim NPC(1 to 20) as NPCclass

For i = 1 to 20
    Set NPC(i) = New NPCclass

    '... your object init ...
    NPC(i).SetSometing = 0
    NPC(i).DoSomething()
Next i

And if later on you want to increase the list you just need to do something like
ReDim Preserve NPC(50)

A: You also can use collections:
Dim NPC as New NPCclass
Dim colNPC as New Collection

for i = 1 to 20
    colNPC.add New NPC
next


text:
Q: update a particular nested list in react native I'm developing an app which allows users in the group to join any group of thier choice. I have the group name displayed in a list. When the user taps on a button for a particular row and accepts to join the group, a value in that particular row is suppose to change.
handleJoinGroup = (item) => {
  Alert.alert(
    'Join Group',
    'Sure to Join ' + item.name + '?',
    [
      {text: 'No', onPress: () => console.log('no')},
      {
        text: 'Yes',
        onPress: () => this.setState({'isUserJoined':'1'}),
        style: 'cancel',
      }
    ],
    {cancelable: false},
  );
}

View
{
  item.isUserJoined == '0' ?
  <Button
   containerViewStyle={{width:'50%', alignSelf:'flex-end', position:"absolute", top:0, right:-25}}
    onPress={()=>(onJoinGroup(item))}
    rounded = {true}
    style={{margin:10}}
    icon={{name: 'add'}}
    backgroundColor='#03A9F4'
    buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
    title='Join Group'
  />
  : null
}

{
  item.isUserJoined == '1' ?
  <Button
   containerViewStyle={{width:'50%', alignSelf:'flex-end', position:"absolute", top:0, right:-25}}
    onPress={()=>(onExist(item))}
    rounded = {true}
    style={{margin:10}}
    icon={{name: 'trash'}}
    backgroundColor='#DC143C'
    buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
    title='Exit Group'
  />
  : null
}

When the user accepts to join a group i want the value of isUserJoined to change to 1 so it updates the view

A: Depending on how you store and pass data to your components, you should either use this.state.isUserJoined (if you accessing it directly from your App component) or this.props.isUserJoined (if you accessing it from child component via props)

A: If you want to update button's view and functionality onClick. that means on first    click user join the group and second click on same button user exit the group.
By this method you can add more buttons (Groups) with same functionality.
this.state = {
  isUserJoined: null,
}
...

isUserJoin(groupNo) {
  if (this.state.isUserJoined) {
    this.setState({ isUserJoined: null })
  } else {
  Alert.alert(
   'Join Group',
   'Sure to Join ' + item.name + '?',
   [
     {text: 'No', onPress: () => console.log('no')},
     {
       text: 'Yes',
       onPress: () => this.setState({ isUserJoined: item }),
       style: 'cancel',
     }
   ],
   {cancelable: false},
 );
  }
}

render() {
return (
<Button
  containerViewStyle={{width:'50%', alignSelf:'flex-end', position:"absolute", top:0, right:-25}}
  onPress={()=>this.isUserJoin('1')}
  rounded = {true}
  style={{margin:10}}
  icon={{name: 'add'}}
  backgroundColor={this.state.isUserJoined ===  '1' ? '#03A9F4' : '#FFFF'}
  buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
  title={this.state.isUserJoined ===  '1' ? 'Join Group 1' : 'Exit Group 1'}
/>
)
}


text:
Q: How can I avoid writing duplicate Unit Tests for classes that implement the same interface? I'm just getting into unit tests using Visual Studio 2010. I'm wondering if there is a workflow that would allow me to create a series of tests that apply to an Interface and then apply those interface tests to any and all classes that implement the interface.
For example say I have the following interface.
public interface IAnimal
{
   public string Name {get;}
   public string Speak();
}

I could obviously have a number of classes that implement this interface.
public class Dog:IAnimal
{
  public string Name {get{return "Dog";}}
  public string Speak{return "BARK BARK";}
  public bool LickBalls();
}

public class Cat:IAnimal
{
  public string Name {get{return "Cat";}}
  public string Speak{return "MEOW MEOW";}
  public bool Scratch();
}

So I'd like to define a series of tests that apply to all IAnimals
   public TestAnimalName(IAnimal animal)
   {
       Assert.IsFalse(string.IsNullorEmpty(animal.Name));
   }

   public TestAnimalSpeak(IAnimal animal)
   {
       string sound = animal.Speak();
       Assert.IsFalse(string.IsNullOrEmpty(sound));
   }

Then I'd like to define a master TestAnimal() method which could be used to test any IAnimal.
TestAnimal(IAnimal animal)
{
    TestAnimalName(animal);
    TestAnimalSpeak(animal);
}

I could then call this TestAnimal() method when testing a concrete type of IAnimal.
[TestMethod]
TestCat()
{
    Cat c = new Cat();
    TestAnimal(c);
}

[TestMethod]
TestDog()
{
    Dog c = new Dog();
    TestAnimal(c);
}

Yet when I try to do this in Visual Studio the Asserts in the called methods are ignored. I tried to simplify the problem with the method below and found that it passed even though it calls a method that should result in a failure.
[TestMethod]
public void AssertInCalledMethod() //this will pass
{
    Assert.IsTrue(true);
    Blah();
}

public void Blah()
{
    Assert.IsTrue(false);
}

So how can I avoid writing a lot of duplicate tests for classes that all implement the same interface?

A: Greg Young's Hei Hei Grensesnitt takes a slightly different approach to this problem, which I like. You can write an interface specification:
[InterfaceSpecification]
public class ICanAddTests : AppliesTo<ICanAdd>{

    [Test]
    public void can_add_two_numbers() {
          Assert.AreEqual(5, sut.Add(2,3));
    }
}

... and the framework automatically executes the test for all classes it finds that implement the interface. This is using NUnit, not MSTest, but I think it's a rather clever idea and makes for a very easy workflow.

A: Your final code snippet:
[TestMethod]
public void AssertInCalledMethod() //this will pass
{
    Assert.IsTrue(true);
    Blah();
}

public void Blah()
{
    Assert.IsTrue(false);
}

fails like it's meant to on my computer. Sometimes visual studio can get confused about old dlls and run old versions of your tests (or libraries being tested), if you rename the test method does that rename reflect itself in the test runner?
P.S. I think your approach with TestAnimal(IAnimal animal) is ideal...


text:
Q: Hibernate ILLEGAL ACCESS ERROR Maria DB Connection Im trying to Connect to Maria DB from JBOSS Web app.
Im using Datasource for the connection.
my hibernate.cfg file

    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
 <property name="hibernate.connection.datasource">java:/datasources/KDCDBM</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="show_sql">true</property>
    <property name="hbm2dll.auto">update</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <mapping resource="com/mycompany/Contact.hbm.xml"/>

When i bring up my app and try to connect . Im getting following error
13:07:01,387 INFO  [org.hibernate.validator.internal.util.Version] (ServerService Thread Pool -- 60) HV000001: Hibernate Validator 4.3.3.Final-redhat-1
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60) org.hibernate.HibernateException: Error applying BeanValidation relational constraints
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:219)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:126)
13:07:01,391 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.services.integration.serviceimpl.batch.CronJobsImpl.startCronJob(CronJobsImpl.java:136)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.invokeCronJobs(DBSBatchJobServlet.java:66)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at com.kony.p2p.servlet.DBSBatchJobServlet.contextInitialized(DBSBatchJobServlet.java:39)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.apache.catalina.core.StandardContext.start(StandardContext.java:3780)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
13:07:01,392 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Thread.run(Thread.java:745)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.jboss.threads.JBossThread.run(JBossThread.java:122)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.reflect.InvocationTargetException
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Method.invoke(Method.java:498)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:208)
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 17 more
13:07:01,393 ERROR [stderr] (ServerService Thread Pool -- 60) Caused by: java.lang.IllegalAccessError: tried to access class javax.persistence.Persistence$1 from class javax.persistence.Persistence
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.persistence.Persistence.<clinit>(Persistence.java:87)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at java.lang.Class.newInstance(Class.java:442)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:48)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.run(DefaultTraversableResolver.java:156)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.detectJPA(DefaultTraversableResolver.java:101)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver.<init>(DefaultTraversableResolver.java:67)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:74)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
13:07:01,394 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:521)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:119)
13:07:01,395 ERROR [stderr] (ServerService Thread Pool -- 60)   ... 22 more

A: This property Fixed my issue ..
none


text:
Q: How to register two configurations that map to the same type in DI injector in ASP.NET Core Let's say we have two connection strings - and that is just an example, I'm looking for a better way to implement this regardless of what I'm configuring - in the appSettings.json file:
  "ImportDb": {
    "StringConexao": "data source=server_n1;initial catalog=MyImportDb;user id=SYSDBA;password=masterkey;Charset=UTF8;",
    "BooleanProperty": false
  },
  "MainDb": {
    "StringConexao": "data source=server_n1;initial catalog=MyMainDb;user id=SYSDBA;password=masterkey;Charset=UTF8;",
    "BooleanProperty": false
  },

Today, I solve that mapping to 2 different types:
public class DbConfig
{
    public string StringConexao { get; set; }
    public bool BooleanProperty { get; set; }
}

public class LocalDbConfig: DbConfig
{

}

And registering in DI like this:
serviceCollection.Configure<DbConfig>(DadosConfig.GetSection("MainDb"));
serviceCollection.Configure<LocalDbConfig>(DadosConfig.GetSection("ImportDb"));

Why I solved that way:

*

*Both configurations have exactly the same properties. They differ only on which class it's used.

*The 2 configs can even refer to different servers, on two different networks in the case of string connections above.

*I cannot treat them as an list (I need to be able address one or another on constructor)

It have some downsides:

*

*Since the two types are descendants, if some requirements changes and a class that uses one of the configurations needs to accept the other as well I can't have two constructors each for each type of DbConfig - it confuses the DI injector.

So I ask: there's an more "elegant" way to do that kind of mapping?
Disclaimers:

*

*user id=SYSDBA;password=masterkey is an login/password default to FirebirdSQL db server. It's well known for years.

*"StringConexao" means "ConnectionString", for those curious.

A: I tried to create a someservicefactory to create services with different configrations as below:
public interface IDbconfig
    {
        public string StringConexao { get; set; }
        public bool BooleanProperty { get; set; }
    }
    public class DbConfig: IDbconfig
    {
        public string StringConexao { get; set; }
        public bool BooleanProperty { get; set; }
    }
    public interface IService
    {
         public string Test { get; set; }
         public string Test1 { get; set; }
    }
    public class Service: IService
    {
        public string Test { get; set; }
        public string Test1 { get; set; }
        public Service(List<DbConfig> config)
        {
            this.Test = config.First().StringConexao;
            this.Test1 = config.Last().StringConexao;
        }
    }
    public interface IServiceFactory
    {
        IServiceFactory Add(string key);
        IService Create(string key);
    }
    public class ServiceFactory : IServiceFactory
    {

        private readonly IConfiguration _configuration;
        private readonly Dictionary<string, IService> _someservices = new Dictionary<string, IService>();

        public ServiceFactory(IConfiguration configuration)
        {
            _configuration = configuration;
            this.Add ("MainDb").Add("ImportDb").Add("MainDb,ImportDb");
        }

        public IServiceFactory Add(string key)
        {
            var keystringlist = key.Split(",").ToList();
            var configs = new List<DbConfig>();
            foreach(var newkey in keystringlist)
            {
                var config = new DbConfig();
                _configuration.GetSection(newkey).Bind(config);
                configs.Add(config);
            }
            var someservice = new Service(configs);
            _someservices.Add(key, someservice);
            return this;
        }
        public IService Create(string keyOfConfiguration)
        {
            return _someservices[keyOfConfiguration];
        }
    }

in startup.cs:
services.AddSingleton<IServiceFactory, ServiceFactory>();

inject the factory into controller or somewhere else and create services with different configs:
            var service1 = _serviceFactory.Create("ImportDb");
            var service2 = _serviceFactory.Create("MainDb");
            var service3 = _serviceFactory.Create("MainDb,ImportDb");

The result:

A: You say a list is not ok since you need to address the correct db in the constructor, but you could use a Dictionary. You can define a class DbConfigs:
public class DBConfigs
{
    public Dictionary<string, DBConfig> DBConfigurations { get; set; }
}

Then in the apSettings you can have:
"DBConfigs": {
    "DBConfigurations": {
        "ImportDb": {
            "StringConexao": "data source=server_n1;initial catalog=MyImportDb;user id=SYSDBA;password=masterkey;Charset=UTF8;",
            "BooleanProperty": false
         },
         "MainDb": {
             "StringConexao": "data source=server_n1;initial catalog=MyMainDb;user id=SYSDBA;password=masterkey;Charset=UTF8;",
             "BooleanProperty": false
         }
     }
 }

The registration in DI becomes:
serviceCollection.Configure<DbConfigs>(DadosConfig.GetSection("DBConfigs"));

And finally you can writhe your constructors in this way:
public MyClass(DBConfig aConfig)
{
    _myConfig = aConfig.DBConfigurations["MainDB"];
}


text:
Q: How to specify common string for version in build.gradle? I have a build.gradle that has following content:-
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'

How can I specify the version number (here 25.3.1) at a common place and reuse it every where, so that when ever I need to change it, I have to change it at only one place?

A: You can use Gradle features to achieve this.
ext {
    supportVersion = "25.3.1"
}

dependencies {
    compile "com.android.support:appcompat-v7:$supportVersion"
    compile "com.android.support:design:$supportVersion"
    compile "com.android.support:cardview-v7:$supportVersion"
    compile "com.android.support:recyclerview-v7:$supportVersion"
}

See also:

*

*https://docs.gradle.org/3.3/userguide/writing_build_scripts.html

A: In Project level gradle, you specify the version code. If we specify version code in project level then we can use that version in all modules. For example, we had three modules in a project. If we specify version code in project level then easily use that in module level gradle file.
ext {
    appcompatVersion = '25.3.1'
    supportDesignVersion = '25.3.1'
    cardviewVersion = '25.3.1'
    recyclerviewVersion = '25.3.1'
}

In Module level gradle, you use it like below:
dependencies {
        compile 'com.android.support:appcompat-v7:$appcompatVersion'
        compile 'com.android.support:design:$supportDesignVersion'
        compile 'com.android.support:cardview-v7:$cardviewVersion'
        compile 'com.android.support:recyclerviewv7:$recyclerviewVersion'
}

A: In the project gradle file add the variable
  buildscript {
     ext.supportLibraryVersion = "25.3.1"

     dependencies {
          classpath 'com.android.tools.build:gradle:2.3.3'
          ........

And in the app gradle file refer the variable created.
  dependencies {
      compile "com.android.support:appcompat-v7:$supportLibraryVersion"
      compile "com.android.support:design:$supportLibraryVersion"

for more reference follow this link


text:
Q: How can I remove error data(overshoot or undershoot) from the averaged dataset? I got 5000 by 25 matrix dataset from the experiment, but there might be some errors due to several experimental conditions. So I used for loop for the filtration of error data comparing with the average dataset.
I made a for loop as
def error_data_1(y_data1):
    error_data = pd.DataFrame()
    for j in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25):
        for i in y_data1.index:
              if y_data1.index[i, j] < 2:
                   c = pd.DataFrame(y_data1.index[i]).T
                   y_data1 = y_data1.drop(i, 0)
   return y_data1, error_data

so that I could adjust the control point manually as setting 1 or 2.
But It would be much better compared with the average values of each data point.
So I have created an average matrix by summation of all the column components and divided by the number of rows. And I would like to drop the error data which is not in a range of +- 95% of average data.
Is there any way to compare the two different data frame for eliminating the error by ratio?
Thanks


text:
Q: Client-Server socket setup, how to respond to a determined client This question has been edited to focus in a simpler problem
So I have a basic client-server socket installation, in which the client send a JSON like {'id': '1', 'value': 'A'}. At the server side, if I receive a message with id 2 I want to send a message to the client with id 1, telling him that his new value is C.
This message should be "private", i.e., only id 1 should receive it, no broadcasting allowed.
How should I approach this problem? How could I keep track of the connections at the server side so that I could send a message to a determined client? The problem is that it's the server the one sending the message to the client, not responding to a client's message. I guess it must be with some combination of threading and queues, but still haven't figured out how to do it.
This is the code I have right now at the server, keeping track of the clients using a dict, but it's not working (bad file descriptor at the sendall('C') line:
track_clients = {}
while True:
    print "waiting for a connection"
    connection, client_address = sock.accept()
    try:
        print "connection from ", client_address
        data = json.loads(connection.recv(1024))
        track_clients[data['id']] = connection

        if data['id'] == '2':
            conn = track_clients['1']
            conn.sendall('C')
        connection.sendall(json.dumps(data))
    finally:
        connection.close()

A: You can have a look at channels http://channels.readthedocs.org/en/latest/.
Alongside redis (https://pypi.python.org/pypi/redis/)

A: Have you considered using zeromq for this task?
It is easy to use and provides high level implementation of common patterns.
From zeromq guide

ZeroMQ (also known as ØMQ, 0MQ, or zmq) looks like an embeddable
  networking library but acts like a concurrency framework. It gives you
  sockets that carry atomic messages across various transports like
  in-process, inter-process, TCP, and multicast. You can connect sockets
  N-to-N with patterns like fan-out, pub-sub, task distribution, and
  request-reply. It's fast enough to be the fabric for clustered
  products. Its asynchronous I/O model gives you scalable multicore
  applications, built as asynchronous message-processing tasks. It has a
  score of language APIs and runs on most operating systems. ZeroMQ is
  from iMatix and is LGPLv3 open source.

Also it seems like it better to reuse existing libraries because you can focus on your tasks directly while library provides you with all required high-level methods.

A: The code above is OK. The problem is the connection.close() at the finally statement. Removing it, fixes the issue.


text:
Q: Insert BLOB into MS SQL DB using Perl script Please excuse my ignorance of Perl, as I'm a .NET developer (I can hear you all spitting and cursing already ;¬) )
We have a requirment to insert a BLOB (+ some other data) to an MS-SQL DB using a Perl script (our backend systems run on AIX using Perl scripts to go about thier daily business).
Our Perl guy, seemingly, ran into a problem: That the largest BLOB he could insert into the MS-SQL server (that us pesky .NETers use) was 64k but we need the Perl scripts to insert BLOBs of 2MB - 6MB.
If it is possible to insert BLOBs over 64k; could any one advise on an avenue of investigation that our Perl guy could persue in order to achive this?
Sorry for asking a question 'via proxy' but our Perl guru's on holiday.
Thanks in advance,
JD

A: If this is DBI, you can set the maximum buffer of your database handle to your desired limit:
$dbh->{LongReadLen} = 10485760;  # 10 MB

From the DBI FAQ:

How do I handle BLOB data with DBI?
Handling BLOB data with the DBI is
  very straight-forward. BLOB columns
  are specified in a SELECT statement as
  per normal columns. However, you also
  need to specify a maximum BLOB size
  that the database handle can
  fetch using the LongReadLen attribute.
For example:
### $dbh is a connected database handle
$sth = $dbh->prepare( "SELECT blob_column FROM blobby_table" );
$sth->execute; would fail.

### $dbh is a connected database handle
### Set the maximum BLOB size...
$dbh->{LongReadLen} = 16384;        ### 16Kb...Not much of a BLOB!
$sth = $dbh->prepare( "..." );

would succeed provided no column
  values were larger than the specified
  value.
If the BLOB data is longer than the
  value of LongReadLen, then an error
  will occur. However, the DBI provides
  an additional piece of functionality
  that will automatically truncate the
  fetched BLOB to the size of
  LongReadLen if it is longer. This does
  not cause an error to occur, but may
  make your fetched BLOB data useless.
This behaviour is regulated by the
  LongTruncOk attribute which is
  defaultly set to a false value ( thus
  making overlong BLOB fetches fail ).
### Set BLOB handling such that it's 16Kb and can be truncated
$dbh->{LongReadLen} = 16384;
$dbh->{LongTruncOk} = 1;

Truncation of BLOB data may not be a
  big deal in cases where the BLOB
  contains run-length encoded data, but
  data containing checksums at the end,
  for example, a ZIP file, would be
  rendered useless.

A: To insert a BLOB, you usually need to use placeholders. Prepare your statement with a placeholder, then bind the value you want to insert as follows:
$statement->bind_param(??, $myvalue, DBI::SQL_BLOB);
Where ?? is the position of the placeholder, starting at 1. Then you execute the statement as usual, e.g.:
$statement->execute();
As always, error handling is a good plan. We use this routinely with SQLite, but I'm pretty sure this is also correct for MSSQL and MySQL.


text:
Q: How to write this batch script in AutoIt? I'm trying to re-write a batch file in AutoIt. How would I do the following in AutoIt?
:BeginLangMenu
if "%OptNum%" gtr "0" goto ShowLangMenu

::Next Section code based on code supplied by Aacini from stackoverflow.com
:DefineLangMenu
for /L %%D in (1,1,99) do (
   if exist Common\Settings\Data%%D.ini for /F "eol=# tokens=1,2 delims==" %%a in (Common\Settings\Data%%D.ini) do (

      set line=%%a
      if "!line:~2,5!" neq "clude" (
         REM Define "normal" variables, i.e. Compressor, Method, etc.
         set %%a=
      ) else if "!line:~7!" neq "" (

         REM Define the base array elements, i.e. D1IncludeAR=%%b, D1ExcludeAR=%%b, ...
         set D%%D%%a=%%b

         REM Set Show?? array elements with value equal 1, i.e. ShowAR=1, ...
         REM when anyone of DiInclude?? or DiExclude?? corresponding elements was given
         if defined D%%D%%a set Show!line:~7!=1

      )
   )
)

REM Define a list of language abbreviations, i.e. "langs=AR CZ DE ..."
REM and the corresponding language names array, i.e. lang[AR]=Arabic, ...
REM At same time, calculate original OptNum

for %%a in ("AR=Arabic" "CZ=Czech" "DE=German" "EN=English" "ES=Spanish" "ESMX=Spanish(Mexico)"
            "FR=French" "HU=Hungarian" "IT=Italian" "JP=Japanese" "KR=Korean" "PL=Polish"
            "PR=Portuguese" "PRBR=Portuguese(Brazil)" "RU=Russian" "ZH=Chinese") do (
   for /F "tokens=1,2 delims==" %%b in (%%a) do (
      set "langs=!langs! %%b"
      set "lang[%%b]=%%c"
      set /A "OptNum+=Show%%b"

   )
)

::NEXT 2 SECTIONS DISPLAYS THE LANGUAGE SELECTION MENU IF APPLICABLE
:ShowLangMenu
set /a step=%step%+1
:LangMenu
if "%OptNum%"=="0" Goto checksplit
echo %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2% - Showing Language Selection Menu >> "%workdir%Conversion.log"
REM Show the language menu
set #=0
for %%a in (%langs%) do (
   if defined Show%%a (
      set /A #+=1
rem       echo [!#!] !lang[%%a]!
      echo !lang[%%a]! >> %b2eincfilepath%\Lang.txt
      set "option[!#!]=%%a"
   )
)

%MYFILES1%\DROPDOWNBOX.exe /F:"%b2eincfilepath%\Lang.txt" "Choose Which Language to Compress" "STEP %step%: Language Selection"  /W:280 /RI /C:13 >nul > %b2eincfilepath%\LangAnswer.txt
if %ERRORLEVEL% EQU 0 del %b2eincfilepath%\LangAnswer.txt
if exist %b2eincfilepath%\LangAnswer.txt set /p "SelectLang="<%b2eincfilepath%\LangAnswer.txt
if not defined SelectLang goto LangError
if %SelectLang%==Arabic Set LangOpt=AR
if %SelectLang%==Czech set LangOpt=CZ
if %SelectLang%==German set LangOpt=DE
if %SelectLang%==English set LangOpt=EN
if %SelectLang%==Spanish set LangOpt=ES
if %SelectLang%==Spanish(Mexico) set LangOpt=ESMX
if %SelectLang%==French set LangOpt=FR
if %SelectLang%==Hungarian set LangOpt=HU
if %SelectLang%==Italian set LangOpt=IT
if %SelectLang%==Japanese set LangOpt=JP
if %SelectLang%==Korean set LangOpt=KR
if %SelectLang%==Polish set LangOpt=PL
if %SelectLang%==Portuguese set LangOpt=PR
if %SelectLang%==Portuguese(Brazil) set LangOpt=PRBR
if %SelectLang%==Russian set LangOpt=RU
if %SelectLang%==Chinese set LangOpt=ZH
if defined SelectLang Goto LangSet

::SETS THE LANGUAGE SELECTION ACCORDING TO USER INPUT IN LANGUAGE MENU
:LangSet
set "LangIs=%LangOpt%"

My code so far:
For $D = 1 To 99 Step +1
    if FileExists (@ScriptDir & "\Common\Settings\Data" & $D & ".ini") Then
        $aLangs = IniReadSection (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude")
        If Not @error Then
            for $i = 1 to $aLangs[0][0]

Problem is it reads into arrays empty keys from the INI files as well. I need the IncludeAR, IncludeEN, etc. -keys and set a list of languages in a dropdown menu GUI accordingly.
Then it should set selected language to a variable and another corresponding variable with the value of selected languages from the INI files.

A: OK, I've managed to eventually create what I wanted on my own, it is crude but it works, I just had to avoid using IniReadSection and Arrays, I used IniRead instead and a lot of If...Then...Else statements, here's the code:
For $D = 1 To 99 Step +1
    if FileExists (@ScriptDir & "\Common\Settings\Data" & $D & ".ini") Then
        $ARi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeAR", "")
        $CZi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeCZ", "")
        $DEi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeDE", "")
        $ENi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeEN", "")
        $ESi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeES", "")
        $ESMXi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeESMX", "")
        $FRi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeFR", "")
        $HUi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeHU", "")
        $ITi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeIT", "")
        $JPi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeJP", "")
        $KRi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeKR", "")
        $PLi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludePL", "")
        $PRi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludePR", "")
        $PRBRi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludePRBR", "")
        $RUi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeRU", "")
        $ZHi = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangInclude", "IncludeZH", "")
        $ARe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeAR", "")
        $CZe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeCZ", "")
        $DEe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeDE", "")
        $ENe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeEN", "")
        $ESe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeES", "")
        $ESMXe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeESMX", "")
        $FRe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeFR", "")
        $HUe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeHU", "")
        $ITe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeIT", "")
        $JPe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeJP", "")
        $KRe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeKR", "")
        $PLe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludePL", "")
        $PRe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludePR", "")
        $PRBRe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludePRBR", "")
        $RUe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeRU", "")
        $ZHe = IniRead (@ScriptDir & "\Common\Settings\Data" & $D & ".ini", "LangExclude", "ExcludeZH", "")

Global $OptNum
Global $LangOptions

If Not IsDeclared ("AR") Then
    If Not $ARe = "" Or Not $ARi = "" Then $AR = "Arabic"
EndIf

If Not IsDeclared ("CZ") Then
    If Not $CZe = "" Or Not $CZi = "" Then $CZ = "Czech"
EndIf
If Not IsDeclared ("DE") Then
    If Not $DEe = "" Or Not $DEi = "" Then $DE = "German"
EndIf
If Not IsDeclared ("EN") Then
    If Not $ENe = "" Or Not $ENi = "" Then $EN = "English"
EndIf
If Not IsDeclared ("ES") Then
    If Not $ESe = "" Or Not $ESi = "" Then $ES = "Spanish"
EndIf
If Not IsDeclared ("ESMX") Then
    If Not $ESMXe = "" Or Not $ESMXi = "" Then $ESMX = "Spanish(Mexico)"
EndIf
If Not IsDeclared ("FR") Then
    If Not $FRe = "" Or Not $FRi = "" Then $FR = "French"
EndIf
If Not IsDeclared ("HU") Then
    If Not $HUe = "" Or Not $HUi = "" Then $HU = "Hungarian"
EndIf
If Not IsDeclared ("IT") Then
    If Not $ITe = "" Or Not $ITi = "" Then $IT = "Italian"
EndIf
If Not IsDeclared ("JP") Then
    If Not $JPe = "" Or Not $JPi = "" Then $JP = "Japanese"
EndIf
If Not IsDeclared ("KR") Then
    If Not $KRe = "" Or Not $KRi = "" Then $KR = "Korean"
EndIf
If Not IsDeclared ("PL") Then
    If Not $PLe = "" Or Not $PLi = "" Then $PL = "Polish"
EndIf
If Not IsDeclared ("PR") Then
    If Not $PRe = "" Or Not $PRi = "" Then $PR = "Portuguese"
EndIf
If Not IsDeclared ("PRBR") Then
    If Not $PRBRe = "" Or Not $PRBRi = "" Then $PRBR = "Portuguese(Brazil)"
EndIf
If Not IsDeclared ("RU") Then
    If Not $RUe = "" Or Not $RUi = "" Then $RU = "Russian"
EndIf
If Not IsDeclared ("ZH") Then
    If Not $ZHe = "" Or Not $ZHi = "" Then $ZH = "Chinese"
EndIf
    EndIf
    Next
if IsDeclared ("AR") then
    $OptNum+=1
    If $OptNum = 1 Then
        $LangOptions = "Arabic"
    EndIf
EndIf
if IsDeclared ("CZ") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Czech"
    Else
        $LangOptions = "Czech"
    EndIf
EndIf
if IsDeclared ("DE") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|German"
    Else
        $LangOptions = "German"
    EndIf
EndIf
if IsDeclared ("EN") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|English"
    Else
        $LangOptions = "English"
    EndIf
EndIf
if IsDeclared ("ES") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Spanish"
    Else
        $LangOptions = "Spanish"
    EndIf
EndIf
if IsDeclared ("ESMX") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Spanish(Mexico)"
    Else
        $LangOptions = "Spanish(Mexico)"
    EndIf
EndIf
if IsDeclared ("FR") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|French"
    Else
        $LangOptions = "French"
    EndIf
EndIf
if IsDeclared ("HU") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Hungarian"
    Else
        $LangOptions = "Hungarian"
    EndIf
EndIf
if IsDeclared ("IT") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Italian"
    Else
        $LangOptions = "Italian"
    EndIf
EndIf
if IsDeclared ("JP") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Japanese"
    Else
        $LangOptions = "Japanese"
    EndIf
EndIf
if IsDeclared ("KR") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Korean"
    Else
        $LangOptions = "Korean"
    EndIf
EndIf
if IsDeclared ("PL") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Polish"
    Else
        $LangOptions = "Polish"
    EndIf
EndIf
if IsDeclared ("PR") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Portuguese"
    Else
        $LangOptions = "Portuguese"
    EndIf
EndIf
if IsDeclared ("PRBR") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Portuguese(Brazil)"
    Else
        $LangOptions = "Portuguese(Brazil)"
    EndIf
EndIf
if IsDeclared ("RU") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Russian"
    Else
        $LangOptions = "Russian"
    EndIf
EndIf
if IsDeclared ("ZH") then
    $OptNum+=1
    If $OptNum > 1 Then
        $LangOptions = $LangOptions & "|Chinese"
    Else
        $LangOptions = "Chinese"
    EndIf
EndIf

After that there's a check for $OptNum and if it's bigger than 1 it displays the GUI with the DropDown box which is being created with $LangOptions.
On Pressing OK the Selected languages is transferred into a Variable of my choice and then I can manipulate it as I see the need to down the road.

A: main.au3
; Create test GUI with a combo and a button
GUICreate('test', 300, 300)
$iCombo = GUICtrlCreateCombo('', 5, 5, 150)
$iButton = GUICtrlCreateButton('Set Language', 5, 40)
GUISetState()

; Read languages from ini file.
$aLang = IniReadSection('test.ini', 'lang')
If @error Then
    ; Use default language on error.
    Global $aLang[][] = [[1, ''], ['EN', 'English']]
EndIf

; Prepare combo list as string.
$sComboList = ''
For $i1 = 1 To UBound($aLang) -1
    $sComboList &= $aLang[$i1][1] & '|'
Next

; Trim last | from combo string.
$sComboList = StringTrimRight($sComboList, 1)

; Update combo ctrl and set default language.
GUICtrlSetData($iCombo, $sComboList, 'English')
$sLangShortname = 'EN'

While 1
    Switch GUIGetMsg()
        Case -3 ; $GUI_EVENT_CLOSE
            Exit
        Case $iButton
            ; Read from combo ctrl.
            $sLangFullname = GUICtrlRead($iCombo)
            ; Set short name from full name.
            For $i1 = 1 To UBound($aLang) -1
                If $aLang[$i1][1] = $sLangFullname Then
                    $sLangShortname = $aLang[$i1][0]
                    ExitLoop
                EndIf
            Next
            ; Show result of current of short name and full name.
            MsgBox(0, 'Lang', _
             'Fullname: ' & $sLangFullname & @CRLF & _
             'Shortname: ' & $sLangShortname _
            )
    EndSwitch
WEnd

test.ini
[lang]
AR=Arabic
CZ=Czech
DE=German
EN=English
ES=Spanish
ESMX=Spanish(Mexico)
FR=French
HU=Hungarian
IT=Italian
JP=Japanese
KR=Korean
PL=Polish
PR=Portuguese
PRBR=Portuguese(Brazil)
RU=Russian
ZH=Chinese

I do not understand all the complication of handling the ini
so I created test.ini as simple as possible.
main.au3 reads the ini section of [lang] into a 2d array.
This array contains the short names and the full names.
The combo takes a string of items delimited by | so a for
loop creates the string. The combo is updated with the string
to add items to the combo for selection.
Clicking the button will set 2 variables with the short name
and long name of the selected language. A Message Box will
display the values of the 2 variables.


text:
Q: C++ vector of custom template class as member I'm currently coding a program in c++ using a template class:
template<typename TYPE>
class TemplateClass {
private:
    TYPE t;
};

I have another class which acts as manager of my TemplateClass which should store multiple instances of this class in a vector. Different instances should have different types e.g. int, std::string, etc.. Speaking in Java ways the solution would be to just use something like in the example below but it seems like this is not possible in C++.
class ManagerClass {
private:
    // Here seems to be the problem.
    std::vector<TemplateClass<?>> templates;
}

Is it possible to do something like that?
Thank you for all answers

A: If you know all the types that will be stored in the std::vector at compile time I'd use an std::variant in such a case.
// This is used for the visitor pattern.
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
// The below line not needed in C++20...
template<class... Ts> overload(Ts...) -> overload<Ts...>;

template<typename T>
struct MyClass { T value; };

using types = std::variant<
    MyClass<std::string>,
    MyClass<int>,
    MyClass<double>>;

int main()
{
    std::vector<types> stuff{};
    stuff.push_back(MyClass<std::string>{});
    stuff.push_back(MyClass<int>{});
    stuff.push_back(MyClass<double>{});

    for(const auto& v : stuff)
    {
        if (std::holds_alternative<MyClass<std::string>>(v))
        {
            std::cout << "Im a string\n";
        }
        else if (auto* p{std::get_if<MyClass<int>>(&v)})
        {
            std::cout << "Im an int\n";
        }
        else
        {
            auto t = std::get<MyClass<double>>(v);
            std::cout << "Im a double\n";
        }

        // Or you can use the visitor pattern.
        std::visit(overload{
            [](const MyClass<std::string>& ) { std::cout << "I'm a string\n"; },
            [](const MyClass<int>& ) { std::cout << "I'm a int\n"; },
            [](const MyClass<double>& ) { std::cout << "I'm a double\n"; },
        }, v);
    }
}

A: If you can use C++17, you can use std::any or std::variant.
class ManagerClass {
private:
    using variant_type = std::variant<
          TemplateClass<std::string>,
          TemplateClass<int>,
          TemplateClass<double> >;
    std::vector<variant_type> templates;
};

A: This is one way of doing it via runtime polymorphishm, which is achieved by function overriding. Function overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
#include <iostream>
#include <vector>

using namespace std;

// Base class declaration
class Base {
public:
    virtual void print()
    {
        cout << "Base" << endl;
    }
    virtual ~Base(){}
};

// Derived Class 1
class Derived1 : public Base {
public:
    void print()
    {
        cout << "Derived1" << endl;
    }
};

// Derived class 2
class Derived2 : public Base {
public:
    void print()
    {
        cout << "Derived2" << endl;
    }
};

int main()
{
    Base* d1 = new Derived1();
    Base* d2 = new Derived2();

    vector<Base*> myVec;
    myVec.push_back(d1);
    myVec.push_back(d2);

    for (auto i : myVec) {
        i->print();
    }

    delete d1;
    delete d2;

    return 0;
}


text:
Q: App get force stop run on lollipop version I am an android beginner, I have developed one app, it was working kitkat version, but it's not supported in lollipop version (nexus 5). When I run the app in nexus 5 the app get force stop. This problem arrives development side or lollipop side Any one can help me
For your reference I have used android version as below
Min sdk is 14
Taget Sdk is 21

A: It may be because of some libraries you have used.I got the same issue when I was having simonvtmenudrawer in my app which was not supported in lolipop.I replaced the same and it is now working fine.


text:
Q: Adjusting JS Live Search to show results regardless of word order I created a simple javascript live search & disappear to filter names from a list, but now I'm running into trouble when someone searches for "John Smith" and can't find him because he's in the list as "John H. Smith". Is there anything I can add to the js code to have the search look for the input's contents regardless of word order or if there's a middle initial or middle name between the first name and last name?
Codepen for reference: https://codepen.io/naomimekeel/pen/rNzoeGQ
View the live page example: https://www.giveto.pitt.edu/s/1729/18/interior-giving.aspx?sid=1729&gid=2&pgid=5065

    <input type="text"
           id="facstaff-search"
           name="facstaff-search"
           rel="facstaff-search"
           placeholder=" Search for a donor on this list . . ." />

Sorry, no results found! Please check your spelling or try again.

+Terry Laughlin KGSB '81 & Regina L. Aldisert

+Dr. W. Harry Archer, DEN '27, A&S '37 & +Mrs. Louise E. Archer, A&S '27

+Lauren H. Ashe, A&S '14

let foundOne = false;
const none = document.getElementById('none');
const searchInput = document.querySelector('input[rel="facstaff-search"]');
const data = document.querySelectorAll(".facstaff-data-item");
show(false);
searchInput.addEventListener('input', function (event) {
    // reset state
    show(false)
    foundOne = false;
    const input = event.target
    if (input.value) {
        const toMatch = input.value.toLowerCase();
        for (let i = 0, len = data.length; i < len; i++) {
            const match = data[i].innerHTML.toLowerCase().includes(toMatch);
            data[i].style.display = match ? 'block' : 'none';
            if (match) foundOne = true;
        }
        if (!foundOne) show(true);
    } else
        resetState()

});
function resetState() {
    for (let i = 0, len = data.length; i < len; i++)
        data[i].style.display = 'block';

}
function show(bool) {
    none.style.display = bool ? 'block' : 'none';
}


text:
Q: Non-negativity of a measure On all textbooks that I have read so far, there are only two conditions for which a function $\mu:\Sigma\to[0,+\infty]$ is a measure on a measurable space $(X,\Sigma)$, which are:

*

*$\mu(\emptyset)=0$,

*$\mu$ is $\sigma$-additive.

However, most of the textbooks leave the non-negativity of $\mu$ as a remark. Why is that not included in the definition? If that follows immediately from the definition, then how?

A: There are various types of measures: positive measures, real measures, complex measures, vector measure etc. In elementary books dealing with positive measures they impose the condition $\mu(E) \geq 0$ for all sets $E$ in the sigma algebra. Note that if $m$ is Lebesgue measure them $\mu(E)=-m(E)$ defines a set functions satisfying 1) and 2). So positivity does not follow from 1) and 2).

A: The question is not clear, because you don't specify exactly what definition you have in mind (the two major typos don't help).
A version of the standard definition is this:

Def A measure on the measurable space $(X,\Sigma)$ is a map $\mu:\Sigma:\to[0,\infty]$ such that $\mu(\emptyset)=0$ and $\mu$ is $\sigma$-additive.

Non-negativity is included in that definition! Saying $\mu:\Sigma\to[0,\infty]$ means precisely that $0\le \mu(E)\le\infty$ for every $e\in\Sigma$.


text:
Q: A guide to justify the calculation of $\operatorname{Ai}'(0)$: differentiation under the integral sign I would like to know how to justify rigorously that $$-\frac{1}{\pi}\int_0^\infty t\sin\left(\frac{t^3}{3}+0\right)dt=\operatorname{Ai}'(0).\tag{1}$$
I've performed the differentiation under the integral sign for the integral representation of the Airy function $\operatorname{Ai}(x)$ and with the help of Wolfram Alpha online calculator:
int -1/pi t*sin(t^3/3)dt, from t=0 to infinity
I did a comparison. I've used the formula from this Wikipedia.

Question. I know that numerically my statement $(1)$ is right, but what details are required for a rigorous proof? I only request a guide with hints about what is required to check, even the convergence of the resulting improper integral. Thank you very much.

A: By addition formula for $\cos$, we have $\cos(t^3/3 + xt) = \cos(t^3/3)\cos xt - \sin(t^3/3) \sin xt$.
If we can prove that $f(x)=\int_0^{\infty} \cos(t^3/3) \cos xt dt$ is differentiable under integral sign, then the same argument will work for $g(x) = \int_0^{\infty} \sin(t^3/3)\sin xt dt$. For $g(x)$, we need to split the integral into $\int_0^1$ and $\int_1^{\infty}$ due to the singularity at $t=0$.
Integration by parts ($u=(\cos xt)/t^2$, $dv=t^2\cos(t^3/3)dt$) --- my previous answer had an error in finding $du$ --- gives
$$
f(x) = \frac{\sin(t^3/3)\cos xt}{t^2} \Bigg\vert_0^{\infty} + \int_0^{\infty} \frac{  x t^2\sin xt+2t\cos xt}{t^4} \sin(t^3/3) dt.
$$
Let us consider $\lim_{x\rightarrow 0+} \frac{f(x)-f(0)}x$, since $x\rightarrow 0-$ can be treated the same way. So, let $x_n$ be a sequence of positive real numbers converging to $0$. Then
$$
\begin{align}
\frac{f(x_n)-f(0)}{x_n} &= \int_0^{\infty} \left( \frac{  x_n t^2\sin x_n t+2t(\cos x_n t -1)}{x_nt^4}\right) \sin (t^3/3) dt
\end{align}
$$
By the Mean Value Theorem, inside of the big paranthesis is bounded by $C/t^2$ uniformly in $n$, for some $C>0$. Thus, we can apply the Dominated Convergence Theorem to obtain
$$\begin{align}
\lim_{n\rightarrow\infty} \frac{f(x_n)-f(0)}{x_n}  &= \int_0^{\infty} \lim_{n\rightarrow\infty} \left( \frac{ x_n t^2\sin x_n t+2t(\cos x_n t -1)}{x_nt^4}\right) \sin (t^3/3) dt < \infty.\end{align}
$$
Thus, the results are the same with $x=0$ plugged in to the expression of $f'$ after differentiated under integral.
Let $g(x)=g_1(x)+g_2(x)$ where the integral is performed as $\int_0^1$ for $g_1$ and $\int_1^{\infty}$ for $g_2$. Then $g_1'$ under integral sign is justified by the Dominated Convergence Theorem without resorting to the integration by parts. We treat $g_2$ with the integration parts.
Integration by parts ($u=(\sin xt)/t^2$, $dv=t^2\sin(t^3/3)$) gives
$$
g_2(x) = \frac{-\cos(t^3/3)\sin xt}{t^2} \Bigg\vert_1^{\infty} + \int_1^{\infty} \frac{xt^2\cos xt-2t\sin xt}{t^4} \cos(t^3/3) dt.
$$
Let us consider $\lim_{x\rightarrow 0+} \frac{g_2(x)-g_2(0)}x$, since $x\rightarrow 0-$ can be treated the same way. So, let $x_n$ be a sequence of positive real numbers converging to $0$. Then
$$
\begin{align}
\frac{g_2(x_n)-g_2(0)}{x_n} &= \cos(1/3)\frac{\sin x_n}{x_n}+\int_1^{\infty} \left( \frac{x_nt^2\cos x_nt - 2t\sin x_n t}{x_nt^4}\right) \cos (t^3/3) dt
\end{align}
$$
By the Mean Value Theorem, inside of the big paranthesis is bounded by $C/t^2$ uniformly in $n$, for some $C>0$. Thus, we can apply the Dominated Convergence Theorem to obtain
$$\begin{align}
\lim_{n\rightarrow\infty} \frac{g_2(x_n)-g_2(0)}{x_n}  &= \cos(1/3)\frac{\sin x_n}{x_n}+  \int_1^{\infty} \lim_{n\rightarrow\infty} \left( \frac{x_nt^2\cos x_nt - 2t\sin x_n t}{x_nt^4}\right) \cos (t^3/3) dt\\
&= \cos(1/3) + \int_1^{\infty} \left(\frac1{t^2}-\frac2{t^2}\right)\cos(t^3/3)dt\end{align}
$$
Thus, the results are the same with $x=0$ plugged in to the expression of $g_2'$ after differentiated under integral. In fact, integration by parts ($u=1/t $, $dv=t^2\sin(t^3/3)dt$)
$$
\int_1^{\infty} t\sin(t^3/3)  dt=\cos(1/3) + \int_1^{\infty} \left(-\frac1{t^2} \right)\cos(t^3/3)dt.
$$

A: We shall prove a more general result. Let $\varphi\in C^{(1)}[0,\infty) \land \big(|\varphi(t)|<1,\,\forall t\in[0,\infty)\big)$. Let $f(t,x) = \varphi\big(\frac{t^3}3+xt\big)$. We will show the differentiation under the integral works for all $x\ge 0$. $I(x)=\int_0^\infty f(t,x)dt$. We need to show
$$\lim_{\delta\to 0}\int_0^\infty \frac{f(t,x+\delta)-f(t,x)}{\delta}dt = \int_0^\infty \lim_{\delta\to 0}\frac{f(t,x+\delta)-f(t,x)}{\delta}dt. \tag1$$
Define
\begin{align}
I_1(x) &:= \int_0^1\varphi\big(\frac{t^3}3+xt\big)\,dt \\
I_2(x) &:= \int_1^\infty\varphi\big(\frac{t^3}3+xt\big)\,dt
\end{align}
Consider $I_2$ first.
Let $u:=\frac{t^3}3+xt$. Surely $u>0$.
$$u<\frac{(t+x)^3}3\Longleftrightarrow (3u)^\frac13-x<t,\,\forall (t>1\land x\ge0). \tag2$$
Now $(u,x)$ is the independent variable, while $t$ becomes a function of $(u,x)$ and is denoted as $t(u,x)$.
$$1 = (t^2+x)\frac{\partial t}{\partial u}$$
$$0=t^2\frac{\partial t}{\partial x}+t+x\frac{\partial t}{\partial x}\Longleftrightarrow \frac{\partial t}{\partial u}=-\frac{t}{t^2+x}$$
$$\frac{\partial}{\partial x}\frac1{t(u,x)^2+x}=-\frac{2t\frac{\partial t}{\partial x}+1}{(t^2+x)^2}=\frac1{(t^2+x)^2}\frac{t^2-x}{t^2+x},$$
$$I_2(x)=\int_{\frac13+x}^\infty \frac{\varphi(u)}{t^2+x}du,$$
and
$$\frac{I_2(x+\delta)-I_2(x)}\delta=J_{2,1}-J_{2,2}$$
where
\begin{align}
J_{2,1}&:=\int_{\frac13+x}^\infty\varphi(u)g(u,x,\delta)du \\
J_{2,2}&:= \frac1\delta\int_{\frac13+x}^{\frac13+x+\delta}\frac{\varphi(u)}{t(u,x+\delta)^2+x+\delta}\,du,
\end{align}
where
\begin{align}
g(u,x,\delta) &:= \frac1\delta\Big(\frac1{t(u,x+\delta)^2+x+\delta}-\frac1{t(u,x)+x}\Big) \\
&=\frac1{(t(u,x+\theta\delta)^2+x+\theta\delta)^2}\frac{t(u,x+\theta\delta)^2-(x+\theta\delta)}{t(u,x+\theta\delta)^2+(x+\theta\delta)}
\end{align}
for some function $\theta:=\theta(u,x,\delta)\in[0,1]$ with the second equation coming from Taylor expansion to the first order.
By inequality (2), for some positive function $C$, $\forall u>C(x)$,
$$t(u,x)^2+x>((3u)^\frac13-x)^2+x>u^\frac23,$$
$$0<\frac{t(u,x)^2-x}{t(u,x)^2+x}\le 1$$
$\forall u>C(u+\Delta),\ \forall \delta<\Delta$, for some $\Delta>0$,
$$0<g(u,x,\delta)<\frac1{u^\frac43}$$
So
$$\int_{C(x+\Delta)}^\infty g(u,x,\delta)\varphi(u)du<\int_{C(x+\Delta)}^\infty\frac1{u^\frac43}du<\infty$$
For $g(u,x,\delta)$ is continuous for $(u,\delta)$ on a compact set $\big[\frac13+x,C(x+\Delta)\big]\times[0,\Delta]$ and thus is bounded for any given $x>0$.
Hence we can apply the Lebesgue's dominated convergence theorem to the integral $J_{2,1}$ as $\delta\to0$.
It is easy to see $J_{2,2}\to\frac{\varphi(\frac13+x)}{1+x}$ as $\delta\to0$ since the integrand is continuous on a compact set.
Now we consider
$$\frac{I_1(x+\delta)-I_1(x)}{\delta}
=\int_0^1\frac1\delta\Big(\varphi\Big(\frac{t^3}3+x+\delta\Big)-\varphi\Big(\frac{t^3}3+x\Big)\Big)\, dt
=\int_0^1\varphi'\Big(\frac{t^3}3+x+\theta_1\delta\Big)\, dt
$$
for some function $\theta_1:=\theta_1(\frac{t^3}3+x,\delta)\in[0,1]$.
As $\varphi\in C^{(1)}$ on a compact set, it is uniformly bounded with respect to $(t,\delta)$ for any given $x$. We can thus apply again Lebesgue's dominated convergence theorem to the above integral.
Summing up equation (1) is proved.

A: If I understand your question correctly, you are asking how we derive the solution to Airy function as a complex Riemannian integral?
If so, consider the Airy equation:
$$
(1) \qquad \frac{d^2 y}{dx^2} - xy = 0
$$
If we search for a contour integral solution in some unknown function, over some general contour $C$ in the complex plane.
$$
y(x) = \int _C f(z) e^{xz} dz
$$
Inserting this into (1) we find:
$$
\int _C ( z^2 -x) f(z) e^{xz} dz = 0
$$
We then integrate the negative bit by parts:
$$
0 = - f(z)e^{xz} \bigg|_C + \int _C \bigg( z^2f + \frac{df}{dz}\bigg) e^{xz} dz
$$
If we choose $f(z) = e^{- z^3/3}$ then we must insist that at the end points of the contour:
$$
f(z)e^{xz} \bigg|_C  = e^{-z^3/3 + zx} \bigg|_C = 0
$$
There are then three regions $j_{1,2,3}$ for a positive cosine where the contour vanishes in the complex plane giving us three functions; one for each region.
$$
f_j = \frac{1}{2\pi} i \int _{C_j} e^{- z^3/3+ xz} dz
$$
We define the Airy function as the above solution evaluated in one of these regions. The function is expressed as:
$$
\operatorname{Ai}(x) = \frac 1 \pi \int ^\infty_0 \cos (  z^3/ + xz) dz = \frac {1}{2\pi} \int ^\infty _0 e^{i(z^3/3 _xz) }dz + \frac {1}{2\pi} \int ^\infty _ 0 e^{i(z^3/3 _xz)} dz
$$
Using Jordan's lemma rotate the integral anti-clockwise in the first and clockwise in the second integrand. This will result in:
$$
\operatorname{Ai}(x) = \frac 1{2\pi} \int ^\infty _0 e^{ i (z^3/3 e^{3i\theta} + xze^{i\theta})} + \frac 1{2\pi} \int ^\infty _0 e^{- i (z^3/3 e^{-3i\theta} + xze^{-i\theta})} e^{-i\theta}dz
$$
We then tidy them exponents to converge:
$$
\operatorname{Ai}(x) = \frac 1 \pi \Re \bigg( \int ^\infty_ 0 e^{\frac{z^3}{3} ( - \sin(3\theta) + i \cos (3\theta)) + xz(-\sin (\theta) + i \cos(\theta)) + i\theta} dz\bigg)
$$
Now we use the following integral assured of the convergence:
$$
\int ^\infty _0 z^\lambda \cos (\frac {z^3}{3} + xz)dz = \frac 1 3 \int ^\infty_0 z^{\frac{(\lambda - 2)}{3}} \cos( \frac 1 3 z + x z^{\frac 1 3})dz
$$
In specific response to your question, differentiating under the integral sign:
$$
\frac{d}{dx}\int ^b_a f(x,z) dz = \int ^b_a \frac{\partial f(x,z)}{\partial x} dz
$$
Cannot be used since we are not certain that the R.H.S exists. That is why we perform the rotation to assure us of an exponentially convergent integrand.


text:
Q: How to overwrite default value from properties of this object with call or apply method in JS I've started learning call, apply and bind and now i want to use it but have some problems:
I have a function:
let addTableRow = function() {
    let template = HtmlTemplatesTelephony.ks.renderTableRow;
    this.id = "";
    this.creationDate = "";
    this.address = "";
    this.numberOfUser = "";
    this.accessExisting = true;
    $(DOM.tableBodyContainer).append(template(this));
};

I declared the this properties as default values
Here i invoke the function either with .call() or without:
let updateTable = function() {
    let locations = userData().locations;
    if(locations.length > 0) {
        for(let location of locations) {
            UIController.addLocation.call(location);
        }
    } else {
        UIController.addLocation();
    }
};

My idea was to use the 'this' values in the 'addTableRow' as default values in case of invoking the function without .call(). And when calling it with .call() I want to overwrite the 'this' default values. But exactly the opposite happens.
I know I could pass the object as parameter and set default object, but is there an other way to do it with .call()? Or is it the wrong use case for .call()?
Thanks for help!
*****  UPDATE  ******
Sorry, it is written in module pattern and i forgot to mention that the function 'addTableRow' is called 'addLoaction' in the return object. Here's some more code:
My UI controller:
let UIController = (function() {
let DOM = {
    tableHeadContainer: $('thead'),
    tableBodyContainer: $('tbody'),
    inputNumberLocations: $('#numberLocations'),
    inputAddress: $('.js-location-address'),
    inputUser: $('.js-location-user'),
    inputVpn: $('.js-location-vpn'),
    btnDeleteLocation: $('.js-delete-location'),
};

let addTableRow = function() {
    let template = HtmlTemplatesTelephony.ks.renderTableRow;
    this.id = "";
    this.creationDate = "";
    this.address = "";
    this.numberOfUser = "";
    this.accessExisting = true;
    $(DOM.tableBodyContainer).append(template(this));
};

return {
    getDOM: DOM,
    addLocation: addTableRow,
    removeLocation: removeTableRow

}

})();
And my main controller:
let Controller = (function(dataController, UIController) {

let updateTable = function() {
    let locations = userData().locations; // locations has the same properties as in function 'addTableTow'
    if(locations.length > 0) {
        for(let location of locations) {
            UIController.addLocation.call(location);
        }
    } else {
        UIController.addLocation();
    }
};

return {
    init: function() {
        setupEventListeners();
        updateTable();
    },
}

})(dataController, UIController);
I hope it's more clear now.

A: When you .call(obj), you are starting your function with this being equal to that object. When you say this.id = "", you are overriding the id that you already had.
This may be a solution to your problem:
if (!this.id) {
  this.id = "";
}
if (!this.property) {
  this.property = "default";
}
// etc.


text:
Q: Mixing variables with text in Javascript Im trying (unsuccessfully) to prepend the following content to a div:
var entry = $('textarea').val();
var formated = '

' . entry . '

';

    $('#entry_container').prepend(formated);

I think the reason it isn't work is related to the way I am mixing variables and text. I looked at the documentation but I can't figure out what the issue is.

A: Try
var entry = $('textarea').val();
var formated = '

' + entry + '

';

    $('#entry_container').prepend(formated);

A: . is for object property lookup in JavaScript. You may have been in the PHP world for too long.
You can concatenate strings in JavaScript with the String object's concat() method or with + (it is overloaded to do arithmetic addition and string concatenation).


text:
Q: open screen/view (iPhone app) I have a iOS developer.  He is writing he iPhone app.
I am writing the web service that is used by the iPhone app.
The mobile app has many screens (or views what do you call it?)
What response does my web service need to respond with so that the mobile app knows what screen to open. There are many screens, and different screen input parameters.
Note: im not an objective-c developer. So I dont know what my developer wants my web service to respond with.

A: ASK YOUR DEVELOPER! (and they're called views). Someone developing a web service shouldn't be worried about views, that's definitely a dev issue

A: It depends on requirement you don't need to do anything with screens(views). This depends on Requirement of the project. What data has o be displayed for a specific screen you need to create functions for that only. The developer will call your web service function and your web service will return response in format of json(I prefer because it's lightweight and fast) or XML. The ios developer will parse the response and display the data on screen. Now it's up to him how he uses your web services. For example assume there is login screen so iphone app will send you user name and password your web service validate the credential and send response as success or failure. I hope you understand.


text:
Q: StringFormat ("0214" to "02:14") I have a String "0214" i would like te present this as 02:14 is this possible in wpf with stringFormat and binding.
If it would be an integer i could do it like bellow but the problem is that the "0" disapears and becomes Int "214" But this is not good for placing in the database because it requires 4 numbers.
<GridViewColumn Header="Start" DisplayMemberBinding="{Binding Start, StringFormat={}{0:00\:00}}"/>

output: '02:14'

A: StringFormat is not actually used to format strings. It's used to format non-string values into strings.
You can use an IValueConverter however to convert your string into the format you want. Another option would be to alter your data class to expose a read-only FormattedStart property which returns the formatted value.

A: *

*Use a converter to split the input string and return the two parts separated by a :

*Convert to an int and use StringFormat={}{0:00\\:00}} (This should be the equivalent of int.ToString("00':'00")


text:
Q: ThinkPad X1 Yoga 3rd Gen on Ubuntu 20.04, stylus calibration erratic Using a 3rd Generation ThinkPad X1 Yoga with 1440p display, the stylus calibration in default GNOME on Ubuntu 20.04 is erratic and unreliable. Trying to calibrate the stylus in the GNOME Settings Wacom section often results in the stylus being wildly miscalibrated (so the cursor is a quarter of screen away from the actual stylus).
I seem to eventually, after logging and logging out, switching between X11 and Wayland, and trying calibration several times to be able to get the stylus to recalibrate, but it's unclear what actually gets it to calibrate properly or why it so badly miscalibrates so often.

A: This is most likely a bug in the GNOME Control Center. I would file an issue at https://gitlab.gnome.org/GNOME/gnome-control-center/-/issues/ which describes the problem and the developers may be able to help. It would help them to know if you have any external displays connected (along with their resolution and layout) or if only the Yoga's internal display is present.


text:
Q: How to pass back control of a program to the calling function in a while loop I have a little visual poker dice app I'm working on, and I'm adding a help screen that clarifies rules and payouts.  I'm running my program in a while loop, so currently whenever the help button gets pressed, it never breaks back out of the loop, even when the help function has completed.  Not sure exactly why.  Here are the two functions:
class PokerApp(object):

    def __init__(self, interface):
        self.dice = Dice()
        self.money = 100
        self.interface = interface

    def run(self):
        choice = self.interface.want_to_play()
        while self.money >= 10 and choice != "Quit":
            if choice == "Help":
                self.interface.help()
                self.run()
            else:
                self.play_round()
        self.interface.close()

Then my help function:
def help(self):
        rule_format = "{value:<20}{reward:>5}".format
        help_screen = Rectangle(Point(100, 300), Point(500, 100))
        help_screen.setFill("gray")
        help_screen.draw(self.win)
        help_title = Text(Point(300, 125), "Dice Poker Rules")
        help_title.setSize(16)
        help_title.setStyle("bold")
        help_title.draw(self.win)
        value_reward = [("Two Pairs", 5), ("Three of a Kind", 8), ("Full House", 12),
                        ("Four of a Kind", 15), ("Straight", 20), ("Five of a Kind", 30)]
        rule_start = [200, 260]
        rules = []
        for value, reward in value_reward:
            rules.append(Text(Point(*rule_start), rule_format(value=value, reward=reward)))
            rule_start[1] -= 20

        for index, item in enumerate(rules):
            item.draw(self.win)

        while True:
            p = self.win.getMouse()
            while not p:
                continue
            help_screen.undraw()
            help_title.undraw()
            [rule.undraw() for rule in rules]

A: First of all, you have two unterminated while loops. The first while loop has no end condition and no break statements to exit the loop. This means that it will never end. Also, as soon as self.win.getMouse() returns a falsy value, not p will become true, and the inner while loop runs, doing absolutely nothing forever because p never changes. If you are intending to end the help function when p becomes false, you need to replace the inner while loop with and if statement and change the continue to a break. Also, do you really want to undraw everything after the first iteration? Corrected code:
while True:
    p = self.win.getMouse()
    if not p:
       break
help_screen.undraw()
help_title.undraw()
[rule.undraw() for rule in rules]


text:
Q: meaning of 'at medium' "And at home, Australia's national terrorism public alert is currently at medium and has remained unchanged for the last 11 years. (Aussie ABC)"
What meaning does 'at medium' have?

A: See this link on Australia's National Terrorism Public Alert System

The National Terrorism Public Alert System is a range of four levels that communicate an assessed risk of terrorist threat to Australia. The four levels are:

*

*low—terrorist attack is not expected

*medium—terrorist attack could occur

*high—terrorist attack is likely

*extreme—terrorist attack is imminent or has occurred

So, it just means the current level of threat is medium, as defined by this alert system.


text:
Q: PHPMailer wont send mails I have this PHPMailer: https://github.com/PHPMailer/PHPMailer/
my code is this:
    $mail = new PHPMailer;

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'kms-play.it';  // Specify main and backup server
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'noreply@kms-play.it';                            // SMTP username
    $mail->Password = 'pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

    $mail->From = 'noreply@kms-play.it';
    $mail->FromName = 'KMS-Play';
    $mail->addAddress('evolutio@kms-play.it', 'Lars Mehrhoff');  // Add a recipient

    #$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    #$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    #$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    #$mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';

and the error is:

2013-12-15 15:02:23 CLIENT -> SERVER: EHLO local.kms-play.it 2013-12-15 15:02:23 CLIENT -> SERVER: STARTTLS 2013-12-15 15:02:23 SMTP ERROR: STARTTLS command failed: 502 5.5.1 Error: command not implemented 2013-12-15 15:02:23 CLIENT -> SERVER: QUIT SMTP connect() failed. Message could not be sent.Mailer Error: SMTP connect() failed.

A: You have 2 options:
1 - As TLS is not active comment this line:
$mail->SMTPSecure = 'tls';

It will work but is not good to send mails without sign them.
2 - Make sure to activate TLS and the EHLO command should return:
EHLO myfriend
2016-10-27 01:15:07 SERVER -> CLIENT: 250-server.urutecno.net
Hello mail.myfriemd.com [216.111.111.111]
250-SIZE 52428800
250-8BITMIME
250-PIPELINING
250-AUTH PLAIN LOGIN
250-STARTTLS
250 HELP

A: Just config issue.

update< human -> goto web ::https://github.com/PHPMailer/PHPMailer/releases
  get --> PHPMailer-5.2-stable and browse to examples\mailing_list.phps

add the followin config files to the file and it will work out of the box.
     $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
    $mail->isSMTP();
    $mail->SMTPAutoTLS = false;
    $mail->Port = 587;
    $mail->SMTPAuth = true;
      $mail->SMTPSecure = 'tls';

for sure it will work

A: I guess this might be wrong:
$mail->Host = 'kms-play.it';

Is that really your SMTP host? Usually it's something like smtp.kms-play.it. Best check with your hosting provider.