Programs & Examples On #Dbdatareader

how to refresh my datagridview after I add new data

this.tablenameTableAdapter.Fill(this.databasenameDataSet.tablename)

Win32Exception (0x80004005): The wait operation timed out

We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this

        <add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Changing that from ./ to either (local) or localhost fixed the problem.

<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

How to fill Dataset with multiple tables?

It is an old topic, but for some people it might be useful:

        DataSet someDataSet = new DataSet();
        SqlDataAdapter adapt = new SqlDataAdapter();

        using(SqlConnection connection = new SqlConnection(ConnString))
        {
            connection.Open();
            SqlCommand comm1 = new SqlCommand("SELECT * FROM whateverTable", connection);
            SqlCommand comm2g = new SqlCommand("SELECT * FROM whateverTable WHERE condition = @0", connection);
            commProcessing.Parameters.AddWithValue("@0", "value");
            someDataSet.Tables.Add("Table1");
            someDataSet.Tables.Add("Table2");

            adapt.SelectCommand = comm1;
            adapt.Fill(someDataSet.Tables["Table1"]);
            adapt.SelectCommand = comm2;
            adapt.Fill(someDataSet.Tables["Table2"]);
        }

Uploading an Excel sheet and importing the data into SQL Server database

A proposed solution will be:   


protected void Button1_Click(object sender, EventArgs e)
{
        try
        {
            CreateXMLFile();



        SqlConnection con = new SqlConnection(constring);
        con.Open();

        SqlCommand cmd = new SqlCommand("bulk_in", con);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@account_det", sw_XmlString.ToString ());

       int i= cmd.ExecuteNonQuery();
            if(i>0)
            {
                Label1.Text = "File Upload successfully";
            }
            else
            {
                Label1.Text = "File Upload unsuccessfully";
                return;

            }


        con.Close();
            }
        catch(SqlException ex)
        {
            Label1.Text = ex.Message.ToString();
        }




    }
     public void CreateXMLFile()
        {

          try
            {
                M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                fileExtn = Path.GetExtension(M_Filepath);
                strGuid = System.Guid.NewGuid().ToString();
                fNameArray = M_Filepath.Split('.');
                fName = fNameArray[0];

                xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
                 fileName =  xlRptName.Trim()  + fileExtn.Trim() ;



                 FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);



                strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
                if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
                {
                    Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
                }
               FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
               lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
               if (strFileName == "DEMO.XLS")
                {

                    strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";

                } 

                if (strFileName == "DEMO.XLSX")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";

                }

                strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";



                OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);

                mydata.TableMappings.Add("Table", "arul");
                mydata.Fill(dsExcl);
                dsExcl.DataSetName = "DocumentElement";
                intRowCnt = dsExcl.Tables[0].Rows.Count;
                intColCnt = dsExcl.Tables[0].Rows.Count;

                if(intRowCnt <1)
                {

                    Label1.Text = "No records in Excel File";
                    return;
                }
                if  (dsExcl==null)
                {

                }
                else
                    if(dsExcl.Tables[0].Rows.Count >= 1000 )
                    {

                        Label1.Text = "Excel data must be in less than 1000  ";
                    }


                for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
                {

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Name should not be empty";
                        return;

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Mobile_num should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Account_number should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }





                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Amount should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "date_a2 should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }
                }


            }
         catch 
            {

            }

         try
         {
             if(dsExcl.Tables[0].Rows.Count >0)
             {

                 dr = dsExcl.Tables[0].Rows[0];
             }
             dsExcl.Tables[0].TableName = "arul";
             dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);

         }
         catch
         {

         }
}`enter code here`

There is already an open DataReader associated with this Command which must be closed first

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

This maybe due to an incorrect table name from where you are fetching the data. Please verify the name of the table you mentioned in asmx file and the table created in database.

Set up adb on Mac OS X

If you are using zsh terminal do the following:

1) Open .zprofile file with the editor of your choice like "open -a xcode ~/.zprofile"

2) Add new PATH or Env Variable in .zprofile Save the file and quit the editor.

3) Execute your .zprofile to update your PATH: source ~/.zprofile

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

Import mysql DB with XAMPP in command LINE

I think the commands are OK, issue is with the spaces. Please observe the spaces between -u and #myusername also between -p and #mypasswd.

mysql -u #myusername -p #mypasswd MYBASE < c:\user\folderss\myscript.sql

Can also be written as:

mysql -u#myusername -p#mypasswd MYBASE < c:\user\folderss\myscript.sql

Also, you need not add -p and the time of command, if your password is blank, it will not ask you for the password. If you have password to your database, it will ask for the password.

Thanks

How to switch activity without animation in Android?

Here is a one-liner solution that works for as low as minSdkVersion 14 which you should insert in you res/styles.xml:

<item name="android:windowAnimationStyle">@null</item>

like so:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        ...
        <item name="android:windowAnimationStyle">@null</item>
    </style>
    ...
</resources>

Cheers!

How to truncate a foreign key constrained table?

While this question was asked I didn't know about it, but now if you use phpMyAdmin you can simply open the database and select the table(s) you want to truncate.

  • At the bottom there is a drop down with many options. Open it and select Empty option under the heading Delete data or table.
  • It takes you to the next page automatically where there is an option in checkbox called Enable foreign key checks. Just unselect it and press the Yes button and the selected table(s) will be truncated.

Maybe it internally runs the query suggested in user447951's answer, but it is very convenient to use from phpMyAdmin interface.

Resize image proportionally with MaxHeight and MaxWidth constraints

Like this?

public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

What exactly are DLL files, and how do they work?

DLLs (dynamic link libraries) and SLs (shared libraries, equivalent under UNIX) are just libraries of executable code which can be dynamically linked into an executable at load time.

Static libraries are inserted into an executable at compile time and are fixed from that point. They increase the size of the executable and cannot be shared.

Dynamic libraries have the following advantages:

1/ They are loaded at run time rather than compile time so they can be updated independently of the executable (all those fancy windows and dialog boxes you see in Windows come from DLLs so the look-and-feel of your application can change without you having to rewrite it).

2/ Because they're independent, the code can be shared across multiple executables - this saves memory since, if you're running 100 apps with a single DLL, there may only be one copy of the DLL in memory.

Their main disadvantage is advantage #1 - having DLLs change independent your application may cause your application to stop working or start behaving in a bizarre manner. DLL versioning tend not to be managed very well under Windows and this leads to the quaintly-named "DLL Hell".

Entity Framework : How do you refresh the model when the db changes?

I've been working on a project, not too large, that incorporates Entity Framework, about a dozen tables, and about 15 stored procs and functions. After weeks of development, attempting to refresh my tables and stored procs has yielded mixed results as far as successfully updating the model. Sometimes the changes are effective, most times they are not. Simple column changes (changing order, adding, removing, or renaming) sometimes works, most times does not. Visual Studio seems to have more problems with refreshing than just adding new. It also exhibits more problems with stored proc changes not being reflected, especially when columns are added or deleted or renamed. I have not detected any consistent behavior so i can't say "This type of change will always be updated and this type of change will not".

End result, if you want 100% effective solution, delete the EDMX file from the project, "Add new" item to project (ADO.NET Entity Data Model), and make sure you use the same name for the Model Name. This works every time.

What's a good IDE for Python on Mac OS X?

"Which editor/IDE for ...?" is a longstanding way to start a "My dog is too prettier than yours!" slapfest. Nowadays most editors from vim upwards can be used, there are multiple good alternatives, and even IDEs that started as C or Java tools work pretty well with Python and other dynamic languages.

That said, having tried a bunch of IDEs (Eclipse, NetBeans, XCode, Komodo, PyCharm, ...), I am a fan of ActiveState's Komodo IDE. I use it on Mac OS X primarily, though I've used it for years on Windows as well. The one license follows you to any platform.

Komodo is well-integrated with popular ActiveState builds of the languages themselves (esp. for Windows), works well with the fabulous (and Pythonic) Mercurial change management system (among others), and has good-to-excellent abilities for core tasks like code editing, syntax coloring, code completion, real-time syntax checking, and visual debugging. It is a little weak when it comes to pre-integrated refactoring and code-check tools (e.g. rope, pylint), but it is extensible and has a good facility for integrating external and custom tools.

Some of the things I like about Komodo go beyond the write-run-debug loop. ActiveState has long supported the development community (e.g. with free language builds, package repositories, a recipes site, ...), since before dynamic languages were the trend. The base Komodo Edit editor is free and open source, an extension of Mozilla's Firefox technologies. And Komodo is multi-lingual. I never end up doing just Python, just Perl, or just whatever. Komodo works with the core language (Python, Perl, Ruby, PHP, JavaScript) alongside supporting languages (XML, XSLT, SQL, X/HTML, CSS), non-dynamic languages (Java, C, etc.), and helpers (Makefiles, INI and config files, shell scripts, custom little languages, etc.) Others can do that too, but Komodo puts them all in once place, ready to go. It's a Swiss Army Knife for dynamic languages. (This is contra PyCharm, e.g., which is great itself, but I'd need like a half-dozen of JetBrains' individual IDEs to cover all the things I do).

Komodo IDE is by no means perfect, and editors/IDEs are the ultimate YMMV choice. But I am regularly delighted to use it, and every year I re-up my support subscription quite happily. Indeed, I just remembered! That's coming up this month. Credit card: Out. I have no commercial connection to ActiveState--just a happy customer.

Bootstrap 3 - How to load content in modal body via AJAX?

I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

The JS part:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

Finally, in the remote content, you need to put the entire structure to work.

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

What's the actual use of 'fail' in JUnit test case?

In concurrent and/or asynchronous settings, you may want to verify that certain methods (e.g. delegates, event listeners, response handlers, you name it) are not called. Mocking frameworks aside, you can call fail() in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.

For example:

final CountDownLatch latch = new CountDownLatch(1);

service.asyncCall(someParameter, new ResponseHandler<SomeType>() {
    @Override
    public void onSuccess(SomeType result) {
        assertNotNull(result);
        // Further test assertions on the result
        latch.countDown();
    }

    @Override
    public void onError(Exception e) {
        fail(exception.getMessage());
        latch.countDown();
    }
});

if ( !latch.await(5, TimeUnit.SECONDS) ) {
    fail("No response after 5s");
}

In-memory size of a Python structure

The recommendation from an earlier question on this was to use sys.getsizeof(), quoting:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
14
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

You could take this approach:

>>> import sys
>>> import decimal
>>> 
>>> d = {
...     "int": 0,
...     "float": 0.0,
...     "dict": dict(),
...     "set": set(),
...     "tuple": tuple(),
...     "list": list(),
...     "str": "a",
...     "unicode": u"a",
...     "decimal": decimal.Decimal(0),
...     "object": object(),
... }
>>> for k, v in sorted(d.iteritems()):
...     print k, sys.getsizeof(v)
...
decimal 40
dict 140
float 16
int 12
list 36
object 8
set 116
str 25
tuple 28
unicode 28

2012-09-30

python 2.7 (linux, 32-bit):

decimal 36
dict 136
float 16
int 12
list 32
object 8
set 112
str 22
tuple 24
unicode 32

python 3.3 (linux, 32-bit)

decimal 52
dict 144
float 16
int 14
list 32
object 8
set 112
str 26
tuple 24
unicode 26

2016-08-01

OSX, Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

decimal 80
dict 280
float 24
int 24
list 72
object 16
set 232
str 38
tuple 56
unicode 52

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

How to select last child element in jQuery?

For 2019 ...

jQuery 3.4.0 is deprecating :first, :last, :eq, :even, :odd, :lt, :gt, and :nth. When we remove Sizzle, we’ll replace it with a small wrapper around querySelectorAll, and it would be almost impossible to reimplement these selectors without a larger selector engine.

We think this trade-off is worth it. Keep in mind we will still support the positional methods, such as .first, .last, and .eq. Anything you can do with positional selectors, you can do with positional methods instead. They perform better anyway.

https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/

So you should be now be using .first(), .last() instead (or no jQuery).

switch case statement error: case expressions must be constant expression

I would like to mention that, I came across the same situation when I tried adding a library into my project. All of a sudden all switch statements started to show errors!

Now I tried to remove the library which I added, even then it did not work. how ever "when I cleaned the project" all the errors just went off !

How to stop creating .DS_Store on Mac?

Put following line into your ".profile" file.

Open .profile file and copy this line

find ~/ -name '.DS_Store' -delete

When you open terminal window it will automatically delete your .DS_Store file for you.

How to select all checkboxes with jQuery?

$("#select_all").change(function () {

    $('input[type="checkbox"]').prop("checked", $(this).prop("checked"));

});  

Asp.net 4.0 has not been registered

For those getting this error in after installing .NET Framework 4.6 - Read and install one of these hotfixes to resolve the issue.

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}

Sass Variable in CSS calc() function

Interpolate:

body
    height: calc(100% - #{$body_padding})

For this case, border-box would also suffice:

body
    box-sizing: border-box
    height: 100%
    padding-top: $body_padding

Using Linq to group a list of objects into a new grouped list of list of objects

Your group statement will group by group ID. For example, if you then write:

foreach (var group in groupedCustomerList)
{
    Console.WriteLine("Group {0}", group.Key);
    foreach (var user in group)
    {
        Console.WriteLine("  {0}", user.UserName);
    }
}

that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement> which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.

List of <p:ajax> events

Schedule provides various ajax behavior events to respond user actions.

  • "dateSelect" org.primefaces.event.SelectEvent When a date is selected.
  • "eventSelect" org.primefaces.event.SelectEvent When an event is selected.
  • "eventMove" org.primefaces.event.ScheduleEntryMoveEvent When an event is moved.
  • "eventResize" org.primefaces.event.ScheduleEntryResizeEvent When an event is resized.
  • "viewChange" org.primefaces.event.SelectEvent When a view is changed.
  • "toggleSelect" org.primefaces.event.ToggleSelectEvent When toggle all checkbox changes
  • "expand" org.primefaces.event.NodeExpandEvent When a node is expanded.
  • "collapse" org.primefaces.event.NodeCollapseEvent When a node is collapsed.
  • "select" org.primefaces.event.NodeSelectEvent When a node is selected.-
  • "collapse" org.primefaces.event.NodeUnselectEvent When a node is unselected
  • "expand org.primefaces.event.NodeExpandEvent When a node is expanded.
  • "unselect" org.primefaces.event.NodeUnselectEvent When a node is unselected.
  • "colResize" org.primefaces.event.ColumnResizeEvent When a column is resized
  • "page" org.primefaces.event.data.PageEvent On pagination.
  • "sort" org.primefaces.event.data.SortEvent When a column is sorted.
  • "filter" org.primefaces.event.data.FilterEvent On filtering.
  • "rowSelect" org.primefaces.event.SelectEvent When a row is being selected.
  • "rowUnselect" org.primefaces.event.UnselectEvent When a row is being unselected.
  • "rowEdit" org.primefaces.event.RowEditEvent When a row is edited.
  • "rowEditInit" org.primefaces.event.RowEditEvent When a row switches to edit mode
  • "rowEditCancel" org.primefaces.event.RowEditEvent When row edit is cancelled.
  • "colResize" org.primefaces.event.ColumnResizeEvent When a column is being selected.
  • "toggleSelect" org.primefaces.event.ToggleSelectEvent When header checkbox is toggled.
  • "colReorder" - When columns are reordered.
  • "rowSelectRadio" org.primefaces.event.SelectEvent Row selection with radio.
  • "rowSelectCheckbox" org.primefaces.event.SelectEvent Row selection with checkbox.
  • "rowUnselectCheckbox" org.primefaces.event.UnselectEvent Row unselection with checkbox.
  • "rowDblselect" org.primefaces.event.SelectEvent Row selection with double click.
  • "rowToggle" org.primefaces.event.ToggleEvent Row expand or collapse.
  • "contextMenu" org.primefaces.event.SelectEvent ContextMenu display.
  • "cellEdit" org.primefaces.event.CellEditEvent When a cell is edited.
  • "rowReorder" org.primefaces.event.ReorderEvent On row reorder.

there is more in here https://www.primefaces.org/docs/guide/primefaces_user_guide_5_0.pdf

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

How to predict input image using trained model in Keras?

That's because you're getting the numeric value associated with the class. For example if you have two classes cats and dogs, Keras will associate them numeric values 0 and 1. To get the mapping between your classes and their associated numeric value, you can use

>>> classes = train_generator.class_indices    
>>> print(classes)
    {'cats': 0, 'dogs': 1}

Now you know the mapping between your classes and indices. So now what you can do is

if classes[0][0] == 1: prediction = 'dog' else: prediction = 'cat'

How to test code dependent on environment variables using JUnit?

Decouple the Java code from the Environment variable providing a more abstract variable reader that you realize with an EnvironmentVariableReader your code to test reads from.

Then in your test you can give an different implementation of the variable reader that provides your test values.

Dependency injection can help in this.

How can I monitor the thread count of a process on linux?

Each thread in a process creates a directory under /proc/<pid>/task. Count the number of directories, and you have the number of threads.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Android API Version for application and device should match. Check if minSdkVersion and targetSdkVersion in Gradle Scripts - build.gradle (Module: app) correspond device API.

Also low versions (e.g. API 15) result in ide-emulator link failure, inspite of applicatrion and device versions match.

LEFT function in Oracle

There is no documented LEFT() function in Oracle. Find the full set here.

Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:

select * from all_objects
where object_name = 'LEFT'

But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.

If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.

Checking for an empty file in C++

pFile = fopen("file", "r");
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
if (size) {
  fseek(pFile, 0, SEEK_SET);
  do something...
}

fclose(pFile)

How to get Exception Error Code in C#

I suggest you to use Message Properte from The Exception Object Like below code

try
{
 object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{  
    //use Console.Write(e.Message); from Console Application 
    //and use MessageBox.Show(e.Message); from WindowsForm and WPF Application
}

ASP.net page without a code behind

File: logdate.aspx

<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%

StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());

tsw.Close();
%>

Done

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

the System.Web.SessionState.SessionStateBehavior enum has the following values:

  • Default
  • Disabled
  • ReadOnly
  • Required

How to tell which disk Windows Used to Boot

Try HKEY_LOCAL_MACHINE\SYSTEM\Setup\SystemPartition

How to check if a double value has no decimal part

Use number formatter to format the value, as required. Please check this.

How to add a new schema to sql server 2008?

Best way to add schema to your existing table: Right click on the specific table-->Design --> Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.

How to set up Automapper in ASP.NET Core

In my Startup.cs (Core 2.2, Automapper 8.1.1)

services.AddAutoMapper(new Type[] { typeof(DAL.MapperProfile) });            

In my data access project

namespace DAL
{
    public class MapperProfile : Profile
    {
        // place holder for AddAutoMapper (to bring in the DAL assembly)
    }
}

In my model definition

namespace DAL.Models
{
    public class PositionProfile : Profile
    {
        public PositionProfile()
        {
            CreateMap<Position, PositionDto_v1>();
        }
    }

    public class Position
    {
        ...
    }

ModalPopupExtender OK Button click event not firing?

I often use a blank label as the TargetControlID. ex. <asp:Label ID="lblghost" runat="server" Text="" />

I've seen two things that cause the click event not fire:
1. you have to remove the OKControlID (as others have mentioned)
2. If you are using field validators you should add CausesValidation="false" on the button.

Both scenarios behaved the same way for me.

Using ConfigurationManager to load config from an arbitrary location

I provided the configuration values to word hosted .nET Compoent as follows.

A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.

string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];

run a python script in terminal without the python command

Add the following line to the beginning script1.py

#!/usr/bin/env python

and then make the script executable:

$ chmod +x script1.py

If the script resides in a directory that appears in your PATH variable, you can simply type

$ script1.py

Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.

$ ./script1.py

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Environment variable substitution in sed

Actually, the simplest thing (in GNU sed, at least) is to use a different separator for the sed substitution (s) command. So, instead of s/pattern/'$mypath'/ being expanded to s/pattern//my/path/, which will of course confuse the s command, use s!pattern!'$mypath'!, which will be expanded to s!pattern!/my/path!. I’ve used the bang (!) character (or use anything you like) which avoids the usual, but-by-no-means-your-only-choice forward slash as the separator.

C# string does not contain possible?

So you can utilize short-circuiting:

bool containsBoth = compareString.Contains(firstString) && 
                    compareString.Contains(secondString);

putting datepicker() on dynamically created elements - JQuery/JQueryUI

The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;    

var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {

    _.each(repeaterWrapper, function (repeaterItem, index) {

        var jq_nodes = $(repeaterItem.addedNodes);

        jq_nodes.each(function () {

            // Date Picker
            $(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
                dateFormat: "dd MM, yy",
                showAnim: "slideDown",
                changeMonth: true,
                numberOfMonths: 1
            });

        });

    });

});

observerjQueryPlugins.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())

Remove last character from string. Swift language

Swift 4.0 (also Swift 5.0)

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

Swift 3.0

The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Or the in-place version:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

Thanks Zmey, Rob Allen!

Swift 2.0+ Way

There are a few ways to accomplish this:

Via the Foundation extension, despite not being part of the Swift library:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Using the removeRange() method (which alters the name):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

Using the dropLast() function:

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Old String.Index (Xcode 6 Beta 4 +) Way

Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

Alternatively (for a more practical, but less educational example) you can use endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

Note: I found this to be a great starting point for understanding String.Index

Old (pre-Beta 4) Way

You can simply use the substringToIndex() function, providing it one less than the length of the String:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"

Eclipse 3.5 Unable to install plugins

finally I got eclipse 3.7 working behind company firewall. I set to true "java.net.useSystemProxies" option on file "net.properties" located on "C:\Program Files\Java\jre6\lib" (this path could be different for your JRE installation). After that,set Active provider to Native on Eclipse preferences. No need to provide any proxy details anywhere, it just pick it up from system default browser settings

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

How to configure CORS in a Spring Boot + Spring Security application?

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
            }
        };
    }

Windows batch: sleep

The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

Start-Sleep -s <time to sleep>

Or something like that.

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

I think if you try:

Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub  

with a watch on a you will see it does make a difference.

Getter and Setter declaration in .NET

1st

string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.

3

string _myProperty;

public string getMyProperty()
{
    return this._myProperty;
}

public string setMyProperty(string value)
{
    this._myProperty = value;
}

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.

Python - Join with newline

The console is printing the representation, not the string itself.

If you prefix with print, you'll get what you expect.

See this question for details about the difference between a string and the string's representation. Super-simplified, the representation is what you'd type in source code to get that string.

PHP Fatal error: Call to undefined function json_decode()

The module was install but symbolic link was not in /etc/php5/cli/conf.d

YouTube Video Embedded via iframe Ignoring z-index?

Just add one of these two to the src url:

&wmode=Opaque

&wmode=transparent

<iframe id="videoIframe" width="500" height="281" src="http://www.youtube.com/embed/xxxxxx?rel=0&wmode=transparent" frameborder="0" allowfullscreen></iframe>

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

Could not load file or assembly 'System.Web.Mvc'

If your NOT using a hosting provider, and you have access to the server to install ... Then install the MVC 3 update tools, do that... it will save you hours of problems on a windows 2003 server / IIS6 machine. , I commented on this page here Nuget.Core.dll version number mismatch

How to print all session variables currently set?

this worked for me:-

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

thanks for sharing code...

Array
(    
    [__ci_last_regenerate] => 1490879962

    [user_id] => 3

    [designation_name] => Admin
    [region_name] => admin
    [territory_name] => admin
    [designation_id] => 2
    [region_id] => 1
    [territory_id] => 1
    [employee_user_id] => mosin11
)

Purpose of ESI & EDI registers?

In addition to the registers being used for mass operations, they are useful for their property of being preserved through a function call (call-preserved) in 32-bit calling convention. The ESI, EDI, EBX, EBP, ESP are call-preserved whereas EAX, ECX and EDX are not call-preserved. Call-preserved registers are respected by C library function and their values persist through the C library function calls.

Jeff Duntemann in his assembly language book has an example assembly code for printing the command line arguments. The code uses esi and edi to store counters as they will be unchanged by the C library function printf. For other registers like eax, ecx, edx, there is no guarantee of them not being used by the C library functions.

https://www.amazon.com/Assembly-Language-Step-Step-Programming/dp/0470497025

See section 12.8 How C sees Command-Line Arguments.

Note that 64-bit calling conventions are different from 32-bit calling conventions, and I am not sure if these registers are call-preserved or not.

How to get arguments with flags in Bash

I propose a simple TLDR:; example for the un-initiated.

Create a bash script called helloworld.sh

#!/bin/bash

while getopts "n:" arg; do
  case $arg in
    n) Name=$OPTARG;;
  esac
done

echo "Hello $Name!"

You can then pass an optional parameter -n when executing the script.

Execute the script as such:

$ bash helloworld.sh -n 'World'

Output

$ Hello World!

Notes

If you'd like to use multiple parameters:

  1. extend while getops "n:" arg: do with more paramaters such as while getops "n:o:p:" arg: do
  2. extend the case switch with extra variable assignments. Such as o) Option=$OPTARG and p) Parameter=$OPTARG

How to test whether a service is running from the command line

Try

sc query state= all 

for a list of services and whether they are running or not.

Xcode "Build and Archive" from command line

After updating to Xcode 8, I found that enterprise ipa generate by

/usr/bin/xcrun -sdk iphoneos PackageApplication -v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" -o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" --sign "${DEVELOPER_NAME}" --embed "${PROVISONING_PROFILE}" 

Command cannot be launched because of some signature issue. The log indicates that "warning: PackageApplication is deprecated, use xcodebuild -exportArchive instead.

So I switch to xcodebuild -exportArchive and everything went back normal.

How to implement a lock in JavaScript

Some addition to JoshRiver's answer according to my case;

var functionCallbacks = [];
    var functionLock = false;
    var getData = function (url, callback) {
                   if (functionLock) {
                        functionCallbacks.push(callback);
                   } else {
                       functionLock = true;
                       functionCallbacks.push(callback);
                        $.getJSON(url, function (data) {
                            while (functionCallbacks.length) {
                                var thisCallback = functionCallbacks.pop();
                                thisCallback(data);
                            }
                            functionLock = false;
                        });
                    }
                };

// Usage
getData("api/orders",function(data){
    barChart(data);
});
getData("api/orders",function(data){
  lineChart(data);
});

There will be just one api call and these two function will consume same result.

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

Visual Studio Code Tab Key does not insert a tab

[Edit] This answer is for MSVS (the IDE, as opposed to VS Code). It seems Microsoft and Google go out of their way to choose confusing names for new products. I'll leave this answer here for now, while I (continue to) look for the equivalent stackoverflow question about MSVS. Let me know in the comments if you think I should delete it. Or better, point me to the MSVS version of this question.

I installed MSVS 2017 recently. None of the suggestions I've seen fixed the problem. The solution I figured out works for MSVS 2015 and 2017. Add a comment below if you find that it works for other versions.

Under Tools -> Options -> Text Editor -> C/C++ -> Formatting -> General, try unchecking the "Automatically indent when I type a tab" box. It seems counter intuitive, but it fixed the problem for me. enter image description here

Display only 10 characters of a long string?

Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "

to

long text long text long ...

        function cutString(text){    
            var wordsToCut = 5;
            var wordsArray = text.split(" ");
            if(wordsArray.length>wordsToCut){
                var strShort = "";
                for(i = 0; i < wordsToCut; i++){
                    strShort += wordsArray[i] + " ";
                }   
                return strShort+"...";
            }else{
                return text;
            }
         };

Is there a REAL performance difference between INT and VARCHAR primary keys?

You make a good point that you can avoid some number of joined queries by using what's called a natural key instead of a surrogate key. Only you can assess if the benefit of this is significant in your application.

That is, you can measure the queries in your application that are the most important to be speedy, because they work with large volumes of data or they are executed very frequently. If these queries benefit from eliminating a join, and do not suffer by using a varchar primary key, then do it.

Don't use either strategy for all tables in your database. It's likely that in some cases, a natural key is better, but in other cases a surrogate key is better.

Other folks make a good point that it's rare in practice for a natural key to never change or have duplicates, so surrogate keys are usually worthwhile.

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

Number of days in particular month of particular year?

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/*
 * 44. Return the number of days in a month
 * , where month and year are given as input.
 */
public class ex44 {
    public static void dateReturn(int m,int y)
    {
        int m1=m;
        int y1=y;
        String str=" "+ m1+"-"+y1;
        System.out.println(str);
        SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");

        try {
            Date d=sd.parse(str);
            System.out.println(d);
            Calendar c=Calendar.getInstance();
            c.setTime(d);
            System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
dateReturn(2,2012);


    }

}

What is the meaning of 'No bundle URL present' in react-native?

For Ios follow the below steps,

  1. rm -rf ./node_modules
  2. npm install
  3. react-native link
  4. cd ios
  5. Pod Install
  6. cd..
  7. react-native start
  8. Build the app in XCode 1st time then you can also from VScode

How to detect a route change in Angular?

Capture route change events in the following manner...

import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';

@Component({
    selector: "my-app",
    templateUrl: "app/app.component.html",
    styleUrls: ["app/app.component.css"]
})
export class AppComponent {

    constructor(private cacheComponentObj: CacheComponent,
        private router: Router) {

        /*  Route event types
            NavigationEnd
            NavigationCancel
            NavigationError
            RoutesRecognized
        */
        router.events.forEach((event: NavigationEvent) => {

            //Before Navigation
            if (event instanceof NavigationStart) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }

            //After Navigation
            if (event instanceof NavigationEnd) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }
        });
    }
}

Missing visible-** and hidden-** in Bootstrap v4

The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.

I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.

Here is the code:

// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
  .hidden-#{$bp}-up {
    @include media-breakpoint-up($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-down {
    @include media-breakpoint-down($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-only{
    @include media-breakpoint-only($bp){
      display:none !important;
    }
  }
}

In my case, I have inserted this part in a _custom.scss file which is included at this point in the bootstrap.scss:

/*!
 * Bootstrap v4.0.0-beta (https://getbootstrap.com)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]

Defining a percentage width for a LinearLayout?

Use new percentage support library

compile 'com.android.support:percent:24.0.0'

See below example

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

For More Info Tutorial1 Tutorial2 Tutorial3

horizontal scrollbar on top and bottom of table

If you are using iscroll.js on webkit browser or mobile browser, you could try:

$('#pageWrapper>div:last-child').css('top', "0px");

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

How to make picturebox transparent?

GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;

        Image test = Properties.Resources.checker_black;
        PictureBox b = new PictureBox();
        b.Parent = GameBoard;
        b.Image = test;
        b.Width = test.Width*2;
        b.Height = test.Height*2;
        b.Location = new Point(0, 90);
        b.BackColor = Color.Transparent;
        b.BringToFront();

enter image description here

Make footer stick to bottom of page correctly

I would like to share how I solved mine using Javascript function that is called on page load. This solution positions the footer at the bottom of the screen when the height of the page content is less than the height of the screen.

_x000D_
_x000D_
function fix_layout(){_x000D_
  //increase content div length by uncommenting below line_x000D_
  //expandContent();_x000D_
  _x000D_
    var wraph = document.getElementById('wrapper').offsetHeight;_x000D_
    if(wraph<window.innerHeight){ //if content is less than screenheight_x000D_
        var headh   = document.getElementById('header').offsetHeight;_x000D_
        var conth   = document.getElementById('content').offsetHeight;_x000D_
        var footh   = document.getElementById('footer').offsetHeight;_x000D_
        //var foottop = window.innerHeight - (headh + conth + footh);_x000D_
        var foottop = window.innerHeight - (footh);_x000D_
        $("#footer").css({top:foottop+'px'});_x000D_
    }_x000D_
}_x000D_
_x000D_
function expandContent(){_x000D_
  $('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna.</p>'+_x000D_
_x000D_
'<p>Nulla facilisi. Nunc volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sit amet orci vel mauris blandit vehicula. Nullam quis enim. Integer dignissim viverra velit. Curabitur in odio. In hac habitasse platea dictumst. Ut consequat, tellus eu volutpat varius, justo orci elementum dolor, sed imperdiet nulla tellus ut diam. Vestibulum ipsum ante, malesuada quis, tempus ac, placerat sit amet, elit.</p>'+_x000D_
_x000D_
'<p>Sed eget turpis a pede tempor malesuada. Vivamus quis mi at leo pulvinar hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque aliquet lacus vitae pede. Nullam mollis dolor ac nisi. Phasellus sit amet urna. Praesent pellentesque sapien sed lacus. Donec lacinia odio in odio. In sit amet elit. Maecenas gravida interdum urna. Integer pretium, arcu vitae imperdiet facilisis, elit tellus tempor nisi, vel feugiat ante velit sit amet mauris. Vivamus arcu. Integer pharetra magna ac lacus. Aliquam vitae sapien in nibh vehicula auctor. Suspendisse leo mauris, pulvinar sed, tempor et, consequat ac, lacus. Proin velit. Nulla semper lobortis mauris. Duis urna erat, ornare et, imperdiet eu, suscipit sit amet, massa. Nulla nulla nisi, pellentesque at, egestas quis, fringilla eu, diam.</p>'+_x000D_
_x000D_
'<p>Donec semper, sem nec tristique tempus, justo neque commodo nisl, ut gravida sem tellus suscipit nunc. Aliquam erat volutpat. Ut tincidunt pretium elit. Aliquam pulvinar. Nulla cursus. Suspendisse potenti. Etiam condimentum hendrerit felis. Duis iaculis aliquam enim. Donec dignissim augue vitae orci. Curabitur luctus felis a metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In varius neque at enim. Suspendisse massa nulla, viverra in, bibendum vitae, tempor quis, lorem.</p>'+_x000D_
_x000D_
'<p>Donec dapibus orci sit amet elit. Maecenas rutrum ultrices lectus. Aliquam suscipit, lacus a iaculis adipiscing, eros orci pellentesque nisl, non pharetra dolor urna nec dolor. Integer cursus dolor vel magna. Integer ultrices feugiat sem. Proin nec nibh. Duis eu dui quis nunc sagittis lobortis. Fusce pharetra, enim ut sodales luctus, lectus arcu rhoncus purus, in fringilla augue elit vel lacus. In hac habitasse platea dictumst. Aliquam erat volutpat. Fusce iaculis elit id tellus. Ut accumsan malesuada turpis. Suspendisse potenti. Vestibulum lacus augue, lobortis mattis, laoreet in, varius at, nisi. Nunc gravida. Phasellus faucibus. In hac habitasse platea dictumst. Integer tempor lacus eget lectus. Praesent fringilla augue fringilla dui.</p>');_x000D_
}
_x000D_
/*sample CSS*/_x000D_
body{ background: black; margin: 0; }_x000D_
#header{ background: grey; }_x000D_
#content{background: yellow; }_x000D_
#footer{ background: red; position: absolute; }_x000D_
_x000D_
#header, #content, #footer{ display: inline-block; width: 100vw; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body onload="fix_layout()">_x000D_
        <div id="wrapper">_x000D_
            <div id="header" class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
                [some header elements here]_x000D_
            </div>_x000D_
            <div id="content" class="container">_x000D_
              [some content elements here]_x000D_
              _x000D_
              _x000D_
            </div>_x000D_
            <div id="footer" class="footer">_x000D_
                [some footer elements here]_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

Hope that helps.

How do I add a new class to an element dynamically?

Short answer no :)

But you could just use the same CSS for the hover like so:

a:hover, .hoverclass {
    background:red;
}

Maybe if you explain why you need the class added, there may be a better solution?

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

you have to install python-mysqldb - Python interface to MySQL

Try
sudo apt-get install python-mysqldb

Swift 3: Display Image from URL

Use this extension and download image faster.

extension UIImageView {
    public func imageFromURL(urlString: String) {

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        activityIndicator.startAnimating()
        if self.image == nil{
            self.addSubview(activityIndicator)
        }

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                activityIndicator.removeFromSuperview()
                self.image = image
            })

        }).resume()
    }
}

How to group time by hour or by 10 minutes

My solution is to use a function to create a table with the date intervals and then join this table to the data I want to group using the date interval in the table. The date interval can then be easily selected when presenting the data.

CREATE FUNCTION [dbo].[fn_MinuteIntervals]
    (
      @startDate SMALLDATETIME ,
      @endDate SMALLDATETIME ,
      @interval INT = 1
    )
RETURNS @returnDates TABLE
    (
      [date] SMALLDATETIME PRIMARY KEY NOT NULL
    )
AS
    BEGIN
        DECLARE @counter SMALLDATETIME
        SET @counter = @startDate
        WHILE @counter <= @endDate
            BEGIN
                INSERT INTO @returnDates VALUES ( @counter )
                SET @counter = DATEADD(n, @interval, @counter)
            END
        RETURN
    END

Random String Generator Returning Same String

I found this to be more helpfull, since it is an extention, and it allows you to select the source of your code.

static string
    numbers = "0123456789",
    letters = "abcdefghijklmnopqrstvwxyz",
    lettersUp = letters.ToUpper(),
    codeAll = numbers + letters + lettersUp;

static Random m_rand = new Random();

public static string GenerateCode(this int size)
{
    return size.GenerateCode(CodeGeneratorType.All);
}

public static string GenerateCode(this int size, CodeGeneratorType type)
{
    string source;

    if (type == CodeGeneratorType.All)
    {
        source = codeAll;
    }
    else
    {
        StringBuilder sourceBuilder = new StringBuilder();
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.Numbers)
            sourceBuilder.Append(numbers);
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.Letters)
            sourceBuilder.Append(letters);
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.LettersUpperCase)
            sourceBuilder.Append(lettersUp);

        source = sourceBuilder.ToString();
    }

    return size.GenerateCode(source);
}

public static string GenerateCode(this int size, string source)
{
    StringBuilder code = new StringBuilder();
    int maxIndex = source.Length-1;
    for (int i = 0; i < size; i++)
    {

        code.Append(source[Convert.ToInt32(Math.Round(m_rand.NextDouble() * maxIndex))]);
    }

    return code.ToString();
}

public enum CodeGeneratorType { Numbers = 1, Letters = 2, LettersUpperCase = 4, All = 16 };

Hope this helps.

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

Find and replace string values in list

words = [w.replace('[br]', '<br />') for w in words]

These are called List Comprehensions.

Failed to allocate memory: 8

Be sure that IntelHAXM is installed correctly. It's not enough to download and "install" it through the SDK Manager. You need to manually install it from:

android-sdk\extras\intel\Hardware_Accelerated_Execution_Manager

Also, be sure that Intel Virtual Technology is enabled in your BIOS.

Follow the guide on developer.android.com or Intel's installation instructions.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

How to format a java.sql Timestamp for displaying?

java.sql.Timestamp extends java.util.Date. You can do:

String s = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);

Or to also include time:

String s = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);

How to sort an array of objects in Java?

[Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]


public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator
  = Comparator.comparing(Employee::getName);

Arrays.sort(employees, employeeNameComparator);

assertTrue(Arrays.equals(employees, sortedEmployeesByName));

}

result

[Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

In case someone is working with Identity users in web forms, I got it working by doing so:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindById(User.Identity.GetUserId());

Creating a 3D sphere in Opengl using Visual C++

In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.

glutSolidSphere is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?

#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>

// your framework of choice here

class SolidSphere
{
protected:
    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;

public:
    SolidSphere(float radius, unsigned int rings, unsigned int sectors)
    {
        float const R = 1./(float)(rings-1);
        float const S = 1./(float)(sectors-1);
        int r, s;

        vertices.resize(rings * sectors * 3);
        normals.resize(rings * sectors * 3);
        texcoords.resize(rings * sectors * 2);
        std::vector<GLfloat>::iterator v = vertices.begin();
        std::vector<GLfloat>::iterator n = normals.begin();
        std::vector<GLfloat>::iterator t = texcoords.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                float const y = sin( -M_PI_2 + M_PI * r * R );
                float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
                float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

                *t++ = s*S;
                *t++ = r*R;

                *v++ = x * radius;
                *v++ = y * radius;
                *v++ = z * radius;

                *n++ = x;
                *n++ = y;
                *n++ = z;
        }

        indices.resize(rings * sectors * 4);
        std::vector<GLushort>::iterator i = indices.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                *i++ = r * sectors + s;
                *i++ = r * sectors + (s+1);
                *i++ = (r+1) * sectors + (s+1);
                *i++ = (r+1) * sectors + s;
        }
    }

    void draw(GLfloat x, GLfloat y, GLfloat z)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x,y,z);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
        glNormalPointer(GL_FLOAT, 0, &normals[0]);
        glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
        glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
        glPopMatrix();
    }
};

SolidSphere sphere(1, 12, 24);

void display()
{
    int const win_width  = …; // retrieve window dimensions from
    int const win_height = …; // framework of choice here
    float const win_aspect = (float)win_width / (float)win_height;

    glViewport(0, 0, win_width, win_height);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, win_aspect, 1, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

#ifdef DRAW_WIREFRAME
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    sphere.draw(0, 0, -5);

    swapBuffers();
}

int main(int argc, char *argv[])
{
    // initialize and register your framework of choice here
    return 0;
}

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

Styling the last td in a table with css

try with:

tr:last-child td:last-child{
    border:none;
    /*any other style*/
}

this will only affect the very last td element in the table, assuming is the only one (else, you'll just have to identify your table). Though, is very general, and it will adapt to the last TD if you add more content to your table. So if it is a particular case

td:nth-child(5){
    border:none;
}

should be enough.

How to calculate time elapsed in bash script?

Here's my bash implementation (with bits taken from other SO ;-)

function countTimeDiff() {
    timeA=$1 # 09:59:35
    timeB=$2 # 17:32:55

    # feeding variables by using read and splitting with IFS
    IFS=: read ah am as <<< "$timeA"
    IFS=: read bh bm bs <<< "$timeB"

    # Convert hours to minutes.
    # The 10# is there to avoid errors with leading zeros
    # by telling bash that we use base 10
    secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
    secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
    DIFF_SEC=$((secondsB - secondsA))
    echo "The difference is $DIFF_SEC seconds.";

    SEC=$(($DIFF_SEC%60))
    MIN=$((($DIFF_SEC-$SEC)%3600/60))
    HRS=$((($DIFF_SEC-$MIN*60)/3600))
    TIME_DIFF="$HRS:$MIN:$SEC";
    echo $TIME_DIFF;
}

$ countTimeDiff 2:15:55 2:55:16
The difference is 2361 seconds.
0:39:21

Not tested, may be buggy.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

How to JSON serialize sets?

Shortened version of @AnttiHaapala:

json.dumps(dict_with_sets, default=lambda x: list(x) if isinstance(x, set) else x)

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

In Python, how to check if a string only contains certain characters?

Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.

In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()

Out[17]: 0.8106249139964348

In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.

How to get date and time from server

You should set the timezone to the one of the timezones you want. let set the Indian timezone

// set default timezone
date_default_timezone_set('Asia/Kolkata');

$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];

$current_date = "$date/$month/$year == $hour:$min:$sec";

Writing an mp4 video using python opencv

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

'mp4v' returns no errors unlike 'MP4V' which is defined inside fourcc

for the error "OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'"

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

How to quietly remove a directory with content in PowerShell

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

How do I get a list of installed CPAN modules?

You can try ExtUtils-Installed, but that only looks in .packlists, so it may miss modules that people moved things into @INC by hand.

I wrote App-Module-Lister for a friend who wanted to do this as a CGI script on a non-shell web hosting account. You simple take the module file and upload it as a filename that your server will treat as a CGI script. It has no dependencies outside of the Standard Library. Use it as is or steal the code.

It outputs a list of the modules and their versions:

Tie::Cycle      1.15
Tie::IxHash     1.21
Tie::Toggle     1.07
Tie::ToObject   0.03
Time::CTime     99.062201
Time::DaysInMonth       99.1117
Time::Epoch     0.02
Time::Fuzzy     0.34
Time::JulianDay 2003.1125
Time::ParseDate 2006.0814
Time::Timezone  2006.0814

I've been meaning to add this as a feature to the cpan tool, so I'll do that too. [Time passes] And, now I have a -l switch in cpan. I have a few other things to do with it before I make a release, but it's in github. If you don't want to wait for that, you could just try the -a switch to create an autobundle, although that puts some Pod around the list.

Good luck;

Detect when an HTML5 video finishes

Here is a full example, I hope it helps =).

<!DOCTYPE html> 
<html> 
<body> 

<video id="myVideo" controls="controls">
  <source src="your_video_file.mp4" type="video/mp4">
  <source src="your_video_file.mp4" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        if(!e) { e = window.event; }
        alert("Video Finished");
    }
</script>
</body> 
</html>

Outline effect to text

Edit: text-stroke is now fairly mature and implemented in most browsers. It is easier, sharper and more precise. If your browser audience can support it, you should now use text-stroke first, instead of text-shadow.


You can and should do this with just the text-shadow effect without any offsets:

.outline {
    color: #fff;
    text-shadow: #000 0px 0px 1px;
    -webkit-font-smoothing: antialiased;
}

Why? When you offset multiple shadow effects, you’ll begin to notice ungainly, jagged corners: Shadow effect offsets result in noticeable jagged corners.


Having text-shadow effects in just one position eliminates the offsets, meaning If you feel that’s too thin and would prefer a darker outline instead, no problem — you can repeat the same effect (keeping the same position and blur), several times. Like so:

text-shadow: #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px,
             #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px;

Here’s a sample of just one effect (top), and the same effect repeated 14 times (bottom):


Sample text rendered with text-shadow

Also note: Because the lines become so thin, it’s a very good idea to turn off sub-pixel rendering using
-webkit-font-smoothing: antialiased.

fetch in git doesn't get all branches

write it from the terminal

git fetch --prune.

it works fine.

Arguments to main in C

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output

How do I break out of nested loops in Java?

Check if the inner loop is exited with an if statement, by checking the inner loop's variable. You could also create another variable such as a boolean to check if the inner loop is exited.

In this example it uses the inner loop's variable to check if it has been exited:

int i, j;
for(i = 0; i < 7; i++){

for(j = 0; j < 5; j++) {

     if (some condition) {
         // Do something and break...
         break; // Breaks out of the inner loop
     }
}
     if(j < 5){    // Checks if inner loop wasn't finished
     break;    // Breaks out of the outer loop   
     } 
}

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Generate table relationship diagram from existing schema (SQL Server)

MySQL WorkBench is free software and is developed by Oracle, you can import an SQL File or specify a database and it will generate an SQL Diagram which you can move around to make it more visually appealing. It runs on GNU/Linux and Windows and it's free and has a professional look..

Determining 32 vs 64 bit in C++

template<int> void DoMyOperationHelper();

template<> void DoMyOperationHelper<4>() 
{
  // do 32-bits operations
}

template<> void DoMyOperationHelper<8>() 
{
  // do 64-bits operations
}

// helper function just to hide clumsy syntax
inline void DoMyOperation() { DoMyOperationHelper<sizeof(size_t)>(); }

int main()
{
  // appropriate function will be selected at compile time 
  DoMyOperation(); 

  return 0;
}

What is a constant reference? (not a reference to a constant)

By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.

PHP cURL error code 60

First, we need download this certificate root certificate bundle:

https://curl.haxx.se/ca/cacert.pem

Move this file to somewhere such as to PHP folder in Wamp/Xampp folder.

Then edit your "php.ini" :

curl.cainfo ="C:/path/to/your/cacert.pem"

and

openssl.cafile="C:/path/to/your/cacert.pem"

IMPORTANT:

Be sure that you open the "php.ini" file directly by your Window Explorer. (in my case: “C:\DevPrograms\wamp64\bin\php\php5.6.25\php.ini”).

Don't use the shortcut to "php.ini" in the Wamp/Xampp icon's menu in the System Tray. This shortcut didn't work in some cases I faced.

After saving "php.ini" you don't need to "Restart All Services" in Wamp icon or close/re-open CMD.

Try with " var_dump(openssl_get_cert_locations()); " and look at line : ["ini_cafile"]=> string(40) "C:/path/to/your/cacert.pem"

Done.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

1) Start by opening up git-bash.exe in Administrator mode. (Right click the file and select "Run as Administrator", or change settings in Properties → Compatibility → Run this program as administrator.)

2) Run cd ~. It will take you to C:/Users/<Your-Username>.

3) Run vi .bashrc. This will open you up into the editor. Hit INSERT and then start entering the following info:

alias ll="ls -la" # this changes the default ll on git bash to see hidden files.
cd "C:\directory\to\your\work\path\"
ll # this shows your your directory before you even type anything.

How do I 'foreach' through a two-dimensional array?

Here's a simple extension method that returns each row as an IEnumerable<T>. This has the advantage of not using any extra memory:

public static class Array2dExt
{
    public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] array)
    {
        for (int r = array.GetLowerBound(0); r <= array.GetUpperBound(0); ++r)
            yield return row(array, r);
    }

    static IEnumerable<T> row<T>(T[,] array, int r)
    {
        for (int c = array.GetLowerBound(1); c <= array.GetUpperBound(1); ++c)
            yield return array[r, c];
    }
}

Sample usage:

static void Main()
{
    string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };

    foreach (var row in siblings.Rows())
        Console.WriteLine("{" + string.Join(", ", row) + "}");
}

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Get max and min value from array in JavaScript

Why not store it as an array of prices instead of object?

prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array

That way you can just

prices[0]; // cheapest
prices[prices.length - 1]; // most expensive

Note that you can do shift() and pop() to get min and max price respectively, but it will take off the price from the array.

Even better alternative is to use Sergei solution below, by using Math.max and min respectively.

EDIT:

I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7] as 11.5 is treated as a string, and would come before the 3.x in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:

prices.sort(function(a, b) { return a - b });

How can I specify a [DllImport] path at runtime?

As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll would be present inside myLibFolder directory inside temporary folder of the current user.

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 

Now you can continue using the DllImport statement using a const string as shown below:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Just at run time before you call the DLLFunction function (present in C++ library) add this line of code in C# code:

string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
Directory.SetCurrentDirectory(assemblyProbeDirectory);

This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory call sets the application's current working directory to the specified directory. If your myDLL.dll is present at path represented by assemblyProbeDirectory path then it will get loaded and the desired function will get called through p/invoke.

Virtualbox shared folder permissions

For the truly lazy (no typing, only totally easy copy and paste):

sudo usermod -aG vboxsf $USER

Log out and back in to make the change active.

I know it's a "me too" solution, but I am truly lazy and didn't find any other solution to appeal my innate apathy... :)

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

A function to convert null to string

Sometimes I just append an empty string to an object that might be null.

object x = null;
string y = (x + "").ToString();

This will never throw an exception and always return an empty string if null and doesn't require if then logic.

Checking for NULL pointer in C/C++

In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.

Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.

I have a preference for code that says what it means without unneeded text. if (ptr != NULL) has the same meaning as if (ptr) but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE) and that way lies madness. The C language is clear that a boolean tested by if, while or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.

How to launch Safari and open URL from iOS app

In Swift 1.2, try this:

let pth = "http://www.google.com"
    if let url = NSURL(string: pth){
        UIApplication.sharedApplication().openURL(url)

Scroll event listener javascript

For those who found this question hoping to find an answer that doesn't involve jQuery, you hook into the window "scroll" event using normal event listening. Say we want to add scroll listening to a number of CSS-selector-able elements:

// what should we do when scrolling occurs
var runOnScroll =  function(evt) {
  // not the most exciting thing, but a thing nonetheless
  console.log(evt.target);
};

// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements = Array.prototype.slice.call(elements);

// and then make each element do something on scroll
elements.forEach(function(element) {
  window.addEventListener("scroll", runOnScroll, {passive: true});
});

(Using the passive attribute to tell the browser that this event won't interfere with scrolling itself)

For bonus points, you can give the scroll handler a lock mechanism so that it doesn't run if we're already scrolling:

// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;

var runOnScroll =  function(evt) {
  if(locked) return;

  if (lastCall) clearTimeout(lastCall);
  lastCall = setTimeout(() => {
    runOnScroll(evt);
    // you do this because you want to handle the last
    // scroll event, even if it occurred while another
    // event was being processed.
  }, 200);

  // ...your code goes here...

  locked = false;
};

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How does a hash table work?

Lots of answers, but none of them are very visual, and hash tables can easily "click" when visualised.

Hash tables are often implemented as arrays of linked lists. If we imagine a table storing people's names, after a few insertions it might be laid out in memory as below, where ()-enclosed numbers are hash values of the text/name.

bucket#  bucket content / linked list

[0]      --> "sue"(780) --> null
[1]      null
[2]      --> "fred"(42) --> "bill"(9282) --> "jane"(42) --> null
[3]      --> "mary"(73) --> null
[4]      null
[5]      --> "masayuki"(75) --> "sarwar"(105) --> null
[6]      --> "margaret"(2626) --> null
[7]      null
[8]      --> "bob"(308) --> null
[9]      null

A few points:

  • each of the array entries (indices [0], [1]...) is known as a bucket, and starts a - possibly empty - linked list of values (aka elements, in this example - people's names)
  • each value (e.g. "fred" with hash 42) is linked from bucket [hash % number_of_buckets] e.g. 42 % 10 == [2]; % is the modulo operator - the remainder when divided by the number of buckets
  • multiple data values may collide at and be linked from the same bucket, most often because their hash values collide after the modulo operation (e.g. 42 % 10 == [2], and 9282 % 10 == [2]), but occasionally because the hash values are the same (e.g. "fred" and "jane" both shown with hash 42 above)
    • most hash tables handle collisions - with slightly reduced performance but no functional confusion - by comparing the full value (here text) of a value being sought or inserted to each value already in the linked list at the hashed-to bucket

Linked list lengths relate to load factor, not the number of values

If the table size grows, hash tables implemented as above tend to resize themselves (i.e. create a bigger array of buckets, create new/updated linked lists there-from, delete the old array) to keep the ratio of values to buckets (aka load factor) somewhere in the 0.5 to 1.0 range.

Hans gives the actual formula for other load factors in a comment below, but for indicative values: with load factor 1 and a cryptographic strength hash function, 1/e (~36.8%) of buckets will tend to be empty, another 1/e (~36.8%) have one element, 1/(2e) or ~18.4% two elements, 1/(3!e) about 6.1% three elements, 1/(4!e) or ~1.5% four elements, 1/(5!e) ~.3% have five etc.. - the average chain length from non-empty buckets is ~1.58 no matter how many elements are in the table (i.e. whether there are 100 elements and 100 buckets, or 100 million elements and 100 million buckets), which is why we say lookup/insert/erase are O(1) constant time operations.

How a hash table can associate keys with values

Given a hash table implementation as described above, we can imagine creating a value type such as `struct Value { string name; int age; };`, and equality comparison and hash functions that only look at the `name` field (ignoring age), and then something wonderful happens: we can store `Value` records like `{"sue", 63}` in the table, then later search for "sue" without knowing her age, find the stored value and recover or even update her age - happy birthday Sue - which interestingly doesn't change the hash value so doesn't require that we move Sue's record to another bucket.

When we do this, we're using the hash table as an associative container aka map, and the values it stores can be deemed to consist of a key (the name) and one or more other fields still termed - confusingly - the value (in my example, just the age). A hash table implementation used as a map is known as a hash map.

This contrasts with the example earlier in this answer where we stored discrete values like "sue", which you could think of as being its own key: that kind of usage is known as a hash set.

There are other ways to implement a hash table

Not all hash tables use linked lists (known as separate chaining), but most general purpose ones do, as the main alternative closed hashing (aka open addressing) - particularly with erase operations supported - has less stable performance properties with collision-prone keys/hash functions.


A few words on hash functions

Strong hashing...

A general purpose, worst-case collision-minimising hash function's job is to spray the keys around the hash table buckets effectively at random, while always generating the same hash value for the same key. Even one bit changing anywhere in the key would ideally - randomly - flip about half the bits in the resultant hash value.

This is normally orchestrated with maths too complicated for me to grok. I'll mention one easy-to-understand way - not the most scalable or cache friendly but inherently elegant (like encryption with a one-time pad!) - as I think it helps drive home the desirable qualities mentioned above. Say you were hashing 64-bit doubles - you could create 8 tables each of 256 random numbers (code below), then use each 8-bit/1-byte slice of the double's memory representation to index into a different table, XORing the random numbers you look up. With this approach, it's easy to see that a bit (in the binary digit sense) changing anywhere in the double results in a different random number being looked up in one of the tables, and a totally uncorrelated final value.

// note caveats above: cache unfriendly (SLOW) but strong hashing...
std::size_t random[8][256] = { ...random data... };
auto p = (const std::byte*)&my_double;
size_t hash = random[0][p[0]] ^
              random[1][p[1]] ^
              ... ^
              random[7][p[7]];

Weak but oft-fast hashing...

Many libraries' hashing functions pass integers through unchanged (known as a trivial or identity hash function); it's the other extreme from the strong hashing described above. An identity hash is extremely collision prone in the worst cases, but the hope is that in the fairly common case of integer keys that tend to be incrementing (perhaps with some gaps), they'll map into successive buckets leaving fewer empty than random hashing leaves (our ~36.8% at load factor 1 mentioned earlier), thereby having fewer collisions and fewer longer linked lists of colliding elements than is achieved by random mappings. It's also great to save the time it takes to generate a strong hash, and if keys are looked up in order they'll be found in buckets nearby in memory, improving cache hits. When the keys don't increment nicely, the hope is they'll be random enough they won't need a strong hash function to totally randomise their placement into buckets.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

Git add all subdirectories

Do,

git add .

while in the root of the repository. It will add everything. If you do git add *, it will only add the files * points to. The single dot refers to the directory.

If your directory or file wasn't added to git index/repo after the above command, remember to check if it's marked as ignored by git in .gitignore file.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

As described in the API of java.sql.PreparedStatement.setBinaryStream() it is available since 1.6 so it is a JDBC 4.0 API! You use a JDBC 3 Driver so this method is not available!

How do I put hint in a asp:textbox

Adding placeholder attributes from code-behind:

txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name);

Or

txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name;

Adding placeholder attributes from aspx Page

<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" />

Or

<input type="text" id="txtFilterTerm" placeholder="Filter"/>

Cloning an Object in Node.js

There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

Looks like it handles all kinds of stuff, including circular references. From the github page:

clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

in my case this fixed the problem:

sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev

as explained here

What's the difference between Thread start() and Runnable run()

t.start() is the method that the library provides for your code to call when you want a new thread.

r.run() is the method that you provide for the library to call in the new thread.


Most of these answers miss the big picture, which is that, as far as the Java language is concerned, there is no more difference between t.start() and r.run() than there is between any other two methods.

They're both just methods. They both run in the thread that called them. They both do whatever they were coded to do, and then they both return, still in the same thread, to their callers.

The biggest difference is that most of the code for t.start() is native code while, in most cases, the code for r.run() is going to be pure Java. But that's not much of a difference. Code is code. Native code is harder to find, and harder to understand when you find it, but it's still just code that tells the computer what to do.

So, what does t.start() do?

It creates a new native thread, it arranges for that thread to call t.run(), and then it tells the OS to let the new thread run. Then it returns.

And what does r.run() do?

The funny thing is, the person asking this question is the person who wrote it. r.run() does whatever you (i.e., the developer who wrote it) designed it to do.

How to put a Scanner input into an array... for example a couple of numbers

**Simple solution**
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int size;
    System.out.println("Enter the number of size of array");
    size = sc.nextInt();
    int[] a = new int[size];
    System.out.println("Enter the array element");
    //For reading the element
    for(int i=0;i<size;i++) {
        a[i] = sc.nextInt();
    }
    //For print the array element
    for(int i : a) {
        System.out.print(i+" ,");
    }
}

laravel collection to array

you can do something like this

$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();

Reference is https://laravel.com/docs/5.1/collections#method-toarray

Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array

How to Export-CSV of Active Directory Objects?

For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.

$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
    $grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
    $arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
    $aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
    $alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv

Java 8 List<V> into Map<K, V>

String array[] = {"ASDFASDFASDF","AA", "BBB", "CCCC", "DD", "EEDDDAD"};
    List<String> list = Arrays.asList(array);
    Map<Integer, String> map = list.stream()
            .collect(Collectors.toMap(s -> s.length(), s -> s, (x, y) -> {
                System.out.println("Dublicate key" + x);
                return x;
            },()-> new TreeMap<>((s1,s2)->s2.compareTo(s1))));
    System.out.println(map);

Dublicate key AA {12=ASDFASDFASDF, 7=EEDDDAD, 4=CCCC, 3=BBB, 2=AA}

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

Problems installing the devtools package

CentOS 7:

I tried solutions in this post

sudo yum -y install libcurl libcurl-devel
sudo yum -y install openssl-devel

but wasn't enough.

Checking R error in Console gave me the anwser. In my case it was lacking libxml-2.0 below (and Console printed an explanation with package name to different Linux versions and other possible R configs)

sudo yum -y install libxml2-devel

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Get the full URL in PHP

Clear code, working in all webservers (Apache, nginx, IIS, ...):

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

java.io.FileNotFoundException: the system cannot find the file specified

i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt")); to Scanner input = new Scanner(new File("./word.txt")); that should work

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

intl extension: installing php_intl.dll

The package is already included in the extensions for PHP 7.2 and above and you just need to uncomment the following line in php.ini

extension=intl

How can I disable inherited css styles?

If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.

CSS

#d1 {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
#d2 {
    background: url('br.gif') no-repeat bottom right;
}
#d3 {
    background: url('bl.gif') no-repeat bottom left;
}
#d4 {
    padding: 10px;
}

HTML

<div id="d1"><div id="d2"><div id="d3"><div id="d4">
    <div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

How do you get the path to the Laravel Storage folder?

For Laravel 5.x, use $storage_path = storage_path().

From the Laravel 5.0 docs:

storage_path

Get the fully qualified path to the storage directory.

Note also that, for Laravel 5.1 and above, per the Laravel 5.1 docs:

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$path = storage_path('app/file.txt');

Entity Framework vs LINQ to SQL

LINQ to SQL

  1. Homogeneous datasource: SQL Server
  2. Recommended for small projects only where data structure is well designed
  3. Mapping can be changed without recompilling with SqlMetal.exe
  4. .dbml (Database Markup Language)
  5. One-to-one mapping between tables and classes
  6. Supports TPH inheritance
  7. Doesn't support complex types
  8. Storage-first approach
  9. Database-centric view of a database
  10. Created by C# team
  11. Supported but not further improvements intended

Entity Framework

  1. Heterogeneus datasource: Support many data providers
  2. Recommended for all new projects except:
    • small ones (LINQ to SQL)
    • when data source is a flat file (ADO.NET)
  3. Mapping can be changed without recompilling when setting model and mapping files Metadata Artifact Process to Copy To Output Directory
  4. .edmx (Entity Data Model) which contains:
    • SSDL (Storage Schema Definition Language)
    • CSDL (Conceptual Schema Definition Language)
    • MSL (Mapping Specification Language)
  5. One-to-one, one-to-many, many-to-one mappings between tables and classes
  6. Supports inheritence:
    • TPH (Table Per Hierarchy)
    • TPT (Table Per Type)
    • TPC (Table Per Concrete Class)
  7. Supports complex types
  8. Code-first, Model-first, Storage-first approaches
  9. Application-centric view of a database
  10. Created by SQL Server team
  11. Future of Microsoft Data APIs

See also:

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

Make a link open a new window (not tab)

You can try this:-

   <a href="some.htm" target="_blank">Link Text</a>

and you can try this one also:-

  <a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>

How to upgrade safely php version in wamp server

For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/

I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.

Enjoy!

Best way to do multi-row insert in Oracle?

Here is a very useful step by step guideline for insert multi rows in Oracle:

https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html

The last step:

INSERT ALL
/* Everyone is a person, so insert all rows into people */
WHEN 1=1 THEN
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
WHEN hired_date IS NOT NULL THEN
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
  WITH names AS (
    SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
           NULL hired_date, DATE'2009-12-31' admission_date
    FROM   dual UNION ALL
    SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
           NULL hired_date, DATE'2014-01-01' admission_date
    FROM   dual UNION ALL
    SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
           NULL hired_date, DATE'2015-04-22' admission_date
    FROM   dual UNION ALL
    SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
           DATE'2015-01-01' hired_date, NULL admission_date
    FROM   dual
  )
  SELECT * FROM names

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Javascript - Regex to validate date format

Format, days, months and year:

var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;

How do I run a spring boot executable jar in a Production environment?

Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.

For Maven, just include the following in your pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>

For Gradle add the following snippet to your build.gradle:

springBoot {
    executable = true
}

The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d or use a systemd script.

init.d example:

$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp

This allows you to start, stop and restart your application like:

$/etc/init.d/yourapp start|stop|restart

Or use a systemd script:

[Unit]
Description=yourapp
After=syslog.target

[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

More information at the following links:

How can I display the users profile pic using the facebook graph api?

to get different sizes, you can use the type parameter:

You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

Why does the 260 character path length limit exist in Windows?

The question is why does the limitation still exist. Surely modern Windows can increase the side of MAX_PATH to allow longer paths. Why has the limitation not been removed?

  • The reason it cannot be removed is that Windows promised it would never change.

Through API contract, Windows has guaranteed all applications that the standard file APIs will never return a path longer than 260 characters.

Consider the following correct code:

WIN32_FIND_DATA findData;

FindFirstFile("C:\Contoso\*", ref findData);

Windows guaranteed my program that it would populate my WIN32_FIND_DATA structure:

WIN32_FIND_DATA {
   DWORD    dwFileAttributes;
   FILETIME ftCreationTime;
   FILETIME ftLastAccessTime;
   FILETIME ftLastWriteTime;
   //...
   TCHAR    cFileName[MAX_PATH];
   //..
}

My application didn't declare the value of the constant MAX_PATH, the Windows API did. My application used that defined value.

My structure is correctly defined, and only allocates 592 bytes total. That means that i am only able to receive a filename that is less than 260 characters. Windows promised me that if i wrote my application correctly, my application would continue to work in the future.

If Windows were to allow filenames longer than 260 characters then my existing application (which used the correct API correctly) would fail.

For anyone calling for Microsoft to change the MAX_PATH constant, they first need to ensure that no existing application fails. For example, i still own and use a Windows application that was written to run on Windows 3.11. It still runs on 64-bit Windows 10. That is what backwards compatibility gets you.

Microsoft did create a way to use the full 32,768 path names; but they had to create a new API contract to do it. For one, you should use the Shell API to enumerate files (as not all files exist on a hard drive or network share).

But they also have to not break existing user applications. The vast majority of applications do not use the shell api for file work. Everyone just calls FindFirstFile/FindNextFile and calls it a day.

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

How to prevent page scrolling when scrolling a DIV element?

I needed to add this event to multiple elements that might have a scrollbar. For the cases where no scrollbar was present, the main scrollbar didn't work as it should. So i made a small change to @Šime code as follows:

$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
    if($(this).prop('scrollHeight') > $(this).height())
    {
        var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail;

        this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
        e.preventDefault();
    }       
});

Now, only elements with a scrollbar will prevent the main scroll from begin stopped.

Can't load IA 32-bit .dll on a AMD 64-bit platform

Had same issue in win64bit and JVM 64bit

Was solved by uploading dll to system32

How to center a table of the screen (vertically and horizontally)

This fixes the box dead center on the screen:

HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

View Results

http://jsfiddle.net/bukov/wJ7dY/168/

Generating random, unique values C#

Depending on what you are really after you can do something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SO14473321
{
    class Program
    {
        static void Main()
        {
            UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10));
            for (int i = 0; i < 10; i++)
            {
                Console.Write("{0} ",u.Next());
            }
        }
    }

    class UniqueRandom
    {
        private readonly List<int> _currentList;
        private readonly Random _random = new Random();

        public UniqueRandom(IEnumerable<int> seed)
        {
            _currentList = new List<int>(seed);
        }

        public int Next()
        {
            if (_currentList.Count == 0)
            {
                throw new ApplicationException("No more numbers");
            }

            int i = _random.Next(_currentList.Count);
            int result = _currentList[i];
            _currentList.RemoveAt(i);
            return result;
        }
    }
}

Return Result from Select Query in stored procedure to a List

SqlConnection con = new SqlConnection("Data Source=DShp;Initial Catalog=abc;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("data", con);

da.SelectCommand.CommandType= CommandType.StoredProcedure;

DataSet ds=new DataSet();

da.Fill(ds, "data");
GridView1.DataSource = ds.Tables["data"];
GridView1.DataBind();

Could not install packages due to an EnvironmentError: [Errno 13]

On Mac, there is no 3.7 directory or the directory 3.7 is owned by root. So, I removed that directory, create a new directory by current user, and move it there. Then installation finishes without error.

sudo rm -rf /Library/Python/3.7
mkdir 3.7
sudo mv 3.7 /Library/Python
ll /Library/Python/
pip3 install numpy

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

hs=$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
       .call(hs,null,{ handle: $('.ui-slider-handle', hs), value: h });

Don't forget to set value by hs.slider('option', 'value',h); before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that h is index/position (not value) in case you are using html select.

Python: Assign Value if None Exists

IfLoop's answer (and MatToufoutu's comment) work great for standalone variables, but I wanted to provide an answer for anyone trying to do something similar for individual entries in lists, tuples, or dictionaries.

Dictionaries

existing_dict = {"spam": 1, "eggs": 2}
existing_dict["foo"] = existing_dict["foo"] if "foo" in existing_dict else 3

Returns {"spam": 1, "eggs": 2, "foo": 3}

Lists

existing_list = ["spam","eggs"]
existing_list = existing_list if len(existing_list)==3 else 
                existing_list + ["foo"]

Returns ["spam", "eggs", "foo"]

Tuples

existing_tuple = ("spam","eggs")
existing_tuple = existing_tuple if len(existing_tuple)==3 else 
                 existing_tuple + ("foo",)

Returns ("spam", "eggs", "foo")

(Don't forget the comma in ("foo",) to define a "single" tuple.)

The lists and tuples solution will be more complicated if you want to do more than just check for length and append to the end. Nonetheless, this gives a flavor of what you can do.

How do you show animated GIFs on a Windows Form (c#)

It doesn't when you start a long operation behind, because everything STOPS since you'Re in the same thread.

How to list the contents of a package using YUM?

rpm -ql [packageName]

Example

# rpm -ql php-fpm

/etc/php-fpm.conf
/etc/php-fpm.d
/etc/php-fpm.d/www.conf
/etc/sysconfig/php-fpm
...
/run/php-fpm
/usr/lib/systemd/system/php-fpm.service
/usr/sbin/php-fpm
/usr/share/doc/php-fpm-5.6.0
/usr/share/man/man8/php-fpm.8.gz
...
/var/lib/php/sessions
/var/log/php-fpm

No need to install yum-utils, or to know the location of the rpm file.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

According to Beau Smith from this subject: How do I remove the blue styling of telephone numbers on iPhone/iOS?

You should apply "tel:" in the href attribute of your link like this:

<a href="tel:5551231234">555 123-1234</a>

It will remove any additionnal style and DOM to the phone number string.

Using pip behind a proxy with CNTLM

Set up invironment variable in Advanced System Settings. In Command prompt it should behave like this :

C:\Windows\system32>echo %http_proxy%

http://username:passowrd@proxy:port

C:\Windows\system32>echo %https_proxy%

http://username:password@proxy:port

Later , Simply pip install whatEver should work.

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

Get HTML source of WebElement in Selenium WebDriver using Python

You can read the innerHTML attribute to get the source of the content of the element or outerHTML for the source with the current element.

Python:

element.get_attribute('innerHTML')

Java:

elem.getAttribute("innerHTML");

C#:

element.GetAttribute("innerHTML");

Ruby:

element.attribute("innerHTML")

JavaScript:

element.getAttribute('innerHTML');

PHP:

$element->getAttribute('innerHTML');

It was tested and worked with the ChromeDriver.

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

How to Toggle a div's visibility by using a button click

You can easily do it with jquery toggle. By this toggle or slideToggle you will get nice animation and effect also.

_x000D_
_x000D_
$(function(){_x000D_
  $("#details_content").css("display","none");_x000D_
  $(".myButton").click(function(){_x000D_
    $("#details_content").slideToggle(1000);_x000D_
  })  _x000D_
})
_x000D_
<div class="main">_x000D_
    <h2 class="myButton" style="cursor:pointer">Click Me</h2>_x000D_
    <div id="details_content">_x000D_
        <h1> Lorem Ipsum is simply dummy text</h1> _x000D_
        <p>    of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Saving image from PHP URL

$img_file='http://www.somedomain.com/someimage.jpg'

$img_file=file_get_contents($img_file);

$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';

$file_handler=fopen($file_loc,'w');

if(fwrite($file_handler,$img_file)==false){
    echo 'error';
}

fclose($file_handler);

Increase permgen space

For tomcat you can increase the permGem space by using

 -XX:MaxPermSize=128m

For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat

Check to see if python script is running

ps ax | grep processName

if yor debug script in pycharm always exit

pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Efficient way to remove keys with empty strings from a dict

I read all replies in this thread and some referred also to this thread: Remove empty dicts in nested dictionary with recursive function

I originally used solution here and it worked great:

Attempt 1: Too Hot (not performant or future-proof):

def scrub_dict(d):
    if type(d) is dict:
        return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
    else:
        return d

But some performance and compatibility concerns were raised in Python 2.7 world:

  1. use isinstance instead of type
  2. unroll the list comp into for loop for efficiency
  3. use python3 safe items instead of iteritems

Attempt 2: Too Cold (Lacks Memoization):

def scrub_dict(d):
    new_dict = {}
    for k, v in d.items():
        if isinstance(v,dict):
            v = scrub_dict(v)
        if not v in (u'', None, {}):
            new_dict[k] = v
    return new_dict

DOH! This is not recursive and not at all memoizant.

Attempt 3: Just Right (so far):

def scrub_dict(d):
    new_dict = {}
    for k, v in d.items():
        if isinstance(v,dict):
            v = scrub_dict(v)
        if not v in (u'', None, {}):
            new_dict[k] = v
    return new_dict

AngularJS sorting rows by table header

I think this working CodePen example that I created will show you exactly how to do what you want.

The template:

<section ng-app="app" ng-controller="MainCtrl">
  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>
          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
        <td>{{emp.firstName}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.age}}</td>
      </tr>
    </tbody>
  </table>
</section>

The JavaScript code:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'firstName';
  $scope.reverseSort = false;

  $scope.data = {
    employees: [{
      firstName: 'John',
      lastName: 'Doe',
      age: 30
    },{
      firstName: 'Frank',
      lastName: 'Burns',
      age: 54
    },{
      firstName: 'Sue',
      lastName: 'Banter',
      age: 21
    }]
  };
});

Error while trying to run project: Unable to start program. Cannot find the file specified

For me it was the virus scanner not liking the fact I have in my exe filename multiple periods.

i.e

project.class.console.exe <- won't run

console.exe <- will run

Hope it helps.

How can I see the raw SQL queries Django is running?

To get result query from django to database(with correct parameter substitution) you could use this function:

from django.db import connection

def print_database_query_formatted(query):
    sql, params = query.sql_with_params()
    cursor = connection.cursor()
    cursor.execute('EXPLAIN ' + sql, params)
    db_query = cursor.db.ops.last_executed_query(cursor, sql, params).replace('EXPLAIN ', '')

    parts = '{}'.format(db_query).split('FROM')
    print(parts[0])
    if len(parts) > 1:
        parts = parts[1].split('WHERE')
        print('FROM{}'.format(parts[0]))
        if len(parts) > 1:
            parts = parts[1].split('ORDER BY')
            print('WHERE{}'.format(parts[0]))
            if len(parts) > 1:
                print('ORDER BY{}'.format(parts[1]))

# USAGE
users = User.objects.filter(email='[email protected]').order_by('-id')
print_database_query_formatted(users.query)

Output example

SELECT "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."deleted", "users_user"."id", "users_user"."phone", "users_user"."username", "users_user"."userlastname", "users_user"."email", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."latitude", "users_user"."longitude", "users_user"."point"::bytea, "users_user"."default_search_radius", "users_user"."notifications", "users_user"."admin_theme", "users_user"."address", "users_user"."is_notify_when_buildings_in_radius", "users_user"."active_campaign_id", "users_user"."is_unsubscribed", "users_user"."sf_contact_id", "users_user"."is_agree_terms_of_service", "users_user"."is_facebook_signup", "users_user"."type_signup" 
FROM "users_user" 
WHERE "users_user"."email" = '[email protected]' 
ORDER BY "users_user"."id" DESC

It based on this ticket comment: https://code.djangoproject.com/ticket/17741#comment:4

How do I get the computer name in .NET

Try this one.

public static string GetFQDN()
{
    string domainName = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
    string hostName = Dns.GetHostName();
    string fqdn;
    if (!hostName.Contains(domainName))
        fqdn = hostName + "." +domainName;
    else
        fqdn = hostName;

    return fqdn;
}

How to detect iPhone 5 (widescreen devices)?

This has been answered a hundred times but this solution worked the best for me and helped address the issue when new devices are introduced and I don't have a size defined.

Swift 5 Helper:

extension UIScreen {
    func phoneSizeInInches() -> CGFloat {
        switch (self.nativeBounds.size.height) {
        case 960, 480:
            return 3.5  //iPhone 4
        case 1136:
            return 4    //iPhone 5
        case 1334:
            return 4.7  //iPhone 6
        case 2208:
            return 5.5  //iPhone 6 Plus
        case 2436:
            return 5.8  //iPhone X
        case 1792:
            return 6.1  //iPhone XR
        case 2688:
            return 6.5  //iPhone XS Max
        default:
            let scale = self.scale
            let ppi = scale * 163
            let width = self.bounds.size.width * scale
            let height = self.bounds.size.height * scale
            let horizontal = width / ppi, vertical = height / ppi
            let diagonal = sqrt(pow(horizontal, 2) + pow(vertical, 2))
            return diagonal
        }
    }
}

This is because it's easy to memorize a phone's inch sizes, like, "5.5 inch" or "4.7 inch" device but difficult to remember the exact pixel sizes.

if UIScreen.main.phoneSizeInInches() == 4 {
  //do something with only 4 inch iPhones
}

This also gives you the opportunity to do something like this:

if UIScreen.main.phoneSizeInInches() < 5.5 {
  //do something on all iPhones smaller than the plus
}

The default: tries to uses the screen size and scale to try and calculate the diagonal inches. This is in case some new device size appears, it will try its best to determine and code, such as the last example, should still work.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I recently started receiving this error inside of my internal NLog failures log, with Visual Studio 2013. The solution has been using NLog v2.0.0 for several years. Within the last month, our main log stopped working. To fix this I updated NLog to the newest version (v3.1.0) via Nuget. The security exception is now gone and ALL of the log messages are appearing again.

Additionally, I later found another Security exception and was able to fix it by following the instructions on this post in another thread.

Can I dynamically add HTML within a div tag from C# on load event?

You could reference controls inside the master page this way:

void Page_Load()
{
    ContentPlaceHolder cph;
    Literal lit;

    cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");

    if (cph != null) {
        lit = (Literal) cph.FindControl("Literal1");
        if (lit != null) {
            lit.Text = "Some <b>HTML</b>";
        }
    }

}

In this example you have to put a Literal control in your ContentPlaceholder.

Bootstrap 3 Gutter Size

@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:

.row {
    margin-left: -7px;
    margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
    padding-left: 7px;
    padding-right: 7px;
}
.container {
    padding-left: 14px;
    padding-right: 14px;
}

This leaves a 14px gutter and outside margin in all places.

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

What's the difference between the Window.Loaded and Window.ContentRendered events

If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.

Open:

  1. SourceInitiated
  2. Activated
  3. Loaded
  4. ContentRendered

Close:

  1. Closing
  2. Deactivated
  3. Closed

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

How to use the PI constant in C++

#include <cmath>
const long double pi = acos(-1.L);

How to vertically align label and input in Bootstrap 3?

I'm sure you've found your answer by now, but for those who are still looking for an answer:

When input-lg is used, margins mismatch unless you use form-group-lg in addition to form-group class. Its example is in docs:

<form class="form-horizontal">
  <div class="form-group form-group-lg">
    <label class="col-sm-2 control-label" for="formGroupInputLarge">Large label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputLarge" placeholder="Large input">
    </div>
  </div>
  <div class="form-group form-group-sm">
    <label class="col-sm-2 control-label" for="formGroupInputSmall">Small label</label>
    <div class="col-sm-10">
      <input class="form-control" type="text" id="formGroupInputSmall" placeholder="Small input">
    </div>
  </div>
</form>

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

How to change app default theme to a different app theme?

Actually you should define your styles in res/values/styles.xml. I guess now you've got the following configuration:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black". You must be lacking android namespace before style tag.

You can read more about styles and themes here.

Filtering a pyspark dataframe using isin by exclusion

It looks like the ~ gives the functionality that I need, but I am yet to find any appropriate documentation on it.

df.filter(~col('bar').isin(['a','b'])).show()



+---+---+
| id|bar|
+---+---+
|  4|  c|
|  5|  d|
+---+---+

How to set default font family in React Native?

With React-Native 0.56, the above method of changing Text.prototype.render does not work anymore, so you have to use your own component, which can be done in one line!

MyText.js

export default props => <Text {...props} style={[{fontFamily: 'Helvetica'}, props.style]}>{props.children}</Text>

AnotherComponent.js

import Text from './MyText';

...
<Text>This will show in default font.</Text>
...

Show compose SMS view in Android

In Android , we have the class SmsManager which manages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault().

SmsManager Javadoc

Check the following link to get the sample code for sending SMS:

article on sending and receiving SMS messages in Android