Programs & Examples On #Rubber band

Debugging in Maven?

I use the MAVEN_OPTS option, and find it useful to set suspend to "suspend=y" as my exec:java programs tend to be small generators which are finished before I have manage to attach a debugger.... :) With suspend on it will wait for a debugger to attach before proceding.

Timing a command's execution in PowerShell

Here's a function I wrote which works similarly to the Unix time command:

function time {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$command,
        [switch]$quiet = $false
    )
    $start = Get-Date
    try {
        if ( -not $quiet ) {
            iex $command | Write-Host
        } else {
            iex $command > $null
        }
    } finally {
        $(Get-Date) - $start
    }
}

Source: https://gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874

Get error message if ModelState.IsValid fails?

It is sample extension

public class GetModelErrors
{
    //Usage return Json to View :
    //return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
    public class KeyMessages
    {
        public string Key { get; set; }
        public string Message { get; set; }
    }
    private readonly ModelStateDictionary _entry;
    public GetModelErrors(ModelStateDictionary entry)
    {
        _entry = entry;
    }

    public int Count()
    {
        return _entry.ErrorCount;
    }
    public string Exceptions(string sp = "\n")
    {
        return string.Join(sp, _entry.Values
            .SelectMany(v => v.Errors)
            .Select(e => e.Exception));
    }
    public string Messages(string sp = "\n")
    {
        string msg = string.Empty;
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
            }
        }
        return msg;
    }

    public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
    {
        List<KeyMessages> list = new List<KeyMessages>();
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                list.Add(new KeyMessages
                {
                    Key = item.Key,
                    Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
                });
            }
        }
        return list;
    }
}

How to generate a number of most distinctive colors in R?

In my understanding searching distinctive colors is related to search efficiently from an unit cube, where 3 dimensions of the cube are three vectors along red, green and blue axes. This can be simplified to search in a cylinder (HSV analogy), where you fix Saturation (S) and Value (V) and find random Hue values. It works in many cases, and see this here :

https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

In R,

get_distinct_hues <- function(ncolor,s=0.5,v=0.95,seed=40) {
  golden_ratio_conjugate <- 0.618033988749895
  set.seed(seed)
  h <- runif(1)
  H <- vector("numeric",ncolor)
  for(i in seq_len(ncolor)) {
    h <- (h + golden_ratio_conjugate) %% 1
    H[i] <- h
  }
  hsv(H,s=s,v=v)
}

An alternative way, is to use R package "uniformly" https://cran.r-project.org/web/packages/uniformly/index.html

and this simple function can generate distinctive colors:

get_random_distinct_colors <- function(ncolor,seed = 100) {
  require(uniformly)
  set.seed(seed)
  rgb_mat <- runif_in_cube(n=ncolor,d=3,O=rep(0.5,3),r=0.5)
  rgb(r=rgb_mat[,1],g=rgb_mat[,2],b=rgb_mat[,3])
}

One can think of a little bit more involved function by grid-search:

get_random_grid_colors <- function(ncolor,seed = 100) {
  require(uniformly)
  set.seed(seed)
  ngrid <- ceiling(ncolor^(1/3))
  x <- seq(0,1,length=ngrid+1)[1:ngrid]
  dx <- (x[2] - x[1])/2
  x <- x + dx
  origins <- expand.grid(x,x,x)
  nbox <- nrow(origins) 
  RGB <- vector("numeric",nbox)
  for(i in seq_len(nbox)) {
    rgb <- runif_in_cube(n=1,d=3,O=as.numeric(origins[i,]),r=dx)
    RGB[i] <- rgb(rgb[1,1],rgb[1,2],rgb[1,3])
  }
  index <- sample(seq(1,nbox),ncolor)
  RGB[index]
} 

check this functions by:

ncolor <- 20
barplot(rep(1,ncolor),col=get_distinct_hues(ncolor))          # approach 1
barplot(rep(1,ncolor),col=get_random_distinct_colors(ncolor)) # approach 2
barplot(rep(1,ncolor),col=get_random_grid_colors(ncolor))     # approach 3

However, note that, defining a distinct palette with human perceptible colors is not simple. Which of the above approach generates diverse color set is yet to be tested.

Forward slash in Java Regex

Double escaping is required when presented as a string.

Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.

Show datalist labels but submit the actual value

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

jquery validate check at least one checkbox

Mmm first your id attributes must be unique, your code is likely to be

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

For your problem :

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

Using unset vs. setting a variable to empty

So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).

I made my own test..

foo=(5 6 8)
echo ${#foo[*]}
unset foo
echo ${#foo[*]}

Which results in..

3
0

So just to clarify that unset'ting the entire array will in fact remove it entirely.

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

How to get nth jQuery element

Why not browse the (short) selectors page first?

Here it is: the :eq() operator. It is used just like get(), but it returns the jQuery object.

Or you can use .eq() function too.

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Learning to write a compiler

I liked the Crenshaw tutorial too, because it makes it absolutely clear that a compiler is just another program that reads some input and writes some out put.

Read it.

Work it if you want, but then look at another reference on how bigger and more complete compilers are really written.

And read On Trusting Trust, to get a clue about the unobvious things that can be done in this domain.

Phone mask with jQuery and Masked Input Plugin

I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number

Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.

$(document).ready(function () {
    $('#yourphone').usPhoneFormat({
        format: '(xxx) xxx-xxxx',
    });   
});

Working JSFiddle Link https://jsfiddle.net/1kbat1nb/

NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number

GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

Adding images to an HTML document with javascript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

_x000D_
_x000D_
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
_x000D_
_x000D_

... you'd get this:

enter image description here

ORA-12560: TNS:protocol adaptor error

I try 2 option:

  1. You change service OracleService in Service Tab -> Running
  2. Login with cmd command: sqlplus user_name/pass_word@orcl12C Note: orcle12c -> name of OracleService name run in you laptop

How to make bootstrap 3 fluid layout without horizontal scrollbar

It's already fluid by default. If you want to be fluid for less width instead of col-md-6 use col-sm-6 or col-xs-6.

What's the best way to do a backwards loop in C/C#/C++?

For C++:

As mentioned by others, when possible (i.e. when you only want each element at a time) it is strongly preferable to use iterators to both be explicit and avoid common pitfalls. Modern C++ has a more concise syntax for that with auto:

std::vector<int> vec = {1,2,3,4};
for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
    std::cout<<*it<<" ";
}

prints 4 3 2 1 .

You can also modify the value during the loop:

std::vector<int> vec = {1,2,3,4};
for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
    *it = *it + 10;
    std::cout<<*it<<" ";
}

leading to 14 13 12 11 being printed and {11, 12, 13, 14} being in the std::vector afterwards.

If you don't plan on modifying the value during the loop, you should make sure that you get an error when you try to do that by accident, similarly to how one might write for(const auto& element : vec). This is possible like this:

std::vector<int> vec = {1,2,3,4};
for (auto it = vec.crbegin(); it != vec.crend(); ++it) { // used crbegin()/crend() here...
    *it = *it + 10; // ... so that this is a compile-time error
    std::cout<<*it<<" ";
}

The compiler error in this case for me is:

/tmp/main.cpp:20:9: error: assignment of read-only location ‘it.std::reverse_iterator<__gnu_cxx::__normal_iterator<const int*, std::vector<int> > >::operator*()’
   20 |     *it = *it + 10;
      |     ~~~~^~~~~~~~~~

Also note that you should make sure not to use different iterator types together:

std::vector<int> vec = {1,2,3,4};
for (auto it = vec.rbegin(); it != vec.end(); ++it) { // mixed rbegin() and end()
    std::cout<<*it<<" ";
}

leads to the verbose error:

/tmp/main.cpp: In function ‘int main()’:
/tmp/main.cpp:19:33: error: no match for ‘operator!=’ (operand types are ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >’ and ‘std::vector<int>::iterator’ {aka ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’})
   19 | for (auto it = vec.rbegin(); it != vec.end(); ++it) {
      |                              ~~ ^~ ~~~~~~~~~
      |                              |            |
      |                              |            std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}
      |                              std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >

If you have C-style arrays on the stack, you can do things like this:

int vec[] = {1,2,3,4};
for (auto it = std::crbegin(vec); it != std::crend(vec); ++it) {
    std::cout<<*it<<" ";
}

If you really need the index, consider the following options:

  • check the range, then work with signed values, e.g.:
void loop_reverse(std::vector<int>& vec) {
    if (vec.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {
        throw std::invalid_argument("Input too large");
    }
    const int sz = static_cast<int>(vec.size());
    for(int i=sz-1; i >= 0; --i) {
        // do something with i
    }
}
  • Work with unsigned values, be careful, and add comments, e.g.:
void loop_reverse2(std::vector<int>& vec) {
    for(size_t i=vec.size(); i-- > 0;) { // reverse indices from N-1 to 0
        // do something with i
    }
}
  • calculate the actual index separately, e.g.:
void loop_reverse3(std::vector<int>& vec) {
    for(size_t offset=0; offset < vec.size(); ++offset) {
        const size_t i = vec.size()-1-offset; // reverse indices from N-1 to 0
        // do something with i
    }
}

How to scroll to top of long ScrollView layout?

I faced Same Problem When i am using Scrollview inside View Flipper or Dialog that case scrollViewObject.fullScroll(ScrollView.FOCUS_UP) returns false so that case scrollViewObject.smoothScrollTo(0, 0) is Worked for me

Scroll Focus Top

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

php $_POST array empty upon form submission

Don't have an elegant solution at this point but wanted to share my findings for the future reference of others who encounter this problem. The source of the problem was 2 overriden php values in an .htaccess file. I had simply added these 2 values to increase the filesize limit for file uploads from the default 8MB to something larger -- I observed that simply having these 2 values in the htaccess file at all, whether larger or smaller than the default, caused the issue.

php_value post_max_size xxMB
php_value upload_max_filesize xxMB

I added additional variables to hopefully raise the limits for all the suhosin.post.xxx/suhosin.upload.xxx vars but these didn't have any effect with this problem unfortunately.

In summary, I can't really explain the "why" here, but have identified the root cause. My feeling is that this is ultimately a suhosin/htaccess issue, but unfortunately one that I wasn't able to resolve other than to remove the 2 php overridden values above.

Hope this helps someone in the future as I killed a handful of hours figuring this out. Thanks to all who took the time to help me with this (MrMage, Andrew)

Setting up enviromental variables in Windows 10 to use java and javac

Just set the path variable to JDK bin in environment variables.

Variable Name : PATH 
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin

But the best practice is to set JAVA_HOME and PATH as follow.

Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31

Variable Name : PATH 
Variable Value : %JAVA_HOME%\bin

Programmatically stop execution of python script?

The exit() and quit() built in functions do just what you want. No import of sys needed.

Alternatively, you can raise SystemExit, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

What is the difference between baud rate and bit rate?

The bit rate is a measure of the number of bits that are transmitted per unit of time.

The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.

Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.

The binary equivalent is 01010010.

So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).

missing FROM-clause entry for table

Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid

SQL Bulk Insert with FIRSTROW parameter skips the following line

I found it easiest to just read the entire line into one column then parse out the data using XML.

IF (OBJECT_ID('tempdb..#data') IS NOT NULL) DROP TABLE #data
CREATE TABLE #data (data VARCHAR(MAX))

BULK INSERT #data FROM 'E:\filefromabove.txt' WITH (FIRSTROW = 2, ROWTERMINATOR = '\n')

IF (OBJECT_ID('tempdb..#dataXml') IS NOT NULL) DROP TABLE #dataXml
CREATE TABLE #dataXml (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, data XML)

INSERT #dataXml (data)
SELECT CAST('<r><d>' + REPLACE(data, '|', '</d><d>') + '</d></r>' AS XML)
FROM #data

SELECT  d.data.value('(/r//d)[1]', 'varchar(max)') AS col1,
        d.data.value('(/r//d)[2]', 'varchar(max)') AS col2,
        d.data.value('(/r//d)[3]', 'varchar(max)') AS col3
FROM #dataXml d

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

How to generate random number in Bash?

Wanted to use /dev/urandom without dd and od

function roll() { local modulus=${1:-6}; echo $(( 1 + 0x$(env LC_CTYPE=C tr -dc '0-9a-fA-F' < /dev/urandom | head -c5 ) % $modulus )); }

Testing

$ roll
5
$ roll 12
12

Just how random is it?

$ (echo "count roll percentage"; i=0; while [ $i -lt 10000 ]; do roll; i=$((i+1)); done | sort | uniq -c | awk '{print $0,($1/10000*100)"%"}') | column -t
count  roll  percentage
1625   1     16.25%
1665   2     16.65%
1646   3     16.46%
1720   4     17.2%
1694   5     16.94%
1650   6     16.5%

Checking the form field values before submitting that page

While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()" instead.

You may want to considering replacing this method with onsubmit="return checkform()" in the form tag instead, though both will work for clicking the button.

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.

Now I have an extra step before attempting the resize operation, which is to do the assertion myself:

def getSizedFrame(width, height):
"""Function to return an image with the size I want"""    
    s, img = self.cam.read()

    # Only process valid image frames
    if s:
            img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
    return s, img

Now I don't see the error.

Does JSON syntax allow duplicate keys in an object?

In C# if you deserialise to a Dictionary<string, string> it takes the last key value pair:

string json = @"{""a"": ""x"", ""a"": ""y""}";
var d = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
// { "a" : "y" }

if you try to deserialise to

class Foo
{
    [JsonProperty("a")]
    public string Bar { get; set; }

    [JsonProperty("a")]
    public string Baz { get; set; }
}

var f = JsonConvert.DeserializeObject<Foo>(json);

you get a Newtonsoft.Json.JsonSerializationException exception.

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

How do I find the MySQL my.cnf location

Found mine using

mysqld --help --verbose | grep my.cnf

How can I create tests in Android Studio?

I think this post by Rex St John is very useful for unit testing with android studio.


(source: rexstjohn.com)

Android: Proper Way to use onBackPressed() with Toast

I use this much simpler approach...

public class XYZ extends Activity {
    private long backPressedTime = 0;    // used by onBackPressed()


    @Override
    public void onBackPressed() {        // to prevent irritating accidental logouts
        long t = System.currentTimeMillis();
        if (t - backPressedTime > 2000) {    // 2 secs
            backPressedTime = t;
            Toast.makeText(this, "Press back again to logout",
                                Toast.LENGTH_SHORT).show();
        } else {    // this guy is serious
            // clean up
            super.onBackPressed();       // bye
        }
    }
}

Xcode 6 iPhone Simulator Application Support location

The simulator puts the file in ~/Library/Developer/CoreSimulator/Devices/... but the path after /Devices is different for everyone.

Use this handy method. It returns the path of the temporary directory for the current user and takes no argument.

NSString * NSTemporaryDirectory ( void );

So in my ViewController class I usually put this line in my viewDidLoad just for a reference when I need to grab my CoreData stored file. Hope this helps.

  NSLog(@"FILE PATH :%@", NSTemporaryDirectory());

(Note: to go to the path, from the finder menu click on Go and type ~/Library to open hidden directory then in the Finder Window you can click on the path shown on your console.)

How to search for a string in cell array in MATLAB?

>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc

Elapsed time is 0.001976 seconds.

>> tic; find(strcmp('KU', strs)); toc

Elapsed time is 0.000014 seconds.

SO, clearly strcmp('KU', strs) takes much lesser time than ismember(strs,'KU')

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

What is the difference between parseInt() and Number()?

One minor difference is what they convert of undefined or null,

Number() Or Number(null) // returns 0

while

parseInt() Or parseInt(null) // returns NaN

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
    title: locations[i].title,
    icon: icon,
    map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
    for(i=0; i<gmarkers.length; i++){
        gmarkers[i].setMap(null);
    }
}

working example (toggles the markers)

code snippet:

_x000D_
_x000D_
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
  stylers: [{_x000D_
    hue: "black"_x000D_
  }, {_x000D_
    saturation: -90_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "geometry",_x000D_
  stylers: [{_x000D_
    lightness: 100_x000D_
  }, {_x000D_
    visibility: "simplified"_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "labels",_x000D_
  stylers: [{_x000D_
    visibility: "on"_x000D_
  }]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
  name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
  center: RoseHulman,_x000D_
  zoom: 15,_x000D_
  mapTypeControl: true,_x000D_
  zoomControl: true,_x000D_
  zoomControlOptions: {_x000D_
    style: google.maps.ZoomControlStyle.SMALL_x000D_
  },_x000D_
  mapTypeControlOptions: {_x000D_
    mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
  },_x000D_
  scrollwheel: false,_x000D_
  streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
  maxWidth: 300,_x000D_
  infoBoxClearance: new google.maps.Size(1, 1),_x000D_
  disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
  "id": "1",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Alpha Tau Omega Fraternity",_x000D_
  "description": "<p>Alpha Tau Omega house</p>",_x000D_
  "longitude": "-87.321133",_x000D_
  "latitude": "39.484092"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment Commons",_x000D_
  "description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
  "longitude": "-87.329282",_x000D_
  "latitude": "39.483599"_x000D_
}, {_x000D_
  "id": "3",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment East",_x000D_
  "description": "<p>Apartment East</p>",_x000D_
  "longitude": "-87.328809",_x000D_
  "latitude": "39.483748"_x000D_
}, {_x000D_
  "id": "4",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment West",_x000D_
  "description": "<p>Apartment West</p>",_x000D_
  "longitude": "-87.329732",_x000D_
  "latitude": "39.483429"_x000D_
}, {_x000D_
  "id": "5",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
  "description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.482382"_x000D_
}, {_x000D_
  "id": "6",_x000D_
  "category": "6",_x000D_
  "campus_location": "D3",_x000D_
  "title": "Blumberg Hall",_x000D_
  "description": "<p>Blumberg Hall</p>",_x000D_
  "longitude": "-87.328321",_x000D_
  "latitude": "39.483388"_x000D_
}, {_x000D_
  "id": "7",_x000D_
  "category": "1",_x000D_
  "campus_location": "E1",_x000D_
  "title": "The Branam Innovation Center",_x000D_
  "description": "<p>The Branam Innovation Center</p>",_x000D_
  "longitude": "-87.322614",_x000D_
  "latitude": "39.48494"_x000D_
}, {_x000D_
  "id": "8",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Chi Omega Sorority",_x000D_
  "description": "<p>Chi Omega house</p>",_x000D_
  "longitude": "-87.319905",_x000D_
  "latitude": "39.482071"_x000D_
}, {_x000D_
  "id": "9",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Cook Stadium/Phil Brown Field",_x000D_
  "description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
  "longitude": "-87.325258",_x000D_
  "latitude": "39.485007"_x000D_
}, {_x000D_
  "id": "10",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Crapo Hall",_x000D_
  "description": "<p>Crapo Hall</p>",_x000D_
  "longitude": "-87.324368",_x000D_
  "latitude": "39.483709"_x000D_
}, {_x000D_
  "id": "11",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Delta Delta Delta Sorority",_x000D_
  "description": "<p>Delta Delta Delta</p>",_x000D_
  "longitude": "-87.317477",_x000D_
  "latitude": "39.482951"_x000D_
}, {_x000D_
  "id": "12",_x000D_
  "category": "6",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Deming Hall",_x000D_
  "description": "<p>Deming Hall</p>",_x000D_
  "longitude": "-87.325822",_x000D_
  "latitude": "39.483421"_x000D_
}, {_x000D_
  "id": "13",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Facilities Operations",_x000D_
  "description": "<p>Facilities Operations</p>",_x000D_
  "longitude": "-87.321782",_x000D_
  "latitude": "39.484916"_x000D_
}, {_x000D_
  "id": "14",_x000D_
  "category": "2",_x000D_
  "campus_location": "E3",_x000D_
  "title": "Flame of the Millennium",_x000D_
  "description": "<p>Flame of Millennium sculpture</p>",_x000D_
  "longitude": "-87.323306",_x000D_
  "latitude": "39.481978"_x000D_
}, {_x000D_
  "id": "15",_x000D_
  "category": "5",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Hadley Hall",_x000D_
  "description": "<p>Hadley Hall</p>",_x000D_
  "longitude": "-87.324046",_x000D_
  "latitude": "39.482887"_x000D_
}, {_x000D_
  "id": "16",_x000D_
  "category": "2",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Hatfield Hall",_x000D_
  "description": "<p>Hatfield Hall</p>",_x000D_
  "longitude": "-87.322340",_x000D_
  "latitude": "39.482146"_x000D_
}, {_x000D_
  "id": "17",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Hulman Memorial Union",_x000D_
  "description": "<p>Hulman Memorial Union</p>",_x000D_
  "longitude": "-87.32698",_x000D_
  "latitude": "39.483574"_x000D_
}, {_x000D_
  "id": "18",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "John T. Myers Center for Technological Research with Industry",_x000D_
  "description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
  "longitude": "-87.322984",_x000D_
  "latitude": "39.484063"_x000D_
}, {_x000D_
  "id": "19",_x000D_
  "category": "6",_x000D_
  "campus_location": "A2",_x000D_
  "title": "Lakeside Hall",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330612",_x000D_
  "latitude": "39.482804"_x000D_
}, {_x000D_
  "id": "20",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Lambda Chi Alpha Fraternity",_x000D_
  "description": "<p>Lambda Chi Alpha</p>",_x000D_
  "longitude": "-87.320999",_x000D_
  "latitude": "39.48305"_x000D_
}, {_x000D_
  "id": "21",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Logan Library",_x000D_
  "description": "<p>Logan Library</p>",_x000D_
  "longitude": "-87.324851",_x000D_
  "latitude": "39.483408"_x000D_
}, {_x000D_
  "id": "22",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Mees Hall",_x000D_
  "description": "<p>Mees Hall</p>",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.483533"_x000D_
}, {_x000D_
  "id": "23",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Moench Hall",_x000D_
  "description": "<p>Moench Hall</p>",_x000D_
  "longitude": "-87.323695",_x000D_
  "latitude": "39.483471"_x000D_
}, {_x000D_
  "id": "24",_x000D_
  "category": "1",_x000D_
  "campus_location": "G4",_x000D_
  "title": "Oakley Observatory",_x000D_
  "description": "<p>Oakley Observatory</p>",_x000D_
  "longitude": "-87.31616",_x000D_
  "latitude": "39.483789"_x000D_
}, {_x000D_
  "id": "25",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Olin Hall and Olin Advanced Learning Center",_x000D_
  "description": "<p>Olin Hall</p>",_x000D_
  "longitude": "-87.324550",_x000D_
  "latitude": "39.482796"_x000D_
}, {_x000D_
  "id": "26",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Percopo Hall",_x000D_
  "description": "<p>Percopo Hall</p>",_x000D_
  "longitude": "-87.328182",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "27",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Public Safety Office",_x000D_
  "description": "<p>The Office of Public Safety</p>",_x000D_
  "longitude": "-87.320377",_x000D_
  "latitude": "39.48191"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Rotz Mechanical Engineering Lab",_x000D_
  "description": "<p>Rotz Lab</p>",_x000D_
  "longitude": "-87.323247",_x000D_
  "latitude": "39.483711"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Scharpenberg Hall",_x000D_
  "description": "<p>Scharpenberg Hall</p>",_x000D_
  "longitude": "-87.328139",_x000D_
  "latitude": "39.483582"_x000D_
}, {_x000D_
  "id": "29",_x000D_
  "category": "6",_x000D_
  "campus_location": "G2",_x000D_
  "title": "Sigma Nu Fraternity",_x000D_
  "description": "<p>The Sigma Nu house</p>",_x000D_
  "longitude": "-87.31999",_x000D_
  "latitude": "39.48374"_x000D_
}, {_x000D_
  "id": "30",_x000D_
  "category": "6",_x000D_
  "campus_location": "E4",_x000D_
  "title": "South Campus / Rose-Hulman Ventures",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330623",_x000D_
  "latitude": "39.417646"_x000D_
}, {_x000D_
  "id": "31",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Speed Hall",_x000D_
  "description": "<p>Speed Hall</p>",_x000D_
  "longitude": "-87.326632",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "32",_x000D_
  "category": "3",_x000D_
  "campus_location": "C1",_x000D_
  "title": "Sports and Recreation Center",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.3272",_x000D_
  "latitude": "39.484874"_x000D_
}, {_x000D_
  "id": "33",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Triangle Fraternity",_x000D_
  "description": "<p>Triangle fraternity</p>",_x000D_
  "longitude": "-87.32113",_x000D_
  "latitude": "39.483659"_x000D_
}, {_x000D_
  "id": "34",_x000D_
  "category": "6",_x000D_
  "campus_location": "B3",_x000D_
  "title": "White Chapel",_x000D_
  "description": "<p>The White Chapel</p>",_x000D_
  "longitude": "-87.329367",_x000D_
  "latitude": "39.482481"_x000D_
}, {_x000D_
  "id": "35",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Women's Fraternity Housing",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320753",_x000D_
  "latitude": "39.482401"_x000D_
}, {_x000D_
  "id": "36",_x000D_
  "category": "3",_x000D_
  "campus_location": "E1",_x000D_
  "title": "Intramural Fields",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.321267",_x000D_
  "latitude": "39.485934"_x000D_
}, {_x000D_
  "id": "37",_x000D_
  "category": "3",_x000D_
  "campus_location": "A3",_x000D_
  "title": "James Rendel Soccer Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.332135",_x000D_
  "latitude": "39.480933"_x000D_
}, {_x000D_
  "id": "38",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Art Nehf Field",_x000D_
  "description": "<p>Art Nehf Field</p>",_x000D_
  "longitude": "-87.330923",_x000D_
  "latitude": "39.48022"_x000D_
}, {_x000D_
  "id": "39",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Women's Softball Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.329904",_x000D_
  "latitude": "39.480278"_x000D_
}, {_x000D_
  "id": "40",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Joy Hulbert Tennis Courts",_x000D_
  "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
  "longitude": "-87.323767",_x000D_
  "latitude": "39.485595"_x000D_
}, {_x000D_
  "id": "41",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Speed Lake",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328134",_x000D_
  "latitude": "39.482779"_x000D_
}, {_x000D_
  "id": "42",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Recycling Center",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320098",_x000D_
  "latitude": "39.484593"_x000D_
}, {_x000D_
  "id": "43",_x000D_
  "category": "1",_x000D_
  "campus_location": "F3",_x000D_
  "title": "Army ROTC",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321342",_x000D_
  "latitude": "39.481992"_x000D_
}, {_x000D_
  "id": "44",_x000D_
  "category": "2",_x000D_
  "campus_location": "  ",_x000D_
  "title": "Self Made Man",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326272",_x000D_
  "latitude": "39.484481"_x000D_
}, {_x000D_
  "id": "P1",_x000D_
  "category": "4",_x000D_
  "title": "Percopo Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328756",_x000D_
  "latitude": "39.481587"_x000D_
}, {_x000D_
  "id": "P2",_x000D_
  "category": "4",_x000D_
  "title": "Speed Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.327361",_x000D_
  "latitude": "39.481694"_x000D_
}, {_x000D_
  "id": "P3",_x000D_
  "category": "4",_x000D_
  "title": "Main Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326245",_x000D_
  "latitude": "39.481446"_x000D_
}, {_x000D_
  "id": "P4",_x000D_
  "category": "4",_x000D_
  "title": "Lakeside Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.330848",_x000D_
  "latitude": "39.483284"_x000D_
}, {_x000D_
  "id": "P5",_x000D_
  "category": "4",_x000D_
  "title": "Hatfield Hall Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321417",_x000D_
  "latitude": "39.482398"_x000D_
}, {_x000D_
  "id": "P6",_x000D_
  "category": "4",_x000D_
  "title": "Women's Fraternity Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320977",_x000D_
  "latitude": "39.482315"_x000D_
}, {_x000D_
  "id": "P7",_x000D_
  "category": "4",_x000D_
  "title": "Myers and Facilities Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.322243",_x000D_
  "latitude": "39.48417"_x000D_
}, {_x000D_
  "id": "P8",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323241",_x000D_
  "latitude": "39.484758"_x000D_
}, {_x000D_
  "id": "P9",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323617",_x000D_
  "latitude": "39.484311"_x000D_
}, {_x000D_
  "id": "P10",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.484584"_x000D_
}, {_x000D_
  "id": "P11",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.484145"_x000D_
}, {_x000D_
  "id": "P12",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.329035",_x000D_
  "latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
  var marker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
    title: locations[i].title,_x000D_
    map: map_x000D_
  });_x000D_
  gmarkers.push(marker);_x000D_
  google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
    return function() {_x000D_
      if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
        infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
          '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
          '<hr class="grey" />' +_x000D_
          hasImage(locations[i]) +_x000D_
          locations[i].description) + '</div>';_x000D_
        infowindow.open(map, marker);_x000D_
      }_x000D_
    }_x000D_
  })(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
  for (i = 0; i < gmarkers.length; i++) {_x000D_
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
    else gmarkers[i].setMap(map);_x000D_
  }_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
  return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
_x000D_
_x000D_

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

How to concatenate string and int in C?

Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];

   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

Converting EditText to int? (Android)

Try this,

EditText x = (EditText) findViewById(R.id.editText1);
int n = Integer.parseInt(x.getText().toString());

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END

Fastest check if row exists in PostgreSQL

as @MikeM pointed out.

select exists(select 1 from contact where id=12)

with index on contact, it can usually reduce time cost to 1 ms.

CREATE INDEX index_contact on contact(id);

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

How to properly upgrade node using nvm

Node.JS to install a new version.

Step 1 : NVM Install

npm i -g nvm

Step 2 : NODE Newest version install

nvm install *.*.*(NodeVersion)

Step 3 : Selected Node Version

nvm use *.*.*(NodeVersion)

Finish

Can you issue pull requests from the command line on GitHub?

I personally like to view the diff in GitHub prior to opening the PR. Additionally, I prefer writing the PR description on GitHub.

For those reasons, I made an alias (or technically a function without arguments), that opens the diff in GitHub between your current branch and master. If you add this to your .zshrc or .bashrc, you will be able to simply type open-pr and see your changes in GitHub. FYI, you will need to have your changes pushed.

function open-pr() {
  # Get the root of the github project, based on where you are configured to push to.  Ex: https://github.com/tensorflow/tensorflow
  base_uri=$(git remote -v | grep push | tr '\t' ' ' | cut -d ' ' -f 2 | rev | cut -d '.' -f 2- | rev)

  # Get your current branch name
  branch=$(git branch --show-current)

  # Create PR url and open in the default web browser
  url="${base_uri}/compare/${branch}/?expand=1"
  open $url
}

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

How to get a variable name as a string in PHP?

I think you want to know variable name with it's value. You can use an associative array to achieve this.

use variable names for array keys:

$vars = array('FooBar' => 'a string');

When you want to get variable names, use array_keys($vars), it will return an array of those variable names that used in your $vars array as it's keys.

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

How do I change TextView Value inside Java Code?

I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

<TextView  
android:id="@+id/rate"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/rate"
/>

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

<string name="rate">Rate</string>

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:


final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");

How do I compare two hashes?

If you need a quick and dirty diff between hashes which correctly supports nil in values you can use something like

def diff(one, other)
  (one.keys + other.keys).uniq.inject({}) do |memo, key|
    unless one.key?(key) && other.key?(key) && one[key] == other[key]
      memo[key] = [one.key?(key) ? one[key] : :_no_key, other.key?(key) ? other[key] : :_no_key]
    end
    memo
  end
end

How do I use a custom deleter with a std::unique_ptr member?

You can simply use std::bind with a your destroy function.

std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
    std::placeholders::_1));

But of course you can also use a lambda.

std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

How to get text and a variable in a messagebox

I wanto to display the count of rows in the excel sheet after the filter option has been applied.

So I declared the count of last rows as a variable that can be added to the Msgbox

Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row

MsgBox ("Number of test results between the selected dates " + lngStart + " 
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue 
Analysis")


End Sub

Android BroadcastReceiver within Activity

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}

How can I disable an <option> in a <select> based on its value in JavaScript?

Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");

? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

Simple jQuery, PHP and JSONP example?

Use this ..

    $str = rawurldecode($_SERVER['REQUEST_URI']);
    $arr = explode("{",$str);
    $arr1 = explode("}", $arr[1]);
    $jsS = '{'.$arr1[0].'}';
    $data = json_decode($jsS,true);

Now ..

use $data['elemname'] to access the values.

send jsonp request with JSON Object.

Request format :

$.ajax({
    method : 'POST',
    url : 'xxx.com',
    data : JSONDataObj, //Use JSON.stringfy before sending data
    dataType: 'jsonp',
    contentType: 'application/json; charset=utf-8',
    success : function(response){
      console.log(response);
    }
}) 

Google maps API V3 - multiple markers on exact same spot

Adding to above answers but offering an alternative quick solution in php and wordpress. For this example I am storing the location field via ACF and looping through the posts to grab that data.

I found that storing the lat / lng in an array and check the value of that array to see if the loop matches, we can then update the value within that array with the amount we want to shift our pips by.

//This is the value to shift the pips by. I found this worked best with markerClusterer
$add_to_latlng = 0.00003;

while ($query->have_posts()) {
    $query->the_post();
    $meta = get_post_meta(get_the_ID(), "postcode", true); //uses an acf field to store location
    $lat = $meta["lat"];
    $lng = $meta["lng"];

    if(in_array($meta["lat"],$lat_checker)){ //check if this meta matches
        
        //if matches then update the array to a new value (current value + shift value)
        // This is using the lng value for a horizontal line of pips, use lat for vertical, or both for a diagonal
        if(isset($latlng_storer[$meta["lng"]])){
            $latlng_storer[$meta["lng"]] = $latlng_storer[$meta["lng"]] + $add_to_latlng;
            $lng = $latlng_storer[$meta["lng"]];
        } else {
            $latlng_storer[$meta["lng"]] = $meta["lng"];
            $lng = $latlng_storer[$meta["lng"]];
        }

    } else {
        $lat_checker[] = $meta["lat"]; //just for simple checking of data
        $latlng_storer[$meta["lat"]] = floatval($meta["lat"]);
        $latlng_storer[$meta["lng"]] =  floatval($meta["lng"]);
    }

    $entry[] = [
        "lat" => $lat,
        "lng" => $lng,
    //...Add all the other post data here and use this array for the pips
    ];
} // end query

Once I've grabbed these locations I json encode the $entry variable and use that within my JS.

let locations = <?=json_encode($entry)?>;

I know this is a rather specific situation but I hope this helps someone along the line!

Effective swapping of elements of an array in Java

Incredibly late to the party (my apologies) but a more generic solution than those provided here can be implemented (will work with primitives and non-primitives alike):

public static void swap(final Object array, final int i, final int j) {
    final Object atI = Array.get(array, i);
    Array.set(array, i, Array.get(array, j));
    Array.set(array, j, atI);
}

You lose compile-time safety, but it should do the trick.

Note I: You'll get a NullPointerException if the given array is null, an IllegalArgumentException if the given array is not an array, and an ArrayIndexOutOfBoundsException if either of the indices aren't valid for the given array.

Note II: Having separate methods for this for every array type (Object[] and all primitive types) would be more performant (using the other approaches given here) since this requires some boxing/unboxing. But it'd also be a whole lot more code to write/maintain.

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

How to handle login pop up window using Selenium WebDriver?

This should works with windows server 2012 and IE.

var alert = driver.SwitchTo().Alert();

alert.SetAuthenticationCredentials("username", "password");

alert.Accept();

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

Changing the resolution of a VNC session in linux

Found out that the vnc4server (4.1.1) shipped with Ubuntu (10.04) is patched to also support changing the resolution on the fly via xrandr. Unfortunately the feature was hard to find because it is undocumented. So here it is...

Start the server with multiple 'geometry' instances, like:

vnc4server -geometry 1280x1024 -geometry 800x600

From a terminal in a vncviewer (with: 'allow dymanic desktop resizing' enabled) use xrandr to view the available modes:

xrandr

to change the resulution, for example use:

xrandr -s 800x600

Thats it.

Accessing JPEG EXIF rotation data in JavaScript on the client side

You can use the exif-js library in combination with the HTML5 File API: http://jsfiddle.net/xQnMd/1/.

$("input").change(function() {
    var file = this.files[0];  // file
        fr   = new FileReader; // to read file contents

    fr.onloadend = function() {
        // get EXIF data
        var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));

        // alert a value
        alert(exif.Make);
    };

    fr.readAsBinaryString(file); // read the file
});

How to use Apple's new San Francisco font on a webpage

Apple is abstracting the system fonts going forward. This facility uses new generic family name -apple-system. So something like below should get you what you want.

body 
{
  font-family: -apple-system, "Helvetica Neue", "Lucida Grande";
}

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Subtract two dates in SQL and get days of the result

Syntax

DATEDIFF(expr1,expr2)

Description

DATEDIFF() returns (expr1 – expr2) expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

@D Stanley

how to sort pandas dataframe from one column

Just adding some more operations on data. Suppose we have a dataframe df, we can do several operations to get desired outputs

ID         cost      tax    label
1       216590      1600    test      
2       523213      1800    test 
3          250      1500    experiment

(df['label'].value_counts().to_frame().reset_index()).sort_values('label', ascending=False)

will give sorted output of labels as a dataframe

    index   label
0   test        2
1   experiment  1

How do I set up Visual Studio Code to compile C++ code?

If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:

{
    "version": "0.1.0",
    "command": "sh",
    "isShellCommand": true,
    "args": ["-c"],
    "showOutput": "always",
    "suppressTaskName": true,
    "options": {
        "cwd": "${workspaceRoot}/build"
    },
    "tasks": [
        {
            "taskName": "cmake",
            "args": ["cmake ."]
        },
        {
            "taskName": "make",
            "args" : ["make"],
            "isBuildCommand": true,
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": "absolute",
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

This assumes that there is a folder build in the root of the workspace with a CMake configuration.

There's also a CMake integration extension that adds a "CMake build" command to VScode.

PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.

C# - Simplest way to remove first occurrence of a substring from another string

I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.

public static string Remove(this string source, string remove,  int firstN)
    {
        if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
        {
            return source;
        }
        int index = source.IndexOf(remove);
        return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);
    }

This does a bit of recursion which is always fun.

Here is a simple unit test as well:

   [TestMethod()]
    public void RemoveTwiceTest()
    {
        string source = "look up look up look it up";
        string remove = "look";
        int firstN = 2;
        string expected = " up  up look it up";
        string actual;
        actual = source.Remove(remove, firstN);
        Assert.AreEqual(expected, actual);

    }

Jenkins Host key verification failed

Best way you can just use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.

git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'

Remove all stylings (border, glow) from textarea

if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important

How to delete an element from an array in C#

' To remove items from string based on Dictionary key values. ' VB.net code

 Dim stringArr As String() = "file1,file2,file3,file4,file5,file6".Split(","c)
 Dim test As Dictionary(Of String, String) = New Dictionary(Of String, String)
 test.Add("file3", "description")
 test.Add("file5", "description")
 stringArr = stringArr.Except(test.Keys).ToArray()

How do I use su to execute the rest of the bash script as that user?

Use sudo instead

EDIT: As Douglas pointed out, you can not use cd in sudo since it is not an external command. You have to run the commands in a subshell to make the cd work.

sudo -u $USERNAME -H sh -c "cd ~/$PROJECT; svn update"

sudo -u $USERNAME -H cd ~/$PROJECT
sudo -u $USERNAME svn update

You may be asked to input that user's password, but only once.

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a similar issue while working with Jupyter. I was trying to copy files from one directory to another using copy function of shutil. The problem was that I had forgotten to import the package.(Silly) But instead of python giving import error, it gave this error.

Solved by adding:

from shutil import copy

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

Removing html5 required attribute with jQuery

Just:

$('#edit-submitted-first-name').removeAttr('required');?????

If you're interested in further reading take a look here.

Format date and Subtract days using Moment.js

startdate = moment().subtract(1, 'days').startOf('day')

Understanding __getitem__ method

__getitem__ can be used to implement "lazy" dict subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.

As a simple example, suppose you have two lists, keys and values, whereby {k:v for k,v in zip(keys, values)} is the dictionary that you need, which must be made lazy for speed or efficiency purposes:

class LazyDict(dict):
    
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values
        super().__init__()
        
    def __getitem__(self, key):
        if key not in self:
            try:
                i = self.keys.index(key)
                self.__setitem__(self.keys.pop(i), self.values.pop(i))
            except ValueError, IndexError:
                raise KeyError("No such key-value pair!!")
        return super().__getitem__(key)

Usage:

>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])

Peak detection in a 2D array

There are several and extensive pieces of software available from the astronomy and cosmology community - this is a significant area of research both historically and currently.

Do not be alarmed if you are not an astronomer - some are easy to use outside the field. For example, you could use astropy/photutils:

https://photutils.readthedocs.io/en/stable/detection.html#local-peak-detection

[It seems a bit rude to repeat their short sample code here.]

An incomplete and slightly biased list of techniques/packages/links that might be of interest is given below - do add more in the comments and I will update this answer as necessary. Of course there is a trade-off of accuracy vs compute resources. [Honestly, there are too many to give code examples in a single answer such as this so I am not sure whether this answer will fly or not.]

Source Extractor https://www.astromatic.net/software/sextractor

MultiNest https://github.com/farhanferoz/MultiNest [+ pyMultiNest]

ASKAP/EMU source-finding challenge: https://arxiv.org/abs/1509.03931

You could also search for Planck and/or WMAP source-extraction challenges.

...

How to list all functions in a Python module?

import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

Best method for reading newline delimited files and discarding the newlines?

I'd do it like this:

f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Bash 4's brace expansion has a step feature:

for {0..10..2}; do
  ..
done

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

How do I set the icon for my application in visual studio 2008?

If you're using .NET, in the solutions explorer right click your program and select properties. Under the resource section select Icon and manifest, then browse to the location of your icon.

How to get multiple counts with one SQL query?

Based on Bluefeet's accepted response with an added nuance using OVER():

SELECT distributor_id,
    COUNT(*) total,
    SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
    SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
FROM yourtable
GROUP BY distributor_id

Using OVER() with nothing in the () will give you the total count for the whole dataset.

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Make an html number input always display 2 decimal places

Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.

How to add many functions in ONE ng-click?

The standard way to add Multiple functions

<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>

or

<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>

Selenium C# WebDriver: Wait until element is present

I confused an anonymous function with a predicate. Here's a little helper method:

   WebDriverWait wait;
    private void waitForById(string id)
    {
        if (wait == null)
            wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));

        //wait.Until(driver);
        wait.Until(d => d.FindElement(By.Id(id)));
    }

File Upload without Form

Try this puglin simpleUpload, no need form

Html:

<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>

Javascript:

$('#simpleUpload').simpleUpload({
  url: 'upload.php',
  trigger: '#enviar',
  success: function(data){
    alert('Envio com sucesso');

  }
});

iCheck check if checkbox is checked

I wrote some simple thing:

When you initialize icheck as:

$('input').iCheck({
    checkboxClass: 'icheckbox_square-blue',
    radioClass: 'iradio_square-blue',
    increaseArea: '20%' // optional
});

Add this code under it:

$('input').on('ifChecked', function (event){
    $(this).closest("input").attr('checked', true);          
});
$('input').on('ifUnchecked', function (event) {
    $(this).closest("input").attr('checked', false);
});

After this you can easily find your original checkbox's state. I wrote this code for using icheck in gridView and accessed its state from server side by C#.

Simply find your checkBox from its id.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

Pythonic way to print list items

Expanding @lucasg's answer (inspired by the comment it received):

To get a formatted list output, you can do something along these lines:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)

01, 02, 05

Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.

How to find a user's home directory on linux or unix?

The userdir prefix (e.g., '/home' or '/export/home') could be a configuration item. Then the app can append the arbitrary user name to that path.

Caveat: This doesn't intelligently interact with the OS, so you'd be out of luck if it were a Windows system with userdirs on different drives, or on Unix with a home dir layout like /home/f/foo, /home/b/bar.

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

How can I update window.location.hash without jumping the document?

When using laravel framework, I had some issues with using a route->back() function since it erased my hash. In order to keep my hash, I created a simple function:

$(function() {   
    if (localStorage.getItem("hash")    ){
     location.hash = localStorage.getItem("hash");
    }
}); 

and I set it in my other JS function like this:

localStorage.setItem("hash", myvalue);

You can name your local storage values any way you like; mine named hash.

Therefore, if the hash is set on PAGE1 and then you navigate to PAGE2; the hash will be recreated on PAGE1 when you click Back on PAGE2.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I was early in my development cycle, so this may not work for everyone (but I don't see why it wouldn't).

I added blank=True, null=True to the columns where I was getting the error. Then I ran the python manage.py makemigrations command.

Immediately after running this command (and before running python manage.py migrate), I removed the blank=True, null=True from all the columns. Then I ran python manage.py makemigrations again. I was given an option to just change the columns myself, which I selected.

Then I ran python manage.py migrate and everything worked well!

Java: How to set Precision for double value?

This worked for me:

public static void main(String[] s) {
        Double d = Math.PI;
        d = Double.parseDouble(String.format("%.3f", d));  // can be required precision
        System.out.println(d);
    }

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

Making a Bootstrap table column fit to content

This solution is not good every time. But i have only two columns and I want second column to take all the remaining space. This worked for me

 <tr>
    <td class="text-nowrap">A</td>
    <td class="w-100">B</td>
 </tr>

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

When compiling memcached under Centos 5.x i got the same problem.

The solution is to upgrade gcc and g++ to version 4.4 at least.

Make sure your CC/CXX is set (exported) to right binaries before compiling.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

The problem could also come because of a lack of SQL driver in your Tomcat installation directory.

I had to had mysql-connector-java-5.1.23-bin.jar in apache-tomcat-9.0.12/lib/ folder.

https://dev.mysql.com/downloads/connector/j/

How do I get a file's last modified time in Perl?

On my FreeBSD system, stat just returns a bless.

$VAR1 = bless( [
                 102,
                 8,
                 33188,
                 1,
                 0,
                 0,
                 661,
                 276,
                 1372816636,
                 1372755222,
                 1372755233,
                 32768,
                 8
               ], 'File::stat' );

You need to extract mtime like this:

my @ABC = (stat($my_file));

print "-----------$ABC['File::stat'][9] ------------------------\n";

or

print "-----------$ABC[0][9] ------------------------\n";

Error: The type exists in both directories

Try cleaning your solution and then try to rebuild. Visual Studio probably still has reference to the old dll after it created the new dll.

How to get Real IP from Visitor?

Proxies may send a HTTP_X_FORWARDED_FOR header but even that is optional.

Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.

Lombok is not generating getter and setter

Download Lombok Jar File https://projectlombok.org/downloads/lombok.jar

Add maven dependency:

   <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.18</version>
   </dependency>   

Start Lombok Installation java -jar lombok-1.16.18.jar

find complete example in this link:
https://howtodoinjava.com/automation/lombok-eclipse-installation-examples/

How to split() a delimited string to a List<String>

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

cURL equivalent in Node.js?

The http module that you use to run servers is also used to make remote requests.

Here's the example in their docs:

var http = require("http");

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Presenting modal in iOS 13 fullscreen

With iOS 13, as stated in the Platforms State of the Union during the WWDC 2019, Apple introduced a new default card presentation. In order to force the fullscreen you have to specify it explicitly with:

let vc = UIViewController()
vc.modalPresentationStyle = .fullScreen //or .overFullScreen for transparency
self.present(vc, animated: true, completion: nil)

default web page width - 1024px or 980px?

If it isn't I could see things heading that way.

I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).

I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

Evaluate a string with a switch in C++

Switch value must have an Integral type. Also, since you know that differenciating character is in position 7, you could switch on a.at(7). But you are not sure the user entered 8 characters. He may as well have done some typing mistake. So you are to surround your switch statement within a Try Catch. Something with this flavour

#include<iostream>
using namespace std;
int main() {
    string a;
    cin>>a;

    try
    {
    switch (a.at(7)) {
    case '1':
        cout<<"It pressed number 1"<<endl;
        break;
    case '2':
        cout<<"It pressed number 2"<<endl;
        break;
    case '3':
        cout<<"It pressed number 3"<<endl;
        break;
    default:
        cout<<"She put no choice"<<endl;
        break;
    }
    catch(...)
    {

    }
    }
    return 0;
}

The default clause in switch statement captures cases when users input is at least 8 characters, but not in {1,2,3}.

Alternatively, you can switch on values in an enum.

EDIT

Fetching 7th character with operator[]() does not perform bounds check, so that behavior would be undefined. we use at() from std::string, which is bounds-checked, as explained here.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Check "Virtualization" status under performance option in your task manager. If you already have enabled it in your BIOS and still status is "Disabled", then go to bios, disable it and save & exit. Restart or shut down again. Enable it in BIOS again and save & exit. This time you'll see the status changed to "Enabled", It took me 3 attempts (don't know why it took that much time, but finally it worked).

Tkinter example code for multiple windows, why won't buttons load correctly?

I rewrote your code in a more organized, better-practiced way:

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()

    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Result:

Demo1 window Demo2 window

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

nodejs npm global config missing on windows

For me (being on Windows 10) the npmrc file was located in:

%USERPROFILE%\.npmrc

Tested with:

  • npm v4.2.0
  • Node.js v7.8.0

What does the "at" (@) symbol do in Python?

It indicates that you are using a decorator. Here is Bruce Eckel's example from 2008.

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

How can I check whether Google Maps is fully loaded?

GMap2::tilesloaded() would be the event you're looking for.

See GMap2.tilesloaded for references.

NoSql vs Relational database

Not all data is relational. For those situations, NoSQL can be helpful.

With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.

SQL has several very big advantages:

  1. Strong mathematical basis.
  2. Declarative syntax.
  3. A well-known language in Structured Query Language (SQL).

Those haven't gone away.

It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.

Documents can be stored in non-relational databases, like CouchDB.

Maybe reading this will help.

How to get last N records with activerecord?

This is the Rails 3 way

SomeModel.last(5) # last 5 records in ascending order

SomeModel.last(5).reverse # last 5 records in descending order

How do I get the number of elements in a list?

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

Wavy shape with css

I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.

css wavy divider in CSS

Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:

Two simple <div>:

_x000D_
_x000D_
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
  background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
  background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
  content: "";_x000D_
  position: relative;_x000D_
  left: -3rem;_x000D_
  /* padding * -1 */_x000D_
  top: calc( 3rem - 4rem / 2);_x000D_
  /* padding - height/2 */_x000D_
  float: left;_x000D_
  display: block;_x000D_
  height: 4rem;_x000D_
  width: 100vw;_x000D_
  background: hsla(0, 0%, 100%, 0.5);_x000D_
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
  padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.2rem;_x000D_
  line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
  color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
_x000D_
_x000D_

Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)

It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)

To edit the colors, you need to edit the URL-encoded SVG itself.

Pay attention (like in the first demo) to a change in the viewBox to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)

Another thing to pay attention to here is the background-size set to 100% 100% to get it to stretch in both directions.

Operator overloading in Java

You can't do this yourself since Java doesn't permit operator overloading.

With one exception, however. + and += are overloaded for String objects.

How to display HTML <FORM> as inline element?

Move your form tag just outside the paragraph and set margins / padding to zero:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

Difference between HashMap, LinkedHashMap and TreeMap

  • HashMap:

    • Order not maintains
    • Faster than LinkedHashMap
    • Used for store heap of objects
  • LinkedHashMap:

    • LinkedHashMap insertion order will be maintained
    • Slower than HashMap and faster than TreeMap
    • If you want to maintain an insertion order use this.
  • TreeMap:

    • TreeMap is a tree-based mapping
    • TreeMap will follow the natural ordering of key
    • Slower than HashMap and LinkedHashMap
    • Use TreeMap when you need to maintain natural(default) ordering

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

Getting the name of the currently executing method

To get the name of the method that called the current method you can use:

new Exception("is not thrown").getStackTrace()[1].getMethodName()

This works on my MacBook as well as on my Android phone

I also tried:

Thread.currentThread().getStackTrace()[1]

but Android will return "getStackTrace" I could fix this for Android with

Thread.currentThread().getStackTrace()[2]

but then I get the wrong answer on my MacBook

Python threading.timer - repeat function every 'n' seconds

I had to do this for a project. What I ended up doing was start a separate thread for the function

t = threading.Thread(target =heartbeat, args=(worker,))
t.start()

****heartbeat is my function, worker is one of my arguments****

inside of my heartbeat function:

def heartbeat(worker):

    while True:
        time.sleep(5)
        #all of my code

So when I start the thread the function will repeatedly wait 5 seconds, run all of my code, and do that indefinitely. If you want to kill the process just kill the thread.

Formatting DataBinder.Eval data

Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.

Mark Up:-

<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>

Code behind:-

Public Function fLabel(ByVal tval) As String
   fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

Parse an HTML string with JS

EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.


For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.

For example try parsing <td>Test</td>. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.

Only jQuery handles that case well.

So the future solution (MS Edge 13+) is to use template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99

Hosting a Maven repository on github

Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

add this to your build section

     <extensions>
        <extension>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <groupId>org.apache.maven.wagon</groupId>
        <version>2.2</version>
        </extension>
    </extensions>

Add something like this to your distributionManagement section

<repository>
    <id>release.repo</id>
    <url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>

Finally make sure to setup the repository access in your settings.xml

add this to your servers section

    <server>
        <id>release.repo</id>
        <username>xxxx</username>
        <password>xxxx</password>
    </server>

and a definition to your repositories section

            <repository>
                <id>release.repo</id>
                <url>http://repo.jillesvangurp.com/releases</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>

Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

Animate scroll to ID on page load

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

jquery-animate-body-for-all-browsers.

JavaScript - populate drop down list with array

<form id="myForm">
<select id="selectNumber">
    <option>Choose a number</option>
    <script>
        var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
        for(i=0; i<myArray.length; i++) {  
            document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
        }
    </script>
</select>
</form>

Using Git with Visual Studio

In Jan 2013, Microsoft announced that they are adding full Git support into all their ALM products. They have published a plugin for Visual Studio 2012 that adds Git source control integration.

Alternatively, there is a project called Git Extensions that includes add-ins for Visual Studio 2005, 2008, 2010 and 2012, as well as Windows Explorer integration. It's regularly updated and having used it on a couple of projects, I've found it very useful.

Another option is Git Source Control Provider.

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

How do I get the different parts of a Flask request's url?

you should try:

request.url 

It suppose to work always, even on localhost (just did it).

jQuery if statement to check visibility

After fixing a performance issue related to the use of .is(":visible"), I would recommend against the above answers and instead use jQuery's code for deciding whether a single element is visible:

$.expr.filters.visible($("#singleElementID")[0]);

What .is does is check whether a set of elements is within another set of elements. So you will looking for your element within the entire set of visible elements on your page. Having 100 elements is pretty normal and might take a few milliseconds to search through the array of visible elements. If you're building a web app you probably have hundreds or possibly thousands. Our app was sometimes taking 100ms for $("#selector").is(":visible") since it was checking if an element was in an array of 5000 other elements.

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

What's the difference between next() and nextLine() methods from Scanner class?

From the documentation for Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

From the documentation for next():

A complete token is preceded and followed by input that matches the delimiter pattern.

Import functions from another js file. Javascript

By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.

If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.

import './course.js';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

<html>
    <head>
        <script src="./models/student.js" type="module"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.

You can also write a quick express server to serve your files (install Node if you don't have it):

//package.json
{
  "scripts": { "start": "node server" },
  "dependencies": { "express": "latest" }
}

// server/index.js
const express = require('express');
const app = express();

app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);

With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.

C: socket connection timeout

Here is a modern connect_with_timeout implementation, using poll, with proper error and signal handling:

#include <sys/socket.h>
#include <fcntl.h>
#include <poll.h>
#include <time.h>

int connect_with_timeout(int sockfd, const struct sockaddr *addr, socklen_t addrlen, unsigned int timeout_ms) {
    int rc = 0;
    // Set O_NONBLOCK
    int sockfd_flags_before;
    if((sockfd_flags_before=fcntl(sockfd,F_GETFL,0)<0)) return -1;
    if(fcntl(sockfd,F_SETFL,sockfd_flags_before | O_NONBLOCK)<0) return -1;
    // Start connecting (asynchronously)
    do {
        if (connect(sockfd, addr, addrlen)<0) {
            // Did connect return an error? If so, we'll fail.
            if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) {
                rc = -1;
            }
            // Otherwise, we'll wait for it to complete.
            else {
                // Set a deadline timestamp 'timeout' ms from now (needed b/c poll can be interrupted)
                struct timespec now;
                if(clock_gettime(CLOCK_MONOTONIC, &now)<0) { rc=-1; break; }
                struct timespec deadline = { .tv_sec = now.tv_sec,
                                             .tv_nsec = now.tv_nsec + timeout_ms*1000000l};
                // Wait for the connection to complete.
                do {
                    // Calculate how long until the deadline
                    if(clock_gettime(CLOCK_MONOTONIC, &now)<0) { rc=-1; break; }
                    int ms_until_deadline = (int)(  (deadline.tv_sec  - now.tv_sec)*1000l
                                                  + (deadline.tv_nsec - now.tv_nsec)/1000000l);
                    if(ms_until_deadline<0) { rc=0; break; }
                    // Wait for connect to complete (or for the timeout deadline)
                    struct pollfd pfds[] = { { .fd = sockfd, .events = POLLOUT } };
                    rc = poll(pfds, 1, ms_until_deadline);
                    // If poll 'succeeded', make sure it *really* succeeded
                    if(rc>0) {
                        int error = 0; socklen_t len = sizeof(error);
                        int retval = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len);
                        if(retval==0) errno = error;
                        if(error!=0) rc=-1;
                    }
                }
                // If poll was interrupted, try again.
                while(rc==-1 && errno==EINTR);
                // Did poll timeout? If so, fail.
                if(rc==0) {
                    errno = ETIMEDOUT;
                    rc=-1;
                }
            }
        }
    } while(0);
    // Restore original O_NONBLOCK state
    if(fcntl(sockfd,F_SETFL,sockfd_flags_before)<0) return -1;
    // Success
    return rc;
}

How to Detect Browser Window /Tab Close Event?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;

function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
 var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
 function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;

}
}
window.onbeforeunload=goodbye;

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
 }
 });

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
  // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
});

 // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

 }

  // Wire up the events as soon as the DOM tree is ready
   $(document).ready(function() {
   wireUpEvents();
   });
   </script>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

Clicking URLs opens default browser

If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.

You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.

You set the WebViewClient of your WebView using the setWebViewClient() method.

If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Android: How to set password property in an edit text?

Here's a new way of putting dots in password

<EditText
    android:id="@+id/loginPassword"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="@string/pwprompt" /

add android:inputType = "textPassword"

How can I concatenate two arrays in Java?

It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use Arrays.copyOf()

Both versions avoid creating any intermediary List objects and use System.arraycopy() to ensure that copying large arrays is as fast as possible.

For two arrays it looks like this:

public static <T> T[] concat(T[] first, T[] second) {
  T[] result = Arrays.copyOf(first, first.length + second.length);
  System.arraycopy(second, 0, result, first.length, second.length);
  return result;
}

And for a arbitrary number of arrays (>= 1) it looks like this:

public static <T> T[] concatAll(T[] first, T[]... rest) {
  int totalLength = first.length;
  for (T[] array : rest) {
    totalLength += array.length;
  }
  T[] result = Arrays.copyOf(first, totalLength);
  int offset = first.length;
  for (T[] array : rest) {
    System.arraycopy(array, 0, result, offset, array.length);
    offset += array.length;
  }
  return result;
}

How do I capture the output into a variable from an external process in PowerShell?

Have you tried:

$OutputVariable = (Shell command) | Out-String

How to install Java SDK on CentOS?

On centos 7, I just do

sudo yum install java-sdk

I assume you have most common repo already. Centos just finds the correct SDK with the -devel sufix.

How to pass values across the pages in ASP.net without using Session

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]

Creating SolidColorBrush from hex color value

Try this instead:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

How to check if spark dataframe is empty?

I found that on some cases:

>>>print(type(df))
<class 'pyspark.sql.dataframe.DataFrame'>

>>>df.take(1).isEmpty
'list' object has no attribute 'isEmpty'

this is same for "length" or replace take() by head()

[Solution] for the issue we can use.

>>>df.limit(2).count() > 1
False

Run jQuery function onclick

Why do you need to attach it to the HTML? Just bind the function with hover

$("div.system_box").hover(function(){ mousin }, 
                          function() { mouseout });

If you do insist to have JS references inside the html, which is usualy a bad idea you can use:

onmouseover="yourJavaScriptCode()"

after topic edit:

<div class="system_box" data-target="sms_box">

...

$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

you can use the return statement without any parameter to exit a function

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

or raise an exception if you want to be informed of the problem

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...

Job for mysqld.service failed See "systemctl status mysqld.service"

  1. open my.cnf and copy the log-error path

  2. then check the permission for the copied log file using
    $ ls -l /var/log/mysql.log

  3. if any log file permission may changed from mysql:mysql, please change the file permission to
    $ chown -R mysql:mysql /var/log/mysql.log

  4. then restart the mysql server
    $ service mysql restart || systemctl restart mysqld

note: this kind of errors formed by the permission issues. all the mysql service start commands using the log file for writing the status of mysql. If the permission has been changed, the service can't be write anything into the log files. If it happens it will stopped to run the service

How to set a Timer in Java?

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

Change <br> height using CSS

Use the content property and style that content. Content behavior is then adjusted using pseudo elements. Pseudo elements ::before and ::after both work in Mac Safari 10.0.3.

Here element br content is used as the element anchor for element br::after content. Element br is where br spacing can be styled. br::after is the place where br::after content can be displayed and styled. Looks pretty, but not a 2px <br>.

br { content: ""; display: block; margin: 1rem 0; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }

The br element line-height property is ignored. If negative values are applied to either or both selectors to give vertical 'lift' to br tags in display, then correct vertical spacing occurs, but display incrementally indents display content following each br tag. The indent is exactly equal to the amount that lift varies from actual typographic line-height. If you guess the right lift, there is no indent but a single pile-up line exactly equal to raw glyph height, jammed between previous and following lines.

Further, a trailing br tag will cause the following html display tag to inherit the br:after content styling. Also, pseudo elements cause <br> <br> to be interpreted as a single <br>. While pseudo-class br:active causes each <br> to be interpreted separately. Finally, using br:active ignores pseudo element br:after and all br:active styling. So, all that's required is this:

br:active { }

which is no help for creating a 2px high <br> display. And here the pseudo class :active is ignored!

br:active { content: ""; display: block; margin: 1.25em 0; }
br { content: ""; display: block; margin: 1rem; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }

This is a partial solution only. Pseudo class and pseudo element may provide solution, if tweaked. This may be part of CSS solution. (I only have Safari, try it in other browsers.)

Learn web development: pseudo classes and pseudo elements

Pay attention to global elements - BR at Mozilla.org

Can you style html form buttons with css?

Yeah, it's pretty simple:

input[type="submit"]{
  background: #fff;
  border: 1px solid #000;
  text-shadow: 1px 1px 1px #000;
}

I recommend giving it an ID or a class so that you can target it more easily.

Calling Member Functions within Main C++

you have to create a instance of the class for calling the method..

Regex Last occurrence?

You can try anchoring it to the end of the string, something like \\[^\\]*$. Though I'm not sure if one absolutely has to use regexp for the task.

How to create an infinite loop in Windows batch file?

A really infinite loop, counting from 1 to 10 with increment of 0.
You need infinite or more increments to reach the 10.

for /L %%n in (1,0,10) do (
  echo do stuff
  rem ** can't be leaved with a goto (hangs)
  rem ** can't be stopped with exit /b (hangs)
  rem ** can be stopped with exit
  rem ** can be stopped with a syntax error
  call :stop
)

:stop
call :__stop 2>nul

:__stop
() creates a syntax error, quits the batch

This could be useful if you need a really infinite loop, as it is much faster than a goto :loop version because a for-loop is cached completely once at startup.

SQL Server default character encoding

Encodings

In most cases, SQL Server stores Unicode data (i.e. that which is found in the XML and N-prefixed types) in UCS-2 / UTF-16 (storage is the same, UTF-16 merely handles Supplementary Characters correctly). This is not configurable: there is no option to use either UTF-8 or UTF-32 (see UPDATE section at the bottom re: UTF-8 starting in SQL Server 2019). Whether or not the built-in functions can properly handle Supplementary Characters, and whether or not those are sorted and compared properly, depends on the Collation being used. The older Collations — names starting with SQL_ (e.g. SQL_Latin1_General_CP1_CI_AS) xor no version number in the name (e.g. Latin1_General_CI_AS) — equate all Supplementary Characters with each other (due to having no sort weight). Starting in SQL Server 2005 they introduced the 90 series Collations (those with _90_ in the name) that could at least do a binary comparison on Supplementary Characters so that you could differentiate between them, even if they didn't sort in the desired order. That also holds true for the 100 series Collations introduced in SQL Server 2008. SQL Server 2012 introduced Collations with names ending in _SC that not only sort Supplementary Characters properly, but also allow the built-in functions to interpret them as expected (i.e. treating the surrogate pair as a single entity). Starting in SQL Server 2017, all new Collations (the 140 series) implicitly support Supplementary Characters, hence there are no new Collations with names ending in _SC.

Starting in SQL Server 2019, UTF-8 became a supported encoding for CHAR and VARCHAR data (columns, variables, and literals), but not TEXT (see UPDATE section at the bottom re: UTF-8 starting in SQL Server 2019).

Non-Unicode data (i.e. that which is found in the CHAR, VARCHAR, and TEXT types — but don't use TEXT, use VARCHAR(MAX) instead) uses an 8-bit encoding (Extended ASCII, DBCS, or EBCDIC). The specific character set / encoding is based on the Code Page, which in turn is based on the Collation of a column, or the Collation of the current database for literals and variables, or the Collation of the Instance for variable / cursor names and GOTO labels, or what is specified in a COLLATE clause if one is being used.

To see how locales match up to collations, check out:

To see the Code Page associated with a particular Collation (this is the character set and only affects CHAR / VARCHAR / TEXT data), run the following:

SELECT COLLATIONPROPERTY( 'Latin1_General_100_CI_AS' , 'CodePage' ) AS [CodePage];

To see the LCID (i.e. locale) associated with a particular Collation (this affects the sorting & comparison rules), run the following:

SELECT COLLATIONPROPERTY( 'Latin1_General_100_CI_AS' , 'LCID' ) AS [LCID];

To view the list of available Collations, along with their associated LCIDs and Code Pages, run:

SELECT [name],
       COLLATIONPROPERTY( [name], 'LCID' ) AS [LCID],
       COLLATIONPROPERTY( [name], 'CodePage' ) AS [CodePage]
FROM sys.fn_helpcollations()
ORDER BY [name];

Defaults

Before looking at the Server and Database default Collations, one should understand the relative importance of those defaults.

The Server (Instance, really) default Collation is used as the default for newly created Databases (including the system Databases: master, model, msdb, and tempdb). But this does not mean that any Database (other than the 4 system DBs) is using that Collation. The Database default Collation can be changed at any time (though there are dependencies that might prevent a Database from having it's Collation changed). The Server default Collation, however, is not so easy to change. For details on changing all collations, please see: Changing the Collation of the Instance, the Databases, and All Columns in All User Databases: What Could Possibly Go Wrong?

The server/Instance Collation controls:

  • local variable names
  • CURSOR names
  • GOTO labels
  • Instance-level meta-data

The Database default Collation is used in three ways:

  • as the default for newly created string columns. But this does not mean that any string column is using that Collation. The Collation of a column can be changed at any time. Here knowing the Database default is important as an indication of what the string columns are most likely set to.
  • as the Collation for operations involving string literals, variables, and built-in functions that do not take string inputs but produces a string output (i.e. IF (@InputParam = 'something') ). Here knowing the Database default is definitely important as it governs how these operations will behave.
  • Database-level meta-data

The column Collation is either specified in the COLLATE clause at the time of the CREATE TABLE or an ALTER TABLE {table_name} ALTER COLUMN, or if not specified, taken from the Database default.

Since there are several layers here where a Collation can be specified (Database default / columns / literals & variables), the resulting Collation is determined by Collation Precedence.

All of that being said, the following query shows the default / current settings for the OS, SQL Server Instance, and specified Database:

SELECT os_language_version,
       ---
       SERVERPROPERTY('LCID') AS 'Instance-LCID',
       SERVERPROPERTY('Collation') AS 'Instance-Collation',
       SERVERPROPERTY('ComparisonStyle') AS 'Instance-ComparisonStyle',
       SERVERPROPERTY('SqlSortOrder') AS 'Instance-SqlSortOrder',
       SERVERPROPERTY('SqlSortOrderName') AS 'Instance-SqlSortOrderName',
       SERVERPROPERTY('SqlCharSet') AS 'Instance-SqlCharSet',
       SERVERPROPERTY('SqlCharSetName') AS 'Instance-SqlCharSetName',
       ---
       DATABASEPROPERTYEX(N'{database_name}', 'LCID') AS 'Database-LCID',
       DATABASEPROPERTYEX(N'{database_name}', 'Collation') AS 'Database-Collation',
  DATABASEPROPERTYEX(N'{database_name}', 'ComparisonStyle') AS 'Database-ComparisonStyle',
       DATABASEPROPERTYEX(N'{database_name}', 'SQLSortOrder') AS 'Database-SQLSortOrder'
FROM   sys.dm_os_windows_info;

Installation Default

Another interpretation of "default" could mean what default Collation is selected for the Instance-level collation when installing. That varies based on the OS language, but the (horrible, horrible) default for systems using "US English" is SQL_Latin1_General_CP1_CI_AS. In that case, the "default" encoding is Windows Code Page 1252 for VARCHAR data, and as always, UTF-16 for NVARCHAR data. You can find the list of OS language to default SQL Server collation here: Collation and Unicode support: Server-level collations. Keep in mind that these defaults can be overridden; this list is merely what the Instance will use if not overridden during install.


UPDATE 2018-10-02

SQL Server 2019 introduces native support for UTF-8 in VARCHAR / CHAR datatypes (not TEXT!). This is accomplished via a set of new collations, the names of which all end with _UTF8. This is an interesting capability that will definitely help some folks, but there are some "quirks" with it, especially when UTF-8 isn't being used for all columns and the Database's default Collation, so don't use it just because you have heard that UTF-8 is magically better. UTF-8 was designed solely for ASCII compatibility: to enable ASCII-only systems (i.e. UNIX back in the day) to support Unicode without changing any existing code or files. That it saves space for data using mostly (or only) US English characters (and some punctuation) is a side-effect. When not using mostly (or only) US English characters, data can be the same size as UTF-16, or even larger, depending on which characters are being used. And, in cases where space is being saved, performance might improve, but it might also get worse.

For a detailed analysis of this new feature, please see my post, "Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?".

Bootstrap carousel multiple frames at once

I had the same problem and the solutions described here worked well. But I wanted to support window size (and layout) changes. The result is a small library that solves all the calculation. Check it out here: https://github.com/SocialbitGmbH/BootstrapCarouselPageMerger

To make the script work, you have to add a new <div> wrapper with the class .item-content directly into your .item <div>. Example:

<div class="carousel slide multiple" id="very-cool-carousel" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
        <div class="item active">
            <div class="item-content">
                First page
            </div>
        </div>
        <div class="item active">
            <div class="item-content">
                Second page
            </div>
        </div>
    </div>
</div>

Usage of this library:

socialbitBootstrapCarouselPageMerger.run('div.carousel');

To change the settings:

socialbitBootstrapCarouselPageMerger.settings.spaceCalculationFactor = 0.82;

Example:

As you can see, the carousel gets updated to show more controls when you resize the window. Check out the watchWindowSizeTimeout setting to control the timeout for reacting to window size changes.

Format number to always show 2 decimal places

Are you looking for floor?

var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
alert(fnum + " and " + fnum2); //both values will be 1.00

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

Is there a short contains function for lists?

In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.  

A dumb use may be:

>>> class ContainsEverything:
    def __init__(self):
        return None
    def __contains__(self, *elem, **k):
        return True


>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>         

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Online PHP syntax checker / validator

I found this for online php validation:-

http://www.icosaedro.it/phplint/phplint-on-line.html

Hope this helps.

Check if object is a jQuery object

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

How to make a new List in Java

List<Object> nameOfList = new ArrayList<Object>();

You need to import List and ArrayList.

How do you iterate through every file/directory recursively in standard C++?

You can use ftw(3) or nftw(3) to walk a filesystem hierarchy in C or C++ on POSIX systems.

Can not find the tag library descriptor of springframework

I know it's an old question, but the tag library http://www.springframework.org/tags is provided by spring-webmvc package. With Maven it can be added to the project with the following lines to be added in the pom.xml

<properties>
    <spring.version>3.0.6.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

Without Maven, just add that jar to your classpath. In any case it's not necessary to refer the tld file directly, it will be automatically found.

What does flex: 1 mean?

flex: 1 means the following:

flex-grow : 1;    ? The div will grow in same proportion as the window-size       
flex-shrink : 1;  ? The div will shrink in same proportion as the window-size 
flex-basis : 0;   ? The div does not have a starting value as such and will 
                     take up screen as per the screen size available for
                     e.g:- if 3 divs are in the wrapper then each div will take 33%.

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

How to fit Windows Form to any screen resolution?

If you want to set the form size programmatically, set the form's StartPosition property to Manual. Otherwise the form's own positioning and sizing algorithm will interfere with yours. This is why you are experiencing the problems mentioned in your question.

Example: Here is how I resize the form to a size half-way between its original size and the size of the screen's working area. I also center the form in the working area:

public MainView()
{
    InitializeComponent();

    // StartPosition was set to FormStartPosition.Manual in the properties window.
    Rectangle screen = Screen.PrimaryScreen.WorkingArea;
    int w = Width >= screen.Width ? screen.Width : (screen.Width + Width) / 2;
    int h = Height >= screen.Height ? screen.Height : (screen.Height + Height) / 2;
    this.Location = new Point((screen.Width - w) / 2, (screen.Height - h) / 2);
    this.Size = new Size(w, h);
}

Note that setting WindowState to FormWindowState.Maximized alone does not change the size of the restored window. So the window might look good as long as it is maximized, but when restored, the window size and location can still be wrong. So I suggest setting size and location even when you intend to open the window as maximized.

How to color System.out.println output?

No, but there are third party API's that can handle it

http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

Edit: of course there are newer articles than that one I posted, the information is still viable though.

PHP Checking if the current date is before or after a set date

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

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

There is a c++ class called _bstr_t. It has useful methods and a collection of overloaded operators.

For example, you can easily assign from a const wchar_t * or a const char * just doing _bstr_t bstr = L"My string"; Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();. You can even convert it back to a regular char const char * c = bstr.operator char *(); You can then just use the const wchar_t * or the const char * to initialize a new std::wstring oe std::string.

Retrieving the first digit of a number

Integer.parseInt will take a string and return a int.

Using the "With Clause" SQL Server 2008

There are two types of WITH clauses:

Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).

;WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

Here is a select statement also using a WITH clause

SELECT * FROM orders WITH (NOLOCK) where order_id = 123

Is there a way for non-root processes to bind to "privileged" ports on Linux?

For some reason no one mention about lowering sysctl net.ipv4.ip_unprivileged_port_start to the value you need. Example: We need to bind our app to 443 port.

sysctl net.ipv4.ip_unprivileged_port_start=443

Some may say, there is a potential security problem: unprivileged users now may bind to the other privileged ports (444-1024). But you can solve this problem easily with iptables, by blocking other ports:

iptables -I INPUT -p tcp --dport 444:1024 -j DROP
iptables -I INPUT -p udp --dport 444:1024 -j DROP

Comparison with other methods. This method:

  • from some point is (IMO) even more secure than setting CAP_NET_BIND_SERVICE/setuid, since an application doesn't setuid at all, even partly (capabilities actually are). For example, to catch a coredump of capability-enabled application you will need to change sysctl fs.suid_dumpable (which leads to another potential security problems) Also, when CAP/suid is set, /proc/PID directory is owned by root, so your non-root user will not have full information/control of running process, for example, user will not be able (in common case) to determine which connections belong to application via /proc/PID/fd/ (netstat -aptn | grep PID).
  • has security disadvantage: while your app (or any app that uses ports 443-1024) is down for some reason, another app could take the port. But this problem could also be applied to CAP/suid (in case you set it on interpreter, e.g. java/nodejs) and iptables-redirect. Use systemd-socket method to exclude this problem. Use authbind method to only allow special user binding.
  • doesn't require setting CAP/suid every time you deploy new version of application.
  • doesn't require application support/modification, like systemd-socket method.
  • doesn't require kernel rebuild (if running version supports this sysctl setting)
  • doesn't do LD_PRELOAD like authbind/privbind method, this could potentially affect performance, security, behavior (does it? haven't tested). In the rest authbind is really flexible and secure method.
  • over-performs iptables REDIRECT/DNAT method, since it doesn't require address translation, connection state tracking, etc. This only noticeable on high-load systems.

Depending on the situation, I would choose between sysctl, CAP, authbind and iptables-redirect. And this is great that we have so many options.

Getting the last argument passed to a shell script

Just use !$.

$ mkdir folder
$ cd !$ # will run: cd folder

How to make code wait while calling asynchronous calls like Ajax

Real programmers do it with semaphores.

Have a variable set to 0. Increment it before each AJAX call. Decrement it in each success handler, and test for 0. If it is, you're done.

How to load URL in UIWebView in Swift?

Used Webview in Swift Language

let url = URL(string: "http://example.com")
   webview.loadRequest(URLRequest(url: url!))

Return list using select new in LINQ

You're creating a new type of object therefore it's anonymous. You can return a dynamic.

public dynamic GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                select new { pro.ProjectName, pro.ProjectId };

        return query.ToList();
    }
}

How do I select the "last child" with a specific class name in CSS?

I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list last">test3</li>
    <li>test4</li>
</ul>

The last element has the list class like its siblings but also has the last class which you can use to set any CSS property you want, like so:

ul li.list {
    color: #FF0000;
}

ul li.list.last {
    background-color: #000;
}