Programs & Examples On #Pubs

FlutterError: Unable to load asset

I haved a similar problem, I fixed here:

uses-material-design: true
 assets:
   - assets/images/

After, do:

Flutter Clean

How to add image in Flutter

I think the error is caused by the redundant ,

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg

I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg

The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.

data.table vs dplyr: can one do something well the other can't or does poorly?

We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed, Memory usage, Syntax and Features.

My intent is to cover each one of these as clearly as possible from data.table perspective.

Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.


The data.table syntax is consistent in its form - DT[i, j, by]. To keep i, j and by together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.

1. Speed

Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas. See also updated benchmarks, which include Spark and pydatatable as well.

On benchmarks, it would be great to cover these remaining aspects as well:

  • Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z] type operations.

  • Benchmark other operations such as update and joins.

  • Also benchmark memory footprint for each operation in addition to runtime.

2. Memory usage

  1. Operations involving filter() or slice() in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.

    Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.

  2. data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).

    # sub-assign by reference, updates 'y' in-place
    DT[x >= 1L, y := NA]
    

    But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):

    # copies the entire 'y' column
    ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
    

    A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.

    Therefore we are working towards exporting shallow() function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:

    foo <- function(DT) {
        DT = shallow(DT)          ## shallow copy DT
        DT[, newcol := 1L]        ## does not affect the original DT 
        DT[x > 2L, newcol := 2L]  ## no need to copy (internally), as this column exists only in shallow copied DT
        DT[x > 2L, x := 3L]       ## have to copy (like base R / dplyr does always); otherwise original DT will 
                                  ## also get modified.
    }
    

    By not using shallow(), the old functionality is retained:

    bar <- function(DT) {
        DT[, newcol := 1L]        ## old behaviour, original DT gets updated by reference
        DT[x > 2L, x := 3L]       ## old behaviour, update column x in original DT.
    }
    

    By creating a shallow copy using shallow(), we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.

    Also, once shallow() is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.

    But it will still lack many features that data.table provides, including (sub)-assignment by reference.

  3. Aggregate while joining:

    Suppose you have two data.tables as follows:

    DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
    #    x y z
    # 1: 1 a 1
    # 2: 1 a 2
    # 3: 1 b 3
    # 4: 1 b 4
    # 5: 2 a 5
    # 6: 2 a 6
    # 7: 2 b 7
    # 8: 2 b 8
    DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
    #    x y mul
    # 1: 1 a   4
    # 2: 2 b   3
    

    And you would like to get sum(z) * mul for each row in DT2 while joining by columns x,y. We can either:

    • 1) aggregate DT1 to get sum(z), 2) perform a join and 3) multiply (or)

      # data.table way
      DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
      
      # dplyr equivalent
      DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
          right_join(DF2) %>% mutate(z = z * mul)
      
    • 2) do it all in one go (using by = .EACHI feature):

      DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
      

    What is the advantage?

    • We don't have to allocate memory for the intermediate result.

    • We don't have to group/hash twice (one for aggregation and other for joining).

    • And more importantly, the operation what we wanted to perform is clear by looking at j in (2).

    Check this post for a detailed explanation of by = .EACHI. No intermediate results are materialised, and the join+aggregate is performed all in one go.

    Have a look at this, this and this posts for real usage scenarios.

    In dplyr you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).

  4. Update and joins:

    Consider the data.table code shown below:

    DT1[DT2, col := i.mul]
    

    adds/updates DT1's column col with mul from DT2 on those rows where DT2's key column matches DT1. I don't think there is an exact equivalent of this operation in dplyr, i.e., without avoiding a *_join operation, which would have to copy the entire DT1 just to add a new column to it, which is unnecessary.

    Check this post for a real usage scenario.

To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!

3. Syntax

Let's now look at syntax. Hadley commented here:

Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...

I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.

We will work with the dummy data shown below:

DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
  1. Basic aggregation/update operations.

    # case (a)
    DT[, sum(y), by = z]                       ## data.table syntax
    DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
    DT[, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
    
    # case (b)
    DT[x > 2, sum(y), by = z]
    DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
    DT[x > 2, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
    
    # case (c)
    DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
    DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
    DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
    DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
    
    • data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).

    • In case (b), we had to use filter() in dplyr while summarising. But while updating, we had to move the logic inside mutate(). In data.table however, we express both operations with the same logic - operate on rows where x > 2, but in first case, get sum(y), whereas in the second case update those rows for y with its cumulative sum.

      This is what we mean when we say the DT[i, j, by] form is consistent.

    • Similarly in case (c), when we have if-else condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if condition satisfies and skip otherwise, we cannot use summarise() directly (AFAICT). We have to filter() first and then summarise because summarise() always expects a single value.

      While it returns the same result, using filter() here makes the actual operation less obvious.

      It might very well be possible to use filter() in the first case as well (does not seem obvious to me), but my point is that we should not have to.

  2. Aggregation / update on multiple columns

    # case (a)
    DT[, lapply(.SD, sum), by = z]                     ## data.table syntax
    DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
    DT[, (cols) := lapply(.SD, sum), by = z]
    ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
    
    # case (b)
    DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
    DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
    
    # case (c)
    DT[, c(.N, lapply(.SD, sum)), by = z]     
    DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
    
    • In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply(), whereas dplyr introduces *_each() along with a bunch of functions to funs().

    • data.table's := requires column names to be provided, whereas dplyr generates it automatically.

    • In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.

    • In case (c) though, dplyr would return n() as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c() to concatenate .N to a list which returns a list.

    Note: Once again, in data.table, all we need to do is return a list in j. Each element of the list will become a column in result. You can use c(), as.list(), lapply(), list() etc... base functions to accomplish this, without having to learn any new functions.

    You will need to learn just the special variables - .N and .SD at least. The equivalent in dplyr are n() and .

  3. Joins

    dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by] (and with reason). It also provides an equivalent merge.data.table() function as an alternative.

    setkey(DT1, x, y)
    
    # 1. normal join
    DT1[DT2]            ## data.table syntax
    left_join(DT2, DT1) ## dplyr syntax
    
    # 2. select columns while join    
    DT1[DT2, .(z, i.mul)]
    left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
    
    # 3. aggregate while join
    DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
    DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
        inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
    
    # 4. update while join
    DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
    ??
    
    # 5. rolling join
    DT1[DT2, roll = -Inf]
    ??
    
    # 6. other arguments to control output
    DT1[DT2, mult = "first"]
    ??
    
    • Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by], or merge() which is similar to base R.

    • However dplyr joins do just that. Nothing more. Nothing less.

    • data.tables can select columns while joining (2), and in dplyr you will need to select() first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.

    • data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI feature. Why materialse the entire join result to add/update just a few columns?

    • data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.

    • data.table also has mult = argument which selects first, last or all matches (6).

    • data.table has allow.cartesian = TRUE argument to protect from accidental invalid joins.

Once again, the syntax is consistent with DT[i, j, by] with additional arguments allowing for controlling the output further.

  1. do()...

    dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do(). You have to know beforehand about all your functions return value.

    DT[, list(x[1], y[1]), by = z]                 ## data.table syntax
    DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
    DT[, list(x[1:2], y[1]), by = z]
    DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
    
    DT[, quantile(x, 0.25), by = z]
    DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
    DT[, quantile(x, c(0.25, 0.75)), by = z]
    DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
    
    DT[, as.list(summary(x)), by = z]
    DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
    
    • .SD's equivalent is .

    • In data.table, you can throw pretty much anything in j - the only thing to remember is for it to return a list so that each element of the list gets converted to a column.

    • In dplyr, cannot do that. Have to resort to do() depending on how sure you are as to whether your function would always return a single value. And it is quite slow.

Once again, data.table's syntax is consistent with DT[i, j, by]. We can just keep throwing expressions in j without having to worry about these things.

Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...

To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.

data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.

But one should also consider the number of features that dplyr lacks in comparison to data.table.

4. Features

I have pointed out most of the features here and also in this post. In addition:

  • fread - fast file reader has been available for a long time now.

  • fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.

  • Automatic indexing - another handy feature to optimise base R syntax as is, internally.

  • Ad-hoc grouping: dplyr automatically sorts the results by grouping variables during summarise(), which may not be always desirable.

  • Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.

  • Non-equi joins: Allows joins using other operators <=, <, >, >= along with all other advantages of data.table joins.

  • Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.

  • setorder() function in data.table that allows really fast reordering of data.tables by reference.

  • dplyr provides interface to databases using the same syntax, which data.table does not at the moment.

  • data.table provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff, fintersect, funion and fsetequal with additional all argument (as in SQL).

  • data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame compatibility when passed to any R package. dplyr changes base functions filter, lag and [ which can cause problems; e.g. here and here.


Finally:

  • On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.

  • On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).

    • Progress is being made currently (in v1.9.7 devel) towards parallelising known time consuming parts for incremental performance gains using OpenMP.

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

REST, HTTP DELETE and parameters

I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.

Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?

What is the current choice for doing RPC in Python?

Since I've asked this question, I've started using python-symmetric-jsonrpc. It is quite good, can be used between python and non-python software and follow the JSON-RPC standard. But it lacks some examples.

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

As written by Dave Butenhof himself:

"The biggest of all the big problems with recursive mutexes is that they encourage you to completely lose track of your locking scheme and scope. This is deadly. Evil. It's the "thread eater". You hold locks for the absolutely shortest possible time. Period. Always. If you're calling something with a lock held simply because you don't know it's held, or because you don't know whether the callee needs the mutex, then you're holding it too long. You're aiming a shotgun at your application and pulling the trigger. You presumably started using threads to get concurrency; but you've just PREVENTED concurrency."

What is the meaning of prepended double colon "::"?

:: is the scope resolution operator. It's used to specify the scope of something.

For example, :: alone is the global scope, outside all other namespaces.

some::thing can be interpreted in any of the following ways:

  • some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
  • some is a class available in the current scope and thing is a member object, function or type of the some class;
  • in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.

You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.

So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.

The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.

I hope this answer is complete and correct enough to help you understand scope resolution.

Hiding elements in responsive layout?

For Bootstrap 4.0 beta (and I assume this will stay for final) there is a change - be aware that the hidden classes were removed.

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

Converting milliseconds to minutes and seconds with Javascript

function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

millisToMinutesAndSeconds(298999); // "4:59"
millisToMinutesAndSeconds(60999);  // "1:01"

As User HelpingHand pointed in the comments the return statement should be

return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);

VBA macro that search for file in multiple subfolders

I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.

Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant

For Each vFile In colFiles
     'file operation here or store file name/path in a string array for use later in the script
     filepath(n) = vFile
     filename = fso.GetFileName(vFile) 'If you want the filename without full path
     n=n+1
Next vFile


'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
    colFiles.Add strFolder & strTemp
    strTemp = Dir
Loop
If bIncludeSubfolders Then

    strTemp = Dir(strFolder, vbDirectory)
    Do While strTemp <> vbNullString
        If (strTemp <> ".") And (strTemp <> "..") Then
            If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                colFolders.Add strTemp
            End If
        End If
        strTemp = Dir
    Loop
    'Call RecursiveDir for each subfolder in colFolders
    For Each vFolderName In colFolders
        Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
    Next vFolderName
End If
End Function

Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
    If Right(strFolder, 1) = "\" Then
        TrailingSlash = strFolder
    Else
        TrailingSlash = strFolder & "\"
    End If
End If
End Function

This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

How do I set a cookie on HttpClient's HttpRequestMessage

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);
    result.EnsureSuccessStatusCode();
}

TypeScript getting error TS2304: cannot find name ' require'

I found the solution was to use the TSD command:

tsd install node --save

Which adds/updates the typings/tsd.d.ts file and that file contains all the type definitions that are required for a node application.

At the top of my file, I put a reference to the tsd.d.ts like this:

/// <reference path="../typings/tsd.d.ts" />

The require is defined like this as of January 2016:

declare var require: NodeRequire;

interface NodeModule {
    exports: any;
    require: NodeRequireFunction;
    id: string;
    filename: string;
    loaded: boolean;
    parent: any;
    children: any[];
}

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

Convert an NSURL to an NSString

If you're interested in the pure string:

[myUrl absoluteString];

If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):

[myUrl path];

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

Problem is, you're trying to upcast to a richer object. You simply need to add the items to a new list:

if (myObject is IEnumerable)
{
   List<object> list = new List<object>();
   var enumerator = ((IEnumerable) myObject).GetEnumerator();
   while (enumerator.MoveNext())
   {
      list.Add(enumerator.Current);
   }
}

How to limit the maximum value of a numeric field in a Django model?

You can use Django's built-in validators

from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator

class CoolModelBro(Model):
    limited_integer_field = IntegerField(
        default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ]
     )

Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm since the forms will do that automatically.

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

How to install popper.js with Bootstrap 4?

It's simple you can Visit this, And save the file as popper.min.js

then import it.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import 'bootstrap/dist/js/popper.min.js';
global.jQuery = require('jquery');
require('bootstrap');

Delete all the records

I can see the that the others answers shown above are right, but I'll make your life easy.

I even created an example for you. I added some rows and want delete them.

You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:

enter image description here

Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.

enter image description here

To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.

jQuery 1.9 .live() is not a function

.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed

How do I convert from BLOB to TEXT in MySQL?

Or you can use this function:

DELIMITER $$

CREATE FUNCTION BLOB2TXT (blobfield VARCHAR(255)) RETURNS longtext
DETERMINISTIC
NO SQL
BEGIN
       RETURN CAST(blobfield AS CHAR(10000) CHARACTER SET utf8);
END
$$


DELIMITER ;

What causes a TCP/IP reset (RST) flag to be sent?

Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.

In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.

recursively use scp but excluding some folders

Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude.

Something like this should do:

sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store

Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.

Running EXE with parameters

ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false; 
System.Diagnostics.Process.Start(startInfo);

setup android on eclipse but don't know SDK directory

May be i am too much late here and question is already answered, but this may help those who still cannot find sdk location. Open eclipse, click window tab it will show a drop down menu, click preferences, in preferences window click Android, here u go Sdk location is right in front of u copy the address :)

How do I exit from the text window in Git?

Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.

Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.

Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?

Adding Multiple Values in ArrayList at a single index

You can pass an object which is refering to all the values at a particular index.

import java.util.ArrayList;

public class HelloWorld{

 public static void main(String []args){


ArrayList<connect> a=new ArrayList<connect>();

a.add(new connect(100,100,100,100,100));

System.out.println(a.get(0).p1);

System.out.println(a.get(0).p2);

System.out.println(a.get(0).p3);
}

}

class connect
{
int p1,p2,p3,p4,p5;

connect(int a,int b,int c,int d,int e)
{

this.p1=a;

this.p2=b;

this.p3=c;

this.p4=d;

this.p5=e;
}

}

Later to get a particular value at a specific index, you can do this:

a.get(0).p1;

a.get(0).p2;

a.get(0).p3;.............

and so on.

Remove all special characters from a string in R?

Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.

astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')

which results in

[1] "Abcdeacoauu"

How do I simulate a low bandwidth, high latency environment?

To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

Safely casting long to int in Java

With Google Guava's Ints class, your method can be changed to:

public static int safeLongToInt(long l) {
    return Ints.checkedCast(l);
}

From the linked docs:

checkedCast

public static int checkedCast(long value)

Returns the int value that is equal to value, if possible.

Parameters: value - any value in the range of the int type

Returns: the int value that equals value

Throws: IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE

Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

mysql error 1364 Field doesn't have a default values

Before every insert action I added below line and solved my issue,

SET SQL_MODE = '';

I'm not sure if this is the best solution,

SET SQL_MODE = ''; INSERT INTO  `mytable` (  `field1` ,  `field2`) VALUES ('value1',  'value2');

How to enter quotes in a Java string?

In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.

If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:

String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";

Or, if you want to do it with one String variable, it would be:

String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";

Of course, this actually replaces the original ROM, since Java Strings are immutable.

If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.

JPA entity without id

I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id.

And if your table has some id but your entity doesn't, make it an Embeddable.

How do I enable Java in Microsoft Edge web browser?

You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.

Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.

Work-arounds

There are a couple of things that you can do:

Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets). IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe). Just pin this exe to your task bar for easy access.

Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.

Convert a Unix timestamp to time in JavaScript

// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

ImportError: cannot import name main when running pip --version command in windows7 32 bit

A simple solution that works with Ubuntu, but may fix the problem on windows too:

Just call

pip install --upgrade pip

Extract filename and extension in Bash

A simple answer:

To expand on the POSIX variables answer, note that you can do more interesting patterns. So for the case detailed here, you could simply do this:

tar -zxvf $1
cd ${1%.tar.*}

That will cut off the last occurrence of .tar.<something>.

More generally, if you wanted to remove the last occurrence of .<something>.<something-else> then

${1.*.*}

should work fine.

The link the above answer appears to be dead. Here's a great explanation of a bunch of the string manipulation you can do directly in Bash, from TLDP.

Retrieving Property name from lambda expression

I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
    var expression = (MemberExpression)action.Body;
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

And then call it like so.

GetInfo((User u) => u.UserId);

and voila it works.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

html5 - canvas element - Multiple layers

You might also checkout http://www.concretejs.com which is a modern, lightweight, Html5 canvas framework that enables hit detection, layering, and lots of other peripheral things. You can do things like this:

var wrapper = new Concrete.Wrapper({
  width: 500,
  height: 300,
  container: el
});

var layer1 = new Concrete.Layer();
var layer2 = new Concrete.Layer();

wrapper.add(layer1).add(layer2);

// draw stuff
layer1.sceneCanvas.context.fillStyle = 'red';
layer1.sceneCanvas.context.fillRect(0, 0, 100, 100);

// reorder layers
layer1.moveUp();

// destroy a layer
layer1.destroy();

collapse cell in jupyter notebook

I had a similar issue and the "nbextensions" pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button: Hide Input

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings Collapsible Headings

  • Codefolding | This has been mentioned but I add it for completeness Codefolding

UILabel - Wordwrap text

In Swift you would do it like this:

    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.numberOfLines = 0

(Note that the way the lineBreakMode constant works is different to in ObjC)

How can the size of an input text box be defined in HTML?

You can set the width in pixels via inline styling:

<input type="text" name="text" style="width: 195px;">

You can also set the width with a visible character length:

<input type="text" name="text" size="35">

Each for object?

for(var key in object) {
   console.log(object[key]);
}

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How to use Git?

Using Git for version control

Visual studio code have Integrated Git Support.

  • Steps to use git.

Install Git : https://git-scm.com/downloads

1) Initialize your repository

Navigate to directory where you want to initialize Git

Use git init command This will create a empty .git repository

2) Stage the changes

Staging is process of making Git to track our newly added files. For example add a file and type git status. You will find the status that untracked file. So to stage the changes use git add filename. If now type git status, you will find that new file added for tracking.

You can also unstage files. Use git reset

3) Commit Changes

Commiting is the process of recording your changes to repository. To commit the statges changes, you need to add a comment that explains the changes you made since your previous commit.

Use git commit -m message string

We can also commit the multiple files of same type using command git add '*.txt'. This command will commit all files with txt extension.

4) Follow changes

The aim of using version control is to keep all versions of each and every file in our project, Compare the the current version with last commit and keep the log of all changes.

Use git log to see the log of all changes.

Visual studio code’s integrated git support help us to compare the code by double clicking on the file OR Use git diff HEAD

You can also undo file changes at the last commit. Use git checkout -- file_name

5) Create remote repositories

Till now we have created a local repository. But in order to push it to remote server. We need to add a remote repository in server.

Use git remote add origin server_git_url

Then push it to server repository

Use git push -u origin master

Let assume some time has passed. We have invited other people to our project who have pulled our changes, made their own commits, and pushed them.

So to get the changes from our team members, we need to pull the repository.

Use git pull origin master

6) Create Branches

Lets think that you are working on a feature or a bug. Better you can create a copy of your code(Branch) and make separate commits to. When you have done, merge this branch back to their master branch.

Use git branch branch_name

Now you have two local branches i.e master and XXX(new branch). You can switch branches using git checkout master OR git checkout new_branch_name

Commiting branch changes using git commit -m message

Switch back to master using git checkout master

Now we need to merge changes from new branch into our master Use git merge branch_name

Good! You just accomplished your bugfix Or feature development and merge. Now you don’t need the new branch anymore. So delete it using git branch -d branch_name

Now we are in the last step to push everything to remote repository using git push

Hope this will help you

How to increment an iterator by 2?

If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next / std::prev:

std::next(iter, 2);          // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2);          // returns a copy of iter decremented by 2

What does file:///android_asset/www/index.html mean?

it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets

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

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

What are best practices that you use when writing Objective-C and Cocoa?

Sort strings as the user wants

When you sort strings to present to the user, you should not use the simple compare: method. Instead, you should always use localized comparison methods such as localizedCompare: or localizedCaseInsensitiveCompare:.

For more details, see Searching, Comparing, and Sorting Strings.

Iterate over model instance field names and values in template

You can use the values() method of a queryset, which returns a dictionary. Further, this method accepts a list of fields to subset on. The values() method will not work with get(), so you must use filter() (refer to the QuerySet API).

In view...

def show(request, object_id):
   object = Foo.objects.filter(id=object_id).values()[0]
   return render_to_response('detail.html', {'object': object})

In detail.html...

<ul>
   {% for key, value in object.items %}
        <li><b>{{ key }}:</b> {{ value }}</li>
   {% endfor %}
</ul>

For a collection of instances returned by filter:

   object = Foo.objects.filter(id=object_id).values() # no [0]

In detail.html...

{% for instance in object %}
<h1>{{ instance.id }}</h1>
<ul>
    {% for key, value in instance.items %}
        <li><b>{{ key }}:</b>  {{ value }}</li>
    {% endfor %}
</ul>
{% endfor %}

Access-Control-Allow-Origin and Angular.js $http

Adding below to server.js resolved mine

    server.post('/your-rest-endpt/*', function(req,res){
    console.log('');
    console.log('req.url: '+req.url);
    console.log('req.headers: ');   
    console.dir(req.headers);
    console.log('req.body: ');
    console.dir(req.body);  

    var options = {
        host: 'restAPI-IP' + ':' + '8080'

        , protocol: 'http'
        , pathname: 'your-rest-endpt/'
    };
    console.log('options: ');
    console.dir(options);   

    var reqUrl = url.format(options);
    console.log("Forward URL: "+reqUrl);

    var parsedUrl = url.parse(req.url, true);
    console.log('parsedUrl: ');
    console.dir(parsedUrl);

    var queryParams = parsedUrl.query;

    var path = parsedUrl.path;
    var substr = path.substring(path.lastIndexOf("rest/"));
    console.log('substr: ');
    console.dir(substr);

    reqUrl += substr;
    console.log("Final Forward URL: "+reqUrl);

    var newHeaders = {
    };

    //Deep-copy it, clone it, but not point to me in shallow way...
    for (var headerKey in req.headers) {
        newHeaders[headerKey] = req.headers[headerKey];
    };

    var newBody = (req.body == null || req.body == undefined ? {} : req.body);

    if (newHeaders['Content-type'] == null
            || newHeaders['Content-type'] == undefined) {
        newHeaders['Content-type'] = 'application/json';
        newBody = JSON.stringify(newBody);
    }

    var requestOptions = {
        headers: {
            'Content-type': 'application/json'
        }
        ,body: newBody
        ,method: 'POST'
    };

    console.log("server.js : routes to URL : "+ reqUrl);

    request(reqUrl, requestOptions, function(error, response, body){
        if(error) {
            console.log('The error from Tomcat is --> ' + error.toString());
            console.dir(error);
            //return false;
        }

        if (response.statusCode != null 
                && response.statusCode != undefined
                && response.headers != null
                && response.headers != undefined) {
            res.writeHead(response.statusCode, response.headers);
        } else {
            //404 Not Found
            res.writeHead(404);         
        }
        if (body != null
                && body != undefined) {

            res.write(body);            
        }
        res.end();
    });
});

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

Using a dispatch_once singleton model in Swift

   func init() -> ClassA {
    struct Static {
        static var onceToken : dispatch_once_t = 0
        static var instance : ClassA? = nil
    }

    dispatch_once(&Static.onceToken) {
        Static.instance = ClassA()
    }

    return Static.instance!
}

In Python how should I test if a variable is None, True or False

if result is None:
    print "error parsing stream"
elif result:
    print "result pass"
else:
    print "result fail"

keep it simple and explicit. You can of course pre-define a dictionary.

messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]

If you plan on modifying your simulate function to include more return codes, maintaining this code might become a bit of an issue.

The simulate might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.

Multiple submit buttons in an HTML form

Sometimes the provided solution by @palotasb is not sufficient. There are use cases where for example a "Filter" submits button is placed above buttons like "Next and Previous". I found a workaround for this: copy the submit button which needs to act as the default submit button in a hidden div and place it inside the form above any other submit button. Technically it will be submitted by a different button when pressing Enter than when clicking on the visible Next button. But since the name and value are the same, there's no difference in the result.

<html>
<head>
    <style>
        div.defaultsubmitbutton {
            display: none;
        }
    </style>
</head>
<body>
    <form action="action" method="get">
        <div class="defaultsubmitbutton">
            <input type="submit" name="next" value="Next">
        </div>
        <p><input type="text" name="filter"><input type="submit" value="Filter"></p>
        <p>Filtered results</p>
        <input type="radio" name="choice" value="1">Filtered result 1
        <input type="radio" name="choice" value="2">Filtered result 2
        <input type="radio" name="choice" value="3">Filtered result 3
        <div>                
            <input type="submit" name="prev" value="Prev">
            <input type="submit" name="next" value="Next">
        </div>
    </form>
</body>
</html>

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
-------------------------
| clr enabled | YES     |

Tested on SQL Server 2017

Tomcat manager/html is not available?

My problem/solution is very embarrassing but who knows... perhaps it happened to someone else:

My solution: Turn off proxy

For the past two hours I've been wondering why my manager would not load. (the root was cached so it loaded). I had set the browser's proxy to proxy traffic to my house. :/

How to record phone calls in android?

There is a simple solution to this problem using this library. I store an instance of the CallRecord class in MyService.class. When the service is first initialized, the following code is executed:

public class MyService extends Service {

    public static CallRecord callRecord;

    @Override
    public void onCreate() {
        super.onCreate();

        callRecord = new CallRecord.Builder(this)
                .setRecordFileName("test")
                .setRecordDirName("Download")
                .setRecordDirPath(Environment.getExternalStorageDirectory().getPath()) // optional & default value
                .setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) // optional & default value
                .setOutputFormat(MediaRecorder.OutputFormat.AMR_NB) // optional & default value
                .setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION) // optional & default value
                .setShowSeed(false) // optional, default=true ->Ex: RecordFileName_incoming.amr || RecordFileName_outgoing.amr
                .build();
        callRecord.enableSaveFile();
        callRecord.startCallReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        callRecord.stopCallReceiver();
    } 
}

Next, do not forget to specify permissions in the manifest. (I may have some extras here, but keep in mind that some of them are necessary only for newer versions of Android)

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Also it is crucial to request some permissions at the first start of the application. A guide is provided here.

If my code doesn't work, alternative code can be found here. I hope I helped you.

Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
                                             join candidateUser in authContext.AuthUsers
                                             on r.CandidateId equals candidateUser.Id
                                             join creatorUser in authContext.AuthUsers
                                             on r.CreatorId equals creatorUser.Id into gj
                                             from x in gj.DefaultIfEmpty()
                                             join initiatorUser in authContext.AuthUsers
                                             on r.InitiatorId equals initiatorUser.Id into init
                                             from x1 in init.DefaultIfEmpty()

                                             where candidateUser.UserName.Equals(candidateUsername)
                                             select new CreateRequestModel
                                             {
                                                 UserName = candidateUser.UserName,
                                                 CreatorId = (x == null ? String.Empty : x.UserName),
                                                 InitiatorId = (x1 == null ? String.Empty : x1.UserName),
                                                 CandidateId = candidateUser.UserName
                                             };

What is FCM token in Firebase?

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

matplotlib error - no module named tkinter

For Windows users, there's no need to download the installer again. Just do the following:

  1. Go to start menu, type Apps & features,
  2. Search for "python" in the search box,
  3. Select the Python version (e.g. Python 3.8.3rc1(32-bit)) and click Modify,
  4. On the Modify Setup page click Modify,
  5. Tick td/tk and IDLE checkbox (which installs tkinter) and click next.

Wait for installation and you're done.

Can I call an overloaded constructor from another constructor of the same class in C#?

If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.

However it seems from the comments, it seems what you really intend to ask is 'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)

class A
{
  //ctor chaining
  public A() : this(0)
  {  
      Console.WriteLine("default ctor"); 
  }

  public A(int i)
  {  
      Init(i); 
  }

  // what you want
  public A(string s)
  {  
      Console.WriteLine("string ctor overload" );
      Console.WriteLine("pre-processing" );
      Init(Int32.Parse(s));
      Console.WriteLine("post-processing" );
  }

   private void Init(int i)
   {
      Console.WriteLine("int ctor {0}", i);
   }
}

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

OR

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;

Angular-cli from css to scss

For users of the Nrwl extensions who come across this thread: all commands are intercepted by Nx (e.g., ng generate component myCompent) and then passed down to the AngularCLI.

The command to get SCSS working in an Nx workspace:

ng config schematics.@nrwl/schematics:component.styleext scss

Compare two DataFrames and output their differences side-by-side

After fiddling around with @journois's answer, I was able to get it to work using MultiIndex instead of Panel due to Panel's deprication.

First, create some dummy data:

df1 = pd.DataFrame({
    'id': ['111', '222', '333', '444', '555'],
    'let': ['a', 'b', 'c', 'd', 'e'],
    'num': ['1', '2', '3', '4', '5']
})
df2 = pd.DataFrame({
    'id': ['111', '222', '333', '444', '666'],
    'let': ['a', 'b', 'c', 'D', 'f'],
    'num': ['1', '2', 'Three', '4', '6'],
})

Then, define your diff function, in this case I'll use the one from his answer report_diff stays the same:

def report_diff(x):
    return x[0] if x[0] == x[1] else '{} | {}'.format(*x)

Then, I'm going to concatenate the data into a MultiIndex dataframe:

df_all = pd.concat(
    [df1.set_index('id'), df2.set_index('id')], 
    axis='columns', 
    keys=['df1', 'df2'],
    join='outer'
)
df_all = df_all.swaplevel(axis='columns')[df1.columns[1:]]

And finally I'm going to apply the report_diff down each column group:

df_final.groupby(level=0, axis=1).apply(lambda frame: frame.apply(report_diff, axis=1))

This outputs:

         let        num
111        a          1
222        b          2
333        c  3 | Three
444    d | D          4
555  e | nan    5 | nan
666  nan | f    nan | 6

And that is all!

How do you pass view parameters when navigating from an action in JSF2?

Check out these:

You're gonna need something like:

<h:link outcome="success">
  <f:param name="foo" value="bar"/>
</h:link>

...and...

<f:metadata>
  <f:viewParam name="foo" value="#{bean.foo}"/>
</f:metadata>

Judging from this page, something like this might be easier:

 <managed-bean>
   <managed-bean-name>blog</managed-bean-name>
   <managed-bean-class>com.acme.Blog</managed-bean-class>
   <managed-property>
      <property-name>entryId</property-name>
      <value>#{param['id']}</value>
   </managed-property>
 </managed-bean>

Python Pandas : pivot table with aggfunc = count unique distinct

aggfunc=pd.Series.nunique provides distinct count.

Full Code:

df2.pivot_table(values='X', rows='Y', cols='Z', 
                         aggfunc=pd.Series.nunique)

Credit to @hume for this solution (see comment under the accepted answer). Adding as an answer here for better discoverability.

console.log not working in Angular2 Component (Typescript)

It's not working because console.log() it's not in a "executable area" of the class "App".

A class is a structure composed by attributes and methods.

The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

_x000D_
_x000D_
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
 s: string = "Hello2";_x000D_
            _x000D_
  constructor() {_x000D_
    console.log(this.s)            _x000D_
  }            _x000D_
}
_x000D_
_x000D_
_x000D_

Think of class like a plain javascript object.

Would it make sense to expect this to work?

_x000D_
_x000D_
class:  {_x000D_
  s: string,_x000D_
  console.log(s)_x000D_
 }
_x000D_
_x000D_
_x000D_

If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

https://www.typescriptlang.org/play/index.html

Switching between GCC and Clang/LLVM using CMake

You can use the syntax: $ENV{environment-variable} in your CMakeLists.txt to access environment variables. You could create scripts which initialize a set of environment variables appropriately and just have references to those variables in your CMakeLists.txt files.

Checking if a variable is not nil and not zero in ruby

unless discount.nil? || discount == 0
  # ...
end

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

Using jQuery how to get click coordinates on the target element

$('#something').click(function (e){
    var elm = $(this);
    var xPos = e.pageX - elm.offset().left;
    var yPos = e.pageY - elm.offset().top;

    console.log(xPos, yPos);
});

Node.js Best Practice Exception Handling

One instance where using a try-catch might be appropriate is when using a forEach loop. It is synchronous but at the same time you cannot just use a return statement in the inner scope. Instead a try and catch approach can be used to return an Error object in the appropriate scope. Consider:

function processArray() {
    try { 
       [1, 2, 3].forEach(function() { throw new Error('exception'); }); 
    } catch (e) { 
       return e; 
    }
}

It is a combination of the approaches described by @balupton above.

Number of days between two dates in Joda-Time

public static int getDifferenceIndays(long timestamp1, long timestamp2) {
    final int SECONDS = 60;
    final int MINUTES = 60;
    final int HOURS = 24;
    final int MILLIES = 1000;
    long temp;
    if (timestamp1 < timestamp2) {
        temp = timestamp1;
        timestamp1 = timestamp2;
        timestamp2 = temp;
    }
    Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
    Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
    endDate.setTimeInMillis(timestamp1);
    startDate.setTimeInMillis(timestamp2);
    if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
        int day1 = endDate.get(Calendar.DAY_OF_MONTH);
        int day2 = startDate.get(Calendar.DAY_OF_MONTH);
        if (day1 == day2) {
            return 0;
        } else {
            return 1;
        }
    }
    int diffDays = 0;
    startDate.add(Calendar.DAY_OF_MONTH, diffDays);
    while (startDate.before(endDate)) {
        startDate.add(Calendar.DAY_OF_MONTH, 1);
        diffDays++;
    }
    return diffDays;
}

SFTP file transfer using Java JSch

Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation

Android studio- "SDK tools directory is missing"

If you are using Windows S.O. make sure it is in the folder:

C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools

Otherwise, open Android Studio and go to:

Tools> SDK Manager> Android SDK> SDK Tools

Select the Android Platform-Tools and Android SDK Tools checkbox and click Apply. After download check the directory again.

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

How to set java.net.preferIPv4Stack=true at runtime?

You can use System.setProperty("java.net.preferIPv4Stack" , "true");

This is equivalent to passing it in the command line via -Djava.net.preferIPv4Stack=true

How can I pass variable to ansible playbook in the command line?

ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

My issue was that my web.config file kept a reference to a deleted entity model connection so check there are not any outdated connection strings.

dyld: Library not loaded: @rpath/libswiftCore.dylib

From the post of https://github.com/CocoaPods/cocoapods-integration-specs/pull/24/files, that mean swift.dylib need sign but failed. I failed even create a new swift project with cocoapod support.

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

C++ where to initialize static const

Only integral values (e.g., static const int ARRAYSIZE) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.

Array vs ArrayList in performance

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

javac not working in windows command prompt

I know this may not be your specific error, but I once had a leading space in my path and java would work but javac would not.

For what it's worth, I offer the sage advice: "Examine your Path closely".

Is there a conditional ternary operator in VB.NET?

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns an Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just an object anyway

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.

How to compare two Dates without the time portion?

If you strictly want to use Date ( java.util.Date ), or without any use of external Library. Use this :

public Boolean compareDateWithoutTime(Date d1, Date d2) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    return sdf.format(d1).equals(sdf.format(d2));
}

python, sort descending dataframe with pandas

Edit: This is out of date, see @Merlin's answer.

[False], being a nonempty list, is not the same as False. You should write:

test = df.sort('one', ascending=False)

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

SoapFault exception: Could not connect to host

With me, this problem in base Address in app.config of WCF service: When I've used:

<baseAddresses><add baseAddress="http://127.0.0.1:9022/Service/GatewayService"/> </baseAddresses>

it's ok if use .net to connect with public ip or domain.

But when use PHP's SoapClient to connect to "http://[online ip]:9022/Service/GatewayService", it's throw exception "Coulod not connect to host"

I've changed baseAddress to [online ip]:9022 and everything's ok.

CKEditor instance already exists

I've had similar issue where we were making several instances of CKeditor for the content loaded via ajax.

CKEDITOR.remove()

Kept the DOM in the memory and didn't remove all the bindings.

CKEDITOR.instance[instance_id].destroy()

Gave the error i.contentWindow error whenever I create new instance with new data from ajax. But this was only until I figured out that I was destroying the instance after clearing the DOM.

Use destroy() while the instance & it's DOM is present on the page, then it works perfectly fine.

Propagate all arguments in a bash shell script

My SUN Unix has a lot of limitations, even "$@" was not interpreted as desired. My workaround is ${@}. For example,

#!/bin/ksh
find ./ -type f | xargs grep "${@}"

By the way, I had to have this particular script because my Unix also does not support grep -r

Rerender view on browser resize with React

You don't necessarily need to force a re-render.

This might not help OP, but in my case I only needed to update the width and height attributes on my canvas (which you can't do with CSS).

It looks like this:

import React from 'react';
import styled from 'styled-components';
import {throttle} from 'lodash';

class Canvas extends React.Component {

    componentDidMount() {
        window.addEventListener('resize', this.resize);
        this.resize();
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.resize);
    }

    resize = throttle(() => {
        this.canvas.width = this.canvas.parentNode.clientWidth;
        this.canvas.height = this.canvas.parentNode.clientHeight;
    },50)

    setRef = node => {
        this.canvas = node;
    }

    render() {
        return <canvas className={this.props.className} ref={this.setRef} />;
    }
}

export default styled(Canvas)`
   cursor: crosshair;
`

using jquery $.ajax to call a PHP function

You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).

If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:

function test() {
    // function code
}

test();

Or, use a PHP include:

include 'functions.php'; // functions.php has the test function
test();

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

SQL How to replace values of select return?

I got the solution

   SELECT 
   CASE status
      WHEN 'VS' THEN 'validated by subsidiary'
      WHEN 'NA' THEN 'not acceptable'
      WHEN 'D'  THEN 'delisted'
      ELSE 'validated'
   END AS STATUS
   FROM SUPP_STATUS

This is using the CASE This is another to manipulate the selected value for more that two options.

Find index of last occurrence of a sub-string using T-SQL

REVERSE(SUBSTRING(REVERSE(ap_description),CHARINDEX('.',REVERSE(ap_description)),len(ap_description)))  

worked better for me

Bootstrap: Position of dropdown menu relative to navbar item

If you wants to center the dropdown, this is the solution.

<ul class="dropdown-menu" style="right:auto; left: auto;">

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

How to create a toggle button in Bootstrap

In case someone is still looking for a nice switch/toggle button, I followed Rick's suggestion and created a simple angular directive around it, angular-switch. Besides preferring a Windows styled switch, the total download is also much smaller (2kb vs 23kb minified css+js) compared to angular-bootstrap-switch and bootstrap-switch mentioned above together.

You would use it as follows. First include the required js and css file:

<script src="./bower_components/angular-switch/dist/switch.js"></script>
<link rel="stylesheet" href="./bower_components/angular-switch/dist/switch.css"></link>

And enable it in your angular app:

angular.module('yourModule', ['csComp'
    // other dependencies
]);

Now you are ready to use it as follows:

<switch state="vm.isSelected" 
    textlabel="Switch" 
    changed="vm.changed()"
    isdisabled="{{isDisabled}}">
</switch>

enter image description here

jQuery datepicker to prevent past date

I am using following code to format date and show 2 months in calendar...

<script>
$(function() {

    var dates = $( "#from, #to" ).datepicker({

        showOn: "button",
        buttonImage: "imgs/calendar-month.png",
        buttonImageOnly: true,                           
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2,

        onSelect: function( selectedDate ) {




            $( ".selector" ).datepicker({ defaultDate: +7 });
            var option = this.id == "from" ? "minDate" : "maxDate",


                instance = $( this ).data( "datepicker" ),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings );

            dates.not( this ).datepicker( "option", "dateFormat", 'yy-mm-dd' );


        }
    });
});

</script>

The problem is I am not sure how to restrict previous dates selection.

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

How to equalize the scales of x-axis and y-axis in Python matplotlib?

Try something like:

import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()

Animate element transform rotate

As far as I know, basic animates can't animate non-numeric CSS properties.

I believe you could get this done using a step function and the appropriate css3 transform for the users browser. CSS3 transform is a bit tricky to cover all your browsers in (IE6 you need to use the Matrix filter, for instance).

EDIT: here's an example that works in webkit browsers (Chrome, Safari): http://jsfiddle.net/ryleyb/ERRmd/

If you wanted to support IE9 only, you could use transform instead of -webkit-transform, or -moz-transform would support FireFox.

The trick used is to animate a CSS property we don't care about (text-indent) and then use its value in a step function to do the rotation:

$('#foo').animate(
..
step: function(now,fx) {
  $(this).css('-webkit-transform','rotate('+now+'deg)'); 
}
...

Should 'using' directives be inside or outside the namespace?

The technical reasons are discussed in the answers and I think that it comes to the personal preferences in the end since the difference is not that big and there are tradeoffs for both of them. Visual Studio's default template for creating .cs files use using directives outside of namespaces e.g.

One can adjust stylecop to check using directives outside of namespaces through adding stylecop.json file in the root of the project file with the following:

{
  "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
    "orderingRules": {
      "usingDirectivesPlacement": "outsideNamespace"
    }
  }
}

You can create this config file in solution level and add it to your projects as 'Existing Link File' to share the config across all of your projects too.

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

ng-repeat: access key and value for each object in array of objects

seems like in Angular 1.3.12 you do not need the inner ng-repeat anymore, the outer loop returns the values of the collection is a single map entry

What is the difference between a web API and a web service?

Well, TMK may be right in the Microsoft world, but in world of all software including Java/Python/etc, I believe that there is no difference. They're the same thing.

Replace all spaces in a string with '+'

var str = 'a b c';
var replaced = str.replace(/\s/g, '+');

Custom sort function in ng-repeat

Actually the orderBy filter can take as a parameter not only a string but also a function. From the orderBy documentation: https://docs.angularjs.org/api/ng/filter/orderBy):

function: Getter function. The result of this function will be sorted using the <, =, > operator.

So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:

$scope.myValueFunction = function(card) {
   return card.values.opt1 + card.values.opt2;
};

and then, in your template:

ng-repeat="card in cards | orderBy:myValueFunction"

Here is the working jsFiddle

The other thing worth noting is that orderBy is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy should be enough for most uses cases).

Angular 5 Service to read local .json file

Try This

Write code in your service

import {Observable, of} from 'rxjs';

import json file

import Product  from "./database/product.json";

getProduct(): Observable<any> {
   return of(Product).pipe(delay(1000));
}

In component

get_products(){
    this.sharedService.getProduct().subscribe(res=>{
        console.log(res);
    })        
}

How to trigger Jenkins builds remotely and to pass parameters

You can trigger Jenkins builds remotely and to pass parameters by using the following query.

JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value

JENKINS_URL (can be) = https://<your domain name or server address>

TOKE_NAME can be created using configure tab

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

How do I get the find command to print out the file size with the file name?

a simple solution is to use the -ls option in find:

find . -name \*.ear -ls

That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:

find . -name \*.ear -printf "%p\t%k KB\n"

Which will give you the filename followed by the size in KB.

How to upgrade all Python packages with pip

The shortest and easiest on Windows.

pip freeze > requirements.txt && pip install --upgrade -r requirements.txt && rm requirements.txt

Using multiprocessing.Process with a maximum number of simultaneous processes

more generally, this could also look like this:

import multiprocessing
def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

numberOfThreads = 4


if __name__ == '__main__':
    jobs = []
    for i, param in enumerate(params):
        p = multiprocessing.Process(target=f, args=(i,param))
        jobs.append(p)
    for i in chunks(jobs,numberOfThreads):
        for j in i:
            j.start()
        for j in i:
            j.join()

Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

How do I check if an integer is even or odd?

I'd say just divide it by 2 and if there is a 0 remainder, it's even, otherwise it's odd.

Using the modulus (%) makes this easy.

eg. 4 % 2 = 0 therefore 4 is even 5 % 2 = 1 therefore 5 is odd

How to add column to numpy array

The easiest solution is to use numpy.insert().

The Advantage of np.insert() over np.append is that you can insert the new columns into custom indices.

import numpy as np

X = np.arange(20).reshape(10,2)

X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

Where is the WPF Numeric UpDown control?

Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro. Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

<mah:NumericUpDown x:Name="NumericUpDown" ... /> 

Enjoy the full extensibility of the object (Bindings, triggers and so on...).

Check whether a path is valid in Python without creating a file at the path's target

try os.path.exists this will check for the path and return True if exists and False if not.

How to prevent favicon.ico requests?

Personally I used this in my HTML head tag:

<link rel="shortcut icon" href="#" />

Add SUM of values of two LISTS into new LIST

The zip function is useful here, used with a list comprehension.

[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

Matplotlib 2 Subplots, 1 Colorbar

Using make_axes is even easier and gives a better result. It also provides possibilities to customise the positioning of the colorbar. Also note the option of subplots to share x and y axes.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

cax,kw = mpl.colorbar.make_axes([ax for ax in axes.flat])
plt.colorbar(im, cax=cax, **kw)

plt.show()

Disable copy constructor

If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:

class NonAssignable {
private:
    NonAssignable(NonAssignable const&);
    NonAssignable& operator=(NonAssignable const&);
public:
    NonAssignable() {}
};

class SymbolIndexer: public Indexer, public NonAssignable {
};

For GCC this gives the following error message:

test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private

I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.

UPD:

In C++11 you may also write NonAssignable class as follows:

class NonAssignable {
public:
    NonAssignable(NonAssignable const&) = delete;
    NonAssignable& operator=(NonAssignable const&) = delete;
    NonAssignable() {}
};

The delete keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:

test.cpp: error: use of deleted function
          ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
          is implicitly deleted because the default definition would
          be ill-formed:

UPD:

Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable and is meant to be used as in the following:

#include <boost/core/noncopyable.hpp>

class SymbolIndexer: public Indexer, private boost::noncopyable {
};

I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable-related question for more information.

Comparing date part only without comparing time in JavaScript

This might be a little cleaner version, also note that you should always use a radix when using parseInt.

window.addEvent('domready', function() {
    // Create a Date object set to midnight on today's date
    var today = new Date((new Date()).setHours(0, 0, 0, 0)),
    input = $('datum').getValue(),
    dateArray = input.split('/'),
    // Always specify a radix with parseInt(), setting the radix to 10 ensures that
    // the number is interpreted as a decimal.  It is particularly important with
    // dates, if the user had entered '09' for the month and you don't use a
    // radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
    userMonth = parseInt(dateArray[1], 10) - 1,
    // Create a Date object set to midnight on the day the user specified
    userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);

    // Convert date objects to milliseconds and compare
    if(userDate.getTime() > today.getTime())
    {
            alert(today+'\n'+userDate);
    }
});

Checkout the MDC parseInt page for more information about the radix.

JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors. It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.

Get array of object's keys

Summary

For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.

Example:

_x000D_
_x000D_
const object = {_x000D_
  a: 'string1',_x000D_
  b: 42,_x000D_
  c: 34_x000D_
};_x000D_
_x000D_
const keys = Object.keys(object)_x000D_
_x000D_
console.log(keys);_x000D_
_x000D_
console.log(keys.length) // we can easily access the total amount of properties the object has
_x000D_
_x000D_
_x000D_

In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.

Getting the values with: Object.values()

The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:

_x000D_
_x000D_
const object = {_x000D_
  a: 'random',_x000D_
  b: 22,_x000D_
  c: true_x000D_
};_x000D_
_x000D_
_x000D_
console.log(Object.values(object));
_x000D_
_x000D_
_x000D_

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

Here is my favorite way, which I think is a little less tedious than the "Select for Compare, then Compare With..." steps.

  • Open the left side file (not editable)
  • F1 Compare Active File With...
  • Select the right side file (editable) - You can either select a recent file from the dropdown list, or click any file in the Explorer panel.

This works with any arbitrary files, even ones that are not in the project dir. You can even just create 2 new Untitled files and copy/paste text in there too.

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

ActiveRecord OR query

Just add an OR in the conditions

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])

Where in an Eclipse workspace is the list of projects stored?

In Eclipse 3.3:

It's installed under your Eclipse workspace. Something like:

.metadata\.plugins\org.eclipse.core.resources\.projects\

within your workspace folder.

Under that folder is one folder per project. There's a file in there called .location, but it's binary.

So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.

How to check a string for a special character?

You will need to define "special characters", but it's likely that for some string s you mean:

import re
if re.match(r'^\w+$', s):
    # s is good-to-go

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

Should you use .htm or .html file extension? What is the difference, and which file is correct?

It's the same in terms of functionality and support. (most OS recognize both, most Search Engines recognize both)

For my everyday use, I choose .htm because it's shorter to type by 25%.

How can I hide the Android keyboard using JavaScript?

Here is a bullet-proof method that works for Android 2.3.x and 4.x

You can test this code using this link: http://jsbin.com/pebomuda/14

function hideKeyboard() {
  //this set timeout needed for case when hideKeyborad
  //is called inside of 'onfocus' event handler
  setTimeout(function() {

    //creating temp field
    var field = document.createElement('input');
    field.setAttribute('type', 'text');
    //hiding temp field from peoples eyes
    //-webkit-user-modify is nessesary for Android 4.x
    field.setAttribute('style', 'position:absolute; top: 0px; opacity: 0; -webkit-user-modify: read-write-plaintext-only; left:0px;');
    document.body.appendChild(field);

    //adding onfocus event handler for out temp field
    field.onfocus = function(){
      //this timeout of 200ms is nessasary for Android 2.3.x
      setTimeout(function() {

        field.setAttribute('style', 'display:none;');
        setTimeout(function() {
          document.body.removeChild(field);
          document.body.focus();
        }, 14);

      }, 200);
    };
    //focusing it
    field.focus();

  }, 50);
}

"No such file or directory" error when executing a binary

Old question, but hopefully this'll help someone else.

In my case I was using a toolchain on Ubuntu 12.04 that was built on Ubuntu 10.04 (requires GCC 4.1 to build). As most of the libraries have moved to multiarch dirs, it couldn't find ld.so. So, make a symlink for it.

Check required path:

$ readelf -a arm-linux-gnueabi-gcc | grep interpreter:
      [Requesting program interpreter: /lib/ld-linux-x86-64.so.2]

Create symlink:

$ sudo ln -s /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib/ld-linux-x86-64.so.2

If you're on 32bit, it'll be i386-linux-gnu and not x86_64-linux-gnu.

Stop node.js program from command line

My use case: on MacOS, run/rerun multiple node servers on different ports from a script

run: "cd $PATH1 && node server1.js & cd $PATH2 && node server2.js & ..."

stop1: "kill -9 $(lsof -nP -i4TCP:$PORT1 | grep LISTEN | awk '{print $2}')"

stop2, stop3...

rerun: "stop1 & stop2 & ... & stopN ; run

for more info about finding a process by a port: Who is listening on a given TCP port on Mac OS X?

Java dynamic array sizes?

It is a good practice get the amount you need to store first then initialize the array.

for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.

//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList(); 
//add a certain amount of data
for(int i=0;i<x;i++)
{
  al.add("data "+i); 
}

//get size of data inside
int size = al.size(); 
//initialize String array with the size you have
String strArray[] = new String[size]; 
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
  strArray[i] = al.get(i);
}

doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack

Disable resizing of a Windows Forms form

  1. First, select the form.
  2. Then, go to the properties menu.
  3. And change the property "FormBorderStyle" from sizable to Fixed3D or FixedSingle.

    This is where to modify the property "FormBorderStyle".

How to clean up R memory (without the need to restart my PC)?

I've found it helpful to go into my "tmp" folder and delete all hanging rsession files. This usually frees any memory that seems to be "stuck".

How to include route handlers in multiple files in Express?

Building on @ShadowCloud 's example I was able to dynamically include all routes in a sub directory.

routes/index.js

var fs = require('fs');

module.exports = function(app){
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file == "index.js") return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);
    });
}

Then placing route files in the routes directory like so:

routes/test1.js

module.exports = function(app){

    app.get('/test1/', function(req, res){
        //...
    });

    //other routes..
}

Repeating that for as many times as I needed and then finally in app.js placing

require('./routes')(app);

Converting an int to std::string

The following macro is not quite as compact as a single-use ostringstream or boost::lexical_cast.

But if you need conversion-to-string repeatedly in your code, this macro is more elegant in use than directly handling stringstreams or explicit casting every time.

It is also very versatile, as it converts everything supported by operator<<(), even in combination.

Definition:

#include <sstream>

#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()

Explanation:

The std::dec is a side-effect-free way to make the anonymous ostringstream into a generic ostream so operator<<() function lookup works correctly for all types. (You get into trouble otherwise if the first argument is a pointer type.)

The dynamic_cast returns the type back to ostringstream so you can call str() on it.

Use:

#include <string>

int main()
{
    int i = 42;
    std::string s1 = SSTR( i );

    int x = 23;
    std::string s2 = SSTR( "i: " << i << ", x: " << x );
    return 0;
}

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

How to execute powershell commands from a batch file?

This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.

pros:

  • can be run like standard .cmd file
  • only one file for batch and powershell script
  • powershell script may be multi-line (easy to read script)
  • allows the standard console input (use the Read-Host cmdlet by standard way)

cons:

  • requires powershell version 2.0+

Commented and runable example of batch-ps-script.cmd:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

Snippet for .cmd file:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...

Illegal Escape Character "\"

do two \'s

"\\"

it's because it's an escape character

How do I rename a Git repository?

  • On the server side, just rename the repository with the mv command as usual:

    mv oldName.git newName.git
    
  • Then on the client side, change the value of the [remote "origin"] URL into the new one:

    url=example.com/newName.git
    

It worked for me.

How to handle checkboxes in ASP.NET MVC forms?

This issue is happening in the release 1.0 as well. Html.Checkbox() causes another hidden field to be added with the same name/id as of your original checkbox. And as I was trying loading up a checkbox array using document.GetElemtentsByName(), you can guess how things were getting messed up. It's a bizarre.

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

Executing an EXE file using a PowerShell script

Not being a developer I found a solution in running multiple ps commands in one line. E.g:

powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc

By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.

Get model's fields in Django

I know this post is pretty old, but I just cared to tell anyone who is searching for the same thing that there is a public and official API to do this: get_fields() and get_field()

Usage:

fields = model._meta.get_fields()
my_field = model._meta.get_field('my_field')

https://docs.djangoproject.com/en/1.8/ref/models/meta/

How can I right-align text in a DataGridView column?

I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

In this case e is from:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

php is null or empty?

No it's not a bug. Have a look at the Loose comparisons with == table (second table), which shows the result of comparing each value in the first column with the values in the other columns:

    TRUE    FALSE   1       0       -1      "1"     "0"     "-1"    NULL    array() "php"   ""

    [...]    

""  FALSE   TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE

There you can see that an empty string "" compared with false, 0, NULL or "" will yield true.

You might want to use is_null [docs] instead, or strict comparison (third table).

Getting visitors country from their IP

Try

  <?php
  //gives you the IP address of the visitors
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      $ip = $_SERVER['HTTP_CLIENT_IP'];}
  else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
      $ip = $_SERVER['REMOTE_ADDR'];
  }

  //return the country code
  $url = "http://api.wipmania.com/$ip";
  $country = file_get_contents($url);
  echo $country;

  ?>

Epoch vs Iteration when training neural networks

Epoch and iteration describe different things.


Epoch

An epoch describes the number of times the algorithm sees the entire data set. So, each time the algorithm has seen all samples in the dataset, an epoch has completed.

Iteration

An iteration describes the number of times a batch of data passed through the algorithm. In the case of neural networks, that means the forward pass and backward pass. So, every time you pass a batch of data through the NN, you completed an iteration.


Example

An example might make it clearer.

Say you have a dataset of 10 examples (or samples). You have a batch size of 2, and you've specified you want the algorithm to run for 3 epochs.

Therefore, in each epoch, you have 5 batches (10/2 = 5). Each batch gets passed through the algorithm, therefore you have 5 iterations per epoch. Since you've specified 3 epochs, you have a total of 15 iterations (5*3 = 15) for training.

Dynamically Changing log4j log level

For log4j 2 API , you can use

Logger logger = LogManager.getRootLogger();
Configurator.setAllLevels(logger.getName(), Level.getLevel(level));

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

How does jQuery work when there are multiple elements with the same ID value?

Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this

$("[id=duplicatedId]")

You will get a collection with all elements with id=duplicatedId

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

jQuery autocomplete with callback ajax json

Perfectly good example in the Autocomplete docs with source code.

jQuery

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#city" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: "http://gd.geobytes.com/AutoCompleteCity",
          dataType: "jsonp",
          data: {
            q: request.term
          },
          success: function( data ) {
            response( data );
          }
        });
      },
      minLength: 3,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });
</script>

HTML

<div class="ui-widget">
  <label for="city">Your city: </label>
  <input id="city">
  Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

Display HTML snippets in HTML

<textarea ><?php echo htmlentities($page_html); ?></textarea>

works fine for me..

"keeping in mind Alexander's suggestion, here is why I think this is a good approach"

if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.

using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.

There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)

What's the difference between primitive and reference types?

These are the primitive types in Java:

  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double

All the other types are reference types: they reference objects.

This is the first part of the Java tutorial about the basics of the language.

c# write text on bitmap

If you want wrap your text, then you should draw your text in a rectangle:

RectangleF rectF1 = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1);

See: https://msdn.microsoft.com/en-us/library/baw6k39s(v=vs.110).aspx

Display PDF file inside my android application

Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.

Array inside a JavaScript Object?

In regards to multiple arrays in an object. For instance, you want to record modules for different courses

var course = {
    InfoTech:["Information Systems","Internet Programming","Software Eng"],
    BusComm:["Commercial Law","Accounting","Financial Mng"],
    Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

tsql returning a table from a function or store procedure

You don't need (shouldn't use) a function as far as I can tell. The stored procedure will return tabular data from any SELECT statements you include that return tabular data.

A stored proc does not use RETURN statements.

 CREATE PROCEDURE name
 AS

 SELECT stuff INTO #temptbl1

 .......


 SELECT columns FROM #temptbln

#define in Java

Java Primitive Specializations Generator supports /* with */, /* define */ and /* if */ ... /* elif */ ... /* endif */ blocks which allow to do some kind of macro generation in Java code, similar to java-comment-preprocessor mentioned in this answer.

JPSG has Maven and Gradle plugins.

Is Python interpreted, or compiled, or both?

The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.

Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).

Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.

How to get the stream key for twitch.tv

This may be an old thread but I came across it and figured that I would give a final answer.

The twitch api is json based and to recieve your stream key you need to authorize your app for use with the api. You do so under the connections tab within your profile on twitch.tv itself.. Down the bottom of said tab there is "register your app" or something similar. Register it and you'll get a client-id header for your get requests.

Now you need to attach your Oauthv2 key to your headers or as a param during the query to the following get request.

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth ' \ -X GET https://api.twitch.tv/kraken/channel

documentataion here

As you can see in the documentation above, if you've done these two things, your stream key will be made available to you.

As I said - Sorry for the bump but some people do find it hard to read the twitch* api.

Hope that helps somebody in the future.

Wait until all jQuery Ajax requests are done?

I found simple way, it using shift()

function waitReq(id)
{
  jQuery.ajax(
  {
    type: 'POST',
    url: ajaxurl,
    data:
    {
      "page": id
    },
    success: function(resp)
    {
      ...........
      // check array length if not "0" continue to use next array value
      if(ids.length)
      {
        waitReq(ids.shift()); // 2
      )
    },
    error: function(resp)
    {
      ....................
      if(ids.length)
      {
        waitReq(ids.shift());
      )
    }
  });
}

var ids = [1, 2, 3, 4, 5];    
// shift() = delete first array value (then print)
waitReq(ids.shift()); // print 1

Python-equivalent of short-form "if" in C++

My cryptic version...

a = ['123', '456'][b == True]

How to build a query string for a URL in C#?

Just for those that need the VB.NET version of the top-answer:

Public Function ToQueryString(nvc As System.Collections.Specialized.NameValueCollection) As String
    Dim array As String() = nvc.AllKeys.SelectMany(Function(key As String) nvc.GetValues(key), Function(key As String, value As String) String.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(key), System.Web.HttpUtility.UrlEncode(value))).ToArray()
    Return "?" + String.Join("&", array)
End Function

And the version without LINQ:

Public Function ToQueryString(nvc As System.Collections.Specialized.NameValueCollection) As String
    Dim lsParams As New List(Of String)()

    For Each strKey As String In nvc.AllKeys
        Dim astrValue As String() = nvc.GetValues(strKey)

        For Each strValue As String In astrValue
            lsParams.Add(String.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(strKey), System.Web.HttpUtility.UrlEncode(strValue)))
        Next ' Next strValue
    Next ' strKey
    Dim astrParams As String() = lsParams.ToArray()
    lsParams.Clear()
    lsParams = Nothing

    Return "?" + String.Join("&", astrParams)
End Function ' ToQueryString

And the C# version without LINQ:

    public static string ToQueryString(System.Collections.Specialized.NameValueCollection nvc)
    {
        List<string> lsParams = new List<string>();

        foreach (string strKey in nvc.AllKeys)
        {
            string[] astrValue = nvc.GetValues(strKey);

            foreach (string strValue in astrValue)
            {
                lsParams.Add(string.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(strKey), System.Web.HttpUtility.UrlEncode(strValue)));
            } // Next strValue

        } // Next strKey

        string[] astrParams =lsParams.ToArray();
        lsParams.Clear();
        lsParams = null;

        return "?" + string.Join("&", astrParams);
    } // End Function ToQueryString

How can I align two divs horizontally?

Wrap them both in a container like so:

_x000D_
_x000D_
.container{ _x000D_
    float:left; _x000D_
    width:100%; _x000D_
}_x000D_
.container div{ _x000D_
    float:left;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <div>_x000D_
        <span>source list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
    <div>_x000D_
        <span>destination list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

Create a CSV File for a user in PHP

Simple method -

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

So each line of the $data array will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.

How do I delete specific characters from a particular String in Java?

To remove the last character do as Mark Byers said

s = s.substring(0, s.length() - 1);

Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.

as in:

s = s.replace(",","");

and

s = s.replace(".","");

When is TCP option SO_LINGER (0) required?

The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.

This isn't a good idea, though - TIME_WAIT exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.

Log4Net configuring log level

Within the definition of the appender, I believe you can do something like this:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
    </filter>
    ...
</appender>

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Rails: select unique values from a column

You can use the following Gem: active_record_distinct_on

Model.distinct_on(:rating)

Yields the following query:

SELECT DISTINCT ON ( "models"."rating" ) "models".* FROM "models"

SHA-256 or MD5 for file integrity

It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.

You are able to checkout the following resources:

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

How prevent CPU usage 100% because of worker process in iis

There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.

  1. High error rates within your ASP.NET web application
  2. Increase in web traffic causing high CPU
  3. Problems with application dependencies
  4. Garbage collection
  5. Requests getting blocked or hung somewhere in the ASP.NET pipeline
  6. Inefficient .NET code that needs to be optimized

How can I use pointers in Java?

As Java has no pointer data types, it is impossible to use pointers in Java. Even the few experts will not be able to use pointers in java.

See also the last point in: The Java Language Environment

How can I fill a column with random numbers in SQL? I get the same value in every row

I tested 2 set based randomization methods against RAND() by generating 100,000,000 rows with each. To level the field the output is a float between 0-1 to mimic RAND(). Most of the code is testing infrastructure so I summarize the algorithms here:

-- Try #1 used
(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
-- Try #2 used
RAND(Checksum(NewId()))
-- and to have a baseline to compare output with I used
RAND() -- this required executing 100000000 separate insert statements

Using CRYPT_GEN_RANDOM was clearly the most random since there is only a .000000001% chance of seeing even 1 duplicate when plucking 10^8 numbers FROM a set of 10^18 numbers. IOW we should not have seen any duplicates and this had none! This set took 44 seconds to generate on my laptop.

Cnt     Pct
-----   ----
 1      100.000000  --No duplicates

SQL Server Execution Times: CPU time = 134795 ms, elapsed time = 39274 ms.

IF OBJECT_ID('tempdb..#T0') IS NOT NULL DROP TABLE #T0;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4  
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8  
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16  
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32  
SELECT TOP 100000000 (CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
  INTO #T0
  FROM L3;

 WITH x AS (
     SELECT Val,COUNT(*) Cnt
      FROM #T0
     GROUP BY Val
)
SELECT x.Cnt,COUNT(*)/(SELECT COUNT(*)/100 FROM #T0) Pct
  FROM X
 GROUP BY x.Cnt;

At almost 15 orders of magnitude less random this method was not quite twice as fast, taking only 23 seconds to generate 100M numbers.

Cnt  Pct
---- ----
1    95.450254    -- only 95% unique is absolutely horrible
2    02.222167    -- If this line were the only problem I'd say DON'T USE THIS!
3    00.034582
4    00.000409    -- 409 numbers appeared 4 times
5    00.000006    -- 6 numbers actually appeared 5 times 

SQL Server Execution Times: CPU time = 77156 ms, elapsed time = 24613 ms.

IF OBJECT_ID('tempdb..#T1') IS NOT NULL DROP TABLE #T1;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4  
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8  
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16  
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32  
SELECT TOP 100000000 RAND(Checksum(NewId())) AS Val
  INTO #T1
  FROM L3;

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T1
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T1) Pct
  FROM X
 GROUP BY x.Cnt;

RAND() alone is useless for set-based generation so generating the baseline for comparing randomness took over 6 hours and had to be restarted several times to finally get the right number of output rows. It also seems that the randomness leaves a lot to be desired although it's better than using checksum(newid()) to reseed each row.

Cnt  Pct
---- ----
1    99.768020
2    00.115840
3    00.000100  -- at least there were comparitively few values returned 3 times

Because of the restarts, execution time could not be captured.

IF OBJECT_ID('tempdb..#T2') IS NOT NULL DROP TABLE #T2;
GO
CREATE TABLE #T2 (Val FLOAT);
GO
SET NOCOUNT ON;
GO
INSERT INTO #T2(Val) VALUES(RAND());
GO 100000000

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T2
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T2) Pct
  FROM X
 GROUP BY x.Cnt;

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

TypeError: $ is not a function when calling jQuery function

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

How can I stage and commit all files, including newly added files, using a single command?

You can write a small script (look at Ian Clelland's answer) called git-commitall which uses several git commands to perform what you want to do.
Place this script in your anywhere in your $PATH. You can call it by git commitall ... very handy!

Found here (question and all answers unfortunately deleted, only visible with high reputation)

How to remove CocoaPods from a project?

pod deintegrate and pod clean are two designated commands to remove CocoaPod from your project/repo.

Here is the complete set of commands:

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod cache clean --all
$ rm Podfile

The original solution was found here: https://medium.com/@icanhazedit/remove-uninstall-deintegrate-cocoapods-from-your-xcode-ios-project-c4621cee5e42#.wd00fj2e5

CocoaPod documentation on pod deintegrate: https://guides.cocoapods.org/terminal/commands.html#pod_deintegrate