text:
Q: Django queryset result is wrong for the test My model is:
class AndroidOffer(models.Model):
    name = models.CharField(max_length=128, db_index=True)
    # ...
    countries = models.ManyToManyField(Country)

And the following code (I skipped previous filtering):
active_offers = active_offers.filter(countries__in=[country])

It generates this SQL query:
SELECT "offers_androidoffer"."id", "offers_androidoffer"."name", "offers_androidoffer"."title", "offers_androidoffer"."is_for_android", "offers_androidoffer"."is_for_ios", "offers_androidoffer"."url", "offers_androidoffer"."icon", "offers_androidoffer"."cost", "offers_androidoffer"."quantity", "offers_androidoffer"."hourly_completions", "offers_androidoffer"."is_active", "offers_androidoffer"."description", "offers_androidoffer"."comment", "offers_androidoffer"."priority", "offers_androidoffer"."offer_type", "offers_androidoffer"."package_name", "offers_androidoffer"."is_search_install", "offers_androidoffer"."search_query", "offers_androidoffer"."launches" FROM "offers_androidoffer" INNER JOIN "offers_androidoffer_platform_versions" ON ("offers_androidoffer"."id" = "offers_androidoffer_platform_versions"."androidoffer_id") INNER JOIN "offers_androidoffer_countries" ON ("offers_androidoffer"."id" = "offers_androidoffer_countries"."androidoffer_id") WHERE ("offers_androidoffer"."is_active" = True AND "offers_androidoffer"."quantity" > 0 AND NOT ("offers_androidoffer"."id" IN (SELECT U0."offer_id" FROM "offers_androidofferstate" U0 WHERE (U0."device_id" = 1 AND (U0."state" = 3 OR U0."state" = 4)))) AND NOT ("offers_androidoffer"."package_name" IN (SELECT V0."package_name" FROM "applications_app" V0 INNER JOIN "applications_deviceapp" V1 ON (V0."id" = V1."app_id") WHERE (V1."device_id" IN (SELECT U0."device_id" FROM "users_userdevice" U0 WHERE U0."user_id" = 2) AND NOT (V0."package_name" IN (SELECT U2."package_name" FROM "offers_androidofferstate" U0 INNER JOIN "offers_androidoffer" U2 ON (U0."offer_id" = U2."id") WHERE (U0."device_id" = 1 AND (U0."state" = 0 OR U0."state" = 1 OR U0."state" = 2))))))) AND "offers_androidoffer_platform_versions"."platformversion_id" IN (14) AND "offers_androidoffer_countries"."country_id" IN (6252001)) ORDER BY "offers_androidoffer"."priority" DESC;

If I run this query in Postgresql console, it will return 0 rows, but active_offers has 4 results (all rows in table), like if I remove AND "offers_androidoffer_countries"."country_id" IN (6252001) statement.
I run this code from tests (APITestCase.client -> DRF view -> filter queryset). Django version is 2.0.2.
Why it ignores country filtering?
UPD. I've just checked with simple TestCase (test -> filter queryset) test and it returns correct number of rows. So, problem exists only with DRF testing.
UPD 2. Testcase where it works incorrectly:
class AndroidOffersListTests(APITestCase):
    fixtures = [
        'geo/fixtures/cities.json',
        'offers/fixtures/users.json',
        'offers/fixtures/devices.json',
        'offers/fixtures/geo.json',
        'offers/fixtures/apps.json',
        'offers/fixtures/offers.json',
    ]

    def test_list_offers_1(self):
        user_device = UserDevice.objects.get(pk=1)

        token = AndroidOffersListTests.get_token_for_device(user_device)
        self.client.credentials(HTTP_AUTHORIZATION='Token {}'.format(token))

        url = AndroidOffersListTests.get_url(user_device)
        response = self.client.get(url)

        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual(0, len(response.data)) # result is 4

View code:
class AndroidOffersView(ListAPIView):
    model = AndroidOffer
    serializer_class = AndroidOffersSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        device = UserDevice.get_from_request(self.request)
        if device is None:
            raise PermissionDenied()

        return AndroidOffer.get_offers_for_device(device)

get_offers_for_device:
@staticmethod
def get_offers_for_device(user_device):
    active_offers = AndroidOffer.get_active_offers()

    # Filter completed
    completed_states = AndroidOfferState.get_completed_for_device(user_device)
    completed_offers_ids = completed_states.values_list('offer__pk', flat=True)

    active_offers = active_offers.exclude(pk__in=completed_offers_ids)

    # Filter apps already installed on the user's devices
    apps = user_device.user.apps

    # Remove packages that are in progress
    in_progress_states = AndroidOfferState.get_in_progress_for_device(user_device)
    in_progress_packages = in_progress_states.values_list('offer__package_name', flat=True)
    apps = apps.exclude(package_name__in=in_progress_packages)

    packages = apps.values_list('package_name', flat=True)

    active_offers = active_offers.exclude(package_name__in=packages)

    # Filter by platform version
    active_offers = active_offers.filter(platform_versions__in=[user_device.device.version])

    # Filter by country
    country = user_device.last_geo_record.country
    if country is not None:
        active_offers = active_offers.filter(countries__in=[country])

    return active_offers

Test case where it works fine:
class AndroidOffersListTests(TestCase):
    fixtures = [
        'geo/fixtures/cities.json',
        'offers/fixtures/users.json',
        'offers/fixtures/devices.json',
        'offers/fixtures/geo.json',
        'offers/fixtures/apps.json',
        'offers/fixtures/offers.json',
    ]

    def test_list_offers_1(self):
        user_device = UserDevice.objects.get(pk=1)

        offers = AndroidOffer.get_offers_for_device(user_device)

        self.assertEqual(0, offers.count()) # 0 — thats ok

UPD 3: when I'm running the same request in browser, it works fine:

A: You said this response is incorrect:
self.assertEqual(0, len(response.data)) # result is 4

But you also say this JSON response is correct:
{
    "count": 0,
    "next": null,
    "previous": null,
    "results": []
}

You're using a paginated API here.  The length of 4 is due to the number of keys present in the deserialized json:
>>> len(json.loads('{"count": 0, "next": null, "previous": null, "results": []}'))
4

Note that you don't need to actually call json.loads yourself, the DRF framework has already handled that for you when preparing the response - i.e. response.data will be a dict already.
In the "Test case where it works fine", you're dealing with the queryset directly:
self.assertEqual(0, offers.count()) # 0 — thats ok
                         ^
                         |____ here you go to the database, no serializer!

If you want to check the number of results, from the paginated JSON api, then you'll need to drill down that page:
len_results = len(response.data['results'])

For a test that is expected to return 0 results, this is sufficient.  But take care - if you ever have tests which you expect to generate more results than the page size (configured in the settings), you may also want to check the count, and next values.  You'll have to make additional requests to subsequent pages to collect all results.

A: field__in checks if the field is in the list that you pass in to it.
You can get your desired behavior with just this
active_offers = active_offers.filter(countries=country)


text:
Q: while(1) loops infinitely executes its first statement and does not go to the next statement I am writing a code in which there is while(1) loop. Inside while(1) loop there is a message box and then recvfrom() function which according to my understanding must block in call to recvfrom() until data is receieved or recvfrom() function fails.
But what actually happens is the while(1) loop continuoulsy keeps on showing message box and doesnot go to recvfrom() statement ever.
Highlighted the part where I think problem lies.
i.e. while(1) is stuck at its first statement. I am adding the whole code for assistance. Please help me figuring out my mistake.
DWORD WINAPI sendThreadProcedure(LPVOID param)
{
    int PORT = 9999;
    WSADATA wsa;

    //Initialise winsock//
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        exit(EXIT_FAILURE);
    }

    //Create a socket//
    SOCKET sendSocketIdentifier;
    SOCKADDR_IN sendSocket;
    if((sendSocketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    {
        exit(EXIT_FAILURE);
    }
    //Socket Created//

    //Prepare the sockaddr_in structure//
    sendSocket.sin_family = AF_INET;
    sendSocket.sin_addr.s_addr = INADDR_ANY;
    sendSocket.sin_port = htons(PORT);

    //Bind//
    if( bind(sendSocketIdentifier ,(struct sockaddr *)&sendSocket, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
    {
        // "BIND FAILED",
        exit(EXIT_FAILURE);
    }

    int clientSocketLength = sizeof(SOCKADDR_IN);
    char receiveBuffer[10000];
    int recv_len=0;
    //=======================================================================

    char threadNumberBuffer[256] = "Thread Number : ";
    char buff[32];
    char file[32]="Master";
    char fileName[128];
    int sendCount=0;
    FILE *fpSend;
    itoa(threadNumber,buff,10);
    strcat(threadNumberBuffer,buff);

    strcpy(fileName,file);
    strcat(fileName,buff);
    strcat(fileName,".txt");
    MSG msg;

    // Start of problem area
    while(1)
    {
        MessageBox( NULL,
                    "Going in while loop",
                    "",
                    MB_ICONINFORMATION);

        recv_len = recvfrom(sendSocketIdentifier, receiveBuffer,
                            sizeof(receiveBuffer), 0,
                            (struct sockaddr *) &clientSocket,
                            &clientSocketLength)
        {
            // "Could not receive data at start of sending thread"
        }
        // End of problem area

        //"Start of Receive thread"

        while(GetMessage(&msg, NULL, 0, 0) > 0)
        {
            if(msg.message == Send_File)
            {
                if((fpSend = fopen(TEXT(fileName), "r+b")) == NULL)
                {
                    MessageBox( NULL,
                                "Unable to open the File",
                                "Error!",
                                MB_ICONEXCLAMATION |
                                MB_OK);
                }

                char file_buffer[10000];
                int bytes_read=0;
                char new_buffer[1000] = "FILE",send[1000];
                if(sendto(sendSocketIdentifier, new_buffer, sizeof(new_buffer), 0,
                          (struct sockaddr *) &clientSocket,
                          sizeof(clientSocket)) < 0)
                {
                    MessageBox( NULL,
                                "NOT SENNT!",
                                "ERROR!",
                                MB_ICONEXCLAMATION |
                                MB_OK);
                    break;
                }
                while(fpSend!=NULL)
                {
                    if((bytes_read=fread(file_buffer, sizeof(char), 1, fpSend))<=0)
                    {
                        if(feof(fpSend))
                        {
                            char new_buffer[1000] = "EXIT",send[1000];
                            if(sendto(sendSocketIdentifier, new_buffer,
                                      sizeof(new_buffer), 0,
                                      (struct sockaddr *) &clientSocket,
                                      sizeof(clientSocket)) < 0)
                            {
                                MessageBox( NULL,
                                            "NOT SENNT!",
                                            "ERROR!",
                                            MB_ICONEXCLAMATION |
                                            MB_OK);
                                break;
                            }
                            char send_Count[128];

                            itoa(sendCount,send_Count,10);
                            fclose(fpSend);
                            break;
                            return 0;
                        }
                        else
                        {
                            char err[128], bread[128];

                            itoa(errno,err,10);
                            itoa(bytes_read,bread,10);
                            MessageBox( NULL,
                                        "Unable to copy file into buffer",
                                        bread,
                                        MB_ICONEXCLAMATION |
                                        MB_OK);
                            fclose(fpSend);
                            break;
                        }
                    }
                    else
                    {
                        if(sendto(sendSocketIdentifier, file_buffer,
                                  bytes_read, 0,
                                  (struct sockaddr *) &clientSocket,
                                  sizeof(clientSocket)) < 0)
                        {
                            MessageBox( NULL,
                                        "NOT SENNT!",
                                        "ERROR!",
                                        MB_ICONEXCLAMATION |
                                        MB_OK);
                            break;
                        }
                        else
                        {
                            sendCount = sendCount+1;
                        }
                    }
                }
                //======================Sent a File at Socket===========================
            }
            else
                DispatchMessage(&msg);
        }
    }
    return 0;
}

Edit:
Even if I truncate the code to the following, even then, message box is displayed almost 40 times and then recvfrom() is called probably.
while(1)
{
    MessageBox( NULL,
                "Going in while loop",
                "",
                MB_ICONINFORMATION);
    if((recv_len = recvfrom(sendSocketIdentifier, receiveBuffer,
                            sizeof(receiveBuffer), 0,
                            (struct sockaddr *) &clientSocket,
                            &clientSocketLength)) == SOCKET_ERROR)
    {
        char err[128];
        itoa(WSAGetLastError(),err,10);
        MessageBox( NULL,
                    "Could not receive data at start of sending thread",
                    err,
                    MB_ICONINFORMATION);
    }

    MessageBox( NULL,
                receiveBuffer,
                "Start of Receive thread",
                MB_ICONINFORMATION);
}

A: If the messagebox is continously showing, then there is a condition fullfilled that causes receive to return.

*

*There is a problem with your socket and receive returns -1

*There is already data available and you must read it. receive returns > 0

*Your socket is nonblocking == -1

*Your socket timed out, == 0 (not in this case)

So what you must do is, check the return value from receive and see what it says. If it is -1 then additionaly look at errno to find out what it tries to tell you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Area Chart Fixed Values I'm using Google Area Chart in ASP.NET MVC app.
The problem is that all areas take place from incoming value to 0.
I need to make, for example, area from 32 to 40, from 43 to 50.
At that time i didn't find the solution. Is it possible?


text:
Q: SideBySide issue with ArcGISRuntime SDK version100.11 Trying to update my WPF application from the ArcGIS Runtime SDK version 100.6 to 100.11. I used the existing style in the WiX package to update the dll's so that all I had to do was ensure all the shader .cso files were accurate in the Components. Here is the screen shot of my dll's that are configured:

When I try to run the application, I get an error that it cannot access the RuntimeCoreNet100_11.dll. In the Event Viewer I get the following message:

In running the SxsTrace program, for the runtimecoreAssembly, it states the Parser "Did not find manifest for culture Neutral".
Any help here would be very appreciated.
Update
per the instructions given in the comment, i added the manifest file to the dependency components in the component group pictured above. this allowed my app to start, but immediately crashed with a KERNELBASE.dll error. Anyone familiar with fixing those?

A: Looks like you're missing the manifest files. There should be 4 files to deploy to each clientXX folder: runtimecore.dll, runtimecoreAssembly.manifest, RuntimeCoreNet100_11.dll and RuntimeCoreNet100_11.WPF.dll


text:
Q: ProtocolException was handled, Max string content length quota 8192 I have a C# WCF service and a C# console application and wish to pass a large file from the application to the WCF.  When I pass the string, I get protocolexception, max string content length quota exceeded (8192) which is correct.  I change the MaxStringContentLength on ReaderQuotas in the Apps.Config to a large amount but nothing happens, it still errors.  Does anyone know why?  Do I need to add something to the web.config.  The contents of my files are below :-
Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
    <compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
    <behaviors>
        <serviceBehaviors>
            <behavior>
                <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                <serviceMetadata httpGetEnabled="true"/>
                <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="88192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                </security>
            </binding>
          <binding name="largeStrings" openTimeout="00:02:00" sendTimeout="00:02:00"
              maxBufferSize="524288" maxReceivedMessageSize="524288">
            <readerQuotas maxDepth="10" maxStringContentLength="524288" maxArrayLength="16384"
             maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:2745/ActuristDemo/Service.svc"
            binding="basicHttpBinding" bindingConfiguration="largeStrings"
            contract="ActuristWS.IService" name="largeStrings" />
    </client>
</system.serviceModel>
</configuration>

A: http://social.msdn.microsoft.com/Forums/eu/wcf/thread/77097d1f-372a-4c7d-910f-57c9ecd9c5c1
Gave me exactly what I wanted.

A: When you're sending the large string from the client to the service, you need to increase the limits in the service configuration (i.e. web.config). Example:
<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="customHttpBinding" maxBufferSize="2147483647"
        maxReceivedMessageSize="2147483647" />
    <binding name="BasicHttpBinding_IMyWebService" closeTimeout="00:01:00"
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
            realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<services>
  <service name="MyService.MyWcfService">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyWebService"
        contract="MyService.IMyWebService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost/MyService/MyWcfService/" />
      </baseAddresses>
    </host>
  </service>
</services>


text:
Q: Converting individual pieces of assembly to machine code I am trying to convert assembly to machine code. I have a MINGW compiler where if i type ./convert.exe mov %a  then it should output  0x01 0xc0. I am thinking of using a struct listing each assembly code with its corresponding machine value. At the moment i keep getting errors like "request for member opcode in something not a structure". Any help would be appreciated.
#include <stdio.h>
#include <string.h>

struct _Instruction {
char mnemonic[10];
unsigned char opcode;} typedef Instruction;

Instruction instruction_list[] = {
{"mov", 0x01},
{"add", 0x04},
{"sub", 0x05},
{"mul",0x06},
{"div", 0x07},
{"and",0x08},
{"or",0x09},
{"xor",0x0a},
{"cmp",0x0b},
{"",-1},
};

Instruction get_inst(char mnemonic[]);

int main2(int argc, char *argv[])
{

char* instruction = argv[1];
Instruction get_inst = get_Instruction(instruction);

printf("%s  ;  %s",instruction_list.mnemonic,instruction_list.opcode);
return 0;
}

Instruction get_inst(char mnemonic[])
{
int i;

for(i=0; instruction_list[i].opcode != -1; i++)
{
  if(!strcmp(instruction_list[i].mnemonic, mnemonic))
  {
    return instruction_list[i];
  }
}
return instruction_list[i];
}

A: For one thing, your structure is declared incorrectly.  You should format it like this instead:
typedef struct _Instruction {
    ....
} Instruction;

I'm not sure why that's not triggering syntax errors, but it's certainly not helping.
Also, you have both a variable and a function named get_inst.  You call a non-existent function named get_Instruction().  You probably meant to name your function get_Instruction().
Also, the .opcode member of your structure is a single char.  Your printf statement uses the "%s" format specifier to print it.  This expects a string, which will cause printf to continue reading past the end of the .opcode member, displaying unpredictable garbage and accessing memory it shouldn't be touching.


text:
Q: MySQL Transaction - Reading during Transaction If I start a transaction in MySQL and update a row like so:
UPDATE table SET SomeValue ...... WHERE Id = 1;
Am I ok to immediately do this:
SELECT SomeValue FROM table WHERE Id = 1;
...during the same connection/session whilst the transaction is still not yet committed, assuming now that I'm getting the updated SomeValue, and safe to assume that nothing can update that SomeValue until I've committed the transaction?
Thanks.

A: No other session can update that row until you commit.
You can test this for yourself, by opening two terminal windows, run the mysql shell, and try starting a transaction and updating in one window, but do not commit. Then try updating in the second window. It hangs, until the first window commits, or the innodb lock wait timeout is reached.
SELECTing from the table has no effect on locks one way or the other.


text:
Q: Did SSH gain the ability to seamlessly hop across network paths? I have been aware of an alternative to ssh, which is mosh, which as a "remote terminal application that supports intermittent connectivity" as its main differentiator, led me to double down at the time on the impression (which I already had at the time, from experience) that SSH cannot survive service interruptions.
From my experience in the past, if your connection to your server got disconnected, your connection was going to hang, and then some time before the two-minute TCP timeout window closes, and often exactly when it closes, the connection will be lost.
However in more recent months (years?) I have noticed certain things that make me question if this is still what I can expect out of ssh.
For example today what I just experienced was:

*

*Connected via ssh to my server ("A") from hotel wifi

*Inside tmux running on A, connected to yet another server ("B") with ssh, in two separate sessions. The first had a long running apt install session going, which got interrupted during the following events, and the second was a regular bash shell session.

*At some point stuff started getting really sluggish. Presumably this was because of the link over the hotel wifi to A, and I decided I was done with wifi and switched my wifi over to my phone's 5G hotspot.

*At around this time, in my second terminal I had typed Ctrl+D, not really expecting anything to happen, I definitely expected my connection to A to die at this point

*Shortly after the connection was made to the hotspot, in this second terminal I saw logout printed and it closed the connection. So somehow not only did my connection to A survive hopping from wifi to 5G, the keystroke I sent on the terminal immediately after doing the switch made it through as well.

*since the connection between A and B had no reason to be interrupted, I could watch the first terminal complete its work

I guess most of these details were completely unnecessary. I'm just surprised by the fact that ssh kept my connection alive across my network device change (and presumably a large change in the route taken to server A). Is this something I should expect from ssh from now on?


text:
Q: java mysql executeupdate update i tried writing a code, that would update a record when a button is pressed with any changes made to any fields. it displays an error message though. this is the code:
    JButton button = new JButton("Save");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

        try {
            con.stmt.executeUpdate("UPDATE student set (StudentID=" + txtAUniqueStudent.getText() + ", FirstName=" + textField_1.getText() + ", Surname=" + textField_2.getText() + ", DOB=" + textField_3.getText() + ", Gender=" + textField.getText() + ", AddressLine1=" + textField_4.getText() + ", AddressLine2=" + textField_5.getText() + ", PostCode=" + textField_6.getText() + ", FatherFullName=" + textField_7.getText() + ", Phone" + textField_8.getText() + ", Mobile=" + textField_9.getText() + ", Fax=" + textField_10.getText() + ", Email=" + textField_11.getText() + ", EmergencyContactName=" + textField_12.getText() + ", EmergencyTel=" + textField_13.getText() + ", AcademicYear=" + textField_14.getText() + ", Subjects=" + textField_15.getText() + "WHERE studentID =" + textField_16.getText());
            con.stmt.executeUpdate();
            JOptionPane.showMessageDialog(frmFindStudent, "Record has been updated successfully.");
        }

        catch (SQLException e) {
        //System.out.println("Record couldn't be added!");
        e.printStackTrace();
        JOptionPane.showMessageDialog(frmFindStudent, "Record couldn't be updated. Please try again.");
        }
        }
        });
    button.setBounds(333, 517, 89, 23);
    panel_1.add(button);

The connection to the db and stuff all works, so it must be just the syntax, as this is the error message i am getting:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(StudentID=25415, FirstName=Shangeethan, Surname=Seevaratnam, DOB=30.08.1994, Ge' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1749)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1666)
at FindStudent$2.actionPerformed(FindStudent.java:255)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

A: you have error here, you forget = sign:
 ", Phone" + textField_8.getText()

also you opening ( without closing , and actually you dont need it:
set (StudentID

you need to put String in between quotes 'name' in case there are names with spaces, like:
con.stmt.executeUpdate("UPDATE student set StudentID='" + txtAUniqueStudent.getText() + "', FirstName='" + textField_1.getText() + "', Surname='" + textField_2.getText() + "', DOB='" + textField_3.getText() + "', Gender='" + textField.getText() + "', AddressLine1='" + textField_4.getText() + "', AddressLine2='" + textField_5.getText() + "', PostCode='" + textField_6.getText() + "', FatherFullName='" + textField_7.getText() + "', Phone='" + textField_8.getText() + "', Mobile='" + textField_9.getText() + "', Fax='" + textField_10.getText() + "', Email='" + textField_11.getText() + "', EmergencyContactName='" + textField_12.getText() + "', EmergencyTel='" + textField_13.getText() + "', AcademicYear='" + textField_14.getText() + "', Subjects='" + textField_15.getText() + "' WHERE studentID ='" + textField_16.getText()) + "'";

you can use String.format, more readable and you can detect error easily:
String statement = String.format("UPDATE student set studentId='%s', firstName='%s'",
id, name);


text:
Q: Samba share on Mountain Lion freezes I'm using a Mac Mini (Mid 2010) with Mountain Lion on (OS X 10.8 12A269 – not OS X Server) as a file server at my home network. The Mac is equipped with an external 2TB USB disk (Western Digital).
The root of the external disk, from here on called extrn, is shared using "File Sharing".
When reading/writing large files from a Windows 7 workstation the entire samba connection seems to freeze for about a minute. It seems like the connection just resets.  Sometimes it takes less than a minute.
So my Question is, how do I troubleshoot this problem? What information is needed to solve this? Does anyone have any idea why this is happening?
In the Sharing menu in OS X, the folder is shared as "Read & Write" for my user, my user group and "Everyone". Under Options I've selected Share files and folders using SMB (Windows). And my user is also selected beneath that check box.
Looking at system.log there is a few related lines:
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: label: default
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]:     dbname: od:/Local/Default
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]:     mkey_file: /var/db/krb5kdc/m-key
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]:     acl_file: /var/db/krb5kdc/kadmind.acl
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: uid=0
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: init request
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: init return domain: MACMINI-012345 server: N-NS-MAC-MINI
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: uid=0
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: init request
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: init return domain: MACMINI-012345 server: N-NS-MAC-MINI
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: uid=0
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: od failed with 2 proto=ntlmv1-with-v2-session
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request: user=WIN7\username
Aug 7 23:01:28 N-Ns-Mac-mini.local digest-service[11674]: digest-request kdc: ok user=MACMINI-012345\username proto=ntlvm1 flags: NEG_KEYEX, ENC_128, NEG_VERSION, NEG_TARGET_INFO, NEG_NTLM2, NEG_ALWAYS_SIGN, NEG_NTLM, NEG_SIGN, NEG_TARGET, NEG_UNICODE
Aug 7 23:01:28 N-Ns-Mac-mini.local smbd[11591]: MACMINI-012345\username connected to path /Volumes/extrn

Then after about 2 minutes, the same chunck of logs appear again.
Sometimes there is an additional row afterwards:
Aug 7 23:05:10 N-Ns-Mac-mini.local smbd[11591]: MACMINI-012345\username connected to path /var/rpc/ncacn_np

username is the same:

*

*MACMINI-012345\username at the server

*WIN7\username at the client.

The strange thing is that sometimes (about 1 out of 30 times) everything works like a charm. Sometimes the problem is even worse.  I can't say that I see any pattern in it.
Any ideas?
UPDATE:
File system is 'Mac OS Extended (Journaled)'. I've also tried to share a folder on the internal drive (320GB included with Mac Mini Mid 2010). The same problem appears there too.
When the system "freeze" I refer to the Windows 7 client. What ever client trying to write the file (e.g. an unzip) gets an error message telling me that the "Path can no longer be found". Or if I'm trying to copy a file the copy progress is aborted due to write error. If I then try to access the drive (or any other samba share at my Mac) nothing happens for a while before everything suddenly works again.

A:  Considerations
For the partition, in its entirety, at the server you grant read and write privileges to everyone:

*

*may be comparable to guest access, which does not require authentication.

Consider the following possibilities:

*

*some communication, or attempted communication, by Windows 7 may be anonymous, without authentication (whether/how such communications would be logged by the server in a non-Server build of the OS, I don't know)

*writes, or attempted writes, by Windows 7 are inappropriate for something at/around the root of the partition.

Suggestions
Increase the verbosity of logging for SMB
This may be easier to achieve with a Server build of the OS.
Diagnosis at the server when the client perceives a problem
Enable the stackshot daemon then use the key chord for sysdiagnose
Preparation: enable the daemon
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.stackshot.plist

When the problem occurs: use the key chord for sysdiagnose.
For at least ten seconds after the chord, touch nothing.
After Finder brings to front the result of sysdiagnose: decompress the archive, consider the files that comprise the diagnosis.
References
stackshot(1) OS X Manual Page
sysdiagnose(1) OS X Manual Page

A: I found in /Library/Preferences/SystemConfiguration/com.apple.smb.server.plist the NetBIOSName  "lion". Not the ServerName. (After I used lion\userid instead of ServerName\userid I could logon, but it was not what I want).
With serveradmin I found the same:
sudo serveradmin settings smb

...
smb:NetBIOSName = "lion"
...

So I changed
sudo serveradmin settings smb:NetBIOSName = "ServerName"

Now it works like before the upgrade to Lion.
I realize this is a solution to a problem in Lion, but you may want to start with it because the same thing could happen to Mountain Lion.


text:
Q: What is the proper formula to highlight variance in utilization I have $160$ machines that are given tasks over time. Each machine is expected to perform $\frac{1}{160}$ of the overall tasks, however if one encounters a fault, it could have some period of inactivity, shifting the average away from $\frac{1}{160} \approx 0.625\%$
I am displaying the data as an $8$ by $20$ grid, where each cell in the grid displays $\frac{\text{Tasks Completed}}{\text{Total Tasks Among All Machines}}$
What I have calculated currently are the Average number of tasks $\frac{\text{Average(Tasks Per Machine)}}{\text{Total Tasks}} \cdot 100 \%$
And the standard deviation $\sqrt{\sum\left(x_i - \mu\right)^2}$
So for a given cell I can determine the number of standard deviations from the mean for an individual machines utilization.
I wanted to color the cells on a scale, where those with a Z-score of 0 would be green (#00FF00). Would it be appropriate to treat the change in Z-score as a linear transition along a scale of Green (#00FF00) to Yellow (#FFFF00) to Red (#FF0000)?
Should the Min and Max value in the table of data below have any factor on the scale, or would the range between colors essentially be arbitrary based on what 'resolution' I want in the results?
At a very trivial level this is splitting the cells into either Red/Yellow/Green where x is the value of the cell
    If (x > (mean - stdD)) And (x < (mean + stdD)) Then
        r = 0
        g = 255
        b = 0
    Else If (x < (mean - stdD)) And (x > (mean - (stdD * 6))) Then
        r = 255
        g = 255
        b = 0
    Else If (x > (mean + stdD)) And (x < (mean + (stdD * 6))) Then
        r = 255
        g = 255
        b = 0
    Else
        r = 255
        g = 0
        b = 0
    End If

*The black cell was due to one machine not having any tasks for the entire time range.


text:
Q: Kernprof (line_profiler): how to output result as text instead of a binary file When running kernprof:
kernprof -l script_to_profile.py

The output is stored in a binary file, which can be read in the terminal/command line.
Is there a way to output the results to a text file?
This seems like useful functionality to have, but can't find it in the documentation or in other posts.

A: python -m line_profiler script_to_profile.py.lprof > profile_output.txt

Will convert the binary output to a text file (thanks @martineau)


text:
Q: how to split dict column from pandas data frame
*

*Splitting dictionary/list inside a Pandas Column into Separate Columns>

The  above link providing some solution to my answer
But i have same problem with little different in input. here my DF:
df = pd.DataFrame({'a':[1,2,3], 'b':[[{'c':1},{'c':3}], {'d':3}, {'c':5, 'd':6}]})

My dict again contains list of dicts for Key "b".
My expected O/P :
  [a    c   c1    d
0  1   1.0  3    NaN
1  2   NaN  NaN  3.0
2  3   5.0  NaN  6.0][1]

Could you please help.

A: You can use:
#convert to list of df with condition for add list
L = [pd.DataFrame(x) if isinstance(x, list) else pd.DataFrame([x]) for x in df['b']]
#join together, reshape and remove all NaNs columns
df1 = pd.concat(L, keys=df.index).unstack().dropna(how='all', axis=1)
#flattening MultiIndex in columns
df1.columns = ['{}{}'.format(a,b) for a,b in df1.columns]
print (df1)
    c0   c1   d0
0  1.0  3.0  NaN
1  NaN  NaN  3.0
2  5.0  NaN  6.0

#remove original column b and join df1
df = df.drop('b',1).join(df1)
print (df)
   a   c0   c1   d0
0  1  1.0  3.0  NaN
1  2  NaN  NaN  3.0
2  3  5.0  NaN  6.0


text:
Q: Accessing Private Methods from Module Functions in Ruby I'm trying to create private helper methods for module functions to no avail. I feel like there's something very simple I'm missing.
Updated example with a more understandable use case:
module FancyScorer
  module_function

  def score(ary)
    scores = []
    ary.each_slice(2).with_index do |slice, i|
      scores <<
        case i % 2
        when 0
          score_eventh(ary)
        else
          score_oddth(ary)
        end
    end
    scores.inject(:+)
  end

  private

  def score_eventh(ary)
    ary.inject(:+) / (ary.size - 1)
  end

  def score_oddth(ary)
    ary.inject(:*) / (ary.size - 1)
  end
end

FancyScorer.score([1,2,3,4])
# => `block in score_curiously': undefined method `score_eventh'
#    for FancyScorer:Module (NoMethodError)

Note: The private methods should remain private.
Here's the use case: there are several modules that contain various scoring techniques, e.g. FancyScorer, SimpleScorer, ComplexScorer. These functions are tested independently, and then are employed to create a score method for different classes.  For instance:
class A
  ...
  def score
    FancyScorer.score(metrics) + 2*SimpleScorer.score(metrics)
  end
end

class B
  ...
  def score
    0.5*FancyScorer.score(metrics) + 2*SimpleScorer.score(metrics[0,3]) + ComplexScorer.score(metrics)
  end
end

Previous example with no provided use case:
module Party
  module_function

  def pooper
    enjoy
  end

  private

  def enjoy
    puts "Wahoo!"
  end
end

Party.pooper
# => NameError: undefined local variable or method `enjoy' for Party:module
#            from (party): in `pooper`

A: module_function(symbol, ...) → self says:-

Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.

You need to make sure you declare the helper method as a #private_class_method:  private only affects instance methods.
module Party

  def enjoy
    puts 'hello'
  end

  def pooper
    enjoy
  end

  private_class_method :enjoy
  module_function :pooper
end

Party.pooper # => 'hello'
Party.enjoy # => private method `enjoy' called for Party:Module (NoMethodError)

Furthermore, you should be careful about the ordering of accessibility keywords like public, private, and module_function. These do not overlap, but rather override.
module Party
  module_function # Module function declarations begin
  def pooper
    bar
  end
  def bar
    enjoy
  end

  private         # Private declarations begin, module function declarations end
  module_function # Private declarations end, module function declarations begin
  def enjoy       # Therefore, this is a module function
    "Wahoo!"
  end
end

Party.pooper # => "Wahoo!"
Party.bar # => "Wahoo!"
Party.enjoy # => "Wahoo!"  <-- No longer private

Note here module_function overrides the previous private declaration.

Here some more examples  when module_function will do its job, and when not.
The module_function definitions stop once another accessibility keyword pops up. In this example, module_function is interrupted by public making #pooper a public instance method. Use of private would similarly block module_method.
module Party
  module_function
  public
  def pooper
    "i am pooper"
  end
end

Party.pooper
# undefined method `pooper' for Party:Module (NoMethodError)

Now if the order is changed:
module Party
  public
  module_function
  def pooper
    "i am pooper"
  end
end

Party.pooper # => "i am pooper"


text:
Q: Remote image as notification icon in Chrome Packaged App? I'm writing this app and would like to display Chrome notifications with certain remote images as notification icons.
I am aware that you are not allowed to directly assign the URL of a remote image as the notification icon, so I assume I would first have to download the remote image via some sort function and then use the now local image as a notification icon.
How could this be achieved?
Thanks in advance

A: Like sowbug mentioned in his comment, this can be done through Data URL.
Documentation and example can be found in Google's documentation at: http://developer.chrome.com/apps/app_external


text:
Q: Ggplot2 - Create a function in order to manually control the line type of several variables I would like to plot the values of several tables. Each of these tables have a different/unknown number of variables/columns.
I am using the following code in order to plot the data:
library(ggplot2)
library(reshape2)
#data <- read.table("jony.csv", header = TRUE, sep = ";", fill = TRUE)
data <- read.table(text="MONTH;GFDL.ESM2M_HBV_IWW_WFDisi;GFDL.ESM2M_SWIM;GFDL.ESM2M_WaterGAP3;GFDL.ESM2M_HYPE;GFDL.ESM2M_VIC;month_mean;q70
1;853.455161290323;550.116774193548;746.965913978495;469.31688172043;546.64752688172;633.300451612903;452.931661075269
2;1037.55011792453;632.34445754717;805.189285714286;567.411202830189;763.929245283019;761.284861859839;452.931661075269
3;782.714301075269;447.378494623656;561.674193548387;422.475483870968;591.257634408602;561.100021505376;452.931661075269
", header = TRUE, sep = ";", fill = TRUE)
jony <- melt(data, id.vars="MONTH")
p <- ggplot(jony, aes(MONTH,value, col=variable))
p + geom_line(size = 0.1) +
  geom_hline(aes(yintercept = 0), linetype="dotted") +
  ylab("Runoff [m3/s]") +
  xlab("Month") +
  theme_bw() +
  theme(legend.key = element_blank())+
  scale_color_discrete(name='Models GCM_HM') +
  ggtitle("Jony")

In order to manually control the colors of the variables "month_mean" and "q70" I have added the following function to the code:
f <- function(x, cols, pal = rainbow) {
  stopifnot(names(cols) %in% x)
  pal <- pal(length(x)-length(cols))
  names(pal) <- setdiff(x, names(cols))
  pal <- c(pal, cols)
  return(pal)
}
p + scale_color_manual(
  values = f(levels(jony$variable), c("month_mean"="black", "q70"="red"))
)

Now I would like to adapt this function in order to control the line type of the two variables "month_mean" and "q70". I have added the following to the code:
f2 <- function(x, cols, lin = lty) {
  stopifnot(names(cols) %in% x)
  lin <- lin(length(x)-length(cols))
  names(lin) <- setdiff(x, names(cols))
  lin <- c(lin, cols)
  return(lin)
}
p + scale_linetype_manual(
  values = f2(levels(jony$variable), c("month_mean"="dotted", "q70"="dashed"))
)

But it is not working and it is even deleting the colors affection done by the first function "f". Does anyone knows why?

A: Ok. So as I said lty is a parameter and not a function like rainbow. Therefore you cannot simply generate linetypes with it.
Here is an example that works:
library(ggplot2)
library(reshape2)
#data <- read.table("jony.csv", header = TRUE, sep = ";", fill = TRUE)
data <- read.table(text="MONTH;GFDL.ESM2M_HBV_IWW_WFDisi;GFDL.ESM2M_SWIM;GFDL.ESM2M_WaterGAP3;GFDL.ESM2M_HYPE;GFDL.ESM2M_VIC;month_mean;q70
                   1;853.455161290323;550.116774193548;746.965913978495;469.31688172043;546.64752688172;633.300451612903;452.931661075269
                   2;1037.55011792453;632.34445754717;805.189285714286;567.411202830189;763.929245283019;761.284861859839;452.931661075269
                   3;782.714301075269;447.378494623656;561.674193548387;422.475483870968;591.257634408602;561.100021505376;452.931661075269
                   ", header = TRUE, sep = ";", fill = TRUE)
jony <- melt(data, id.vars="MONTH")
p <- ggplot(jony)

p <- p + geom_line(size = 1, aes(MONTH,value, col=variable, linetype=variable)) +
  geom_hline(aes(yintercept = 0), linetype="dotted") +
  ylab("Runoff [m3/s]") +
  xlab("Month") +
  theme_bw() +
  theme(legend.key = element_blank())+
  #scale_color_discrete(name='Models GCM_HM') +
  ggtitle("Jony")

f <- function(x, cols, pal = rainbow) {
  stopifnot(names(cols) %in% x)
  pal <- pal(length(x)-length(cols))
  names(pal) <- setdiff(x, names(cols))
  pal <- c(pal, cols)
  return(pal)
}
p + scale_color_manual(
  values = f(levels(jony$variable), c("month_mean"="black", "q70"="red"))
)

f2 <- function(x, cols) {
  stopifnot(names(cols) %in% x)
  lin <- 1:(length(x)-length(cols)) # 0:12 are the linetypes available
  names(lin) <- setdiff(x, names(cols))
  lin <- c(lin, cols)
  return(lin)
}
p + scale_linetype_manual(values = as.numeric(f2(levels(jony$variable), c("month_mean"=9, "q70"=9))))

Notice: I gave the variables that are not month_mean or q79 the linetypes 1:5. From this example on, you can come up with your own function to generate linetypes I guess.


text:
Q: Calling Assembly in C++ I wan to learn
1). How to call assembly code so that I can call it from C++?
2). I want to keep all my assembly code in separate files.
I am using Linux,GCC and other GNU developer tools.
Can you please provide some good references for it?

A: Write C++ header files declaring the functions you want.  Define those functions with assembly language in another file.  build object files of the assembly language code.  Then in other C++ code files, #include the header which contains the declarations of your assembly code defined functions.  Call the functions as any C++ functions, link against the object file as you link with any object file.
For references, read the code of some project that uses a mix of assembly language and C/C++.  Device drivers could export functions that way.


text:
Q: cucumber with timecop I'm trying to use cucumber and timecop together and it's timecop doesn't seem to be overriding my Time.now call in my transaction.rb model file.
Here is my Scenario:
  @stop @wip
  Scenario: Displaying defaults when entering a form
    Given I am on the new transaction page
    And the time is Dec 31 2010, 9:00 UTC
    Then the "Tran date" field should contain "31/12/2010"

I have these steps in a timecop_steps.rb file
Given 'the time is $time' do |time|
  Timecop.freeze Time.parse(time)
end

When '$time pass' do |time|
  Timecop.travel future_time(time)
  Given 'delayed jobs are run' # we use delayed jobs and have some that get scheduled in the future.
end

When 'time stands still' do
  Timecop.freeze Time.now
end

Then in my transaction.rb file I set my default:
class Transaction < ActiveRecord::Base
  def set_defaults
    self.tran_date = Time.now.strftime("%d/%m/%Y")
  end
end

When I run my scenario I get the following:
  Scenario: Displaying defaults when entering a form   # features/receipt_journal_new.feature:29
    Given I am on the new transaction page
                         # features/step_definitions/web_steps.rb:45
    And the time is Dec 31 2010, 9:00 UTC                              # features/step_definitions/timecop_steps.rb:1
    Then the "Tran date" field should contain "31/12/2010"             # features/step_definitions/web_steps.rb:142
      expected: /31\/12\/2010/
           got: "20/07/2011" (using =~)
      Diff:
      @@ -1,2 +1,2 @@
      -/31\/12\/2010/
      +20/07/2011
       (RSpec::Expectations::ExpectationNotMetError)
      ./features/step_definitions/web_steps.rb:147:in `block (2 levels) in <top (required)>'
      ./features/step_definitions/web_steps.rb:30:in `with_scope'
      ./features/step_definitions/web_steps.rb:143:in `/^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/'
      features/transaction_new.feature:32:in `Then the "Tran date" field should contain "31/12/2010"'

Update:
I've even tried stubbing out Time.now and that didn't work either:
Given 'the time is $time' do |time|
  Time.stub!(:now).and_return("31/12/2010") #Time.parse(time))
#  Timecop.freeze Time.parse(time)
end

Update2:
I've tried using chronic as well as using Timecop.travel instead of Timecop.freeze as in this article:
http://www.louismrose.me.uk/post/876230592/freezing-time-in-cucumber
Update3:
I've tested Timecop in my rspec model tests and it works fine.

A: The answer was simply the order in which I was setting Timecop in my Scenario
Given the time is Dec 31 2010, 9:00 UTC
And I am on the new transaction page


text:
Q: how to use observed livedata outside of observe block I want to put the observed LiveData in a list and you that list elsewhere in the code. Like this:
        var listCategory = listOf<Category>()

        categoryViewModel.categories.observe(viewLifecycleOwner) {
            listCategory = it
        }

        //do something with listCategory

CategoryViewModel.kt
@HiltViewModel
class CategoryViewModel @Inject constructor(private val categoryDao: CategoryDao) :ViewModel() {
    private val categoryFlow = categoryDao.getCategoryFlow()
    val categories = categoryFlow.asLiveData()

    fun addCategory(name:String){
        viewModelScope.launch {
            categoryDao.insert(Category(name = name))
        }
    }
}

CategoryDao.kt
@Dao
interface CategoryDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(category: Category)

    @Update
    suspend fun update(category: Category)

    @Delete
    suspend fun delete(category: Category)

    @Query("SELECT * FROM category_table")
    fun getCategoryFlow(): Flow<List<Category>>
}

But listCategory is always empty. How can I use observed data outside the observation block?

A: Your listCategory has List<Category> type, which is immutable. This is also declared as val, which means that you cannot legally use listCategory = something
To allow mutations and adding, you should create it as a mutable list like this
val listCategory = mutableListOf<Category>()

And then, in observe block you can
categoryViewModel.categories.observe(viewLifecycleOwner) {
    listCategory.addAll(it)
}

Moreover I suggest to perform manipulations with livedata and its' dependent components in observe block, to make sure, that livedata changes will be processed.


text:
Q: Mongo filter documents where a given value is same as minimum value in array A collection called bookstore is as below (sample 2 documents):
[{
"bookname": "hi",
"orders" : [
    {"rate" : 1},
    {"rate" : 2}
 ]
},

{
"bookname":"hello",
"orders" : [
    {"rate" : 3},
    {"rate" : 2},
    {"rate" : 5}
  ]
}]

I want to return documents where the minimum rate value from orders array is equal to value number 2.
Output: Entire document with all fields where bookname:hello as the minimum rate value in orders array is 2 and not the document with bookname:hi as the minimum rate is 1 there.
How to I achieve this with mongo db query?
I tried this:
db.collection.aggregate([
      {
        $unwind: "$orders"
      },
      {
        $group: {
          _id: "$_id",
          minRateDoc: {
            $min: "$orders.rate"
          }
        }
      },
      {
        "$match": {
          "minRateDoc": 2
        }
      }
    ])

It returns output as:
[{
_id: ObjectId of 2nd document,
"minRateDoc": 2
}
]

But to return all fields I don't want to use projection as in reality there are many fields I want to return. Also is there other way to return documents where minimum rate value is number 2.

A: You can directly apply $min to the array orders.rate and compare to 2 to get the documents you want.
db.collection.find({
  $expr: {
    $eq: [
      2,
      {
        $min: "$orders.rate"
      }
    ]
  }
})

Mongo Playground

A: You could query for documents which contain an order whose rate is 2, and which do NOT contain an order whose rate is less than 2. This can be achieved as follows:
db.collection.find(
  {
    $and: [
      { "orders.rate": 2 },
      { "orders.rate": { $not: { $lt: 2 } } }
    ]
  }
)


text:
Q: Python list comprehension for Numpy I'm looking for list-comprehension method or similar in Numpy to eliminate use of a for-loop eg. index_values is a Python dictionary list of lists (each list containing a different number of index values) and s is a numpy vector:
for i in range(33):
    s[index_values[i]] += 4.1

Is there a method available that allows eliminating the for-loop?

A: I don't fully understand what kind of object index_values is. But if it were an ndarray, or could be converted to an ndarray, you could just do this:
>>> s = numpy.arange(20)
>>> index_values = (numpy.random.random((3, 3)) * 20).astype('i')
>>> s[index_values] = 4
>>> s
array([ 0,  1,  4,  4,  4,  5,  6,  4,  8,  4,  4, 11, 12,
       13,  4, 15,  4,  4,  4, 19])

Edit: But it seems that won't work in this case. On the basis of your edits and comments, here's a method I think might work for you. A random list of lists with varying lengths...
>>> index_values = [list(range(x, x + random.randrange(1, 5)))
...                 for x in [random.randrange(0,50) for y in range(33)]]

...isn't hard to convert into an array:
>>> index_value_array = numpy.fromiter(itertools.chain(*index_values),
                                       dtype='i')

If you know the length of the array, specify the count for better performance:
>>> index_value_array = numpy.fromiter(itertools.chain(*index_values),
                                       dtype='i', count=83)

Since your edit indicates that you want histogram-like behavior, simple indexing won't do, as pointed out by Robert Kern. So use numpy.histogram:
>>> hist = numpy.histogram(index_value_array, bins=range(0, 51))

histogram is really constructed for floating point histograms. This means that bins has to be a bit larger than expected because the last value is included in the last bin, and so 48 and 49 would be in the same bin if we used the more intuitive range(0, 50). The result is a tuple with an array of n counts and an array of n + 1 bin borders:
>>> hist
(array([2, 2, 1, 2, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 5, 5, 5, 3, 3,
        3, 3, 3, 2, 1, 0, 2, 3, 3, 1, 0, 2, 3, 2, 2, 2, 3, 2, 1, 1, 2, 2,
        2, 0, 0, 0, 1, 0]),
 array([ 0,  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, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]))

Now we can scale the counts up by a factor of 4.1 and perform vector addition:
>>> s = numpy.arange(50, dtype='f')
>>> hist[0] * 4.1 + s
array([  8.2,   9.2,   6.1,  11.2,   8.1,   5. ,   6. ,   7. ,  12.1,
        13.1,  14.1,  15.1,  16.1,  13. ,  18.1,  19.1,  20.1,  37.5,
        38.5,  39.5,  32.3,  33.3,  34.3,  35.3,  36.3,  33.2,  30.1,
        27. ,  36.2,  41.3,  42.3,  35.1,  32. ,  41.2,  46.3,  43.2,
        44.2,  45.2,  50.3,  47.2,  44.1,  45.1,  50.2,  51.2,  52.2,
        45. ,  46. ,  47. ,  52.1,  49. ])

I have no idea if this suits your purposes, but it seems like a good approach, and should probably happen at near c speed since it uses only numpy and itertools.

A: What about:
s[reduce(lambda x,y: x+y, [index_values[x] for x in range(33)], [])] = 4.1


text:
Q: How can preon use bean properties? I need to read a binary file where the size of a byte array depends on an optional value as well as on a constant number. How can I achieve this using Preon?
It seems that the byte array size calculation cannot be conditional ie. size="adaptationFieldControl==0b10 || adaptationFieldControl==0b11 ? 184-adaptationFieldLength : 184"
Using a method (see sample below) to calculate the dynamic size makes Preon fail with Caused by: org.codehaus.preon.el.BindingException: Failed to create binding for bound data called getPayloadLength.
public class packet {
    @BoundNumber(size = "2")
    byte adaptationFieldControl;

    /**
     * Returns the size of the payload if present in the packet
     * @return size corrected for adaptation fields
     */
    public int getPayloadLength() {
        if(isAdaptationFieldsPresent()) {
            return 188 - (4+adaptationFieldLength);
        }
        return 188-4;
    }

    @If("adaptationFieldControl==0b10 || adaptationFieldControl==0b11")
    @BoundNumber(size="8")
    short adaptationFieldLength;

    @If("adaptationFieldControl==0b01 || adaptationFieldControl==0b11")
    @BoundList(size="payloadLength")
    byte[] payload;

...

A: Preon uses the language "Limbo" to implement the expression evaluation. In Limbo, an expression evaluated to true, would take the value of "1" (and false "0").
As consequence the expression:
size=adaptationFieldControl==0b10 || adaptationFieldControl==0b11
    ? 184-adaptationFieldLength : 184

would take probably the form of:
size=184-(adaptationFieldControl==0b10||adaptationFieldControl==0b11)
    *adaptationFieldLength

I tested it, and unfortunately it seams that the method size does not accept it. I get the exception:
org.codehaus.preon.el.InvalidExpressionException: NoViableAltException(18@[])

It seams that the logical tokens are understood only by the "@If" annotation.
As a workaround I suggest you to define two fields prefixed by a "@If" annotation, and then implement a get method witch test the two fields for "null" and return the "non-null" one.

A: Unless I'm entirely mistaken, the @If annotation actually prevents the field to be registered at all if the condition is false. So, according to Preon, there is no field called addaptationFieldLenght. That, and Preon has now way to bind to methods. There is technically not much to prevent it from getting implemented, but I wanted to make sure you can alway generate a sensible HTML description of the file format, and if there's logic hiding inside the body of methods, you cannot turn it into documentation.
If you have some complicated logic that simply doesn't fit in a Limbo expression, you might be better of creating a Codec for it. That way, you can make sure that your logic is also documented in the description of the file format generated.


text:
Q: Use CSOM To Pull Date Value From Date And Time Field Using C# CSOM and this is SharePoint 2010 - I am attempting to pull the vale of a Date And a time field to my Winform.
If I type in the immediate window
    listItem["datetimefield"];
It will return
    {7/22/2018 3:22:00 AM}
    Date:
    Day:
    DayOfWeek:
    DayOfYear:
    Hour:
    Kind:
    Millisecond:
    Minute:
    Month:
    Seconds:
    Ticks:
    TimeOfDay:
    Year:
I want to pull the value from Date - what would be the syntax to do such?
EDIT
If it helps this is full syntax I attempted to use.  I can connect fine and pull values for other field types, just not a Date and Time field type.
Public static void GetDateTimeData()
{
  using (var ctx = new ClientContext(SPURL))
  {
    List list = web.Lists.GetByTitle(SPSite);
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml= strong.Format();

    ListItemCollection items = list.GetItems(camlQuery);
    ctx.Load(list);
    ctx.Load(items);
    ctx.ExecuteQuery();

    foreach (ListItem listItem in items)
    {
        DateTime TargetSD = (dateTime)listItem["maindate"];
        string date = Convert.ToDateTime(listItem["maindate"].ToString();
    }
  }
}

A: Per my test in my SharePoint 2013 environment, if I get the value from the date and time column in the item, I get the time as the picture below.

Then you could format the time according to the article below.
String Format for DateTime.

A: The value is already DateTime. If that's what you want, casting will be enough:
(DateTime)listItem["maindate"]

But if you need as a formatted string, use the toString() method:
DateTime dateTimeValue = (DateTime)listItem["maindate"];
string formatedValue = dateTimeValue.ToString("dd/MM/yyyy");

You may look here if you want to customize the format:

*

*https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings


text:
Q: Closing Bootstrap Modal doesn't stop JW Player I have JW PLayer embedded in a Bootstrap modal (not iframe/youtube). It plays fine but when closing the modal (either by clicking the "x" or clicking outside the dialog) the audio continues to play. I was able to stop it by adding :
    onclick='jwplayer().stop()'
to the close button.
However this doesn't help when the modal is closed by clicking outside the dialog (modal-backdrop). Can anybody help? I'm a bit of a js noob!
Here is the url: http://bit.ly/1g4Dz3o

A: Remove the click that you have attached.
If you check their documentation, you will find event hide.bs.modal which is fired immediately when the hide instance method has been called.
$('#videohome').on('hide.bs.modal', function () {
  jwplayer().stop();
})


text:
Q: Pagination in ionic I am working on ionic framework for app development. I can fetch the list of customer from db but list is large that's why i want to load that list slowly like want to display data in some portion then again display next data like Lazy loading can anyone please suggest me the various options for this or any links or examples for my problem
thanks in advance

A: Use ionic infinite scroll, it is used to handle pagination , here is documentation for the infinite scroll https://ionicframework.com/docs/v1/api/directive/ionInfiniteScroll/
Here is a good link for practical understanding: http://sunnycyk.com/2014/02/ionic-framework-infinite-scrolling/
Purpose of ionic infintie scroll is to load only that amount of items which fit to screen, and scroll to load more.The ionInfiniteScroll directive allows you to call a function whenever the user gets to the bottom of the page or near the bottom of the page.


text:
Q: Laravel Datatables Getting First Row of the query I'm using yajra's laravel/datatables plugin and I want to send only the first row of every group from the query sorted according to date of the record descending. This is my query :
$qsrecords = QualityScore::where('clientID', '=', $user['id'])
       ->whereBetween('day', array($startDate, $endDate))
       ->where($desiredValue, $operator, $quantity)
       ->where('previousQualityScore','!=','0');

This query returns every record for this given user id like :
Client ID | Keyword ID | Quality Score |     Date
   2           81            8            21.08.2016
   2           42            9            19.08.2016
   2           81            7            16.08.2016
   2           42            5            14.08.2016

as you can see, ı got 2 different keywords and my query is giving that output.
but i want my query to generate results like :
Client ID | Keyword ID | Quality Score |     Date
   2           81            8            21.08.2016
   2           42            9            19.08.2016

Only the last records of every keyword. That's I want to achieve.
The way i send the query to view :
    // Send data to view via datatables plugin
    return Datatables::of($qsrecords)->make(true);

A: Try this
QualityScore::select( * , DB::raw('MAX(date) as date'))
              ->where('clientID', '=', $user['id'])
             ->whereBetween('day', array($startDate, $endDate))
             ->where($desiredValue, $operator, $quantity)
             ->where('previousQualityScore','!=','0');
             ->groupBy('keyword_id')
               ->get();

A: Finally i've figured it out! I've changed the way i approach to this issue but the following code has solved the issue, thanks @Kiran-sadvilkar for suggestions.
$groupByMaxDateQuery = ' SELECT qs.adGroup,qs.keyword, qs.previousQualityScore, qs.qualityScore, qs.qualityScoreDifference, qs.day
                FROM homestead.qualityScore AS qs
                INNER JOIN (
                    SELECT adGroupID, keywordID, max(day)
                    AS MaxDay
                    FROM homestead.qualityScore
                    GROUP BY adGroupID,keywordID
                )
                innerTable ON qs.adGroupID = innerTable.adGroupID
                    AND qs.keywordID = innerTable.keywordID
                    AND qs.day = innerTable.MaxDay
                WHERE qs.clientID = '.$user['id'].' AND
                    qs.day BETWEEN "'.$startDate.'" AND "'.$endDate.'" AND
                    qs.'.$desiredValue.' '.$operator.' '.$quantity.' AND
                    qs.previousQualityScore != 0
                ';

    // Pull data from database with current conditions
    $qsrecords = DB::table(DB::raw("($groupByMaxDateQuery) as qs"));

As a result i've decided to use a raw sql query and now it works...


text:
Q: How could SUM(column) give incorrect results in MySQL? I have the following simple MySQL query, called from PHP:
SELECT foo_id, SUM(number_of_guests)
FROM guests
WHERE foo_id = $foo_id
GROUP BY foo_id

This works fine, except for one $foo_id, which returns about 2.5 times greater than the sum of the number_of_guests field.
What could cause this behavior for only a certain value of $foo_id?
Is there a better way to do this?

A: Your query should work. The error is most likely in the other method you are using to verify the result.

Is there a better way to do this?

Yes. Since you are only fetching one group there's no need for your GROUP BY clause:
SELECT SUM(number_of_guests)
FROM guests
WHERE foo_id = $foo_id

A: The problem is that there was one row with a large value for number_of_guests. I didn't see in in browsing the data because there are a few hundred rows. It didn't show up when I copied and pasted from HTML page into Excel because that row was missing most of the other columns, and the HTML page has all the columns.
Thanks for all your help!


text:
Q: AFTER UPDATE TRIGGER failure First, create the trigger:
CREATE TRIGGER UpdateSentiero_AfterUpdatingTappa
AFTER UPDATE ON TAPPA
FOR EACH ROW
BEGIN

//NEW.tempo and OLD.tempo would refers to TAPPA "tempo" and "lunghezza", really? I ask you this because SENTIERO has it own "tempo" and "lunghezza"
IF (NEW.tempo is not null) and NOT (NEW.tempo=OLD.tempo) THEN

        UPDATE SENTIERO
        SET tempo=0;

END IF;
END$$

Then, run the query:
UPDATE SENTIERO
SET tempo=null;

It seems the TRIGGER doesn't work and i don't know the reason.
NEW.tempo and OLD.tempo could be NULL (i suppose they refers to TAPPA, because it's a TRIGGER ON TAPPA) that's the reason for i've written that IF condition.

EDIT ::
One INSTANCE of SENTIERO has multiple INSTANCES of TAPPA, so one INSTANCE of SENTIERO collect the values of it own "tempo" and "lunghezza" TAPPA INSTANCES
IF (NEW.tempo is not null) and NOT (NEW.tempo=OLD.tempo) THEN

    IF (OLD.tempo is NOT NULL) THEN

            UPDATE SENTIERO
            SET tempo=tempo - OLD.tempo + NEW.tempo
            WHERE (tempo is NOT NULL) and IDsentiero IN ( SELECT DISTINCT IDsentiero
                                                         FROM SENTIERO__HA__TAPPA AS sht
                                                         WHERE NEW.IDtappa=sht.IDtappa);
    ELSE

            UPDATE SENTIERO
            SET tempo=tempo + NEW.tempo
            WHERE (tempo is NOT NULL) and IDsentiero IN ( SELECT DISTINCT IDsentiero
                                                          FROM SENTIERO__HA__TAPPA AS sht
                                                          WHERE NEW.IDtappa=sht.IDtappa);

            UPDATE SENTIERO
            SET tempo=NEW.tempo
            WHERE (tempo is NULL) and IDsentiero IN ( SELECT DISTINCT IDsentiero
                                                      FROM SENTIERO__HA__TAPPA AS sht
                                                      WHERE NEW.IDtappa=sht.IDtappa);
    END IF;

END IF;

But when I try to run
UPDATE TAPPA
SET tempo=9
WHERE IDtappa=0;
//where instance of IDtappa=0 has "tempo"'s value=NULL

it doesn't work

TABLES DATA:
SENTIERO              |    SENTIERO_HA_TAPPA       |  TAPPA
IDsentiero  time      |    IDsentiero  IDtappa     |  IDtappa  time
   0         7.5      |        0          0        |     0      null
                      |        0          1        |     1      1.45
                      |        0          2        |     2      2.3
                      |        0          5        |     5      1.45
                      |        0          8        |     8      2.3

The first time (update on tappa, set tempo=2 where IDtappa=0) the trigger doesn't work.
NOTE: OLD.tempo is NULL, SENTIERO.tempo is not null
But the second time (update on tappa, set tempo=3 where IDtappa=0) the trigger works.
The derived data calculated on SENTIERO's "tempo", for IDsentiero=0, HAS CHANGED: 8.5
It seems that it has done: 7.5 - 2 +3, so it seems it has been taken the right condition.
NOTE: OLD.tappa is NOT NULL, SENTIERO.tempo is NOT NULL
So the problem is with the NULL value of TAPPA.tempo

A: Your query doesn't fire the trigger. Here's why:
CREATE TRIGGER UpdateSentiero_AfterUpdatingTappa
AFTER UPDATE ON TAPPA

The trigger only fires after updates are made to table TAPPA.
UPDATE SENTIERO
SET tempo=null;

Your test query is updating table SENTIERO, and setting tempo to null, which is filtered out by the trigger's IF conditional. Try updating TAPPA instead, like this:
UPDATE TAPPA
SET tempo=5;

This query should cause SENTIERO's tempo values to get set to zero, assuming there's a tempo value != 5 in that table.
Note that it appears your trigger will affect every row in SENTIERO. Perhaps you should include some kind of ID matching between the two tables? For example:
UPDATE SENTIERO
SET tempo=0
WHERE SENTIERO.ID = NEW.ID;

In response to new question:
Your IF statement:
IF (NEW.tempo is not null) and NOT (NEW.tempo=OLD.tempo) THEN

Your test query:
UPDATE TAPPA
SET tempo=9
WHERE IDtappa=0;
//where instance of IDtappa=0 has "tempo"'s value=NULL

Given the comment, it's clear the IF block isn't being entered. You're comparing a non-null value against null. This yields null. You need to use the null safe equality operator, <=>. Your IF statement should look like this instead:
IF (NEW.tempo is not null) and NOT (NEW.tempo<=>OLD.tempo) THEN


text:
Q: why setCurrentItem() of viewPager works for next page and not for previous page? I am using Tabbed Activity of Android Studio.
I'm moving between the pages swiping but i added 2 views to move next and previous by onclick method but it doesn't work to go back only to go next.
     nextAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //it works
                        mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER));
                    }
                });

     backAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       //it doesn't work
                       mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER)-1);
                    }
                });

I'm using FragmentPagerAdapter.
It works swiping back.
I put onClick methods inside onCreateview.

A: Refering to the Tabbed Activity, take a look at the section number as the fragment is initialized. (sectionNumber = position+1).
    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

Therefore, ARG_SECTION_NUMBER-1 refers to the position of the current fragment, ARG_SECTION_NUMBER-2 to the previous, and ARG_SECTION_NUMBER to the next.
Consequently, your code should be like this:
 nextAbitudini.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //it works
                    mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER));
                }
            });

 backAbitudini.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                   //it doesn't work
                   mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER)-2);
                }
            });


text:
Q: Rails detect if Attribute Changed Before Update - SystemStackError: stack level too deep I want to detect whether an attribute has changed before a model has updated.
I have the following (based on:http://api.rubyonrails.org/classes/ActiveModel/Dirty.html):
before_update :changed_attributes

def changed_attributes
    self.path_changed? ? puts('Path was changed') : puts('Path was not changed')
end

But now when i try t edit the Model.path attribute I get the following error:
SystemStackError: stack level too deep

Which I'm told means an infinite recursion is occurring.
What's the correct way to do this and without creating the SystemStackError?

A: The problem is that ActiveRecord already has a method called changed_attributes. Most likely path_changed? calls changed_attributes, but you have redefined changed_attributes and it contains path_changed?. This results in an endless recursion and eventually a too deep stack level.
Try changing the name of your method to check_changed_attributes or something:
before_update :check_changed_attributes

def check_changed_attributes
  self.path_changed? ? puts 'Path was changed' : puts 'Path was not changed'
end


text:
Q: NodeJS express auto created app binding to server I created an express app in NodeJS using express --view=pug expressapp. It created an app.js file
app.js
var createError = require('http-errors');
...

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//socket setup
var socket = require('socket.io');

var io = socket(app);
io.on('connection', function(socket) {
    console.log('made socket connection')
})

module.exports = app;

at the end I try to bind socket.io to app but it expects to bind to server like so
var server = app.listen(3000, function() {

});

//socket setup
var socket = require('socket.io');

var io = socket(server);

I also use nodemon so I run the app using nodemon expressapp and it runs on port 3000. However I can't find where the auto generated express files have setup the server. Because If i try like this
//socket setup
var socket = require('socket.io');

var server = app.listen(3000, function() {

});

var io = socket(server);

I get an error that port 3000 is already in use (by itself) I changed it to 4000 and it works.
Not ideal, if you know how to connect with port 3000 will appreciate the assist.

A: You shall find it under the directory bin/www


text:
Q: Lambda Function Using Unknown Parameter I see PRISM declaring the following constructor, and I don't understand what's that "o" being used with the lambda function that serves as the second parameter when the base constructor is called:
public DelegateCommand(Action<T> executeMethod)
    : this(executeMethod, (o)=>true)
{
}

I'd appreciate an explanation.

A: It calls this constructor:
DelegateCommand<T>(Action<T>, Func<T, Boolean>)

Passing a lambda that always returns true as the second parameter

A: The constructor which declaration you posted calls another constructor, so to explain it, we should first look at the other constructor's signature:
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)

So the second parameter is a Func<T, bool>. That means it is a function that takes a parameter of type T and returns a boolean.
Now if you look at the lambda that is used:
(o) => true

Lambdas in general have the syntax (parameter-list) => lambda-body, so in this case, the single parameter of the lambda is a variable o (which type is inferred to be T) and the function returns a constant result true.
The purpose of this is to basically make a command that is always executable.
Of course that lambda could look a lot more complicated, so when using the DelegateCommand, you are likely to use more complex and non-constant expressions. For example:
 new DelegateCommand(DoSomething, o => o.SomeProperty >= 0 && o.SomeProperty < 10 && o.SomeBoolProperty)


text:
Q: How to find intersection of values that meet multiple conditions in R? Assume I have the following data frame:
df <- data.frame(year=c(2010,2011,2012,2010,2011,2010,2011,2012), company = c("a","a","a","b","b","c","c","c"))

  year company
1 2010       a
2 2011       a
3 2012       a
4 2010       b
5 2011       b
6 2010       c
7 2011       c
8 2012       c

I want to find the companies that are present in all three years. One cumbersome approach would be:
library(dplyr)

companies_2010 <- df %>% filter(year==2010) %>% select(company)
companies_2011 <- df %>% filter(year==2011) %>% select(company)
companies_2012 <- df %>% filter(year==2012) %>% select(company)

companies <- intersect(companies_2010, companies_2011) %>% intersect(., companies_2012)

  company
1       a
2       c

Is there any more elegant way to do this?

A: Since the years are distinct and in the desired set we only have to count how many there are for each company.  (If that is not true, in general, then apply the solutions below to df2 <- unique(merge(df, data.frame(year = 2010:2012))) in place of df.  Also if we did not know the value 3 and we wanted it to equal the number of unique years in the data then we could compute it using length(unique(df$year)).
Now, using that idea here are several alternatives. We can use table to get their frequencies and then keep those with frequency 3 or in the last case we can use dplyr's count and then filter to get those with a count of 3.
tab <- table(df$company)
names(tab)[tab == 3]
## [1] "a" "c"

names(Filter(function(x) x == 3, table(df$company)))
## [1] "a" "c"

library(dplyr)
df %>%
  count(company) %>%
  filter(n == 3) %>%
  select(company)
##   company
## 1       a
## 2       c

To use the intersect idea of the question split company by year and then use Reduce to apply intersect repeatedly:
 with(df, Reduce(intersect, split(company, year)))
 ## [1] "a" "c"

We can visualize this using table like this.  Any column having no zero values corresponds to a company having all years.
table(df)
##       company
## year   a b c
##   2010 1 1 1
##   2011 1 1 1
##   2012 1 0 1

or a heatmap where green is present and red is absent.  Any column that is entirely green has all years.
heatmap(table(df), Rowv = NA, Colv = NA, col = 2:3, scale = "none")

A: Here is a base R solution with ave and unique.
n <- with(df, ave(year, company, FUN = length))
unique(df$company[n == 3])
#[1] "a" "c"

A: Since you have received some excellent answers, I thought a very different approach with a little bit of imagination might also be fine.
I visualized your problem set up as a bipartite graph where we have 2 distinct set of nodes where one is company names and the other is the years, while there is no connection between companies and also between year.
library(igraph)

# Creating a graph object but first I alternate the columns of your data set
df[, c(2, 1)] |>
  graph_from_data_frame() -> g

# Then we create a type object to distinguish between 2 sets of nodes, Type FALSE
# refers to company name and type TRUE refers to years
V(g)$type <- bipartite.mapping(g)$type

# Then we extract those nodes whose degree are equal to 3 while they are of type FALSE
V(g)[degree(g, V(g)) == length(unique(df$year)) & V(g)$type == FALSE]
+ 2/6 vertices, named, from c172916:
[1] a c

In case you would like to see how the graph looks like:
plot(g,
     vertex.color = ifelse(V(g)$type, "lightblue", "salmon"),
     vertex.shape = ifelse(V(g)$type, "circle", "square"),
     vertex.size = 25,
     edge.color = "grey",
     layout = layout.bipartite)

A: This won't work in general to compute arbitrary intersections, but (¿ I think ?) does what you specified above:
(df
   %>% group_by(company)
   %>% filter(all(2010:2012 %in% year))
   %>% select(company)
   %>% distinct()
)

A: Just nest and reduce:
df <- data.frame(year=c(2010,2011,2012,2010,2011,2010,2011,2012), company = c("a","a","a","b","b","c","c","c"))
df %>%
    tidyr::nest(data = -year) %>%
    magrittr::use_series(data) %>%
    purrr::reduce(dplyr::intersect)
# A tibble: 2 x 1
  company
  <chr>
1 a
2 c

Or split-map-reduce:
split.data.frame(df, df$year) %>%
    purrr::map(magrittr::use_series, company) %>%
    purrr::reduce(dplyr::intersect)
[1] "a" "c"

A: Expounding on the answers given, this here would work in general:
df %>%
  mutate(rn = list(seq(min(year), max(year))))%>%
  group_by(company) %>%
  summarise(rn = all(unlist(rn) %in% year)) %>%
  filter(rn) %>%
  select(company)

# A tibble: 2 x 1
  company
  <chr>
1 a
2 c

A: Another igraph solution
> g <- graph_from_data_frame(df)

> names(which(degree(g, V(g)[names(V(g)) %in% df$company]) == length(unique(df$year))))
[1] "a" "c"


text:
Q: How to perform correct loop for Multiplication quiz I'm new to programming and would like some help.
I'm trying to create a Multiplication quiz that loops infinitely until the user inputs no. Also, when a multiplication problem is presented the program must also display rather or not the user input is correct.
When the user inputs no the loop will stop and display how many correct answers out of the total amount of questions asked.
any ideas?
Here is my code:
public static void main(String[] args) {
    int correctCount = 0; // count the number correct question
    int count = 0; // count the number of question
    Scanner input = new Scanner(System.in);

   // 2 random single-digit int
    int number1 = (int) (Math.random() * 10);
    int number2 = (int) (Math.random() * 10);

   do {
     // prompt the student to answer "what is number1 - number2
     System.out.print("What is " + number1 + " * " + number2 + "?");
     int answer = input.nextInt();

     // grade the answer and display the result
     if (number1 * number2 == answer) {
        System.out.println("You are correct!");
        correctCount++; // increase the correct answer count
     } else {
        System.out.println("Your answer is worng. \n" + number1 + " * "
                + number2 + " should be: " + (number1 * number2));
     }

     count++;

     System.out.println("\nWould you like more questions?");
     System.out.print(" Y or N ?");
     String option = input.nextLine();
 } while (input.equals('y'));
    System.out.println("\nYou've answered " + correctCount + " out of "
        + count + " Correct");
}

I know my code is a bit of a mess because I tried to perform do-while loop but wasn't able to get my program to run correctly.

A: Your main problem is that you are checking to see if the value of input equals "y" which it doesn't because input is a Scanner not a String.
In order to make this work there are a few changes you need to make.
First you want to choose the random numbers inside the do loop, otherwise you will get the same numbers over and over again.
Second, you want to move the declaration of the option String outside the loop so that it will have the right scope to be usable.
Third you need to call input.nextLine() after getting the answer int because the nextInt() method only gets the int, leaving the rest of the line.
Fourth you want to use .trim() when getting the next line to remove whitespace and newline chars.
Finally when checking the value of option use the .equalsIgnoreCase() so that it will work for upper or lowercase y.
        int correctCount = 0; // count the number correct question
        int count = 0; // count the number of question
        Scanner input = new Scanner(System.in);

        String option;

        do {
            //2 random single-digit int
            int number1 = (int)(Math.random() * 10);
            int number2 = (int)(Math.random() * 10);

            //prompt the student to answer "what is number1 - number2
            System.out.print("What is " + number1 + " * " + number2 + "?");
            int answer = input.nextInt();
            input.nextLine();

            //grade the answer and display the result
            if (number1 * number2 == answer)
            {
                System.out.println("You are correct!");
                correctCount++; //increase the correct answer count

            }
            else
            {
                System.out.println("Your answer is worng. \n" +
            number1 + " * " + number2 + " should be: " + (number1 * number2));
            }

            count++;

            System.out.println("\nWould you like more questions?");
            System.out.print(" Y or N ?");

            option = input.nextLine().trim();
        } while (option.equalsIgnoreCase("Y"));

A: Your do-while loop condition is while(input.equals('y')), but input is a Scanner object, which doesn't work in this loop. Since you read in the user's choice to continue into option, It should be while(option.equals("y")), or better still, while(option.equalsIgnoreCase("y")), which will let the user enter y or Y

A: I'm not entirely sure what is going wrong with the scanner, but I updated your class and it is now working fine.  I moved the random numbers within the loop so the numbers change for each iteration.  I also changed the while condition to be "input.next().equalsIgnoreCase("y")".  When it is input.nextLine().equalsIgnoreCase("y") it stops on one iteration.  I'm not familiar with the oddities of the Scanner class and would personally just use a Reader.
public class Main {
    public static void main(String[] args) {
        int correctCount = 0; // count the number correct question
        int count = 0; // count the number of question
        Scanner input = new Scanner(System.in);

        do {
            //2 random single-digit int
            int number1 = (int) (Math.random() * 10);
            int number2 = (int) (Math.random() * 10);

            //prompt the student to answer "what is number1 - number2
            System.out.print("What is " + number1 + " * " + number2 + "?");
            int answer = input.nextInt();

            //grade the answer and display the result
            if (number1 * number2 == answer) {
                System.out.println("You are correct!");
                correctCount++; //increase the correct answer count

            } else {
                System.out.println("Your answer is worng. \n" +
                        number1 + " * " + number2 + " should be: " + (number1 * number2));
            }

            count++;

            System.out.println("\nWould you like more questions?");
            System.out.print(" Y or N ?");
        } while (input.next().equalsIgnoreCase("y"));

        System.out.println("\nYou've answered " + correctCount + " out of " + count
                + " Correct");
    }
}


text:
Q: Xcode copies the whole project directory when I try to copy only a group of files Consider we have two projects both opened in Xcode. I need to copy a group of files (a folder with files inside) from one to another. I select a group in first project's Project Navigator, drag it to another project, then choose:
Destination: Copy items if needed
Added folders: Create groups

Yet it copies the whole directory (with subgroups) of the first project which is weird.
Moreover if I delete (move to trash) copied files from second project, they are deleted from the first project as well. Need to emphasize that I choose Create groups not Create folder references.
If I try to copy a single file everything works as expected.
Is it a bug or am I doing something wrong?
Xcode version is 13.3 (13E113)


text:
Q: How to list all the messages from producer in consumer from beginning in kafka (Windows)? How to list all the messages from producer in consumer from beginning in kafka (Windows)?
Not able to display message from producer from beginning in kafka-windows

A: Console producer does not read data. Use the consumer instead

A: Try this command in windows powershell:
.\bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic cities --from-beginning