Programs & Examples On #Type declaration

How do I remove the last comma from a string using PHP?

It is better to use implode for that purpose. Implode is easy and awesome:

    $array = ['name1', 'name2', 'name3'];
    $str = implode(', ', $array);

Output:

    name1, name2, name3

How to get the string size in bytes?

I like to use:

(strlen(string) + 1 ) * sizeof(char)

This will give you the buffer size in bytes. You can use this with snprintf() may help:

const char* message = "%s, World!";
char* string = (char*)malloc((strlen(message)+1))*sizeof(char));
snprintf(string, (strlen(message)+1))*sizeof(char), message, "Hello");

Cheers! Function: size_t strlen (const char *s)

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

Is there a simple way to use button to navigate page as a link does in angularjs

Your ngClick is correct; you just need the right service. $location is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:

$location.path( '/new-page.html' );

The $location service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.

You could also do something more flexible with a directive if you so chose:

.directive( 'goClick', function ( $location ) {
  return function ( scope, element, attrs ) {
    var path;

    attrs.$observe( 'goClick', function (val) {
      path = val;
    });

    element.bind( 'click', function () {
      scope.$apply( function () {
        $location.path( path );
      });
    });
  };
});

And then you could use it on anything:

<button go-click="/go/to/this">Click!</button>

There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

Disabling Chrome cache for website development

I was in a situation that the browser load the cache data from disk even I checked it disabled cache (I was using Chrome). All my CSS and JS were loading from server but not the web page. This was happening on both my local and Production.

To fixed it, I need to put an extra param in my URL to force the browser to get the web page from server, even the controller did not need it.

I was using ASP.Net, so here is my example :

//Controller function
public ActionResult Index()
    {
        return View();
    }
//Link
@Html.Action("Index", "Home", new { ts = DateTime.Now.Ticks.ToString()})

The result is, it will generate a link like: http://www.myweb.com/Home/Index?ts=636558555408282209

This is my situation and solution. Hopefully it could help somebody.

Reset Entity-Framework Migrations

In Entity Framework Core.

  1. Remove all files from migrations folder.

  2. Type in console

    dotnet ef database drop -f -v
    dotnet ef migrations add Initial
    dotnet ef database update
    

UPD: Do that only if you don't care about your current persisted data. If you do, use Greg Gum's answer

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

Why can't I reference my class library?

If both projects are contained within the same solution, it will be more apropiate if you add the reference for the project you need, not its compiled dll.

enter image description here

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

Determine the line of code that causes a segmentation fault?

Also, you can give valgrind a try: if you install valgrind and run

valgrind --leak-check=full <program>

then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.

Open new Terminal Tab from command line (Mac OS X)

If you are using iTerm this command will open a new tab:

osascript -e 'tell application "iTerm" to activate' -e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'

How to get the date from the DatePicker widget in Android?

The DatePicker class has methods for getting the month, year, day of month. Or you can use an OnDateChangedListener.

Opening a .ipynb.txt File

These steps work for me:

  • Open the file in Jupyter Notebook.
  • Rename the file: Click File > Rename, change the name so that it ends with '.ipynb' behind, and click OK
  • Close the file.
  • From the Jupyter Notebook's directory tree, click the filename to open it.

Traverse all the Nodes of a JSON Object Tree with JavaScript

I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

Examples of usage: You should always have root object which is the first parameter of each method:

var rootObj = {
  name: 'rootObject',
  children: [
    {
      'name': 'child1',
       children: [ ... ]
    },
    {
       'name': 'child2',
       children: [ ... ]
    }
  ]
};

The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

And you can:

  1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
  2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
  3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
  4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

replacementObj is used as the last parameter in two last methods:

  1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
  2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}

How do I evenly add space between a label and the input field regardless of length of text?

You can always use the 'pre' tag inside the label, and just enter the blank spaces in it, So you can always add the same or different number of spaces you require

<form>
<label>First Name :<pre>Here just enter number of spaces you want to use(I mean using spacebar to enter blank spaces)</pre>
<input type="text"></label>
<label>Last Name :<pre>Now Enter enter number of spaces to match above number of 
spaces</pre>
<input type="text"></label>
</form>

Hope you like my answer, It's a simple and efficient hack

Eliminating NAs from a ggplot

Just an update to the answer of @rafa.pereira. Since ggplot2 is part of tidyverse, it makes sense to use the convenient tidyverse functions to get rid of NAs.

library(tidyverse)
airquality %>% 
        drop_na(Ozone) %>%
        ggplot(aes(x = Ozone))+
        geom_bar(stat="bin")

Note that you can also use drop_na() without columns specification; then all the rows with NAs in any column will be removed.

Multiple conditions in a C 'for' loop

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to && or ||.

Get a CSS value with JavaScript

The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:

function getStyleRuleValue(style, selector) {
  let value = null;
  for (let i = 0; i < document.styleSheets.length; i++) {
    const mysheet = document.styleSheets[i];
    const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    for (let j = 0; j < myrules.length; j++) {
      if (myrules[j].selectorText && 
          myrules[j].selectorText.toLowerCase() === selector) {
        value =  myrules[j].style[style];
      }
    }
  }
  return value;
}  

However, this simple search will not work in case of complex selectors.

Get google map link with latitude/longitude

The suggested answer no longer works after 2014. Now you have to use Google Maps Embed API for loading into iframe.

Here is the link for the question and solution.

If you are using Angular like me you won't be able to load the google maps in iframe because of XSS security issue. For that you need to sanitise the URL with Pipe from angular.

Here is the link to do so.

All the suggestions are tested and works 100% as of today.

handling dbnull data in vb.net

Microsoft came up with DBNull in .NET 1.0 to represent database NULL. However, it's a pain in the behind to use because you can't create a strongly-typed variable to store a genuine value or null. Microsoft sort of solved that problem in .NET 2.0 with nullable types. However, you are still stuck with large chunks of API that use DBNull, and they can't be changed.

Just a suggestion, but what I normally do is this:

  1. All variables containing data read from or written to a database should be able to handle null values. For value types, this means making them Nullable(Of T). For reference types (String and Byte()), this means allowing the value to be Nothing.
  2. Write a set of functions to convert back and forth between "object that may contain DBNull" and "nullable .NET variable". Wrap all calls to DBNull-style APIs in these functions, then pretend that DBNull doesn't exist.

hasOwnProperty in JavaScript

hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")

With block equivalent in C#?

About 3/4 down the page in the "Using Objects" section:

VB:

With hero 
  .Name = "SpamMan" 
  .PowerLevel = 3 
End With 

C#:

//No "With" construct
hero.Name = "SpamMan"; 
hero.PowerLevel = 3; 

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Setting the environment variable NODE_PATH to point to your global node_modules folder.

In Windows 7 or higher the path is something like %AppData%\npm\node_modules while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/ but it depends on user configuration.

The command npm config get prefix could help finding out which is the correct path.

In UNIX systems you can accomplish it with the following command:

export NODE_PATH=`npm config get prefix`/lib/node_modules/

How can I detect if a selector returns null?

My preference, and I have no idea why this isn't already in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Used like this:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

Or, as it looks in CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

What is the difference between a 'closure' and a 'lambda'?

It's as simple as this: lambda is a language construct, i.e. simply syntax for anonymous functions; a closure is a technique to implement it -- or any first-class functions, for that matter, named or anonymous.

More precisely, a closure is how a first-class function is represented at runtime, as a pair of its "code" and an environment "closing" over all the non-local variables used in that code. This way, those variables are still accessible even when the outer scopes where they originate have already been exited.

Unfortunately, there are many languages out there that do not support functions as first-class values, or only support them in crippled form. So people often use the term "closure" to distinguish "the real thing".

Using HTML data-attribute to set CSS background-image url

How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).

/*
  Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";

@each $i in $social {
  [data-social="#{$i}"] {
    background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
    background-size: cover; // Only seems to work if placed below background property
  }
}

Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.

Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

When we use the slf4j api jar, we need any of the logger implementations like log4j. On my system, we have the complete set and it works fine.

1. slf4j-api-1.5.6.jar
2. slf4j-log4j12-1.5.6.jar
3. **log4j-1.2.15.jar**

How to dynamically build a JSON object with Python?

You build the object before encoding it to a JSON string:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.

Remove part of string after "."

We can pretend they are filenames and remove extensions:

tools::file_path_sans_ext(a)
# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

How to convert unix timestamp to calendar date moment.js

Moment.js provides Localized formats which can be used.

Here is an example:

const moment = require('moment');

const timestamp = 1519482900000;
const formatted = moment(timestamp).format('L');

console.log(formatted); // "02/24/2018"

IOException: The process cannot access the file 'file path' because it is being used by another process

The error indicates another process is trying to access the file. Maybe you or someone else has it open while you are attempting to write to it. "Read" or "Copy" usually doesn't cause this, but writing to it or calling delete on it would.

There are some basic things to avoid this, as other answers have mentioned:

  1. In FileStream operations, place it in a using block with a FileShare.ReadWrite mode of access.

    For example:

    using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
    {
    }
    

    Note that FileAccess.ReadWrite is not possible if you use FileMode.Append.

  2. I ran across this issue when I was using an input stream to do a File.SaveAs when the file was in use. In my case I found, I didn't actually need to save it back to the file system at all, so I ended up just removing that, but I probably could've tried creating a FileStream in a using statement with FileAccess.ReadWrite, much like the code above.

  3. Saving your data as a different file and going back to delete the old one when it is found to be no longer in use, then renaming the one that saved successfully to the name of the original one is an option. How you test for the file being in use is accomplished through the

    List<Process> lstProcs = ProcessHandler.WhoIsLocking(file);
    

    line in my code below, and could be done in a Windows service, on a loop, if you have a particular file you want to watch and delete regularly when you want to replace it. If you don't always have the same file, a text file or database table could be updated that the service always checks for file names, and then performs that check for processes & subsequently performs the process kills and deletion on it, as I describe in the next option. Note that you'll need an account user name and password that has Admin privileges on the given computer, of course, to perform the deletion and ending of processes.

  4. When you don't know if a file will be in use when you are trying to save it, you can close all processes that could be using it, like Word, if it's a Word document, ahead of the save.

    If it is local, you can do this:

    ProcessHandler.localProcessKill("winword.exe");
    

    If it is remote, you can do this:

    ProcessHandler.remoteProcessKill(computerName, txtUserName, txtPassword, "winword.exe");
    

    where txtUserName is in the form of DOMAIN\user.

  5. Let's say you don't know the process name that is locking the file. Then, you can do this:

    List<Process> lstProcs = new List<Process>();
    lstProcs = ProcessHandler.WhoIsLocking(file);
    
    foreach (Process p in lstProcs)
    {
        if (p.MachineName == ".")
            ProcessHandler.localProcessKill(p.ProcessName);
        else
            ProcessHandler.remoteProcessKill(p.MachineName, txtUserName, txtPassword, p.ProcessName);
    }
    

    Note that file must be the UNC path: \\computer\share\yourdoc.docx in order for the Process to figure out what computer it's on and p.MachineName to be valid.

    Below is the class these functions use, which requires adding a reference to System.Management. The code was originally written by Eric J.:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Management;
    
    namespace MyProject
    {
        public static class ProcessHandler
        {
            [StructLayout(LayoutKind.Sequential)]
            struct RM_UNIQUE_PROCESS
            {
                public int dwProcessId;
                public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
            }
    
            const int RmRebootReasonNone = 0;
            const int CCH_RM_MAX_APP_NAME = 255;
            const int CCH_RM_MAX_SVC_NAME = 63;
    
            enum RM_APP_TYPE
            {
                RmUnknownApp = 0,
                RmMainWindow = 1,
                RmOtherWindow = 2,
                RmService = 3,
                RmExplorer = 4,
                RmConsole = 5,
                RmCritical = 1000
            }
    
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            struct RM_PROCESS_INFO
            {
                public RM_UNIQUE_PROCESS Process;
    
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
                public string strAppName;
    
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
                public string strServiceShortName;
    
                public RM_APP_TYPE ApplicationType;
                public uint AppStatus;
                public uint TSSessionId;
                [MarshalAs(UnmanagedType.Bool)]
                public bool bRestartable;
            }
    
            [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
            static extern int RmRegisterResources(uint pSessionHandle,
                                                UInt32 nFiles,
                                                string[] rgsFilenames,
                                                UInt32 nApplications,
                                                [In] RM_UNIQUE_PROCESS[] rgApplications,
                                                UInt32 nServices,
                                                string[] rgsServiceNames);
    
            [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
            static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
    
            [DllImport("rstrtmgr.dll")]
            static extern int RmEndSession(uint pSessionHandle);
    
            [DllImport("rstrtmgr.dll")]
            static extern int RmGetList(uint dwSessionHandle,
                                        out uint pnProcInfoNeeded,
                                        ref uint pnProcInfo,
                                        [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                        ref uint lpdwRebootReasons);
    
            /// <summary>
            /// Find out what process(es) have a lock on the specified file.
            /// </summary>
            /// <param name="path">Path of the file.</param>
            /// <returns>Processes locking the file</returns>
            /// <remarks>See also:
            /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
            /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
            /// 
            /// </remarks>
            static public List<Process> WhoIsLocking(string path)
            {
                uint handle;
                string key = Guid.NewGuid().ToString();
                List<Process> processes = new List<Process>();
    
                int res = RmStartSession(out handle, 0, key);
                if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");
    
                try
                {
                    const int ERROR_MORE_DATA = 234;
                    uint pnProcInfoNeeded = 0,
                        pnProcInfo = 0,
                        lpdwRebootReasons = RmRebootReasonNone;
    
                    string[] resources = new string[] { path }; // Just checking on one resource.
    
                    res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
    
                    if (res != 0) throw new Exception("Could not register resource.");
    
                    //Note: there's a race condition here -- the first call to RmGetList() returns
                    //      the total number of process. However, when we call RmGetList() again to get
                    //      the actual processes this number may have increased.
                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
    
                    if (res == ERROR_MORE_DATA)
                    {
                        // Create an array to store the process results
                        RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                        pnProcInfo = pnProcInfoNeeded;
    
                        // Get the list
                        res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                        if (res == 0)
                        {
                            processes = new List<Process>((int)pnProcInfo);
    
                            // Enumerate all of the results and add them to the 
                            // list to be returned
                            for (int i = 0; i < pnProcInfo; i++)
                            {
                                try
                                {
                                    processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                                }
                                // catch the error -- in case the process is no longer running
                                catch (ArgumentException) { }
                            }
                        }
                        else throw new Exception("Could not list processes locking resource.");
                    }
                    else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
                }
                finally
                {
                    RmEndSession(handle);
                }
    
                return processes;
            }
    
            public static void remoteProcessKill(string computerName, string userName, string pword, string processName)
            {
                var connectoptions = new ConnectionOptions();
                connectoptions.Username = userName;
                connectoptions.Password = pword;
    
                ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);
    
                // WMI query
                var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
    
                using (var searcher = new ManagementObjectSearcher(scope, query))
                {
                    foreach (ManagementObject process in searcher.Get()) 
                    {
                        process.InvokeMethod("Terminate", null);
                        process.Dispose();
                    }
                }            
            }
    
            public static void localProcessKill(string processName)
            {
                foreach (Process p in Process.GetProcessesByName(processName))
                {
                    p.Kill();
                }
            }
    
            [DllImport("kernel32.dll")]
            public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);
    
            public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
    
        }
    }
    

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Examples of good gotos in C or C++

Here is an example of a good goto:

// No Code

MySQL DISTINCT on a GROUP_CONCAT()

You can simply add DISTINCT in front.

SELECT GROUP_CONCAT(DISTINCT categories SEPARATOR ' ')

if you want to sort,

SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ')

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

JavaScript OR (||) variable assignment explanation

There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

How to change the color of progressbar in C# .NET 3.5?

I found this can be done by drawing a rectangle inside the progress bar, and to set its width according to the progress's current value. I also added support for right to left progress. This way you don't need to use the Image, and since Rectnalge.Inflate isn't called the drawn rectangle is smaller.

public partial class CFProgressBar : ProgressBar
{
    public CFProgressBar()
    {
        InitializeComponent();
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent) { }

    protected override void OnPaint(PaintEventArgs e)
    {
        double scaleFactor = (((double)Value - (double)Minimum) / ((double)Maximum - (double)Minimum));
        int currentWidth = (int)((double)Width * scaleFactor);
        Rectangle rect;
        if (this.RightToLeftLayout)
        {
            int currentX = Width - currentWidth;
            rect = new Rectangle(currentX, 0, this.Width, this.Height);
        }
        else
            rect = new Rectangle(0, 0, currentWidth, this.Height);

        if (rect.Width != 0)
        {
            SolidBrush sBrush = new SolidBrush(ForeColor);
            e.Graphics.FillRectangle(sBrush, rect);
        }
    }
}

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Well I got this Issue too in my few websites and all i need to do is customize the content fetler for HTML entites. before that more i delete them more i got, so just change you html fiter or parsing function for the page and it worked. Its mainly due to HTML editors in most of CMSs. the way they store parse the data caused this issue (In My case). May this would Help in your case too

MongoDB or CouchDB - fit for production?

The BBC and meebo.com use CouchDB in production and so does one of my clients. Here is a list of other people using Couch: CouchDB in the wild

The major challenge is to know how to organize your documents and stop thinking in terms of relational data.

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

How to compare two tables column by column in oracle

Used full outer join -- But it will not show - if its not matched -

SQL> desc aaa - its a table Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> desc aaav -its a view Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> select a.column_name,b.column_name from dba_tab_columns a full outer join dba_tab_columns b on a.column_name=b.column_name where a.TABLE_NAME='AAA' and B.table_name='AAAV';

COLUMN_NAME COLUMN_NAME


A1 A1 B1 B1

Could not load file or assembly for Oracle.DataAccess in .NET

I switched over to the managed ODP.NET assemblies from Oracle. I also had to purge all the files from the IIS web apps that were using the older assemblies. Now I don't get any conflicts regarding 32 vs 64 bit versions when I debug in IIS Express vs IIS. See the following article.

An Easy Drive to .NET

How can I count the number of matches for a regex?

This should work for matches that might overlap:

public static void main(String[] args) {
    String input = "aaaaaaaa";
    String regex = "aa";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    int from = 0;
    int count = 0;
    while(matcher.find(from)) {
        count++;
        from = matcher.start() + 1;
    }
    System.out.println(count);
}

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

For me on windows it was Ctrl+¡ , indent line. It adds a tab at the beggining of each line.

Importing large sql file to MySql via command line

Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...

First open MySQL:

mysql -u root -p

Then, You just need to do following :

mysql>use your_db

mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format:

ALTER [ COLUMN ] column { SET | DROP } NOT NULL

What is a regex to match ONLY an empty string?

I believe Python is the only widely used language that doesn't support \z in this way (yet). There are Python bindings for Russ Cox / Google's super fast re2 C++ library that can be "dropped in" as a replacement for the bundled re.

There's an excellent discussion (with workarounds) for this at Perl Compatible Regular Expression (PCRE) in Python, here on SO.

python
Python 2.7.11 (default, Jan 16 2016, 01:14:05) 
[GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> import re2 as re
>>> 
>>> re.match(r'\A\z', "")
<re2.Match object at 0x805d97170>

@tchrist's answer is worth the read.

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

How do I install the yaml package for Python?

Type in pip3 install yaml or like Connor pip3 install strictyaml

How to get IP address of the device from code?

kotlin minimalist version

fun getIpv4HostAddress(): String {
    NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
        networkInterface.inetAddresses?.toList()?.find {
            !it.isLoopbackAddress && it is Inet4Address
        }?.let { return it.hostAddress }
    }
    return ""
}

Find all paths between two graph nodes

I've implemented a version where it basically finds all possible paths from one node to the other, but it doesn't count any possible 'cycles' (the graph I'm using is cyclical). So basically, no one node will appear twice within the same path. And if the graph were acyclical, then I suppose you could say it seems to find all the possible paths between the two nodes. It seems to be working just fine, and for my graph size of ~150, it runs almost instantly on my machine, though I'm sure the running time must be something like exponential and so it'll start to get slow quickly as the graph gets bigger.

Here is some Java code that demonstrates what I'd implemented. I'm sure there must be more efficient or elegant ways to do it as well.

Stack connectionPath = new Stack();
List<Stack> connectionPaths = new ArrayList<>();
// Push to connectionsPath the object that would be passed as the parameter 'node' into the method below
void findAllPaths(Object node, Object targetNode) {
    for (Object nextNode : nextNodes(node)) {
       if (nextNode.equals(targetNode)) {
           Stack temp = new Stack();
           for (Object node1 : connectionPath)
               temp.add(node1);
           connectionPaths.add(temp);
       } else if (!connectionPath.contains(nextNode)) {
           connectionPath.push(nextNode);
           findAllPaths(nextNode, targetNode);
           connectionPath.pop();
        }
    }
}

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

PHP - check if variable is undefined

To check is variable is set you need to use isset function.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

this code will print:

isset true
isset false

read more in https://php.net/manual/en/function.isset.php

Get GPS location from the web browser

Observable

/*
  function geo_success(position) {
    do_something(position.coords.latitude, position.coords.longitude);
  }

  function geo_error() {
    alert("Sorry, no position available.");
  }

  var geo_options = {
    enableHighAccuracy: true,
    maximumAge        : 30000,
    timeout           : 27000
  };

  var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
  */
  getLocation(): Observable<Position> {
    return Observable.create((observer) => {
      const watchID = navigator.geolocation.watchPosition((position: Position) => {
        observer.next(position);
      });
      return () => {
        navigator.geolocation.clearWatch(watchID);
      };
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

Java method to sum any number of ints

import java.util.Scanner;

public class SumAll {
    public static void sumAll(int arr[]) {//initialize method return sum
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.println("Sum is : " + sum);
    }

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);//create scanner object 
        System.out.print("How many # you want to add : ");
        num = input.nextInt();//return num from keyboard
        int[] arr2 = new int[num];
        for (int i = 0; i < arr2.length; i++) {
            System.out.print("Enter Num" + (i + 1) + ": ");
            arr2[i] = input.nextInt();
        }
        sumAll(arr2);
    }

}

Array as session variable

Yes, you can put arrays in sessions, example:

$_SESSION['name_here'] = $your_array;

Now you can use the $_SESSION['name_here'] on any page you want but make sure that you put the session_start() line before using any session functions, so you code should look something like this:

 session_start();
 $_SESSION['name_here'] = $your_array;

Possible Example:

 session_start();
 $_SESSION['name_here'] = $_POST;

Now you can get field values on any page like this:

 echo $_SESSION['name_here']['field_name'];

As for the second part of your question, the session variables remain there unless you assign different array data:

 $_SESSION['name_here'] = $your_array;

Session life time is set into php.ini file.

More Info Here

Adjust icon size of Floating action button (fab)

Make this entry in dimens

<!--Floating action button-->
<dimen name="design_fab_image_size" tools:override="true">36dp</dimen>

Here 36dp is icon size on floating point button. This will set 36dp size for all icons for floating action button.

Updates As Per Comments

If you want to set icon size to particular Floating Action Button just go with Floating action button attributes like app:fabSize="normal" and android:scaleType="center".

  <!--app:fabSize decides size of floating action button You can use normal, auto or mini as per need-->
  app:fabSize="normal" 

  <!--android:scaleType decides how the icon drawable will be scaled on Floating action button. You can use center(to show scr image as original), fitXY, centerCrop, fitCenter, fitEnd, fitStart, centerInside.-->
  android:scaleType="center"

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

How to escape single quotes in MySQL

If you are using PHP, just use the addslashes() function.

PHP Manual addslashes

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

How do I convert a String to a BigInteger?

If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")

In this case you could do it like this way:

public  BigInteger stringToBigInteger(String string){
    byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
    StringBuilder asciiString = new StringBuilder();
    for(byte asciiCharacter:asciiCharacters){
        asciiString.append(Byte.toString(asciiCharacter));
    }
    BigInteger bigInteger = new BigInteger(asciiString.toString());
    return bigInteger;
}

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

Change a Django form field to a hidden field

You can just use css :

_x000D_
_x000D_
#id_fieldname, label[for="id_fieldname"] {_x000D_
  position: absolute;_x000D_
  display: none_x000D_
}
_x000D_
_x000D_
_x000D_

This will make the field and its label invisible.

How to pass parameter to function using in addEventListener?

When you use addEventListener, this will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this from within your function:

productLineSelect.addEventListener('change',getSelection,false);

function getSelection(){
    var value = sel.options[this.selectedIndex].value;
    alert(value);
}

If you want to pass in some other argument from the context where you call addEventListener, you can use a closure, like this:

productLineSelect.addEventListener('change', function(){ 
    // pass in `this` (the element), and someOtherVar
    getSelection(this, someOtherVar); 
},false);

function getSelection(sel, someOtherVar){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
    alert(someOtherVar);
}

How to escape special characters of a string with single backslashes

This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",
                                          "]":  r"\]",
                                          "\\": r"\\",
                                          "^":  r"\^",
                                          "$":  r"\$",
                                          "*":  r"\*",
                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import re
escaped = re.escape(a_string)

How to close TCP and UDP ports via windows command line

Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.

Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic.

So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it.

There is at least one program (CurrPorts) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.

Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

your nested for loop

 for(int j = 0; j < array2.size(); i++){

is infinite as j will always equal to zero, on the other hand, i will be increased at will in this loop. You get OutOfBoundaryException when i is larger than plusArray.size()

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

Convert Unix timestamp to a date string

Other examples here are difficult to remember. At its simplest:

date -r 1305712800

count number of rows in a data frame in R based on group

The count() function in plyr does what you want:

library(plyr)

count(mydf, "MONTH-YEAR")

Get the height and width of the browser viewport without scrollbars using jquery?

The script $(window).height() does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:

For html5: <!doctype html>

for transitional html4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Probably the default doctype assumed by some browsers is such, that $(window).height() takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.

Moreover, if you are doing a script, you can invent tests to help programmers in your libraries, let me invent a couple:

$(document).ready(function() {
    if(typeof $=='undefined') {
        alert("Error, you haven't called JQuery library");
    }
    if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
        alert("ERROR, check your doctype, the calculated heights are not what you might expect");
    } 
});

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

Display a loading bar before the entire page is loaded

HTML

<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>

<div class="content">
I would like to display a loading bar before the entire page is loaded. 
</div>

JAVASCRIPT

$(function() {
    $(".preload").fadeOut(2000, function() {
        $(".content").fadeIn(1000);        
    });
});?

CSS

.content {display:none;}
.preload { 
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
}
?

DEMO

How to get the element clicked (for the whole document)?

You need to use the event.target which is the element which originally triggered the event. The this in your example code refers to document.

In jQuery, that's...

$(document).click(function(event) {
    var text = $(event.target).text();
});

Without jQuery...

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement,
        text = target.textContent || target.innerText;   
}, false);

Also, ensure if you need to support < IE9 that you use attachEvent() instead of addEventListener().

Kotlin Ternary Conditional Operator

For myself I use following extension functions:

fun T?.or<T>(default: T): T = if (this == null) default else this 
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this

First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.

Usage:

1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }

Personally for me code above more readable than if construction inlining

How to navigate back to the last cursor position in Visual Studio Code?

This will be different for each OS, based on the information at https://code.visualstudio.com/docs/customization/keybindings

Go Back: workbench.action.navigateBack Go Forward: workbench.action.navigateForward

Linux Go Back: Ctrl+Alt+-
Go Forward: Ctrl+Shift+-

OSX ^- / ^?-

Windows Alt+ ? / ?

How do I syntax check a Bash script without running it?

Time changes everything. Here is a web site which provide online syntax checking for shell script.

I found it is very powerful detecting common errors.

enter image description here

About ShellCheck

ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.

Haskell source code is available on GitHub!

Concatenating Files And Insert New Line In Between Files

You can do:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

Make sure the file finalfile.txt does not exist before you run the above command.

If you are allowed to use awk you can do:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt

makefile:4: *** missing separator. Stop

This is because tab is replaced by spaces. To disable this feature go to

gedit->edit->preferences->editor

and remove check for

"replace tab with space"

Setting a property by reflection with a string value

I will answer this with a general answer. Usually these answers not working with guids. Here is a working version with guids too.

var stringVal="6e3ba183-89d9-e611-80c2-00155dcfb231"; // guid value as string to set
var prop = obj.GetType().GetProperty("FooGuidProperty"); // property to be setted
var propType = prop.PropertyType;

// var will be type of guid here
var valWithRealType = TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal); 

vagrant login as root by default

This is useful:

sudo passwd root

for anyone who's been caught out by the need to set a root password in vagrant first

Show MySQL host via SQL Command

Maybe

mysql> show processlist;

How to generate UL Li list from string array using jquery?

Even better approach using array's join method

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var list = '<ul class="myList"><li class="ui-menu-item" role="menuitem"><a class="ui-all" tabindex="-1">' + countries.join('</a></li><li>') + '</li></ul>';

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Linux/Unix command to determine if process is running?

The simpliest way is to use ps and grep:

command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
    echo "Command is running"
else
    echo "Command is not running"
fi

If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.

Example: show me if any java process with supplied argument:

-Djava.util.logging.config.file=logging.properties

is running

ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l

Prepare for Segue in Swift

This seems to be due to a problem in the UITableViewController subclass template. It comes with a version of the prepareForSegue method that would require you to unwrap the segue.

Replace your current prepareForSegue function with:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "Load View") {
        // pass data to next view
    }
}

This version implicitly unwraps the parameters, so you should be fine.

How to set Google Chrome in WebDriver

Aditya,

As you said in your last comment that you are trying to access chrome of some other system so based on that you should keep your chrome driver in that system itself.

for example: if you are trying to access linux chrome from windows then you need to put your chrome driver in linux at some place and give permission as 777 and use below code at your windows system.

System.setProperty("webdriver.chrome.driver", "\\var\\www\\Jar\\chromedriver");
Capability= DesiredCapabilities.chrome();   Capability.setPlatform(org.openqa.selenium.Platform.ANY);
browser=new RemoteWebDriver(new URL(nodeURL),Capability);

This is working code of my system.

Getting list of items inside div using Selenium Webdriver

alternatively, you can try writing a specific element:

    //label[1] is the first element.
    el =  await driver.findElement(By.xpath("//div[@class=\"facetContainerDiv\"]/div/label[1]/input")));
    await el.click();

More information can be found here: https://www.browserstack.com/guide/locators-in-selenium

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Show git diff on file in staging area

You can show changes that have been staged with the --cached flag:

$ git diff --cached

In more recent versions of git, you can also use the --staged flag (--staged is a synonym for --cached):

$ git diff --staged

In C#, what's the difference between \n and \r\n?

\n is the line break used by Unix(-like) systems, \r\n is used by windows. This has nothing to do with C#.

Can we instantiate an abstract class directly?

No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.

Replace spaces with dashes and make all letters lower-case

Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

In Python, how do I determine if an object is iterable?

Duck typing

try:
    iterator = iter(theElement)
except TypeError:
    # not iterable
else:
    # iterable

# for obj in iterator:
#     pass

Type checking

Use the Abstract Base Classes. They need at least Python 2.6 and work only for new-style classes.

from collections.abc import Iterable   # import directly from collections for Python < 3.3

if isinstance(theElement, Iterable):
    # iterable
else:
    # not iterable

However, iter() is a bit more reliable as described by the documentation:

Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).

What is the effect of encoding an image in base64?

It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.

Java 6 Unsupported major.minor version 51.0

I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more

Step to Do this

1-sudo vim /etc/environment

2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)

3-Run echo $JAVA_HOME will give the JAVA_HOME set value

4-Now mvn -version will give the desired output

Apache Maven 3.3.9

Maven home: /usr/share/maven

Java version: 1.7.0_45, vendor: Oracle Corporation

Java home: /opt/dev/jdk1.7.0_45/jre

Default locale: en_US, platform encoding: UTF-8

OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"

How to make a DIV not wrap?

The following worked for me without floating (I modified your example a little for visual effect):

_x000D_
_x000D_
.container_x000D_
{_x000D_
    white-space: nowrap; /*Prevents Wrapping*/_x000D_
    _x000D_
    width: 300px;_x000D_
    height: 120px;_x000D_
    overflow-x: scroll;_x000D_
    overflow-y: hidden;_x000D_
}_x000D_
.slide_x000D_
{_x000D_
    display: inline-block; /*Display inline and maintain block characteristics.*/_x000D_
    vertical-align: top; /*Makes sure all the divs are correctly aligned.*/_x000D_
    white-space: normal; /*Prevents child elements from inheriting nowrap.*/_x000D_
    _x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: red;_x000D_
    margin: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
   <div class="slide">something something something</div>_x000D_
   <div class="slide">something something something</div>_x000D_
   <div class="slide">something something something</div>_x000D_
   <div class="slide">something something something</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The divs may be separated by spaces. If you don't want this, use margin-right: -4px; instead of margin: 5px; for .slide (it's ugly but it's a tricky problem to deal with).

How do I get the name of the active user via the command line in OS X?

Via here

Checking the owner of /dev/console seems to work well.

stat -f "%Su" /dev/console

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

mean() warning: argument is not numeric or logical: returning NA

If you just want to know the mean, you can use

summary(results)

It will give you more information than expected.

ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.

Furthermore, If you want to get mean values of each column, you can simply use the method below.

mean(results$columnName, na.rm = TRUE)

That will return mean value. (you have to change 'columnName' to your variable name

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to generate gcc debug symbol outside the build target?

Check out the "--only-keep-debug" option of the strip command.

From the link:

The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.

How do I check if an object's type is a particular subclass in C++?

You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.

I am assuming you have a situation like this:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}

If this is what you have, then try to do something like this:

class Base
{
  virtual void bar() = 0;
};

class A : public Base
{
  void bar() {/* do X */}
};

class B : public Base
{
  void bar() {/* do Y */}
};

void foo(Base *p)
{
  p->bar();
}

Edit: Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates Liskov substitution principle. Uncle Bob calls this an "anathema to Object Oriented Design".

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

iText - add content to existing PDF file

iText has more than one way of doing this. The PdfStamper class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.

// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();

// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1); 

// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);

// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp")); 

document.close();

This will read in a PDF from templateInputStream and write it out to outputStream. These might be file streams or memory streams or whatever suits your application.

Padding characters in printf

If you are ending the pad characters at some fixed column number, then you can overpad and cut to length:

# Previously defined:
# PROC_NAME
# PROC_STATUS

PAD="--------------------------------------------------"
LINE=$(printf "%s %s" "$PROC_NAME" "$PAD" | cut -c 1-${#PAD})
printf "%s %s\n" "$LINE" "$PROC_STATUS"

Copy directory contents into a directory with python

from subprocess import call

def cp_dir(source, target):
    call(['cp', '-a', source, target]) # Linux

cp_dir('/a/b/c/', '/x/y/z/')

It works for me. Basically, it executes shell command cp.

Convert month int to month name

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

SVG fill color transparency / alpha?

fill="#044B9466"

This is an RGBA color in hex notation inside the SVG, defined with hex values. This is valid, but not all programs can display it properly...

You can find the browser support for this syntax here: https://caniuse.com/#feat=css-rrggbbaa

As of August 2017: RGBA fill colors will display properly on Mozilla Firefox (54), Apple Safari (10.1) and Mac OS X Finder's "Quick View". However Google Chrome did not support this syntax until version 62 (was previously supported from version 54 with the Experimental Platform Features flag enabled).

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

How to create a number picker dialog?

Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:

Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);

What, exactly, is needed for "margin: 0 auto;" to work?

It's perhaps interesting that you do not have to specify width for a <button> element to make it work - just make sure it has display:block : http://jsfiddle.net/muhuyttr/

How to clear the entire array?

Find a better use for myself: I usually test if a variant is empty, and all of the above methods fail with the test. I found that you can actually set a variant to empty:

Dim aTable As Variant
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
If IsEmpty(aTable) Then
    'This is False
End If
ReDim aTable(2)
aTable = Empty
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
Erase aTable
If IsEmpty(aTable) Then
    'This is False
End If

this way i get the behaviour i want

Github: error cloning my private repository

On git for Windows you can also reinstall and select the Windows native certificate validation method (OpenSSL is default). This will skip the OpenSSL verification and instead use the Windows native one, which doesn't require maintaining a separate tool (OpenSSL) and certificates.

Worked perfectly for me :)

Return index of greatest value in an array

If you create a copy of the array and sort it descending, the first element of the copy will be the largest. Than you can find its index in the original array.

var sorted = [...arr].sort((a,b) => b - a)
arr.indexOf(sorted[0])

Time complexity is O(n) for the copy, O(n*log(n)) for sorting and O(n) for the indexOf.

If you need to do it faster, Ry's answer is O(n).

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

Are (non-void) self-closing tags valid in HTML5?

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

Difference between \w and \b regular expression meta characters

\w matches a word character. \b is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)

\w matches a, b, c, d, e, and f in "abc def"
\b matches the (zero-width) position before a, after c, before d, and after f in "abc def"

See: http://www.regular-expressions.info/reference.html/

How to get date, month, year in jQuery UI datepicker?

Hi you can try viewing this jsFiddle.

I used this code:

var day = $(this).datepicker('getDate').getDate();  
var month = $(this).datepicker('getDate').getMonth();  
var year = $(this).datepicker('getDate').getYear();  

I hope this helps.

How can I throw a general exception in Java?

It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

java.math.BigInteger cannot be cast to java.lang.Long

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

Query query = session
             .createSQLQuery("SELECT COUNT(*) as count
                             FROM SpyPath 
                             WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) 
                             GROUP BY DATE(time) 
                             ORDER BY time;")
             .addScalar("count", LongType.INSTANCE);

Then

List<Long> result = query.list(); //No ClassCastException here  

Related link

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

In my case the pod update didn't update the project somehow. So I had to do it by myself, adding the MBProgressHud to OtherLinkerFlags.

enter image description here

In Tkinter is there any way to make a widget not visible?

I know this is a couple of years late, but this is the 3rd Google response now for "Tkinter hide Label" as of 10/27/13... So if anyone like myself a few weeks ago is building a simple GUI and just wants some text to appear without swapping it out for another widget via "lower" or "lift" methods, I'd like to offer a workaround I use (Python2.7,Windows):

from Tkinter import *


class Top(Toplevel):
    def __init__(self, parent, title = "How to Cheat and Hide Text"):
        Toplevel.__init__(self,parent)
        parent.geometry("250x250+100+150")
        if title:
            self.title(title)
        parent.withdraw()
        self.parent = parent
        self.result = None
        dialog = Frame(self)
        self.initial_focus = self.dialog(dialog)
        dialog.pack()


    def dialog(self,parent):

        self.parent = parent

        self.L1 = Label(parent,text = "Hello, World!",state = DISABLED, disabledforeground = parent.cget('bg'))
        self.L1.pack()

        self.B1 = Button(parent, text = "Are You Alive???", command = self.hello)
        self.B1.pack()

    def hello(self):
        self.L1['state']="normal"


if __name__ == '__main__':
    root=Tk()   
    ds = Top(root)
    root.mainloop()

The idea here is that you can set the color of the DISABLED text to the background ('bg') of the parent using ".cget('bg')" http://effbot.org/tkinterbook/widget.htm rendering it "invisible". The button callback resets the Label to the default foreground color and the text is once again visible.

Downsides here are that you still have to allocate the space for the text even though you can't read it, and at least on my computer, the text doesn't perfectly blend to the background. Maybe with some tweaking the color thing could be better and for compact GUIs, blank space allocation shouldn't be too much of a hassle for a short blurb.

See Default window colour Tkinter and hex colour codes for the info about how I found out about the color stuff.

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Format cell color based on value in another sheet and cell

Here is my own solution for restoring the original colors when copying certain highly formatted sheets or templates to a new spreadsheet.. it copies all data directly, so it only works if you need to copy a sheet, not only apply colors to a different sheet with different data:

copy the original format workbook by ctrl + g and selecting the appropriate range

paste it into the new work sheet, colors will be all changed

with the destination still highlighted, right click and go to "Paste special" and select "All using source theme", then repeat the paste special, only with "Values" this time, and it should be identical to the original sheet you copied

Could not find method compile() for arguments Gradle

Make sure that you are editing the correct build.gradle file. I received this error when editing android/build.gradle rather than android/app/build.gradle.

Which font is used in Visual Studio Code Editor and how to change fonts?

In VSCode if "editor.fontFamily": "" is blank, the font size will NOT work. Set a font family to change the size.

"editor.fontFamily": "Verdana", or "editor.fontFamily": "Monaco",

Really, use whatever font family you like.

Then "editor.fontSize": 16, should work.

Ajax request returns 200 OK, but an error event is fired instead of success

Use the following code to ensure the response is in JSON format (PHP version)...

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;

For vs. while in C programming?

One common misunderstanding withwhile/for loops I've seen is that their efficiency differs. While loops and for loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.

For loops are simply syntactically sugared while loops, and make iteration code faster to write.

When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while and for syntaxes are lost, and they become exactly the same.

Hadoop "Unable to load native-hadoop library for your platform" warning

The answer depends... I just installed Hadoop 2.6 from tarball on 64-bit CentOS 6.6. The Hadoop install did indeed come with a prebuilt 64-bit native library. For my install, it is here:

/opt/hadoop/lib/native/libhadoop.so.1.0.0

And I know it is 64-bit:

[hadoop@VMWHADTEST01 native]$ ldd libhadoop.so.1.0.0
./libhadoop.so.1.0.0: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by ./libhadoop.so.1.0.0)
linux-vdso.so.1 =>  (0x00007fff43510000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f9be553a000)
libc.so.6 => /lib64/libc.so.6 (0x00007f9be51a5000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9be5966000)

Unfortunately, I stupidly overlooked the answer right there staring me in the face as I was focuses on, "Is this library 32 pr 64 bit?":

`GLIBC_2.14' not found (required by ./libhadoop.so.1.0.0)

So, lesson learned. Anyway, the rest at least led me to being able to suppress the warning. So I continued and did everything recommended in the other answers to provide the library path using the HADOOP_OPTS environment variable to no avail. So I looked at the source code. The module that generates the error tells you the hint (util.NativeCodeLoader):

15/06/18 18:59:23 WARN util.NativeCodeLoader: Unable to load native-hadoop    library for your platform... using builtin-java classes where applicable

So, off to here to see what it does:

http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.action/0.2.6/org/apache/hadoop/util/NativeCodeLoader.java/

Ah, there is some debug level logging - let's turn that on a see if we get some additional help. This is done by adding the following line to $HADOOP_CONF_DIR/log4j.properties file:

log4j.logger.org.apache.hadoop.util.NativeCodeLoader=DEBUG

Then I ran a command that generates the original warning, like stop-dfs.sh, and got this goodie:

15/06/18 19:05:19 DEBUG util.NativeCodeLoader: Failed to load native-hadoop with error: java.lang.UnsatisfiedLinkError: /opt/hadoop/lib/native/libhadoop.so.1.0.0: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /opt/hadoop/lib/native/libhadoop.so.1.0.0)

And the answer is revealed in this snippet of the debug message (the same thing that the previous ldd command 'tried' to tell me:

`GLIBC_2.14' not found (required by opt/hadoop/lib/native/libhadoop.so.1.0.0)

What version of GLIBC do I have? Here's simple trick to find out:

[hadoop@VMWHADTEST01 hadoop]$ ldd --version
ldd (GNU libc) 2.12

So, can't update my OS to 2.14. Only solution is to build the native libraries from sources on my OS or suppress the warning and just ignore it for now. I opted to just suppress the annoying warning for now (but do plan to build from sources in the future) buy using the same logging options we used to get the debug message, except now, just make it ERROR level.

log4j.logger.org.apache.hadoop.util.NativeCodeLoader=ERROR

I hope this helps others see that a big benefit of open source software is that you can figure this stuff out if you take some simple logical steps.

Add a fragment to the URL without causing a redirect?

window.location.hash = 'something';

That is just plain JavaScript.

Your comment...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.

Try this...

window.location = '#';

Also, don't forget about the window.location.replace() method.

Shell script not running, command not found

Add below lines in your .profile path

PATH=$PATH:$HOME/bin:$Dir_where_script_exists

export PATH

Now your script should work without ./

Raj Dagla

how get yesterday and tomorrow datetime in c#

You want DateTime.Today.AddDays(1).

Clear and reset form input fields

You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!

handleSubmit(e){
 e.preventDefault();
 e.target.reset();
}

<form onSubmit={this.handleSubmit}>
  ...
</form>

CSV in Python adding an extra carriage return, on Windows

You have to add attribute newline="\n" to open function like this:

with open('file.csv','w',newline="\n") as out:
    csv_out = csv.writer(out, delimiter =';')

How to use a TRIM function in SQL Server

LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'

I think you're missing a ) on both of the trims. Some SQL versions support just TRIM which does both L and R trims...

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

Creating a singleton in Python

Method 3 seems to be very neat, but if you want your program to run in both Python 2 and Python 3, it doesn't work. Even protecting the separate variants with tests for the Python version fails, because the Python 3 version gives a syntax error in Python 2.

Thanks to Mike Watkins: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/. If you want the program to work in both Python 2 and Python 3, you need to do something like:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

MC = Singleton('MC', (object), {})

class MyClass(MC):
    pass    # Code for the class implementation

I presume that 'object' in the assignment needs to be replaced with the 'BaseClass', but I haven't tried that (I have tried code as illustrated).

Write to rails console

In addition to already suggested p and puts — well, actually in most cases you do can write logger.info "blah" just as you suggested yourself. It works in console too, not only in server mode.

But if all you want is console debugging, puts and p are much shorter to write, anyway.

Is a view faster than a simple query?

In SQL Server at least, Query plans are stored in the plan cache for both views and ordinary SQL queries, based on query/view parameters. For both, they are dropped from the cache when they have been unused for a long enough period and the space is needed for some other newly submitted query. After which, if the same query is issued, it is recompiled and the plan is put back into the cache. So no, there is no difference, given that you are reusing the same SQL query and the same view with the same frequency.

Obviously, in general, a view, by it's very nature (That someone thought it was to be used often enough to make it into a view) is generally more likely to be "reused" than any arbitrary SQL statement.

Download Excel file via AJAX MVC

I was recently able to accomplish this in MVC (although there was no need to use AJAX) without creating a physical file and thought I'd share my code:

Super simple JavaScript function (datatables.net button click triggers this):

function getWinnersExcel(drawingId) {
    window.location = "/drawing/drawingwinnersexcel?drawingid=" + drawingId;
}

C# Controller code:

    public FileResult DrawingWinnersExcel(int drawingId)
    {
        MemoryStream stream = new MemoryStream(); // cleaned up automatically by MVC
        List<DrawingWinner> winnerList = DrawingDataAccess.GetWinners(drawingId); // simple entity framework-based data retrieval
        ExportHelper.GetWinnersAsExcelMemoryStream(stream, winnerList, drawingId);

        string suggestedFilename = string.Format("Drawing_{0}_Winners.xlsx", drawingId);
        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", suggestedFilename);
    }

In the ExportHelper class I do use a 3rd party tool (GemBox.Spreadsheet) to generate the Excel file and it has a Save to Stream option. That being said, there are a number of ways to create Excel files that can easily be written to a memory stream.

public static class ExportHelper
{
    internal static void GetWinnersAsExcelMemoryStream(MemoryStream stream, List<DrawingWinner> winnerList, int drawingId)
    {

        ExcelFile ef = new ExcelFile();

        // lots of excel worksheet building/formatting code here ...

        ef.SaveXlsx(stream);
        stream.Position = 0; // reset for future read

     }
}

In IE, Chrome, and Firefox, the browser prompts to download the file and no actual navigation occurs.

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

jQuery - Fancybox: But I don't want scrollbars!

$(".various").fancybox({
    fitToView   : false,
    width       : '100%',
    height      : '100%',
    maxWidth    : 850,
    maxHeight   : 550,    
    fitToView   : false,
    padding : 20,
    autoSize    : true,
    closeClick  : true,
    openEffect  : 'none',
    closeEffect : 'none',
    overflow : 'hidden', 

            scrolling   : 'no'
});

Use basic authentication with jQuery and Ajax

Use the beforeSend callback to add a HTTP header with the authentication information like so:

var username = $("input#username").val();
var password = $("input#password").val();  

function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax
  ({
    type: "GET",
    url: "index1.php",
    dataType: 'json',
    async: false,
    data: '{}',
    beforeSend: function (xhr){ 
        xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
    },
    success: function (){
        alert('Thanks for your comment!'); 
    }
});

m2eclipse not finding maven dependencies, artifacts not found

One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.

Filter dict to contain only certain keys?

Another option:

content = dict(k1='foo', k2='nope', k3='bar')
selection = ['k1', 'k3']
filtered = filter(lambda i: i[0] in selection, content.items())

But you get a list (Python 2) or an iterator (Python 3) returned by filter(), not a dict.

What does "where T : class, new()" mean?

when using the class in constraints it's mean you can only use Reference type, another thing to add is when to use the constraint new(), it's must be the last thing you write in the Constraints terms.

numpy: most efficient frequency counts for unique values in an array

Old question, but I'd like to provide my own solution which turn out to be the fastest, use normal list instead of np.array as input (or transfer to list firstly), based on my bench test.

Check it out if you encounter it as well.

def count(a):
    results = {}
    for x in a:
        if x not in results:
            results[x] = 1
        else:
            results[x] += 1
    return results

For example,

>>>timeit count([1,1,1,2,2,2,5,25,1,1]) would return:

100000 loops, best of 3: 2.26 µs per loop

>>>timeit count(np.array([1,1,1,2,2,2,5,25,1,1]))

100000 loops, best of 3: 8.8 µs per loop

>>>timeit count(np.array([1,1,1,2,2,2,5,25,1,1]).tolist())

100000 loops, best of 3: 5.85 µs per loop

While the accepted answer would be slower, and the scipy.stats.itemfreq solution is even worse.


A more indepth testing did not confirm the formulated expectation.

from zmq import Stopwatch
aZmqSTOPWATCH = Stopwatch()

aDataSETasARRAY = ( 100 * abs( np.random.randn( 150000 ) ) ).astype( np.int )
aDataSETasLIST  = aDataSETasARRAY.tolist()

import numba
@numba.jit
def numba_bincount( anObject ):
    np.bincount(    anObject )
    return

aZmqSTOPWATCH.start();np.bincount(    aDataSETasARRAY );aZmqSTOPWATCH.stop()
14328L

aZmqSTOPWATCH.start();numba_bincount( aDataSETasARRAY );aZmqSTOPWATCH.stop()
592L

aZmqSTOPWATCH.start();count(          aDataSETasLIST  );aZmqSTOPWATCH.stop()
148609L

Ref. comments below on cache and other in-RAM side-effects that influence a small dataset massively repetitive testing results.

How to print VARCHAR(MAX) using Print Statement?

Here is how this should be done:

DECLARE @String NVARCHAR(MAX);
DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */
DECLARE @offset tinyint; /*tracks the amount of offset needed */
set @string = replace(  replace(@string, char(13) + char(10), char(10))   , char(13), char(10))

WHILE LEN(@String) > 1
BEGIN
    IF CHARINDEX(CHAR(10), @String) between 1 AND 4000
    BEGIN
           SET @CurrentEnd =  CHARINDEX(char(10), @String) -1
           set @offset = 2
    END
    ELSE
    BEGIN
           SET @CurrentEnd = 4000
            set @offset = 1
    END   
    PRINT SUBSTRING(@String, 1, @CurrentEnd) 
    set @string = SUBSTRING(@String, @CurrentEnd+@offset, LEN(@String))   
END /*End While loop*/

Taken from http://ask.sqlservercentral.com/questions/3102/any-way-around-the-print-limit-of-nvarcharmax-in-s.html

Command failed due to signal: Segmentation fault: 11

In my case it was caused by trying to use a function that returned an NSNumber as an argument where a Double was expected. My advice is be careful mixing Objective C objects with Swift datatypes. And as many others have suggested, comment out lines until you pinpoint which one causes the error. (Even if you create other errors when doing so, you can just ignore them and see what makes the segmentation fault error go away.)

What are the differences between a superkey and a candidate key?

Candidate key is a super key from which you cannot remove any fields.

For instance, a software release can be identified either by major/minor version, or by the build date (we assume nightly builds).

Storing date in three fields is not a good idea of course, but let's pretend it is for demonstration purposes:

year  month date  major  minor
2008  01    13     0      1
2008  04    23     0      2
2009  11    05     1      0
2010  04    05     1      1

So (year, major, minor) or (year, month, date, major) are super keys (since they are unique) but not candidate keys, since you can remove year or major and the remaining set of columns will still be a super key.

(year, month, date) and (major, minor) are candidate keys, since you cannot remove any of the fields from them without breaking uniqueness.

How can I initialize base class member variables in derived class constructor?

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

class B : public A 
{
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    } 
};

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

try this

provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);

Bye.

Call Python function from MATLAB

Since MATLAB seamlessly integrates with Java, you can use Jython to write your script and call that from MATLAB (you may have to add a thin pure JKava wrapper to actually call the Jython code). I never tried it, but I can't see why it won't work.

Is there any standard for JSON API response format?

Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.

As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?

Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:

https://github.com/adnan-kamili/rest-api-response-format

Swagger file:

https://github.com/adnan-kamili/swagger-sample-template

What exactly does stringstream do?

You entered an alphanumeric and int, blank delimited in mystr.

You then tried to convert the first token (blank delimited) into an int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

When you only entered int values the second time, everything worked as you expected.

It was the spurious RS that caused your code to fail.

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

How do I center a Bootstrap div with a 'spanX' class?

Incidentally, if your span class is even-numbered (e.g. span8) you can add an offset class to center it – for span8 that would be offset2 (assuming the default 12-column grid), for span6 it would be offset3 and so on (basically, half the number of remaining columns if you subtract the span-number from the total number of columns in the grid).

UPDATE Bootstrap 3 renamed a lot of classes so all the span*classes should be col-md-* and the offset classes should be col-md-offset-*, assuming you're using the medium-sized responsive grid.

I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

super() in Java

Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.

class Explicit() {
    Explicit() {
        super();
    }
}

class Implicit {
    Implicit() {
    }
}

Have log4net use application config file for configuration data

From the config shown in the question there is but one appender configured and it is named "EventLogAppender". But in the config for root, the author references an appender named "ConsoleAppender", hence the error message.

Is the sizeof(some pointer) always equal to four?

Technically speaking, the C standard only guarantees that sizeof(char) == 1, and the rest is up to the implementation. But on modern x86 architectures (e.g. Intel/AMD chips) it's fairly predictable.

You've probably heard processors described as being 16-bit, 32-bit, 64-bit, etc. This usually means that the processor uses N-bits for integers. Since pointers store memory addresses, and memory addresses are integers, this effectively tells you how many bits are going to be used for pointers. sizeof is usually measured in bytes, so code compiled for 32-bit processors will report the size of pointers to be 4 (32 bits / 8 bits per byte), and code for 64-bit processors will report the size of pointers to be 8 (64 bits / 8 bits per byte). This is where the limitation of 4GB of RAM for 32-bit processors comes from -- if each memory address corresponds to a byte, to address more memory you need integers larger than 32-bits.

What does [object Object] mean? (JavaScript)

Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)

How to force garbage collection in Java?

It would be better if you would describe the reason why you need garbage collection. If you are using SWT, you can dispose resources such as Image and Font to free memory. For instance:

Image img = new Image(Display.getDefault(), 16, 16);
img.dispose();

There are also tools to determine undisposed resources.

Purge or recreate a Ruby on Rails database

I know two ways to do this:

This will reset your database and reload your current schema with all:

rake db:reset db:migrate

This will destroy your db and then create it and then migrate your current schema:

rake db:drop db:create db:migrate

All data will be lost in both scenarios.

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

Creating an Array from a Range in VBA

Just define the variable as a variant, and make them equal:

Dim DirArray As Variant
DirArray = Range("a1:a5").Value

No need for the Array command.

Session 'app' error while installing APK

Try to this way :

1) In Instance Run is Enable then desable it. 2) Save it and Rebuild the project. 3) Check devices is online or USB debugging On your device. 4) Then Run It App On your devices.

Note :

If you use mobile device is MI (Xiaomi) Then Check : => setting>Additional setting> Developer options> Install via USB (ON it) => setting>Additional setting> Developer options> USB debugging (ON it) => setting>Additional setting> Developer options> Verify apps over USB (ON/Off it)

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

gpg decryption fails with no secret key error

You can also be interested at the top answer in here: https://askubuntu.com/questions/1080204/gpg-problem-with-the-agent-permission-denied

basically the solution that worked for me too is:

gpg --decrypt --pinentry-mode=loopback <file>

Windows 7 environment variable not working in path

I had exactly the same problem, to solve it, you can do one of two things:

  • Put all variables in System Variables instead of User and add the ones you want to PATH

Or

  • Put all variables in User Variables, and create or edit the PATH variables in User Variable, not In System. The Path variables in System don't expand the User Variables.

If the above are all correct, but the problem is still present, you need to check the system Registry, in HKEY_CURRENT_USER\Environment, to make sure the "PATH" key type is REG_EXPAND_SZ (not REG_SZ).

problem with php mail 'From' header

headers were not working for me on my shared hosting, reason was i was using my hotmail email address in header. i created a email on my cpanel and i set that same email in the header yeah it worked like a charm!

 $header = 'From: ShopFive <[email protected]>' . "\r\n";

Auto generate function documentation in Visual Studio

I'm working on an open-source project called Todoc which analyzes words to produce proper documentation output automatically when saving a file. It respects existing comments and is really fast and fluid.

http://todoc.codeplex.com/

Read all worksheets in an Excel workbook into an R list with data.frames

You can load the work book and then use lapply, getSheets and readWorksheet and do something like this.

wb.mtcars <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", 
                          package = "XLConnect"))
sheet_names <- getSheets(wb.mtcars)
names(sheet_names) <- sheet_names

sheet_list <- lapply(sheet_names, function(.sheet){
    readWorksheet(object=wb.mtcars, .sheet)})

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

Using different Web.config in development and production environment

The <appSettings> tag in web.config supports a file attribute that will load an external config with it's own set of key/values. These will override any settings you have in your web.config or add to them.

We take advantage of this by modifying our web.config at install time with a file attribute that matches the environment the site is being installed to. We do this with a switch on our installer.

eg;

<appSettings file=".\EnvironmentSpecificConfigurations\dev.config">

<appSettings file=".\EnvironmentSpecificConfigurations\qa.config">

<appSettings file=".\EnvironmentSpecificConfigurations\production.config">

Note:

  • Changes to the .config specified by the attribute won't trigger a restart of the asp.net worker process

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.

However, there are other considerations at play here too.

Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.

Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).

If you refer to classic VxWorks RTOS kernel, they define three mechanisms:

  • mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
  • binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
  • counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.

Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

clear table jquery

The nuclear option:

$("#yourtableid").html("");

Destroys everything inside of #yourtableid. Be careful with your selectors, as it will destroy any html in the selector you pass!

Why isn't .ico file defined when setting window's icon?

Try this:

from tkinter import *
import os
import sys

root = Tk()
root.iconbitmap(os.path.join(sys.path[0], '<your-ico-file>'))

root.mainloop()

Note: replace <your-ico-file> with the name of the ico file you are using otherwise it won't work.

I have tried this in Python 3. It worked.

Find all files with a filename beginning with a specified string?

Use find with a wildcard:

find . -name 'mystring*'

Remove Elements from a HashSet while Iterating

You can manually iterate over the elements of the set:

Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
    Integer element = iterator.next();
    if (element % 2 == 0) {
        iterator.remove();
    }
}

You will often see this pattern using a for loop rather than a while loop:

for (Iterator<Integer> i = set.iterator(); i.hasNext();) {
    Integer element = i.next();
    if (element % 2 == 0) {
        i.remove();
    }
}

As people have pointed out, using a for loop is preferred because it keeps the iterator variable (i in this case) confined to a smaller scope.

PHP Checking if the current date is before or after a set date

if(strtotime($row['database_date']) > strtotime('now')) echo $row['database_date'];
else echo date("d-m-Y");

No need to check the hours because if they are on the same day it will show the same date either way...

NumPy array initialization (fill with identical values)

I had

numpy.array(n * [value])

in mind, but apparently that is slower than all other suggestions for large enough n.

Here is full comparison with perfplot (a pet project of mine).

enter image description here

The two empty alternatives are still the fastest (with NumPy 1.12.1). full catches up for large arrays.


Code to generate the plot:

import numpy as np
import perfplot


def empty_fill(n):
    a = np.empty(n)
    a.fill(3.14)
    return a


def empty_colon(n):
    a = np.empty(n)
    a[:] = 3.14
    return a


def ones_times(n):
    return 3.14 * np.ones(n)


def repeat(n):
    return np.repeat(3.14, (n))


def tile(n):
    return np.repeat(3.14, [n])


def full(n):
    return np.full((n), 3.14)


def list_to_array(n):
    return np.array(n * [3.14])


perfplot.show(
    setup=lambda n: n,
    kernels=[empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array],
    n_range=[2 ** k for k in range(27)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this - I slightly changed the above answers:

var getAttributes = function(attribute) {
    var allElements = document.getElementsByTagName('*'),
        allElementsLen = allElements.length,
        curElement,
        i,
        results = [];

    for(i = 0; i < allElementsLen; i += 1) {
        curElement = allElements[i];

        if(curElement.getAttribute(attribute)) {
            results.push(curElement);
        }
    }

    return results;
};

Then,

getAttributes('data-foo');

django import error - No module named core.management

Having an application called site can reproduce this issue either.

Remove rows with all or some NAs (missing values) in data.frame

Using dplyr package we can filter NA as follows:

dplyr::filter(df,  !is.na(columnname))