Programs & Examples On #Suexec

Apache suEXEC is a feature of the Apache Web server that allows users to run CGI and SSI applications as a different user.

Completely removing phpMyAdmin

Try purge

sudo aptitude purge phpmyadmin

Not sure this works with plain old apt-get though

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Correct way to read a text file into a buffer in C?

See this article from JoelOnSoftware for why you don't want to use strcat.

Look at fread for an alternative. Use it with 1 for the size when you're reading bytes or characters.

One line if-condition-assignment

If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.

>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>

Inline IF Statement in C#

The literal answer is:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

return (value == 1
    ? Periods.VariablePeriods
    : (value == 2
        ? Periods.FixedPeriods
        : Periods.Unknown));

If you add more values an inline if will become unreadable and a switch would be preferred:

switch (value)
{
case 1:
    return Periods.VariablePeriods;
case 2:
    return Periods.FixedPeriods;
}

The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use

$(window).on('load', function() {
    // your code here
});

Which will wait until the page is loaded. $(document).ready() waits until the DOM is loaded.

In plain JS:

window.addEventListener('load', function() {
    // your code here
})

How to append contents of multiple files into one file

All of the (text-) files into one

find . | xargs cat > outfile

xargs makes the output-lines of find . the arguments of cat.

find has many options, like -name '*.txt' or -type.

you should check them out if you want to use it in your pipeline

Correct way to pass multiple values for same parameter name in GET request

Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

http://localhost/?key[]=1&key[]=2

Returns:

Array
(
[key] => Array
    (
        [0] => 1
        [1] => 2
    )

Mail not sending with PHPMailer over SSL using SMTP

Don't use SSL on port 465, it's been deprecated since 1998 and is only used by Microsoft products that didn't get the memo; use TLS on port 587 instead: So, the code below should work very well for you.

mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "smtp.gmail.com"; // SMTP server

$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 587;                   // set the SMTP port for the 

Easiest way to detect Internet connection on iOS?

You may also try this one if you already configured AFNetworking in your project.

-(void)viewDidLoad{  // -- add connectivity notification --//
[[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(ReachabilityDidChangeNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];}
-(void)ReachabilityDidChangeNotification:(NSNotification *)notify
{
// -- NSLog(@"Reachability changed: %@", AFStringFromNetworkReachabilityStatus(status));  -- //
NSDictionary *userInfo =[notif userInfo];
AFNetworkReachabilityStatus status= [[userInfo valueForKey:AFNetworkingReachabilityNotificationStatusItem] intValue];
switch (status)
{
    case AFNetworkReachabilityStatusReachableViaWWAN:
    case AFNetworkReachabilityStatusReachableViaWiFi:
        // -- Reachable -- //
// -- Do your stuff when internet connection is available -- //
        [self getLatestStuff];
        NSLog(@"Reachable");
        break;
    case AFNetworkReachabilityStatusNotReachable:
    default:
        // -- Not reachable -- //
        // -- Do your stuff for internet connection not available -- //
NSLog(@"Not Reachable");
        break;
}
}

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

MAX function in where clause mysql

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT.

The normative pattern for solving this type of problem is to use an inline view, something like this:

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
  JOIN ( SELECT MAX(mx.id) AS max_id
           FROM mytable mx
       ) m
    ON m.max_id = t.id

This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:

 WHERE t.id = (SELECT MAX(id) FROM ... )

Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
 ORDER BY t.id DESC
 LIMIT 1

Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)

This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5.

Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.

How to print environment variables to the console in PowerShell?

The following is works best in my opinion:

Get-Item Env:PATH
  1. It's shorter and therefore a little bit easier to remember than Get-ChildItem. There's no hierarchy with environment variables.
  2. The command is symmetrical to one of the ways that's used for setting environment variables with Powershell. (EX: Set-Item -Path env:SomeVariable -Value "Some Value")
  3. If you get in the habit of doing it this way you'll remember how to list all Environment variables; simply omit the entry portion. (EX: Get-Item Env:)

I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.

What's the point of the trailing colon in Env:? Try listing all of the "drives" available through Providers like this:

PS> Get-PSDrive

I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.

You can navigate the drives and pick out specific values:

Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM

How to add a Try/Catch to SQL Stored Procedure

See TRY...CATCH (Transact-SQL)

 CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]        
       @GAD_COMP_CODE  VARCHAR(2) =NULL, 
       @@voucher_no numeric =null output 
       AS         
   BEGIN  

     begin try 
         -- your proc code
     end try

     begin catch
          -- what you want to do in catch
     end catch    
  END -- proc end

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

How to create a box when mouse over text in pure CSS?

Exactly what they said, it will work.

In the parent element stablish a max-height.

I'm taking sandeep example and adding the max-height and if required you can add max-width property. The text will stay where It should stay (If possible, in some cases you will need to change some values to make it stay in there)

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;
}

span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
     transform:rotate(45deg);
}

p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
    max-height: 10px;
}

p:hover span{
    display:block;
}

max-height in the p paragraph, second to last one, last line.

Test it before rating it useless.

How to set environment variables in Python?

if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.

Then do

os.environ["DEBUSSY"] = "1"

I also want to know how to read the environment variables in python(in the later part of the script) once i set it.

Just use os.environ["DEBUSSY"], as in

some_value = os.environ["DEBUSSY"]

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

Git push error pre-receive hook declined

Following resolved problem in my local machine:

A. First, ensure that you are using the correct log on details to connect to Bitbucket Server (ie. a username/password/SSH key that belongs to you) 

B. Then, ensure that the name/email address is correctly set in your local Git configuration: Set your local Git configuration for the account that you are trying to push under (the check asserts that you are the person who committed the files) * Note that this is case sensitive, both for name and email address * It is also space sensitive - some company accounts have extra spaces/characters in their name eg. "Contractor/ space space(LDN)".  You must include the same number of spaces in your configuration as on Bitbucket Server.  Check this in Notepad if stuck.

C. If you were using the wrong account, simply switch your account credentials (username/password/SSH key) and try pushing again.

D. Else, if your local configuration incorrect you will need to amend it

For MAC

open -a TextEdit.app ~/.gitconfig

NOTE: You will have to fix up the old commits that you were trying to push.

  1. Amend your last commit:

    > git commit --amend --reset-author
    
      
    <save and quit the commit file text editor that opens, if Vim then
    :wq to save and quit>
    
  2. Try re-pushing your commits:

    > git push
    

Maximize a window programmatically and prevent the user from changing the windows state

To stop the window being resizeable once you've maximised it you need to change the FormBorderStyle from Sizable to one of the fixed constants:

FixedSingle
Fixed3D
FixedDialog

From the MSDN Page Remarks section:

The border style of the form determines how the outer edge of the form appears. In addition to changing the border display for a form, certain border styles prevent the form from being sized. For example, the FormBorderStyle.FixedDialog border style changes the border of the form to that of a dialog box and prevents the form from being resized. The border style can also affect the size or availability of the caption bar section of a form.

It will change the appearance of the form if you pick Fixed3D for example, and you'll probably have to do some work if you want the form to restore to non-maximised and be resizeable again.

Sending email from Azure

A nice way to achieve this "if you have an office 365 account" is to use Office 365 outlook connector integrated with Azure Logic App,

Hope this helps someone!

Throwing exceptions in a PHP Try Catch block

To rethrow do

 throw $e;

not the message.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

The specific characters that can be stored in a varchar or char column depend upon the column collation. See my answer here for a script that will show you these for the various different collations.

If you want to find all characters outside a particular ASCII range see my answer here.

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

Controlling fps with requestAnimationFrame?

I suggest wrapping your call to requestAnimationFrame in a setTimeout:

const fps = 25;
function animate() {
  // perform some animation task here

  setTimeout(() => {
    requestAnimationFrame(animate);
  }, 1000 / fps);
}
animate();

You need to call requestAnimationFrame from within setTimeout, rather than the other way around, because requestAnimationFrame schedules your function to run right before the next repaint, and if you delay your update further using setTimeout you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

How to remove first and last character of a string?

You can always use substring:

String loginToken = getName().toString();
loginToken = loginToken.substring(1, loginToken.length() - 1);

How to move up a directory with Terminal in OS X

To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

alias ..='cd ..'

and then one would need only to type '..[return]'.

When to use margin vs padding in CSS

The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.

enter image description here

it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.

note that some times you have to use margin.

Adding a y-axis label to secondary y-axis in matplotlib

There is a straightforward solution without messing with matplotlib: just pandas.

Tweaking the original example:

table = sql.read_frame(query,connection)

ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)

ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')

Basically, when the secondary_y=True option is given (eventhough ax=ax is passed too) pandas.plot returns a different axes which we use to set the labels.

I know this was answered long ago, but I think this approach worths it.

Open directory using C

Here is a simple way to implement ls command using c. To run use for example ./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }

LINQ: Distinct values

In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:

var query = from e in doc.Elements("whatever")
            group e by new { id = e.Key, val = e.Value } into g
            select new { id = g.Key.id, val = g.Key.val, count = g.Count() };

How to "Open" and "Save" using java

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

EditText, clear focus on touch outside

This is my Version based on zMan's code. It will not hide the keyboard if the next view also is an edit text. It will also not hide the keyboard if the user just scrolls the screen.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        downX = (int) event.getRawX();
    }

    if (event.getAction() == MotionEvent.ACTION_UP) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            //Was it a scroll - If skip all
            if (Math.abs(downX - x) > 5) {
                return super.dispatchTouchEvent(event);
            }
            final int reducePx = 25;
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            //Bounding box is to big, reduce it just a little bit
            outRect.inset(reducePx, reducePx);
            if (!outRect.contains(x, y)) {
                v.clearFocus();
                boolean touchTargetIsEditText = false;
                //Check if another editText has been touched
                for (View vi : v.getRootView().getTouchables()) {
                    if (vi instanceof EditText) {
                        Rect clickedViewRect = new Rect();
                        vi.getGlobalVisibleRect(clickedViewRect);
                        //Bounding box is to big, reduce it just a little bit
                        clickedViewRect.inset(reducePx, reducePx);
                        if (clickedViewRect.contains(x, y)) {
                            touchTargetIsEditText = true;
                            break;
                        }
                    }
                }
                if (!touchTargetIsEditText) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".

Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:

CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;

because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:

CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;

Inserting a PDF file in LaTeX

\includegraphics{myfig.pdf}

How to convert NSNumber to NSString

The funny thing is that NSNumber converts to string automatically if it becomes a part of a string. I don't think it is documented. Try these:

NSLog(@"My integer NSNumber:%@",[NSNumber numberWithInt:184]);
NSLog(@"My float NSNumber:%@",[NSNumber numberWithFloat:12.23f]);
NSLog(@"My bool(YES) NSNumber:%@",[NSNumber numberWithBool:YES]);
NSLog(@"My bool(NO) NSNumber:%@",[NSNumber numberWithBool:NO]);

NSString *myStringWithNumbers = [NSString stringWithFormat:@"Int:%@, Float:%@ Bool:%@",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]];
NSLog(@"%@",myStringWithNumbers);

It will print:

My integer NSNumber:184
My float NSNumber:12.23
My bool(YES) NSNumber:1
My bool(NO) NSNumber:0
Int:132, Float:-4.823 Bool:1

Works on both Mac and iOS

This one does not work:

NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f];

Hashing a string with Sha256

public string EncryptPassword(string password, string saltorusername)
        {
            using (var sha256 = SHA256.Create())
            {
                var saltedPassword = string.Format("{0}{1}", salt, password);
                byte[] saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
                return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
            }
        }

How do I add a simple onClick event handler to a canvas element?

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.

Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.

To add a click event to your canvas element, use...

canvas.addEventListener('click', function() { }, false);

To determine which element was clicked...

var elem = document.getElementById('myCanvas'),
    elemLeft = elem.offsetLeft + elem.clientLeft,
    elemTop = elem.offsetTop + elem.clientTop,
    context = elem.getContext('2d'),
    elements = [];

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
    var x = event.pageX - elemLeft,
        y = event.pageY - elemTop;

    // Collision detection between clicked offset and element.
    elements.forEach(function(element) {
        if (y > element.top && y < element.top + element.height 
            && x > element.left && x < element.left + element.width) {
            alert('clicked an element');
        }
    });

}, false);

// Add element.
elements.push({
    colour: '#05EFFF',
    width: 150,
    height: 100,
    top: 20,
    left: 15
});

// Render elements.
elements.forEach(function(element) {
    context.fillStyle = element.colour;
    context.fillRect(element.left, element.top, element.width, element.height);
});?

jsFiddle.

This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.

The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.

When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.


For completeness, why your attempts didn't work...

elem.onClick = alert("hello world"); // displays alert without clicking

This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().

elem.onClick = alert('hello world');  // displays alert without clicking

In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.

elem.onClick = "alert('hello world!')"; // does nothing, even with clicking

You are assigning a string to the onClick property of elem.

elem.onClick = function() { alert('hello world!'); }; // does nothing

JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.

elem.onClick = function() { alert("hello world!"); }; // does nothing

Again, ' === ".

What is the easiest way to remove all packages installed by pip?

I wanted to elevate this answer out of a comment section because it's one of the most elegant solutions in the thread. Full credit for this answer goes to @joeb.

pip uninstall -y -r <(pip freeze)

This worked great for me for the use case of clearing my user packages folder outside the context of a virtualenv which many of the above answers don't handle.

Edit: Anyone know how to make this command work in a Makefile?

Bonus: A bash alias

I add this to my bash profile for convenience:

alias pipuninstallall="pip uninstall -y -r <(pip freeze)"

Then run:

pipuninstallall

Alternative for pipenv

If you happen to be using pipenv you can just run:

pipenv uninstall --all

How to find the php.ini file used by the command line?

You can use get_cfg_var('cfg_file_path') for that:

To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.
Unlike phpinfo() it will tell if it didn't find/use a php.ini at all.

var_dump( get_cfg_var('cfg_file_path') );

And you can simply set the location of the php.ini. You're using the command line version, so using the -c parameter you can specifiy the location, e.g.

php -c /home/me/php.ini -f /home/me/test.php

LINQ query on a DataTable

I realize this has been answered a few times over, but just to offer another approach:

I like to use the .Cast<T>() method, it helps me maintain sanity in seeing the explicit type defined and deep down I think .AsEnumerable() calls it anyways:

var results = from myRow in myDataTable.Rows.Cast<DataRow>() 
                  where myRow.Field<int>("RowNo") == 1 select myRow;

or

var results = myDataTable.Rows.Cast<DataRow>()
                      .FirstOrDefault(x => x.Field<int>("RowNo") == 1);

As noted in comments, no other assemblies needed as it's part of Linq (Reference)

Is it possible to run CUDA on AMD GPUs?

You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..

Java, return if trimmed String in List contains String

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

How to count frequency of characters in a string?

You can use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.

For example:

HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    Integer val = map.get(c);
    if (val != null) {
        map.put(c, new Integer(val + 1));
    }
    else {
       map.put(c, 1);
   }
}

At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.

Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.

How to read connection string in .NET Core?

The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}

In your controller add a field for the configuration and a parameter for it on a constructor

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}

Now later in your view code you can access it like:

connectionString = configuration.GetConnectionString("DefaultConnection");

How do you get total amount of RAM the computer has?

/*The simplest way to get/display total physical memory in VB.net (Tested)

public sub get_total_physical_mem()

    dim total_physical_memory as integer

    total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
    MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
end sub
*/


//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)

public void get_total_physical_mem()
{
    int total_physical_memory = 0;

    total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) /  (1024 * 1024));
    Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
}

C# equivalent of C++ vector, with contiguous memory?

C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

removing bold styling from part of a header

If you don't want a separate CSS file, you can use inline CSS:

<h1>This text should be bold, <span style="font-weight:normal">but this text should not</span></h1>

However, as Madara's comment suggests, you might want to consider putting the unbolded part in a different header, depending on the use case involved.

Regex match digits, comma and semicolon?

You current regex will only match 1 character. you need either * (includes empty string) or + (at least one) to match multiple characters and numbers have a shortcut : \d (need \\ in a string).

word.matches("^[\\d,;]+$") 

The Pattern documentation is pretty good : http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

Also you can try your regexps online at: http://www.regexplanet.com/simple/index.html

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

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

How to get numeric position of alphabets in java?

just logic I can suggest take two arrays.

one is Char array

and another is int array.

convert ur input string to char array,get the position of char from char and int array.

dont expect source code here

scrollIntoView Scrolls just too far

Here's my 2 cents.

I've also had the issue of the scrollIntoView scrolling a bit past the element, so I created a script (native javascript) that prepends an element to the destination, positioned it a bit to the top with css and scrolled to that one. After scrolling, I remove the created elements again.

HTML:

//anchor tag that appears multiple times on the page
<a href="#" class="anchors__link js-anchor" data-target="schedule">
    <div class="anchors__text">
        Scroll to the schedule
    </div>
</a>

//The node we want to scroll to, somewhere on the page
<div id="schedule">
    //html
</div>

Javascript file:

(() => {
    'use strict';

    const anchors = document.querySelectorAll('.js-anchor');

    //if there are no anchors found, don't run the script
    if (!anchors || anchors.length <= 0) return;

    anchors.forEach(anchor => {
        //get the target from the data attribute
        const target = anchor.dataset.target;

        //search for the destination element to scroll to
        const destination = document.querySelector(`#${target}`);
        //if the destination element does not exist, don't run the rest of the code
        if (!destination) return;

        anchor.addEventListener('click', (e) => {
            e.preventDefault();
            //create a new element and add the `anchors__generated` class to it
            const generatedAnchor = document.createElement('div');
            generatedAnchor.classList.add('anchors__generated');

            //get the first child of the destination element, insert the generated element before it. (so the scrollIntoView function scrolls to the top of the element instead of the bottom)
            const firstChild = destination.firstChild;
            destination.insertBefore(generatedAnchor, firstChild);

            //finally fire the scrollIntoView function and make it animate "smoothly"
            generatedAnchor.scrollIntoView({
                behavior: "smooth",
                block: "start",
                inline: "start"
            });

            //remove the generated element after 1ms. We need the timeout so the scrollIntoView function has something to scroll to.
            setTimeout(() => {
                destination.removeChild(generatedAnchor);
            }, 1);
        })
    })
})();

CSS:

.anchors__generated {
    position: relative;
    top: -100px;
}

Hope this helps anyone!

How to use putExtra() and getExtra() for string data

A single inlined code would be enough for this task. This worked for me effortlessly. For #android devlopers out there. String strValue=Objects.requireNonNull(getIntent().getExtras()).getString("string_Key");

How to create a Custom Dialog box in android?

Simplest way to create custom dialog box:

  1. Initialize and show dialog:

     ViewDialog alertDialoge = new ViewDialog();
     alertDialoge.showDialog(getActivity(), "PUT DIALOG TITLE");
    
  2. Create method:

    public class ViewDialog {
    
      public void showDialog(Activity activity, String msg) {
    
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.custom_dialoge_feedback);
    
        TextView text = (TextView) dialog.findViewById(R.id.text_dialog_feedback);
        text.setText(msg);
    
        Button okButton = (Button) dialog.findViewById(R.id.btn_dialog_feedback);
        Button cancleButton = (Button) dialog.findViewById(R.id.btn_dialog_cancle_feedback);
        final EditText edittext_tv = (EditText) dialog.findViewById(R.id.dialoge_alert_text_feedback);
    
        okButton.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                //Perfome Action
            }
        });
        cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    
        dialog.show();
    
        }
    }
    
  3. Create layout XML which you want or need.

How to fill Matrix with zeros in OpenCV?

use cv::mat::setto

img.setTo(cv::Scalar(redVal,greenVal,blueVal))

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

After searching for a while I found out that it is not sufficient to export the developer accounts from Xcode and import these on the new machine, again via Xcode.

Additionally I needed to copy the Certficate named "Apple World Wide Developer Relations Certificate Authority" from the keychain of the former development machine to the keychain of the new one.

This solved the problem for me.

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Free tool to Create/Edit PNG Images?

Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.

Note--Inkscape is open source and available for free on multiple platforms.

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

Inversion of Control vs Dependency Injection

1) DI is Child->obj depends on parent-obj. The verb depends is important. 2) IOC is Child->obj perform under a platform. where platform could be school, college, dance class. Here perform is an activity with different implication under any platform provider.

practical example: `

//DI
child.getSchool();
//IOC
child.perform()// is a stub implemented by dance-school
child.flourish()// is a stub implemented by dance-school/school/

`

-AB

How to hide axes and gridlines in Matplotlib (python)

Turn the axes off with:

plt.axis('off')

And gridlines with:

plt.grid(b=None)

Why should I use var instead of a type?

In this case it is just coding style.

Use of var is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.

Convert varchar into datetime in SQL Server

DECLARE @d char(8)
SET @d = '06082020'    /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (@d AS INT), '##/##/####') as DATETIME)

Result returned is the original date string in @d as a DateTime.

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download()

Click on download button when gui prompted. It worked for me.(nltk.download('stopwords') doesn't work for me)

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Find size of Git repository

You can easily find the size of each of your repository in your Accounts settings

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How to get the real path of Java application at runtime?

Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:

import java.io.File;
import java.net.URISyntaxException;

public class ProgramDirectoryUtilities
{
    private static String getJarName()
    {
        return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
                .getName();
    }

    private static boolean runningFromJAR()
    {
        String jarName = getJarName();
        return jarName.contains(".jar");
    }

    public static String getProgramDirectory()
    {
        if (runningFromJAR())
        {
            return getCurrentJARDirectory();
        } else
        {
            return getCurrentProjectDirectory();
        }
    }

    private static String getCurrentProjectDirectory()
    {
        return new File("").getAbsolutePath();
    }

    private static String getCurrentJARDirectory()
    {
        try
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
        } catch (URISyntaxException exception)
        {
            exception.printStackTrace();
        }

        return null;
    }
}

Simply call getProgramDirectory() and you should be good either way.

SQL Server : trigger how to read value for Insert, Update, Delete

There is no updated dynamic table. There is just inserted and deleted. On an UPDATE command, the old data is stored in the deleted dynamic table, and the new values are stored in the inserted dynamic table.

Think of an UPDATE as a DELETE/INSERT combination.

How to set a background image in Xcode using swift?

You can try this as well, which is really a combination of previous answers from other posters here :

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "RubberMat")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

Receive result from DialogFragment

I'm very surprised to see that no-one has suggested using local broadcasts for DialogFragment to Activity communication! I find it to be so much simpler and cleaner than other suggestions. Essentially, you register for your Activity to listen out for the broadcasts and you send the local broadcasts from your DialogFragment instances. Simple. For a step-by-step guide on how to set it all up, see here.

RESTful web service - how to authenticate requests from other services?

Besides authentication, I suggest you think about the big picture. Consider make your backend RESTful service without any authentication; then put some very simple authentication required middle layer service between the end user and the backend service.

How to hide a navigation bar from first ViewController in Swift?

In IOS 8 do it like

navigationController?.hidesBarsOnTap = true

but only when it's part of a UINavigationController

make it false when you want it back

Explanation of <script type = "text/template"> ... </script>

It's legit and very handy!

Try this:

<script id="hello" type="text/template">
  Hello world
</script>
<script>
  alert($('#hello').html());
</script>

Several Javascript templating libraries use this technique. Handlebars.js is a good example.

Iterating over Typescript Map

I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:

let myMap = new Map<string, boolean>();
myMap.set("a", true);
for (let [k, v] of myMap) {
    console.log(k + "=" + v);
}

How to round each item in a list of floats to 2 decimal places?

mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList =  [round(x,2) for x in mylist] 
# [0.3, 0.5, 0.2]

Best equivalent VisualStudio IDE for Mac to program .NET/C#

The question is quite old so I feel like I need to give a more up to date response to this question.

Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

SSIS Excel Import Forcing Incorrect Column Type

This worked for me. Select the problematic column in Excel - highlight the whole column. Change the format to "Text". Save the Excel file.

In your SSIS package, go to the Data Flow pane for your import. Double click the Excel Source node. It should warn you that the types have changed and ask you if you want to remap them. Click Yes. Executing should now work and bring in all values.

Note: I'm using Excel 2013 and Visual Studio 2015, but I assume these instructions would work for earlier versions too.

How do you calculate log base 2 in Java for integers?

To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :

public static int ceilbinlog(int number) // returns 0 for bits=0
{
    int log = 0;
    int bits = number;
    if ((bits & 0xffff0000) != 0) {
        bits >>>= 16;
        log = 16;
    }
    if (bits >= 256) {
        bits >>>= 8;
        log += 8;
    }
    if (bits >= 16) {
        bits >>>= 4;
        log += 4;
    }
    if (bits >= 4) {
        bits >>>= 2;
        log += 2;
    }
    if (1 << log < number)
        log++;
    return log + (bits >>> 1);
}

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

Java - Get a list of all Classes loaded in the JVM

One way if you already know the package top level path is to use OpenPojo

final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively("my.package.path", null);

Then you can go over the list and perform any functionality you desire.

How can I get the current PowerShell executing file?

As noted in previous responses, using "$MyInvocation" is subject to scoping issues and doesn't necessarily provide consistent data (return value vs. direct access value). I've found that the "cleanest" (most consistent) method for getting script info like script path, name, parms, command line, etc. regardless of scope (in main or subsequent/nested function calls) is to use "Get-Variable" on "MyInvocation"...

# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value

# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path

# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath

# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name

# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName

So, you can get the same info as $PSCommandPath, but a whole lot more in the deal. Not sure, but it looks like "Get-Variable" was not available until PS3 so not a lot of help for really old (not updated) systems.

There are also some interesting aspects when using "-Scope" as you can backtrack to get the names, etc. of the calling function(s). 0=current, 1=parent, etc.

Hope this is somewhat helpful.

Ref, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

How can I debug my JavaScript code?

I use WebKit's developer menu/console (Safari 4). It is almost identical to Firebug.

console.log() is the new black -- far better than alert().

Read each line of txt file to new array element

$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();

while ( $line = fgets($f, 1000) )
{
    $nl = mb_strtolower($line,'UTF-8');
    $array1[] = $nl;
}

print_r($array);

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

ProcessStartInfo hanging on "WaitForExit"? Why?

None of the answers above is doing the job.

Rob solution hangs and 'Mark Byers' solution get the disposed exception.(I tried the "solutions" of the other answers).

So I decided to suggest another solution:

public void GetProcessOutputWithTimeout(Process process, int timeoutSec, CancellationToken token, out string output, out int exitCode)
{
    string outputLocal = "";  int localExitCode = -1;
    var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        outputLocal = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        localExitCode = process.ExitCode;
    }, token);

    if (task.Wait(timeoutSec, token))
    {
        output = outputLocal;
        exitCode = localExitCode;
    }
    else
    {
        exitCode = -1;
        output = "";
    }
}

using (var process = new Process())
{
    process.StartInfo = ...;
    process.Start();
    string outputUnicode; int exitCode;
    GetProcessOutputWithTimeout(process, PROCESS_TIMEOUT, out outputUnicode, out exitCode);
}

This code debugged and works perfectly.

How can I switch views programmatically in a view controller? (Xcode, iPhone)

Swift version:

If you are in a Navigation Controller:

let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.navigationController?.pushViewController(viewController, animated: true)

Or if you just want to present a new view:

let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.presentViewController(viewController, animated: true, completion: nil)

What is the difference between & and && in Java?

I think my answer can be more understandable:

There are two differences between & and &&.

If they use as logical AND

& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.

when & and && as logical AND, there is a difference:

when use && as logical AND, if the left expression result is false, the right expression will not execute.

Take the example :

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute

}

If using &:

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 

}

An other more example:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

& can be used as bit operator

& can be used as Bitwise AND operator, && can not.

The bitwise AND " &" operator produces 1 if and only if both of the bits in its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 

From the wiki page:

http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

How can I close a window with Javascript on Mozilla Firefox 3?

This code works for both IE 7 and the latest version of Mozilla although the default setting in mozilla doesnt allow to close a window through javascript.

Here is the code:

function F11() { window.open('','_parent',''); window.open("login.aspx", "", "channelmode"); window.close(); }

To change the default setting :

1.type"about:config " in your firefox address bar and enter;

2.make sure your "dom.allow_scripts_to_close_windows" is true

Convert/cast an stdClass object to another class

consider adding a new method to BusinessClass:

public static function fromStdClass(\stdClass $in): BusinessClass
{
  $out                   = new self();
  $reflection_object     = new \ReflectionObject($in);
  $reflection_properties = $reflection_object->getProperties();
  foreach ($reflection_properties as $reflection_property)
  {
    $name = $reflection_property->getName();
    if (property_exists('BusinessClass', $name))
    {
      $out->{$name} = $in->$name;
    }
  }
  return $out;
}

then you can make a new BusinessClass from $stdClass:

$converted = BusinessClass::fromStdClass($stdClass);

Jupyter Notebook not saving: '_xsrf' argument missing from post

I got the same problem (impossible to save either notebooks and .py modules) using an image in the nvidia docker. The solution was just opening a terminal inside jupyter without typing anything but exit once the files were saved. It was done in the same browser/jupyter instance.

Machine OS: Ubuntu 18.04

Select all elements with a "data-xxx" attribute without using jQuery

While not as pretty as querySelectorAll (which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.

To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.

Code:

function recurseDOM(start, whitelist)
{
    /*
    *    @start:        Node    -    Specifies point of entry for recursion
    *    @whitelist:    Object  -    Specifies permitted nodeTypes to collect
    */

    var i = 0, 
    startIsNode = !!start && !!start.nodeType, 
    startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
    nodes, node, nodeHasChildNodes;
    if(startIsNode && startHasChildNodes)
    {       
        nodes = start.childNodes;
        for(i;i<nodes.length;i++)
        {
            node = nodes[i];
            nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
            if(!whitelist || whitelist[node.nodeType])
            {
                //condition here
                if(!!node.dataset && !!node.dataset.foo)
                {
                    //handle results here
                }
                if(nodeHasChildNodes)
                {
                    recurseDOM(node, whitelist);
                }
            }
            node = null;
            nodeHasChildNodes = null;
        }
    }
}

You can then initiate it with the following:

recurseDOM(document.body, {"1": 1}); for speed, or just recurseDOM(document.body);

Example with your specification: http://jsbin.com/unajot/1/edit

Example with differing specification: http://jsbin.com/unajot/2/edit

Calling a method every x minutes

I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));

Identifier not found error on function call

At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:

void swapCase(char* name);

Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write

if ('A' <= name[i] && name[i] <= 'Z')
    name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
    name[i] += 'A' - 'a';

The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.

Good luck learning!

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

Try

sc query state= all 

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

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

React-router: How to manually invoke Link?

React Router v5 - React 16.8+ with Hooks (updated 09/23/2020)

If you're leveraging React Hooks, you can take advantage of the useHistory API that comes from React Router v5.

import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';

export default function StackOverflowExample() {
  const history = useHistory();
  const handleOnClick = useCallback(() => history.push('/sample'), [history]);

  return (
    <button type="button" onClick={handleOnClick}>
      Go home
    </button>
  );
}

Another way to write the click handler if you don't want to use useCallback

const handleOnClick = () => history.push('/sample');

React Router v4 - Redirect Component

The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).

import { Redirect } from 'react-router';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});
}

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />;
  }

  return <button onClick={this.handleOnClick} type="button">Button</button>;
}

Reference: https://reacttraining.com/react-router/web/api/Redirect

React Router v4 - Reference Router Context

You can also take advantage of Router's context that's exposed to the React component.

static contextTypes = {
  router: PropTypes.shape({
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
      replace: PropTypes.func.isRequired
    }).isRequired,
    staticContext: PropTypes.object
  }).isRequired
};

handleOnClick = () => {
  this.context.router.push('/sample');
}

This is how <Redirect /> works under the hood.

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60

React Router v4 - Externally Mutate History Object

If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter then expose the history as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.

// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';

export const history = createHistory();

export default class BrowserRouter extends Component {
  render() {
    return <Router history={history} children={this.props.children} />
  }
}

// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';

render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
);

// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';

history.push('/sample');

Latest BrowserRouter to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js

React Router v2

Push a new state to the browserHistory instance:

import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');

Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

Change size of text in text input tag?

I would say to set up the font size change in your CSS stylesheet file.

I'm pretty sure that you want all text at the same size for all your form fields. Adding inline styles in your HTML will add to many lines at the end... plus you would need to add it to the other types of form fields such as <select>.

HTML:

<div id="cForm">
    <form method="post">
        <input type="text" name="name" placeholder="Name" data-required="true">
        <option value="" selected="selected" >Choose Category...</option>
    </form>
</div>

CSS:

input, select {
    font-size: 18px;
}

Rename all files in a folder with a prefix in a single command

You can just use -i instead of -I {}

ls | xargs -i mv {} unix_{}

This also works perfectly.

  • ls - lists all the files in the directory
  • xargs - accepts all files line by line due to the -i option
  • {} is the placeholder for all files, necessary if xargs gets more than two arguments as input

Using awk:

ls -lrt | grep '^-' | awk '{print "mv "$9" unix_"$9""}' | sh

How to open Atom editor from command line in OS X?

When Atom installs it automatically creates a symlink in your /usr/local/bin. However in case it hasn't, you can create it yourself on your Mac

ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom

Now you can use atom folder_name to open a folder and atom file_name to open a file.

jQuery click / toggle between two functions

I don't think you should implement the toggle method since there is a reason why it was removed from jQuery 1.9.

Consider using toggleClass instead that is fully supported by jQuery:

function a(){...}
function b(){...}   

Let's say for example that your event trigger is onclick, so:

First option:

$('#test').on('click', function (event) {

    $(this).toggleClass('toggled');

    if ($(this).hasClass('toggled')) {
        a();
    } else{
        b();
    }
}

You can also send the handler functions as parameters:

Second option:

$('#test').on('click',{handler1: a, handler2: b}, function (event) {

    $(this).toggleClass('toggled');

    if ($(this).hasClass('toggled')) {
        event.data.handler1();
    } else{
        event.data.handler2();
    }
}

Shorter syntax for casting from a List<X> to a List<Y>?

In case when X derives from Y you can also use ToList<T> method instead of Cast<T>

listOfX.ToList<Y>()

EventListener Enter Key

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

Merge (with squash) all changes from another branch as a single commit

Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

Select 2 columns in one and combine them

Yes, just like you did:

select something + somethingElse as onlyOneColumn from someTable

If you queried the database, you would have gotten the right answer.

What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.

Create a directory if it does not exist and then create the files in that directory as well

If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

    private File createFile(String path, String fileName) throws IOException {
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource(".").getFile() + path + fileName);

       // Lets create the directory
       try {
          file.getParentFile().mkdir();
       } catch (Exception err){
           System.out.println("ERROR (Directory Create)" + err.getMessage());
       }

       // Lets create the file if we have credential
       try {
           file.createNewFile();
       } catch (Exception err){
           System.out.println("ERROR (File Create)" + err.getMessage());
       }
       return  file;
   }

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

1) I am using WAMP.

2) I have installed Open Office (from apache http://www.openoffice.org/download/).

3) $output_dir = "C:/wamp/www/projectfolder/"; this is my project folder where i want to create output file.

4) I have already placed my input file here C:/wamp/www/projectfolder/wordfile.docx";

Then I Run My Code.. (given below)

<?php
    set_time_limit(0);
    function MakePropertyValue($name,$value,$osm){
    $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
    $oStruct->Name = $name;
    $oStruct->Value = $value;
    return $oStruct;
    }
    function word2pdf($doc_url, $output_url){

    //Invoke the OpenOffice.org service manager
    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //print_r($export_args);
    //Write out the PDF
    $oWriterDoc->storeToURL($output_url,$export_args);
    $oWriterDoc->close(true);
    }

    $output_dir = "C:/wamp/www/projectfolder/";
    $doc_file = "C:/wamp/www/projectfolder/wordfile.docx";
    $pdf_file = "outputfile_name.pdf";

    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;
    word2pdf($doc_file,$output_file);
    ?>

What does an exclamation mark mean in the Swift language?

The entire story begins with a feature of swift called optional vars. These are the vars which may have a value or may not have a value. In general swift doesn't allow us to use a variable which isn't initialised, as this may lead to crashes or unexpected reasons and also server a placeholder for backdoors. Thus in order to declare a variable whose value isn't initially determined we use a '?'. When such a variable is declared, to use it as a part of some expression one has to unwrap them before use, unwrapping is an operation through which value of a variable is discovered this applies to objects. Without unwrapping if you try to use them you will have compile time error. To unwrap a variable which is an optional var, exclamation mark "!" is used.

Now there are times when you know that such optional variables will be assigned values by system for example or your own program but sometime later , for example UI outlets, in such situation instead of declaring an optional variable using a question mark "?" we use "!".

Thus system knows that this variable which is declared with "!" is optional right now and has no value but will receive a value in later in its lifetime.

Thus exclamation mark holds two different usages, 1. To declare a variable which will be optional and will receive value definitely later 2. To unwrap an optional variable before using it in an expression.

Above descriptions avoids too much of technical stuff, i hope.

Consistency of hashCode() on a Java string

As said above, in general you should not rely on the hash code of a class remaining the same. Note that even subsequent runs of the same application on the same VM may produce different hash values. AFAIK the Sun JVM's hash function calculates the same hash on every run, but that's not guaranteed.

Note that this is not theoretical. The hash function for java.lang.String was changed in JDK1.2 (the old hash had problems with hierarchical strings like URLs or file names, as it tended to produce the same hash for strings which only differed at the end).

java.lang.String is a special case, as the algorithm of its hashCode() is (now) documented, so you can probably rely on that. I'd still consider it bad practice. If you need a hash algorithm with special, documented properties, just write one :-).

How to obtain the location of cacerts of the default java installation?

In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts

How can I get the browser's scrollbar sizes?

With jquery (only tested in firefox):

function getScrollBarHeight() {
    var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
    $('body').append(jTest);
    var h = jTest.innerHeight();
    jTest.css({
        overflow: 'auto',
        width: '200px'
    });
    var h2 = jTest.innerHeight();
    return h - h2;
}

function getScrollBarWidth() {
    var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
    $('body').append(jTest);
    var w = jTest.innerWidth();
    jTest.css({
        overflow: 'auto',
        height: '200px'
    });
    var w2 = jTest.innerWidth();
    return w - w2;
}

But I actually like @Steve's answer better.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

Floating point vs integer calculations on modern hardware

TIL This varies (a lot). Here are some results using gnu compiler (btw I also checked by compiling on machines, gnu g++ 5.4 from xenial is a hell of a lot faster than 4.6.3 from linaro on precise)

Intel i7 4700MQ xenial

short add: 0.822491
short sub: 0.832757
short mul: 1.007533
short div: 3.459642
long add: 0.824088
long sub: 0.867495
long mul: 1.017164
long div: 5.662498
long long add: 0.873705
long long sub: 0.873177
long long mul: 1.019648
long long div: 5.657374
float add: 1.137084
float sub: 1.140690
float mul: 1.410767
float div: 2.093982
double add: 1.139156
double sub: 1.146221
double mul: 1.405541
double div: 2.093173

Intel i3 2370M has similar results

short add: 1.369983
short sub: 1.235122
short mul: 1.345993
short div: 4.198790
long add: 1.224552
long sub: 1.223314
long mul: 1.346309
long div: 7.275912
long long add: 1.235526
long long sub: 1.223865
long long mul: 1.346409
long long div: 7.271491
float add: 1.507352
float sub: 1.506573
float mul: 2.006751
float div: 2.762262
double add: 1.507561
double sub: 1.506817
double mul: 1.843164
double div: 2.877484

Intel(R) Celeron(R) 2955U (Acer C720 Chromebook running xenial)

short add: 1.999639
short sub: 1.919501
short mul: 2.292759
short div: 7.801453
long add: 1.987842
long sub: 1.933746
long mul: 2.292715
long div: 12.797286
long long add: 1.920429
long long sub: 1.987339
long long mul: 2.292952
long long div: 12.795385
float add: 2.580141
float sub: 2.579344
float mul: 3.152459
float div: 4.716983
double add: 2.579279
double sub: 2.579290
double mul: 3.152649
double div: 4.691226

DigitalOcean 1GB Droplet Intel(R) Xeon(R) CPU E5-2630L v2 (running trusty)

short add: 1.094323
short sub: 1.095886
short mul: 1.356369
short div: 4.256722
long add: 1.111328
long sub: 1.079420
long mul: 1.356105
long div: 7.422517
long long add: 1.057854
long long sub: 1.099414
long long mul: 1.368913
long long div: 7.424180
float add: 1.516550
float sub: 1.544005
float mul: 1.879592
float div: 2.798318
double add: 1.534624
double sub: 1.533405
double mul: 1.866442
double div: 2.777649

AMD Opteron(tm) Processor 4122 (precise)

short add: 3.396932
short sub: 3.530665
short mul: 3.524118
short div: 15.226630
long add: 3.522978
long sub: 3.439746
long mul: 5.051004
long div: 15.125845
long long add: 4.008773
long long sub: 4.138124
long long mul: 5.090263
long long div: 14.769520
float add: 6.357209
float sub: 6.393084
float mul: 6.303037
float div: 17.541792
double add: 6.415921
double sub: 6.342832
double mul: 6.321899
double div: 15.362536

This uses code from http://pastebin.com/Kx8WGUfg as benchmark-pc.c

g++ -fpermissive -O3 -o benchmark-pc benchmark-pc.c

I've run multiple passes, but this seems to be the case that general numbers are the same.

One notable exception seems to be ALU mul vs FPU mul. Addition and subtraction seem trivially different.

Here is the above in chart form (click for full size, lower is faster and preferable):

Chart of above data

Update to accomodate @Peter Cordes

https://gist.github.com/Lewiscowles1986/90191c59c9aedf3d08bf0b129065cccc

i7 4700MQ Linux Ubuntu Xenial 64-bit (all patches to 2018-03-13 applied)
    short add: 0.773049
    short sub: 0.789793
    short mul: 0.960152
    short div: 3.273668
      int add: 0.837695
      int sub: 0.804066
      int mul: 0.960840
      int div: 3.281113
     long add: 0.829946
     long sub: 0.829168
     long mul: 0.960717
     long div: 5.363420
long long add: 0.828654
long long sub: 0.805897
long long mul: 0.964164
long long div: 5.359342
    float add: 1.081649
    float sub: 1.080351
    float mul: 1.323401
    float div: 1.984582
   double add: 1.081079
   double sub: 1.082572
   double mul: 1.323857
   double div: 1.968488
AMD Opteron(tm) Processor 4122 (precise, DreamHost shared-hosting)
    short add: 1.235603
    short sub: 1.235017
    short mul: 1.280661
    short div: 5.535520
      int add: 1.233110
      int sub: 1.232561
      int mul: 1.280593
      int div: 5.350998
     long add: 1.281022
     long sub: 1.251045
     long mul: 1.834241
     long div: 5.350325
long long add: 1.279738
long long sub: 1.249189
long long mul: 1.841852
long long div: 5.351960
    float add: 2.307852
    float sub: 2.305122
    float mul: 2.298346
    float div: 4.833562
   double add: 2.305454
   double sub: 2.307195
   double mul: 2.302797
   double div: 5.485736
Intel Xeon E5-2630L v2 @ 2.4GHz (Trusty 64-bit, DigitalOcean VPS)
    short add: 1.040745
    short sub: 0.998255
    short mul: 1.240751
    short div: 3.900671
      int add: 1.054430
      int sub: 1.000328
      int mul: 1.250496
      int div: 3.904415
     long add: 0.995786
     long sub: 1.021743
     long mul: 1.335557
     long div: 7.693886
long long add: 1.139643
long long sub: 1.103039
long long mul: 1.409939
long long div: 7.652080
    float add: 1.572640
    float sub: 1.532714
    float mul: 1.864489
    float div: 2.825330
   double add: 1.535827
   double sub: 1.535055
   double mul: 1.881584
   double div: 2.777245

How does cellForRowAtIndexPath work?

1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

2)NSIndexPath is essentially two things-

  • Your Section
  • Your row

Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

from superuser accepted answer:

sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
exit;

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

use IDENTITY(1,1) while creating the table eg

CREATE TABLE SAMPLE(
[Id]     [int]  IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,

CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
)

phpMyAdmin + CentOS 6.0 - Forbidden

Non of the above mentioned solutions worked for me. Below is what finally worked:

#yum update
#yum install phpmyadmin

Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.

After this, going to the browser, I got an error that said ./config.inic.php can't be accessed

#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php

This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.

Remember to restart httpd.

#service httpd restart

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

Leave only two decimal places after the dot

You can use this

"String.Format("{0:F2}", String Value);"

Gives you only the two digits after Dot, exactly two digits.

Calculate cosine similarity given 2 sentence strings

Thanks @vpekar for your implementation. It helped a lot. I just found that it misses the tf-idf weight while calculating the cosine similarity. The Counter(word) returns a dictionary which has the list of words along with their occurence.

cos(q, d) = sim(q, d) = (q · d)/(|q||d|) = (sum(qi, di)/(sqrt(sum(qi2)))*(sqrt(sum(vi2))) where i = 1 to v)

  • qi is the tf-idf weight of term i in the query.
  • di is the tf-idf
  • weight of term i in the document. |q| and |d| are the lengths of q and d.
  • This is the cosine similarity of q and d . . . . . . or, equivalently, the cosine of the angle between q and d.

Please feel free to view my code here. But first you will have to download the anaconda package. It will automatically set you python path in Windows. Add this python interpreter in Eclipse.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Laravel stylesheets and javascript don't load for non-base routes

Laravel 5.4 with mix helper:

<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}"> </script>

Python Pandas: Get index of rows which column matches certain value

df.iloc[i] returns the ith row of df. i does not refer to the index label, i is a 0-based index.

In contrast, the attribute index returns actual index labels, not numeric row-indices:

df.index[df['BoolCol'] == True].tolist()

or equivalently,

df.index[df['BoolCol']].tolist()

You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:

df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
       index=[10,20,30,40,50])

In [53]: df
Out[53]: 
   BoolCol
10    True
20   False
30   False
40    True
50    True

[5 rows x 1 columns]

In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]

If you want to use the index,

In [56]: idx = df.index[df['BoolCol']]

In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')

then you can select the rows using loc instead of iloc:

In [58]: df.loc[idx]
Out[58]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

Note that loc can also accept boolean arrays:

In [55]: df.loc[df['BoolCol']]
Out[55]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

If you have a boolean array, mask, and need ordinal index values, you can compute them using np.flatnonzero:

In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])

Use df.iloc to select rows by ordinal index:

In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]: 
   BoolCol
10    True
40    True
50    True

Remove duplicated rows

The function distinct() in the dplyr package performs arbitrary duplicate removal, either from specific columns/variables (as in this question) or considering all columns/variables. dplyr is part of the tidyverse.

Data and package

library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))

Remove rows duplicated in a specific column (e.g., columna)

Note that .keep_all = TRUE retains all columns, otherwise only column a would be retained.

distinct(dat, a, .keep_all = TRUE)

  a b
1 1 A
2 2 B

Remove rows that are complete duplicates of other rows:

distinct(dat)

  a b
1 1 A
2 2 B
3 1 C
4 2 D

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

Which exception should I raise on bad/illegal argument combinations in Python?

I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:

$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

Our junior dev just found this page in a google search for "python exception wrong arguments" and I'm surprised that the obvious (to me) answer wasn't ever suggested in the decade since this question was asked.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

For imported maven project and JDK 1.7 do the following:

  1. Delete project from Eclipse (keep files)
  2. Delete .settings directory, .project and .classpath files inside your project directory.
  3. Modify your pom.xml file, add following properties (make sure following settings are not overridden by explicit maven-compiler-plugin definition in your POM)

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    
  4. Import updated project into Eclipse.

How to output oracle sql result into a file in windows?

Having the same chore on windows 10, and windows server 2012. I found the following solution:

echo quit |sqlplus schemaName/schemaPassword@sid @plsqlScript.sql > outputFile.log

Explanation

echo quit | send the quit command to exit sqlplus after the script completes

sqlplus schemaName/schemaPassword@sid @plsqlScript.sql execute plssql script plsqlScript.sql in schema schemaName with password schemaPassword connecting to SID sid

> outputFile.log redirect sqlplus output to log file outputFile.log

Download history stock prices automatically from yahoo finance in python

Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.

Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Is there a way to collapse all code blocks in Eclipse?

If you always want the code collapsed by default, go to Windows > Preferences. Search for "folding". Then check all the items under "Initially fold these elements".

enter image description here

How to cancel a local git commit

You can tell Git what to do with your index (set of files that will become the next commit) and working directory when performing git reset by using one of the parameters:

--soft: Only commits will be reseted, while Index and the working directory are not altered.

--mixed: This will reset the index to match the HEAD, while working directory will not be touched. All the changes will stay in the working directory and appear as modified.

--hard: It resets everything (commits, index, working directory) to match the HEAD.

In your case, I would use git reset --soft to keep your modified changes in Index and working directory. Be sure to check this out for a more detailed explanation.

"Repository does not have a release file" error

This problem is probably from your /etc/apt/sources.list as others mentioned but there is chance that the problem is with your hard disk. I solved the same issue by cleaning up some space.

When you don't have enough space on your hard disk, updating your machine won't occur until you delete some files.

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

Update ViewPager dynamically?

I had been trying so many different approaches, none really sove my problem. Below are how I solve it with a mix of solutions provided by you all. Thanks everyone.

class PagerAdapter extends FragmentPagerAdapter {

    public boolean flag_refresh=false;

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int page) {
        FragmentsMain f;
        f=new FragmentsMain();
        f.page=page;
        return f;
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public int getItemPosition(Object item) {
        int page= ((FragmentsMain)item).page;

        if (page == 0 && flag_refresh) {
            flag_refresh=false;
            return POSITION_NONE;
        } else {
            return super.getItemPosition(item);
        }
    }

    @Override
    public void destroyItem(View container, int position, Object object) {

        ((ViewPager) container).removeView((View) object);
    }
}

I only want to refresh page 0 after onResume().

 adapter=new PagerAdapter(getSupportFragmentManager());
 pager.setAdapter(adapter);

@Override
protected void onResume() {
    super.onResume();

    if (adapter!=null) {
        adapter.flag_refresh=true;
        adapter.notifyDataSetChanged();
    }
}

In my FragmentsMain, there is public integer "page", which can tell me whether it is the page I want to refresh.

public class FragmentsMain extends Fragment {

private Cursor cursor;
private static Context context;
public int page=-1;

Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
        pb.directory(dir);
        Process p = pb.start();

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

What is the best (idiomatic) way to check the type of a Python variable?

isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses.

For example:

 >>> class a_dict(dict):
 ...     pass
 ... 
 >>> type(a_dict()) == type(dict())
 False
 >>> isinstance(a_dict(), dict)
 True
 >>> 

Of course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it.

.prop() vs .attr()

Update 1 November 2012

My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr() to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr().

Original answer

If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

I'll summarize the main issues:

  • You usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.

If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.

As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:

<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">

So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}

This is actually the simplest thing in the world to do with the checked Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:

if (document.getElementById("cb").checked) {...}

The property also makes checking or unchecking the checkbox trivial:

document.getElementById("cb").checked = false

In jQuery 1.6, this unambiguously becomes

$("#cb").prop("checked", false)

The idea of using the checked attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checked attribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See http://jsfiddle.net/VktA6/49/.

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

Android - how to replace part of a string by another string?

You're doing only one mistake.

use replaceAll() function over there.

e.g.

String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );

Generating a random hex color code with PHP

I think this would be good as well it gets any color available

$color= substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6);

JTable won't show column headers

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you

Java switch statement multiple cases

The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Javascript/jQuery detect if input is focused

With pure javascript:

this === document.activeElement // where 'this' is a dom object

or with jquery's :focus pseudo selector.

$(this).is(':focus');

Defining and using a variable in batch file

input location.bat

@echo off
cls

set /p "location"="bob"
echo We're working with %location%
pause

output

We're working with bob

(mistakes u done : space and " ")

How to make Git "forget" about a file that was tracked but is now in .gitignore?

Especially for the IDE based files, I use this:

For instance the slnx.sqlite, I just got rid off it completely like following:

git rm {PATH_OF_THE_FILE}/slnx.sqlite -f
git commit -m "remove slnx.sqlite"

Just keep that in mind that some of those files stores some local user settings and preferences for projects (like what files you had open). So every time you navigate or do some changes in your IDE, that file is changed and therefore it checks it out and show as there are uncommitted changes.

How to pass the -D System properties while testing on Eclipse?

Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. -Dkey=value.

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

Angular 2 Scroll to bottom (Chat style)

In case anyone has this problem with Angular 9, this is how I manage to fix it.

I started with the solution with #scrollMe [scrollTop]="scrollMe.scrollHeight" and I got the ExpressionChangedAfterItHasBeenCheckedError error as people mentioned.

In order to fix this one I just add in my ts component:

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
...})

 constructor(private cdref: ChangeDetectorRef) {}

 ngAfterContentChecked() {
        this.cdref.detectChanges();
    }

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

How to efficiently count the number of keys/properties of an object in JavaScript?

Here are some performance tests for three methods;

https://jsperf.com/get-the-number-of-keys-in-an-object

Object.keys().length

20,735 operations per second

Very simple and compatible. Runs fast but expensive because it creates a new array of keys, which that then gets thrown away.

return Object.keys(objectToRead).length;

loop through the keys

15,734 operations per second

let size=0;
for(let k in objectToRead) {
  size++
}
return size;

Slightly slower, but nowhere near the memory usage, so probably better if you're interested in optimising for mobile or other small machines

Using Map instead of Object

953,839,338 operations per second

return mapToRead.size;

Basically, Map tracks its own size so we're just returning a number field. Far, far faster than any other method. If you have control of the object, convert them to maps instead.

Is it valid to define functions in JSON results?

JSON explicitly excludes functions because it isn't meant to be a JavaScript-only data structure (despite the JS in the name).

How to make Java work with SQL Server?

Maybe a little late, but using different drivers altogether is overkill for a case of user error:

db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );

should be either one of these:

db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );

(using named pipe) or:

db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );

using port number directly; you can leave out 1433 because it's the default port, leaving:

db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

WampServer orange icon

I ran into this same problem this morning but none of the answers above provided me with the solution.

I realised eventually that my issue was because I had changed the DocumentRoot to a subfolder of the www directory, as I had previously been running a Symfony2 project inside www.

With the new project I am working on inside www, that old DocumentRoot dir did not exist any more so Apache failed to start.

wampserver -> Apache -> httpd.conf, then look for "DocumentRoot" and make sure the directory it points to exists or else change it to one that does.

Thank you to RiggsFolly, it was because of your hint about the Event Viewer above that I found the issue.

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

Thread pooling in C++11

This is copied from my answer to another very similar post, hope it can help:

1) Start with maximum number of threads a system can support:

int Num_Threads =  thread::hardware_concurrency();

2) For an efficient threadpool implementation, once threads are created according to Num_Threads, it's better not to create new ones, or destroy old ones (by joining). There will be performance penalty, might even make your application goes slower than the serial version.

Each C++11 thread should be running in their function with an infinite loop, constantly waiting for new tasks to grab and run.

Here is how to attach such function to the thread pool:

int Num_Threads = thread::hardware_concurrency();
vector<thread> Pool;
for(int ii = 0; ii < Num_Threads; ii++)
{  Pool.push_back(thread(Infinite_loop_function));}

3) The Infinite_loop_function

This is a "while(true)" loop waiting for the task queue

void The_Pool:: Infinite_loop_function()
{
    while(true)
    {
        {
            unique_lock<mutex> lock(Queue_Mutex);

            condition.wait(lock, []{return !Queue.empty() || terminate_pool});
            Job = Queue.front();
            Queue.pop();
        }
        Job(); // function<void()> type
    }
};

4) Make a function to add job to your Queue

void The_Pool:: Add_Job(function<void()> New_Job)
{
    {
        unique_lock<mutex> lock(Queue_Mutex);
        Queue.push(New_Job);
    }
    condition.notify_one();
}

5) Bind an arbitrary function to your Queue

Pool_Obj.Add_Job(std::bind(&Some_Class::Some_Method, &Some_object));

Once you integrate these ingredients, you have your own dynamic threading pool. These threads always run, waiting for job to do.

I apologize if there are some syntax errors, I typed these code and and I have a bad memory. Sorry that I cannot provide you the complete thread pool code, that would violate my job integrity.

Edit: to terminate the pool, call the shutdown() method:

XXXX::shutdown(){
{
    unique_lock<mutex> lock(threadpool_mutex);
    terminate_pool = true;} // use this flag in condition.wait

    condition.notify_all(); // wake up all threads.

    // Join all threads.
    for(std::thread &every_thread : thread_vector)
    {   every_thread.join();}

    thread_vector.clear();  
    stopped = true; // use this flag in destructor, if not set, call shutdown() 
}

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

RegEx to parse or validate Base64 data

From the RFC 4648:

Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

adding child nodes in treeview

void treeView(string [] LineString)
    {
        int line = LineString.Length;
        string AssmMark = "";
        string PartMark = "";
        TreeNode aNode;
        TreeNode pNode;
        for ( int i=0 ; i<line ; i++){
            string sLine = LineString[i];
            if ( sLine.StartsWith("ASSEMBLY:") ){
                sLine  = sLine.Replace("ASSEMBLY:","");
                string[] aData = sLine.Split(new char[] {','});
                AssmMark  = aData[0].Trim();
                //TreeNode aNode;
                //aNode = new TreeNode(AssmMark);
                treeView1.Nodes.Add(AssmMark,AssmMark);
            }
            if( sLine.Trim().StartsWith("PART:") ){
                sLine  = sLine.Replace("PART:","");
                string[] pData = sLine.Split(new char[] {','});
                PartMark = pData[0].Trim();
                pNode = new TreeNode(PartMark);
                treeView1.Nodes[AssmMark].Nodes.Add(pNode);
            }
        }

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

Remote Linux server to remote linux server dir copy. How?

Log in to one machine

$ scp -r /path/to/top/directory user@server:/path/to/copy

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

How can I wrap text in a label using WPF?

try use this

lblresult.Content = lblresult.Content + "prime are :" + j + "\n";

Length of a JavaScript object

Simple one liner:

_x000D_
_x000D_
console.log(Object.values({id:"1",age:23,role_number:90}).length);
_x000D_
_x000D_
_x000D_

How to identify server IP address in PHP

Like this:

$_SERVER['SERVER_ADDR'];

Only local connections are allowed Chrome and Selenium webdriver

  1. Check the version of your installed Chrome browser.

  2. Download the compatible version of ChromeDriver from

    https://sites.google.com/a/chromium.org/chromedriver/

  3. Set the location of the compatible ChromeDriver to:

     System.setProperty("webdriver.chrome.driver", "C:\\Users\\your_path\\chromedriver.exe");
    
  4. Run the Test again.

It should be good now.

What does int argc, char *argv[] mean?

The parameters to main represent the command line parameters provided to the program when it was started. The argc parameter represents the number of command line arguments, and char *argv[] is an array of strings (character pointers) representing the individual arguments provided on the command line.

Get a specific bit from byte

Using BitArray class and making an extension method as OP suggests:

public static bool GetBit(this byte b, int bitNumber)
{
    System.Collections.BitArray ba = new BitArray(new byte[]{b});
    return ba.Get(bitNumber);
}

What's the difference between console.dir and console.log?

From the firebug site http://getfirebug.com/logging/

Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.

INSERT VALUES WHERE NOT EXISTS

This isn't an answer. I just want to show that IF NOT EXISTS(...) INSERT method isn't safe. You have to execute first Session #1 and then Session #2. After v #2 you will see that without an UNIQUE index you could get duplicate pairs (SoftwareName,SoftwareSystemType). Delay from session #1 is used to give you enough time to execute the second script (session #2). You could reduce this delay.

Session #1 (SSMS > New Query > F5 (Execute))

CREATE DATABASE DemoEXISTS;
GO
USE DemoEXISTS;
GO
CREATE TABLE dbo.Software(
    SoftwareID INT PRIMARY KEY,
    SoftwareName NCHAR(400) NOT NULL,  
    SoftwareSystemType NVARCHAR(50) NOT NULL
);
GO

INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (1,'Dynamics AX 2009','ERP');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (2,'Dynamics NAV 2009','SCM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (3,'Dynamics CRM 2011','CRM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (4,'Dynamics CRM 2013','CRM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (5,'Dynamics CRM 2015','CRM');
GO
/*
CREATE UNIQUE INDEX IUN_Software_SoftwareName_SoftareSystemType
ON dbo.Software(SoftwareName,SoftwareSystemType);
GO
*/

-- Session #1
BEGIN TRANSACTION;
    UPDATE  dbo.Software
    SET     SoftwareName='Dynamics CRM',
            SoftwareSystemType='CRM'    
    WHERE   SoftwareID=5;

    WAITFOR DELAY '00:00:15' -- 15 seconds delay; you have less than 15 seconds to switch SSMS window to session #2

    UPDATE  dbo.Software
    SET     SoftwareName='Dynamics AX',
            SoftwareSystemType='ERP'
    WHERE   SoftwareID=1;
COMMIT
--ROLLBACK
PRINT 'Session #1 results:';
SELECT *
FROM dbo.Software;

Session #2 (SSMS > New Query > F5 (Execute))

USE DemoEXISTS;
GO
-- Session #2
DECLARE 
    @SoftwareName NVARCHAR(100),  
    @SoftwareSystemType NVARCHAR(50);
SELECT
    @SoftwareName=N'Dynamics AX',
    @SoftwareSystemType=N'ERP';

PRINT 'Session #2 results:';
IF NOT EXISTS(SELECT *
    FROM dbo.Software s
    WHERE s.SoftwareName=@SoftwareName 
    AND s.SoftwareSystemType=@SoftwareSystemType)
BEGIN
    PRINT 'Session #2: INSERT';

    INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
    VALUES (6,@SoftwareName,@SoftwareSystemType);
END 
PRINT 'Session #2: FINISH';
SELECT  * 
FROM    dbo.Software;

Results:

Session #1 results:
SoftwareID  SoftwareName      SoftwareSystemType
----------- ----------------- ------------------
1           Dynamics AX       ERP
2           Dynamics NAV 2009 SCM
3           Dynamics CRM 2011 CRM
4           Dynamics CRM 2013 CRM
5           Dynamics CRM      CRM

Session #2 results:
Session #2: INSERT
Session #2: FINISH
SoftwareID  SoftwareName      SoftwareSystemType
----------- ----------------- ------------------
1           Dynamics AX       ERP <-- duplicate (row updated by session #1)
2           Dynamics NAV 2009 SCM
3           Dynamics CRM 2011 CRM
4           Dynamics CRM 2013 CRM
5           Dynamics CRM      CRM
6           Dynamics AX       ERP <-- duplicate (row inserted by session #2)

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Get current NSDate in timestamp format

use [[NSDate date] timeIntervalSince1970]

Get parent directory of running script

Fugly, but this will do it:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))