Binding collection to ComboBox in Listview

Question: I have a ListView whose DataTemplate consists of a ComboBox and some TextBoxes.
The ComboBox is bound to a Collection which is mapped to a CollectionViewSource.
The ListView can have any number of rows.
The problem is that selecting an item in one ComboBox changes them all. I do want them all to be populated with the same contents, but to be able to be set independently.
The Resources section contains the following:
    <CollectionViewSource Source="{Binding ChildAccounts}" x:Key="ChildGroupedData">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="group"/>
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

    <DataTemplate x:Key="ChildTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="90"/>
                <ColumnDefinition Width="130"/>
                <ColumnDefinition Width="90"/>
                <ColumnDefinition Width="90"/>
                <ColumnDefinition Width="90"/>
                <ColumnDefinition Width="210"/>
            </Grid.ColumnDefinitions>

            <ComboBox Grid.Column="1" SelectedValue="{Binding Path=accFrom}" ItemsSource="{Binding Source={StaticResource ChildGroupedData}}" ItemTemplate="{StaticResource AccountTemplate}" SelectedValuePath="ID" Width="120" Style="{StaticResource RoundedComboBox}" HorizontalAlignment="Left" VerticalAlignment="Center">
                <ComboBox.GroupStyle>
                    <GroupStyle ContainerStyle="{StaticResource CustomExpanderComboGroupItemStyle}" HeaderTemplate="{StaticResource GroupHeader}"/>
                </ComboBox.GroupStyle>
            </ComboBox>

            <TextBox Grid.Column="3" Text="{Binding Path=amount, StringFormat='#,##0.00'}" Style="{StaticResource RoundedTextBox}" Width="80" HorizontalAlignment="Left" VerticalAlignment="Center"/>

            <TextBox Grid.Column="5" Text="{Binding Path=comment}" Style="{StaticResource RoundedTextBox}" Width="200" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        </Grid>
    </DataTemplate>

    </Style>

The ListView is defined as:
<ListView Grid.Column="0" x:Name="lstChildren" Margin="20,30,0,0" ItemsSource="{Binding Path=Items}" Style="{StaticResource ChildListViewStyle}"/>

EDIT:
The following is found in the associated class
Imports System.Data
Imports System.Data.OleDb
Imports System.Collections.ObjectModel
Imports System.ComponentModel

Class ItemView
Implements INotifyPropertyChanged

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

Private Sub NotifyPropertyChanged(ByVal info As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

....

Private _ChildAccounts As ObservableCollection(Of AccountEntry)
Public Property ChildAccounts As ObservableCollection(Of AccountEntry)
    Get
        Return _ChildAccounts
    End Get
    Set(value As ObservableCollection(Of AccountEntry))
        _ChildAccounts = value
    End Set
End Property

....

Private Sub ItemView_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

    Dim dsacmd As OleDbDataAdapter
    Dim dsa As New DataSet
    Dim dva As DataView
    Dim strSelect As String

    Try
        ' ** Open a connection to the database.
        cn = New OleDbConnection(strConnection)
        cn.Open()

        Me.DataContext = Me

        strSelect = "SELECT Accounts.ID, Accounts.deleted, Accounts.accType, Accounts.currency as curr, IIf([Currencies.ID]=1,Accounts.comment,Accounts.comment & "" ("" & Currencies.symbol & "")"") AS comment, Currencies.comment AS currS FROM Currencies INNER JOIN Accounts ON Currencies.ID = Accounts.currency"
        dsacmd = New OleDbDataAdapter(strSelect, cn)
        dsacmd.Fill(dsa, "Accounts")
        dva = New DataView(dsa.Tables("Accounts"))
        dva.RowFilter = "accType=" & cVirtual.ToString & " AND deleted=False"
        dva.Sort = "curr, comment"
        ChildAccounts = New ObservableCollection(Of AccountEntry)(dva.ToTable.AsEnumerable().[Select](Function(i) New [AccountEntry](i("ID"), i("currS").TrimEnd(" "), i("comment"))))

....

Private Sub DisplayItem()

    ....

            strSelect = ""
            Dim Relations As Collection(Of Relation) = GetRelations(ID)
            For Each r As Relation In Relations
                strSelect &= "ID=" & r.ID.ToString & " OR "
            Next
            If strSelect <> "" Then strSelect = "SELECT * FROM Items WHERE " & strSelect.Substring(0, strSelect.Length - 4)
            If strSelect <> "" Then
                dsrcmd = New OleDbDataAdapter(strSelect, cn)
                dsr.Clear()
                dsrcmd.Fill(dsr, "Items")
                lstChildren.DataContext = dsr
            End If
....

Answer: You will need to move your CollectionViewSource into the DataTemplate. To force all combobox-items to use the same Source Collection I think you can try two things:
One - Use Relative Source to pick the ChildAccounts from ListView's DataContext
...
<Grid.Resources>
  <CollectionViewSource x:Key="ChildGroupedData"
                        Source="{Binding RelativeSource={RelativeSource FindAncestor,
                                                                        AncestorType={x:Type ListView}},
                                          Path=DataContext.ChildAccounts}">
    <CollectionViewSource.GroupDescriptions>
      <PropertyGroupDescription PropertyName="group" />
    </CollectionViewSource.GroupDescriptions>
  </CollectionViewSource>
</Grid.Resources>
...

Update:
Above method can be seen in This sample I put together. Note that ChildAccount's is just an ObservableCollection<T> in the view-model, this is so that we are not having a new collection per ListBoxItem but share em across like what you had asked for in the question.
If your ChildAccounts property is actually like say the "comment" property where you have a ChildAccounts property object per ListBoxItem, just change
<CollectionViewSource x:Key="ChildGroupedData"
                        Source="{Binding RelativeSource={RelativeSource FindAncestor,
                                                                        AncestorType={x:Type ListView}},
                                          Path=DataContext.ChildAccounts}">

to
<CollectionViewSource x:Key="ChildGroupedData"
                        Source="{Binding ChildAccounts}">

and it should work as well. You do however now have a ChildAccounts collection per ListBoxItem and aren't sharing their source.
Main thing is to Define the CollectionViewSource inside the DataTemplate. Download the attached sample and try it for yourself and check the specifics.
Two - Have ChildAccounts as a static variable
...
<Grid.Resources>
  <CollectionViewSource x:Key="ChildGroupedData"
                        Source="{x:Static local:ChildAccounts}">
    <CollectionViewSource.GroupDescriptions>
      <PropertyGroupDescription PropertyName="group" />
    </CollectionViewSource.GroupDescriptions>
  </CollectionViewSource>
</Grid.Resources>
...

Comment: Thanks. Tried the first and it doesn't work. The ComboBoxes are empty. Can't get the second to compile. It says 'Cannot find the member 'ChildAccounts' on the target type' and 'l:ChildAccounts member is not valid because it does not have a qualifying type name. I changed it to {x:Static l:ItemView.ChildAccounts} - which then only gets one error - cannot find the member 'ChildAccounts' on the type 'ItemView'. I have declared xmlns:l="clr-namespace:WpfAccounts" to allow access to the namespace. The class that contains ChildAccounts in code is called ItemView. Thanks. Andy
Comment: @AndyPowell First method works fine for me. Can you please post your view model code for both ChuldAccounts property and Items property. Trim the code if required. Retain the namespace and class structure. Ill post my working solution to Dropbox as well so you can try in a bit. Is the property Items which is bound to ListView an observable collection of ItemView class objects?
Comment: @AndyPowell I've updated my answer after Option 1 with a link to download a sample project that shows Option 1 working. Download it and have a look to see how your VM property declarations are different. Option 2 as I mentioned in the answer is for Static variables. If your property ain't static you cannot use it.
Comment: Thanks. Will look tonight. I don't think I'm using ViewModel (but will certainly learn from your example). ChildAccounts is declared as a Public Property of ObservableCollection(Of Account) in the Class ItemView. Will update question with the code tonight.
Comment: I think I may have cracked it..... `` works I think!
Comment: Is ItemView your Window, if so you can actually have the binding with AncestorType={x:Type l:ItemView} instead of AncestorType={x:Type Window} making it type-safe
Answer: You can add set IsSynchronizedWithCurrentItem="False" to the combo box.


Mouse gets stuck when switching screens

Question: Hi I have the latest amd drivers, and 3 monitors setup. When moving the mouse from one screen to another it seems like it gets stuck, and I have to keep moving it for it to finally switch, its really odd, does anybody know a quick fix?
Example:
(the black is the other screen and the pattern is the other screen)
If I move the mouse fast enough it dosen't seems to happen.
Answer: See identical question: How do I disable mouse magnet on middle edge with multi monitors?
System Settings - Displays. Uncheck the box that says "Sticky edges".

Mouse gets stuck when switching screens


How do I add a qrc file to my Ubuntu Touch qml project?

Question: My UT QML project makes use of a set of images, and I was planning use them via "qrc:///pathtoimages/myimage.png" style of url.
In Ubuntu SDK, I can "add new... Qt / Qt Resource File".
The file is created, but then I get the following error saying:

What does the error mean?
Can I safely ignore it?
Will the package generation include my images?

[EDIT]
After further investigation, it seems that using qt resources files only makes sense when using qmake, to embed some file into the binary. So it might be just useless in Ubuntu SDK.
Answer: You can manage resource files with the Qt resource system, but it's only meant to be use for applications mixing QML AND C++, not for projects started as simple Touch UI:

The Qt resource system allows resource files to be stored as
  binary files in an application executable. This can be useful when
  building a mixed QML/C++ application as it enables QML files (as well
  as other resources such as images and sound files) to be referred to
  through the resource system URI scheme rather than relative or
  absolute paths to filesystem resources.

For projects only made of QML files, the way to use images resource is by using relative paths in your QML application, e.g:
Image {
    anchors.fill: parent
    source: "../../svg/test.svg"
}

All images files will be included automatically by the <My_project>.qmlproject file.
Comment: Hi Sylvain, sorry to be a pain & point you at my own question but it _is_ related [http://askubuntu.com/questions/777348/ubuntu-sdk-having-difficulty-getting-images-to-work-in-qml-only-app-when-dep] When deployed to Desktop the `source: "Pics/testpic.png"` works fine but not when deployed to armhf device where it says `QML QQuickImage: Cannot open: file:///opt/click.ubuntu.com` etc
Comment: @pHeLiOn Sorry for the late reply, please try to ask your question on the phone mailing list, email@example.com. You'll get a wider (developer) audience for this kind of issues.


How to lock localization of DateTime in ASP.NET MCV4 C#

Question: I'm working with a group on a project that at one point requires a DateTime to be posted in a form. We added a simple jquery-ui datepicker to do that, and it worked fine on my English configured machine. However when they tried using it themselves on a Dutch configured machine, the DateTime started using a different format, while the datepicker kept the same English format, causing errors.
How do I lock the DateTime localization in MVC4 (or the overall localization) to English to fix this?
Alternatively, how do I detect the localization to make the datepicker use the different one?
Answer: Try this:
<globalization culture="en-US" uiCulture="en-US" />

How to configure invariant culture in ASP.NET globalization?
How to Set default language in web.config file ?

This will also fix potential problems with float's and etc (point vs comma)
Answer: You could use a DataAnnotation to your DateTime object
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy HH:mm}")]
public DateTime dateTime;

then edit your format string to the English standard.
If i am correct, it will always use this format.
Comment: This only seems to change the output, not the input.
Comment: I think you should then look to the jquery-ui datepicker to pick a date in a specific format. Or maybe you should pick the time, minutes, seconds and data as seperate data and construct your custom datetime format. Not sure how that has to be done in jquery, but that might be the case
Comment: I ended up doing that in fact, because I needed the Dutch format. But that still doesn't fix the initial problem that it changes what format it uses.


Caliburn.Micro Action Message with StaticResource as parameter

Question: How can i convert this long format to short inline format. I tried with various combinations but none worked. I always get the parameter as null.

        <cal:ActionMessage MethodName="SelectTool">
           <cal:Parameter Value="{StaticResource contrastTool}" />
        </cal:ActionMessage>

I tried with this:
cal:Message.Attach="[Event GotFocus] = [Action SelectTool({StaticResource contrastTool})]"

but this doesn't work
Answer: It can be solved using Caliburn.Micro Contrib (also available via Nuget).
To enable XamlBinding, insert below code in your bootstrapper
FrameworkExtensions.Message.Attach.AllowExtraSyntax(MessageSyntaxes.SpecialValueProperty | MessageSyntaxes.XamlBinding);

Then in Xaml you may use
cal:Message.Attach="[Event GotFocus] = [Action SelectTool({StaticResource contrastTool})]"

Comment: Do not use this library. It does not work with Caliburn Micro 2.0.2 and it messes up your whole project references. I lost hours because of this.


interior cell color seems to obscure text

Question: I have a problem with my script not being able to "see" the text in a cell if it is colored.
I have two rows with all most the same data, but only one of the two is correct, and that cell has interior colorindex = 6
What I would like is to copy the text in the cells which are yellow and paste it into column D
I thought that it would be simple... I was wrong, because it seems like my script cannot see the text if the cell is colored.
My problem is centered around the strOldFolderName and strNewFolderName.
I have tried to get the text from column 2 and 3 into these strings, but if the cell is colored, the string is empty, even though the value on the other side of the = shows the correct text, if I set a stop in the sub and run it.
If the cell is not colored there is no problem with the string, it contains the correct text.
But it seems illogical to just switch the two, when I do not know what causes the inability to read the text in the cell.
I hope this make sense. Thanks for any advice :)
Here are my script:
<code> Sub PhotoDocCopyToLupus()

 Dim intOldFolderNameColumn As Integer
 Dim intNewFolderNameColumn As Integer
 Dim intCorrectFolderNameColumn As Integer
 Dim intRowStart As Integer
 Dim intRowEnd As Integer
 Dim i As Integer

 Dim strOldFolderName As String
 Dim strNewFolderName As String
 Dim strCorrectFolderName As String

 intOldFolderNameColumn = 2
 intNewFolderNameColumn = 3
 intCorrectFolderNameColumn = 4
 intRowStart = 2
 intRowEnd = 15

 Worksheets("Compare").Activate
 Cells(1, 4) = "CorrectFolderName"

 For i = intRowStart To intRowEnd

     strOldFolderName = Trim(Cells(i, intOldFolderNameColumn))
     strNewFolderName = Trim(Cells(i, intNewFolderNameColumn))

         If Cells(i, intOldFolderNameColumn).Interior.ColorIndex = 6 Then
             strOldFolderName = Trim(Cells(i, intOldFolderNameColumn))
             strOldFolderName = strCorrectFolderName
         ElseIf Cells(i, intNewFolderNameColumn).Interior.ColorIndex = 6 Then
             strNewFolderName = Trim(Cells(i, intNewFolderNameColumn))
             strNewFolderName = strCorrectFolderName
         Else
             strCorrectFolderName = ""
             Cells(i, intCorrectFolderNameColumn).Interior.ColorIndex = 35
         End If

     Cells(i, intCorrectFolderNameColumn) = strCorrectFolderName

 Next i

 End Sub
</code>
Comment: Your code doesn't set `strCorrectFolderName` to anything other than an empty string.
Comment: Did you try to debug your code? Go through it step by step using F8 to see how it goes and check your variable values in each step to find out your issue.
Answer: Should do what you want:
<code>Sub PhotoDocCopyToLupus()

    'use constants for fixed values...
    Const COL_OLD_FLDR As Long = 2
    Const COL_NEW_FLDR As Long = 3
    Const COL_CORR_FLDR As Long = 4
    Const ROW_START As Long = 2
    Const ROW_END As Long = 15

    Dim i As Long, corrName As String

    With Worksheets("Compare")
        .Cells(1, COL_CORR_FLDR) = "CorrectFolderName"

        For i = ROW_START To ROW_END
            If .Cells(i, COL_OLD_FLDR).Interior.ColorIndex = 6 Then
                corrName = Trim(.Cells(i, COL_OLD_FLDR))
            ElseIf .Cells(i, COL_NEW_FLDR).Interior.ColorIndex = 6 Then
                corrName = Trim(.Cells(i, COL_NEW_FLDR))
            Else
                corrName = ""
                .Cells(i, COL_CORR_FLDR).Interior.ColorIndex = 35
            End If
            .Cells(i, COL_CORR_FLDR) = corrName
        Next i
    End With

 End Sub
</code>
Comment: It does :) Thanks a lot :)


Understanding the purpose of returning and passing custom Objects in OOP

Question: First of all let me tell you that programming is my hobby (love programming) and even though I have taken some programming classes in college (C++) and have created some small programs in C++(QT), Objective-C, PHP and now Swift, I have never had the need to heavily use custom objects other than create instances, call some functions/methods from those objects or inherit from one to the other, all pretty simple stuff. The one thing that has been bothering me and that I think is the heart of the OOP world is understanding the concept of creating and using custom objects. I know this question is something I should have asked long time ago, shame on me.
Can someone be so kind and create a quick and simple example of how and what functionality is usually involved when creating custom objects?
Here I'm using Swift but this could be in any other language:
// custom object
class ClassA{

    // what functionality could fit here
}

class ClassB{

     init(customObject:ClassA){
         // when would you pass a custom object to this class?
     {

        func returnCustomObjec()->ClassA{
        // when would you return a custom object?
    }
        func passCustomObject(customObjec:ClassA){
        // when would you pass a custom object?
    }
}

FYI - I know when to return or pass, Stings, Ints, Doubles, etc. but I want to see when would make sense to create functions that return or accept custom objects in a real program.
Comment: This seems like a really broad topic that you are better off learning from a book or searching the Internet for topics. Covering the advantages of Objects has a very broad scope. QT is full of objects, so if you are familiar with it, then you should be able to ascertain why and how objects are used. Without some context, we can't tell you how you'd use objects in your example.
Comment: One of the usages is Dependency Injection.
Comment: Search for Dependency Injection
Comment: @fs_tigre Just about any C++ book should have a section on Object Oriented Programming and what problems it solves.
Comment: @FélixGagnon-Grenier - A non built-in type. I have built a lot of custom objects and used inheritance a lot but I have never passed around these types to other classes.
Comment: Do you have any specific book that you could recommend that uses custom objects? All of the books I have read are more of a how-to reference.
Comment: Ok, I will look into books that use that concept, I believe the Laravel framework uses Dependency Injection a lot. Thanks
Comment: You might want to look into what OOP is all about.  You are not really asking the "right" question to get the answer you desire.
Comment: Sorry for being obtuse, but... I don't exactly understand what is meant by custom objects. An anonymous object, created on the fly? A non built-in type?
Comment: I don't understand how you've taken "some" (i.e. > 1) C++ classes in college without having created a multitude of your own classes. *Any* book on C++ is full of them.
Comment: I see you have already accepted an answer, but for lots of examples I suggest you read the book "Design Patterns" (http://preview.tinyurl.com/phb8ctv). If the book costs too much for you, the check it out from the library, but it's one of those books that every programmer should own IMHO.
Answer: IMHO the most basic use of custom objects is return types of functions. Lets say I want to write a function that returns an int a double and a string then I could do this by passing references:
void foo(int& a,double& b,string& c);

However, in this way it is not so clear that these parameters are only for return values. And also now the caller has to take care to declare (and maybe initialize) these 3 variables and has to give them reasonable names. If the return type is lightweight and copying is not a problem, this can be done like this:
struct foo_returnType {
    int a;
    double b;
    string c;
}

foo_returnType foo();

Now there is no confusion whether its return values or parameters and more importantly if the function returns those 3 parameters, it is very likely that they logically belong together and this should be reflected in the code. I can give them a reasonable name (maybe something better than foo_returnType) and for convenience I can provide some more nice features for this new type (e.g. overloading ostreams << operator to print the type on the screen with some additional meaningful information on the meaning of the 3 parameters).
Comment: I think the main point is "it is very likely that they logically belong together". Objects are meant to encapsulate instances of properties that apply to a single "object". A cat has whiskers, fur, purrs, and pounces. A car has 4 wheels, an engine, can drive in a given direction in forward or reverse.
Comment: @crush I remember the story of cars that have wheels and an engine from school, but I always wonder where this thing with the cat with fur, purrs and that stuff is coming from
Comment: The cat example is usually used to illustrate polymorphism/inheritance. You start with a base Animal or Mammal class, then specialize it into a cat. The idea is to illustrate that objects encapsulate properties and actions that define said object.
Comment: @fs_tigre Mislead by stupid teachers with all their cars and animals I thought for very long time that inheritance is the main point of having classes. For some reason the point where I started to really like C++ coincided with me realizing that inheritance can be nice but its definitely not the main advantage of having custom types/classes.
Comment: Exactly, I feel like I'm missing the real purpose of using custom classes.
Comment: @fs_tigre I gave you an example where there is no inheritance or dependency injection or whatsoever, just a plain custom class. I really think this is super useful and I use it for return types on an every day basis. What is it that you dont understand on this example?
Comment: @tobi303 Your example returns an int, a double and a string, I have no problem with that, I do that all the time. My issue is that I don't know when to pass or return custom objects (other than int, floats etc). As some other have suggested I think I need to read more about advance OOP. Thanks
Comment: @fs_tigre My example is not returning an int, a double and a string, but it returns an object that encapsulates an int, a double and a string. That may seem a minor difference but actually it is a major one when you consider readability, maintainability and convenience for the user of the function.
Comment: Well, I do get the concept of inheritance, but for some reason I don't fully understand when to pass or return a custom object. I will read more about the Dependency Injection concept.
Answer: Oh my, there is a lot, lot of cases that does this. I just made some object that deal with uniform shaders in opengl. See my simplified code. There is a lot of object involved here:
Shader ShaderManager::load(Camera* camera, Entity* entity) {
    Shader shader;

    shader.addUniform("transform", make_unique<TransformUniform>(camera));
    shader.addUniform("color", make_unique<Vec4Uniform>(entity->getColor()));

    return shader;
}

And even color is an object, a very simple struct, but still an object. I rarely deal with primitives, but again some of my object act as primitive (I'm in C++, dynamic allocation is a choice)
Comment: Oh yes, sorry, must be a typo. Thank for the correction.
Comment: Guillaume Racicot - I'm getting closer, now let me see if I understand this concept. Is the method `addUniform` implemented in class `Shader` right? If my assumption is right, I got it now..
Comment: Exactly. `addUniform` takes a `unique_ptr` as parameter and store it in a list. structs and classes are just a way to put a concept  and a way to do things into one construct. So `Shader` encapsulate all the logic behind what's a shader, and need to deal with uniforms. Object are a way to group data and logic with a name.
Comment: Guillaume Racicot - I think you example is close to what I'm trying to understand. But there are a few things that I don't fully understand. In your example you have a method that returns a type `Shader` but it is declared as "void" shouldn't this be `Shader ShaderManager::load(Camera* camera, Entity* entity){//...}`?
Comment: Thanks a lot for the example, I just needed an example to get around this concept. I will keep reading more about it
Answer: I have a php backgound. I messed around a bit with c++ and java, but this answer is in a php perspective.
In php, custom objects are the objects which actually do things (in java there are a lot of libraries if I understand correctly, one might be able to do a lot without any custom object). That is, objects representing your business entities, such as an invoice or a sale item, or representing your application, such as a http response object, or a template parser object.
Passing and returning custom objects ensures that your methods will have a predictable behavior, that is, not calling non-existing methods on your objects, being sure that if you type-hint an interface in a method, any object that implements the sumable interface will be able to be sumed (for example).
The purpose of passing and returning cutom objects is to ensure of an application's behavior


SqlDataReader returning incorrect results

Question: I have an issue with this code in my MSSQL Data Access manager. Sometimes the returned records are not the expected ones. The DataReader columns come from the good table but the fields seems to become from another request.
This behavior appears when I got lot of simultaneous requests on the same table and the result is moreless like 'select A retrun B, select B return D, select C retrun Z,...'
 public bool Read(string ID)
    {

        bool _return = false;

        System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection(ConnectionString);

        try
        {

            string Query = "Select * From Sounds Where ID = '" + ID + "'";

            System.Data.SqlClient.SqlDataReader DataReader;

            using (System.Data.SqlClient.SqlCommand Command = new SqlCommand())
            {
                Command.Connection = Connection;
                Command.CommandText = Query;

                Connection.Open();

                DataReader = Command.ExecuteReader();
            }
            if (DataReader.Read())
            {
                FillClass(DataReader);
                _return = true;
            }
            else
            {
                _return = false;
            }

            if (! DataReader.IsClosed)  DataReader.Close();

        }
        catch (Exception e)
        {
            _return = false;
        }
        finally
        {
            if ((Connection != null) && (Connection.State == ConnectionState.Open)) {
                Connection.Close();
            }
        }

        return _return;
    }

I don't understand SQL 2012 return a bad record or the .Net CLR mismatch the SQL pipes...
Thank for help.
-Alex
Comment: First things to fix: a) use parameterized SQL; b) stop swallowing exceptions without reporting them; c) stop catching bare `Exception`; d) use `using` statements to dispose of the connection, command and reader.
Comment: calling `if (DataReader.Read())` advances the reader to 1 record. Then you call `FillClass(DataReader);`. If you call `DataReader.Read()` again inside `FillClass`, you will miss the first record. Check that you don't have that mistake.
Comment: I would be very interested in seeing what the *calling* code looks like here; I wonder if the problem is at the caller (i.e. sharing state) rather than in the data access
Comment: That FillClass method is just a binding method to load datareader content to derivated class poperties (i.e. this.foo = DataReader("foo"))
Answer: It is staggeringly unlikely that you're seeing a new never-seen-before issue on command / result mismatches; more likely, your code is simply getting something wrong; the first thing to do is to simplify (and fix a lot of the problems):
public bool Read(string ID)
{
    using(var connection = new SqlConnection(ConnectionString))
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "select * from Sounds where ID=@ID";
        command.Parameters.AddWithValue("ID",ID);
        Connection.Open();
        using(var reader = command.ExecuteReader())
        {
            if(reader.Read()
            {
                FillClass(reader);
                return true;
            }
            return false;
        }
    }
}

The next interesting question is "what does FillClass look like?".
The next interesting question is "what does the calling code look like? - is there any chance you are simply incorrectly sharing state between requests, for example by using static in a web application?".
The final interesting question is: could this just use something like dapper (which simplifies ADO.NET access, parameterizes, and automatically maps properties/fields by column name):
Foo GetFoo(string id)
{
    using(var connection = new SqlConnection(ConnectionString))
    {
        return connection.Query<Foo>(
            "select * from Sounds where ID=@id", new { id }).SingleOrDefault();
    }
}

the less code you write, the less chance there is to inject unnecessary mistakes...
Answer: there is no static in this part of the application. This read method is a part of the base class who load object from the database.
I implement your piece of code in my application and put on my server. The problem still remain...
Here is a part of the code who call the read to the database:
public class program
{
    public static Toolbox toolbox = new Toolbox();

    public void main()
    {
        // ....

        var Duration = toolbox.GetFileDuration(File);

        // ...
    }

    //...
}

public class Toolbox
{
    //....

     public long GetFileDuration (string FileName){

         Repository.dbSound Sound = new Repository.dbSound(ConnectionString);
         if (Sound.Read(FileName))
         {
             return Sound.Duration;
         }
         else
         {
             return -1;
         }

    }

    //....

}

I the other hand, I add logging in the method to get the ID send and the ID returned in the datareader and I got this in the logfile:

07920-04.mp3 --> Datareader.Read() FAILED
  07747-12.mp3 --> 07920-04.mp3

the both file exist in the table !!!
Thank for help.


Automatically generate assignment variables by Resharper

Question: Say I have a function
public List<FileChangedData> GetFileChanging(DateTime startDateTime)
{
...
}

If I call the function
GetFileChanging(startDate);

Is there a way to use resharper to automatically generate the assignment, i.e.,
List<FileChangedData> obj=GetFileChanging(startDate);

?
Answer: Yes, kind of... resharper use the [Pure] attribute in order to see that specific method returns a value and do nothing else useful.
So you can use the [Pure] attribute and reshaper will suggest you to introduce a variable or a field.
Eg.
[System.Diagnostics.Contracts.Pure]
public List<FileChangedData> GetFileChanging(DateTime startDateTime)
{
    ...
}


How to get the commit hash (ID) from specific commit count?

Question:
Each time we committed, that consider as a count. You can check your current commit count by running this command:
git log --pretty=format:'' | wc -l

100th
Let's assume, I want to get the commit-id of my 100th commits.
Is there a way to get the commit id base on that count?
Comment: I think they think that because your request is very unusual. People normally don't track commit counts, except as in number of parents back. Usually you don't need to know the number of commits from the root. It would be interesting to hear what you are going to use this for.
Comment: @ChristofferHammarström : If you did your first commit , that's 1. After a while, you will make 100 commits, that's `100th`, if someone come back to you to relook into your commit `#65`. What would that be ?

That is what I am after - right now.
Comment: what do you mean by commit count?
Comment: Each time we committed, that consider as a count. You can check your current commit count by running this : `git log --pretty=format:'' | wc -l
`
Comment: Which commit do you want the id for?
Comment: @Code-Apprentice `100` th, as I stated in the OP.
Comment: @cyber8200 When I read your OP, that isn't entirely clear. I suggest you edit to make that more clear.
Comment: Do you mean that the current `HEAD` is the 1st commit, and its 99th ancestor is the 100th commit, or do you mean that the very first commit in the repo is the 1st commit, and all of its 99th descendants are each considered a 100th commit?
Comment: @cyber8200: OK, because everyone seems to be answering the other way around.
Comment: @ChristofferHammarström, yep. I will make a diagram. I have no idea why people think like that. I think only `Daniel` answer that way. I think Rakmo on the right track.
Comment: @ChristofferHammarström I updated my OP with picture to make it cleaer.
Answer: git log -1 --skip=n

will skip the first n-commits, and just show 1 commit
To just get the ID:
git log -1 --skip=n --pretty=format:"%h" --no-patch

Where in your case n=100
Comment: I need to get the commit id of my `100th` commit.
Comment: What are you talking about ? Is this even relevant ?
Comment: @cyber8200 Then yes, this is relevant. Just replace `n` with `100`. Or maybe `99`.
Comment: @Rakmo : You're right, your answer is perfect then. :)
Comment: Ok, I will try that again then.
Comment: I have added further to get "just the Hash"
Comment: I've tried that command - nothing is printing : https://i.imgur.com/DT6Qpms.png
Comment: Replace n with 100:

git log -1 --skip=100 --pretty=format:"%h" --no-patch
Comment: I am not sure of your Git history, but does it go back to count 2323 also? This should work until your first commit.
Comment: My real current commit `2236`, so `2323` definitely there.
Comment: Dude.. See what you are saying. Your current commit count is less than that you are searching for :)
Answer: You can also do git show HEAD~n --format=oneline to just get the one commit.
Comment: oh ok. that's what I need. I didn't know n was for the number.
Comment: `git show HEAD~2323 --format=oneline
fatal: ambiguous argument 'HEAD~2323': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]' ` <--- now get this
Comment: I need to get the commit id of my `17th` commit. Let's say `n=17`
Comment: I got this error running your suggestion `⚡  git show HEAD^2323 --format=oneline
fatal: ambiguous argument 'HEAD^2323': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'                                                                       `
Comment: @cyber8200 oops try `~` instead of `^`.
Comment: Ok, will try again now base on your updated answer.
Comment: Are you counting from top to bottom?
Comment: @cyber8200 thats the way git works - from most recent to the past.
Comment: Ok, will leave it then. BTW, your answer is backward what I asked.
Comment: @cyber8200 you could do some math and calculate it yourself... subtraction is your friend.
Answer: You've drawn your commits as being all in a nice neat straight line.
This does sometimes happen, but in most real repositories, there are sections of commits that are not in a nice neat straight line:
...--A--B--D---------H--I--J   <-- newest
         \          /
          C--E--F--G

Let's say we want commit I.  This is easy to find: it's one step back from commit J.  Using:
git rev-parse newest~1

will find commit J.  Similarly, to find commit H, we can go back two steps:
git rev-parse newest~2

will print the hash ID of commit H.
But commit G is two steps back, then one step down-and-back.  Commit D is three steps back in a straight line.  This happens because commit H is a merge commit.
Assuming commit D is the first parent of commit H, writing:
git rev-parse newest~3

will find its hash ID.  Git will step back three times, along the first-parent line.  There's only one parent of J and only one of I so the first parent is the only parent, but at H, the first-parent specifically chooses D and not G.
If you use git log or git rev-list, both of these must display the commits linearly.  The method they use to do this is rather tricky, and the order that commits show up, in this output, is affected by command-line options: --author-date-order, --topo-order, and so on.
If you're satisified with the order that git rev-list (or git log) uses on its own, use Rakmo's answer.  (Remember that git log and git rev-list work backwards, from the newest towards the oldest.  You can have them reverse their output with --reverse but this interacts weirdly with --skip.  You might want to just get a complete list of commits, reverse it, and pick the n'th line of that.)
If you would like to traverse first-parents only, and want to count from the end—that is, newest names the newest, newest~1 names the commit one step back, and so on—use Daniel A. White's answer or some variant of it.
For more complex answers to what turns out to be a complex question (if you aren't satisfied with Git's default linearization, that is), you'll need to refine the question.
Comment: Your explaining is precisely perfect . Thank-you.


Why does float do this?

Question: I am playing around with plain old C. I am simply calculating a number of pennies and then increasing the amount exponentially over a certain number of iterations. At the end of the process, I have large number of cents/pennies that I want to display on the screen as dollars and cents.
My output current looks like this:
"You have 805306365 pennies"

I attempt to convert this number into dollars by defining a new variable as a float:
float totalD = total / 100.00;

The output shows 8053063.50. Why is the division of this int causing a loss of 15 cents?
I am trying to display it through a "printf" if that helps:
printf("You have %.2f dollars", totalD);

I know I can just convert my cents into a string and try to format it however I like, but I am perplexed as to why a float would do this. Can anyone give me any insight on why this happens and maybe how to deal with it?
Comment: If you're using `float`, it will not have enough precision to hold `805306365`. And don't use floating-point types for money.
Comment: [Read this carefully](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). It will take awhile but it will forever change any ideas you may have about floating pointer numbers.
Comment: Don't do math on floating point numbers when integers will suffice.
Comment: @WhozCraig - if I could put five "helpful" flags on your comment, I would.
Answer: updated for accuracy and completeness
You are encountering is a (rather common) problem of precision in floating point numbers. On many compilers, floating point numbers are only 32 bits long, and they use a certain number of those bits (23) for their "significand" (sometimes referred to as "mantissa"), 1 sign bit, and 8 bits for the "exponent" (in a number like 1.23E45, the "1.23" is the significand, and the "45" is the exponent. In binary, you actually have relatively few (24) ones and zeros available so you run out of precision at around digit 6 or 7 in decimal notation).
To illustrate this loss of precision, I wrote a few lines of code:
#include <stdio.h>

int main(){
  float fpennies;
  long lpennies, ii;

  lpennies = 805306360;
  for(ii = 0; ii< 100; ii++) {
      fpennies = lpennies + ii;
      printf("%ld pennies converted to float: %.0f fpennies\n",ii+ lpennies, fpennies);
  }
}

This produced many lines of the type
805306360 pennies converted to float: 805306368 fpennies
805306361 pennies converted to float: 805306368 fpennies
805306362 pennies converted to float: 805306368 fpennies
...
805306400 pennies converted to float: 805306368 fpennies
805306401 pennies converted to float: 805306432 fpennies

As you can see, right around 805306400, incrementing the long by just one increments the float representation of the number by 64! This is best explained by looking at the binary representation of the floating point number a little closer.
First, here is the organization of a 32 bit floating point number (from http://upload.wikimedia.org/wikipedia/commons/d/d2/Float_example.svg):

We can get the hex representation of a number with some explicit casting:
printf("%.0f %08x", fpennies, *(unsigned int*)(&fpennies));

For the two values that spanned the jump we saw earlier, this results in
805306368 4e400000
805306432 4e400001

As you can see, the "least significant bit" of the significand increased by 1, but the exponent implies a multiplier of 64. Why 64? Well, let's expand the top few bits:
0x4e40 = 0100 1110 0100 0000 in binary

Since the top bit is the sign bit (0 = positive), and the next eight bits are the exponent, this makes the exponent
1001 1100 = 0x9c = 156

Now the rule for getting from the bits in the floating point to its value (see http://en.wikipedia.org/wiki/Single-precision_floating-point_format ) is
value = (-1)^(sign bit) * (1 + sum(i=1 to 23, bit(23-i)*2^(-i))) * 2^(exponent - 127)

In this case, an change of 1 in the least significant bit (bit 0) adds 2^(-23) * 2^( 156 - 127 ) = 2^6 = 64
Thus, for numbers of this magnitude, the smallest step that can be represented is 64, as you see in the output.
If you want to get around this problem, you can do the thing suggested in Vaughn's answer - work with long integers representing pennies, and using integer math (division, modulo) to obtain the "whole dollars, whole cents" amount.
long int dollars, cents, pennies;
...
dollars = pennies / 100;
cents = pennies % 100;

In this way you can represent some pretty big sums of money without loss of precision.
In practice, when you write
float pennies = 805306365;
printf("you have %f pennies\n", pennies);

You get
You have 805306368 pennies

If you use a double type you will have better luck (in this case).
Answer: I think you would have better luck doing it this way:
printf("You have %d.%02d dollars", total/100,total%100);

Answer: Consider using long int, or long long to represent pennies. Floats, or doubles are not suitable for what you are trying to do. I suggest reading this discussion on StackOverflow.

Why does float do this?


What's the maximum inventory size?

Question: You can increase your inventory size 10 slots at a time for an expenditure of Pax Romana.
What is the maximum size your inventory can reach in this manner?  Do you ever have to do anything other than spend PAX?
Answer: This thread indicates that the maximum personal inventory space is 200 slots, purchased using PAX at an incremental cost for each additional purchase.
It appears that your personal bank space can be increased by 200 slots as well.
Comment: And you can get another 100 slots for free by creating a Cabal (via the Cabal bank).
Comment: Oops, I forgot to accept this...
Answer: The maximum inventory size is 200.
I checked experimentally by buying until actually hitting the limit. After that the "+" button only gives the message that the maximum size has been reached.
The alternative to the inventory is using (and upgrading) your bank account to "swap out" items you don't need during the game, but want to keep. Up to 200 items here as well.
The "create a cabal" trick to get additional slots in the cabal bank (as opposed to your own bank account) is available only for those who do not join a "real" cabal, and only as long as they do. Once you join a real cabal, you have to leave your "one-man-cabal" and forfeit those extra slots.
On a related note, the maximum Skill Points (SP) you can collect are 40 - after that, you get the message "You did not receive any skill points as you have reached the cap of 40.".
Answer: The maximum inventory size in the beta was 200 purchasable with PAX and you can buy 10 extra inventory from a vendor but its pretty expensive to get max inventory slots.
Comment: which vendor sells more bag space?
Comment: This is confusing - so you're saying 210?  Does the vendor in question not take PAX?
Answer: It's 250 now, but those last upgrades are very, very costly (almost 1m from 200-210)

What's the maximum inventory size?


Template argument deduction for variadic function pointer parameter - handling of ambiguous cases

Question: Consider the following code:
#include <iostream>

void f(int) { }

void f(int, short) { }

template<typename... Ts> void g(void (*)(Ts...))
{
   std::cout << sizeof...(Ts) << '\n';
}

template<typename T, typename... Ts> void h(void (*)(T, Ts...))
{
   std::cout << sizeof...(Ts) << '\n';
}

int main()
{
   g(f);         // #1
   g<int>(f);    // #2
   h(f);         // #3
   h<int>(f);    // #4
}

The intent is to try each of the lines in the body of main() separately. My expectations were that all four calls were ambiguous and would result in compiler errors.
I tested the code on:

Clang 3.6.0 and GCC 4.9.2, both using -Wall -Wextra -pedantic -std=c++14 (-std=c++1y for GCC) - same behaviour in all these cases, except for minor differences in the wording of error messages;
Visual C++ 2013 Update 4 and Visual C++ 2015 CTP6 - again, same behaviour, so I'll call them "MSVC" going forward.

Clang and GCC:

#1: Compiler error, with a confusing message, basically no overload of 'f' matching 'void (*)()'. What? Where did the no-param declaration come from?
#3: Compiler error, with another confusing message: couldn't infer template argument 'T'. Of all the things that could fail there, deducing the argument for T would be the last one I would expect...
#2 and #4: Compiles with no errors and no warnings, and chooses the first overload.

For all four cases, if we eliminate one of the overloads (any one), the code compiles fine and chooses the remaining function. This looks like an inconsistency in Clang and GCC: after all, if deduction succeeds for both overloads separately, how can one be chosen over the other in cases #2 and #4? Aren't they both perfect matches?
Now, MSVC:

#1, #3 and #4: Compiler error, with a nice message: cannot deduce template argument as function argument is ambiguous. Now that's what I'm talking about! But, wait...
#2: Compiles with no errors and no warnings, and chooses the first overload. Trying the two overloads separately, only the first one matches. The second one generates an error: cannot convert argument 1 from 'void (*)(int,short)' to 'void (*)(int)'. Not so good anymore.

To clarify what I'm looking for with case #2, this is what the standard (N4296, first draft after C++14 final) says in [14.8.1p9]:

Template argument deduction can extend the sequence of template
  arguments corresponding to a template parameter pack, even when the
  sequence contains explicitly specified template arguments.

Looks like this part doesn't quite work in MSVC, making it choose the first overload for #2.
So far, it looks like MSVC, while not quite right, is at least relatively consistent. What's going on with Clang and GCC? What's the correct behaviour according to the standard for each case?
Answer: As far as I can tell, Clang and GCC are right in all four cases according to the standard, even though their behaviour may seem counter-intuitive, especially in cases #2 and #4.
There are two main steps in the analysis of the function calls in the code sample. The first one is template argument deduction and substitution. When that completes, it yields a declaration of a specialization (of either g or h) where all template parameters have been replaced with actual types.
Then, the second step attempts to match f's overloads against the actual pointer-to-function parameter that was constructed in the previous step. The best match is chosen according to the rules in [13.4] - Address of overloaded function; in our cases this is pretty simple, as there are no templates among the overloads, so we have either one perfect match or none at all.
The key point to understanding what happens here is that an ambiguity in the first step doesn't necessarily mean that the whole process fails.
The quotes below are from N4296 but the content hasn't changed since C++11.
[22.214.171.124p6] describes the process of template argument deduction when a function parameter is a pointer to function (emphasis mine):

When P is a function type, pointer to function type, or pointer to
  member function type:
  — If the argument is an overload set containing one or more function
  templates, the parameter is treated as a non-deduced context.
  — If the argument is an overload set (not
  containing function templates), trial argument deduction is attempted
  using each of the members of the set. If deduction succeeds for only
  one of the overload set members, that member is used as the argument
  value for the deduction. If deduction succeeds for more than one
  member of the overload set the parameter is treated as a non-deduced
  context.

For completeness, [220.127.116.11p5] clarifies that the same rule applies even when there's no match:

The non-deduced contexts are: [...]
  — A function parameter for which argument deduction cannot be done because
  the associated function argument is a function, or a set of overloaded
  functions (13.4), and one or more of the following apply:
  — more than one function matches
  the function parameter type (resulting in an ambiguous deduction), or
  — no function matches the function parameter type, or
  — the set of functions supplied as an argument contains one or more
  function templates.

So, no hard errors because of ambiguity in these cases. Instead, all template parameters are in non-deduced contexts in all our cases. This combines with [14.8.1p3]:

[...] A trailing template parameter pack (14.5.3) not otherwise
  deduced will be deduced to an empty sequence of template arguments.
  [...]

While the use of the word "deduced" is confusing here, I take this to mean that a template parameter pack is set to the empty sequence if no elements can be deduced for it from any source and there are no template arguments explicitly specified for it.
Now, the error messages from Clang and GCC start to make sense (an error message that only makes sense after you understand why the error occurs is not exactly the definition of a helpful error message, but I guess it's better than nothing):

#1: Since Ts is the empty sequence, the parameter of g's specialization is indeed void (*)() in this case. The compiler then tries to match one of the overloads to the destination type and fails.
#3: T only appears in a non-deduced context and is not explicitly specified (and it's not a parameter pack, so it cannot be "empty"), so a specialization declaration cannot be constructed for h, hence the message.

For the cases that do compile:

#2: Ts cannot be deduced, but one template parameter is explicitly specified for it, so Ts is int, making g's specialization's parameter void (*)(int). The overloads are then matched against this destination type, and the first one is chosen.
#4: T is explicitly specified as int and Ts is the empty sequence, so h's specialization's parameter is void (*)(int), the same as above.

When we eliminate one of the overloads, we eliminate the ambiguity during template argument deduction, so the template parameters are no longer in non-deduced contexts, allowing them to be deduced according to the remaining overload.
A quick verification is that adding a third overload
void f() { }

allows case #1 to compile, which is consistent with all of the above.
I suppose things were specified this way to allow template arguments involved in pointer-to-function parameters to be obtained from other sources, like other function arguments or explicitly-specified template arguments, even when template argument deduction can't be done based on the pointer-to-function parameter itself. This allows a function template specialization declaration to be constructed in more cases. Since the overloads are then matched against the parameter of the synthesized specialization, this means we have a way to select an overload even if template argument deduction is ambiguous. Quite useful if this is what you're after, terribly confusing in some other cases - nothing unusual, really.
The funny thing is that MSVC's error message, while apparently nice and helpful, is actually misleading for #1, somewhat but not quite helpful for #3, and incorrect for #4. Also, its behaviour for #2 is a side effect of a separate problem in its implementation, as explained in the question; if it weren't for that, it would probably issue the same incorrect error message for #2 as well.
This is not to say that I like Clang's and GCC's error messages for #1 and #3; I think they should at least include a note about the non-deduced context and the reason it occurs.


Will ubuntu work on my computer?

Question: Here are the specs:
Microsoft Windows XP Media Center Edition Version 2002 SP3
Packard Bell.
Intel (R) Pentium (R) D CPU 2.80GHz
1.00 Gb of RAM
Comment: You can try Ubuntu before you install it.  without affecting your system
Answer: In theory - yes - is the short answer.  You meet the minimum recommend specifications.
The quickest way to find out is to download the ISO and either burn it onto a CD or write it to a USB stick.
Follow the 1 - 2 - 3 guide on the Ubuntu website.
You can Ubuntu from what is called a live CD - if everything looks ok - go ahead and install

as an installation from windows (this is called a wubi install) - or
as a side-by-side installation (called a dual boot) - or even
just say goodbye to windows and wipe your hard-drive clean during installation with a Ubuntu only install.

There is more than Ubuntu for you to explore as well (download links below)....

Lubuntu
Xubuntu
Kubuntu
Ubuntu
Comment: If it turn out that Ubuntu is to heavy / sluggish / slow for your pc you can try a light weight version called xubuntu (http://www.xubuntu.com)
Comment: almost all people forget this version of ubuntu Lubuntu -> https://help.ubuntu.com/community/Lubuntu
Answer: It will work Although it will be good to update your RAM to 2GB or even 4GB. I had 1.9GHz CPU and it worked fine with 10.04 and I don't think there is much thinks to make it not work! But my advice is install 10.10 and if it performs well upgrade to 11.10.
Comment: What a bad idea to suggest 10.10. This is a release that will not get any security updates anymore from April on.
Comment: You can see a bad idea up until when the computer cannot support Natty (unity) or Gnome3/Unity 11.10. If you read between lines I said that if performance is Optimum he should upgrade. So Yes if machine cannot handle Natty/Oneiric, only option is Maverick or below. And that is not my faulty
Comment: I see your answer is great but wait a minute I didn't knew the specs for Ubuntu and so I proposed doing tests from lower versions upwards. Thanks for downvotes and sorry for this little "protest" ;)

Will ubuntu work on my computer?


Install TP-link TL-WN725N USB wifi driver on Ubuntu 20.04

Question: I have a USB wifi adaper tp-link model TL-WN725N. It was working fine but suddenly today it's saying that "No wifi adapters found". So I tried installing a driver from this page. But the installation failed. make all command wasn't compiling then I checked the website again. In the website it says, Operating System: Linux (kernel 2.6.18 ~ 3.19.3). But my kernal is 5.11.0-25-generic. And the USB device finds all the wifi that are available. But it can't connect to them. What can I do now?
This is the error that I am getting:
$HOME/Documents/Driver/include/osdep_service_linux.h:261:8: error: '_timer' {aka 'struct timer_list'} has no member named 'data'
  261 |  ptimer->data = (unsigned long)cntx;
      |        ^~
$HOME/Documents/Driver/include/osdep_service_linux.h:262:2: error: implicit declaration of function 'init_timer'; did you mean '_init_timer'? [-Werror=implicit-function-declaration]
  262 |  init_timer(ptimer);
      |  ^~~~~~~~~~
      |  _init_timer

Some other useful command outputs:
➜ ifconfig
enp2s0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 10:7b:44:32:b5:91  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 3866  bytes 321595 (321.5 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 3866  bytes 321595 (321.5 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlx7cc2c61b3890: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet6 fe80::f871:26fc:9f55:13ed  prefixlen 64  scopeid 0x20<link>
        ether 7c:c2:c6:1b:38:90  txqueuelen 1000  (Ethernet)
        RX packets 3  bytes 348 (348.0 B)
        RX errors 0  dropped 1  overruns 0  frame 0
        TX packets 19  bytes 3460 (3.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

➜ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 13d3:5a01 IMC Networks USB2.0 VGA UVC WebCam
Bus 001 Device 002: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 008: ID 0bda:8179 Realtek Semiconductor Corp. RTL8188EUS 802.11n Wireless Network Adapter
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

More outputs:

########## wireless info START ##########

Report from: 07 Aug 2021 05:18 +06 +0600

Booted last: 07 Aug 2021 00:00 +06 +0600

Script from: 25 Jan 2020 03:34 UTC +0000

##### release ###########################

Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:    20.04
Codename:   focal

##### kernel ############################

Linux 5.11.0-25-generic #27~20.04.1-Ubuntu SMP Tue Jul 13 17:41:23 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Parameters: ro, quiet, splash, vt.handoff=7

##### desktop ###########################

Ubuntu

##### lspci #############################

02:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL810xE PCI Express Fast Ethernet controller [10ec:8136] (rev 07)
    Subsystem: ASUSTeK Computer Inc. RTL810xE PCI Express Fast Ethernet controller [1043:200f]
    Kernel driver in use: r8169

##### lsusb #############################

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 031: ID 0bda:b721 Realtek Semiconductor Corp. Bluetooth Radio
Bus 001 Device 003: ID 13d3:5a01 IMC Networks USB2.0 VGA UVC WebCam
Bus 001 Device 002: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 035: ID 0bda:8179 Realtek Semiconductor Corp. RTL8188EUS 802.11n Wireless Network Adapter
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

##### PCMCIA card info ##################

##### rfkill ############################

0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

##### secure boot #######################

EFI variables are not supported on this system

##### lsmod #############################

r8188eu               421888  0
lib80211               16384  1 r8188eu
cfg80211              888832  1 r8188eu
asus_nb_wmi            32768  0
wmi_bmof               16384  0
asus_wmi               36864  1 asus_nb_wmi
sparse_keymap          16384  1 asus_wmi
wmi                    32768  3 asus_wmi,wmi_bmof,mfd_aaeon
video                  49152  2 asus_wmi,i915

##### interfaces ########################

##### ifconfig ##########################

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback <MAC address> brd <MAC address>
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp2s0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN group default qlen 1000
    link/ether <MAC 'enp2s0' [IF1]> brd <MAC address>
14: wlx<IF from MAC [IF2]>: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN group default qlen 1000
    link/ether <MAC 'wlx<IF from MAC [IF2]>' [IF2]> brd <MAC address>

##### iwconfig ##########################

lo        no wireless extensions.

enp2s0    no wireless extensions.

wlx<IF from MAC [IF2]>  unassociated  ESSID:""  Nickname:"<WIFI@REALTEK>"
          Mode:Managed  Frequency=2.412 GHz  Access Point: Not-Associated
          Sensitivity:0/0
          Retry:off   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality:0  Signal level:0  Noise level:0
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

##### route #############################

##### resolv.conf #######################

[777 root '/etc/resolv.conf' -> '../run/systemd/resolve/stub-resolv.conf']

nameserver 127.0.0.53
options edns0 trust-ad

##### network managers ##################

Installed:

    NetworkManager

Running:

root         695       1  0 Aug06 ?        00:00:29 /usr/sbin/NetworkManager --no-daemon

##### NetworkManager info ###############

GENERAL.DEVICE:                         wlx<IF from MAC [IF2]>
GENERAL.TYPE:                           wifi
GENERAL.NM-TYPE:                        NMDeviceWifi
GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/Devices/14
GENERAL.VENDOR:                         Realtek Semiconductor Corp.
GENERAL.PRODUCT:                        RTL8188EUS 802.11n Wireless Network Adapter
GENERAL.DRIVER:                         r8188eu
GENERAL.DRIVER-VERSION:                 5.11.0-25-generic
GENERAL.FIRMWARE-VERSION:               --
GENERAL.HWADDR:                         <MAC 'wlx<IF from MAC [IF2]>' [IF2]>
GENERAL.MTU:                            1500
GENERAL.STATE:                          30 (disconnected)
GENERAL.REASON:                         42 (The supplicant is now available)
GENERAL.IP4-CONNECTIVITY:               1 (none)
GENERAL.IP6-CONNECTIVITY:               1 (none)
GENERAL.UDI:                            /sys/devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0/net/wlx<IF from MAC [IF2]>
GENERAL.IP-IFACE:                       --
GENERAL.IS-SOFTWARE:                    no
GENERAL.NM-MANAGED:                     yes
GENERAL.AUTOCONNECT:                    yes
GENERAL.FIRMWARE-MISSING:               no
GENERAL.NM-PLUGIN-MISSING:              no
GENERAL.PHYS-PORT-ID:                   --
GENERAL.CONNECTION:                     --
GENERAL.CON-UUID:                       --
GENERAL.CON-PATH:                       --
GENERAL.METERED:                        unknown
CAPABILITIES.CARRIER-DETECT:            no
CAPABILITIES.SPEED:                     unknown
CAPABILITIES.IS-SOFTWARE:               no
CAPABILITIES.SRIOV:                     no
INTERFACE-FLAGS.UP:                     yes
INTERFACE-FLAGS.LOWER-UP:               no
INTERFACE-FLAGS.CARRIER:                no
WIFI-PROPERTIES.WEP:                    yes
WIFI-PROPERTIES.WPA:                    yes
WIFI-PROPERTIES.WPA2:                   yes
WIFI-PROPERTIES.TKIP:                   yes
WIFI-PROPERTIES.CCMP:                   yes
WIFI-PROPERTIES.AP:                     no
WIFI-PROPERTIES.ADHOC:                  yes
WIFI-PROPERTIES.2GHZ:                   yes
WIFI-PROPERTIES.5GHZ:                   no
WIFI-PROPERTIES.MESH:                   no
WIFI-PROPERTIES.IBSS-RSN:               no
CONNECTIONS.AVAILABLE-CONNECTION-PATHS: /org/freedesktop/NetworkManager/Settings/3
CONNECTIONS.AVAILABLE-CONNECTIONS[1]:   353f4586-0b86-4c1f-86aa-40c066ce5b31 | Redmi

GENERAL.DEVICE:                         enp2s0
GENERAL.TYPE:                           ethernet
GENERAL.NM-TYPE:                        NMDeviceEthernet
GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/Devices/2
GENERAL.VENDOR:                         Realtek Semiconductor Co., Ltd.
GENERAL.PRODUCT:                        RTL810xE PCI Express Fast Ethernet controller
GENERAL.DRIVER:                         r8169
GENERAL.DRIVER-VERSION:                 5.11.0-25-generic
GENERAL.FIRMWARE-VERSION:               --
GENERAL.HWADDR:                         <MAC 'enp2s0' [IF1]>
GENERAL.MTU:                            1500
GENERAL.STATE:                          20 (unavailable)
GENERAL.REASON:                         2 (Device is now managed)
GENERAL.IP4-CONNECTIVITY:               1 (none)
GENERAL.IP6-CONNECTIVITY:               1 (none)
GENERAL.UDI:                            /sys/devices/pci0000:00/0000:00:1c.4/0000:02:00.0/net/enp2s0
GENERAL.IP-IFACE:                       --
GENERAL.IS-SOFTWARE:                    no
GENERAL.NM-MANAGED:                     yes
GENERAL.AUTOCONNECT:                    yes
GENERAL.FIRMWARE-MISSING:               no
GENERAL.NM-PLUGIN-MISSING:              no
GENERAL.PHYS-PORT-ID:                   --
GENERAL.CONNECTION:                     --
GENERAL.CON-UUID:                       --
GENERAL.CON-PATH:                       --
GENERAL.METERED:                        unknown
CAPABILITIES.CARRIER-DETECT:            yes
CAPABILITIES.SPEED:                     unknown
CAPABILITIES.IS-SOFTWARE:               no
CAPABILITIES.SRIOV:                     no
INTERFACE-FLAGS.UP:                     yes
INTERFACE-FLAGS.LOWER-UP:               no
INTERFACE-FLAGS.CARRIER:                no
WIRED-PROPERTIES.CARRIER:               off
CONNECTIONS.AVAILABLE-CONNECTION-PATHS: --

SSID       BSSID              MODE   CHAN  FREQ      RATE       SIGNAL  BARS  SECURITY  ACTIVE  IN-USE
Redmi      <MAC 'Redmi' [AC2]>  Infra  11    2462 MHz  44 Mbit/s  62      ▂▄▆_  WPA2      no
Free wifi  <MAC 'Free wifi' [AC1]>  Infra  6     2437 MHz  44 Mbit/s  23      ▂___  WPA2      no

##### NetworkManager.state ##############

[main]
NetworkingEnabled=true
WirelessEnabled=true
WWANEnabled=true

##### NetworkManager config #############

[[/etc/NetworkManager/conf.d/default-wifi-powersave-on.conf]]
[connection]
wifi.powersave = 3

[[/etc/NetworkManager/NetworkManager.conf]]
[main]
plugins=ifupdown,keyfile
[ifupdown]
managed=false
[device]
wifi.scan-rand-mac-address=no

[[/usr/lib/NetworkManager/conf.d/10-dns-resolved.conf]]
[main]
dns=systemd-resolved

[[/usr/lib/NetworkManager/conf.d/10-globally-managed-devices.conf]]
[keyfile]
unmanaged-devices=*,except:type:wifi,except:type:gsm,except:type:cdma

[[/usr/lib/NetworkManager/conf.d/20-connectivity-ubuntu.conf]]
[connectivity]
uri=http://connectivity-check.ubuntu.com/

[[/usr/lib/NetworkManager/conf.d/no-mac-addr-change.conf]]
[device-mac-addr-change-wifi]
match-device=driver:rtl8723bs,driver:rtl8189es,driver:r8188eu,driver:8188eu,driver:eagle_sdio,driver:wl
wifi.scan-rand-mac-address=no

##### NetworkManager profiles ###########

[[/etc/NetworkManager/system-connections/Sir MMR Hall - 4th Floor Root.nmconnection]] (600 root)
[connection] id=Sir MMR Hall - 4th Floor Root | type=wifi | permissions=
[wifi] mac-address-blacklist= | ssid=Sir MMR Hall - 4th Floor Root
[ipv4] method=auto
[ipv6] method=auto

[[/etc/NetworkManager/system-connections/Sir MMR Hall-Block 2.nmconnection]] (600 root)
[connection] id=Sir MMR Hall-Block 2 | type=wifi | permissions=
[wifi] mac-address-blacklist= | ssid=Sir MMR Hall-Block 2
[ipv4] method=auto
[ipv6] method=auto

[[/etc/NetworkManager/system-connections/Redmi.nmconnection]] (600 root)
[connection] id=Redmi | type=wifi | permissions=
[wifi] mac-address-blacklist= | ssid=Redmi
[ipv4] method=auto
[ipv6] method=auto

[[/etc/NetworkManager/system-connections/NETGEAR85.nmconnection]] (600 root)
[connection] id=NETGEAR85 | type=wifi | permissions=
[wifi] mac-address-blacklist= | ssid=NETGEAR85
[ipv4] method=auto
[ipv6] method=auto

##### Netplan config ####################

[/etc/netplan/01-network-manager-all.yaml]
network:
  version: 2
  renderer: NetworkManager

##### iw reg get ########################

Region: Asia/Dhaka (based on set time zone)

global
country 00: DFS-UNSET
    (2402 - 2472 @ 40), (N/A, 20), (N/A)
    (2457 - 2482 @ 20), (N/A, 20), (N/A), AUTO-BW, PASSIVE-SCAN
    (2474 - 2494 @ 20), (N/A, 20), (N/A), NO-OFDM, PASSIVE-SCAN
    (5170 - 5250 @ 80), (N/A, 20), (N/A), AUTO-BW, PASSIVE-SCAN
    (5250 - 5330 @ 80), (N/A, 20), (0 ms), DFS, AUTO-BW, PASSIVE-SCAN
    (5490 - 5730 @ 160), (N/A, 20), (0 ms), DFS, PASSIVE-SCAN
    (5735 - 5835 @ 80), (N/A, 20), (N/A), PASSIVE-SCAN
    (57240 - 63720 @ 2160), (N/A, 0), (N/A)

##### iwlist channels ###################

lo        no frequency information.

enp2s0    no frequency information.

wlx<IF from MAC [IF2]>  13 channels in total; available frequencies :
          Channel 01 : 2.412 GHz
          Channel 02 : 2.417 GHz
          Channel 03 : 2.422 GHz
          Channel 04 : 2.427 GHz
          Channel 05 : 2.432 GHz
          Channel 06 : 2.437 GHz
          Channel 07 : 2.442 GHz
          Channel 08 : 2.447 GHz
          Channel 09 : 2.452 GHz
          Channel 10 : 2.457 GHz
          Channel 11 : 2.462 GHz
          Channel 12 : 2.467 GHz
          Channel 13 : 2.472 GHz
          Current Frequency:2.412 GHz (Channel 1)

##### iwlist scan #######################

lo        Interface doesn't support scanning.

enp2s0    Interface doesn't support scanning.

Channel occupancy:

      1   APs on   Frequency:2.437 GHz (Channel 6)
      1   APs on   Frequency:2.462 GHz (Channel 11)

wlx<IF from MAC [IF2]>  Scan completed :
          Cell 01 - Address: <MAC 'Free wifi' [AC1]>
                    ESSID:"Free wifi"
                    Protocol:IEEE 802.11bgn
                    Mode:Master
                    Frequency:2.437 GHz (Channel 6)
                    Encryption key:on
                    Bit Rates:300 Mb/s
                    Extra:rsn_ie=30140100000fac040100000fac040100000fac020000
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    Quality=0/100  Signal level=23/100
          Cell 02 - Address: <MAC 'Redmi' [AC2]>
                    ESSID:"Redmi"
                    Protocol:IEEE 802.11bgn
                    Mode:Master
                    Frequency:2.462 GHz (Channel 11)
                    Encryption key:on
                    Bit Rates:108 Mb/s
                    Extra:rsn_ie=30140100000fac040100000fac040100000fac020c00
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    Quality=0/100  Signal level=69/100

##### module infos ######################

[r8188eu]
filename:       /lib/modules/5.11.0-25-generic/kernel/drivers/staging/rtl8188eu/r8188eu.ko
description:    Realtek Wireless Lan Driver
license:        GPL
depends:        cfg80211,lib80211
retpoline:      Y
intree:         Y
name:           r8188eu
vermagic:       5.11.0-25-generic SMP mod_unload modversions
parm:           rtw_ips_mode:The default IPS mode (int)
parm:           ifname:The default name to allocate for first interface (charp)
parm:           if2name:The default name to allocate for second interface (charp)
parm:           rtw_initmac:charp
parm:           rtw_channel_plan:int
parm:           rtw_channel:int
parm:           rtw_wmm_enable:int
parm:           rtw_vrtl_carrier_sense:int
parm:           rtw_vcs_type:int
parm:           rtw_ht_enable:int
parm:           rtw_cbw40_enable:int
parm:           rtw_ampdu_enable:int
parm:           rtw_rx_stbc:int
parm:           rtw_ampdu_amsdu:int
parm:           rtw_power_mgnt:int
parm:           rtw_smart_ps:int
parm:           rtw_wifi_spec:int
parm:           rtw_antdiv_cfg:int
parm:           rtw_antdiv_type:int
parm:           rtw_enusbss:int
parm:           rtw_hwpdn_mode:int
parm:           rtw_max_roaming_times:The max roaming times to try (uint)
parm:           rtw_fw_iol:FW IOL (int)
parm:           rtw_mc2u_disable:int
parm:           rtw_80211d:Enable 802.11d mechanism (int)
parm:           rtw_notch_filter:0:Disable, 1:Enable, 2:Enable only for P2P (uint)
parm:           debug:Set debug level (1-9) (default 1) (int)
parm:           monitor_enable:Enable monitor interface (default: false) (bool)

[cfg80211]
filename:       /lib/modules/5.11.0-25-generic/kernel/net/wireless/cfg80211.ko
description:    wireless configuration support
license:        GPL
depends:
retpoline:      Y
intree:         Y
name:           cfg80211
vermagic:       5.11.0-25-generic SMP mod_unload modversions
parm:           bss_entries_limit:limit to number of scan BSS entries (per wiphy, default 1000) (int)
parm:           ieee80211_regdom:IEEE 802.11 regulatory domain code (charp)
parm:           cfg80211_disable_40mhz_24ghz:Disable 40MHz support in the 2.4GHz band (bool)

##### module parameters #################

[r8188eu]
debug: 1
if2name: wlan%d
ifname: wlan%d
monitor_enable: N
rtw_80211d: 0
rtw_ampdu_amsdu: 0
rtw_ampdu_enable: 1
rtw_antdiv_cfg: 2
rtw_antdiv_type: 0
rtw_cbw40_enable: 3
rtw_channel: 1
rtw_channel_plan: 66
rtw_enusbss: 0
rtw_fw_iol: 1
rtw_ht_enable: 1
rtw_hwpdn_mode: 2
rtw_initmac: (null)
rtw_ips_mode: 1
rtw_max_roaming_times: 2
rtw_mc2u_disable: 0
rtw_notch_filter: 0
rtw_power_mgnt: 1
rtw_rx_stbc: 1
rtw_smart_ps: 2
rtw_vcs_type: 1
rtw_vrtl_carrier_sense: 2
rtw_wifi_spec: 0
rtw_wmm_enable: 1

[cfg80211]
bss_entries_limit: 1000
cfg80211_disable_40mhz_24ghz: N
ieee80211_regdom: 00

##### /etc/modules ######################

##### modprobe options ##################

[/etc/modprobe.d/amd64-microcode-blacklist.conf]
blacklist microcode

[/etc/modprobe.d/blacklist-ath_pci.conf]
blacklist ath_pci

[/etc/modprobe.d/blacklist.conf]
blacklist evbug
blacklist usbmouse
blacklist usbkbd
blacklist eepro100
blacklist de4x5
blacklist eth1394
blacklist snd_intel8x0m
blacklist snd_aw2
blacklist prism54
blacklist bcm43xx
blacklist garmin_gps
blacklist asus_acpi
blacklist snd_pcsp
blacklist pcspkr
blacklist amd76x_edac

[/etc/modprobe.d/blacklist-rare-network.conf]
alias net-pf-3 off
alias net-pf-6 off
alias net-pf-9 off
alias net-pf-11 off
alias net-pf-12 off
alias net-pf-19 off
alias net-pf-21 off
alias net-pf-36 off

[/etc/modprobe.d/intel-microcode-blacklist.conf]
blacklist microcode

[/etc/modprobe.d/iwlwifi.conf]
remove iwlwifi \
(/sbin/lsmod | grep -o -e ^iwlmvm -e ^iwldvm -e ^iwlwifi | xargs /sbin/rmmod) \
&& /sbin/modprobe -r mac80211

##### rc.local ##########################

grep: /etc/rc.local: No such file or directory

##### pm-utils ##########################

##### udev rules ########################

##### dmesg #############################

[20207.578982] Bluetooth: hci0: RTL: loading rtl_bt/rtl8723b_fw.bin
[20207.617403] Bluetooth: hci0: RTL: loading rtl_bt/rtl8723b_config.bin
[20207.617471] bluetooth hci0: Direct firmware load for rtl_bt/rtl8723b_config.bin failed with error -2
[22647.782046] r8188eu 1-1:1.0 wlx<IF from MAC [IF2]>: renamed from wlan0 (repeated 2 times)

########## wireless info END ############

And another thing is that it scans the available wifi. But it can't connect with them.
~ ➜ sudo dmesg | grep -e wlx -e r8188
[  124.081192] r8188eu: module is from the staging directory, the quality is unknown, you have been warned.
[  124.105802] usbcore: registered new interface driver r8188eu
[  124.172294] r8188eu 1-1:1.0 wlx7cc2c61b3890: renamed from wlan0
[  127.683225] IPv6: ADDRCONF(NETDEV_CHANGE): wlx7cc2c61b3890: link becomes ready
[  847.092120] r8188eu 1-1:1.0 wlx7cc2c61b3890: renamed from wlan0
[  875.921812] IPv6: ADDRCONF(NETDEV_CHANGE): wlx7cc2c61b3890: link becomes ready

Comment: "wlx7cc2c61b3890" It looks like it's working to me. Does it scan and see networks? `sudo iwlist scan`
Comment: Yes it scans. But it doesn't connect to the network. It says `Activation of network connection failed`. When I go the settings, I see no wifi adapters found.
Comment: Please provide the results of the wireless script from here: https://askubuntu.com/questions/425155/my-wireless-wifi-connection-does-not-work-what-information-is-needed-to-diagnos/425180#425180
Comment: I have added them.
Comment: What we do not see here is any attempt to connect and therefore any clue as to why it fails. Please click the Network Manager icon, select your network and attempt to connect. Supply the password if requested. Let it try and fail. Then run and post: `sudo dmesg | grep -e wlx -e r8188`
Comment: I don't know what happened but it's working now. But its strange. I didn't install any driver for it. And it took a very long time to connect to it. I don't know if this will be stable or not.
Comment: I have added those output. My USB isn't working again.
Answer: We are still unable to discover why the device, using the usual built-in kernel driver, doesn't connect as expected. I notice, however, that the driver version here is newer than the built-in driver. https://github.com/lwfinger/rtl8188eu
Let's install it and see if it helps.
With a temporary internet connection by ethernet, tethering or whatever means possible, open a terminal and do:
sudo apt update
sudo apt install git
git clone https://github.com/lwfinger/rtl8188eu.git
cd rtl8188eu
make
sudo make install
sudo -i
echo "blacklist r8188eu"  >>  /etc/modprobe.d/blacklist.conf
modprobe -r r8188eu
exit

Remove and reinsert your USB wireless and tell us if there is any improvement.
At each newer kernel version update, after the requested restart, please do:
cd rtl8188eu
make clean
git pull
make
sudo make install

Please retain these instructions and the rtl8188eu directory for that time.
Comment: It works fine now. Thanks a lot.
Comment: tried this, (same device, same linux version), device now not working at all after reinserting it. journalctl shows  'not an MTP device'
Comment: after some searching it appears this could be a problem with having secure boot enabled?
Comment: @jimsmith Yes, indeed. Please disable Secure Boot.
Comment: this line inserts it with quotes into blacklist for me on ubuntu 20: echo "blacklist r8188eu"  >>  /etc/modprobe.d/blacklist.conf just use SIMPLE quotes here echo "blacklist r8188eu"  >>  /etc/modprobe.d/blacklist.conf


Objective C - UITextFieldTextDidChangeNotification not responding to correction selection

Question: In my app, I have a simple textfield set up for the user's zip code while registering:
I am listening for changes to the textfield as so:
[self.zipCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

However, if the user begins typing and their ZIP code is shown as a suggestion above the keyboard, textFieldDidChange: is not called when the user taps that suggestion.
What control event should I be listening for to also include keyboard suggestions being selected?
Comment: I have created a new project and tried your code. `textFieldDidChange:` is called when you click on suggestion. Check your project again, maybe problem is from another place.
Answer: I have checked your code and it is working fine.
textFieldDidChange: not getting call that means something wrong. So please check.
So please check :
1) add UITextFieldDelegate in your class.
2) self.zipCode.delegate = self;
Note : Make sure if you have not created self.zipCode programmatically So you must have to check your textfield connection with storyboard.
If you need more help you can ask me :)


Socket.io configuration resulting in error 404

Question: I tried to setup socket.io into my node server in order to make a messaging function for my app but having problem getting to function despite doing test app correct.
server.js:
/* long list of requires */
var express = require('express');
var http = require('http');
var https = require('https');

var config = require('./config');

var app = express();

var server = require('http').createServer(app);
var io = require('socket.io')(server);

io.on('connection', function(socket){
    console.log('a user connected');
});

/* ssl setup */

// Create an HTTP service.
http.createServer(app).listen(8000); // opens the port
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(4433); // for the ssl

index.html
..bunch of code like bootstrap and angular.js

I tried to run the site on localhost:8000.
Despite all that, I'm getting error 404 in the console:

GET /socket.io/?EIO=3&transport=polling&t=LnM0Fd3 404

I'm not sure what went wrong with the set up process of socket.io
Answer: You're creating three servers, only one of which gets the Socket.io
// createServer No 1
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// ...

// createServer No 2
http.createServer(app).listen(8000); // opens the port
// Create an HTTPS service identical to the HTTP service.

// createServer No 3
https.createServer(options, app).listen(4433); // for the ssl

You should probably only create one server and add the socket.io call to that one.
If you create only the Port 8000 server, you could add it like this:
// (exactly your code, except for the "var server = " in front.
var server = http.createServer(app).listen(8000); // opens the port
// the next line is new:
var io = require('socket.io')(server);

notice that you'll also have to move the io.on...... part below that line.
Comment: so how would I add the socket.io to the 8000 server? like what would that look like? I need the third server for ssl as it running the port 443 when I put it on aws.
Comment: Also his client connects to http (`io.connect('http://localhost:8000')`)


Page.Request.UserHostAddress is in an invalid format

Question: Sometimes my ASP.NET application returns a value of "::1" when querying Page.Request.UserHostAddress.
I can't see any pattern as to when it returns a correct IP address vs when it returns the incorrectly formatted string. It will work for half a day and then stop working for an hour randomly. Any thoughts?
Edit:
Okay, it's the loopback address for IPv6. :) Which leads to the further question... When/why would IPv6 be used on some occasions and not others?
Answer: ::1 is the IPv6 loopback address. Equivalent to 127.0.0.1 for IPv4.
Answer: That's also a correct IP address, but it's an IPv6 address instead of an IPv4 address.
Answer: I believe you can override this by commenting out the IPv6 localhost entry your hosts file. The file is at:
C:\Windows\System32\drivers\etc\hosts
You'll want to modify the last couple of lines to look like this:
127.0.0.1       localhost
# ::1             localhost
Answer: I believe the Visual Studio Web Server defaults to IPv6, could can turn off the support in the browsers, here is a post about a bug that causes performance issues with Firefox and IPv6.
Answer: I guess you are on the server, browse your website and page from a remote machine you should see the client IPv4 address.


Windows messed my partitions, is there a way to fix them?

Question: I decided to delete a partition called "HDDRECOVERY" which I wouldnt use, of around 14 GB, I decided to do it on Windows because I was already working there so I didn't have to boot again into Ubuntu, which is my main system, I only use Windows once a week or so.
So I opened the Disk Manager in Windows and simply deleted it. Everything was going fine until then. Then I right clicked my biggest partition where I store all my media files (and have Windows installed) and asked the program to check if I could shrink it and by how much, so I could have another partition to store stuff on.
The program froze for like 10 min and then it came back up again, working.
Then I tried doing some other stuff but didn't because it wouldn't let me.
Then, I installed like 300 MB of Windows updates bc I don't log on that system very often, and also uninstalled ZoneAlarm and other software that could be slowing my machine, finally restarted the computer and all I see is a grub recovery > command prompt, I tried some stuff there but it couldn't recognize my filesystem.
Then I inserted the Ubuntu DVD and here I am, trying to figure out what to do.
image showing gparted:

That is what gparted shows,/dev/sda2 is where my biggest partition with all the media and Windows is.
/dev/sda3 is where my Linux partition should be - note:my home folder is encrypted
A couple of commands that I tried to determine what to do:
Ubuntu@Ubuntu: ~$ sudo fdisk -l
Disk /dev/sda: 640.1 GB, 640135028736 bytes
255 heads, 63 sectors/track, 77825 cylinders, total 1250263728 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x637ca5d8

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     3074047     1536000   27  Hidden NTFS WinRE
/dev/sda2         3074048  1167904767   582415360    7  HPFS/NTFS/exFAT
/dev/sda3      1167906814  1220651007    26372097    5  Extended
/dev/sda5      1208262656  1220651007     6194176   82  Linux swap / Solaris

sudo parted -l
ubuntu@ubuntu:~$ sudo parted -l
Model: ATA TOSHIBA MK6475GS (scsi)
Disk /dev/sda: 640GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type      File system  Flags
 1      1049kB  1574MB  1573MB  primary   ntfs         boot, diag
 2      1574MB  598GB   596GB   primary   ntfs
 3      598GB   625GB   27.0GB  extended
 5      619GB   625GB   6343MB  logical

Warning: Unable to open /dev/sr0 read-write (Read-only file system).  /dev/sr0
has been opened read-only.
Error: Can't have a partition outside the disk!

So I really don't know what to do here, it looks like my partition table got completely broken and also grub doesn't work, so I basically cannot boot to neither Windows or Linux, the only positive thing is that I can access my media partition with Windows from the live DVD but I work on my Ubuntu partition and I need access to it at least to restore all the files I had on my download and desktop folders.
any suggestion is welcome.
Answer: Looks like you're screwed, especially with an encrypted partition. What you can try is:
1) Copy everything as it is now, on an external USB, another DD, w/e. Copy byte-by-byte is dd if=/dev/sdX of=foo/bar, that will create an exact replica of /dev/sdX to a file named bar located in /foo (adapt those of course, like dd if=/dev/sda5 of=/media/files/backup_hdd.bkp
2) Try to recover your partition with a live-session where you'll install testdisk
3) Play with testdisk and try to restore your DD.
Bonus: you could try to recover some data with ext4undelete (if your partition was in ext4 format?) but I never managed to recover much with that tool.
Comment: Okay im going to try to copy all my data to an external drive and reformatting it, looks like its the only option, do you know if i will lose my certified windows installation? it came with the notebook.
Comment: I never mentionned formatting, I pointed out 2 tools to avoid reformatting, `testdisk` and `ext4undelete`
Comment: Hey man, finally i managed to fix the partitions AND GRUB, thanks for your advice anyways.
Answer: Finally fixed all my hard drive following these simple steps.
while on the ubuntu live CD:
1) Install TestDisk and run it, very simple.
2) Install Boot-repair and run it with recommended settings, very simple too.


What is the crash causing fault?

Question: Is the problem an out of bounds exception for i exceeds the array limit?
int initfunc(int *array, int len) {
    int i;
    for (i = 1; i <= len; i++) {
        array[i] = i;
    }
    return 0;
}

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

    int*  myarray = 0;
    initfunc(myarray, 10);
}

Comment: `for (i = 1; i <= len; i++)` - this should probably be `for (i = 1; i < len; i++)` - because arrays are zero based you want to stop 1 before the length.
Comment: I know, my assignment is to take this piece of code and find out which line is causing the crash. I know about the out of bounds exception that will occur but I don't know which line in particular is causing the crash
Answer: int initfunc(int *array, int len) {
    int i;
    for (i = 1; i <= len; i++) {
        array[i] = i;
    }
    return 0;
}

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

    int*  myarray = 0;
    initfunc(myarray, 10);
}

You never declare the size of your array in main. You need to either allocating the size either statically or dynamically. You currently have an int pointer that's pointed at nothing. And then passing that pointer in and trying to access it using:
array[i] = i;

This is the working code
int initfunc(int *array, int len) {

    array = new int[len];

    for (int i = 1; i <= len; i++) {
        array[i] = i;
    }
    return 0;
}

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

    int*  myarray = 0;
    initfunc(myarray, 10);
}

Answer: There are two issues with the code you provided.
The first issue is that you haven't actually allocated any memory for myarray. You just created a pointer, which currently points to NULL.
Create a static array
int myarray[10];

Or dynamically
int *myarray = new int[10];

The second issue is you'll most likely access outside the bounds of array in the for loop. Because arrays indices are zero based, you'll what to check i < len, rather than i <= len.
Comment: That would be true if he started his loop at 0, but it starts at 1.
Comment: It doesn't matter where he starts, `i` will end up equal to `10`, which is outside the bounds of the array.
Comment: I need to find out what line the fault will occur at? Would that be 4 or 11?
Comment: The fault will occur on line 4 because you're assigning to the `NULL` pointer.

What is the crash causing fault?


How to format/partition new hdd for Windows?

Question: I have one hdd with Ubuntu 12.04, and now I added another one for windows (because I wanna play Day Z =p).
The problem is that the windows installer says it can't partition the hdd (unknown reason).
So I want to use Ubuntu's disk utility to format/partition the hdd, but I don't know exactly what to do (for example, which filesystem does windows 7 need?). Can you help me on this?
Comment: You added a another one!!! you mean a new hdd?! or just a partition?!
Comment: @maythux a new hdd
Answer: I had two separate problems:

This particular disk (western digital caviar blue 1tb) uses a different block size, and the disk utility was adding the wrong offset at the beginning of the partition. So I installed gparted, created the partition with it (I used NTFS by the way), and it worked fine.
Windows won't install itself unless the target partition is in a disk that is set to boot up first, and it won't tell you why either.

Now I only need to add Windows to grub so I can use both OS.
Answer: Hello Chocodeveloper,
you need a partition in FAT - otherwise the Windows-Installer cannot recognize - where to put Windows into.
When you dont want to rebuild completely from new and want to keep the Ubuntu - Installation, then you need a live-CD as tool like "knoppix" - and some knowledge about commands: fdisk, cfdisk, mkdosfs (you can find explanations with e.g. man fdisk - in the shell/terminal).
Answer: To use the Ubuntu installation disc:

Insert the Ubuntu installation disc into the CD-ROM and boot the PC with it. During the boot-up process, select "Try Ubuntu without installation".
From the dash, search for Disk Utility.
Choose the HDD in you want to install windows at and then format choosing NTFS as File system.

Now restart your PC and install Windows to the new partition (HDD).
Also you can use GParted to do that.
You can install GParted by
<code>sudo apt-get install gparted
</code>
For more info about GParted, check its manual.
Comment: No its just some mess i did it before
Comment: Sidequestion: Are these all actual physical SSDs listed there?
Comment: i change the image for not making confusions for others later
Answer: Sorry for my inconvenience. Have overseen - that Windows has the spleen always to install and always to boot as first OS on the first partition or harddisk.


Irreducible polynomial over field $\mathbb{R}$

Question: How to show that $f(x)= x^4 + 2x^2 + x −1$ is irreducible over $\mathbb{R}$?
If its degree where odd, then obviously it must be reducible over $\mathbb{R}$, but here degree is even. I also do know its reducible over field with three elements. It's  irreducible over $\mathbb{Z}_2$. So by $p$-modulo test  it's irreducible over $\mathbb{Q}$. But I am getting annoyed when it comes to $\mathbb{R}$. Is there any short method to cope such problem in bond of times like within $1$ or $2$ minutes span of time.
Comment: What is your $R$? Is it the field of real numbers $\mathbb R$? In that case the polynomial cannot be irreducible over $\mathbb R$ as it has a root in $\mathbb R$.
Comment: All polynomials in $\mathbb{R}[x]$ of degree greater than 2 are reducible (Hint: Think of solutions over $\mathbb{C})$.
Comment: It is not irreducible over $\Bbb{Z}_2$. Modulo two $1$ is a root, and $x-1$ a factor. Also three is odd, so I don't understand your second and third sentences at all.
Comment: Sorry  I edited the question and discarded some part.
Comment: Actually question was $f(x) = x^3 + 2x^2 + x − 1$
Comment: It's still a polynomial of degree $3$ and as @AnotherJohnDoe said, it must be reducible in $\mathbb{R}[x]$.
Comment: @AotherJohnDoes thanks..... Is it a result to mug up........
Comment: @take008 I owe my apologies..... it's of degree 4 and corrected.
Comment: It's still a polynomial of degree $>2$, so it must be reducible in $\mathbb{R}[x]$.
Comment: Here are more hints for how to prove the proposition https://math.stackexchange.com/questions/275953/all-polynomials-in-bbb-r-can-be-factored-as-a-product-of-polynomials-over-b?rq=1
Answer: I think this problem is solved if we just consider the comment of the user AnotherJohnDoe as above. But there is a another simple view to deal with it. Now let $f(x):=x^{4}+2x^{2}+x-1$ and hence this is a real-valued continuous function on the interval $[0,1]$ with $f(0)=-1$ and $f(1)=3.$ Thus, we see on account of $0$ is between $-1$ and $3$, one has that $f(\eta)=0$ for some $\eta\in(0,1),$ where we used the Intermediate value theorem to conclude. So $f$ has a factor $(x-\eta)$ with $\eta\in(0,1).$
Comment: Sorry sir don't know I posted the wrong question and asking something else. Now I edited and now it's fine.  It's all due to hectic schedule.
Comment: @TheIotaa even if the post edited, this method still works. By the way, I edited the function $f.$