Programs & Examples On #Crossword

Anything related to crosswords, a kind of puzzle game where a square grid of squares is to be filled with letters forming words or phrases.

Entity Framework Provider type could not be loaded?

Same problem, but i installed EF 6 through Nuget. EntityFramework.SqlServer was missing for another executable. I simply added the nuget package to that project.

Defining a variable with or without export

Two of the creators of UNIX, Brian Kernighan and Rob Pike, explain this in their book "The UNIX Programming Environment". Google for the title and you'll easily find a pdf version.

They address shell variables in section 3.6, and focus on the use of the export command at the end of that section:

When you want to make the value of a variable accessible in sub-shells, the shell's export command should be used. (You might think about why there is no way to export the value of a variable from a sub-shell to its parent).

How to use LogonUser properly to impersonate domain user from workgroup client

this works for me, full working example (I wish more people would do this):

//logon impersonation
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute

...

class Program {

    // obtains user token
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    // closes open handes returned by LogonUser
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public void DoWorkUnderImpersonation() {
        //elevate privileges before doing file copy to handle domain security
        WindowsImpersonationContext impersonationContext = null;
        IntPtr userHandle = IntPtr.Zero;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
        string user = ConfigurationManager.AppSettings["ImpersonationUser"];
        string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

        try {
            Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);

            // if domain name was blank, assume local machine
            if (domain == "")
                domain = System.Environment.MachineName;

            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user,
                                        domain,
                                        password,
                                        LOGON32_LOGON_INTERACTIVE,
                                        LOGON32_PROVIDER_DEFAULT,
                                        ref userHandle);

            if (!loggedOn) {
                Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
                return;
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);

            Console.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);

            //run the program with elevated privileges (like file copying from a domain server)
            DoWork();

        } catch (Exception ex) {
            Console.WriteLine("Exception impersonating user: " + ex.Message);
        } finally {
            // Clean up
            if (impersonationContext != null) {
                impersonationContext.Undo();
            }

            if (userHandle != IntPtr.Zero) {
                CloseHandle(userHandle);
            }
        }
    }


    private void DoWork() {
        //everything in here has elevated privileges

        //example access files on a network share through e$ 
        string[] files = System.IO.Directory.GetFiles(@"\\domainserver\e$\images", "*.jpg");
    }
}

No provider for Http StaticInjectorError

You would need also to import the HttpClientModule from Angular '@angular/common/http' into your main AppModule for making HTTP requests.

app.module.ts

import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';

@NgModule({
   imports: [
       HttpClientModule
   ],
   providers: [
       ServiceService
   ]
})
export class AppModule {...}

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

Laravel Soft Delete posts

Just an update for Laravel 5:

In Laravel 4.2:

use Illuminate\Database\Eloquent\SoftDeletingTrait;    
class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

becomes in Laravel 5:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {

    use SoftDeletes;
    protected $dates = ['deleted_at'];

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

How do I pick randomly from an array?

myArray.sample(x) can also help you to get x random elements from the array.

Most efficient way to create a zero filled JavaScript array?

Using lodash or underscore

_.range(0, length - 1, 0);

Or if you have an array existing and you want an array of the same length

array.map(_.constant(0));

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

What is more efficient? Using pow to square or just multiply it with itself?

x*x or x*x*x will be faster than pow, since pow must deal with the general case, whereas x*x is specific. Also, you can elide the function call and suchlike.

However, if you find yourself micro-optimizing like this, you need to get a profiler and do some serious profiling. The overwhelming probability is that you would never notice any difference between the two.

How to declare a static const char* in your header file?

There is a trick you can use with templates to provide H file only constants.

(note, this is an ugly example, but works verbatim in at least in g++ 4.6.1.)

(values.hpp file)

#include <string>

template<int dummy>
class tValues
{
public:
   static const char* myValue;
};

template <int dummy> const char* tValues<dummy>::myValue = "This is a value";

typedef tValues<0> Values;

std::string otherCompUnit(); // test from other compilation unit

(main.cpp)

#include <iostream>
#include "values.hpp"

int main()
{
   std::cout << "from main: " << Values::myValue << std::endl;
   std::cout << "from other: " << otherCompUnit() << std::endl;
}

(other.cpp)

#include "values.hpp"

std::string otherCompUnit () {
   return std::string(Values::myValue);
}

Compile (e.g. g++ -o main main.cpp other.cpp && ./main) and see two compilation units referencing the same constant declared in a header:

from main: This is a value
from other: This is a value

In MSVC, you may instead be able to use __declspec(selectany)

For example:

__declspec(selectany) const char* data = "My data";

When to use StringBuilder in Java

The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.

However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)

How can I create a text box for a note in markdown?

With GitHub, I usually insert a blockquote.

> **_NOTE:_**  The note content.

becomes...

NOTE: The note content.

Of course, there is always plain HTML...

Check if a given time lies between two times regardless of date

There are lots of answers here but I want to provide a new one which is similar with Basil Bourque's answer but with a full code example. So please see the method below:

private static void checkTime(String startTime, String endTime, String checkTime) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
    LocalTime startLocalTime = LocalTime.parse(startTime, formatter);
    LocalTime endLocalTime = LocalTime.parse(endTime, formatter);
    LocalTime checkLocalTime = LocalTime.parse(checkTime, formatter);

    boolean isInBetween = false;
    if (endLocalTime.isAfter(startLocalTime)) {
      if (startLocalTime.isBefore(checkLocalTime) && endLocalTime.isAfter(checkLocalTime)) {
          isInBetween = true;
      }
    } else if (checkLocalTime.isAfter(startLocalTime) || checkLocalTime.isBefore(endLocalTime)) {
        isInBetween = true;
    }

    if (isInBetween) {
        System.out.println("Is in between!");
    } else {
        System.out.println("Is not in between!");
    }
}

Either if you are calling this method using:

checkTime("20:11:13", "14:49:00", "01:00:00");

Or using:

checkTime("20:11:13", "14:49:00", "05:00:00");

The result will be:

Is in between!

Write string to output stream

By design it is to be done this way:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

I had the exact same error but in my case, the problem was the result of having rebuilt Apache after an upgrade to the PHP version. Long story short, I forgot to install the Apache module 'suexec'.

It had nothing to do with group or ownership. That only took me two days to figure out, someone shoot me...

Set background image on grid in WPF using C#

I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.

  ImageBrush myBrush = new ImageBrush();
  Image image = new Image();
  image.Source = new BitmapImage(
      new Uri(
         "pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
  myBrush.ImageSource = image.Source;
  Grid grid = new Grid();
  grid.Background = myBrush;          

C#: How would I get the current time into a string?

string t = DateTime.Now.ToString("h/m/s tt");
string t2 = DateTime.Now.ToString("hh:mm:ss tt");
string d = DateTime.Now.ToString("MM/dd/yy");

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

Entity framework linq query Include() multiple children entities

How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

There is no other way - except implementing lazy loading.

Or manual loading....

myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...

How to calculate age (in years) based on Date of Birth and getDate()

You need to consider the way the datediff command rounds.

SELECT CASE WHEN dateadd(year, datediff (year, DOB, getdate()), DOB) > getdate()
            THEN datediff(year, DOB, getdate()) - 1
            ELSE datediff(year, DOB, getdate())
       END as Age
FROM <table>

Which I adapted from here.

Note that it will consider 28th February as the birthday of a leapling for non-leap years e.g. a person born on 29 Feb 2020 will be considered 1 year old on 28 Feb 2021 instead of 01 Mar 2021.

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

PostgreSQL psql terminal command

psql --pset=format=FORMAT

Great for executing queries from command line, e.g.

psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.

How to display list of repositories from subversion server

If you know your way around Java, you can use SvnKit to do browse, search and God knows what with your Subversion server.

After that, you can package your program and invoke it either via an Ant task or a shell script.

It's quite a "brute force" solution, but once you master SvnKit, you can really do lots of cool things.

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

HTTP status code 0 - Error Domain=NSURLErrorDomain?

The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.

List of HTTP status codes

How to print_r $_POST array?

Came across this 'implode' recently.

May be useful to output arrays. http://in2.php.net/implode

echo 'Variables: ' . implode( ', ', $_POST);

Angularjs $http post file and form data

I had similar problem when had to upload file and send user token info at the same time. transformRequest along with forming FormData helped:

        $http({
            method: 'POST',
            url: '/upload-file',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                email: Utils.getUserInfo().email,
                token: Utils.getUserInfo().token,
                upload: $scope.file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }
        })
        .success(function (data) {

        })
        .error(function (data, status) {

        });

For getting file $scope.file I used custom directive:

app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
});

Html:

<input type="file" file="file" required />

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

jquery json to string?

Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.

Grab the json2.js file from: https://github.com/douglascrockford/JSON-js


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

Pure Javascript listen to input value change

Another approach in 2020 could be using document.querySelector():

const myInput = document.querySelector('input[name="exampleInput"]');

myInput.addEventListener("change", (e) => {
  // here we do something
});

vba error handling in loop

I do not want to craft special error handlers for every loop structure in my code so I have a way of finding problem loops using my standard error handler so that I can then write a special error handler for them.

If an error occurs in a loop, I normally want to know about what caused the error rather than just skip over it. To find out about these errors, I write error messages to a log file as many people do. However writing to a log file is dangerous if an error occurs in a loop as the error can be triggered for every time the loop iterates and in my case 80 000 iterations is not uncommon. I have therefore put some code into my error logging function that detects identical errors and skips writing them to the error log.

My standard error handler that is used on every procedure looks like this. It records the error type, procedure the error occurred in and any parameters the procedure received (FileType in this case).

procerr:
    Call NewErrorLog(Err.number, Err.Description, "GetOutputFileType", FileType)
    Resume exitproc

My error logging function which writes to a table (I am in ms-access) is as follows. It uses static variables to retain the previous values of error data and compare them to current versions. The first error is logged, then the second identical error pushes the application into debug mode if I am the user or if in other user mode, quits the application.

Public Function NewErrorLog(ErrCode As Variant, ErrDesc As Variant, Optional Source As Variant = "", Optional ErrData As Variant = Null) As Boolean
On Error GoTo errLogError

    'Records errors from application code
    Dim dbs As Database
    Dim rst As Recordset

    Dim ErrorLogID As Long
    Dim StackInfo As String
    Dim MustQuit As Boolean
    Dim i As Long

    Static ErrCodeOld As Long
    Static SourceOld As String
    Static ErrDataOld As String

    'Detects errors that occur in loops and records only the first two.
    If Nz(ErrCode, 0) = ErrCodeOld And Nz(Source, "") = SourceOld And Nz(ErrData, "") = ErrDataOld Then
        NewErrorLog = True
        MsgBox "Error has occured in a loop: " & Nz(ErrCode, 0) & Space(1) & Nz(ErrDesc, "") & ": " & Nz(Source, "") & "[" & Nz(ErrData, "") & "]", vbExclamation, Appname
        If Not gDeveloping Then  'Allow debugging
            Stop
            Exit Function
        Else
            ErrDesc = "[loop]" & Nz(ErrDesc, "")  'Flag this error as coming from a loop
            MsgBox "Error has been logged, now Quiting", vbInformation, Appname
            MustQuit = True  'will Quit after error has been logged
        End If
    Else
        'Save current values to static variables
        ErrCodeOld = Nz(ErrCode, 0)
        SourceOld = Nz(Source, "")
        ErrDataOld = Nz(ErrData, "")
    End If

    'From FMS tools pushstack/popstack - tells me the names of the calling procedures
    For i = 1 To UBound(mCallStack)
        If Len(mCallStack(i)) > 0 Then StackInfo = StackInfo & "\" & mCallStack(i)
    Next

    'Open error table
    Set dbs = CurrentDb()
    Set rst = dbs.OpenRecordset("tbl_ErrLog", dbOpenTable)

    'Write the error to the error table
    With rst
        .AddNew
        !ErrSource = Source
        !ErrTime = Now()
        !ErrCode = ErrCode
        !ErrDesc = ErrDesc
        !ErrData = ErrData
        !StackTrace = StackInfo
        .Update
        .BookMark = .LastModified
        ErrorLogID = !ErrLogID
    End With


    rst.Close: Set rst = Nothing
    dbs.Close: Set dbs = Nothing
    DoCmd.Hourglass False
    DoCmd.Echo True
    DoEvents
    If MustQuit = True Then DoCmd.Quit

exitLogError:
    Exit Function

errLogError:
    MsgBox "An error occured whilst logging the details of another error " & vbNewLine & _
    "Send details to Developer: " & Err.number & ", " & Err.Description, vbCritical, "Please e-mail this message to developer"
    Resume exitLogError

End Function

Note that an error logger has to be the most bullet proofed function in your application as the application cannot gracefully handle errors in the error logger. For this reason, I use NZ() to make sure that nulls cannot sneak in. Note that I also add [loop] to the second identical error so that I know to look in the loops in the error procedure first.

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Try this:

use POSIX qw/strftime/;
print strftime('%Y-%m-%d',localtime);

the strftime method does the job effectively for me. Very simple and efficient.


How do you manually execute SQL commands in Ruby On Rails using NuoDB

Reposting the answer from our forum to help others with a similar issue:

@connection = ActiveRecord::Base.connection
result = @connection.exec_query('select tablename from system.tables')
result.each do |row|
puts row
end

How to set image in imageview in android?

The images your put into res/drawable are handled by Android. There is no need for you to get the image the way you did. in your case you could simply call iv.setImageRessource(R.drawable.apple)

to just get the image (and not adding it to the ImageView directly), you can call Context.getRessources().getDrawable(R.drawable.apple) to get the image

Safely limiting Ansible playbooks to a single machine?

This shows how to run the playbooks on the target server itself.

This is a bit trickier if you want to use a local connection. But this should be OK if you use a variable for the hosts setting and in the hosts file create a special entry for localhost.

In (all) playbooks have the hosts: line set to:

- hosts: "{{ target | default('no_hosts')}}"

In the inventory hosts file add an entry for the localhost which sets the connection to be local:

[localhost]
127.0.0.1  ansible_connection=local

Then on the command line run commands explicitly setting the target - for example:

$ ansible-playbook --extra-vars "target=localhost" test.yml

This will also work when using ansible-pull:

$ ansible-pull -U <git-repo-here> -d ~/ansible --extra-vars "target=localhost" test.yml

If you forget to set the variable on the command line the command will error safely (as long as you've not created a hosts group called 'no_hosts'!) with a warning of:

skipping: no hosts matched

And as mentioned above you can target a single machine (as long as it is in your hosts file) with:

$ ansible-playbook --extra-vars "target=server.domain" test.yml

or a group with something like:

$ ansible-playbook --extra-vars "target=web-servers" test.yml

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

jQuery validate: How to add a rule for regular expression validation?

we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.

<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />

therefore we use the following snippet

$.validator.addMethod(
        "regex",
        function(value, element, regstring) {
            // fast exit on empty optional
            if (this.optional(element)) {
                return true;
            }

            var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
            if (regParts) {
                // the parsed pattern had delimiters and modifiers. handle them. 
                var regexp = new RegExp(regParts[1], regParts[2]);
            } else {
                // we got pattern string without delimiters
                var regexp = new RegExp(regstring);
            }

            return regexp.test(value);
        },
        "Please check your input."
);  

Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).

PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js

How to get function parameter names/values dynamically?

You can access the argument values passed to a function using the "arguments" property.

    function doSomething()
    {
        var args = doSomething.arguments;
        var numArgs = args.length;
        for(var i = 0 ; i < numArgs ; i++)
        {
            console.log("arg " + (i+1) + " = " + args[i]);  
                    //console.log works with firefox + firebug
                    // you can use an alert to check in other browsers
        }
    }

    doSomething(1, '2', {A:2}, [1,2,3]);    

Run Excel Macro from Outside Excel Using VBScript From Command Line

I tried the above methods but I got the "macro cannot be found" error. This is final code that worked!

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

  ' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True

'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)

' Run Macro
xlApp.Run "Sheet1.MyMacro"

xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Quit

In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.

How do I include a pipe | in my linux find -exec command?

The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).

In your example you can either choose to use your top level shell to perform the piping like so:

find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'

In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.

This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.

If you for some reason would like to invoke agrep multiple times, you can do:

find . -name 'file_*' -follow -type f \
    -printf "zcat %p | agrep -dEOE 'grep'\n" | sh

This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)

In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.

The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.

Multiple selector chaining in jQuery?

I think you might see slightly better performance by doing it this way:

$("#Create, #Edit").find(".myClass").plugin(){
    // Options
});

Javascript require() function giving ReferenceError: require is not defined

Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:

In your BrowserWindow declaration, add the following webPreferences field: i.e, instead of plain mainWindow = new BrowserWindow(), write

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });

MySQL - Make an existing Field Unique

If you also want to name the constraint, use this:

ALTER TABLE myTable
  ADD CONSTRAINT constraintName 
    UNIQUE (columnName);

Read url to string in few lines of java code

Additional example using Guava:

URL xmlData = ...
String data = Resources.toString(xmlData, Charsets.UTF_8);

Using LIKE in an Oracle IN clause

select * from tbl
 where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))

how to merge 200 csv files in Python

Here is a script:

  • Concatenating csv files named SH1.csv to SH200.csv
  • Keeping the headers
import glob
import re

# Looking for filenames like 'SH1.csv' ... 'SH200.csv'
pattern = re.compile("^SH([1-9]|[1-9][0-9]|1[0-9][0-9]|200).csv$")
file_parts = [name for name in glob.glob('*.csv') if pattern.match(name)]

with open("file_merged.csv","wb") as file_merged:
    for (i, name) in enumerate(file_parts):
        with open(name, "rb") as file_part:
            if i != 0:
                next(file_part) # skip headers if not first file
            file_merged.write(file_part.read())

Get product id and product type in magento?

Item collection.

$_item->product_type;
$_item->getId()

Product :

$product->getTypeId();
$product->getId()

What is cURL in PHP?

Php curl function (POST,GET,DELETE,PUT)

function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if($method == 'POST'){
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    if($json == true){
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
    }else{
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    if($ssl == false){
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    // curl_setopt($ch, CURLOPT_HEADER, 0);     
    $r = curl_exec($ch);    
    if (curl_error($ch)) {
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        print_r('Error: ' . $err . ' Status: ' . $statusCode);
        // Add error
        $this->error = $err;
    }
    curl_close($ch);
    return $r;
}

"Could not load type [Namespace].Global" causing me grief

One situation I've encountered which caused this problem is when you specify the platform for a build through "Build Configuration".

If you specify x86 as your build platform, visual studio will automatically assign bin/x86/Debug as your output directory for this project. This is perfectly valid for other project types, except for web applications where ASP.NET expects the assemblies to be output to the Bin folder.

What I found in my situation was that they were being output to both (Bin and Bin/x86/Debug), with the exception that some of the dll's, and inexplicably the most important one being your web application dll, being missing from the Bin folder.

This obviously caused a compilation problem and hence the "Could not load type Global" exception. Cleaning the solution and deleting the assemblies made no difference to subsequent builds. My solution was to just change the output path in project settings for the web app to Bin (rather than bin/x86/Debug).

Get name of object or class

Get your object's constructor function and then inspect its name property.

myObj.constructor.name

Returns "myClass".

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Sum across multiple columns with dplyr

I encounter this problem often, and the easiest way to do this is to use the apply() function within a mutate command.

library(tidyverse)
df=data.frame(
  x1=c(1,0,0,NA,0,1,1,NA,0,1),
  x2=c(1,1,NA,1,1,0,NA,NA,0,1),
  x3=c(0,1,0,1,1,0,NA,NA,0,1),
  x4=c(1,0,NA,1,0,0,NA,0,0,1),
  x5=c(1,1,NA,1,1,1,NA,1,0,1))

df %>%
  mutate(sum = select(., x1:x5) %>% apply(1, sum, na.rm=TRUE))

Here you could use whatever you want to select the columns using the standard dplyr tricks (e.g. starts_with() or contains()). By doing all the work within a single mutate command, this action can occur anywhere within a dplyr stream of processing steps. Finally, by using the apply() function, you have the flexibility to use whatever summary you need, including your own purpose built summarization function.

Alternatively, if the idea of using a non-tidyverse function is unappealing, then you could gather up the columns, summarize them and finally join the result back to the original data frame.

df <- df %>% mutate( id = 1:n() )   # Need some ID column for this to work

df <- df %>%
  group_by(id) %>%
  gather('Key', 'value', starts_with('x')) %>%
  summarise( Key.Sum = sum(value) ) %>%
  left_join( df, . )

Here I used the starts_with() function to select the columns and calculated the sum and you can do whatever you want with NA values. The downside to this approach is that while it is pretty flexible, it doesn't really fit into a dplyr stream of data cleaning steps.

How to get the python.exe location programmatically?

I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe

which gives this value on my machine:

C:\Python25\Python.exe

You just read the registry key to get the location.

However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.

React Router with optional path parameter

As with regular parameters, declaring an optional parameter is just a matter of the path property of a Route; any parameter that ends with a question mark will be treated as optional:

<Route path="to/page/:pathParam?" component={MyPage}/>

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

How to view unallocated free space on a hard disk through terminal

The simplest way to show unallocated free space in a single command:

$ sudo sfdisk --list-free /dev/sdX

(Add the --quiet option if you don't need the extra info about sector size, etc.)

Creating and Update Laravel Eloquent

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

What does mvn install in maven exactly do

The install:install goal is provided by «Apache Maven Install Plugin»:

Apache Maven Install Plugin

The Install Plugin is used during the install phase to add artifact(s) to the local repository. The Install Plugin uses the information in the POM (groupId, artifactId, version) to determine the proper location for the artifact within the local repository.

The local repository is the local cache where all artifacts needed for the build are stored. By default, it is located within the user's home directory (~/.m2/repository) but the location can be configured in ~/.m2/settings.xml using the <localRepository> element.

Apache Maven Install Plugin - Introduction.

Having said that, the exact goal purpose:

install:install is used to automatically install the project's main artifact (the JAR, WAR or EAR), its POM and any attached artifacts (sources, javadoc, etc) produced by a particular project.

Apache Maven Install Plugin - Introduction.

For additional details on the goal, please refer to the Apache Maven Install Plugin - install:install page.

For additional details on the build lifecycle in general and on which place the goal has in the build lifecycle, please refer to the Maven – Introduction to the Build Lifecycle page.

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

How to center buttons in Twitter Bootstrap 3?

<div class="container-fluid">
   <div class="col-sm-12 text-center">
       <button class="btn btn-primary" title="Submit"></button>
       <button class="btn btn-warning" title="Cancel"></button>
   </div>
</div>

"Cannot GET /" with Connect on Node.js

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

Python loop counter in a for loop

You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

Conversion from List<T> to array T[]

You can simply use ToArray() extension method

Example:

Person p1 = new Person() { Name = "Person 1", Age = 27 };
Person p2 = new Person() { Name = "Person 2", Age = 31 };

List<Person> people = new List<Person> { p1, p2 };

var array = people.ToArray();

According to Docs

The elements are copied using Array.Copy(), which is an O(n) operation, where n is Count.

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

Creating a Plot Window of a Particular Size

Use dev.new(). (See this related question.)

plot(1:10)
dev.new(width=5, height=4)
plot(1:20)

To be more specific which units are used:

dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)

edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)

For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)

What is "Advanced" SQL?

I think it's best highlighted with an example. If you feel you could write the following SQL statement quickly with little/no reference material, then I'd guess that you probably meet their Advanced SQL requirement:

DECLARE @date DATETIME
SELECT @date = '10/31/09'

SELECT
      t1.EmpName,
      t1.Region,
      t1.TourStartDate,
      t1.TourEndDate,
      t1.FOrdDate,
      FOrdType  = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderType  ELSE NULL END),
      FOrdTotal = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderTotal ELSE NULL END),
      t1.LOrdDate,
      LOrdType  = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderType  ELSE NULL END),
      LOrdTotal = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderTotal ELSE NULL END)
  FROM 
      (--Derived table t1 returns the tourdates, and the order dates
      SELECT
            e.EmpId,
            e.EmpName,
            et.Region,
            et.TourStartDate,
            et.TourEndDate,
            FOrdDate = MIN(o.OrderDate),
            LOrdDate = MAX(o.OrderDate)
        FROM #Employees e INNER JOIN #EmpTours et
          ON e.EmpId = et.EmpId INNER JOIN #Orders o
          ON e.EmpId = o.EmpId
       WHERE et.TourStartDate <= @date
         AND (et.TourEndDate > = @date OR et.TourEndDate IS NULL)
         AND o.OrderDate BETWEEN et.TourStartDate AND @date
       GROUP BY e.EmpId,e.EmpName,et.Region,et.TourStartDate,et.TourEndDate
      ) t1 INNER JOIN #Orders o
    ON t1.EmpId = o.EmpId
   AND (t1.FOrdDate = o.OrderDate OR t1.LOrdDate = o.OrderDate)
 GROUP BY t1.EmpName,t1.Region,t1.TourStartDate,t1.TourEndDate,t1.FOrdDate,t1.LOrdDate

(source of query)

And to be honest, that's a relatively simple query - just some inner joins and a subquery, along with a few common keywords (max, min, case).

How to reset / remove chrome's input highlighting / focus border?

The simpliest way is to use something like this but note that it may not be that good.

input {
  outline: none;
}

I hope you find this useful.

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

How can I render HTML from another file in a React component?

It is common to have components that are only rendering from props. Like this:

class Template extends React.Component{
  render (){
    return <div>this.props.something</div>
  }
}

Then in your upper level component where you have the logic you just import the Template component and pass the needed props. All your logic stays in the higher level component, and the Template only renders. This is a possible way to achieve 'templates' like in Angular.

There is no way to have .jsx file with jsx only and use it in React because jsx is not really html but markup for a virtual DOM, which React manages.

How do I clear my local working directory in Git?

All the answers so far retain local commits. If you're really serious, you can discard all local commits and all local edits by doing:

git reset --hard origin/branchname

For example:

git reset --hard origin/master

This makes your local repository exactly match the state of the origin (other than untracked files).

If you accidentally did this after just reading the command, and not what it does :), use git reflog to find your old commits.

Changing an element's ID with jQuery

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");

Cast received object to a List<object> or IEnumerable<object>

You need to type cast using as operator like this.

private void MyMethod(object myObject)  
{  
if(myObject is IEnumerable)  
{
    List<object> collection = myObject as(List<object>); 
    ... do something   
}  
else  
{  
    ... do something  
}  
}      

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

You may get this error because you namespaced the file. If so you will need to specify that PHPUnit_Framework_TestCase is in the global namespace by preceding it with a backslash:

namespace AcmeInc\MyApplication\Tests
class StackTest extends \PHPUnit_Framework_TestCase {}

I submitted a crude PR to start conversation for correcting the documentation.

Nginx - Customizing 404 page

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

location /my_blog {
    error_page    404 /blog_article_not_found.html;
}

A site wide 404 page:

server {
    listen 80;
    error_page  404  /website_page_not_found.html;
    ...

You can append standard error codes together to have a single page for several types of errors:

location /my_blog {
    error_page 500 502 503 504 /server_error.html
}

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 {
    server 10.0.0.1:80;
}
server {
    location /my_blog {
        error_page    404 @try_server2;
    }
    location @try_server2 {
        proxy_pass http://server2;
    }

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

JFrame: How to disable window resizing?

This Code May be Help you : [ Both maximizing and preventing resizing on a JFrame ]

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);

jQuery count child elements

You can use .length with just a descendant selector, like this:

var count = $("#selected li").length;

If you have to use .children(), then it's like this:

var count = $("#selected ul").children().length;

You can test both versions here.

How to find if directory exists in Python

You may also want to create the directory if it's not there.

Source, if it's still there on SO.

=====================================================================

On Python = 3.5, use pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:

Try os.path.exists, and consider os.makedirs for the creation.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.

Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

How do you remove the title text from the Android ActionBar?

If you only want to do it for one activity and perhaps even dynamically, you can also use

ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions() ^ ActionBar.DISPLAY_SHOW_TITLE);

What is the preferred syntax for defining enums in JavaScript?

This can be useful:

const [CATS, DOGS, BIRDS] = ENUM();

The implementation is simple and efficient:

function * ENUM(count=1) { while(true) yield count++ }

A generator can yield the exact sequence of integers required, without knowing how many constants there are. It can also support an optional argument that specifies which (possibly negative) number to start from (defaulting to 1).

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

you need to add jersey-bundle-1.17.1.jar to lib of project

<servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> --> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <!-- <param-name>jersey.config.server.provider.packages</param-name> --> <param-value>package.package.test</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

?: ?? Operators Instead Of IF|ELSE

The ternary operator (?:) is not designed for control flow, it's only designed for conditional assignment. If you need to control the flow of your program, use a control structure, such as if/else.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

If you use cell.imageView?.translatesAutoresizingMaskIntoConstraints = false you can set constraints on the imageView. Here's a working example I used in a project. I avoided subclassing and didn't need to create storyboard with prototype cells but did take me quite a while to get running, so probably best to only use if there isn't a simpler or more concise way available to you.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
}



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: ChangesRequiringApprovalTableViewController.self))

    let record = records[indexPath.row]

    cell.textLabel?.text = "Title text"

    if let thumb = record["thumbnail"] as? CKAsset, let image = UIImage(contentsOfFile: thumb.fileURL.path) {
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.image = image
        cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
        cell.imageView?.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
        cell.imageView?.widthAnchor.constraint(equalToConstant: 80).rowHeight).isActive = true
        cell.imageView?.heightAnchor.constraint(equalToConstant: 80).isActive = true
        if let textLabel = cell.textLabel {
            let margins = cell.contentView.layoutMarginsGuide
            textLabel.translatesAutoresizingMaskIntoConstraints = false
            cell.imageView?.trailingAnchor.constraint(equalTo: textLabel.leadingAnchor, constant: -8).isActive = true
            textLabel.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
            textLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
            let bottomConstraint = textLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor)
            bottomConstraint.priority = UILayoutPriorityDefaultHigh
            bottomConstraint.isActive = true
            if let description = cell.detailTextLabel {
                description.translatesAutoresizingMaskIntoConstraints = false
                description.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
                description.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
                cell.imageView?.trailingAnchor.constraint(equalTo: description.leadingAnchor, constant: -8).isActive = true
                textLabel.bottomAnchor.constraint(equalTo: description.topAnchor).isActive = true
            }
        }
        cell.imageView?.clipsToBounds = true
    }

    cell.detailTextLabel?.text = "Detail Text"

    return cell
}

HTML span align center not working?

On top of all the other explanations, I believe you're using equal "=" sign, instead of colon ":":

<span style="border:1px solid red;text-align=center">

It should be:

<span style="border:1px solid red;text-align:center">

Detecting a mobile browser

Feature detection is much better than trying to figure out which device you are on and very hard to keep up with new devices coming out all the time, a library like Modernizr lets you know if a particular feature is available or not.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Adding line break in C# Code behind page

Use @ symbol before starting the string. like

string s = @"this is a really
long string
and this is 
the rest of it";

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);


main()
{
     Foo(0);         
     Foo(NULL); // same as Foo(0)
} 

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

Finding the handle to a WPF window

Well, instead of passing Application.Current.MainWindow, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle and so on.

Angular2 handling http response

in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

It's nice because it can be used with all other Observable chained methods like .retry .map etc.

import {Observable} from 'rxjs/Rx';


  Http
  .put(...)
  .catch(err =>  { 
     notify('UI error handling');
     return Observable.throw(err); // observable needs to be returned or exception raised
  })
  .subscribe(data => ...) // handle success

from documentation:

Returns

(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

C# : changing listbox row color?

I think you have to draw the listitems yourself to achieve this.

Here's a post with the same kind of question.

Write to text file without overwriting in Java

try this one

_x000D_
_x000D_
public void writeFile(String arg1,String arg2) {_x000D_
  try {_x000D_
   if (!dir.exists()) {_x000D_
_x000D_
    if (dir.mkdirs()) {_x000D_
_x000D_
     Toast.makeText(getBaseContext(), "Directory created",_x000D_
       Toast.LENGTH_SHORT).show();_x000D_
    } else {_x000D_
     Toast.makeText(getBaseContext(),_x000D_
       "Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
       .show();_x000D_
    }_x000D_
   }_x000D_
_x000D_
   else {_x000D_
_x000D_
    File file = new File(dir, filename);_x000D_
    if (!file.exists()) {_x000D_
     file.createNewFile();_x000D_
    }_x000D_
    _x000D_
    FileWriter fileWritter = new FileWriter(file, true);_x000D_
    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
    bufferWritter.write(arg1 + "\n");_x000D_
    bufferWritter.close();_x000D_
_x000D_
            } catch (Exception e) {_x000D_
   e.printStackTrace();_x000D_
   Toast.makeText(getBaseContext(),_x000D_
     "Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
     .show();_x000D_
  }_x000D_
_x000D_
 }
_x000D_
_x000D_
_x000D_

How to install and use "make" in Windows?

Download make.exe from their official site GnuWin32

  • In the Download session, click Complete package, except sources.

  • Follow the installation instructions.

  • Once finished, add the <installation directory>/bin/ to the PATH variable.

Now you will be able to use make in cmd.

Specify a Root Path of your HTML directory for script links?

To be relative to the root directory, just start the URI with a /

<link type="text/css" rel="stylesheet" href="/style.css" />
<script src="/script.js" type="text/javascript"></script>

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

write() versus writelines() and concatenated strings

  • writelines expects an iterable of strings
  • write expects a single string.

line1 + "\n" + line2 merges those strings together into a single string before passing it to write.

Note that if you have many lines, you may want to use "\n".join(list_of_lines).

How to prevent Google Colab from disconnecting?

function ClickConnect(){
    console.log("Clicked on connect button"); 
    document.querySelector("connect").click() // Change id here
}
setInterval(ClickConnect,60000)

Try above code it worked for me:)

PG::ConnectionBad - could not connect to server: Connection refused

I had to reinstall my postgres, great instructions outlined here: https://medium.com/@zowoodward/effectively-uninstall-and-reinstall-psql-with-homebrew-on-osx-fabbc45c5d9d

Then I had to create postgres user: /usr/local/opt/postgres/bin/createuser -s postgres

This approach will clobber all of your local data so please back up your data if needed.

How to force a line break in a long word in a DIV?

Use word-wrap:break-word;

It even works in IE6, which is a pleasant surprise.


word-wrap: break-word has been replaced with overflow-wrap: break-word; which works in every modern browser. IE, being a dead browser, will forever rely on the deprecated and non-standard word-wrap instead.

Existing uses of word-wrap today still work as it is an alias for overflow-wrap per the specification.

Create an array of integers property in Objective-C

This works

@interface RGBComponents : NSObject {

    float components[8];

}

@property(readonly) float * components;

- (float *) components {
    return components;
}

Best practices to test protected methods with PHPUnit

If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

protected static function getMethod($name) {
  $class = new ReflectionClass('MyClass');
  $method = $class->getMethod($name);
  $method->setAccessible(true);
  return $method;
}

public function testFoo() {
  $foo = self::getMethod('foo');
  $obj = new MyClass();
  $foo->invokeArgs($obj, array(...));
  ...
}

Multiple IF statements between number ranges

standalone one cell solution based on VLOOKUP

US syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
        IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
 {{(TRANSPOSE({{{0;   "Less than 500"},
               {500;  "Between 500 and 1000"}},
              {{1000; "Between 1000 and 1500"},
               {1500; "Between 1500 and 2000"}}}))}}, 2)),)), )

EU syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
        IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
 {{(TRANSPOSE({{{0;   "Less than 500"}\
               {500;  "Between 500 and 1000"}}\
              {{1000; "Between 1000 and 1500"}\
               {1500; "Between 1500 and 2000"}}}))}}; 2));)); )

alternatives: https://webapps.stackexchange.com/questions/123729/

Trim spaces from start and end of string

As @ChaosPandion mentioned, the String.prototype.trim method has been introduced into the ECMAScript 5th Edition Specification, some implementations already include this method, so the best way is to detect the native implementation and declare it only if it's not available:

if (typeof String.prototype.trim != 'function') { // detect native implementation
  String.prototype.trim = function () {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  };
}

Then you can simply:

title = title.trim();

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

ValueError: could not convert string to float: id

Perhaps your numbers aren't actually numbers, but letters masquerading as numbers?

In my case, the font I was using meant that "l" and "1" looked very similar. I had a string like 'l1919' which I thought was '11919' and that messed things up.

In Python, what happens when you import inside of a function?

Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?

And then you can use profiling to assure that your optimizations have actually benefited you, too.

What does -1 mean in numpy reshape?

numpy.reshape(a,newshape,order{})

check the below link for more info. https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

for the below example you mentioned the output explains the resultant vector to be a single row.(-1) indicates the number of rows to be 1. if the

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

output:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

this can be explained more precisely with another example:

b = np.arange(10).reshape((-1,1))

output:(is a 1 dimensional columnar array)

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

or

b = np.arange(10).reshape((1,-1))

output:(is a 1 dimensional row array)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

How to use multiple @RequestMapping annotations in spring?

The following is acceptable as well:

@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath", 
                     "/fixedPath/{some-name}/{some-id}/fixed" }, 
            produces = "application/json")

Same can be applied to @RequestMapping as well

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Make function wait until element exists

This will only work with modern browsers but I find it easier to just use a then so please test first but:

Code

function rafAsync() {
    return new Promise(resolve => {
        requestAnimationFrame(resolve); //faster than set time out
    });
}

function checkElement(selector) {
    if (document.querySelector(selector) === null) {
        return rafAsync().then(() => checkElement(selector));
    } else {
        return Promise.resolve(true);
    }
}

Or using generator functions

async function checkElement(selector) {
    const querySelector = null;
    while (querySelector === null) {
        await rafAsync();
        querySelector = document.querySelector(selector);
    }
    return querySelector;
}  

Usage

checkElement('body') //use whichever selector you want
.then((element) => {
     console.info(element);
     //Do whatever you want now the element is there
});

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

How can I create objects while adding them into a vector?

// create a vector of unknown players.
std::vector<player> players;

// resize said vector to only contain 6 players.
players.resize(6);

Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.

As for the second part, you need to use pointers. Instantiating c++ interface as a child class

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

Bootstrap 4 responsive tables won't take up 100% width

The following WON'T WORK. It causes another issue. It will now do the 100% width but it won't be responsive on smaller devices:

.table-responsive {
    display: table;
}

All these answers introduced another problem by recommending display: table;. The only solution as of right now is to use it as a wrapper:

<div class="table-responsive">
  <table class="table">
...
 </table>
</div>

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

Python read JSON file and modify

falsetru's solution is nice, but has a little bug:

Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.

I solved that by replacing the original file.

import json
import os

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.

os.remove(filename)
with open(filename, 'w') as f:
    json.dump(data, f, indent=4)

What is the best method of handling currency/money?

Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"

add_column :products, :price, :decimal, :precision => 8, :scale => 2 

This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like

def validate 
  errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01 
end 

to sanity-check your values.

CodeIgniter -> Get current URL relative to base url

 //if you want to get parameter from url use:
 parse_str($_SERVER['QUERY_STRING'], $_GET);
 //then you can use:
 if(isset($_GET["par"])){
      echo $_GET["par"];
 }
 //if you want to get current page url use:
 $current_url = current_url();

Can't concatenate 2 arrays in PHP

+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

With the example:

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Since both your arrays have one entry with the key 0, the result is expected.

To concatenate, use array_merge.

javascript onclick increment number

Check this out.

_x000D_
_x000D_
var timeout_;

function mouseDown_i() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  document.getElementById('xxxx').value = value + 1;  
  timeout_ = setTimeout(function() { mouseDown_i(); }, 150);
}

function mouseDown_d() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  value - 1 <= 0 ? document.getElementById('xxxx').value = '' : document.getElementById('xxxx').value = value - 1;  
  timeout_ = setTimeout(function() { mouseDown_d(); }, 150);
}

function mouseUp() { clearTimeout(timeout_); }

function mouseLeave() { clearTimeout(timeout_); }
_x000D_
<p onmousedown="mouseDown_i()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to INCREMENT!</p>
<p onmousedown="mouseDown_d()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to DECREMENT!</p>
<input id="xxxx" type="text" value="0">
_x000D_
_x000D_
_x000D_

How can I find script's directory?

This worked for me (and I found it via the this stackoverflow question)

os.path.realpath(__file__)

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How can I declare a two dimensional string array?

string[,] Tablero = new string[3,3];

You can also instantiate it in the same line with array initializer syntax as follows:

string[,] Tablero = new string[3, 3] {{"a","b","c"},
                                      {"d","e","f"}, 
                                      {"g","h","i"} };

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

jQuery SVG, why can't I addClass?

jQuery 2.2 supports SVG class manipulation

The jQuery 2.2 and 1.12 Released post includes the following quote:

While jQuery is a HTML library, we agreed that class support for SVG elements could be useful. Users will now be able to call the .addClass(), .removeClass(), .toggleClass(), and .hasClass() methods on SVG. jQuery now changes the class attribute rather than the className property. This also makes the class methods usable in general XML documents. Keep in mind that many other things will not work with SVG, and we still recommend using a library dedicated to SVG if you need anything beyond class manipulation.

Example using jQuery 2.2.0

It tests:

  • .addClass()
  • .removeClass()
  • .hasClass()

If you click on that small square, it will change its color because the class attribute is added / removed.

_x000D_
_x000D_
$("#x").click(function() {_x000D_
    if ( $(this).hasClass("clicked") ) {_x000D_
        $(this).removeClass("clicked");_x000D_
    } else {_x000D_
        $(this).addClass("clicked");_x000D_
    }_x000D_
});
_x000D_
.clicked {_x000D_
    fill: red !important;  _x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <script src="https://code.jquery.com/jquery-2.2.0.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <svg width="80" height="80">_x000D_
        <rect id="x" width="80" height="80" style="fill:rgb(0,0,255)" />_x000D_
    </svg>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Applications are expected to have a root view controller at the end of application launch

Have you tried setting the delegate, i.e.

self.rootController.delegate = self;

within applicationDidFinishLaunchingWithOptions? That worked for me, although I'm not sure why.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

How to write a large buffer into a binary file in C++, fast?

I see no difference between std::stream/FILE/device. Between buffering and non buffering.

Also note:

  • SSD drives "tend" to slow down (lower transfer rates) as they fill up.
  • SSD drives "tend" to slow down (lower transfer rates) as they get older (because of non working bits).

I am seeing the code run in 63 secondds.
Thus a transfer rate of: 260M/s (my SSD look slightly faster than yours).

64 * 1024 * 1024 * 8 /*sizeof(unsigned long long) */ * 32 /*Chunks*/

= 16G
= 16G/63 = 260M/s

I get a no increase by moving to FILE* from std::fstream.

#include <stdio.h>

using namespace std;

int main()
{
    
    FILE* stream = fopen("binary", "w");

    for(int loop=0;loop < 32;++loop)
    {
         fwrite(a, sizeof(unsigned long long), size, stream);
    }
    fclose(stream);

}

So the C++ stream are working as fast as the underlying library will allow.

But I think it is unfair comparing the OS to an application that is built on-top of the OS. The application can make no assumptions (it does not know the drives are SSD) and thus uses the file mechanisms of the OS for transfer.

While the OS does not need to make any assumptions. It can tell the types of the drives involved and use the optimal technique for transferring the data. In this case a direct memory to memory transfer. Try writing a program that copies 80G from 1 location in memory to another and see how fast that is.

Edit

I changed my code to use the lower level calls:
ie no buffering.

#include <fcntl.h>
#include <unistd.h>


const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    int data = open("test", O_WRONLY | O_CREAT, 0777);
    for(int loop = 0; loop < 32; ++loop)
    {   
        write(data, a, size * sizeof(unsigned long long));
    }   
    close(data);
}

This made no diffference.

NOTE: My drive is an SSD drive if you have a normal drive you may see a difference between the two techniques above. But as I expected non buffering and buffering (when writting large chunks greater than buffer size) make no difference.

Edit 2:

Have you tried the fastest method of copying files in C++

int main()
{
    std::ifstream  input("input");
    std::ofstream  output("ouptut");

    output << input.rdbuf();
}

Error handling with PHPMailer

Please note!!! You must use the following format when instantiating PHPMailer!

$mail = new PHPMailer(true);

If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.

Android Fragments and animation

As for me, i need the view diraction:

in -> swipe from right

out -> swipe to left

Here works for me code:

slide_in_right.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
            android:duration="@android:integer/config_mediumAnimTime" />
</set>

slide_out_left.xml

 <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="0" android:toXDelta="-50%p"
                android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
                android:duration="@android:integer/config_mediumAnimTime" />
    </set>

transaction code:

inline fun FragmentActivity.setContentFragment(
        containerViewId: Int,
        backStack: Boolean = false,
        isAnimate: Boolean = false,
        f: () -> Fragment

): Fragment? {
    val manager = supportFragmentManager
    return f().apply {
        manager.beginTransaction().let {
            if (isAnimate)
                it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)

            if (backStack) {
                it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
            } else {
                it.replace(containerViewId, this, "Fr").commit()
            }
        }
    }
}

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

How can I directly view blobs in MySQL Workbench

Perform three steps:

  1. Go to "WorkBench Preferences" --> Choose "SQL Editor" Under "Query Results": check "Treat BINARY/VARBINARY as nonbinary character string"

  2. Restart MySQL WorkBench.

  3. Now select SELECT SUBSTRING(BLOB<COLUMN_NAME>,1,2500) FROM <Table_name>;

Using classes with the Arduino

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:

By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.

Code:

#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); } 
void operator delete(void* ptr) { free(ptr); }

This let's you create objects, e.g.

C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory

Regards, tamberg

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)

How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.

For instance, if you don't mind the value being a shallow clone:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

If you've already constrained T to implement ICloneable:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, 
                                               entry => (T) entry.Value.Clone());

(Those are untested, but should work.)

How to embed a SWF file in an HTML page?

What is the 'best' way? Words like 'most efficient,' 'fastest rendering,' etc. are more specific. Anyway, I am offering an alternative answer that helps me most of the time (whether or not is 'best' is irrelevant).

Alternate answer: Use an iframe.

That is, host the SWF file on the server. If you put the SWF file in the root or public_html folder then the SWF file will be located at www.YourDomain.com/YourFlashFile.swf.

Then, on your index.html or wherever, link the above location to your iframe and it will be displayed around your content wherever you put your iframe. If you can put an iframe there, you can put an SWF file there. Make the iframe dimensions the same as your SWF file. In the example below, the SWF file is 500 by 500.

Pseudo code:

<iframe src="//www.YourDomain.com/YourFlashFile.swf" width="500" height="500"></iframe>

The line of HTML code above will embed your SWF file. No other mess needed. Pros: W3C compliant, page design friendly, no speed issue, minimalist approach.
Cons: White space around your SWF file when launched in a browser.

That is an alternate answer. Whether it is the 'best' answer depends on your project.

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

How to get a cookie from an AJAX response?

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

For this to work you need to:

1) login with the ajax request from which you expect cookies to be returned:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie

How to increase code font size in IntelliJ?

It is possible to change font size etc when creating custom Scheme using Save As... button:

Save As...

How to set ChartJS Y axis title?

Consider using a the transform: rotate(-90deg) style on an element. See http://www.w3schools.com/cssref/css3_pr_transform.asp

Example, In your css

.verticaltext_content {
  position: relative;
  transform: rotate(-90deg);
  right:90px;   //These three positions need adjusting
  bottom:150px; //based on your actual chart size
  width:200px;
}

Add a space fudge factor to the Y Axis scale so the text has room to render in your javascript.

scaleLabel: "      <%=value%>"

Then in your html after your chart canvas put something like...

<div class="text-center verticaltext_content">Y Axis Label</div>

It is not the most elegant solution, but worked well when I had a few layers between the html and the chart code (using angular-chart and not wanting to change any source code).

Change icons of checked and unchecked for Checkbox for Android

I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/

Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.

Converting a UNIX Timestamp to Formatted Date String

use date function date ( string $format [, int $timestamp = time() ] )

Use date('c',time()) as format to convert to ISO 8601 date (added in PHP 5) - 2012-04-06T12:45:47+05:30

use date("Y-m-d\TH:i:s\Z",1333699439) to get 2012-04-06T13:33:59Z

Here are some of the formats date function supports

<?php
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
?>

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

gcc version 4.8.1, the error seems like:

/root/bllvm/build/Release+Asserts/bin/llvm-tblgen: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /root/bllvm/build/Release+Asserts/bin/llvm-tblgen)

I found the libstdc++.so.6.0.18 at the place where I complied gcc 4.8.1

Then I do like this

cp ~/objdir/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.18 /usr/lib64/

rm /usr/lib64/libstdc++.so.6

ln -s libstdc++.so.6.0.18 libstdc++.so.6

problem solved.

What is the difference between require and require-dev sections in composer.json?

Note the require-dev (root-only) !

which means that the require-dev section is only valid when your package is the root of the entire project. I.e. if you run composer update from your package folder.

If you develop a plugin for some main project, that has it's own composer.json, then your require-dev section will be completely ignored! If you need your developement dependencies, you have to move your require-dev to composer.json in main project.

Laravel Controller Subfolder routing

For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group will be really helpful for you. For example:

Update: Works with Laravel 5.4

My folder Structure:

Http
----Controllers
    ----Api
          ----V1
                 PostsApiController.php
                 CommentsApiController.php
    PostsController.php

PostAPIController:

<?php namespace App\Http\Controllers\Api\V1;

use App\Http\Requests;
use App\Http\Controllers\Controller;   
use Illuminate\Http\Request;

class PostApiController extends Controller {  
...

In My Route.php, I set namespace group to Api\V1 and overall it looks like:

Route::group(
        [           
            'namespace' => 'Api\V1',
            'prefix' => 'v1',
        ], function(){

            Route::get('posts', ['uses'=>'PostsApiController@index']);
            Route::get('posts/{id}', ['uses'=>'PostssAPIController@show']);

    });

For move details to create sub-folder visit this link.

How to check if any value is NaN in a Pandas DataFrame

I've been using the following and type casting it to a string and checking for the nan value

   (str(df.at[index, 'column']) == 'nan')

This allows me to check specific value in a series and not just return if this is contained somewhere within the series.

Prevent users from submitting a form by hitting Enter

I can't comment yet, so I'll post a new answer

Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.

if(event.keyCode == 13 || event.keyCode == 169) {...}

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

this also worked for me. Go to the bootstrap-datepicker.js.

replace this code :

_x000D_
_x000D_
var defaults = $.fn.datepicker.defaults = {_x000D_
  autoclose: false,_x000D_
  beforeShowDay: $.noop,_x000D_
  calendarWeeks: false,_x000D_
  clearBtn: false,_x000D_
  daysOfWeekDisabled: [],_x000D_
  endDate: Infinity,_x000D_
  forceParse: true,_x000D_
  format: 'mm/dd/yyyy',_x000D_
  keyboardNavigation: true,_x000D_
  language: 'en',_x000D_
  minViewMode: 0,_x000D_
  multidate: false,_x000D_
  multidateSeparator: ',',_x000D_
  orientation: "auto",_x000D_
  rtl: false,_x000D_
  startDate: -Infinity,_x000D_
  startView: 0,_x000D_
  todayBtn: false,_x000D_
  todayHighlight: false,_x000D_
  weekStart: 0_x000D_
 };
_x000D_
_x000D_
_x000D_

with :

_x000D_
_x000D_
var defaults = $.fn.datepicker.defaults = {_x000D_
  autoclose: false,_x000D_
  beforeShowDay: $.noop,_x000D_
  calendarWeeks: false,_x000D_
  clearBtn: false,_x000D_
  daysOfWeekDisabled: [],_x000D_
  endDate: Infinity,_x000D_
  forceParse: true,_x000D_
  format: 'yyyy-mm-dd',_x000D_
  keyboardNavigation: true,_x000D_
  language: 'en',_x000D_
  minViewMode: 0,_x000D_
  multidate: false,_x000D_
  multidateSeparator: ',',_x000D_
  orientation: "auto",_x000D_
  rtl: false,_x000D_
  startDate: -Infinity,_x000D_
  startView: 0,_x000D_
  todayBtn: false,_x000D_
  todayHighlight: false,_x000D_
  weekStart: 0_x000D_
 };
_x000D_
_x000D_
_x000D_

Skip over a value in the range function in python

It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:

import itertools

m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
    print(i)  # skips m = 5

As an aside, you woudn't want to use (*range(m), *range(m + 1, n)) even though it works because it will expand the iterables into a tuple and this is memory inefficient.


Credit: comment by njzk2, answer by Locke

Removing special characters VBA Excel

What do you consider "special" characters, just simple punctuation? You should be able to use the Replace function: Replace("p.k","."," ").

Sub Test()
Dim myString as String
Dim newString as String

myString = "p.k"

newString = replace(myString, ".", " ")

MsgBox newString

End Sub

If you have several characters, you can do this in a custom function or a simple chained series of Replace functions, etc.

  Sub Test()
Dim myString as String
Dim newString as String

myString = "!p.k"

newString = Replace(Replace(myString, ".", " "), "!", " ")

'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")

MsgBox newString

End Sub

If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?"  'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
    newString = Replace(newString, char, " ")
Next
End Sub

How do you render primitives as wireframes in OpenGL?

From http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5

// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box
DrawBox();

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);

Editing in the Chrome debugger

As this is quite popular question that deals with live-editing of JS, I want to point out another useful option. As described by svjacob in his answer:

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

The above solution didn't work for me for quite large JS (webpack bundle - 3.21MB minified version, 130k lines of code in prettified version) - chrome crashed and asked for page reloading which reverted any saved changes. The way to go in this case was Fiddler where you can set AutoRespond option to replace any remote resource with any local file from your computer - see this SO question for details.

In my case I also had to add CORS headers to fiddler to successfully mock response.

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Try

(n+10).toString(36)

_x000D_
_x000D_
chr = n=>(n+10).toString(36);_x000D_
_x000D_
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);
_x000D_
_x000D_
_x000D_

Decrementing for loops

for i in range(10,0,-1):
    print i,

The range() function will include the first value and exclude the second.

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

React "after render" code?

A little bit of update with ES6 classes instead of React.createClass

import React, { Component } from 'react';

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    // this code might be called when there is no element avaliable in `document` yet (eg. initial render)
  }

  componentDidMount() {
    // this code will be always called when component is mounted in browser DOM ('after render')
  }

  render() {
    return (
      <div className="component">
        Some Content
      </div>
    );
  }
}

Also - check React component lifecycle methods:The Component Lifecycle

Every component have a lot of methods similar to componentDidMount eg.

  • componentWillUnmount() - component is about to be removed from browser DOM

Can I use a :before or :after pseudo-element on an input field?

I found that you can do it like this:

_x000D_
_x000D_
.submit .btn input_x000D_
{_x000D_
   padding:11px 28px 12px 14px;_x000D_
   background:#004990;_x000D_
   border:none;_x000D_
    color:#fff;_x000D_
}_x000D_
_x000D_
 .submit .btn_x000D_
 {_x000D_
     border:none;_x000D_
     color:#fff;_x000D_
     font-family: 'Open Sans', sans-serif;_x000D_
     font-size:1em;_x000D_
     min-width:96px;_x000D_
     display:inline-block;_x000D_
     position:relative;_x000D_
 }_x000D_
_x000D_
.submit .btn:after_x000D_
{_x000D_
    content:">";_x000D_
    width:6px;_x000D_
    height:17px;_x000D_
    position:absolute;_x000D_
    right:36px;_x000D_
    color:#fff;_x000D_
    top:7px;_x000D_
}
_x000D_
<div class="submit">_x000D_
  <div class="btn">_x000D_
     <input value="Send" type="submit" />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You need to have a div parent that takes the padding and the :after. The first parent needs to be relative and the second div should be absolute so you can set the position of the after.

How to read a .xlsx file using the pandas Library in iPython?

DataFrame's read_excel method is like read_csv method:

dfs = pd.read_excel(xlsx_file, sheetname="sheet1")


Help on function read_excel in module pandas.io.excel:

read_excel(io, sheetname=0, header=0, skiprows=None, skip_footer=0, index_col=None, names=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, convert_float=True, has_index_names=None, converters=None, true_values=None, false_values=None, engine=None, squeeze=False, **kwds)
    Read an Excel table into a pandas DataFrame

    Parameters
    ----------
    io : string, path object (pathlib.Path or py._path.local.LocalPath),
        file-like object, pandas ExcelFile, or xlrd workbook.
        The string could be a URL. Valid URL schemes include http, ftp, s3,
        and file. For file URLs, a host is expected. For instance, a local
        file could be file://localhost/path/to/workbook.xlsx
    sheetname : string, int, mixed list of strings/ints, or None, default 0

        Strings are used for sheet names, Integers are used in zero-indexed
        sheet positions.

        Lists of strings/integers are used to request multiple sheets.

        Specify None to get all sheets.

        str|int -> DataFrame is returned.
        list|None -> Dict of DataFrames is returned, with keys representing
        sheets.

        Available Cases

        * Defaults to 0 -> 1st sheet as a DataFrame
        * 1 -> 2nd sheet as a DataFrame
        * "Sheet1" -> 1st sheet as a DataFrame
        * [0,1,"Sheet5"] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames
        * None -> All sheets as a dictionary of DataFrames

    header : int, list of ints, default 0
        Row (0-indexed) to use for the column labels of the parsed
        DataFrame. If a list of integers is passed those row positions will
        be combined into a ``MultiIndex``
    skiprows : list-like
        Rows to skip at the beginning (0-indexed)
    skip_footer : int, default 0
        Rows at the end to skip (0-indexed)
    index_col : int, list of ints, default None
        Column (0-indexed) to use as the row labels of the DataFrame.
        Pass None if there is no such column.  If a list is passed,
        those columns will be combined into a ``MultiIndex``
    names : array-like, default None
        List of column names to use. If file contains no header row,
        then you should explicitly pass header=None
    converters : dict, default None
        Dict of functions for converting values in certain columns. Keys can
        either be integers or column labels, values are functions that take one
        input argument, the Excel cell content, and return the transformed
        content.
    true_values : list, default None
        Values to consider as True

        .. versionadded:: 0.19.0

    false_values : list, default None
        Values to consider as False

        .. versionadded:: 0.19.0

    parse_cols : int or list, default None
        * If None then parse all columns,
        * If int then indicates last column to be parsed
        * If list of ints then indicates list of column numbers to be parsed
        * If string then indicates comma separated list of column names and
          column ranges (e.g. "A:E" or "A,C,E:F")
    squeeze : boolean, default False
        If the parsed data only contains one column then return a Series
    na_values : scalar, str, list-like, or dict, default None
        Additional strings to recognize as NA/NaN. If dict passed, specific
        per-column NA values. By default the following values are interpreted
        as NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
    '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'nan'.
    thousands : str, default None
        Thousands separator for parsing string columns to numeric.  Note that
        this parameter is only necessary for columns stored as TEXT in Excel,
        any numeric columns will automatically be parsed, regardless of display
        format.
    keep_default_na : bool, default True
        If na_values are specified and keep_default_na is False the default NaN
        values are overridden, otherwise they're appended to.
    verbose : boolean, default False
        Indicate number of NA values placed in non-numeric columns
    engine: string, default None
        If io is not a buffer or path, this must be set to identify io.
        Acceptable values are None or xlrd
    convert_float : boolean, default True
        convert integral floats to int (i.e., 1.0 --> 1). If False, all numeric
        data will be read in as floats: Excel stores all numbers as floats
        internally
    has_index_names : boolean, default None
        DEPRECATED: for version 0.17+ index names will be automatically
        inferred based on index_col.  To read Excel output from 0.16.2 and
        prior that had saved index names, use True.

    Returns
    -------
    parsed : DataFrame or Dict of DataFrames
        DataFrame from the passed in Excel file.  See notes in sheetname
        argument for more information on when a Dict of Dataframes is returned.

Emulate/Simulate iOS in Linux

Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium

How to create a file with a given size in Linux?

You can do it programmatically:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main() {
    int fd = creat("/tmp/foo.txt", 0644);
    ftruncate(fd, SIZE_IN_BYTES);
    close(fd);
    return 0;
}

This approach is especially useful to subsequently mmap the file into memory.

use the following command to check that the file has the correct size:

# du -B1 --apparent-size /tmp/foo.txt

Be careful:

# du /tmp/foo.txt

will probably print 0 because it is allocated as Sparse file if supported by your filesystem.

see also: man 2 open and man 2 truncate

?: operator (the 'Elvis operator') in PHP

Elvis operator:

?: is the Elvis operator. This is a binary operator which does the following:

Coerces the value left of ?: to a boolean and checks if it is true. If true it will return the expression on the left side, if false it will return the expression on the right side.

Example:

var_dump(0 ?: "Expression not true");     // expression returns: Expression not true
var_dump("" ?: "Expression not true");    // expression returns: Expression not true
var_dump("hi" ?: "Expression not true");  // expression returns string hi
var_dump(null ?: "Expression not true");  // expression returns: Expression not true
var_dump(56 ?: "Expression not true");    // expression return int 56

When to use:

The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:

$testedVar ? $ testedVar : $otherVar;

The Elvis operator will make the syntax more consise in the following manner:

$testedVar ?: $otherVar;

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Loop inside React JSX

You can only write a JavaScript expression in a JSX element, so a for loop cannot work. You can convert the element into an array first and use the map function to render it:

<tbody>
    {[...new Array(numrows)].map((e) => (
         <ObjectRow/>
    ))}
</tbody>

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

How do I start a program with arguments when debugging?

for .NET Core console apps you can do this 2 ways - from the launchsettings.json or the properties menu.

Launchsettings.json

enter image description here

or right click the project > properties > debug tab on left

see "Application Arguments:"

  • this is " " (space) delimited, no need for any commas. just start typing. each space " " will represent a new input parameter.
  • (whatever changes you make here will be reflected in the launchsettings.json file...)

enter image description here

How to Correctly handle Weak Self in Swift Blocks with Arguments

You can use [weak self] or [unowned self] in the capture list prior to your parameters of the block. The capture list is optional syntax.

[unowned self] works good here because the cell will never be nil. Otherwise you can use [weak self]

How to enter in a Docker container already running with a new TTY

The "nsinit" way is:

install nsinit

git clone [email protected]:dotcloud/docker.git
cd docker
make shell

from inside the container:

go install github.com/dotcloud/docker/pkg/libcontainer/nsinit/nsinit

from outside:

docker cp id_docker_container:/go/bin/nsinit /root/

use it

cd /var/lib/docker/execdriver/native/<container_id>/
nsinit exec bash

How to stop a thread created by implementing runnable interface?

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

How to force maven update?

Just in case someone wants only update project's snapshot dependencies and doesn't want to install artifact:

mvn dependency:resolve -U

Don't forget to reimport dependencies in your IDE. In IDEA you need to right click on pom file and choose Maven -> Reimport

Can you Run Xcode in Linux?

If you really want to use Xcode on linux you could get Virtual Box and install Hackintosh on a VM. Edit: Virtual Box Guest Additions is not supported with MacOS Movaje. You will want to use VMware

https://www.vmware.com/

https://hackintosh.com/

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

The solution is to change the DropDownStyle property to DropDownList. It will help.

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

How to force link from iframe to be opened in the parent window

As noted, you could use a target attribute, but it was technically deprecated in XHTML. That leaves you with using javascript, usually something like parent.window.location.

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

Detect encoding and make everything UTF-8

I find solution here http://deer.org.ua/2009/10/06/1/

class Encoding
{
    /**
     * http://deer.org.ua/2009/10/06/1/
     * @param $string
     * @return null
     */
    public static function detect_encoding($string)
    {
        static $list = ['utf-8', 'windows-1251'];

        foreach ($list as $item) {
            try {
                $sample = iconv($item, $item, $string);
            } catch (\Exception $e) {
                continue;
            }
            if (md5($sample) == md5($string)) {
                return $item;
            }
        }
        return null;
    }
}

$content = file_get_contents($file['tmp_name']);
$encoding = Encoding::detect_encoding($content);
if ($encoding != 'utf-8') {
    $result = iconv($encoding, 'utf-8', $content);
} else {
    $result = $content;
}

I think that @ is bad decision, and make some changes to solution from deer.org.ua;

Examples for string find in Python

Try this:

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break

how to read System environment variable in Spring applicationContext

For my use case, I needed to access just the system properties, but provide default values in case they are undefined.

This is how you do it:

<bean id="propertyPlaceholderConfigurer"   
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
</bean>  
<bean id="myBean" class="path.to.my.BeanClass">
    <!-- can be overridden with -Dtest.target.host=http://whatever.com -->
    <constructor-arg value="${test.target.host:http://localhost:18888}"/>
</bean>

How to align 3 divs (left/center/right) inside another div?

Using Bootstrap 3 I create 3 divs of equal width (in 12 column layout 4 columns for each div). This way you can keep your central zone centered even if left/right sections have different widths (if they don't overflow their columns' space).

HTML:

<div id="container">
  <div id="left" class="col col-xs-4 text-left">Left</div>
  <div id="center" class="col col-xs-4 text-center">Center</div>
  <div id="right" class="col col-xs-4 text-right">Right</div>
</div>

CSS:

#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  border: 1px solid #07f;
  padding: 0;
}

CodePen

To create that structure without libraries I copied some rules from Bootstrap CSS.

HTML:

<div id="container">
  <div id="left" class="col">Left</div>
  <div id="center" class="col">Center</div>
  <div id="right" class="col">Right</div>
</div>

CSS:

* {
  box-sizing: border-box;
}
#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  float: left;
  width: 33.33333333%;
  border: 1px solid #07f;
  padding: 0;
}
#left {
  text-align: left;
}
#center {
  text-align: center;
}
#right {
  text-align: right;
}

CopePen

Delete from two tables in one query

DELETE message.*, usersmessage.* from users, usersmessage WHERE message.messageid=usersmessage.messageid AND message.messageid='1'

How to determine the version of the C++ standard used by the compiler?

From the Bjarne Stroustrup C++0x FAQ:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.

These are the C++ standards and what value you should be able to expect in __cplusplus:

  • C++ pre-C++98: __cplusplus is 1.
  • C++98: __cplusplus is 199711L.
  • C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
  • C++11: __cplusplus is 201103L.
  • C++14: __cplusplus is 201402L.
  • C++17: __cplusplus is 201703L.

If the compiler might be an older gcc, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.

The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).

Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).

If else on WHERE clause

You want to use coalesce():

where coalesce(email, email2) like '%[email protected]%'

If you want to handle empty strings ('') versus NULL, a case works:

where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'

And, if you are worried about the string really being just spaces:

where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'

As an aside, the sample if statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.

Should each and every table have a primary key?

To make it future proof you really should. If you want to replicate it you'll need one. If you want to join it to another table your life (and that of the poor fools who have to maintain it next year) will be so much easier.

Python: avoid new line with print command

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere

jQuery addClass onClick

Using jQuery:

$('#Button').click(function(){
    $(this).addClass("active");
});

This way, you don't have to pollute your HTML markup with onclick handlers.