Programs & Examples On #Strassen

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

How can I detect browser type using jQuery?

The best solution is probably: use Modernizr.

However, if you necessarily want to use $.browser property, you can do it using jQuery Migrate plugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:

if($.browser.chrome) {
   alert(1);
} else if ($.browser.mozilla) {
   alert(2);
} else if ($.browser.msie) {
   alert(3);
}

And if you need for some reason to use navigator.userAgent, then it would be:

$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase()); 
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase()); 

Getting today's date in YYYY-MM-DD in Python?

You can use datetime.date.today() and convert the resulting datetime.date object to a string:

from datetime import date
today = str(date.today())
print(today)   # '2017-12-26'

How to import a single table in to mysql database using command line

All of these options are fine, if you have the option to re-export the data.

But if you need to use an existing SQL file, and use a specific table from it, then this perl script in the TimeSheet blog, with enable you to extract the table to a separate SQL file, and then import it.

The original link is dead, so it is a good thing that someone has put it instead of the author, Jared Cheney, on GitHub, in this link.

How do I run Python script using arguments in windows command line

To execute your program from the command line, you have to call the python interpreter, like this :

C:\Python27>python hello.py 1 1

If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.

How do I make a div full screen?

This is the simplest one.

#divid {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}

What's the best practice to "git clone" into an existing folder?

git init
git remote add origin [email protected]:<user>/<repo>.git
git remote -v
git pull origin master

ERROR in Cannot find module 'node-sass'

I had the same error when installing dependencies in Angular. I've tried aforementioned techniques but none of them worked until I've deleted package-lock.json which was previously created when running Node v11.

Now I'm using Node v12 so this is how I got resolved.

I repeat if you have package-lock.json delete it, file and then install dependencies.

How to upload a file in Django?

Here it may helps you: create a file field in your models.py

For uploading the file(in your admin.py):

def save_model(self, request, obj, form, change):
    url = "http://img.youtube.com/vi/%s/hqdefault.jpg" %(obj.video)
    url = str(url)

    if url:
        temp_img = NamedTemporaryFile(delete=True)
        temp_img.write(urllib2.urlopen(url).read())
        temp_img.flush()
        filename_img = urlparse(url).path.split('/')[-1]
        obj.image.save(filename_img,File(temp_img)

and use that field in your template also.

How do I include a newline character in a string in Delphi?

var
  stlst: TStringList;
begin
  Label1.Caption := 'Hello,'+sLineBreak+'world!';

  Label2.Caption := 'Hello,'#13#10'world!';

  Label3.Caption := 'Hello,' + chr(13) + chr(10) + 'world!';

  stlst := TStringList.Create;
  stlst.Add('Hello,');
  stlst.Add('world!');
  Label4.Caption := stlst.Text;

  Label5.WordWrap := True; //Multi-line Caption
  Label5.Caption := 'Hello,'^M^J'world!';

  Label6.Caption := AdjustLineBreaks('Hello,'#10'world!');
  {http://delphi.about.com/library/rtl/blrtlAdjustLineBreaks.htm}
end;

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

How to change option menu icon in the action bar?

The following lines should be updated in app -> main -> res -> values -> Styles.xml

 <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
</style>

<!-- Style to replace actionbar overflow icon. set item 'android:actionOverflowButtonStyle' in AppTheme -->
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_launcher</item>
    <item name="android:background">?android:attr/actionBarItemBackground</item>
    <item name="android:contentDescription">"Lala"</item>
</style>

This is how it can be done. If you want to change the overflow icon in action bar

Best radio-button implementation for IOS

Just want to sum up, there might be 4 ways.

  • If you don't have much space, add a click event for text or button, then show UIPickerView:

UIPickerView

or open a new table view control with a check mark:

UITableView

  • If there is more space, add a table view directly to your main view:

enter image description here

  • The final solution is using UISegmentedControl:

enter image description here

Hope this helps.

How to get list of all installed packages along with version in composer?

If you only want to check version for only one, you can do

composer show -- twig/twig

Note that only installed packages are shown by default now, and installed option is now deprecated.

How can I parse a CSV string with JavaScript, which contains comma in data?

PEG(.js) grammar that handles RFC 4180 examples at http://en.wikipedia.org/wiki/Comma-separated_values:

start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]

Test at http://jsfiddle.net/knvzk/10 or https://pegjs.org/online.

Download the generated parser at https://gist.github.com/3362830.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

There are two ways I can think of to make this happen in a reusable way. One is to rename all of your columns with a prefix for the table they have come from. I have seen this many times, but I really don't like it. I find that it's redundant, causes a lot of typing, and you can always use aliases when you need to cover the case of a column name having an unclear origin.

The other way, which I would recommend you do in your situation if you are committed to seeing this through, is to create views for each table that alias the table names. Then you join against those views, rather than the tables. That way, you are free to use * if you wish, free to use the original tables with original column names if you wish, and it also makes writing any subsequent queries easier because you have already done the renaming work in the views.

Finally, I am not clear why you need to know which table each of the columns came from. Does this matter? Ultimately what matters is the data they contain. Whether UserID came from the User table or the UserQuestion table doesn't really matter. It matters, of course, when you need to update it, but at that point you should already know your schema well enough to determine that.

C++ static virtual members?

This question is over a decade old, but it looks like it gets a good amount of traffic, so I wanted to post an alternative using modern C++ features that I haven't seen anywhere else.

This solution uses CRTP and SFINAE to perform static dispatching. That, in itself, is nothing new, but all such implementations I've found lack strict signature checking for "overrides." This implementation requires that the "overriding" method signature exactly matches that of the "overridden" method. This behavior more closely resembles that of virtual functions, while also allowing us to effectively overload and "override" a static method.

Note that I put override in quotes because, strictly speaking, we're not technically overriding anything. Instead, we're calling a dispatch method X with signature Y that forwards all of its arguments to T::X, where T is to the first type among a list of types such that T::X exists with signature Y. This list of types considered for dispatching can be anything, but generally would include a default implementation class and the derived class.

Implementation

#include <experimental/type_traits>

template <template <class...> class Op, class... Types>
struct dispatcher;

template <template <class...> class Op, class T>
struct dispatcher<Op, T> : std::experimental::detected_t<Op, T> {};

template <template <class...> class Op, class T, class... Types>
struct dispatcher<Op, T, Types...>
  : std::experimental::detected_or_t<
    typename dispatcher<Op, Types...>::type, Op, T> {};


// Helper to convert a signature to a function pointer
template <class Signature> struct function_ptr;

template <class R, class... Args> struct function_ptr<R(Args...)> {
    using type = R (*)(Args...);
};


// Macro to simplify creation of the dispatcher
// NOTE: This macro isn't smart enough to handle creating an overloaded
//       dispatcher because both dispatchers will try to use the same
//       integral_constant type alias name. If you want to overload, do it
//       manually or make a smarter macro that can somehow put the signature in
//       the integral_constant type alias name.
#define virtual_static_method(name, signature, ...)                            \
    template <class VSM_T>                                                     \
    using vsm_##name##_type = std::integral_constant<                          \
        function_ptr<signature>::type, &VSM_T::name>;                          \
                                                                               \
    template <class... VSM_Args>                                               \
    static auto name(VSM_Args&&... args)                                       \
    {                                                                          \
        return dispatcher<vsm_##name##_type, __VA_ARGS__>::value(              \
            std::forward<VSM_Args>(args)...);                                  \
    }

Example Usage

#include <iostream>

template <class T>
struct Base {
    // Define the default implementations
    struct defaults {
        static std::string alpha() { return "Base::alpha"; };
        static std::string bravo(int) { return "Base::bravo"; }
    };

    // Create the dispatchers
    virtual_static_method(alpha, std::string(void), T, defaults);
    virtual_static_method(bravo, std::string(int), T, defaults);
    
    static void where_are_the_turtles() {
        std::cout << alpha() << std::endl;  // Derived::alpha
        std::cout << bravo(1) << std::endl; // Base::bravo
    }
};

struct Derived : Base<Derived> {
    // Overrides Base::alpha
    static std::string alpha(){ return "Derived::alpha"; }

    // Does not override Base::bravo because signatures differ (even though
    // int is implicitly convertible to bool)
    static std::string bravo(bool){ return "Derived::bravo"; }
};

int main() {
    Derived::where_are_the_turtles();
}

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

Close Android Application

just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Prevent form redirect OR refresh on submit?

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {
 sendContactForm();
 return false;
});

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" />

Nested lists python

If you really need the indices you can just do what you said again for the inner list:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:

for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

In Java, remove empty elements from a list of Strings

  • This code compiles and runs smoothly.
  • It uses no iterator so more readable.
  • list is your collection.
  • result is filtered form (no null no empty).

public static void listRemove() {
    List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
    List<String> result = new ArrayList<String>();

    for (String str : list) {
        if (str != null && !str.isEmpty()) {
            result.add(str);
        }
    }

    System.out.println(result);
}

How do I find the stack trace in Visual Studio?

Consider this as the current update (Windows 10 (Version 1803) and Visual Studio 2017): I was unable to view the stack trace window and did find an option/menu item to view it. On investigating further, it seems this feature is not available on Windows 10. For further information please refer:

https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/viewing-the-call-stack-in-visual-studio

Copied from the above link: "This feature is not available in Windows 10, version 1507 and later versions of the WDK."

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

Displaying the build date

The above method can be tweaked for assemblies already loaded within the process by using the file's image in memory (as opposed to re-reading it from storage):

using System;
using System.Runtime.InteropServices;
using Assembly = System.Reflection.Assembly;

static class Utils
{
    public static DateTime GetLinkerDateTime(this Assembly assembly, TimeZoneInfo tzi = null)
    {
        // Constants related to the Windows PE file format.
        const int PE_HEADER_OFFSET = 60;
        const int LINKER_TIMESTAMP_OFFSET = 8;

        // Discover the base memory address where our assembly is loaded
        var entryModule = assembly.ManifestModule;
        var hMod = Marshal.GetHINSTANCE(entryModule);
        if (hMod == IntPtr.Zero - 1) throw new Exception("Failed to get HINSTANCE.");

        // Read the linker timestamp
        var offset = Marshal.ReadInt32(hMod, PE_HEADER_OFFSET);
        var secondsSince1970 = Marshal.ReadInt32(hMod, offset + LINKER_TIMESTAMP_OFFSET);

        // Convert the timestamp to a DateTime
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
        var dt = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tzi ?? TimeZoneInfo.Local);
        return dt;
    }
}

Generating an MD5 checksum of a file

change the file_path to your file

import hashlib
def getMd5(file_path):
    m = hashlib.md5()
    with open(file_path,'rb') as f:
        line = f.read()
        m.update(line)
    md5code = m.hexdigest()
    return md5code

XSS filtering function in PHP

I'm was collect most of issues by the web and combine stepping filter for all of them.

After some testing seems it works perfect:


/*
* Total XSS preventer class by Full-R
*
*/

final class xCleaner {

    public static function clean( string $html ): string {

        return self::cleanXSS(

            preg_replace(

                [

                    '/\s?<iframe[^>]*?>.*?<\/iframe>\s?/si',
                    '/\s?<style[^>]*?>.*?<\/style>\s?/si',
                    '/\s?<script[^>]*?>.*?<\/script>\s?/si',
                    '#\son\w*="[^"]+"#',

                ],

                [
                    '',
                    '',
                    ''
                ],

                $html

            )

        );

    }

    protected static function hexToSymbols( string $s ): string {

        return html_entity_decode($s, ENT_XML1, 'UTF-8');

    }

    protected static function escape( string $s, string $m = 'attr' ): string {

        preg_match_all('/data:\w+\/([a-zA-Z]*);base64,(?!_#_#_)([^)\'"]*)/mi', $s, $b64, PREG_OFFSET_CAPTURE);

        if( count( array_filter( $b64 ) ) > 0 ) {

            switch( $m ) {

                case 'attr':

                    $xclean = self::cleanXSS(

                                        urldecode(

                                            base64_decode(

                                                $b64[ 2 ][ 0 ][ 0 ]

                                            )

                                        )

                                );

                    break;

                case 'tag':

                    $xclean = self::cleanTagInnerXSS(

                                        urldecode(

                                            base64_decode(

                                                $b64[ 2 ][ 0 ][ 0 ]

                                            )

                                        )

                                );

                    break;

            }

            return substr_replace(

                $s,

                '_#_#_'. base64_encode( $xclean ),

                $b64[ 2 ][ 0 ][ 1 ],

                strlen( $b64[ 2 ][ 0 ][ 0 ] )

            );

        }
        else {

            return $s;

        }

    }

    protected static function cleanXSS( string $s ): string {

        // base64 injection prevention
        $st = self::escape( $s, 'attr' );

        return preg_replace([

                // JSON unicode
                '/\\\\u?{?([a-f0-9]{4,}?)}?/mi',                                                                    // [1] unicode JSON clean

                // Data b64 safe
                '/\*\w*\*/mi',                                                                                            // [2] unicode simple clean

                // Malware payloads
                '/:?e[\s]*x[\s]*p[\s]*r[\s]*e[\s]*s[\s]*s[\s]*i[\s]*o[\s]*n[\s]*(:|;|,)?\w*/mi',    // [3]  (:expression) evalution
                '/l[\s]*i[\s]*v[\s]*e[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',         // [4]  (livescript:) evalution
                '/j[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',                                 // [5]  (jscript:) evalution
                '/j[\s]*a[\s]*v[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',       // [6]  (javascript:) evalution
                '/b[\s]*e[\s]*h[\s]*a[\s]*v[\s]*i[\s]*o[\s]*r[\s]*(:|;|,)?\w*/mi',                     // [7]  (behavior:) evalution
                '/v[\s]*b[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',                      // [8]  (vsbscript:) evalution
                '/v[\s]*b[\s]*s[\s]*(:|;|,)?\w*/mi',                                                              // [9]  (vbs:) evalution
                '/e[\s]*c[\s]*m[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t*(:|;|,)?\w*/mi',        // [10] (ecmascript:) possible ES evalution
                '/b[\s]*i[\s]*n[\s]*d[\s]*i[\s]*n[\s]*g*(:|;|,)?\w*/mi',                                 // [11] (-binding) payload
                '/\+\/v(8|9|\+|\/)?/mi',                                                                          // [12] (UTF-7 mutation)

                // Some entities
                '/&{\w*}\w*/mi',                                                                                   // [13] html entites clenup
                '/&#\d+;?/m',                                                                                      // [14] html entites clenup

                // Script tag encoding mutation issue
                '/\¼\/?\w*\¾\w*/mi',                                                                         // [21] mutation KOI-8
                '/\+ADw-\/?\w*\+AD4-\w*/mi',                                                         // [22] mutation old encodings

                '/\/*?%00*?\//m',

                // base64 escaped
                '/_#_#_/mi',                                                                                       // [23] base64 escaped marker cleanup
             
            ],

            // Replacements steps :: 23
            ['&#x$1;', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],

            str_ireplace(

                ['\u0', '&colon;', '&tab;', '&newline;'],
                ['\0', ':', '', ''],

            // U-HEX prepare step
            self::hexToSymbols( $st ))

        );

    }

}

Also you can add Tidy markup correction to make HTML valid.

percentage of two int?

Two options:

Do the division after the multiplication:

int n = 25;
int v = 100;
int percent = n * 100 / v;

Convert an int to a float before dividing

int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
//  float percent = (float) n * 100 / v;
//  float percent = n * 100 / (float) v;

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Execute php file from another php

exec('wget http://<url to the php script>') worked for me.

It enable me to integrate two php files that were designed as web pages and run them as code to do work without affecting the calling page

Better way to sum a property value in an array

Here's a solution I find more flexible:

function sumOfArrayWithParameter (array, parameter) {
  let sum = null;
  if (array && array.length > 0 && typeof parameter === 'string') {
    sum = 0;
    for (let e of array) if (e && e.hasOwnProperty(parameter)) sum += e[parameter];
  }
  return sum;
}

To get the sum, simply use it like that:

let sum = sumOfArrayWithParameter(someArray, 'someProperty');

Combine multiple JavaScript files into one JS file

This may be a bit of effort but you could download my open-source wiki project from codeplex:

http://shuttlewiki.codeplex.com

It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.

The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)

The ShuttleWiki project shows how to use it in the post-build event.

Write to text file without overwriting in Java

You can even use FileOutputStream to get what you need. This is how it can be done,

File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();

TypeError: a bytes-like object is required, not 'str'

Encoding and decoding can solve this in Python 3:

Client Side:

>>> host='127.0.0.1'
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect((host,port))
>>> st='connection done'
>>> byt=st.encode()
>>> s.send(byt)
15
>>>

Server Side:

>>> host=''
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.bind((host,port))
>>> s.listen(1)
>>> conn ,addr=s.accept()
>>> data=conn.recv(2000)
>>> data.decode()
'connection done'
>>>

Android Studio installation on Windows 7 fails, no JDK found

Install the latest JDK in your system from JDK 7 and JRE 7 Installation Guide.

JAVA_HOME -> C:\Program Files\Java\jdk1.7.0_4
path -> C:\Program Files\Java\jdk1.7.0_4\bin

Auto-scaling input[type=text] to width of value?

My jQuery plugin works for me:

Usage:

    $('form input[type="text"]').autoFit({

    });

Source code of jquery.auto-fit.js:

;
(function ($) {
    var methods = {
        init: function (options) {
            var settings = $.extend(true, {}, $.fn.autoFit.defaults, options);
            var $this = $(this);

            $this.keydown(methods.fit);

            methods.fit.call(this, null);

            return $this;
        },

        fit: function (event) {
            var $this = $(this);

            var val = $this.val().replace(' ', '-');
            var fontSize = $this.css('font-size');
            var padding = $this.outerWidth() - $this.width();
            var contentWidth = $('<span style="font-size: ' + fontSize + '; padding: 0 ' + padding / 2 + 'px; display: inline-block; position: absolute; visibility: hidden;">' + val + '</span>').insertAfter($this).outerWidth();

            $this.width((contentWidth + padding) + 'px');

            return $this;
        }
    };

    $.fn.autoFit = function (options) {
        if (typeof options == 'string' && methods[options] && typeof methods[options] === 'function') {
            return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof options === 'object' || !options) {
            // Default to 'init'
            return this.each(function (i, element) {
                methods.init.apply(this, [options]);
            });
        } else {
            $.error('Method ' + options + ' does not exist on jquery.auto-fit.');
            return null;
        }
    };

    $.fn.autoFit.defaults = {};

})(this['jQuery']);

MySQL JOIN with LIMIT 1 on joined table

When using postgres you can use the DISTINCT ON syntex to limit the number of columns returned from either table.

Here is a sample of the code:

SELECT c.id, c.title, p.id AS product_id, p.title FROM categories AS c JOIN ( SELECT DISTINCT ON(p1.id) id, p1.title, p1.category_id FROM products p1 ) p ON (c.id = p.category_id)
The trick is not to join directly on the table with multiple occurrences of the id, rather, first create a table with only a single occurrence for each id

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

SQL multiple columns in IN clause

You could do like this:

SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));

The sqlfiddle.

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

symfony 2 twig limit the length of the text and put three dots

I wrote this simple marco for the same purpose, hope it helps:

{%- macro stringMaxLength(str, maxLength) -%}
    {%- if str | length < maxLength -%}
        {{ str }}
    {%- else -%}
        {{ str|slice(0, maxLength) }}...
    {%- endif -%}
{%- endmacro -%}

Usage Example #1 (Output: "my long string here ..."):

{{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}

Usage Example #2 (Output: "shorter string!"):

{{ _self.stringMaxLength("shorter string!", 20) }}

How to use onClick with divs in React.js

This also works:

I just changed with this.state.color==='white'?'black':'white'.

You can also pick the color from drop-down values and update in place of 'black';

(CodePen)

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Effective method to hide email from spam bots

The best method hiding email addresses is only good until bot programmer discover this "encoding" and implement a decryption algorithm.

The JavaScript option won't work long, because there are a lot of crawler interpreting JavaScript.

There's no answer, imho.

How to stop console from closing on exit?

You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:

  • in Visual Studio, right click your project in Solution Explorer or the tab with the file name if you have a file in the solution open, and choose Open Containing Folder or Open in Windows Explorer
  • in the resulting Windows Explorer window, double-click your way to the folder with the exe
  • Shift-right-click in the background of the explorer window and choose Open Commmand Window here
  • type the first letter of your executable and press tab until the full name appears
  • press enter

I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.

Java, how to compare Strings with String Arrays

import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

Adding a newline into a string in C#

Then just modify the previous answers to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don't want the newlines in the text file, then don't preserve it.

How do I make the first letter of a string uppercase in JavaScript?

yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)

VBA: Selecting range by variables

I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.

This did work though:

Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select

That took care of converting the cell's numerical location to what Range expects, which is the A1 format.

What is the return value of os.system() in Python?

The return value of os.system is OS-dependant.

On Unix, the return value is a 16-bit number that contains two different pieces of information. From the documentation:

a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)

So if the signal number (low byte) is 0, it would, in theory, be safe to shift the result by 8 bits (result >> 8) to get the error code. The function os.WEXITSTATUS does exactly this. If the error code is 0, that usually means that the process exited without errors.

On Windows, the documentation specifies that the return value of os.system is shell-dependant. If the shell is cmd.exe (the default one), the value is the return code of the process. Again, 0 would mean that there weren't errors.

For others error codes:

aspx page to redirect to a new page

You could also do this is plain in html with a meta tag:

<html>
<head>
  <meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>

SVN: Is there a way to mark a file as "do not commit"?

Some of the proposed ideas can be implemented like this:

On Windows in PowerShell

add all to default list.ps1

dir -Recurse | ? { -not $_.PSIsContainer } | % { svn cl default $_.FullName }

add to ignore list.ps1

 dir file1 ... filN  % { $_.FullName } > ignore-on-commit
 cat .\ignore-on-commit | % { svn cl ignore-on-commit $_ }
 svn add ignore-on-commit

Now, you can alias svn ci --changelist default so that you don't have to specify it each time. The additional benefit is that you can store the ignore-on-commit list (if you want) in the repository.

I do this for some files which are constantly regenerated but rarely actually changed by hand. For instance I add revision number to my config files on specific placeholders so files are changed on each commit, yet manual change is rare.

Laravel Eloquent - distinct() and count() not working properly together

$solution = $query->distinct()
            ->groupBy
            (
                [
                    'array',
                    'of',
                    'columns',
                ]
            )
            ->addSelect(
                [
                    'columns',
                    'from',
                    'the',
                    'groupby',
                ]
            )
            ->get();

Remember the group by is optional,this should work in most cases when you want a count group by to exclude duplicated select values, the addSelect is a querybuilder instance method.

How do I set the default page of my application in IIS7?

  1. On IIS Manager select your page in the Sites tree.
  2. Double click on configuration editor.
  3. Select system.webServer/defaultDocument in the drop-down.
  4. Change the "default.aspx" to the name of your document.

How to find the installed pandas version

Run

pip freeze

It works the same as above.

pip show pandas

Displays information about a specific package. For more information, check out pip help

How do I convert Long to byte[] and back in java

You could use the Byte conversion methods from Google Guava.

Example:

byte[] bytes = Longs.toByteArray(12345L);

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

Animate the transition between fragments

If you can afford to tie yourself to just Lollipop and later, this seems to do the trick:

import android.transition.Slide;
import android.util.Log;
import android.view.Gravity;
.
.
.
f = new MyFragment();
f.setEnterTransition(new Slide(Gravity.END));
f.setExitTransition(new Slide(Gravity.START));
getFragmentManager()
    .beginTransaction()
    .replace(R.id.content, f, FRAG_TAG)  // FRAG_TAG is the tag for your fragment
    .commit();

Kotlin version:

f = MyFragment().apply {
    enterTransition = Slide(Gravity.END)
    exitTransition = Slide(Gravity.START)
}
fragmentManager
    .beginTransaction()
    .replace(R.id.content, f, FRAG_TAG)  // FRAG_TAG is the tag for your fragment
    .commit();

Hope this helps.

Calling a function from a string in C#

A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)

Ex. slightly modified from the project documentation:

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
        if (name == "MyFunction")
            args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
    };

// confirm it worked
Debug.Assert(19 == e.Evaluate());

And within the EvaluateFunction delegate you would call your existing function.

Understanding The Modulus Operator %

modulus is remainders system.

So 7 % 5 = 2.

5 % 7 = 5

3 % 7 = 3

2 % 7 = 2

1 % 7 = 1

When used inside a function to determine the array index. Is it safe programming ? That is a different question. I guess.

JAX-RS — How to return JSON and HTTP status code together?

In case you want to change the status code because of an exception, with JAX-RS 2.0 you can implement an ExceptionMapper like this. This handles this kind of exception for the whole app.

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<EJBAccessException> {

    @Override
    public Response toResponse(EJBAccessException exception) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
    }

}

Center content vertically on Vuetify

Update for new vuetify version

In v.2.x.x , we can use align and justify. We have below options for setup the horizontal and vertical alignment.

  1. PROPS align : 'start','center','end','baseline','stretch'

  2. PRPS justify : 'start','center','end','space-around','space-between'

<v-container fill-height fluid>
  <v-row align="center"
      justify="center">
      <v-col></v-col>
  </v-row>
</v-container>

For more details please refer this vuetify grid-system and you could check here with working codepen demo.


Original answer

You could use align-center for layout and fill-height for container.

Demo with v1.x.x

_x000D_
_x000D_
new Vue({
  el: '#app' 
})
_x000D_
.bg{
    background: gray;
    color: #fff;
    font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>

<div id="app">
  <v-app>
      <v-container bg fill-height grid-list-md text-xs-center>
        <v-layout row wrap align-center>
          <v-flex>
            Hello I am center to vertically using "align-center".
          </v-flex>
        </v-layout>
      </v-container>
  </v-app>
</div>
_x000D_
_x000D_
_x000D_

How to make Java honor the DNS Caching Timeout?

To expand on Byron's answer, I believe you need to edit the file java.security in the %JRE_HOME%\lib\security directory to effect this change.

Here is the relevant section:

#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
#       serious security implications. Do not set it unless 
#       you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1 

Documentation on the java.security file here.

CSS background-image-opacity?

You can put a second element inside the element you wish to have a transparent background on.

<div class="container">
    <div class="container-background"></div>
    <div class="content">
         Yay, happy content!
    </div>
</div>

Then make the '.container-background' positioned absolutely to cover the parent element. At this point you'll be able to adjust the opacity of it without affecting the opacity of the content inside '.container'.

.container {
    position: relative;
}
.container .container-background {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: url(background.png);
    opacity: 0.5;
}
.container .content {
    position: relative;
    z-index: 1;
}

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Java Desktop application: SWT vs. Swing

Pros Swing:

  • part of java library, no need for additional native libraries
  • works the same way on all platforms
  • Integrated GUI Editor in Netbeans and Eclipse
  • good online tutorials by Sun/Oracle
  • Supported by official java extensions (like java OpenGL)

Cons Swing:

  • Native look and feel may behave different from the real native system.
  • heavy components (native/awt) hide swing components, not a problem most of the time as as use of heavy components is rather rare

Pros SWT:

  • uses native elements when possible, so always native behavior
  • supported by eclipse, gui editor VEP (VEP also supports Swing and AWT)
  • large number of examples online
  • has an integrated awt/swt bridge to allow use of awt and swing components

Cons SWT:

  • requires native libraries for each supported system
  • may not support every behavior on all systems because of native resources used (hint options)
  • managing native resources, while native components will often be disposed with their parent other resources such as Fonts have to be manually released or registered as dispose listener to a component for automatic release.

How to uninstall a package installed with pip install --user

example to uninstall package 'oauth2client' on MacOS:

pip uninstall oauth2client

Difference between Fact table and Dimension table?

  1. The fact table mainly consists of business facts and foreign keys that refer to primary keys in the dimension tables. A dimension table consists mainly of descriptive attributes that are textual fields.
  2. A dimension table contains a surrogate key, natural key, and a set of attributes. On the contrary, a fact table contains a foreign key, measurements, and degenerated dimensions.
  3. Dimension tables provide descriptive or contextual information for the measurement of a fact table. On the other hand, fact tables provide the measurements of an enterprise.
  4. When comparing the size of the two tables, a fact table is bigger than a dimensional table. In a comparison table, more dimensions are presented than the fact tables. In a fact table, less numbers of facts are observed.
  5. The dimension table has to be loaded first. While loading the fact tables, one should have to look at the dimension table. This is because the fact table has measures, facts, and foreign keys that are the primary keys in the dimension table.

Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo

How to set an image's width and height without stretching it?

#logo {
    width: 400px;
    height: 200px;

    /*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
    object-fit:scale-down;
}

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Simple check can be made. I am currently using Spring MVC architecture along with hibernate. I had missed writing @Controller annotations just above class name. This was causing the problem for me.

@Controller
public class MyClass{
    ...
}

Hope this simple check solves your problem.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

How to use Visual Studio Code as Default Editor for Git

GitPad sets your current text editor as the default editor for Git.

My default editor for .txt files in Windows 10 is Visual Studio Code and running GitPad once made it the default editor for Git. I haven't experienced the problems mentioned in the question (Git waits until VS Code window is closed in my case).

(The link for the .exe file didn't work for me, you may need to compile the source yourself.)

Best way to list files in Java, sorted by Date Modified?

You can try guava Ordering:

Function<File, Long> getLastModified = new Function<File, Long>() {
    public Long apply(File file) {
        return file.lastModified();
    }
};

List<File> orderedFiles = Ordering.natural().onResultOf(getLastModified).
                          sortedCopy(files);

AngularJS - Animate ng-view transitions

1.Install angular-animate

2.Add the animation effect to the class ng-enter for page entering animation and the class ng-leave for page exiting animation

for reference: this page has a free resource on angular view transition https://e21code.herokuapp.com/angularjs-page-transition/

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I'm not using different versions of libraries and got the same error, it's happened after remove buildToolsVersion in AS RC 1, but adding tools:node="replace" did the trick, just add this into your manifest.xml inside <application ..../> block:

<meta-data 
 tools:node="replace"
 android:name="com.google.android.gms.version"
 android:value="@integer/google_play_services_version" />

How to use PHP with Visual Studio

Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.

This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.

Maybe you can now understand why your approach so far could never work out.

How to add a list item to an existing unordered list?

jQuery comes with the following options which could fulfil your need in this case:

append is used to add an element at the end of the parent div specified in the selector:

$('ul.tabs').append('<li>An element</li>');

prepend is used to add an element at the top/start of the parent div specified in the selector:

$('ul.tabs').prepend('<li>An element</li>');

insertAfter lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:

$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>

insertBefore will do the opposite of the above:

$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>

is it possible to update UIButton title/text programmatically?

Turns out the docs tell you the answer! The UIButton will ignore the title change if it already has an Attributed String to use (with seems to be the default you get when using Xcode interface builder).

I used the following:

[self.loginButton 
     setAttributedTitle:[[NSAttributedString alloc] initWithString:@"Error !!!" attributes:nil] 
     forState:UIControlStateDisabled];
[self.loginButton setEnabled:NO];

Twitter bootstrap 3 two columns full height

So it seems your best option is going with the padding-bottom countered by negative margin-bottom strategy.

I made two examples. One with <header> inside .container, and another with it outside.

Both versions should work properly. Note the use of the following @media query so that it removes the extra padding on smaller screens...

@media screen and (max-width:991px) {
    .content { padding-top:0; }
}

Other than that, those examples should fix your problem.

Write to UTF-8 file in Python

I use the file *nix command to convert a unknown charset file in a utf-8 file

# -*- encoding: utf-8 -*-

# converting a unknown formatting file in utf-8

import codecs
import commands

file_location = "jumper.sub"
file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)

file_stream = codecs.open(file_location, 'r', file_encoding)
file_output = codecs.open(file_location+"b", 'w', 'utf-8')

for l in file_stream:
    file_output.write(l)

file_stream.close()
file_output.close()

contenteditable change events

_x000D_
_x000D_
const p = document.querySelector('p')_x000D_
const result = document.querySelector('div')_x000D_
const observer = new MutationObserver((mutationRecords) => {_x000D_
  result.textContent = mutationRecords[0].target.data_x000D_
  // result.textContent = p.textContent_x000D_
})_x000D_
observer.observe(p, {_x000D_
  characterData: true,_x000D_
  subtree: true,_x000D_
})
_x000D_
<p contenteditable>abc</p>_x000D_
<div />
_x000D_
_x000D_
_x000D_

Changing background colour of tr element on mouseover

Try it

<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">

<script>
function mOvr(src,clrOver) { 
  if (!src.contains(event.fromElement)) { 
  src.bgColor = clrOver; 
  } 
} 
function mOut(src,clrIn) { 
  if (!src.contains(event.toElement)) { 
  src.bgColor = clrIn; 
  } 
} 
</script>

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

401 Unauthorized: Access is denied due to invalid credentials

I had a slightly different problem. The credential problem was for the underlying user running the application, not the user trying to login. One way to test this is to go to IIS Management -> Sites -> Your Site -> Basic Settings -> Test Settings.

Scrolling an iframe with JavaScript?

I've also had trouble using any type of javascript "scrollTo" function in an iframe on an iPad. Finally found an "old" solution to the problem, just hash to an anchor.

In my situation after an ajax return my error messages were set to display at the top of the iframe but if the user had scrolled down in what is an admittedly long form the submission goes out and the error appears "above the fold". Additionally, assuming the user did scroll way down the top level page was scrolled away from 0,0 and was also hidden.

I added

<a name="ptop"></a>

to the top of my iframe document and

<a name="atop"></a>

to the top of my top level page

then

    $(document).ready(function(){
      $("form").bind("ajax:complete",
        function() {
          location.hash = "#";
          top.location.hash = "#";
          setTimeout('location.hash="#ptop"',150);
          setTimeout('top.location.hash="#atop"',350);
        }
      )
    });

in the iframe.

You have to hash the iframe before the top page or only the iframe will scroll and the top will remain hidden but while it's a tiny bit "jumpy" due to the timeout intervals it works. I imagine tags throughout would allow various "scrollTo" points.

How to declare a global variable in php?

You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.

Ignore python multiple return value

If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.

# Example 1: a is 1 and b is [2, 3]

a, *b = [1, 2, 3]

# Example 2: a is 1, b is [2, 3], and c is 4

a, *b, c = [1, 2, 3, 4]

# Example 3: b is [1, 2] and c is 3

*b, c = [1, 2, 3]       

# Example 4: a is 1 and b is []

a, *b = [1]

How to get a MemoryStream from a Stream in .NET?

public static void Do(Stream in)
{
    _ms = new MemoryStream();
    byte[] buffer = new byte[65536];
    while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
        _ms.Write (buffer, 0, read);
}

How do I convert an integer to binary in JavaScript?

This is my code:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

"unadd" a file to svn before commit

Use svn revert --recursive folder_name


Warning

svn revert is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.

http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html

Parse String to Date with Different Format in Java

tl;dr

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details

The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.

You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console.

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | output: mardi 19 mai 2009

See in action in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

'' is not recognized as an internal or external command, operable program or batch file

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

Round double value to 2 decimal places

 value = (round(value*100)) / 100.0;

How to inflate one view with a layout

With Kotlin, you can use:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

How to compare binary files to check if they are the same?

Try diff -s

Short answer: run diff with the -s switch.

Long answer: read on below.


Here's an example. Let's start by creating two files with random binary contents:

$ dd if=/dev/random bs=1k count=1 of=test1.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0100332 s, 102 kB/s

                                                                                  
$ dd if=/dev/random bs=1k count=1 of=test2.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0102889 s, 99,5 kB/s

Now let's make a copy of the first file:

$ cp test1.bin copyoftest1.bin

Now test1.bin and test2.bin should be different:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

... and test1.bin and copyoftest1.bin should be identical:

$ diff test1.bin copyoftest1.bin

But wait! Why is there no output?!?

The answer is: this is by design. There is no output on identical files.

But there are different error codes:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

$ echo $?
1


$ diff test1.bin copyoftest1.bin

$ echo $?
0

Now fortunately you don't have to check error codes each and every time because you can just use the -s (or --report-identical-files) switch to make diff be more verbose:

$ diff -s test1.bin copyoftest1.bin
Files test1.bin and copyoftest1.bin are identical

Map implementation with duplicate keys

 1, Map<String, List<String>> map = new HashMap<>();

this verbose solution has multiple drawbacks and is prone to errors. It implies that we need to instantiate a Collection for every value, check for its presence before adding or removing a value, delete it manually when no values are left, etcetera.

2, org.apache.commons.collections4.MultiMap interface
3, com.google.common.collect.Multimap interface 

java-map-duplicate-keys

How to abort a Task like aborting a Thread (Thread.Abort method)?

The guidance on not using a thread abort is controversial. I think there is still a place for it but in exceptional circumstance. However you should always attempt to design around it and see it as a last resort.

Example;

You have a simple windows form application that connects to a blocking synchronous web service. Within which it executes a function on the web service within a Parallel loop.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    Thread.Sleep(120000); // pretend web service call

});

Say in this example, the blocking call takes 2 mins to complete. Now I set my MaxDegreeOfParallelism to say ProcessorCount. iListOfItems has 1000 items within it to process.

The user clicks the process button and the loop commences, we have 'up-to' 20 threads executing against 1000 items in the iListOfItems collection. Each iteration executes on its own thread. Each thread will utilise a foreground thread when created by Parallel.ForEach. This means regardless of the main application shutdown, the app domain will be kept alive until all threads have finished.

However the user needs to close the application for some reason, say they close the form. These 20 threads will continue to execute until all 1000 items are processed. This is not ideal in this scenario, as the application will not exit as the user expects and will continue to run behind the scenes, as can be seen by taking a look in task manger.

Say the user tries to rebuild the app again (VS 2010), it reports the exe is locked, then they would have to go into task manager to kill it or just wait until all 1000 items are processed.

I would not blame you for saying, but of course! I should be cancelling these threads using the CancellationTokenSource object and calling Cancel ... but there are some problems with this as of .net 4.0. Firstly this is still never going to result in a thread abort which would offer up an abort exception followed by thread termination, so the app domain will instead need to wait for the threads to finish normally, and this means waiting for the last blocking call, which would be the very last running iteration (thread) that ultimately gets to call po.CancellationToken.ThrowIfCancellationRequested. In the example this would mean the app domain could still stay alive for up to 2 mins, even though the form has been closed and cancel called.

Note that Calling Cancel on CancellationTokenSource does not throw an exception on the processing thread(s), which would indeed act to interrupt the blocking call similar to a thread abort and stop the execution. An exception is cached ready for when all the other threads (concurrent iterations) eventually finish and return, the exception is thrown in the initiating thread (where the loop is declared).

I chose not to use the Cancel option on a CancellationTokenSource object. This is wasteful and arguably violates the well known anti-patten of controlling the flow of the code by Exceptions.

Instead, it is arguably 'better' to implement a simple thread safe property i.e. Bool stopExecuting. Then within the loop, check the value of stopExecuting and if the value is set to true by the external influence, we can take an alternate path to close down gracefully. Since we should not call cancel, this precludes checking CancellationTokenSource.IsCancellationRequested which would otherwise be another option.

Something like the following if condition would be appropriate within the loop;

if (loopState.ShouldExitCurrentIteration || loopState.IsExceptional || stopExecuting) {loopState.Stop(); return;}

The iteration will now exit in a 'controlled' manner as well as terminating further iterations, but as I said, this does little for our issue of having to wait on the long running and blocking call(s) that are made within each iteration (parallel loop thread), since these have to complete before each thread can get to the option of checking if it should stop.

In summary, as the user closes the form, the 20 threads will be signaled to stop via stopExecuting, but they will only stop when they have finished executing their long running function call.

We can't do anything about the fact that the application domain will always stay alive and only be released when all foreground threads have completed. And this means there will be a delay associated with waiting for any blocking calls made within the loop to complete.

Only a true thread abort can interrupt the blocking call, and you must mitigate leaving the system in a unstable/undefined state the best you can in the aborted thread's exception handler which goes without question. Whether that's appropriate is a matter for the programmer to decide, based on what resource handles they chose to maintain and how easy it is to close them in a thread's finally block. You could register with a token to terminate on cancel as a semi workaround i.e.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    using (cts.Token.Register(Thread.CurrentThread.Abort))
    {
        Try
        {
           Thread.Sleep(120000); // pretend web service call          
        }
        Catch(ThreadAbortException ex)
        {
           // log etc.
        }
        Finally
        {
          // clean up here
        }
    }

});

but this will still result in an exception in the declaring thread.

All things considered, interrupt blocking calls using the parallel.loop constructs could have been a method on the options, avoiding the use of more obscure parts of the library. But why there is no option to cancel and avoid throwing an exception in the declaring method strikes me as a possible oversight.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

connecting to MySQL from the command line

See here http://dev.mysql.com/doc/refman/5.0/en/connecting.html

mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME 

The options above means:

-u: username
-p: password (**no space between -p and the password text**)
-h: host
last one is name of the database that you wanted to connect. 

Look into the link, it's detailed there!


As already mentioned by Rick, you can avoid passing the password as the part of the command by not passing the password like this:

mysql -u USERNAME -h HOSTNAMEORIP DATABASENAME -p

People editing this answer: PLEASE DONOT ADD A SPACE between -p and PASSWORD

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

How to access the php.ini file in godaddy shared hosting linux

Procedures:

  • Go to your CPanel
  • Select PHP version
  • Click on the link Switch to PHP options
  • Edit your configuration
  • don't forget to click save

enter image description here

You can also follow this screencast

https://www.youtube.com/watch?v=tdUlIkZcOe0

List of tables, db schema, dump etc using the Python sqlite3 API

Here's a short and simple python program to print out the table names and the column names for those tables (python 2. python 3 follows).

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(zip(*result)[0])
print "\ntables are:"+newline_indent+newline_indent.join(table_names)

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = zip(*result)[1]
    print ("\ncolumn names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names))

db.close()
print "\nexiting."

(EDIT: I have been getting periodic vote-ups on this, so here is the python3 version for people who are finding this answer)

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(list(zip(*result))[0])
print ("\ntables are:"+newline_indent+newline_indent.join(table_names))

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = list(zip(*result))[1]
    print (("\ncolumn names for %s:" % table_name)
           +newline_indent
           +(newline_indent.join(column_names)))

db.close()
print ("\nexiting.")

Should I use alias or alias_method?

alias_method can be redefined if need be. (it's defined in the Module class.)

alias's behavior changes depending on its scope and can be quite unpredictable at times.

Verdict: Use alias_method - it gives you a ton more flexibility.

Usage:

def foo
  "foo"
end

alias_method :baz, :foo

Calculate date/time difference in java

This is more of a maths problem than a java problem basically.

The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:

  • divide by 1000 to get the number of seconds -> rest is milliseconds
  • divide that by 60 to get number of minutes -> rest are seconds
  • divide that by 60 to get number of hours -> rest are minutes

or in java:

int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;

JavaScript: How to get parent element by selector?

Here is simple way to access parent id

document.getElementById("child1").parentNode;

will do the magic for you to access the parent div.

<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>

ERROR 1067 (42000): Invalid default value for 'created_at'

The problem is because of sql_modes. Please check your current sql_modes by command:

show variables like 'sql_mode' ; 

And remove the sql_mode "NO_ZERO_IN_DATE,NO_ZERO_DATE" to make it work. This is the default sql_mode in mysql new versions.

You can set sql_mode globally as root by command:

set global sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

Understanding colors on Android (six characters)

If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).

If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).

So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).

See the "Color" documentation for the supported formats.

How to add a search box with icon to the navbar in Bootstrap 3?

You could use the segmented buttons example from Bootstrap 3:

<form action="" class="navbar-form navbar-right">
   <div class="input-group">
       <input type="Search" placeholder="Search..." class="form-control" />
       <div class="input-group-btn">
           <button class="btn btn-info">
           <span class="glyphicon glyphicon-search"></span>
           </button>
       </div>
   </div>
</form>

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

Kotlin: How to get and set a text to TextView in Android using Kotlin?

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.

val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
    textView.text = getString(R.string.name)
}

To get the values from the Textview we have to use this method

 val str: String = textView.text.toString()

 println("the value is $str")

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

SQL Server Convert Varchar to Datetime

Try the below

select Convert(Varchar(50),yourcolumn,103) as Converted_Date from yourtbl

Put request with simple string as request body

Another simple solution is to surround the content variable in your given code with braces like this:

 let content = 'Hello world' 
 axios.put(url, {content}).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

Caveat: But this will not send it as string; it will wrap it in a json body that will look like this: {content: "Hello world"}

Bootstrap 3 Navbar with Logo

<header class="navbar navbar-inverse header-outer" role="banner">
  <div class="container form-inline">
    <img src="@Url.Content(" ~/Content/img/Logo-Sample.png ")" alt="Image" id="logo" class="img-responsive pull-left" />

    <div class="pull-right padding-top">
      <form class="hidden-xs" role="form">

        <div class="form-group" style="padding-left:10px">
          <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Username">
        </div>

        <div class="form-group">
          <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">
        </div>
        <div class="form-group navbar-remember">
          <label class="white-font">
            <input type="checkbox" class="white-font"> Remember me
          </label>
        </div>
        <button type="button" class="btn btn-primary form-group" title="Sign In">Sign In</button>
      </form>
    </div>
  </div>

</header>

Please understand the code at your own effort :D This is my draft code and its already working :) Here's the screenshot.

enter image description here

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

TCP vs UDP on video stream

but during a soccer-match, or a concert what does it matter if you are a single minute behind the stream?

To some soccer fans, quite a bit. It has been remarked that delays of even a few seconds present in digital video streams due to encoding (or whatever) can be very annoying when, during high-profile events such as world cup matches, you can hear the cheers and groans from the guys next door (who are watching an undelyed analog program) before you get to see the game moves that caused them.

I think that to someone caring a lot about sports (and those are the biggest group of paying customers for digital TV, at least here in Germany), being a minute behind in a live video stream would be completely unacceptable (As in, they'd switch to your competitor where this doesn't happen).

XAMPP Apache Webserver localhost not working on MAC OS

This solution worked perfectly fine for me..

1) close XAMPP control

2) Open Activity Monitor(Launchpad->Other->Activity Monitor)

3) select filter for All processes (default is My processes)

4) in fulltext search type: httpd

5) kill all httpd items

6) relaunch XAMPP control and launch apache again

Hurray :)

How do I use Wget to download all images into a single folder, from a URL?

Try this:

wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.somedomain.com

Here is some more information:

-nd prevents the creation of a directory hierarchy (i.e. no directories).

-r enables recursive retrieval. See Recursive Download for more information.

-P sets the directory prefix where all files and directories are saved to.

-A sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.

How to parse a text file with C#

You could do something like:

using (TextReader rdr = OpenYourFile()) {
    string line;
    while ((line = rdr.ReadLine()) != null) {
        string[] fields = line.Split('\t'); // THIS LINE DOES THE MAGIC
        int theInt = Convert.ToInt32(fields[1]);
    }
}

The reason you didn't find relevant result when searching for 'formatting' is that the operation you are performing is called 'parsing'.

Creating the checkbox dynamically using JavaScript?

You can create a function:

function changeInputType(oldObj, oTyp, nValue) {
  var newObject = document.createElement('input');
  newObject.type = oTyp;
  if(oldObj.size) newObject.size = oldObj.size;
  if(oldObj.value) newObject.value = nValue;
  if(oldObj.name) newObject.name = oldObj.name;
  if(oldObj.id) newObject.id = oldObj.id;
  if(oldObj.className) newObject.className = oldObj.className;
  oldObj.parentNode.replaceChild(newObject,oldObj);
  return newObject;
}

And you do a call like:

changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);

close fxml window by code, javafx

finally, I found a solution

 Window window =   ((Node)(event.getSource())).getScene().getWindow(); 
            if (window instanceof Stage){
                ((Stage) window).close();
            }

WooCommerce return product object by id

Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63

sample:

// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();  
foreach ($IDs as $id) {

    $_product = $_pf->get_product($id);

    // from here $_product will be a fully functional WC Product object, 
    // you can use all functions as listed in their api
}

You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html

Remove row lines in twitter bootstrap

Add this to your main CSS:

table td {
    border-top: none !important;
}

Use this for newer versions of bootstrap:

.table th, .table td { 
     border-top: none !important; 
 }

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Makefile to compile multiple C programs?

SRC = a.cpp b.cpp
BIN = $(patsubst %.cpp,%,$(SRC))

all: $(BIN)

clean:
    rm -f $(BIN)

.PHONY: all clean

make all will do:

c++     a.cpp   -o a
c++     b.cpp   -o b

If you set CXX and CXXFLAGS variables make will use them.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use the following:

driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

Python constructor and default value

class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []

Cannot find or open the PDB file in Visual Studio C++ 2010

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for. Go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically. Or you may just ignore these warnings if you don't need to see correct call stack in these modules.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

Exit/save edit to sudoers file? Putty SSH

To make changes to sudo from putty/bash:

  • Type visudo and press enter.
  • Navigate to the place you wish to edit using the up and down arrow keys.
  • Press insert to go into editing mode.
  • Make your changes - for example: user ALL=(ALL) ALL.
  • Note - it matters whether you use tabs or spaces when making changes.
  • Once your changes are done press esc to exit editing mode.
  • Now type :wq to save and press enter.
  • You should now be back at bash.
  • Now you can press ctrl + D to exit the session if you wish.

Composer Update Laravel

You can use :

composer self-update --2

To update to 2.0.8 version (Latest stable version)

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

If you have Java installed, you can compress to a ZIP archive using the jar command:

jar -cMf targetArchive.zip sourceDirectory

c = Creates a new archive file.

M = Specifies that a manifest file should not be added to the archive.

f = Indicates target file name.

StringIO in Python3

Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.

Python 2.7

See: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

import numpy as np
from StringIO import StringIO

data = "1, abc , 2\n 3, xxx, 4"

print type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
 ['3' 'xxx' '4']]
"""

print '\n', type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Python 3.5:

import numpy as np
from io import StringIO
import io

data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
 3, xxx, 4
"""

#print(type(data))
"""
<class 'str'>
"""

#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
 [b'3' b'xxx' b'4']]
"""

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Aside:

dtype="|Sx", where x = any of { 1, 2, 3, ...}:

dtypes. Difference between S1 and S2 in Python

"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Just want to share my situation on this matter.

Problem context:

  1. Running composer in a vagrant box.
  2. Was getting this message after try to run composer require "laravel-doctrine/orm:~1.4.13":

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.

  1. Have tried setting php.ini memory limit to -1. (still not working).

Solution:

  1. Apparently my composer.json and composer.lock has some issues. Ran $ composer validate, and the result was: "The lock file is not up to date with the latest changes in composer.json, it is recommended that you run composer update."

  2. So I ran $ composer update, and all dependencies are resolved. Imho, when the dependencies has some issues, maybe the tree building is out of sync, hence the out of memory issue.

Hope this helps anyone out there.

PowerShell To Set Folder Permissions

In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:

$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose

Verbosity is optional in the last line

Authentication issue when debugging in VS2013 - iis express

It appears that the right answer is provided by user3149240 above. However, As Neil Watson pointed out, the applicationhost.config file is at play here.

The changes can actually be made in the VS Property pane or in the file albeit in a different spot. Near the bottom of the applicationhost.config file is a set of location elements. Each app for IIS Express seems to have one of these. Changing the settings in the UI updates this section of the file. So, you can either change the settings through the UI or modify this file.

Here is an example with anonymous auth off and Windows auth on:

<location path="MyApp">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

This is equivalent in the VS UI to:

Anonymous Authentication: Disabled
Windows Authentication: Enabled

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

What is a callback URL in relation to an API?

A callback URL will be invoked by the API method you're calling after it's done. So if you call

POST /api.example.com/foo?callbackURL=http://my.server.com/bar

Then when /foo is finished, it sends a request to http://my.server.com/bar. The contents and method of that request are going to vary - check the documentation for the API you're accessing.

How can I pair socks from a pile efficiently?

I came out with another solution which would not promise fewer operations, neither less time consumption, but it should be tried to see if it can be a good-enough heuristic to provide less time consumption in huge series of sock pairing.

Preconditions: There is no guarantee that there are the same socks. If they are of the same color it doesn't mean they have the same size or pattern. Socks are randomly shuffled. There can be odd number of socks (some are missing, we don't know how many). Prepare to remember a variable "index" and set it to 0.

The result will have one or two piles: 1. "matched" and 2. "missing"

Heuristic:

  1. Find most distinctive sock.
  2. Find its match.
  3. If there is no match, put it on the "missing" pile.
  4. Repeat from 1. until there are no more most distinctive socks.
  5. If there are less then 6 socks, go to 11.
  6. Pair blindly all socks to its neighbor (do not pack it)
  7. Find all matched pairs, pack it and move packed pairs to "matched" pile; If there were no new matches - increment "index" by 1
  8. If "index" is greater then 2 (this could be value dependent on sock number because with greater number of socks there are less chance to pair them blindly) go to 11
  9. Shuffle the rest
  10. Go to 1
  11. Forget "index"
  12. Pick a sock
  13. Find its pair
  14. If there is no pair for the sock, move it to the "missing" pile
  15. If match found pair it, pack pair and move it to the "matched" pile
  16. If there are still more then one socks go to 12
  17. If there is just one left go to 14
  18. Smile satisfied :)

Also, there could be added check for damaged socks also, as if the removal of those. It could be inserted between 2 and 3, and between 13 and 14.

I'm looking forward to hear about any experiences or corrections.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Rails ActiveRecord date between

I would personally created a scope to make it more readable and re-usable:

In you Comment.rb, you can define a scope:

scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}

Then to query created between:

@comment.created_between(1.year.ago, Time.now)

Hope it helps.

Min / Max Validator in Angular 2 Final

Find the custom validator for min number validation. The selector name of our directive is customMin.

custom-min-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMin][formControlName],[customMin][formControl],[customMin][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMinDirective, multi: true}]
})
export class CustomMinDirective implements Validator {
  @Input()
  customMin: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v < this.customMin)? {"customMin": true} : null;
  }
} 

Find the custom validator for max number validation. The selector name of our directive is customMax.

custom-max-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMax][formControlName],[customMax][formControl],[customMax][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMaxDirective, multi: true}]
})
export class CustomMaxDirective implements Validator {
  @Input()
  customMax: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v > this.customMax)? {"customMax": true} : null;
  }
} 

We can use customMax with formControlName, formControl and ngModel attributes.

Using Custom Min and Max Validator in Template-driven Form

We will use our custom min and max validator in template-driven form. For min number validation we have customMin attribute and for max number validation we have customMax attribute. Now find the code snippet for validation.

<input name="num1" [ngModel]="user.num1" customMin="15" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" customMax="50"  #numberTwo="ngModel"> 

We can show validation error messages as following.

<div *ngIf="numberOne.errors?.customMin"> 
     Minimum required number is 15.
</div>  

<div *ngIf="numberTwo.errors?.customMax"> 
     Maximum number can be 50.
</div> 

To assign min and max number we can also use property biding. Suppose we have following component properties.

minNum = 15;
maxNum = 50; 

Now use property binding for customMin and customMax as following.

<input name="num1" [ngModel]="user.num1" [customMin]="minNum" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" [customMax]="maxNum"  #numberTwo="ngModel"> 

Is it possible to decompile a compiled .pyc file into a .py file?

You may try Easy Python Decompiler. It's based on Decompyle++ and Uncompyle2. It's supports decompiling python versions 1.0-3.3

Note: I am the author of the above tool.

How do you declare an interface in C++?

The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance.

C++ supports multiple inheritance, and so a special type isn't needed. An abstract base class with no non-abstract (pure virtual) methods is functionally equivalent to a C#/Java interface.

What is SOA "in plain english"?

I would suggest you read articles by Thomas Erl and Roger Sessions, this will give you a firm handle on what SOA is all about. These are also good resources, look at the SOA explained for your boss one for a layman explanation

Building a SOA

SOA Design Pattern

Achieving integrity in a SOA

Why your SOA should be like a VW Beetle

SOA explained for your boss

WCF Service Performance

How can I split a text file using PowerShell?

I've made a little modification to split files based on size of each part.

##############################################################################
#.SYNOPSIS
# Breaks a text file into multiple text files in a destination, where each
# file contains a maximum number of lines.
#
#.DESCRIPTION
# When working with files that have a header, it is often desirable to have
# the header information repeated in all of the split files. Split-File
# supports this functionality with the -rc (RepeatCount) parameter.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Destination
# (Or -d) The location in which to place the chunked output files.
#
#.PARAMETER Size
# (Or -s) The maximum size of each file. Size must be expressed in MB.
#
#.PARAMETER RepeatCount
# (Or -rc) Specifies the number of "header" lines from the input file that will
# be repeated in each output file. Typically this is 0 or 1 but it can be any
# number of lines.
#
#.EXAMPLE
# Split-File bigfile.csv -s 20 -rc 1
#
#.LINK 
# Out-TempFile
##############################################################################
function Split-File {

    [CmdletBinding(DefaultParameterSetName='Path')]
    param(

        [Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$Path,

        [Alias("PSPath")]
        [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$LiteralPath,

        [Alias('s')]
        [Parameter(Position=2,Mandatory=$true)]
        [Int32]$Size,

        [Alias('d')]
        [Parameter(Position=3)]
        [String]$Destination='.',

        [Alias('rc')]
        [Parameter()]
        [Int32]$RepeatCount

    )

    process {

  # yeah! the cmdlet supports wildcards
        if ($LiteralPath) { $ResolveArgs = @{LiteralPath=$LiteralPath} }
        elseif ($Path) { $ResolveArgs = @{Path=$Path} }

        Resolve-Path @ResolveArgs | %{

            $InputName = [IO.Path]::GetFileNameWithoutExtension($_)
            $InputExt  = [IO.Path]::GetExtension($_)

            if ($RepeatCount) { $Header = Get-Content $_ -TotalCount:$RepeatCount }

   Resolve-Path @ResolveArgs | %{

    $InputName = [IO.Path]::GetFileNameWithoutExtension($_)
    $InputExt  = [IO.Path]::GetExtension($_)

    if ($RepeatCount) { $Header = Get-Content $_ -TotalCount:$RepeatCount }

    # get the input file in manageable chunks

    $Part = 1
    $buffer = ""
    Get-Content $_ -ReadCount:1 | %{

     # make an output filename with a suffix
     $OutputFile = Join-Path $Destination ('{0}-{1:0000}{2}' -f ($InputName,$Part,$InputExt))

     # In the first iteration the header will be
     # copied to the output file as usual
     # on subsequent iterations we have to do it
     if ($RepeatCount -and $Part -gt 1) {
      Set-Content $OutputFile $Header
     }

     # test buffer size and dump data only if buffer is greater than size
     if ($buffer.length -gt ($Size * 1MB)) {
      # write this chunk to the output file
      Write-Host "Writing $OutputFile"
      Add-Content $OutputFile $buffer
      $Part += 1
      $buffer = ""
     } else {
      $buffer += $_ + "`r"
     }
    }
   }
        }
    }
}

Quick unix command to display specific lines in the middle of a file?

You can use the ex command, a standard Unix editor (part of Vim now), e.g.

  • display a single line (e.g. 2nd one):

    ex +2p -scq file.txt
    

    corresponding sed syntax: sed -n '2p' file.txt

  • range of lines (e.g. 2-5 lines):

    ex +2,5p -scq file.txt
    

    sed syntax: sed -n '2,5p' file.txt

  • from the given line till the end (e.g. 5th to the end of the file):

    ex +5,p -scq file.txt
    

    sed syntax: sed -n '2,$p' file.txt

  • multiple line ranges (e.g. 2-4 and 6-8 lines):

    ex +2,4p +6,8p -scq file.txt
    

    sed syntax: sed -n '2,4p;6,8p' file.txt

Above commands can be tested with the following test file:

seq 1 20 > file.txt

Explanation:

  • + or -c followed by the command - execute the (vi/vim) command after file has been read,
  • -s - silent mode, also uses current terminal as a default output,
  • q followed by -c is the command to quit editor (add ! to do force quit, e.g. -scq!).

How to use Session attributes in Spring-mvc

If you want to delete object after each response you don't need session,

If you want keep object during user session , There are some ways:

  1. directly add one attribute to session:

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";
    }
    

    and you can get it from controller like this :

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
    
  2. Make your controller session scoped

    @Controller
    @Scope("session")
    
  3. Scope the Objects ,for example you have user object that should be in session every time:

    @Component
    @Scope("session")
    public class User
     {
        String user;
        /*  setter getter*/
      }
    

    then inject class in each controller that you want

       @Autowired
       private User user
    

    that keeps class on session.

  4. The AOP proxy injection : in spring -xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
      <bean id="user"    class="com.User" scope="session">     
          <aop:scoped-proxy/>
      </bean>
    </beans>
    

    then inject class in each controller that you want

    @Autowired
    private User user
    

5.Pass HttpSession to method:

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";
        }

6.Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();
}

or you can add Model To entire Controller Class like,

@Controller
    @SessionAttributes("ShoppingCart")
    @RequestMapping("/req")
    public class MYController {

        @ModelAttribute("ShoppingCart")
        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session
        }  
      }

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.

To access session jsp

<%=session.getAttribute("ShoppingCart.prop")%>

in Jstl :

<c:out value="${sessionScope.ShoppingCart.prop}"/>

in Thymeleaf:

<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>

mongodb count num of distinct values per field/key

I use this query:

var collection = "countries"; var field = "country"; 
db[collection].distinct(field).forEach(function(value){print(field + ", " + value + ": " + db.hosts.count({[field]: value}))})

Output:

countries, England: 3536
countries, France: 238
countries, Australia: 1044
countries, Spain: 16

This query first distinct all the values, and then count for each one of them the number of occurrences.

Switching to a TabBar tab view programmatically?

Use in AppDelegate.m file:

(void)tabBarController:(UITabBarController *)tabBarController
 didSelectViewController:(UIViewController *)viewController
{

     NSLog(@"Selected index: %d", tabBarController.selectedIndex);

    if (viewController == tabBarController.moreNavigationController)
    {
        tabBarController.moreNavigationController.delegate = self;
    }

    NSUInteger selectedIndex = tabBarController.selectedIndex;

    switch (selectedIndex) {

        case 0:
            NSLog(@"click me %u",self.tabBarController.selectedIndex);
            break;
        case 1:
            NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
            break;

        default:
            break;

    }

}

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

How to add fonts to create-react-app based projects?

  1. Go to Google Fonts https://fonts.google.com/
  2. Select your font as depicted in image below:

enter image description here

  1. Copy and then paste that url in new tab you will get the css code to add that font. In this case if you go to

https://fonts.googleapis.com/css?family=Spicy+Rice

It will open like this:

enter image description here

4, Copy and paste that code in your style.css and simply start using that font like this:

      <Typography
          variant="h1"
          gutterBottom
          style={{ fontFamily: "Spicy Rice", color: "pink" }}
        >
          React Rock
        </Typography>

Result:

enter image description here

Tomcat Server Error - Port 8080 already in use

If you want to regain the 8080 port number you do so by opening the task manager and then process tab, right click java.exe process and click on end process as shown in image attached.

screen shot

CSS text-decoration underline color

You can do it if you wrap your text into a span like:

_x000D_
_x000D_
a {_x000D_
  color: red;_x000D_
  text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
  color: blue;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
  <span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

Node.js global proxy setting

You can try my package node-global-proxy which work with all node versions and most of http-client (axios, got, superagent, request etc.)

after install by

npm install node-global-proxy --save

a global proxy can start by

const proxy = require("node-global-proxy").default;

proxy.setConfig({
  http: "http://localhost:1080",
  https: "https://localhost:1080",
});
proxy.start();

/** Proxy working now! */

More information available here: https://github.com/wwwzbwcom/node-global-proxy

Difference between HashSet and HashMap?

HashSet allows us to store objects in the set where as HashMap allows us to store objects on the basis of key and value. Every object or stored object will be having key.

Android: Reverse geocoding - getFromLocation

First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info

double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
    List<Address> addresses = gc.getFromLocation(lat, lng, 1);
    StringBuilder sb = new StringBuilder();
    if (addresses.size() > 0) {
        Address address = addresses.get(0);
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
            sb.append(address.getAddressLine(i)).append("\n");
            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
    }

City info is now in sb. Now convert the sb to String (using sb.toString() ).

Add days Oracle SQL

Some disadvantage of "INTERVAL '1' DAY" is that bind variables cannot be used for the number of days added. Instead, numtodsinterval can be used, like in this small example:

select trunc(sysdate) + numtodsinterval(:x, 'day') tag
from dual

See also: NUMTODSINTERVAL in Oracle Database Online Documentation

Reading string by char till end of line C/C++

You want to use single quotes:

if(c=='\0')

Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.

However, the end-of-line is represented by the newline character, which is '\n'.

Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.

Aren't Python strings immutable? Then why does a + " " + b work?

You can make a numpy array immutable and use the first element:

numpyarrayname[0] = "write once"

then:

numpyarrayname.setflags(write=False)

or

numpyarrayname.flags.writeable = False

Emulate Samsung Galaxy Tab

I don't know if it is help. Create an AVD for a tablet-type device: Set the target to "Android 3.0" and the skin to "WXGA" (the default skin). You can check this site. http://developer.android.com/guide/practices/optimizing-for-3.0.html

Gitignore not working

Also, comments have to be on their own line. They can't be put after an entry. So this won't work:

/node_modules  # DON'T COMMENT HERE (since nullifies entire line)

But this will work:

# fine to comment here
/node_modules

How can I change Eclipse theme?

enter image description here My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page

How To Auto-Format / Indent XML/HTML in Notepad++

I had to update the proxy settings under Plugins -> Plugin Manager -> Show Plugin Manager -> Settings to see any PlugIns in the "Available" list.

After that, installing "XML Tools" was easy and did the requested job as described above.

How do I create an average from a Ruby array?

Don't have ruby on this pc, but something to this extent should work:

values = [0,4,8,2,5,0,2,6]
total = 0.0
values.each do |val|
 total += val
end

average = total/values.size

How to verify CuDNN installation?

Getting cuDNN Version [Linux]

Use following to find path for cuDNN:

cat $(whereis cudnn.h) | grep CUDNN_MAJOR -A 2

If above doesn't work try this:

cat $(whereis cuda)/include/cudnn.h | grep CUDNN_MAJOR -A 2

Getting cuDNN Version [Windows]

Use following to find path for cuDNN:

C:\>where cudnn*
C:\Program Files\cuDNN6\cuda\bin\cudnn64_6.dll

Then use this to dump version from header file,

type "%PROGRAMFILES%\cuDNN6\cuda\include\cudnn.h" | findstr "CUDNN_MAJOR CUDNN_MINOR CUDNN_PATCHLEVEL"

Getting CUDA Version

This works on Linux as well as Windows:

nvcc --version

SyntaxError: expected expression, got '<'

I had this same error when I migrated a Wordpress site to another server. The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

Refreshing page on click of a button

There are several ways to reload the current page using a button or other trigger. The examples below use a button click to reload the page but you can use a text hyperlink or any trigger you like.

<input type="button" value="Reload Page" onClick="window.location.reload()">

<input type="button" value="Reload Page" onClick="history.go(0)">

<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">

Convert textbox text to integer

Suggest do this in your code-behind before sending down to SQL Server.

 int userVal = int.Parse(txtboxname.Text);

Perhaps try to parse and optionally let the user know.

int? userVal;
if (int.TryParse(txtboxname.Text, out userVal) 
{
  DoSomething(userVal.Value);
}
else
{ MessageBox.Show("Hey, we need an int over here.");   }

The exception you note means that you're not including the value in the call to the stored proc. Try setting a debugger breakpoint in your code at the time you call down into the code that builds the call to SQL Server.

Ensure you're actually attaching the parameter to the SqlCommand.

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@ParamName", SqlDbType.Int);
    cmd.Parameters["@ParamName"].Value = newName;        
    conn.Open();
    string someReturn = (string)cmd.ExecuteScalar();        
}

Perhaps fire up SQL Profiler on your database to inspect the SQL statement being sent/executed.

Get viewport/window height in ReactJS

// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";

export function () {
  useEffect(() => {
    window.addEventListener('resize', () => {
      const myWidth  = window.innerWidth;
      console.log('my width :::', myWidth)
   })
  },[window])

  return (
    <>
      enter code here
   </>
  )
}

How can I get the application's path in a .NET console application?

I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;
       
}

This will return the full C:\\xxx\\xxx formatted path to where your code is.

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

Get Substring - everything before certain char

.Net Fiddle example

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
        Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
        Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());

        Console.ReadKey();
    }
}

static class Helper
{
    public static string GetUntilOrEmpty(this string text, string stopAt = "-")
    {
        if (!String.IsNullOrWhiteSpace(text))
        {
            int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);

            if (charLocation > 0)
            {
                return text.Substring(0, charLocation);
            }
        }

        return String.Empty;
    }
}

Results:

223232
443
34443553
344

34

jQuery click events firing multiple times

.one()

A better option would be .one() :

The handler is executed at most once per element per event type.

$(".bet").one('click',function() {
    //Your function
});

In case of multiple classes and each class needs to be clicked once,

$(".bet").on('click',function() {
    //Your function
    $(this).off('click');   //or $(this).unbind()
});

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Try this:

SELECT
    od.Sku,
    od.mf_item_number,
    od.Qty,
    od.Price,
    s.SupplierId,
    s.SupplierName,
    s.DropShipFees,
    si.Price as cost
FROM
    OrderDetails od
    INNER JOIN Supplier s on s.SupplierId = od.Mfr_ID
    INNER JOIN Group_Master gm on gm.Sku = od.Sku
    INNER JOIN Supplier_Item si on si.SKU = od.Sku and si.SupplierId = s.SupplierID
WHERE
    od.invoiceid = '339740'

This will return multiple rows that are identical except for the cost column. Look at the different cost values that are returned and figure out what is causing the different values. Then ask somebody which cost value they want, and add the criteria to the query that will select that cost.

MySQL Server has gone away when importing large sql file

I got same issue with

$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/jpeg;base64,'.$image_base64;
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);

In \xampp\mysql\bin\my.ini file of phpmyadmin we get only

[mysqldump]
max_allowed_packet=110M

which is just for mysqldump -u root -p dbname . I resolved my issue by replacing above code with

max_allowed_packet=110M
[mysqldump]
max_allowed_packet=110M

How to write to a CSV line by line?

What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

Update just one gem with bundler

It appears that with newer versions of bundler (>= 1.14) it's:

bundle update --conservative gem-name

Reading an Excel file in PHP

I have used following code to read "xls and xlsx" :

    include 'PHPExcel/IOFactory.php';

    $location='sample-excel-files.xlsx';

    $objPHPExcel = PHPExcel_IOFactory::load($location);
    $sheet = $objPHPExcel->getSheet(0);
    $total_rows = $sheet->getHighestRow();
    $total_columns = $sheet->getHighestColumn();
    $set_excel_query_all=array();
    for($row =2; $row <= $total_rows; $row++) {
        $singlerow = $sheet->rangeToArray('A' . $row . ':' . $total_columns . $row, NULL, TRUE, FALSE);
        $single_row=$singlerow[0];
        $set_excel_query['store_id']=$single_row[0];
        $set_excel_query['employee_uid']=$single_row[1];
        $set_excel_query['opus_id']=$single_row[2];
        $set_excel_query['item_description']=$single_row[3];
        if($single_row[4])
        {
            $set_excel_query['opus_transaction_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[4]));
        }
        $set_excel_query['opus_transaction_num']=$single_row[5];
        $set_excel_query['opus_invoice_num']=$single_row[6];
        $set_excel_query['customer_name']=$single_row[7];
        $set_excel_query['mobile_num']=$single_row[8];
        $set_excel_query['opus_amount']=$single_row[9];
        $set_excel_query['rq4_amount']=$single_row[10];
        $set_excel_query['difference']=$single_row[11];
        $set_excel_query['ocomment']=$single_row[12];
        $set_excel_query['mark_delete']=$single_row[13];
        if($single_row[14])
        {
            $set_excel_query['upload_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[14]));
        }
        $set_excel_query_all[]=$set_excel_query;
    }

   print_r($set_excel_query_all); 

How to edit binary file on Unix systems

There's lightweight binary editor, check hexedit. http://www.linux.org/apps/AppId_6968.html. I tried using it for editing ELF binaries in Linux at least.

css 'pointer-events' property alternative for IE

There's a workaround for IE - use inline SVG and set pointer-events="none" in SVG. See my answer in How to make Internet Explorer emulate pointer-events:none?

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

To find first N prime numbers in python

using a regexp :)

#!/usr/bin/python

import re, sys


def isPrime(n):
    # see http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/
    return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None


N = int(sys.argv[1]) # number of primes wanted (from command-line)
M = 100              # upper-bound of search space
l = list()           # result list

while len(l) < N:
    l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l
    M += 100                                # increment upper-bound

print l[:N] # print result list limited to N elements

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

Since people will be coming from Google, make sure you're in the right database.

Running SQL in the 'master' database will often return this error.