Programs & Examples On #Frameworkelement

Provides properties, events and methods to elements to support WPF framework level capabilities such as layout, object lifetime events, databinding and styles.

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

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The documentation on MSDN about the ItemsSource of the DataGridComboBoxColumn says that only static resources, static code or inline collections of combobox items can be bound to the ItemsSource:

To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:

  • A static resource. For more information, see StaticResource Markup Extension.
  • An x:Static code entity. For more information, see x:Static Markup Extension.
  • An inline collection of ComboBoxItem types.

Binding to a DataContext's property is not possible if I understand that correctly.

And indeed: When I make CompanyItems a static property in ViewModel ...

public static ObservableCollection<CompanyItem> CompanyItems { get; set; }

... add the namespace where the ViewModel is located to the window ...

xmlns:vm="clr-namespace:DataGridComboBoxColumnApp"

... and change the binding to ...

<DataGridComboBoxColumn
    ItemsSource="{Binding Source={x:Static vm:ViewModel.CompanyItems}}" 
    DisplayMemberPath="Name"
    SelectedValuePath="ID"
    SelectedValueBinding="{Binding CompanyID}" />

... then it works. But having the ItemsSource as a static property might be sometimes OK, but it is not always what I want.

Setting Margin Properties in code

One would guess that (and my WPF is a little rusty right now) that Margin takes an object and cannot be directly changed.

e.g

MyControl.Margin = new Margin(10,0,0,0);

Unable to open project... cannot be opened because the project file cannot be parsed

Steps to be followed:- 1.Navigate to folder where your projectName.xcodeproj 2.Right click and select 'Show Package Contents'. You will be able to see list of files with .pbxproj extension. 3.Select project.pbxproj. Right click and open this file using 'Text Edit'. 4.You will be able to see <<<<<<, ============ and >>>>>>>>>>. These are generally conflicts that arise when you take update from Sourcetree/SVN/GITLAB. Delete these and save file. 5.Now, you'll be able to open project without any error message.

Check if checkbox is NOT checked on click - jQuery

$(document).ready(function() {
        $("#check1").click(function() {
            var checked = $(this).is(':checked');
            if (checked) {
                alert('checked');
            } else {
                alert('unchecked');
            }
        });
    });

Bypass invalid SSL certificate errors when calling web services in .Net

Alternatively you can register a call back delegate which ignores the certification error:

...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...

static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}

When & why to use delegates?

Say you want to write a procedure to integrate some real-valued function f (x) over some interval [a, b]. Say we want to use the 3-Point Gaussian method to do this (any will do, of course).

Ideally we want some function that looks like:

// 'f' is the integrand we want to integrate over [a, b] with 'n' subintervals.
static double Gauss3(Integrand f, double a, double b, int n) {
  double res = 0;

  // compute result
  // ...

  return res;
}

So we can pass in any Integrand, f, and get its definite integral over the closed interval.

Just what type should Integrand be?

Without Delegates

Well, without delegates, we'd need some sort of interface with a single method, say eval declared as follows:

// Interface describing real-valued functions of one variable.
interface Integrand {
  double eval(double x);
}

Then we'd need to create a whole bunch of classes implementing this interface, as follows:

// Some function
class MyFunc1 : Integrand {
  public double eval(double x) {
    return /* some_result */ ;
  }
}

// Some other function
class MyFunc2 : Integrand {
  public double eval(double x) {
    return /* some_result */ ;
  }
}

// etc

Then to use them in our Gauss3 method, we need to invoke it as follows:

double res1 = Gauss3(new MyFunc1(), -1, 1, 16);
double res2 = Gauss3(new MyFunc2(), 0, Math.PI, 16);

And Gauss3 needs to do the look like the following:

static double Gauss3(Integrand f, double a, double b, int n) {
  // Use the integrand passed in:
  f.eval(x);
}

So we need to do all that just to use our arbitrary functions in Guass3.

With Delegates

public delegate double Integrand(double x);

Now we can define some static (or not) functions adhering to that prototype:

class Program {
   public delegate double Integrand(double x);   
   // Define implementations to above delegate 
   // with similar input and output types
   static double MyFunc1(double x) { /* ... */ }
   static double MyFunc2(double x) { /* ... */ }
   // ... etc ...

   public static double Gauss3(Integrand f, ...) { 
      // Now just call the function naturally, no f.eval() stuff.
      double a = f(x); 
      // ...
   }

   // Let's use it
   static void Main() {
     // Just pass the function in naturally (well, its reference).
     double res = Gauss3(MyFunc1, a, b, n);
     double res = Gauss3(MyFunc2, a, b, n);    
   }
}

No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.

Of course, delegates are more than just function pointers under the hood, but that's a separate issue (function chaining and events).

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).

import error: 'No module named' *does* exist

I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py. Earlier i was using Python 2.7.

Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).

Oracle: how to INSERT if a row doesn't exist

you can use this syntax:

INSERT INTO table_name ( name, age )
select  'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');

if its open an pop for asking as "enter substitution variable" then use this before the above queries:

set define off;
INSERT INTO table_name ( name, age )
select  'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

  1. rename the new path to temp
  2. revert the new path (not temp!) so svn does not try to commit it
  3. commit the rest of your changes
  4. copy the path inside the repository: svn copy -m "copied path" -r
  5. update your working copy
  6. mv all files from temp to the new path, which comes from the update
  7. commit your local changes since revision
  8. Have a nice Day including history ;-)

How to remove multiple deleted files in Git repository

The best solution if you don't care about staging modified files is to use git add -u as said by mshameers and/or pb2q.

If you just want to remove deleted files, but not stage any modified ones, I think you should use the ls-files argument with the --deleted option (no need to use regex or other complex args/options) :

git ls-files --deleted | xargs git rm

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

Creating random numbers with no duplicates

The simplest way would be to create a list of the possible numbers (1..20 or whatever) and then shuffle them with Collections.shuffle. Then just take however many elements you want. This is great if your range is equal to the number of elements you need in the end (e.g. for shuffling a deck of cards).

That doesn't work so well if you want (say) 10 random elements in the range 1..10,000 - you'd end up doing a lot of work unnecessarily. At that point, it's probably better to keep a set of values you've generated so far, and just keep generating numbers in a loop until the next one isn't already present:

if (max < numbersNeeded)
{
    throw new IllegalArgumentException("Can't ask for more numbers than are available");
}
Random rng = new Random(); // Ideally just create one instance globally
// Note: use LinkedHashSet to maintain insertion order
Set<Integer> generated = new LinkedHashSet<Integer>();
while (generated.size() < numbersNeeded)
{
    Integer next = rng.nextInt(max) + 1;
    // As we're adding to a set, this will automatically do a containment check
    generated.add(next);
}

Be careful with the set choice though - I've very deliberately used LinkedHashSet as it maintains insertion order, which we care about here.

Yet another option is to always make progress, by reducing the range each time and compensating for existing values. So for example, suppose you wanted 3 values in the range 0..9. On the first iteration you'd generate any number in the range 0..9 - let's say you generate a 4.

On the second iteration you'd then generate a number in the range 0..8. If the generated number is less than 4, you'd keep it as is... otherwise you add one to it. That gets you a result range of 0..9 without 4. Suppose we get 7 that way.

On the third iteration you'd generate a number in the range 0..7. If the generated number is less than 4, you'd keep it as is. If it's 4 or 5, you'd add one. If it's 6 or 7, you'd add two. That way the result range is 0..9 without 4 or 6.

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

jQuery function after .append

Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

How to check version of a CocoaPods framework

pod --version

to get the version of installed pod

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        {
        AssetID = x.AssetID,
        Status = xx.Online ?? false
        };

What does "for" attribute do in HTML <label> tag?

The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

What is two way binding?

Worth mentioning that there are many different solutions which offer two way binding and play really nicely.

I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.

There is a more extended list of backbone extensions/plugins on github

How to merge lists into a list of tuples?

You can use map lambda

a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)

This will also work if there lengths of original lists do not match

When I catch an exception, how do I get the type, file, and line number?

Without any imports, but also incompatible with imported modules:

try:
    raise TypeError("Hello, World!")  # line 2
except Exception as e:
    print(
        type(e).__name__,          # TypeError
        __file__,                  # /tmp/example.py
        e.__traceback__.tb_lineno  # 2
    )

$ python3 /tmp/example.py
TypeError /tmp/example.py 2

To reiterate, this does not work across imports or modules, so if you do import X; try: X.example(); then the filename and line number will point to the line containing X.example() instead of the line where it went wrong within X.example(). If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something like e[-1].filename, but no such luck), please improve this answer.

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

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

Imports :

org.apache.commons.io.comparator.LastModifiedFileComparator

Apache Commons

Code :

public static void main(String[] args) throws IOException {
        File directory = new File(".");
        // get just files, not directories
        File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);

        System.out.println("Default order");
        displayFiles(files);

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        System.out.println("\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)");
        displayFiles(files);

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        System.out.println("\nLast Modified Descending Order (LASTMODIFIED_REVERSE)");
        displayFiles(files);

    }

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

Is there a way to iterate over a range of integers?

Here is a program to compare the two ways suggested so far

import (
    "fmt"

    "github.com/bradfitz/iter"
)

func p(i int) {
    fmt.Println(i)
}

func plain() {
    for i := 0; i < 10; i++ {
        p(i)
    }
}

func with_iter() {
    for i := range iter.N(10) {
        p(i)
    }
}

func main() {
    plain()
    with_iter()
}

Compile like this to generate disassembly

go build -gcflags -S iter.go

Here is plain (I've removed the non instructions from the listing)

setup

0035 (/home/ncw/Go/iter.go:14) MOVQ    $0,AX
0036 (/home/ncw/Go/iter.go:14) JMP     ,38

loop

0037 (/home/ncw/Go/iter.go:14) INCQ    ,AX
0038 (/home/ncw/Go/iter.go:14) CMPQ    AX,$10
0039 (/home/ncw/Go/iter.go:14) JGE     $0,45
0040 (/home/ncw/Go/iter.go:15) MOVQ    AX,i+-8(SP)
0041 (/home/ncw/Go/iter.go:15) MOVQ    AX,(SP)
0042 (/home/ncw/Go/iter.go:15) CALL    ,p+0(SB)
0043 (/home/ncw/Go/iter.go:15) MOVQ    i+-8(SP),AX
0044 (/home/ncw/Go/iter.go:14) JMP     ,37
0045 (/home/ncw/Go/iter.go:17) RET     ,

And here is with_iter

setup

0052 (/home/ncw/Go/iter.go:20) MOVQ    $10,AX
0053 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-24(SP)
0054 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-16(SP)
0055 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-8(SP)
0056 (/home/ncw/Go/iter.go:20) MOVQ    $type.[]struct {}+0(SB),(SP)
0057 (/home/ncw/Go/iter.go:20) MOVQ    AX,8(SP)
0058 (/home/ncw/Go/iter.go:20) MOVQ    AX,16(SP)
0059 (/home/ncw/Go/iter.go:20) PCDATA  $0,$48
0060 (/home/ncw/Go/iter.go:20) CALL    ,runtime.makeslice+0(SB)
0061 (/home/ncw/Go/iter.go:20) PCDATA  $0,$-1
0062 (/home/ncw/Go/iter.go:20) MOVQ    24(SP),DX
0063 (/home/ncw/Go/iter.go:20) MOVQ    32(SP),CX
0064 (/home/ncw/Go/iter.go:20) MOVQ    40(SP),AX
0065 (/home/ncw/Go/iter.go:20) MOVQ    DX,~r0+-24(SP)
0066 (/home/ncw/Go/iter.go:20) MOVQ    CX,~r0+-16(SP)
0067 (/home/ncw/Go/iter.go:20) MOVQ    AX,~r0+-8(SP)
0068 (/home/ncw/Go/iter.go:20) MOVQ    $0,AX
0069 (/home/ncw/Go/iter.go:20) LEAQ    ~r0+-24(SP),BX
0070 (/home/ncw/Go/iter.go:20) MOVQ    8(BX),BP
0071 (/home/ncw/Go/iter.go:20) MOVQ    BP,autotmp_0006+-32(SP)
0072 (/home/ncw/Go/iter.go:20) JMP     ,74

loop

0073 (/home/ncw/Go/iter.go:20) INCQ    ,AX
0074 (/home/ncw/Go/iter.go:20) MOVQ    autotmp_0006+-32(SP),BP
0075 (/home/ncw/Go/iter.go:20) CMPQ    AX,BP
0076 (/home/ncw/Go/iter.go:20) JGE     $0,82
0077 (/home/ncw/Go/iter.go:20) MOVQ    AX,autotmp_0005+-40(SP)
0078 (/home/ncw/Go/iter.go:21) MOVQ    AX,(SP)
0079 (/home/ncw/Go/iter.go:21) CALL    ,p+0(SB)
0080 (/home/ncw/Go/iter.go:21) MOVQ    autotmp_0005+-40(SP),AX
0081 (/home/ncw/Go/iter.go:20) JMP     ,73
0082 (/home/ncw/Go/iter.go:23) RET     ,

So you can see that the iter solution is considerably more expensive even though it is fully inlined in the setup phase. In the loop phase there is an extra instruction in the loop, but it isn't too bad.

I'd use the simple for loop.

Add custom headers to WebView resource requests - android

Here is an implementation using HttpUrlConnection:

class CustomWebviewClient : WebViewClient() {
    private val charsetPattern = Pattern.compile(".*?charset=(.*?)(;.*)?$")

    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        try {
            val connection: HttpURLConnection = URL(request.url.toString()).openConnection() as HttpURLConnection
            connection.requestMethod = request.method
            for ((key, value) in request.requestHeaders) {
                connection.addRequestProperty(key, value)
            }

            connection.addRequestProperty("custom header key", "custom header value")

            var contentType: String? = connection.contentType
            var charset: String? = null
            if (contentType != null) {
                // some content types may include charset => strip; e. g. "application/json; charset=utf-8"
                val contentTypeTokenizer = StringTokenizer(contentType, ";")
                val tokenizedContentType = contentTypeTokenizer.nextToken()

                var capturedCharset: String? = connection.contentEncoding
                if (capturedCharset == null) {
                    val charsetMatcher = charsetPattern.matcher(contentType)
                    if (charsetMatcher.find() && charsetMatcher.groupCount() > 0) {
                        capturedCharset = charsetMatcher.group(1)
                    }
                }
                if (capturedCharset != null && !capturedCharset.isEmpty()) {
                    charset = capturedCharset
                }

                contentType = tokenizedContentType
            }

            val status = connection.responseCode
            var inputStream = if (status == HttpURLConnection.HTTP_OK) {
                connection.inputStream
            } else {
                // error stream can sometimes be null even if status is different from HTTP_OK
                // (e. g. in case of 404)
                connection.errorStream ?: connection.inputStream
            }
            val headers = connection.headerFields
            val contentEncodings = headers.get("Content-Encoding")
            if (contentEncodings != null) {
                for (header in contentEncodings) {
                    if (header.equals("gzip", true)) {
                        inputStream = GZIPInputStream(inputStream)
                        break
                    }
                }
            }
            return WebResourceResponse(contentType, charset, status, connection.responseMessage, convertConnectionResponseToSingleValueMap(connection.headerFields), inputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.shouldInterceptRequest(view, request)
    }

    private fun convertConnectionResponseToSingleValueMap(headerFields: Map<String, List<String>>): Map<String, String> {
        val headers = HashMap<String, String>()
        for ((key, value) in headerFields) {
            when {
                value.size == 1 -> headers[key] = value[0]
                value.isEmpty() -> headers[key] = ""
                else -> {
                    val builder = StringBuilder(value[0])
                    val separator = "; "
                    for (i in 1 until value.size) {
                        builder.append(separator)
                        builder.append(value[i])
                    }
                    headers[key] = builder.toString()
                }
            }
        }
        return headers
    }
}

Note that this does not work for POST requests because WebResourceRequest doesn't provide POST data. There is a Request Data - WebViewClient library which uses a JavaScript injection workaround for intercepting POST data.

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

Send multiple checkbox data to PHP via jQuery ajax()

Check this out.

<script type="text/javascript">
    function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {

        var myCheckboxes = new Array();
        $("input:checked").each(function() {
           myCheckboxes.push($(this).val());
        });

        $.ajax({
            type: "POST",
            url: "myurl.php",
            dataType: 'html',
            data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
            success: function(data){
                $('#myResponse').html(data)
            }
        });
        return false;
});
});
}
</script>

And on myurl.php you can use print_r($_POST['myCheckboxes']);

Best Practice for Forcing Garbage Collection in C#

I think the example given by Rico Mariani was good: it may be appropriate to trigger a GC if there is a significant change in the application's state. For example, in a document editor it may be OK to trigger a GC when a document is closed.

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

How to set Apache Spark Executor memory

Spark executor memory is required for running your spark tasks based on the instructions given by your driver program. Basically, it requires more resources that depends on your submitted job.

Executor memory includes memory required for executing the tasks plus overhead memory which should not be greater than the size of JVM and yarn maximum container size.

Add the following parameters in spark-defaults.conf

spar.executor.cores=1

spark.executor.memory=2g

If you using any cluster management tools like cloudera manager or amabari please refresh the cluster configuration for reflecting the latest configs to all nodes in the cluster.

Alternatively, we can pass the executor core and memory value as an argument while running spark-submit command along with class and application path.

Example:

spark-submit \

  --class org.apache.spark.examples.SparkPi \

  --master yarn \

  --deploy-mode cluster \  # can be client for client mode

  --executor-memory 2G \

  --num-executors 5 \

  /path/to/examples.jar \

  1000

How to show MessageBox on asp.net?

I took the code from the brilliant @KrisVanDerMast and made it wrapped up in a static method that can be called as many times as you want on the same page!

/// <summary>
/// Shows a basic MessageBox on the passed in page
/// </summary>
/// <param name="page">The Page object to show the message on</param>
/// <param name="message">The message to show</param>
/// <returns></returns>
public static ShowMessageBox(Page page, string message)
{
    Type cstype = page.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = page.ClientScript;

    // Find the first unregistered script number
    int ScriptNumber = 0;
    bool ScriptRegistered = false;
    do
    {
        ScriptNumber++;
        ScriptRegistered = cs.IsStartupScriptRegistered(cstype, "PopupScript" + ScriptNumber);
    } while (ScriptRegistered == true);

    //Execute the new script number that we found
    cs.RegisterStartupScript(cstype, "PopupScript" + ScriptNumber, "alert('" + message + "');", true);
}

Removing the title text of an iOS UIBarButtonItem

extension UIViewController{
    func hideBackButton(){
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

Clicking a checkbox with ng-click does not update the model

How about changing

<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">

to

<input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model="todo.done">

From docs:

Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.

Note, this directive requires ngModel to be present.

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

Detect network connection type on Android

@Emil's answer above is brilliant.

Small addition: We should ideally use TelephonyManager to detect network types. So the above should instead read:

/**
 * Check if there is fast connectivity
 * @param context
 * @return
 */
public static boolean isConnectedFast(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), tm.getNetworkType()));
}

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

How to output git log with the first line only?

git log --format="%H" -n 1

Use the above command to get the commitid, hope this helps.

How do I create a simple 'Hello World' module in Magento?

And,

I suggest you to learn about system configuration.

How to Show All Categories on System Configuration Field?

Here I solved with a good example. It working. You can check and learn the flow of code.

There are other too many examples also that you should learn.

Why should I use core.autocrlf=true in Git?

The only specific reasons to set autocrlf to true are:

  • avoid git status showing all your files as modified because of the automatic EOL conversion done when cloning a Unix-based EOL Git repo to a Windows one (see issue 83 for instance)
  • and your coding tools somehow depends on a native EOL style being present in your file:

Unless you can see specific treatment which must deal with native EOL, you are better off leaving autocrlf to false (git config --global core.autocrlf false).

Note that this config would be a local one (because config isn't pushed from repo to repo)

If you want the same config for all users cloning that repo, check out "What's the best CRLF handling strategy with git?", using the text attribute in the .gitattributes file.

Example:

*.vcproj    text eol=crlf
*.sh        text eol=lf

Note: starting git 2.8 (March 2016), merge markers will no longer introduce mixed line ending (LF) in a CRLF file.
See "Make Git use CRLF on its “<<<<<<< HEAD” merge lines"

Using isKindOfClass with Swift

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.

Android Recyclerview vs ListView with Viewholder

Okay so little bit of digging and I found these gems from Bill Philips article on RecycleView

RecyclerView can do more than ListView, but the RecyclerView class itself has fewer responsibilities than ListView. Out of the box, RecyclerView does not:

  • Position items on the screen
  • Animate views
  • Handle any touch events apart from scrolling

All of this stuff was baked in to ListView, but RecyclerView uses collaborator classes to do these jobs instead.

The ViewHolders you create are beefier, too. They subclass RecyclerView.ViewHolder, which has a bunch of methods RecyclerView uses. ViewHolders know which position they are currently bound to, as well as which item ids (if you have those). In the process, ViewHolder has been knighted. It used to be ListView’s job to hold on to the whole item view, and ViewHolder only held on to little pieces of it.

Now, ViewHolder holds on to all of it in the ViewHolder.itemView field, which is assigned in ViewHolder’s constructor for you.

Why use a READ UNCOMMITTED isolation level?

Use READ_UNCOMMITTED in situation where source is highly unlikely to change.

  • When reading historical data. e.g some deployment logs that happened two days ago.
  • When reading metadata again. e.g. metadata based application.

Don't use READ_UNCOMMITTED when you know souce may change during fetch operation.

Check if Variable is Empty - Angular 2

Lets say we have a variable called x, as below:

var x;

following statement is valid,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1. Number:

x = 10;
if(x){
//True
}

and for x = undefined or x = 0 (be careful here)

if(x){
 //False
}

2. String x = null , x = undefined or x = ""

if(x){
  //False
}

3 Boolean x = false and x = undefined,

if(x){
  //False
}

By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.

Extracting text from HTML file using Python

You can use html2text method in the stripogram library also.

from stripogram import html2text
text = html2text(your_html_string)

To install stripogram run sudo easy_install stripogram

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

Access to the path is denied

I Solved with this setting:

IIS > Application Pools > [your site] > Advanced Settings... > Identity > Built-in accound > LocalSystem

How do I get the last character of a string using an Excel function?

=RIGHT(A1)  

is quite sufficient (where the string is contained in A1).

Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:

SYNTAX

RIGHT( text, [number_of_characters] )

Parameters or Arguments

text

The string that you wish to extract from.

number_of_characters

Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.

Applies To

Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Since number_of_characters is optional and defaults to 1 it is not required in this case.

However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):

=RIGHT(TRIM(A1))  

might be preferred.

Mongoose.js: Find user by username LIKE value

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});

How to urlencode a querystring in Python?

Try requests instead of urllib and you don't need to bother with urlencode!

import requests
requests.get('http://youraddress.com', params=evt.fields)

EDIT:

If you need ordered name-value pairs or multiple values for a name then set params like so:

params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]

instead of using a dictionary.

How do I switch between command and insert mode in Vim?

Coming from emacs I've found that I like ctrl + keys to do stuff, and in vim I've found that both [ctrl + C] and [alt + backspace] will enter Normal mode from insert mode. You might try and see if any of those works out for you.

How to detect when cancel is clicked on file input?

function file_click() {
    document.body.onfocus = () => {
        setTimeout(_=>{
            let file_input = document.getElementById('file_input');
            if (!file_input.value) alert('please choose file ')
            else alert(file_input.value)
            document.body.onfocus = null
        },100)
    }
}

Using setTimeout to get the certain value of the input.

django MultiValueDictKeyError error, how do I deal with it

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”

In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.

The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

You can handle this error by putting :

is_private = request.POST.get('is_private', False);

What is the C# version of VB.net's InputDialog?

You mean InputBox? Just look in the Microsoft.VisualBasic namespace.

C# and VB.Net share a common library. If one language can use it, so can the other.

How to stop execution after a certain time in Java?

If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:

Thread t = new Thread(myRunnable); // myRunnable does your calculations

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;

t.start(); // Kick off calculations

while (System.currentTimeMillis() < endTime) {
    // Still within time theshold, wait a little longer
    try {
         Thread.sleep(500L);  // Sleep 1/2 second
    } catch (InterruptedException e) {
         // Someone woke us up during sleep, that's OK
    }
}

t.interrupt();  // Tell the thread to stop
t.join();       // Wait for the thread to cleanup and finish

That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.

Your runnable's run would look something like this:

public void run() {
    while (true) {
        try {
            // Long running work
            calculateMassOfUniverse();
        } catch (InterruptedException e) {
            // We were signaled, clean things up
            cleanupStuff();
            break;           // Leave the loop, thread will exit
    }
}

Update based on Dmitri's answer

Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.

CSS Float: Floating an image to the left of the text

_x000D_
_x000D_
.post-container{_x000D_
    margin: 20px 20px 0 0;  _x000D_
    border:5px solid #333;_x000D_
    width:600px;_x000D_
    overflow:hidden;_x000D_
}_x000D_
_x000D_
.post-thumb img {_x000D_
    float: left;_x000D_
    clear:left;_x000D_
    width:50px;_x000D_
    height:50px;_x000D_
    border:1px solid red;_x000D_
}_x000D_
_x000D_
.post-title {_x000D_
     float:left;   _x000D_
    margin-left:10px;_x000D_
}_x000D_
_x000D_
.post-content {_x000D_
    float:right;_x000D_
}
_x000D_
<div class="post-container">                _x000D_
   <div class="post-thumb"><img src="thumb.jpg" /></div>_x000D_
   <div class="post-title">Post title</div>_x000D_
   <div class="post-content"><p>post description description description etc etc etc</p></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

SQL query to select dates between two dates

best query for the select date between current date and back three days:

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN       
DATE_SUB(CURDATE(), INTERVAL 3 DAY)  AND CURDATE() 

best query for the select date between current date and next three days:

  select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN   
   CURDATE()  AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)   

In Python, how do I read the exif data for an image?

import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date, lat, lon)

    except Exception as e:
        print(e)

When using a Settings.settings file in .NET, where is the config actually stored?

All your settings are stored in the respective .config file.

The .settings file simply provides a strongly typed class for a set of settings that belong together, but the actual settings are stored in app.config or a .config file in your application.

If you add a .settings file, an app.config will be automatically added to house the settings if you don't already have one.

No space left on device

To list processes holding deleted files a linux system which has no lsof, here's my trick:

    pushd /proc ; for i in [1-9]* ; do ls -l $i/fd | grep "(deleted)" && (echo -n "used by: " ; ps -p $i | grep -v PID ; echo ) ; done ; popd

Difference between Visual Basic 6.0 and VBA

Here's a more technical and thorough answer to an old question: Visual Basic for Applications (VBA) and Visual Basic (pre-.NET) are not just similar languages, they are the same language. Specifically:

  • They have the same specification: The implementation-independent description of what the language contains and what it means. You can read it here: [MS-VBAL]: VBA Language Specification
  • They have the same platform: They both compile to Microsoft P-Code, which is in turn executed by the exact same virtual machine, which is implemented in the dll msvbvm[x.0].dll.

In an old VB reference book I came across last year, the author (Paul Lomax) even asserted that 'VBA' has always been the name of the language itself, whether used in stand-alone applications or in embedded contexts (such as MS Office):

"Before we go any further, let's just clarify on fundamental point. Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB). VB itself is a development environment; the language element of that environment is VBA."

The minor differences

Hosted vs. stand-alone: In practical, terms, when most people say "VBA" they specifically mean "VBA when used in MS Office", and they say "VB6" to mean "VBA used in the last version of the standalone VBA compiler (i.e. Visual Studio 6)". The IDE and compiler bundled with MS Office is almost identical to Visual Studio 6, with the limitation that it does not allow compilation to stand-alone dll or exe files. This in turns means that classes defined in embedded VBA projects are not accessible from non-embedded COM consumers, because they cannot be registered.

Continued development: Microsoft stopped producing a stand-alone VBA compiler with Visual Studio 6, as they switched to the .NET runtime as the platform of choice. However, the MS Office team continues to maintain VBA, and even released a new version (VBA7) with a new VM (now just called VBA7.dll) starting with MS Office 2010. The only major difference is that VBA7 has both a 32- and 64-bit version and has a few enhancements to handle the differences between the two, specifically with regards to external API invocations.

How can I force a hard reload in Chrome for Android

Keyboard shortcuts such as Ctrl+Shift+R work on Android too, you just need a keyboard capable of sending these keys. I used Hacker's Keyboard to send Ctrl+Shift+R, which did a hard reload on my phone.

Does JSON syntax allow duplicate keys in an object?

The JSON spec says this:

An object is an unordered set of name/value pairs.

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

Can I run multiple programs in a Docker container?

They can be in separate containers, and indeed, if the application was also intended to run in a larger environment, they probably would be.

A multi-container system would require some more orchestration to be able to bring up all the required dependencies, though in Docker v0.6.5+, there is a new facility to help with that built into Docker itself - Linking. With a multi-machine solution, its still something that has to be arranged from outside the Docker environment however.

With two different containers, the two parts still communicate over TCP/IP, but unless the ports have been locked down specifically (not recommended, as you'd be unable to run more than one copy), you would have to pass the new port that the database has been exposed as to the application, so that it could communicate with Mongo. This is again, something that Linking can help with.

For a simpler, small installation, where all the dependencies are going in the same container, having both the database and Python runtime started by the program that is initially called as the ENTRYPOINT is also possible. This can be as simple as a shell script, or some other process controller - Supervisord is quite popular, and a number of examples exist in the public Dockerfiles.

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

How to save a spark DataFrame as csv on disk?

I had similar issue where i had to save the contents of the dataframe to a csv file of name which i defined. df.write("csv").save("<my-path>") was creating directory than file. So have to come up with the following solutions. Most of the code is taken from the following dataframe-to-csv with little modifications to the logic.

def saveDfToCsv(df: DataFrame, tsvOutput: String, sep: String = ",", header: Boolean = false): Unit = {
    val tmpParquetDir = "Posts.tmp.parquet"

    df.repartition(1).write.
        format("com.databricks.spark.csv").
        option("header", header.toString).
        option("delimiter", sep).
        save(tmpParquetDir)

    val dir = new File(tmpParquetDir)
    val newFileRgex = tmpParquetDir + File.separatorChar + ".part-00000.*.csv"
    val tmpTsfFile = dir.listFiles.filter(_.toPath.toString.matches(newFileRgex))(0).toString
    (new File(tmpTsvFile)).renameTo(new File(tsvOutput))

    dir.listFiles.foreach( f => f.delete )
    dir.delete
    }

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

How to view kafka message

If you're wondering why the original answer is not working. Well it might be that you're not in the home directory. Try this:

$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

How to get client's IP address using JavaScript?

Not possible in general unless you use some kind of external service.

bootstrap responsive table content wrapping

Fine then. You can use CSS word wrap property. Something like this :

td.test /* Give whatever class name you want */
{
width:11em; /* Give whatever width you want */
word-wrap:break-word;
}

How do I find out my root MySQL password?

It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.

sudo mysql_secure_installation

rotating axis labels in R

Use par(las=1).

See ?par:

las
numeric in {0,1,2,3}; the style of axis labels.
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.

Response.Redirect with POST instead of Get?

@Matt,

You can still use the HttpWebRequest, then direct the response you receive to the actual outputstream response, this would serve the response back to the user. The only issue is that any relative urls would be broken.

Still, that may work.

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

jQuery Dialog Box

Even I faced similar issues. This is how I was able to solve the same

    $("#lnkDetails").live('click', function (e) {

        //Create dynamic element after the element that raised the event. In my case a <a id="lnkDetails" href="/Attendance/Details/2012-07-01" />
        $(this).after('<div id=\"dialog-confirm\" />');

        //Optional : Load data from an external URL. The attr('href') is the href of the <a> tag.
        $('#dialog-confirm').load($(this).attr('href'));

        //Copied from jQueryUI site . Do we need this?
        $("#dialog:ui-dialog").dialog("destroy");

        //Transform the dynamic DOM element into a dialog
        $('#dialog-confirm').dialog({
            modal: true,
            title: 'Details'
        });

        //Prevent Bubbling up to other elements.
        return false;
    });

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

React onClick function fires on render

For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...

replace this <a onClick={props.signOut()}>Log Out</a>

with this <a onClick={props.signOut}>Log Out</a> ... !

Prepend line to beginning of a file

with open("fruits.txt", "r+") as file:
    file.write("bab111y")
    file.seek(0)
    content = file.read()
    print(content)

Android: How do I prevent the soft keyboard from pushing my view up?

Add following code to the 'activity' of Manifest file.

android:windowSoftInputMode="adjustResize"

Creating InetAddress object in Java

From the API for InetAddress

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

Converting HTML to XML

I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.

  function tryToXml($dom,$content) {
    if(!$content) return false;

    // xml well formed content can be loaded as xml node tree
    $fragment = $dom->createDocumentFragment();
    // wonderfull appendXML to add an XML string directly into the node tree!

    // aappendxml will fail on a xml declaration so manually skip this when occurred
    if( substr( $content,0, 5) == '<?xml' ) {
      $content = substr($content,strpos($content,'>')+1);
      if( strpos($content,'<') ) {
        $content = substr($content,strpos($content,'<'));
      }
    }

    // if appendXML is not working then use below htmlToXml() for nasty html correction
    if(!@$fragment->appendXML( $content )) {
      return $this->htmlToXml($dom,$content);
    }

    return $fragment;
  }



  // convert content into xml
  // dom is only needed to prepare the xml which will be returned
  function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {

    // no xml when html is empty
    if(!$content) return false;

    // real content and possibly it needs encoding
    if( $needEncoding ) {
      // no need to convert character encoding as loadHTML will respect the content-type (only)
      $content =  '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
    }

    // return a dom from the content
    $domInject = new DOMDocument("1.0", "UTF-8");
    $domInject->preserveWhiteSpace = false;
    $domInject->formatOutput = true;

    // html type
    try {
      @$domInject->loadHTML( $content );
    } catch(Exception $e){
      // do nothing and continue as it's normal that warnings will occur on nasty HTML content
    }
        // to check encoding: echo $dom->encoding
        $this->reworkDom( $domInject );

    if( $bodyOnly ) {
      $fragment = $dom->createDocumentFragment();

      // retrieve nodes within /html/body
      foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
       if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
         foreach( $elementLevel1->childNodes as $elementInject ) {
           $fragment->insertBefore( $dom->importNode($elementInject, true) );
         }
        }
      }
    } else {
      $fragment = $dom->importNode($domInject->documentElement, true);
    }

    return $fragment;
  }



    protected function reworkDom( $node, $level = 0 ) {

        // start with the first child node to iterate
        $nodeChild = $node->firstChild;

        while ( $nodeChild )  {
            $nodeNextChild = $nodeChild->nextSibling;

            switch ( $nodeChild->nodeType ) {
                case XML_ELEMENT_NODE:
                    // iterate through children element nodes
                    $this->reworkDom( $nodeChild, $level + 1);
                    break;
                case XML_TEXT_NODE:
                case XML_CDATA_SECTION_NODE:
                    // do nothing with text, cdata
                    break;
                case XML_COMMENT_NODE:
                    // ensure comments to remove - sign also follows the w3c guideline
                    $nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
                    break;
                case XML_DOCUMENT_TYPE_NODE:  // 10: needs to be removed
                case XML_PI_NODE: // 7: remove PI
                    $node->removeChild( $nodeChild );
                    $nodeChild = null; // make null to test later
                    break;
                case XML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                case XML_HTML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                default:
                    throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
            }
            $nodeChild = $nodeNextChild;
        } ;
    }

Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:

        $c='<p>test<font>two</p>';
    $dom=new DOMDocument('1.0', 'UTF-8');

$n=$dom->appendChild($dom->createElement('info')); // make a root element

if( $valueXml=tryToXml($dom,$c) ) {
  $n->appendChild($valueXml);
}
    echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';

In this example '<p>test<font>two</p>' will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info> tag can be skipped.

With this I'm getting real nice XML out of unstructured and even corrupted HTML!

I hope it's a bit clear and might contribute to other people to use it.

Defining custom attrs

if you omit the format attribute from the attr element, you can use it to reference a class from XML layouts.

  • example from attrs.xml.
  • Android Studio understands that the class is being referenced from XML
    • i.e.
      • Refactor > Rename works
      • Find Usages works
      • and so on...

don't specify a format attribute in .../src/main/res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="MyCustomView">
        ....
        <attr name="give_me_a_class"/>
        ....
    </declare-styleable>

</resources>

use it in some layout file .../src/main/res/layout/activity__main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- make sure to use $ dollar signs for nested classes -->
    <MyCustomView
        app:give_me_a_class="class.type.name.Outer$Nested/>

    <MyCustomView
        app:give_me_a_class="class.type.name.AnotherClass/>

</SomeLayout>

parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt

class MyCustomView(
        context:Context,
        attrs:AttributeSet)
    :View(context,attrs)
{
    // parse XML attributes
    ....
    private val giveMeAClass:SomeCustomInterface
    init
    {
        context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
        {
            try
            {
                // very important to use the class loader from the passed-in context
                giveMeAClass = context::class.java.classLoader!!
                        .loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
                        .newInstance() // instantiate using 0-args constructor
                        .let {it as SomeCustomInterface}
            }
            finally
            {
                recycle()
            }
        }
    }

Arguments to main in C

Imagine it this way

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

int main(int argc,char *argv[])
{

    printf("you entered in reverse order:\n");

    while(argc--)
    {
        printf("%s\n",argv[argc]);
    }

return 0;
}

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

compile it (as say hello) run it from the terminal with the arguments like

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

if(argc!=3)/*3 because even the executables name string is on argc*/
{
    printf("unexpected number of arguments\n");
    return -1;
}

then check if argv[2] is the reverse of argv[1] and print the result

./hello asdf fdsa

should output

they are exact reverses of each other

the best example is a file copy program try it it's like cp

cp file1 file2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

if you made the cp program you understood the main args really...

How to Clear Console in Java?

If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:

System.out.print("\033[H\033[2J");
System.out.flush();

This works on almost all UNIX terminals and terminal emulators. The Windows cmd.exe does not interprete ANSI escape codes.

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

go to iis -> application pools -> find your application pool used in application

enter image description here

select your application pool used for the application right click select advanced settings

enter image description here

Select application pool identity enter image description here

select built in as Local System and click ok

Inject service in app.config

A solution very easy to do it

Note : it's only for an asynchrone call, because service isn't initialized on config execution.

You can use run() method. Example :

  1. Your service is called "MyService"
  2. You want to use it for an asynchrone execution on a provider "MyProvider"

Your code :

(function () { //To isolate code TO NEVER HAVE A GLOBAL VARIABLE!

    //Store your service into an internal variable
    //It's an internal variable because you have wrapped this code with a (function () { --- })();
    var theServiceToInject = null;

    //Declare your application
    var myApp = angular.module("MyApplication", []);

    //Set configuration
    myApp.config(['MyProvider', function (MyProvider) {
        MyProvider.callMyMethod(function () {
            theServiceToInject.methodOnService();
        });
    }]);

    //When application is initialized inject your service
    myApp.run(['MyService', function (MyService) {
        theServiceToInject = MyService;
    }]);
});

How to have an auto incrementing version number (Visual Studio)?

You could try using UpdateVersion by Matt Griffith. It's quite old now, but works well. To use it, you simply need to setup a pre-build event which points at your AssemblyInfo.cs file, and the application will update the version numbers accordingly, as per the command line arguments.

As the application is open-source, I've also created a version to increment the version number using the format (Major version).(Minor version).([year][dayofyear]).(increment). I've put the code for my modified version of the UpdateVersion application on GitHub: https://github.com/munr/UpdateVersion

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

How to pass parameter to click event in Jquery

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Delete rows containing specific strings in R

This should do the trick:

df[- grep("REVERSE", df$Name),]

Or a safer version would be:

df[!grepl("REVERSE", df$Name),]

Java Date cut off time information

For all the answers using Calendar, you should use it like this instead

public static Date truncateDate(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
    c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
    c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
    c.set(Calendar.MILLISECOND, c.getActualMinimum(Calendar.MILLISECOND));
    return c.getTime();
}

But I prefer this:

public static Date truncateDate(Date date) {
    return new java.sql.Date(date.getTime());
}

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

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

If you are using <ng-content> with *ngIf you are bound to fall into this loop.

Only way out I found was to change *ngIf to display:none functionality

How to mark a build unstable in Jenkins when running shell scripts

The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:

errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
    }
 }

See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/

Which loop is faster, while or for?

I find the fastest loop is a reverse while loop, e.g:

var i = myArray.length;
while(i--){
  // Do something
}

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

How to set time zone of a java.util.Date?

tl;dr

…parsed … from a String … time zone is not specified … I want to set a specific time zone

LocalDateTime.parse( "2018-01-23T01:23:45.123456789" )  // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
    .atZone( ZoneId.of( "Africa/Tunis" ) )              // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.

No Time Zone in j.u.Date

As the other correct answers stated, a java.util.Date has no time zone. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.

Avoid j.u.Date

For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.

Instead use the java.time package bundled with Java 8.

java.time

The java.time classes can represent a moment on the timeline in three ways:

  • UTC (Instant)
  • With an offset (OffsetDateTime with ZoneOffset)
  • With a time zone (ZonedDateTime with ZoneId)

Instant

In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.

Instant instant = Instant.now();

OffsetDateTime

Apply an offset-from-UTC to adjust into some locality’s wall-clock time.

Apply a ZoneOffset to get an OffsetDateTime.

ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );

ZonedDateTime

Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).

Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

LocalDateTime

If the input string lacked any indicator of offset or zone, parse as a LocalDateTime.

If you are certain of the intended time zone, assign a ZoneId to produce a ZonedDateTime. See code example above in tl;dr section at top.

Formatted Strings

Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.

String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]

For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.


Table of all date-time types in Java, both modern and legacy


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.

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

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

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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.

In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.

String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );

Call the toString method to generate a String in ISO 8601 format.

String output = dateTimeIndia.toString();

Joda-Time also offers rich capabilities for generating all kinds of other String formats.

If required, you can convert from Joda-Time DateTime to a java.util.Date.

Java.util.Date date = dateTimeIndia.toDate();

Search StackOverflow for "joda date" to find many more examples, some quite detailed.


Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

Start ssh-agent on login

Add this to your ~/.bashrc, then logout and back in to take effect.

if [ ! -S ~/.ssh/ssh_auth_sock ]; then
  eval `ssh-agent`
  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add

This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.

How to use Collections.sort() in Java?

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

Using Python, find anagrams for a list of words

def findanagranfromlistofwords(li):
    dict = {}
    index=0
    for i in range(0,len(li)):
        originalfirst = li[index]
        sortedfirst = ''.join(sorted(str(li[index])))
        for j in range(index+1,len(li)):
            next = ''.join(sorted(str(li[j])))
            print next
            if sortedfirst == next:
                dict.update({originalfirst:li[j]})
                print "dict = ",dict
        index+=1

    print dict

findanagranfromlistofwords(["car", "tree", "boy", "girl", "arc"])

How to force the browser to reload cached CSS and JavaScript files

Disable caching of script.js only for local development in pure JavaScript.

It injects a random script.js?wizardry=1231234 and blocks regular script.js:

<script type="text/javascript">
  if(document.location.href.indexOf('localhost') !== -1) {
    const scr = document.createElement('script');
    document.setAttribute('type', 'text/javascript');
    document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());
    document.head.appendChild(scr);
    document.write('<script type="application/x-suppress">'); // prevent next script(from other SO answer)
  }
</script>

<script type="text/javascript" src="scripts.js">

How can I change all input values to uppercase using Jquery?

Try like below,

$('input[type=text]').val (function () {
    return this.value.toUpperCase();
})

You should use input[type=text] instead of :input or input as I believe your intention are to operate on textbox only.

How to remove application from app listings on Android Developer Console

Select Store Presense then Pricing Distribution and select Unpublish from App Availability. enter image description here

Google's help for this is here: https://support.google.com/googleplay/android-developer/answer/113476#unpublish (as of Feb-2020)

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

the same problem also happened to me when i training my classification model. the reason caused this problem is as what the warning message said "in labels with no predicated samples", it will caused the zero-division when compute f1-score. I found another solution when i read sklearn.metrics.f1_score doc, there is a note as follows:

When true positive + false positive == 0, precision is undefined; When true positive + false negative == 0, recall is undefined. In such cases, by default the metric will be set to 0, as will f-score, and UndefinedMetricWarning will be raised. This behavior can be modified with zero_division

the zero_division default value is "warn", you could set it to 0 or 1 to avoid UndefinedMetricWarning. it works for me ;) oh wait, there is another problem when i using zero_division, my sklearn report that no such keyword argument by using scikit-learn 0.21.3. Just update your sklearn to the latest version by running pip install scikit-learn -U

How do I set a cookie on HttpClient's HttpRequestMessage

The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler defaults to using its CookieContainer property for cookies. If you disable that then by setting UseCookies to false you can set cookie headers manually and they will appear in the request, e.g.

var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var message = new HttpRequestMessage(HttpMethod.Get, "/test");
    message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
    var result = await client.SendAsync(message);
    result.EnsureSuccessStatusCode();
}

How to list all files in a directory and its subdirectories in hadoop hdfs

Here is a code snippet, that counts number of files in a particular HDFS directory (I used this to determine how many reducers to use in a particular ETL code). You can easily modify this to suite your needs.

private int calculateNumberOfReducers(String input) throws IOException {
    int numberOfReducers = 0;
    Path inputPath = new Path(input);
    FileSystem fs = inputPath.getFileSystem(getConf());
    FileStatus[] statuses = fs.globStatus(inputPath);
    for(FileStatus status: statuses) {
        if(status.isDirectory()) {
            numberOfReducers += getNumberOfInputFiles(status, fs);
        } else if(status.isFile()) {
            numberOfReducers ++;
        }
    }
    return numberOfReducers;
}

/**
 * Recursively determines number of input files in an HDFS directory
 *
 * @param status instance of FileStatus
 * @param fs instance of FileSystem
 * @return number of input files within particular HDFS directory
 * @throws IOException
 */
private int getNumberOfInputFiles(FileStatus status, FileSystem fs) throws IOException  {
    int inputFileCount = 0;
    if(status.isDirectory()) {
        FileStatus[] files = fs.listStatus(status.getPath());
        for(FileStatus file: files) {
            inputFileCount += getNumberOfInputFiles(file, fs);
        }
    } else {
        inputFileCount ++;
    }

    return inputFileCount;
}

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Little hack: you can prevent destroying your activity by GC (you should not do it, but it can help in some situations. Don't forget to set contextForDialog to null when it's no longer needed):

public class PostActivity extends Activity  {
    ...
    private Context contextForDialog = null;
    ...
    public void onCreate(Bundle savedInstanceState) {
        ...
        contextForDialog = this;
    }
    ...
    private void showAnimatedDialog() {
        mSpinner = new Dialog(contextForDialog);
        mSpinner.setContentView(new MySpinner(contextForDialog));
        mSpinner.show();
    }
    ...
}

How to remove blank lines from a Unix file

awk 'NF' filename

awk 'NF > 0' filename

sed -i '/^$/d' filename

awk '!/^$/' filename

awk '/./' filename

The NF also removes lines containing only blanks or tabs, the regex /^$/ does not.

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Problem with converting int to string in Linq to entities

My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.

public partial class Contact{

   public string ContactIdString
   {
      get{ 
            return this.ContactId.ToString();
      }
   } 
}

Then

var items = from c in contacts
select new ListItem
{
    Value = c.ContactIdString, 
    Text = c.Name
};

How to uninstall / completely remove Oracle 11g (client)?

There are some more actions you should consider:

  • Remove Registry Entries for MS Distributed Transaction Coordinator (MSDTC)

    Note: on the Internet I found this step only at a single (private) page. I don't know if it is required/working or if it breaks anything on your PC.

    • Open Regedit
    • Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib
    • Navigate to HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib

    Otherwise these files, if they exist, will still be in use next time you reboot, and unable to be deleted.

  • Remove environment variable ORACLE_HOME, ORACLE_BASE, TNS_ADMIN, NLS_LANG if exist

    Check also Oracle doc to find all Oracle related environment variables, however apart from variables listed above they are very rarely used on Windows Client: Oracle Environment Variables

  • Unregister oci.dll

    • Open a command line window (Start Menu -> Run... -> cmd)
    • Enter regsvr32 /u oci.dll, resp. %windir%\SysWOW64\regsvr32 /u oci.dll

    • In some cases the file %ORACLE_HOME%\bin\oci.dll is locked and you cannot delete it. In such case rename the file (e.g. to oci.dll.x) and reboot the PC, afterwards you can delete it.

  • Remove Oracle .NET assemblies from Global Assembly Cache (GAC). You do this typically with the gacutil utility, if available on your system. Would be like this:

    gacutil /u Policy.10.1.Oracle.DataAccess
    gacutil /u Policy.10.2.Oracle.DataAccess
    gacutil /u Policy.1.102.Oracle.DataAccess
    gacutil /u Policy.1.111.Oracle.DataAccess
    
    gacutil /u Policy.2.102.Oracle.DataAccess
    gacutil /u Policy.2.111.Oracle.DataAccess
    gacutil /u Policy.2.112.Oracle.DataAccess
    gacutil /u Policy.2.121.Oracle.DataAccess
    gacutil /u Policy.2.122.Oracle.DataAccess
    
    gacutil /u Policy.4.112.Oracle.DataAccess
    gacutil /u Policy.4.121.Oracle.DataAccess
    gacutil /u Policy.4.122.Oracle.DataAccess
    
    gacutil /u Oracle.DataAccess
    gacutil /u Oracle.DataAccess.resources
    
    gacutil /u Policy.4.121.Oracle.ManagedDataAccess
    gacutil /u Policy.4.122.Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess.resources
    gacutil /u Oracle.ManagedDataAccessDTC
    gacutil /u Oracle.ManagedDataAccessIOP
    gacutil /u Oracle.ManagedDataAccess.EntityFramework
    
    • Entry System.Data.OracleClient should not be removed, this one is installed by Microsoft - not an Oracle component!

    • Instead of gacutil /u ... you can also use OraProvCfg /action:ungac /providerpath:... if OraProvCfg is still available on your system. You may find it at %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe.

  • With a text editor, open XML Config file %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config and delete branch <oracle.manageddataaccess.client>, if existing.

    • Do the same with:

      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\web.config
      

    Instead of editing the XML Config file manually you can also run (if OraProvCfg.exe is still available on your system):

    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319
    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319
    
  • Check following Registry Keys and delete them if existing

    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Managed Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Unmanaged Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Provider for OLE DB
    
  • Delete the Inventory folder, typically C:\Program Files\Oracle\Inventory and C:\Program Files (x86)\Oracle\Inventory

  • Delete temp folders %TEMP%\deinstall\, %TEMP%\OraInstall\ and %TEMP%\CVU* (e.g %TEMP%\CVU_11.1.0.2.0_domscheit) if existing.

Sending email with PHP from an SMTP server

When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).

For example, I usually use PHPMailer with similar settings to this ones:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com"; // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username"; // SMTP account username example
$mail->Password   = "password";        // SMTP account password example

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();

You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer

Extracting .jar file with command line

You can use the following command: jar xf rt.jar

Where X stands for extraction and the f would be any options that indicate that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.

Rotating a view in Android

@Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:

(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)

canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();

Configure Log4net to write to multiple files

Yes, just add multiple FileAppenders to your logger. For example:

<log4net>
    <appender name="File1Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-1.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>
    <appender name="File2Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-2.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="File1Appender" />
        <appender-ref ref="File2Appender" />
    </root>
</log4net>

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

Android: show/hide status bar/power bar

For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,

Here is the solution that worked for me, (Documentation) (Flag Reference)

Hide Status Bar

// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
   View decorView = getWindow().getDecorView();
  // Hide Status Bar.
   int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
   decorView.setSystemUiVisibility(uiOptions);
}

Show Status Bar

   if (Build.VERSION.SDK_INT < 16) {
              getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    else {
       View decorView = getWindow().getDecorView();
      // Show Status Bar.
       int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
       decorView.setSystemUiVisibility(uiOptions);
    }

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

SQL Server: the maximum number of rows in table

I have a three column table with just over 6 Billion rows in SQL Server 2008 R2.

We query it every day to create minute-by-minute system analysis charts for our customers. I have not noticed any database performance hits (though the fact that it grows ~1 GB every day does make managing backups a bit more involved than I would like).

Update July 2016

Row count

We made it to ~24.5 billion rows before backups became large enough for us to decide to truncate records older than two years (~700 GB stored in multiple backups, including on expensive tapes). It's worth noting that performance was not a significant motivator in this decision (i.e., it was still working great).

For anyone who finds themselves trying to delete 20 billion rows from SQL Server, I highly recommend this article. Relevant code in case the link dies (read the article for a full explanation):

ALTER DATABASE DeleteRecord SET RECOVERY SIMPLE;
GO

BEGIN TRY
    BEGIN TRANSACTION
        -- Bulk logged 
        SELECT  *
        INTO    dbo.bigtable_intermediate
        FROM    dbo.bigtable
        WHERE   Id % 2 = 0;

        -- minimal logged because DDL-Operation 
        TRUNCATE TABLE dbo.bigtable;  

        -- Bulk logged because target table is exclusivly locked! 
        SET IDENTITY_INSERT dbo.bigTable ON;
        INSERT INTO dbo.bigtable WITH (TABLOCK) (Id, c1, c2, c3)
        SELECT Id, c1, c2, c3 FROM dbo.bigtable_intermediate ORDER BY Id;
        SET IDENTITY_INSERT dbo.bigtable OFF;
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

ALTER DATABASE DeleteRecord SET RECOVERY FULL;
GO

Update November 2016

If you plan on storing this much data in a single table: don't. I highly recommend you consider table partitioning (either manually or with the built-in features if you're running Enterprise edition). This makes dropping old data as easy as truncating a table once a (week/month/etc.). If you don't have Enterprise (which we don't), you can simply write a script which runs once a month, drops tables older than 2 years, creates next month's table, and regenerates a dynamic view that joins all of the partition tables together for easy querying. Obviously "once a month" and "older than 2 years" should be defined by you based on what makes sense for your use-case. Deleting directly from a table with tens of billions of rows of data will a) take a HUGE amount of time and b) fill up the transaction log hundreds or thousands of times over.

How does Facebook disable the browser's integrated Developer Tools?

I would go along the way of:

Object.defineProperty(window, 'console', {
  get: function() {

  },
  set: function() {

  }
});

Setting up connection string in ASP.NET to SQL SERVER

I JUST FOUND!! You need to put this string connection and point directly to your database. Same case on server.

"Provider=Microsoft.ACE.OLEDB.12.0; 
 Data Source=c:/inetpub/wwwroot/TEST/data/data.mdb;"

It works!! :)

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Import this in to app.module.ts

import {HttpClientModule} from '@angular/common/http';

and add this one in imports

HttpClientModule

IF-THEN-ELSE statements in postgresql

As stated in PostgreSQL docs here:

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.

Code snippet specifically answering your question:

SELECT field1, field2,
  CASE
    WHEN field1>0 THEN field2/field1
    ELSE 0
  END 
  AS field3
FROM test

Best /Fastest way to read an Excel Sheet into a DataTable?

This is the way to read from excel oledb

try
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.DataSet DtSet;
    System.Data.OleDb.OleDbDataAdapter MyCommand;
    string strHeader7 = "";
    strHeader7 = (hdr7) ? "Yes" : "No";
    MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fn + ";Extended Properties=\"Excel 12.0;HDR=" + strHeader7 + ";IMEX=1\"");
    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + wks + "$]", MyConnection);
    MyCommand.TableMappings.Add("Table", "TestTable");
    DtSet = new System.Data.DataSet();
    MyCommand.Fill(DtSet);
    dgv7.DataSource = DtSet.Tables[0];
    MyConnection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

How to script FTP upload and download?

I've done this with PowerShell:

function DownloadFromFtp($destination, $ftp_uri, $user, $pass){
    $dirs = GetDirecoryTree $ftp_uri $user $pass

    foreach($dir in $dirs){
       $path = [io.path]::Combine($destination,$dir)

       if ((Test-Path $path) -eq $false) {
          "Creating $path ..."
          New-Item -Path $path -ItemType Directory | Out-Null
       }else{
          "Exists $path ..."
       }
    }

    $files = GetFilesTree $ftp_uri $user $pass

    foreach($file in $files){
        $source = [io.path]::Combine($ftp_uri,$file)
        $dest = [io.path]::Combine($destination,$file)

        "Downloading $source ..."
        Get-FTPFile $source $dest $user $pass
    }
}

function UploadToFtp($artifacts, $ftp_uri, $user, $pass){
    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  

    foreach($item in Get-ChildItem -recurse $artifacts){ 

        $relpath = [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($artifacts).Length + 1)

        if ($item.Attributes -eq "Directory"){

            try{
                Write-Host Creating $item.Name

                $makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
                $makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
                $makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
                $makeDirectory.GetResponse();

            }catch [Net.WebException] {
                Write-Host $item.Name probably exists ...
            }

            continue;
        }

        "Uploading $item..."
        $uri = New-Object System.Uri($ftp_uri+$relpath) 
        $webclient.UploadFile($uri, $item.FullName)
    }
}

 function Get-FTPFile ($Source,$Target,$UserName,$Password) 
 { 
     $ftprequest = [System.Net.FtpWebRequest]::create($Source) 
     $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password) 
     $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile 
     $ftprequest.UseBinary = $true 
     $ftprequest.KeepAlive = $false 

     $ftpresponse = $ftprequest.GetResponse() 
     $responsestream = $ftpresponse.GetResponseStream() 

     $targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create) 
     [byte[]]$readbuffer = New-Object byte[] 1024 

     do{ 
         $readlength = $responsestream.Read($readbuffer,0,1024) 
         $targetfile.Write($readbuffer,0,$readlength) 
     } 
     while ($readlength -ne 0) 

     $targetfile.close() 
 } 

#task ListFiles {
#   
#    $files = GetFilesTree 'ftp://127.0.0.1/' "web" "web"
#    $files | ForEach-Object {Write-Host $_ -foregroundcolor cyan}
#}

function GetDirecoryTree($ftp, $user, $pass){
    $creds = New-Object System.Net.NetworkCredential($user,$pass)

    $files = New-Object "system.collections.generic.list[string]"
    $folders = New-Object "system.collections.generic.queue[string]"
    $folders.Enqueue($ftp)

    while($folders.Count -gt 0){
        $fld = $folders.Dequeue()

        $newFiles = GetAllFiles $creds $fld
        $dirs = GetDirectories $creds $fld

        foreach ($line in $dirs){
            $dir = @($newFiles | Where { $line.EndsWith($_) })[0]
            [void]$newFiles.Remove($dir)
            $folders.Enqueue($fld + $dir + "/")

            [void]$files.Add($fld.Replace($ftp, "") + $dir + "/")
        }
    }

    return ,$files
}

function GetFilesTree($ftp, $user, $pass){
    $creds = New-Object System.Net.NetworkCredential($user,$pass)

    $files = New-Object "system.collections.generic.list[string]"
    $folders = New-Object "system.collections.generic.queue[string]"
    $folders.Enqueue($ftp)

    while($folders.Count -gt 0){
        $fld = $folders.Dequeue()

        $newFiles = GetAllFiles $creds $fld
        $dirs = GetDirectories $creds $fld

        foreach ($line in $dirs){
            $dir = @($newFiles | Where { $line.EndsWith($_) })[0]
            [void]$newFiles.Remove($dir)
            $folders.Enqueue($fld + $dir + "/")
        }

        $newFiles | ForEach-Object { 
            $files.Add($fld.Replace($ftp, "") + $_) 
        }
    }

    return ,$files
}

function GetDirectories($creds, $fld){
    $dirs = New-Object "system.collections.generic.list[string]"

    $operation = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $reader = GetStream $creds $fld $operation
    while (($line = $reader.ReadLine()) -ne $null) {

       if ($line.Trim().ToLower().StartsWith("d") -or $line.Contains(" <DIR> ")) {
            [void]$dirs.Add($line)
        }
    }
    $reader.Dispose();

    return ,$dirs
}

function GetAllFiles($creds, $fld){
    $newFiles = New-Object "system.collections.generic.list[string]"
    $operation = [System.Net.WebRequestMethods+Ftp]::ListDirectory

    $reader = GetStream $creds $fld $operation

    while (($line = $reader.ReadLine()) -ne $null) {
       [void]$newFiles.Add($line.Trim()) 
    }
    $reader.Dispose();

    return ,$newFiles
}

function GetStream($creds, $url, $meth){

    $ftp = [System.Net.WebRequest]::Create($url)
    $ftp.Credentials = $creds
    $ftp.Method = $meth
    $response = $ftp.GetResponse()

    return New-Object IO.StreamReader $response.GetResponseStream()
}

Export-ModuleMember UploadToFtp, DownLoadFromFtp

How do you add multi-line text to a UIButton?

The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:

pic

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...: 
   ...:     print 'Doing stuff!!!'
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

How to connect to LocalDb

 <add name="Default" connectionString="Data Source=(LocalDb)\MSSqlLocalDB; Initial Catalog=CRM_Default_v1; Integrated Security=True"
      providerName="System.Data.SqlClient"/>

your web.config files in visual studio under connectiionString or Go to View > SQL Server Object Viewer > Add Sql Server> add your server there

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

Though this seems to be an old question with many answers I'm posting another one, because it provides information about another approaches (looking more convenient than already mentioned), and the question itself remains actual.

First, there is a blogpost Running multiple versions of Google Chrome on Windows. It describes a method which works, but has 2 drawbacks:

  • you can't run Chrome instances of different versions simultaneously;
  • from time to time, Chrome changes format of its profile, and as long as 2 versions installed by this method share the same directory with profiles, this may produce a problem if it's happened to test 2 versions with incompatible profile formats;

Second method is a preferred one, which I'm currently using. It relies on portable versions of Chrome, which become available for every stable release at the portableapps.com.

The only requirement of this method is that existing Chrome version should not run during installation of a next version. Of course, each version must be installed in a separate directory. This way, after installation, you can run Chromes of different versions in parallel. Of course, there is a drawback in this method as well:

  • profiles in all versions live separately, so if you need to setup a profile in a specific way, you should do it twice or more times, according to the number of different Chrome versions you have installed.

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

If you just want to give users using a MS browser a warning or something, this code should be good.

HTML:

<p id="IE">You are not using a microsoft browser</p>

Javascript:

using_ms_browser = navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Edge') > -1) || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Trident') > -1);

if (using_ms_browser == true){
    document.getElementById('IE').innerHTML = "You are using a MS browser"
}

Thanks to @GavinoGrifoni

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

1) Put =Left(E1,5) in F1

2) Copy F1, then select entire F column and paste.

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

Charts for Android

To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:

Open Source:

Paid:

** - means I didn't try those so I can't really recommend it but other users suggested it..

.NET NewtonSoft JSON deserialize map to a different property name

Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).

public class PropertyFilterResolver : DefaultContractResolver
{
  const string _Err = "A type can be either in the include list or the ignore list.";
  Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null) return this;

    if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IgnorePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null)
      return this;

    if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IncludePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
  {
    var properties = base.CreateProperties(type, memberSerialization);

    var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
    if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
      return properties;

    Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
    return properties.Where(predicate).ToArray();
  }

  string GetPropertyName<TSource, TProperty>(
  Expression<Func<TSource, TProperty>> propertyLambda)
  {
    if (!(propertyLambda.Body is MemberExpression member))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");

    if (!(member.Member is PropertyInfo propInfo))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");

    var type = typeof(TSource);
    if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
      throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");

    return propInfo.Name;
  }
}

Usage:

var resolver = new PropertyFilterResolver()
  .SetIncludedProperties<User>(
    u => u.Id, 
    u => u.UnitId)
  .SetIgnoredProperties<Person>(
    r => r.Responders)
  .SetIncludedProperties<Blog>(
    b => b.Id)
  .Ignore(nameof(IChangeTracking.IsChanged)); //see gist

How does the "final" keyword in Java work? (I can still modify an object.)

Final keyword has a numerous way to use:

  • A final class cannot be subclassed.
  • A final method cannot be overridden by subclasses
  • A final variable can only be initialized once

Other usage:

  • When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class

A static class variable will exist from the start of the JVM, and should be initialized in the class. The error message won't appear if you do this.

Staging Deleted files

Since Git 2.0.0, git add will also stage file deletions.

Git 2.0.0 Docs - git-add

< pathspec >…

Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to update the index to match the current state of the directory as a whole (e.g. specifying dir will record not just a file dir/file1 modified in the working tree, a file dir/file2 added to the working tree, but also a file dir/file3 removed from the working tree. Note that older versions of Git used to ignore removed files; use --no-all option if you want to add modified or new files but ignore removed ones.

How do I make Git use the editor of my choice for commits?

Windows: setting notepad as the default commit message editor

git config --global core.editor notepad.exe

Hit Ctrl+S to save your commit message. To discard, just close the notepad window without saving.

In case you hit the shortcut for save, then decide to abort, go to File->Save as, and in the dialog that opens, change "Save as type" to "All files (*.*)". You will see a file named "COMMIT_EDITMSG". Delete it, and close notepad window.

Edit: Alternatively, and more easily, delete all the contents from the open notepad window and hit save. (thanks mwfearnley for the comment!)

I think for small write-ups such as commit messages notepad serves best, because it is simple, is there with windows, opens up in no time. Even your sublime may take a second or two to get fired up when you have a load of plugins and stuff.

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

A non well formed numeric value encountered

if $_GET['start_date'] is a string then convert it in integer or double to deal numerically.

$int = (int) $_GET['start_date']; //Integer
$double = (double) $_GET['start_date']; //It takes in floating value with 2 digits

How do I debug "Error: spawn ENOENT" on node.js?

Are you changing the env option?

Then look at this answer.


I was trying to spawn a node process and TIL that you should spread the existing environment variables when you spawn else you'll loose the PATH environment variable and possibly other important ones.

This was the fix for me:

const nodeProcess = spawn('node', ['--help'], {
  env: {
    // by default, spawn uses `process.env` for the value of `env`
    // you can _add_ to this behavior, by spreading `process.env`
    ...process.env,
    OTHER_ENV_VARIABLE: 'test',
  }
});

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

VB.Net: Dynamically Select Image from My.Resources

Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.

PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name") 

Vertical divider doesn't work in Bootstrap 3

Here is some LESS for you, in case you customize the navbar:

.navbar .divider-vertical {
    height: floor(@navbar-height - @navbar-margin-bottom);
    margin: floor(@navbar-margin-bottom / 2) 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

Which Eclipse version should I use for an Android app?

I literally did this 1 hour ago.

  1. SDK R7
  2. Get Java - if you don't have (its the first image link JDK)
  3. Get Eclipse - it's the first on the list with the most downloads
  4. Android Plugin

Download the appropriate files for your OS. The Android SDK needs java in order to install. Once you get the Android SDK installed go get eclipse and install that. Basically download the file and unzip then in a directory. The android install is the same but it will install a lot more files. (5) Finally open eclipse and go to help > install new software >> and add the url to the plugin - I used this one https://dl-ssl.google.com/android/eclipse/

Elegant way to check for missing packages and install them?

A lot of the answers above (and on duplicates of this question) rely on installed.packages which is bad form. From the documentation:

This can be slow when thousands of packages are installed, so do not use this to find out if a named package is installed (use system.file or find.package) nor to find out if a package is usable (call require and check the return value) nor to find details of a small number of packages (use packageDescription). It needs to read several files per installed package, which will be slow on Windows and on some network-mounted file systems.

So, a better approach is to attempt to load the package using require and and install if loading fails (require will return FALSE if it isn't found). I prefer this implementation:

using<-function(...) {
    libs<-unlist(list(...))
    req<-unlist(lapply(libs,require,character.only=TRUE))
    need<-libs[req==FALSE]
    if(length(need)>0){ 
        install.packages(need)
        lapply(need,require,character.only=TRUE)
    }
}

which can be used like this:

using("RCurl","ggplot2","jsonlite","magrittr")

This way it loads all the packages, then goes back and installs all the missing packages (which if you want, is a handy place to insert a prompt to ask if the user wants to install packages). Instead of calling install.packages separately for each package it passes the whole vector of uninstalled packages just once.

Here's the same function but with a windows dialog that asks if the user wants to install the missing packages

using<-function(...) {
    libs<-unlist(list(...))
    req<-unlist(lapply(libs,require,character.only=TRUE))
    need<-libs[req==FALSE]
    n<-length(need)
    if(n>0){
        libsmsg<-if(n>2) paste(paste(need[1:(n-1)],collapse=", "),",",sep="") else need[1]
        print(libsmsg)
        if(n>1){
            libsmsg<-paste(libsmsg," and ", need[n],sep="")
        }
        libsmsg<-paste("The following packages could not be found: ",libsmsg,"\n\r\n\rInstall missing packages?",collapse="")
        if(winDialog(type = c("yesno"), libsmsg)=="YES"){       
            install.packages(need)
            lapply(need,require,character.only=TRUE)
        }
    }
}

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Android add placeholder text to EditText

In your Activity

<EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@null"
                android:hint="Text Example"
                android:padding="5dp"
                android:singleLine="true"
                android:id="@+id/name"
                android:textColor="@color/magenta"/>

enter image description here

Sharing url link does not show thumbnail image on facebook

I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.

<meta property="og:url" content="<? 
 $url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];; 
echo htmlentities($url,ENT_QUOTES); ?>"/> 

How to install node.js as windows service?

The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.

Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable machine-wide.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

In the next major version of the library HttpClient interface is going to extend Closeable. Until then it is recommended to use CloseableHttpClient if compatibility with earlier 4.x versions (4.0, 4.1 and 4.2) is not required.

AppCompat v7 r21 returning error in values.xml?

my solucion is compile with other version

build.gradle (app)

compileSdkVersion 21

Good Luck

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Is there a Pattern Matching Utility like GREP in Windows?

UnxUtils is a great set of Unix utilites that run on Windows. It has grep, sed, gawk, etc.

SoapUI "failed to load url" error when loading WSDL

In my case the server were the service was installed was configured only for TLS. SSL was not allowed. So you have to update SoapUI vmoptions file by adding

-Dsoapui.https.protocols=TLSv1.2

You can find vmoptions file under SoapUI installation folder:

C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\bin\soapUI-5.0.0.vmoptions

OR change your server setting to allow SSL

Sorting table rows according to table header column using javascript or jquery

I found @naota's solution useful, and extended it to use dates as well

//taken from StackOverflow:
//https://stackoverflow.com/questions/3880615/how-can-i-determine-whether-a-given-string-represents-a-date
function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

var getVal = function(elm, n){
  var v = $(elm).children('td').eq(n).text().toUpperCase();
  if($.isNumeric(v)){
    v = parseFloat(v,10);
    return v;
  }
  if (isDate(v)) {
    v = new Date(v);
    return v;
  }
  return v;
}

Automatic HTTPS connection/redirect with node.js/express

I find req.protocol works when I am using express (have not tested without but I suspect it works). using current node 0.10.22 with express 3.4.3

app.use(function(req,res,next) {
  if (!/https/.test(req.protocol)){
     res.redirect("https://" + req.headers.host + req.url);
  } else {
     return next();
  } 
});

ng-change not working on a text input

ng-change requires ng-model,

<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">

Is there an "exists" function for jQuery?

Use querySelectorAll with forEach, no need for if and extra assignment:

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

as the opposite to:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}

What does 'x packages are looking for funding' mean when running `npm install`?

You can skip fund using:

npm install --no-fund YOUR PACKAGE NAME

For example :

npm install --no-fund core-js

How to normalize an array in NumPy to a unit vector?

I would agree that it were nice if such a function was part of the included batteries. But it isn't, as far as I know. Here is a version for arbitrary axes, and giving optimal performance.

import numpy as np

def normalized(a, axis=-1, order=2):
    l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
    l2[l2==0] = 1
    return a / np.expand_dims(l2, axis)

A = np.random.randn(3,3,3)
print(normalized(A,0))
print(normalized(A,1))
print(normalized(A,2))

print(normalized(np.arange(3)[:,None]))
print(normalized(np.arange(3)))

SQL QUERY replace NULL value in a row with a value from the previous known value

The best solution is the one offered by Bill Karwin. I recently had to solve this in a relatively large resultset (1000 rows with 12 columns each needing this type of "show me last non-null value if this value is null on the current row") and using the update method with a top 1 select for the previous known value (or subquery with a top 1 ) ran super slow.

I am using SQL 2005 and the syntax for a variable replacement is slightly different than mysql:

UPDATE mytable 
SET 
    @n = COALESCE(number, @n),
    number = COALESCE(number, @n)
ORDER BY date

The first set statement updates the value of the variable @n to the current row's value of 'number' if the 'number' is not null (COALESCE returns the first non-null argument you pass into it) The second set statement updates the actual column value for 'number' to itself (if not null) or the variable @n (which always contains the last non NULL value encountered).

The beauty of this approach is that there are no additional resources expended on scanning the temporary table over and over again... The in-row update of @n takes care of tracking the last non-null value.

I don't have enough rep to vote his answer up, but someone should. It's the most elegant and best performant.

Open Excel file for reading with VBA without display

Open them from a new instance of Excel.

Sub Test()

    Dim xl As Excel.Application
    Set xl = CreateObject("Excel.Application")

    Dim w As Workbook
    Set w = xl.Workbooks.Add()

    MsgBox "Not visible yet..."
    xl.Visible = True

    w.Close False
    Set xl = Nothing

End Sub

You need to remember to clean up after you're done.

How to get row number in dataframe in Pandas?

To get all indices that matches 'Smith'

>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')

or as a numpy array

>>> df[df['LastName'] == 'Smith'].index.to_numpy()  # .values on older versions
array([1])

or if there is only one and you want the integer, you can subset

>>> df[df['LastName'] == 'Smith'].index[0]
1

You could use the same boolean expressions with .loc, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.

Why does JavaScript only work after opening developer tools in IE once?

I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:

        try {
            console.log(message);
        } catch (e) {
        }

It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.

hash keys / values as array

Don't know if it helps, but the "foreach" goes through all the keys: for (var key in obj1) {...}

Clearing an input text field in Angular2

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }

Is it possible to append to innerHTML without destroying descendants' event listeners?

something.innerHTML += 'add whatever you want';

it worked for me. I added a button to an input text using this solution

Split data frame string column into multiple columns

Here is a base R one liner that overlaps a number of previous solutions, but returns a data.frame with the proper names.

out <- setNames(data.frame(before$attr,
                  do.call(rbind, strsplit(as.character(before$type),
                                          split="_and_"))),
                  c("attr", paste0("type_", 1:2)))
out
  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2

It uses strsplit to break up the variable, and data.frame with do.call/rbind to put the data back into a data.frame. The additional incremental improvement is the use of setNames to add variable names to the data.frame.

jquery AJAX and json format

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Just wanted to add this little snippet which works beautifully for me.

INSERT INTO your_target_table SELECT * FROM your_rescource_table WHERE id = 18;

And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier

How can I generate random alphanumeric strings?

Try to combine two parts: unique (sequence, counter or date ) and random

public class RandomStringGenerator
{
    public static string Gen()
    {
        return ConvertToBase(DateTime.UtcNow.ToFileTimeUtc()) + GenRandomStrings(5); //keep length fixed at least of one part
    }

    private static string GenRandomStrings(int strLen)
    {
        var result = string.Empty;

        using (var gen = new RNGCryptoServiceProvider())
        {
            var data = new byte[1];

            while (result.Length < strLen)
            {
                gen.GetNonZeroBytes(data);
                int code = data[0];
                if (code > 48 && code < 57 || // 0-9
                    code > 65 && code < 90 || // A-Z
                    code > 97 && code < 122   // a-z
                )
                {
                    result += Convert.ToChar(code);
                }
            }

            return result;
        }
    }

    private static string ConvertToBase(long num, int nbase = 36)
    {
        const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //if you wish to make the algorithm more secure - change order of letter here

        // check if we can convert to another base
        if (nbase < 2 || nbase > chars.Length)
            return null;

        int r;
        var newNumber = string.Empty;

        // in r we have the offset of the char that was converted to the new base
        while (num >= nbase)
        {
            r = (int)(num % nbase);
            newNumber = chars[r] + newNumber;
            num = num / nbase;
        }
        // the last number to convert
        newNumber = chars[(int)num] + newNumber;

        return newNumber;
    }
}

Tests:

    [Test]
    public void Generator_Should_BeUnigue1()
    {
        //Given
        var loop = Enumerable.Range(0, 1000);
        //When
        var str = loop.Select(x=> RandomStringGenerator.Gen());
        //Then
        var distinct = str.Distinct();
        Assert.AreEqual(loop.Count(),distinct.Count()); // Or Assert.IsTrue(distinct.Count() < 0.95 * loop.Count())
    }

how to set auto increment column with sql developer

UPDATE: In Oracle 12c onward we have an option to create auto increment field, its better than trigger and sequence.

  • Right click on the table and select "Edit".
  • In "Edit" Table window, select "columns", and then select your PK column.
  • Go to Identity Column tab and select "Generated as Identity" as Type, put 1 in both start with and increment field. This will make this column auto increment.

See the below image

enter image description here

From SQL Statement

IDENTITY column is now available on Oracle 12c:

 create table t1 (
     c1 NUMBER GENERATED by default on null as IDENTITY,
     c2 VARCHAR2(10)
     );

or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)

create table t1 (
    c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
    c2 VARCHAR2(10)
    );

EDIT : if you face any error like "ORA-30673: column to be modified is not an identity column", then you need to create new column and delete the old one.

How can getContentResolver() be called in Android?

import android.content.Context;
import android.content.ContentResolver;

context = (Context)this;
ContentResolver result = (ContentResolver)context.getContentResolver();

Sort JavaScript object by key

Underscore version:

function order(unordered)
{
return _.object(_.sortBy(_.pairs(unordered),function(o){return o[0]}));
}

If you don't trust your browser for keeping the order of the keys, I strongly suggest to rely on a ordered array of key-value paired arrays.

_.sortBy(_.pairs(c),function(o){return o[0]})

Proper way to rename solution (and directories) in Visual Studio

To rename a website:

http://www.c-sharpcorner.com/Blogs/46334/rename-website-project-in-visual-studio-2013.aspx

locate and edit IISExpress's applicationhost.config, found here: C:\Users{username}\Documents\IISExpress\config

How to declare an array of strings in C++?

You can use Will Dean's suggestion [#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.

The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[]) is really some_function(string *parameter).

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Exporting functions from a DLL with dllexport

I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.

For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

The bigger question is why do you want to do that? What's wrong with the mangled names?

Can a foreign key be NULL and/or duplicate?

By default there are no constraints on the foreign key, foreign key can be null and duplicate.

while creating a table / altering the table, if you add any constrain of uniqueness or not null then only it will not allow the null/ duplicate values.

Wait until page is loaded with Selenium WebDriver for Python

You can do that very simple by this function:

def page_is_loading(driver):
    while True:
        x = driver.execute_script("return document.readyState")
        if x == "complete":
            return True
        else:
            yield False

and when you want do something after page loading complete,you can use:

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get("https://www.google.com/")

while not page_is_loading(Driver):
    continue

Driver.execute_script("alert('page is loaded')")

Convert Java object to XML string

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

private String generateXml(Object obj, Class objClass) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(obj, sw);
        return sw.toString();
    }

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Find files in created between a date range

Use stat to get the creation time. You can compare the time in the format YYYY-MM-DD HH:MM:SS lexicographically.

This work on Linux with modification time, creation time is not supported. On AIX, the -c option might not be supported, but you should be able to get the information anyway, using grep if nothing else works.

#! /bin/bash
from='2013-08-01 00:00:00.0000000000' # 01-Aug-13
to='2013-08-31 23:59:59.9999999999'   # 31-Aug-13

for file in * ; do
    modified=$( stat -c%y "$file" )
    if [[ $from < $modified && $modified < $to ]] ; then
        echo "$file"
    fi
done

Run two async tasks in parallel and collect results in .NET 4.5

To answer this point:

I want Sleep to be an async method so it can await other methods

you can maybe rewrite the Sleep function like this:

private static async Task<int> Sleep(int ms)
{
    Console.WriteLine("Sleeping for " + ms);
    var task = Task.Run(() => Thread.Sleep(ms));
    await task;
    Console.WriteLine("Sleeping for " + ms + "END");
    return ms;
}

static void Main(string[] args)
{
    Console.WriteLine("Starting");

    var task1 = Sleep(2000);
    var task2 = Sleep(1000);

    int totalSlept = task1.Result +task2.Result;

    Console.WriteLine("Slept for " + totalSlept + " ms");
    Console.ReadKey();
}

running this code will output :

Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms

Pretty Printing a pandas dataframe

If you are in Jupyter notebook, you could run the following code to interactively display the dataframe in a well formatted table.

This answer builds on the to_html('temp.html') answer above, but instead of creating a file displays the well formatted table directly in the notebook:

from IPython.display import display, HTML

display(HTML(df.to_html()))

Credit for this code due to example at: Show DataFrame as table in iPython Notebook

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root