Programs & Examples On #.nettiers

.netTiers is a set of open source code generation templates that simplify the tasks of creating customized Application Tiers for your Microsoft.Net applications in just a few minutes.

Oracle SQL Developer - tables cannot be seen

For me, this wound up being a permissions issue.

I solved the problem by creating a superuser role (CREATE ROLE root WITH SUPERUSER LOGIN PASSWORD 'XXXXX';) and then using that superuser account to connect to the database.

This obviously won't be a viable solution in all situations.

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

use Javascript sort() function

var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){ 
    var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
    var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
            // if a < b return 1
    return tda < tdb ? 1 
           // else if a > b return -1
           : tda > tdb ? -1 
           // else they are equal - return 0    
           : 0;           
}).appendTo($tbody);

If you want ascending you just have to reverse the > and <

Change the logic accordingly for you.

FIDDLE

Commit history on remote repository

git isn't a centralized scm like svn so you have two options:

It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.


An example with fetching into a temporary directory:

git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline

Alternatively:

git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master

Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.


An example with GitHub:

GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3

An example with GitLab:

GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3

Both are really fast but have different interfaces (like every platform).


Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement

How to create range in Swift?

I created the following extension:

extension String {
    func substring(from from:Int, to:Int) -> String? {
        if from<to && from>=0 && to<self.characters.count {
            let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
            return self.substringWithRange(rng)
        } else {
            return nil
        }
    }
}

example of use:

print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4))  //Optional("cd")
print("abcde".substring(from: 1, to: 0))  //nil
print("abcde".substring(from: 1, to: 1))  //nil
print("abcde".substring(from: -1, to: 1)) //nil

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

UIButton: set image for selected-highlighted state

In Swift 3.x, you can set highlighted image when button is selected in the following way:

// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal) 

// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)

// Selected state
button.setImage(UIImage(named: "selectedImage"), for:  .selected)

// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"), 
                for:  UIControlState.selected.union(.highlighted))

Replace HTML page with contents retrieved via AJAX

You could try doing

document.getElementById(id).innerHTML = ajax_response

How can I make my match non greedy in vim?

With \v (as suggested in several comments)

:%s/\v(style|class)\=".{-}"//g

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Are (non-void) self-closing tags valid in HTML5?

However -just for the record- this is invalid:

<address class="vcard">
  <svg viewBox="0 0 800 400">
    <rect width="800" height="400" fill="#000">
  </svg>
</address>

And a slash here would make it valid again:

    <rect width="800" height="400" fill="#000"/>

Transparent color of Bootstrap-3 Navbar

The class is .navbar-default. You need to create a class on your custom css .navbar-default.And follow the css code. Also if you don’t want box-shadow on your menu, you can put on the same class.

 .navbar-default {
      background-color:transparent !important;
      border-color:transparent;
      background-image:none;
      box-shadow:none;  
 }

enter image description here

To change font navbar color, the class is to change – .navbar-default .navbar-nav>li>a see the code bellow:

  .navbar-default .navbar-nav>li>a {
     font-size:20px; 
     color:#fff; 
 }

ref : http://twitterbootstrap.org/bootstrap-navbar-background-color-transparent/

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

When your function is deterministic, you are safe to declare it to be deterministic. The location of "DETERMINISTIC" keyword is as follows.

enter image description here

How to compare two List<String> to each other?

You can check in all the below ways for a List

List<string> FilteredList = new List<string>();
//Comparing the two lists and gettings common elements.
FilteredList = a1.Intersect(a2, StringComparer.OrdinalIgnoreCase);

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

Call a child class method from a parent class object

Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:

void caluculate(Person p){
  p.dotheCalculate();
}

This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.

Get dates from a week number in T-SQL

How about a function that jumps to the week before that week number and then steps through the next few days until the week number changes (max 7 steps), returning the new date?

CREATE FUNCTION dbo.fnGetDateFromWeekNo
(@weekNo int , @yearNo  int)
RETURNS smalldatetime
AS
BEGIN 

DECLARE @tmpDate smalldatetime


set @tmpdate= cast(cast (@yearNo as varchar) + '-01-01' as smalldatetime)
-- jump forward x-1 weeks to save counting through the whole year 
set @tmpdate=dateadd(wk,@weekno-1,@tmpdate)

-- make sure weekno is not out of range
if @WeekNo <= datepart(wk,cast(cast (@yearNo as varchar) + '-12-31' as smalldatetime))
BEGIN
    WHILE (datepart(wk,@tmpdate)<@WeekNo)
    BEGIN
        set @tmpdate=dateadd(dd,1,@tmpdate)
    END
END
ELSE
BEGIN
    -- invalid weeknumber given
    set @tmpdate=null
END


RETURN @tmpDate

END

How to extract .war files in java? ZIP vs JAR

Like you said, a jar is a zip file (not a special type, but just a plain old zip), so either library could be made to work. The reasoning is that the average person, seeing a *.zip extension, tends to unzip it. Since the app server wants it unzipped, a simple rename keeps people from unzipping it simply out of habit. Likewise, *.war file also should remain uncompressed.

java.util.jar basically just adds additional functionality to java.util.zip with very little extra overhead. Let the java.util.jar be a helper in posting, etc... and use it.

Java JTable getting the data of the selected row

You can use the following code to get the value of the first column of the selected row of your table.

int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();

make sounds (beep) with c++

std::cout << '\7';

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

  1. Go to the project folder and right click on it -> properties -> check off the read only box and click ok

  2. Right-click on your project and select "Android Tools -> Fix Project Properties"

  3. Right-click on your project and select "Properties -> Java Compiler", check "Enable project specific settings" and select 1.5 or 1.6 from "Compiler compliance settings" select box. (try all the levels one by one just in case)

  4. Under Window -> Preferences -> Java -> Compiler, set Compiler compliance level to 1.6 or 1.5.

Hopefully it will settle the problem.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

How can I fill a div with an image while keeping it proportional?

This should do it:

img {    
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}

Jasmine JavaScript Testing - toBe vs toEqual

Thought someone might like explanation by (annotated) example:

Below, if my deepClone() function does its job right, the test (as described in the 'it()' call) will succeed:

describe('deepClone() array copy', ()=>{
    let source:any = {}
    let clone:any = source
    beforeAll(()=>{
        source.a = [1,'string literal',{x:10, obj:{y:4}}]
        clone = Utils.deepClone(source) // THE CLONING ACT TO BE TESTED - lets see it it does it right.
    })
    it('should create a clone which has unique identity, but equal values as the source object',()=>{
        expect(source !== clone).toBe(true) // If we have different object instances...
        expect(source).not.toBe(clone) // <= synonymous to the above. Will fail if: you remove the '.not', and if: the two being compared are indeed different objects.
        expect(source).toEqual(clone) // ...that hold same values, all tests will succeed.
    })
})

Of course this is not a complete test suite for my deepClone(), as I haven't tested here if the object literal in the array (and the one nested therein) also have distinct identity but same values.

Add disabled attribute to input element using Javascript

$("input").attr("disabled", true); as of... I don't know any more.

It's December 2013 and I really have no idea what to tell you.

First it was always .attr(), then it was always .prop(), so I came back here updated the answer and made it more accurate.

Then a year later jQuery changed their minds again and I don't even want to keep track of this.

Long story short, as of right now, this is the best answer: "you can use both... but it depends."

You should read this answer instead: https://stackoverflow.com/a/5876747/257493

And their release notes for that change are included here:

Neither .attr() nor .prop() should be used for getting/setting value. Use the .val() method instead (although using .attr("value", "somevalue") will continue to work, as it did before 1.6).

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

Or in other words:

".prop = non-document stuff"

".attr" = document stuff

... ...

May we all learn a lesson here about API stability...

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Android Percentage Layout Height

android:layout_weight=".YOURVALUE" is best way to implement in percentage

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/logTextBox"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:maxLines="500"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="@string/logText" >
    </TextView>

</LinearLayout>

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

Difference between StringBuilder and StringBuffer

There are no basic differences between StringBuilder and StringBuffer, only a few differences exist between them. In StringBuffer the methods are synchronized. This means that at a time only one thread can operate on them. If there is more than one thread then the second thread will have to wait for the first one to finish and the third one will have to wait for the first and second one to finish and so on. This makes the process very slow and hence the performance in the case of StringBuffer is low.

On the other hand, StringBuilder is not synchronized. This means that at a time multiple threads can operate on the same StringBuilder object at the same time. This makes the process very fast and hence performance of StringBuilder is high.

Why does intellisense and code suggestion stop working when Visual Studio is open?

Try to install the update 1 package, link. I have had the same problem and solved when I installed the update.

Why an interface can not implement another interface?

Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.

How to override Bootstrap's Panel heading background color?

Bootstrap sometimes uses contextual class constructs. Those are what you should target to change styling.

You don't need to create your own custom class as suggested in the answer from Kiran Varti.

So you only need:

CSS:

.panel-default > .panel-heading {
  background: #black;
}

HTML:

<div class="panel panel-default">

Explanation here. Also see contextual class section here.

To match navbar-inverse use #222. Panel-inverse was requested in V3, but rejected due to larger priorities.

You can change the foreground color in that heading override or you can do it separately for panel titles. Depends what you are trying to achieve.

.panel-title {
  color: white;
}

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

Switch in Laravel 5 - Blade

When you start using switch statements within your views, that usually indicate that you can further re-factor your code. Business logic is not meant for views, I would rather suggest you to do the switch statement within your controller and then pass the switch statements outcome to the view.

Error message "No exports were found that match the constraint contract name"

Deleting the Component Model Cache did not work for me (well, the relative directory given above did not exist in my machine). Instead, I installed an extension to Visual Studio 2012 Express. Menu Tools ? Extensions and Updates... ? Online ? Choose any and then download. This apparently invalidates the cache causing Visual Studio to rebuild it.

Here's my source.

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

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

I had the same problem described by Ashu, but in addition to that, the PATH entry for nodejs was terminated by a backslash:

C:\Program Files\nodejs\

I also had to remove that final backslash in order to have it work.

Only read selected columns

To read a specific set of columns from a dataset you, there are several other options:

1) With freadfrom the data.table-package:

You can specify the desired columns with the select parameter from fread from the data.table package. You can specify the columns with a vector of column names or column numbers.

For the example dataset:

library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))

Alternatively, you can use the drop parameter to indicate which columns should not be read:

dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))

All result in:

> data
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

UPDATE: When you don't want fread to return a data.table, use the data.table = FALSE-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)

2) With read.csv.sql from the sqldf-package:

Another alternative is the read.csv.sql function from the sqldf package:

library(sqldf)
dat <- read.csv.sql("data.txt",
                    sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                    sep = "\t")

3) With the read_*-functions from the readr-package:

library(readr)
dat <- read_table("data.txt",
                  col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                        Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
                  col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                   Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')

From the documentation an explanation for the used characters with col_types:

each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

Static Block in Java

A static block executes once in the life cycle of any program, another property of static block is that it executes before the main method.

Splitting strings in PHP and get last part

This code will do that

<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

How to change the colors of a PNG image easily?

Ok guys it can be done easy in photoshop.

Open png photo and then check image -> mode value(i had indexed color). Go image -> mode and check rgb color. Now change your color EASY.

IOError: [Errno 32] Broken pipe: Python

The problem is due to SIGPIPE handling. You can solve this problem using the following code:

from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL) 

See here for background on this solution. Better answer here.

How to check the installed version of React-Native

The best practice for checking the react native environment information.

react-native info

which will give the information

React Native Environment Info:
System:
  OS: Linux 4.15 Ubuntu 18.04.1 LTS (Bionic Beaver)
  CPU: (8) x64 Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
  Memory: 2.08 GB / 7.67 GB
  Shell: 4.4.19 - /bin/bash
Binaries:
  Node: 8.10.0 - /usr/bin/node
  Yarn: 1.12.3 - /usr/bin/yarn
  npm: 3.5.2 - /usr/bin/npm
npmPackages:
  react: 16.4.1 => 16.4.1 
  react-native: 0.56.0 => 0.56.0 
npmGlobalPackages:
  react-native-cli: 2.0.1
  react-native: 0.57.8

How do I use HTML as the view engine in Express?

to server html pages through routing, I have done this.

var hbs = require('express-hbs');
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');

and renamed my .html files to .hbs files - handlebars support plain html

Serializing enums with Jackson

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

Java Desktop application: SWT vs. Swing

Interesting question. I don't know SWT too well to brag about it (unlike Swing and AWT) but here's the comparison done on SWT/Swing/AWT.

http://www.developer.com/java/other/article.php/10936_2179061_2/Swing-and-SWT-A-Tale-of-Two-Java-GUI-Libraries.htm

And here's the site where you can get tutorial on basically anything on SWT (http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm)

Hope you make a right decision (if there are right decisions in coding)... :-)

Calculating how many minutes there are between two times

If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):

// Default value that is returned is of type *double* 
double double_minutes = endTime.Subtract(startTime).TotalMinutes; 
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes; 
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes; 
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes; 

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

Input mask for numeric and decimal

You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:

HTML

<input class="numeric" type="text" />

Javascript

$(".numeric").numeric({ decimal : ".",  negative : false, scale: 3 });

This is the whole source.
And I've prepared this fiddle so you can see how it works.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Good to also check the other combinators in the family and to get back to what is this specific one.

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

Example checklist:

  • ul li - Looking inside - Selects all the li elements placed (anywhere) inside the ul; Descendant selector
  • ul > li - Looking inside - Selects only the direct li elements of ul; i.e. it will only select direct children li of ul; Child Selector or Child combinator selector
  • ul + ul - Looking outside - Selects the ul immediately following the ul; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selector
  • ul ~ ul - Looking outside - Selects all the ul which follows the ul doesn't matter where it is, but both ul should be having the same parent; General Sibling Selector

The one we are looking at here is General Sibling Selector

What does href expression <a href="javascript:;"></a> do?

    1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
    2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows

<div class="table-cell">
    <span id="clearRow{id}">
        <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Clear</a>
    </span>
</div>

<div class="table-cell">
   <span id="deleteRow{id}">
       <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Delete</a>
   </span>
</div>

//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
});

//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
    //depending upon levels of parent / child use 1 to many .parent().parent().parent()
    $(this).parent().remove();
});

Getting Checkbox Value in ASP.NET MVC 4

I ran into a similar issue and was able to get the checkbox value back by using a checkbox, hiddenfor and little JQuery like so:

@Html.CheckBox("isPreferred", Model.IsPreferred)
@Html.HiddenFor(m => m.IsPreferred)

<script>

    $("#isPreferred").change(function () {

        $("#IsPreferred").val($("#isPreferred").val());

    })

</script>

tsc throws `TS2307: Cannot find module` for a local file

Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"

Date difference in years using C#

Simple solution:

public int getYearDiff(DateTime startDate, DateTime endDate){
    int y = Year(endDate) - Year(startDate);
    int startMonth = Month(startDate);
    int endMonth = Month(endDate);
    if (endMonth < startMonth) 
        return y - 1;
    if (endMonth > startMonth) 
        return y;
    return (Day(endDate) < Day(startDate) ? y - 1 : y);
}

Write objects into file with Node.js

Just incase anyone else stumbles across this, I use the fs-extra library in node and write javascript objects to a file like this:

const fse = require('fs-extra');
fse.outputJsonSync('path/to/output/file.json', objectToWriteToFile); 

Floating Point Exception C++ Why and what is it?

Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

How do you rename a Git tag?

You can also rename remote tags without checking them out, by duplicate the old tag/branch to a new name and delete the old one, in a single git push command.

Remote tag rename / Remote branch ? tag conversion: (Notice: :refs/tags/)

git push <remote_name> <old_branch_or_tag>:refs/tags/<new_tag> :<old_branch_or_tag>

Remote branch rename / Remote tag ? branch conversion: (Notice: :refs/heads/)

git push <remote_name> <old_branch_or_tag>:refs/heads/<new_branch> :<old_branch_or_tag>

Output renaming a remote tag:

D:\git.repo>git push gitlab App%2012.1%20v12.1.0.23:refs/tags/App_12.1_v12.1.0.23 :App%2012.1%20v12.1.0.23

Total 0 (delta 0), reused 0 (delta 0)
To https://gitlab.server/project/repository.git
 - [deleted]               App%2012.1%20v12.1.0.23
 * [new tag]               App%2012.1%20v12.1.0.23 -> App_12.1_v12.1.0.23

How to remove list elements in a for loop in Python?

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you're trying to do.

For example, your code is equivalent to:

for item in a:
  print item
a[:] = []

Alternatively, you could use a while loop:

while a:
  print a.pop(0)

I'm trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn't match the condition into a second list:

result = []
for item in a:
  if condition is False:
    result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

Refreshing data in RecyclerView and keeping its scroll position

If you have one or more EditTexts inside of a recyclerview items, disable the autofocus of these, putting this configuration in the parent view of recyclerview:

android:focusable="true"
android:focusableInTouchMode="true"

I had this issue when I started another activity launched from a recyclerview item, when I came back and set an update of one field in one item with notifyItemChanged(position) the scroll of RV moves, and my conclusion was that, the autofocus of EditText Items, the code above solved my issue.

best.

How to remove leading and trailing whitespace in a MySQL field?

You can use the following sql, UPDATE TABLE SET Column= replace(Column , ' ','')

How to export data to CSV in PowerShell?

This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.

$results = @()
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation

If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.

This is why I create a new object first.

Try the following:

write-output "test" | convertto-csv -NoTypeInformation

This will give you:

"Length"
"4"

If you use the Get-Member on Write-Output as follows:

write-output "test" | Get-Member -MemberType Property

You will see that it has one property - 'length':

   TypeName: System.String

Name   MemberType Definition
----   ---------- ----------
Length Property   System.Int32 Length {get;}

This is why Length will be written to the csv file.


Update: Appending a CSV Not the most efficient way if the file gets large...

$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
    $results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path $csvFileName -NoTypeInformation

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How to move all files including hidden files into parent directory via *

By using the find command in conjunction with the mv command, you can prevent the mv command from trying to move directories (e.g. .. and .) and subdirectories. Here's one option:

find /path/subfolder -maxdepth 1 -type f -name '*' -exec mv -n {} /path \;

There are problems with some of the other answers provided. For example, each of the following will try to move subdirectories from the source path:

1) mv /path/subfolder/* /path/ ; mv /path/subfolder/.* /path/
2) mv /path/subfolder/{.,}* /path/ 
3) mv /source/path/{.[!.],}* /destination/path

Also, 2) includes the . and .. files and 3) misses files like ..foobar, ...barfoo, etc.

You could use, mv /source/path/{.[!.],..?,}* /destination/path, which would include the files missed by 3), but it would still try to move subdirectories. Using the find command with the mv command as I describe above eliminates all these problems.

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Get path of executable

I'm not sure about Linux, but try this for Windows:

#include <windows.h>
#include <iostream>

using namespace std ;

int main()
{
     char ownPth[MAX_PATH]; 

     // When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
     HMODULE hModule = GetModuleHandle(NULL);
     if (hModule != NULL)
     {
         // Use GetModuleFileName() with module handle to get the path
         GetModuleFileName(hModule, ownPth, (sizeof(ownPth))); 
         cout << ownPth << endl ;
         system("PAUSE");
         return 0;
     }
     else
     {
         cout << "Module handle is NULL" << endl ;
         system("PAUSE");
         return 0;
     }
}

How to replace item in array?

Here's a one liner. It assumes the item will be in the array.

_x000D_
_x000D_
var items = [523, 3452, 334, 31, 5346]_x000D_
var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr)_x000D_
console.log(replace(items, 3452, 1010))
_x000D_
_x000D_
_x000D_

How do I search for files in Visual Studio Code?

To search for specifil file types in visual studio code.
Type ctrl+p and then search for something like *.py.
Simple and easy

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It causes the error when you access $(this).val() when it called by change event this points to the invoker i.e. CourseSelect so it is working and and will get the value of CourseSelect. but when you manually call it this points to document. so either you will have to pass the CourseSelect object or access directly like $("#CourseSelect").val() instead of $(this).val().

CAML query with nested ANDs and ORs for multiple fields

This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:

        private static void Main(string[] args)
        {
            var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
            var whereClause =
                new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
            var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");

            string[] values = {"1", "2", "3", "4", "5", "6"};

            query["WhereClauses"] = NestEq(whereClause, andClause, values);

            Console.WriteLine(query);
        }

And here's the code:

   private static string MakeExpression(PropertyString nestClause, string value)
        {
            var expr = nestClause.New();
            expr["NestClauseValue"] = value;
            return expr.ToString();
        }

        /// <summary>
        /// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
        /// </summary>
        /// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
        /// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
        /// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
        public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
        {
            if (pos > nestClauseValues.Length)
            {
                return "";
            }

            if (nestClauseValues.Length == 1)
            {
                return MakeExpression(whereClause, nestClauseValues[0]);
            }

            var expr = nestingExpression.New();
            if (pos == nestClauseValues.Length - 2)
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
                return expr.ToString();
            }
            else
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
                return expr.ToString();
            }
        }






          public class PropertyString
    {
        private string _propStr;

        public PropertyString New()
        {
            return new PropertyString(_propStr );
        }

        public PropertyString(string propStr)
        {
            _propStr = propStr;
            _properties = new Dictionary<string, string>();
        }

        private Dictionary<string, string> _properties;
        public string this[string key]
        {
            get
            {
                return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
            }
            set
            {
                if (_properties.ContainsKey(key))
                {
                    _properties[key] = value;
                }
                else
                {
                    _properties.Add(key, value);
                }
            }
        }



        /// <summary>
        /// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you 
        /// </summary>
        /// <param name="originalStr"></param>
        /// <param name="keyValuePairPropertiesDictionary"></param>
        /// <returns></returns>
        public override string ToString()
        {
            string modifiedStr = _propStr;
            foreach (var keyvaluePair in _properties)
            {
                modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
            }

            return modifiedStr;
        }
    }

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

How do you run a single test/spec file in RSpec?

To run all of your rspec files: rspec

note: you must be in the root of your project

To run one rspec file: rspec 'path_to/spec.rb'

note: replace 'path_to/spec.rb' with your path. Quotation marks optional.

To run one rspec test from one file: rspec 'path_to/spec.rb:7'

note: :7 is the line number where the test starts

Error handling in getJSON calls

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

How do I get the base URL with PHP?

function server_url(){
    $server ="";

    if(isset($_SERVER['SERVER_NAME'])){
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/');
    }
    else{
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/');
    }
    print $server;

}

How to select between brackets (or quotes or ...) in Vim?

Use whatever navigation key you want to get inside the parentheses, then you can use either yi( or yi) to copy everything within the matching parens. This also works with square brackets (e.g. yi]) and curly braces. In addition to y, you can also delete or change text (e.g. ci), di]).

I tried this with double and single-quotes and it appears to work there as well. For your data, I do:

write (*, '(a)') 'Computed solution coefficients:'

Move cursor to the C, then type yi'. Move the cursor to a blank line, hit p, and get

Computed solution coefficients:

As CMS noted, this works for visual mode selection as well - just use vi), vi}, vi', etc.

Convert PDF to image with high resolution

It appears that the following works:

convert           \
   -verbose       \
   -density 150   \
   -trim          \
    test.pdf      \
   -quality 100   \
   -flatten       \
   -sharpen 0x1.0 \
    24-18.jpg

It results in the left image. Compare this to the result of my original command (the image on the right):

  

(To really see and appreciate the differences between the two, right-click on each and select "Open Image in New Tab...".)

Also keep the following facts in mind:

  • The worse, blurry image on the right has a file size of 1.941.702 Bytes (1.85 MByte). Its resolution is 3060x3960 pixels, using 16-bit RGB color space.
  • The better, sharp image on the left has a file size of 337.879 Bytes (330 kByte). Its resolution is 758x996 pixels, using 8-bit Gray color space.

So, no need to resize; add the -density flag. The density value 150 is weird -- trying a range of values results in a worse looking image in both directions!

Putting HTML inside Html.ActionLink(), plus No Link Text?

Here is an uber expansion of @tvanfosson's answer. I was inspired by it and decide to make it more generic.

    public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName,
        string controllerName, object routeValues = null, object htmlAttributes = null,
        RouteValueDictionary childElements = null)
    {
        var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (childElements != null)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            var anchorTag = new TagBuilder("a");
            anchorTag.MergeAttribute("href",
                routeValues == null
                    ? urlHelper.Action(actionName, controllerName)
                    : urlHelper.Action(actionName, controllerName, routeValues));
            anchorTag.MergeAttributes(htmlAttributesDictionary);
            TagBuilder childTag = null;

            if (childElements != null)
            {
                foreach (var childElement in childElements)
                {
                    childTag = new TagBuilder(childElement.Key.Split('|')[0]);
                    object elementAttributes;
                    childElements.TryGetValue(childElement.Key, out elementAttributes);

                    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes);

                    foreach (var attribute in attributes)
                    {
                        switch (attribute.Key)
                        {
                            case "@class":
                                childTag.AddCssClass(attribute.Value.ToString());
                                break;
                            case "InnerText":
                                childTag.SetInnerText(attribute.Value.ToString());
                                break;
                            default:
                                childTag.MergeAttribute(attribute.Key, attribute.Value.ToString());
                                break;
                        }
                    }
                    childTag.ToString(TagRenderMode.SelfClosing);
                    if (childTag != null) anchorTag.InnerHtml += childTag.ToString();
                }                    
            }
            return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary);
        }
    }

How to set opacity in parent div and not affect in child div?

You can do it with pseudo-elements: (demo on dabblet.com) enter image description here

your markup:

<div class="parent">
    <div class="child"> Hello I am child </div>
</div>

css:

.parent{
    position: relative;
}

.parent:before {
    z-index: -1;
    content: '';
    position: absolute;

    opacity: 0.2;
    width: 400px;
    height: 200px;
    background: url('http://img42.imageshack.us/img42/1893/96c75664f7e94f9198ad113.png') no-repeat 0 0; 
}

.child{
    Color:black;
}

How can I show a hidden div when a select option is selected?

<select id="test" name="form_select" onchange="showDiv()">
   <option value="0">No</option>
   <option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
<script>
    function showDiv(){
        getSelectValue = document.getElementById("test").value;
        if(getSelectValue == "1"){
            document.getElementById("hidden_div").style.display="block";
        }else{
            document.getElementById("hidden_div").style.display="none";
        }
    }
</script>

What causing this "Invalid length for a Base-64 char array"

Take a look at your HttpHandlers. I've been noticing some weird and completely random errors over the past few months after I implemented a compression tool (RadCompression from Telerik). I was noticing errors like:

  • System.Web.HttpException: Unable to validate data.

  • System.Web.HttpException: The client disconnected.---> System.Web.UI.ViewStateException: Invalid viewstate.

and

  • System.FormatException: Invalid length for a Base-64 char array.

  • System.Web.HttpException: The client disconnected. ---> System.Web.UI.ViewStateException: Invalid viewstate.

I wrote about this on my blog.

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

What are the most common naming conventions in C?

Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.

First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.

Then, the convention:

  • Any names MUST be a readable sentence explaining what you have. Like "this is my convention".
  • Then, 4 methods to get a convention out of a sentence:
    1. THIS_IS_MY_CONVENTION for macros, enum members
    2. ThisIsMyConvention for file name, object name (class, struct, enum, union...), function name, method name, typedef
    3. this_is_my_convention global and local variables,
      parameters, struct and union elements
    4. thisismyconvention [optional] very local and temporary variables (such like a for() loop index)

And that's it.

It gives

class MyClass {
    enum TheEnumeration {
        FIRST_ELEMENT,
        SECOND_ELEMENT,
    }

    int class_variable;

    int MyMethod(int first_param, int second_parameter) {
        int local_variable;
        TheEnumeration local_enum;
        for(int myindex=0, myindex<class_variable, myindex++) {
             localEnum = FIRST_ELEMENT;
        }
    }
}

Server Error in '/' Application. ASP.NET

http://www.velocityreviews.com/forums/t123353-configuration-error.html


If you want to use inetpub/wwwroot/aspnet as your application, remove this line :

Line 26: and any other lines which define MachineToApplication beyond application level

If you want to use d:\inetpub\wwwroot\aspnet\begin\chapter02\ as your application, create an IIS Application which points to d:\inetpub\wwwroot\aspnet\begin\chapter02\


maybe you can refer link above. For my application, my web.config store in d:\inetpub\wwwroot\aspnet\begin\chapter02\ and when i move the web.config to d:\inetpub\wwwroot\aspnet and the problem is solve. Please check also does your application have two web.config file.

Calling the base constructor in C#

As per some of the other answers listed here, you can pass parameters into the base class constructor. It is advised to call your base class constructor at the beginning of the constructor for your inherited class.

public class MyException : Exception
{
    public MyException(string message, string extraInfo) : base(message)
    {
    }
}

I note that in your example you never made use of the extraInfo parameter, so I assumed you might want to concatenate the extraInfo string parameter to the Message property of your exception (it seems that this is being ignored in the accepted answer and the code in your question).

This is simply achieved by invoking the base class constructor, and then updating the Message property with the extra info.

public class MyException: Exception
{
    public MyException(string message, string extraInfo) : base($"{message} Extra info: {extraInfo}")
    {
    }
}

How to run an EXE file in PowerShell with parameters with spaces and quotes

See this page: https://slai.github.io/posts/powershell-and-external-commands-done-right/

Summary using vshadow as the external executable:

$exe = "H:\backup\scripts\vshadow.exe"
&$exe -p -script=H:\backup\scripts\vss.cmd E: M: P:

How to use underscore.js as a template engine?

<!-- Install jQuery and underscore -->

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>

<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <%
        // repeat items 
        _.each(items,function(item,key,list){
          // create variables
          var f = item.name.split("").shift().toLowerCase();
      %>
        <tr>
          <!-- use variables -->
          <td><%= key %></td>
          <td class="<%= f %>">
            <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
            <h3><%- item.name %></h3>
            <p><%- item.interests %></p>
          </td>
        </tr>
      <%
        });
      %>
    </tbody>
  </table>
</script>

<!-- Create your target -->

<div id="target"></div>

<!-- Write some code to fetch the data and apply template -->

<script type="text/javascript">
  var items = [
    {name:"Alexander", interests:"creating large empires"},
    {name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
    {name:"..."},
    {name:"Yolando", interests:"working out"},
    {name:"Zachary", interests:"picking flowers for Angela"}
  ];
  var template = $("#usageList").html();
  $("#target").html(_.template(template,{items:items}));
</script>
  • JsFiddle Thanks @PHearst!
  • JsFiddle (latest)
  • JsFiddle List grouped by first letter (complex example w/ images, function calls, sub-templates) fork it! have a blast...
  • JsFiddle Demo of XSS hack noted by @tarun_telang below
  • JsFiddle One non-standard method to do sub-templates

When should I use git pull --rebase?

One practice case is when you are working with Bitbucket PR. There is PR open.

Then you decide to rebase the PR remote branch on the latest Master branch. This will change the commit's ids of your PR.

Then you want to add a new commit to the PR branch.

Since you have rebased the remote branch using GUI first you to sync the local branch on PC with the remote branch.

In this case git pull --rebase works like magic.

After git pull --rebase your remote branch and local branch has same history with same commit ids.

Now you can nicely push a new commit without using force or anything.

How to return JSON with ASP.NET & jQuery

You're not far; you need to do something like this:

[WebMethod]
public static string GetProducts()
{
  // instantiate a serializer
  JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

  //optional: you can create your own custom converter
  TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});

  var products = context.GetProducts().ToList();   

  var TheJson = TheSerializer.Serialize(products);

  return TheJson;
}

You can reduce this code further but I left it like that for clarity. In fact, you could even write this:

return context.GetProducts().ToList();

and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer works just fine out of the box.

Get safe area inset top and bottom heights

Swift 5, Xcode 11.4

`UIApplication.shared.keyWindow` 

It will give deprecation warning. ''keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes' because of connected scenes. I use this way.

extension UIView {

    var safeAreaBottom: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.bottom
            }
         }
         return 0
    }

    var safeAreaTop: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.top
            }
         }
         return 0
    }
}

extension UIApplication {
    var keyWindowInConnectedScenes: UIWindow? {
        return windows.first(where: { $0.isKeyWindow })
    }
}

Default port for SQL Server

We can take a look at three different ways you can identify the port used by an instance of SQL Server.

  1. Reading SQL Server Error Logs
  2. Using SQL Server Configuration Manager
  3. Using Windows Application Event Viewer

    USE master
    GO

    xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc'
    GO

Identify Port used by SQL Server Database Engine Using SQL Server Configuration Manager

  1. Click Start -> Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager

  2. In SQL Server Configuration Manager, expand SQL Server Network Configuration and then select Protocols for on the left panel. To identify the TCP/IP Port used by the SQL Server Instance, right click onTCP/IP and select Properties from the drop down as shown below.

For More Help
http://sqlnetcode.blogspot.com/2011/11/sql-server-identify-tcp-ip-port-being.html

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

Set value for particular cell in pandas DataFrame with iloc

If you know the position, why not just get the index from that?

Then use .loc:

df.loc[index, 'COL_NAME'] = x

How to access full source of old commit in BitBucket?

Step 1

Step 1


Step 2

Step 2


Step 3

Step 3


Step 4

Step 4


Final Step

Final Step

adb shell su works but adb root does not

I have a rooted Samsung Galaxy Trend Plus (GT-S7580).

Running 'adb root' gives me the same 'adbd cannot run as root in production builds' error.

For devices that have Developer Options -> Root access, choose "ADB only" to provide adb root access to the device (as suggested by NgaNguyenDuy).

Then try to run the command as per the solution at Launch a script as root through ADB. In my case, I just wanted to run the 'netcfg rndis0 dhcp' command, and I did it this way:

adb shell "su -c netcfg rndis0 dhcp"

Please check whether you are making any mistakes while running it this way.

If it still does not work, check whether you rooted the device correctly. If still no luck, try installing a custom ROM such as Cyanogen Mod in order for 'adb root' to work.

Call to undefined function oci_connect()

  1. Check your php –version as like as PHP 5.6.32 (cli) (built: Oct 25 2017 16:02:15).
  2. Using the OCI8 extension to access Oracle Database. So Download php_oci8.dll from 1https://pecl.php.net/package/oci8/2.0.8/windows. (5.6 Thread Safe (TS) x86 ) php_oci8.dll must be the same version with your php version.Then unzipped it and you will find 1.php_oci8.dll 2.php_oci8_11g.dll (as per your oralce version) these two file pasted into your
    (xampp\php\ext) folder.

  3. Open your php.ini file and add these extension=php_oci8.dll extension=php_oci8_11g.dll

  4. Check your oracle version and service name using these commands

    1. Open your cmd
    2. sqlplus / as sysdba
    3. select * from v$version; Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production, our oracle version is 11g so we can use instantclient_11_1 (Instant Client 32-bit) downloads from https://www.oracle.com/technetwork/topics/winsoft-085727.html
  5. show parameter service_name; service_name is orcl (you should remember this service name)

  6. After downloading instantclient_11_1 unzipped it and then pasted in your Local Disk. And copy the path C:\instantclient_11_1 and then set this path as your user variable & system variable. Note is that my code is working without setting path variable.

  7. Open your cmd and enter into SQL, create your schema following these commands

    1. sqlplus / as sysdba
    2. create user dbname identified by pass123;
    3. grant connect,resource to dbname;

    4. Create table user_info and insert data into your table and commit out. Note: you must commit your data either data is not inserted.

    5. Then this script run in your htdocs

_x000D_
_x000D_
<html>_x000D_
<head><title>Oracle demo</title></head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
// Create connection to Oracle_x000D_
$conn = oci_connect("dbname", "pass123", "//localhost/orcl");  // orcl is your service_name_x000D_
_x000D_
$query = 'select * from user_info';_x000D_
$stid = oci_parse($conn, $query);_x000D_
$r = oci_execute($stid);_x000D_
_x000D_
// Fetch each row in an associative array_x000D_
print '<table border="1">';_x000D_
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {_x000D_
   print '<tr>';_x000D_
   foreach ($row as $item) {_x000D_
       print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '&nbsp').'</td>';_x000D_
   }_x000D_
   print '</tr>';_x000D_
}_x000D_
print '</table>';
_x000D_
_x000D_
_x000D_

Install Node.js on Ubuntu

As of today, you can simply install it with:

sudo apt-get install nodejs

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

How do I calculate percentiles with python/numpy?

check for scipy.stats module:

 scipy.stats.scoreatpercentile

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

Kill a Process by Looking up the Port being used by it from a .BAT

If anyone is looking for a Powershell Script:

function Search-And-Destroy
{
    param ( [Parameter(Mandatory=$true)][string]$port )
    $lines = netstat -a -o -n | findstr $port
    $ports = @()

    ForEach($line In $lines)
    {
        $res = $($lines -split '\s+')
        $ports += $res[5]
    }

    $ports = $ports | select -uniq

    ForEach($port In $ports)
    {
        echo $(taskkill /F /PID $port)
    }
}

This function basically does what the above functions do, but it is in the Powershell scripting format so you can add it to your Powershell profile. To find your profile's location go to powershell and type echo $profile

What is a word boundary in regex, does \b match hyphen '-'?

A word boundary can occur in one of three positions:

  1. Before the first character in the string, if the first character is a word character.
  2. After the last character in the string, if the last character is a word character.
  3. Between two characters in the string, where one is a word character and the other is not a word character.

Word characters are alpha-numeric; a minus sign is not. Taken from Regex Tutorial.

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

Forwarding port 80 to 8080 using NGINX

This is how you can achieve this.

upstream {
    nodeapp 127.0.0.1:8080;
}

server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location /(.*) {
        proxy_pass http://nodeapp/$1$is_args$args;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Port $server_port;
        proxy_set_header X-Real-Scheme $scheme;
    }
}

You can also use this configuration to load balance amongst multiple Node processes like so:

upstream {
    nodeapp 127.0.0.1:8081;
    nodeapp 127.0.0.1:8082;
    nodeapp 127.0.0.1:8083;
}

Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.

Ansible: How to delete files and folders inside a directory?

Using shell module (idempotent too):

- shell: /bin/rm -rf /home/mydata/web/*

If there are dot/hidden files:

- shell: /bin/rm -rf /home/mydata/web/* /home/mydata/web/.*

Cleanest solution if you don't care about creation date and owner/permissions:

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

fatal error LNK1104: cannot open file 'kernel32.lib'

Today in Visual Studio 2017 I had the same problem.

The cause in my case turned out to be a bad environment setting in NETFXSDKDir (NETFXSDKDir=C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1). It needs to be instead NETFXSDKDir=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. Specifically, as set in this batch file (my directory actually has 4 different files) for the Command Prompt for VS2017:

%comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvars32.bat"

as I am reluctant to change one of the "as installed" batch files… even more as that batch file calls another yet another:

@call "%~dp0vcvarsall.bat" x86 %*

...instead for my specific C++ command-line app, I simply added the explicit path text: ;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 for a total string in "Library Directories" like this: $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. (Right click on project, Properties → Configuration Properties → VC++ Directories → Library Directories.) That resolved my "fatal error LNK1104: cannot open file 'kernel32.lib'" error. I found that hint in this GitHub issue.

Note this is reproducible in Visual Studio 2017 Enterprise 2017 Version 15.1 (26403.0) even after successful "repair" install… when creating a new Visual C++ Win32 Console Application and attempting to compile.

In fact, unless a blank application is created, the default template also includes reference to <SDKDDKVer.h> and with that I get this additional error: Error (active) E1696 cannot open source file "SDKDDKVer.h". So I created an empty C++ project.

Count number of rows per group and add result to original data frame

Using sqldf package:

library(sqldf)

sqldf("select a.*, b.cnt
       from df a,
           (select name, type, count(1) as cnt
            from df
            group by name, type) b
      where a.name = b.name and
            a.type = b.type")

#    name  type num cnt
# 1 black chair   4   2
# 2 black chair   5   2
# 3 black  sofa  12   1
# 4   red  sofa   4   1
# 5   red plate   3   1

jQuery: Clearing Form Inputs

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Original Answer: Resetting a multi-stage form with jQuery


Mike's suggestion (from the comments) to keep checkbox and selects intact!

Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

How to add a spinner icon to button when it's in the Loading state?

These are mine, based on pure SVG and CSS animations. Don't pay attention to JS code in the snippet bellow, it's just for demoing purposes. Feel free to make your custom ones basing on mine, it's super easy.

_x000D_
_x000D_
var svg = d3.select("svg"),_x000D_
    columnsCount = 3;_x000D_
_x000D_
['basic', 'basic2', 'basic3', 'basic4', 'loading', 'loading2', 'spin', 'chrome', 'chrome2', 'flower', 'flower2', 'backstreet_boys'].forEach(function(animation, i){_x000D_
  var x = (i%columnsCount+1) * 200-100,_x000D_
      y = 20 + (Math.floor(i/columnsCount) * 200);_x000D_
  _x000D_
  _x000D_
  svg.append("text")_x000D_
    .attr('text-anchor', 'middle')_x000D_
    .attr("x", x)_x000D_
    .attr("y", y)_x000D_
    .text((i+1)+". "+animation);_x000D_
  _x000D_
  svg.append("circle")_x000D_
    .attr("class", animation)_x000D_
    .attr("cx",  x)_x000D_
    .attr("cy",  y+40)_x000D_
    .attr("r",  16)_x000D_
});
_x000D_
circle {_x000D_
  fill: none;_x000D_
  stroke: #bbb;_x000D_
  stroke-width: 4_x000D_
}_x000D_
_x000D_
.basic {_x000D_
  animation: basic 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 80;_x000D_
}_x000D_
_x000D_
@keyframes basic {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic2 {_x000D_
  animation: basic2 0.5s linear infinite;_x000D_
  stroke-dasharray: 80 20;_x000D_
}_x000D_
_x000D_
@keyframes basic2 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic3 {_x000D_
  animation: basic3 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 30;_x000D_
}_x000D_
_x000D_
@keyframes basic3 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic4 {_x000D_
  animation: basic4 0.5s linear infinite;_x000D_
  stroke-dasharray: 10 23.3;_x000D_
}_x000D_
_x000D_
@keyframes basic4 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.loading {_x000D_
  animation: loading 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes loading {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 50 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 50;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 50 0;}_x000D_
}_x000D_
_x000D_
.loading2 {_x000D_
  animation: loading2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes loading2 {_x000D_
  0% {stroke-dasharray: 5 28.3;   stroke-dashoffset: 75;}_x000D_
  50% {stroke-dasharray: 45 5;    stroke-dashoffset: -50;}_x000D_
  100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -125; }_x000D_
}_x000D_
_x000D_
.spin {_x000D_
  animation: spin 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 33.3 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 33.3;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 33.3 0;}_x000D_
}_x000D_
_x000D_
.chrome {_x000D_
  animation: chrome 2s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 75 25; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -125;}_x000D_
  75%    {stroke-dasharray: 75 25; stroke-dashoffset: -150;}_x000D_
  100%   {stroke-dasharray: 0 100; stroke-dashoffset: -275;}_x000D_
}_x000D_
_x000D_
.chrome2 {_x000D_
  animation: chrome2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome2 {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 50 50; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -50;}_x000D_
  75%   {stroke-dasharray: 50 50;  stroke-dashoffset: -125;}_x000D_
  100%  {stroke-dasharray: 0 100;  stroke-dashoffset: -175;}_x000D_
}_x000D_
_x000D_
.flower {_x000D_
  animation: flower 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower {_x000D_
  0%    {stroke-dasharray: 0  20; stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 0;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 0 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.flower2 {_x000D_
  animation: flower2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower2 {_x000D_
  0%    {stroke-dasharray: 5 20;  stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 5;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 5 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.backstreet_boys {_x000D_
  animation: backstreet_boys 3s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes backstreet_boys {_x000D_
  0%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -225;}_x000D_
  15%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -300;}_x000D_
  30%   {stroke-dasharray: 5 20;  stroke-dashoffset: -300;}_x000D_
  45%    {stroke-dasharray: 5 20;  stroke-dashoffset: -375;}_x000D_
  60%   {stroke-dasharray: 5 15;  stroke-dashoffset: -375;}_x000D_
  75%    {stroke-dasharray: 5 15;  stroke-dashoffset: -450;}_x000D_
  90%   {stroke-dasharray: 5 15;  stroke-dashoffset: -525;}_x000D_
  100%   {stroke-dasharray: 5 28.3;  stroke-dashoffset: -925;}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>_x000D_
<svg width="600px" height="700px"></svg>
_x000D_
_x000D_
_x000D_

Also available on CodePen: https://codepen.io/anon/pen/PeRazr

How to pass objects to functions in C++?

Do I need to pass pointers, references, or non-pointer and non-reference values?

This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.

The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &, is needed.

For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *.

How to create a directive with a dynamic template in AngularJS?

You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

It can be use like this:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

How can I enable the Windows Server Task Scheduler History recording?

The adjustment in the Task Scheduler app actually just controls the enabled state of a certain event log, so you can equivalently adjust the Task Scheduler "history" mode via the Windows command line:

wevtutil set-log Microsoft-Windows-TaskScheduler/Operational /enabled:true

To check the current state:

wevtutil get-log Microsoft-Windows-TaskScheduler/Operational

For the keystroke-averse, here are the slightly abbreviated versions of the above:

wevtutil sl Microsoft-Windows-TaskScheduler/Operational /e:true
wevtutil gl Microsoft-Windows-TaskScheduler/Operational

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

Why use pointers?

In C++, if you want to use subtype polymorphism, you have to use pointers. See this post: C++ Polymorphism without pointers.

Really, when you think about it, this makes sense. When you use subtype polymorphism, ultimately, you don't know ahead of time which class's or subclass's implementation of the method will be invoked because you don't know what the actual class is.

This idea of having a variable that holds an object of an unknown class is incompatible with C++'s default (non-pointer) mode of storing objects on the stack, where the amount of space allocated directly corresponds to the class. Note: if a class has 5 instance fields versus 3, more space will need to be allocated.


Note that if you are using '&' to pass arguments by reference, indirection (i.e., pointers) is still involved behind the scenes. The '&' is just syntactic sugar that (1) saves you the trouble of using pointer syntax and (2) allows the compiler to be more strict (such as prohibiting null pointers).

OAuth: how to test with local URLs?

Set your local domain to mywebsite.example.com (and redirect it to localhost) -- even though the usual is to use mywebsite.dev. This will allow robust automatic testing.

Although authorizing .test and .dev is not allowed, authorizing example.com is allowed in google oauth2.

(You can redirect any domain to localhost in your hosts file (unix/linux: /etc/hosts))

Why mywebsite.example.com?
Because example.com is a reserved domain name. So

  1. there would be no naming conflicts on your machine.
  2. no data-risk if your test system exposes data to not-redirected-by-mistake.example.com.

How can I solve ORA-00911: invalid character error?

I encountered the same thing lately. it was just due to spaces when copying a script from a document to sql developer. I had to remove the spaces and the script ran.

SQL Server Creating a temp table for this query

Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.

SELECT  
    tblMEP_Sites.Name AS SiteName, 
    convert(varchar(10),BillingMonth ,101) AS BillingMonth, 
    SUM(Consumption) AS Consumption
INTO 
    #MyTempTable
FROM 
    tblMEP_Projects
    JOIN tblMEP_Sites
        ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
    JOIN tblMEP_Meters
        ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
    JOIN tblMEP_MonthlyData
        ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
    JOIN tblMEP_CustomerAccounts
        ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
    JOIN tblMEP_UtilityCompanies
        ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
    JOIN tblMEP_MeterTypes
        ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE 
    tblMEP_Projects.ID = @ProjectID
    AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
    AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY 
    BillingMonth, tblMEP_Sites.Name

DROP TABLE #MyTempTable

Can I use a case/switch statement with two variables?

If the action of each combination is static, you could build a two-dimensional array:

var data = [
  [1,2,3,4,5],
  [6,7,8,9,10],
  [11,12,13,14,15],
  [16,17,18,19,20],
  [21,22,23,24,25]
];

The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):

var info = data[firstSliderValue][secondSliderValue];

How do I add a resources folder to my Java project in Eclipse

When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder enter image description here

add "my-resource.txt" file inside the new folder. Then in your code:

    InputStream res =
    Main.class.getResourceAsStream("/my-resource.txt");

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(res));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();

Download a file with Android, and showing the progress in a ProgressDialog

Important

AsyncTask is deprecated in Android 11.

For more information please checkout following posts

Probably should move to concorency Framework as suggested by google

Relay access denied on sending mail, Other domain outside of network

Configuring $mail->SMTPAuth = true; was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.

The simplest way to comma-delimit a list?

Because your delimiter is ", " you could use any of the following:

public class StringDelim {

    public static void removeBrackets(String string) {
        System.out.println(string.substring(1, string.length() - 1));
    }

    public static void main(String... args) {
        // Array.toString() example
        String [] arr = {"Hi" , "My", "name", "is", "br3nt"};
        String string = Arrays.toString(arr);
        removeBrackets(string);

        // List#toString() example
        List<String> list = new ArrayList<String>();
        list.add("Hi");
        list.add("My");
        list.add("name");
        list.add("is");
        list.add("br3nt");
        string = list.toString();
        removeBrackets(string);

        // Map#values().toString() example
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("1", "Hi");
        map.put("2", "My");
        map.put("3", "name");
        map.put("4", "is");
        map.put("5", "br3nt");
        System.out.println(map.values().toString());
        removeBrackets(string);

        // Enum#toString() example
        EnumSet<Days> set = EnumSet.allOf(Days.class);
        string = set.toString();
        removeBrackets(string);
    }

    public enum Days {
        MON("Monday"),
        TUE("Tuesday"),
        WED("Wednesday"),
        THU("Thursday"),
        FRI("Friday"),
        SAT("Saturday"),
        SUN("Sunday");

        private final String day;

        Days(String day) {this.day = day;}
        public String toString() {return this.day;}
    }
}

If your delimiter is ANYTHING else then this isn't going to work for you.

Where is SQLite database stored on disk?

.databases

If you run this command inside SQLite

.databases

it lists the path of all currently connected databases. Sample output:

seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /home/me/a.db

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Windows Scipy Install: No Lapack/Blas Resources Found

My 5 cents; You can just install the entire (pre-compiled) SciPy from https://github.com/scipy/scipy/releases

Good Luck!

How to get the ASCII value of a character

Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:

>>> ord(u'?')
12354

Output Django queryset as JSON

If the goal is to build an API that allow you to access your models in JSON format I recommend you to use the django-restframework that is an enormously popular package within the Django community to achieve this type of tasks.

It include useful features such as Pagination, Defining Serializers, Nested models/relations and more. Even if you only want to do minor Javascript tasks and Ajax calls I would still suggest you to build a proper API using the Django Rest Framework instead of manually defining the JSON response.

Export to csv in jQuery

Hope the following demo can help you out.

_x000D_
_x000D_
$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
        rowData.push(column.innerText);_x000D_
      });_x000D_
      tableData.push(rowData.join(","));_x000D_
    });_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
_x000D_
_x000D_
    $('#download-link')[0].click();_x000D_
    $('#download-link').remove();_x000D_
  });_x000D_
});
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
  <table id="mainTable">_x000D_
    <tr>_x000D_
      <td>Col1</td>_x000D_
      <td>Col2</td>_x000D_
      <td>Col3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val1</td>_x000D_
      <td>Val2</td>_x000D_
      <td>Val3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val11</td>_x000D_
      <td>Val22</td>_x000D_
      <td>Val33</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val111</td>_x000D_
      <td>Val222</td>_x000D_
      <td>Val333</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android getText from EditText field

Try this.

EditText text = (EditText)findViewById(R.id.edittext1);
String  str = text.getText().toString().trim();

How to navigate through textfields (Next / Done Buttons)

Here's one without delegation:

tf1.addTarget(tf2, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
tf2.addTarget(tf3, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)

ObjC:

[tf1 addTarget:tf2 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
[tf2 addTarget:tf3 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];

Works using the (mostly unknown) UIControlEventEditingDidEndOnExit UITextField action.

You can also easily hook this up in the storyboard, so no delegation or code is required.

Edit: actually I cannot figure out how to hook this up in storyboard. becomeFirstResponder does not seem to be a offered action for this control-event, which is a pity. Still, you can hook all your textfields up to a single action in your ViewController which then determines which textField to becomeFirstResponder based on the sender (though then it is not as elegant as the above programmatic solution so IMO do it with the above code in viewDidLoad).

Is JavaScript guaranteed to be single-threaded?

I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.

Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.

(Note to others commenters: Even though setTimeout/setInterval, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)

Eclipse : Maven search dependencies doesn't work

I have the same problem. None of the options suggested above worked for me. However I find, that if I lets say manually add groupid/artifact/version for org.springframework.spring-core version 4.3.4.RELEASE and save the pom.xml, the dependencies download automatically and the search works for the jars already present in the repository. However if I now search for org.springframework.spring-context , which isnt in the current dependencies, this search still doesn't work.

What's the difference between an argument and a parameter?

A parameter is something you have to fill in when you call a function. What you put in it is the argument.

Simply set: the argument goes into the parameter, an argument is the value of the parameter.

A bit more info on: http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments

How add spaces between Slick carousel item

simply add padding on to the slick-side class will do

.slick-slider .slick-slide {
  padding: 0 15px;
}

Is there a Subversion command to reset the working copy?

Delete unversioned files and revert any changes:

svn revert D:\tmp\sql -R
svn cleanup D:\tmp\sql --remove-unversioned

Out:

D         D:\tmp\sql\update\abc.txt

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

How to read the content of a file to a string in C?

If "read its contents into a string" means that the file does not contain characters with code 0, you can also use getdelim() function, that either accepts a block of memory and reallocates it if necessary, or just allocates the entire buffer for you, and reads the file into it until it encounters a specified delimiter or end of file. Just pass '\0' as the delimiter to read the entire file.

This function is available in the GNU C Library, http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994

The sample code might look as simple as

char* buffer = NULL;
size_t len;
ssize_t bytes_read = getdelim( &buffer, &len, '\0', fp);
if ( bytes_read != -1) {
  /* Success, now the entire file is in the buffer */

How to do a recursive find/replace of a string with awk or sed?

A simpler way is to use the below on the command line

find /home/www/ -type f|xargs perl -pi -e 's/subdomainA\.example\.com/subdomainB.example.com/g' 

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

How do I execute a file in Cygwin?

When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.

Then at the prompt run:

cd a.exe

It will be read in by Cygwin and you will be asked to install it.

On - window.location.hash - Change?

var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    }
    return false;
}
var RunTabs = setInterval(TrackHash, 200);

That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.

Spring Boot: Cannot access REST Controller on localhost (404)

It could be that something else is running on port 8080, and you're actually connecting to it by mistake.

Definitely check that out, especially if you have dockers that are bringing up other services you don't control, and are port forwarding those services.

How to vertically align text with icon font?

to center vertically and horizontally use this:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

Ajax call Into MVC Controller- Url Issue

Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :

var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
  $.ajax({
   type: "POST",
   url: requrl,
   data: "{queryString:'" + searchVal + "'}",
   contentType: "application/json; charset=utf-8",
   dataType: "html",
   success: function (data) {
   alert("here" + data.d.toString());
   }
  });

MongoDB and "joins"

If you use mongoose, you can just use(assuming you're using subdocuments and population):

Profile.findById profileId
  .select 'friends'
  .exec (err, profile) ->
    if err or not profile
      handleError err, profile, res
    else
      Status.find { profile: { $in: profile.friends } }, (err, statuses) ->
        if err
          handleErr err, statuses, res
        else
          res.json createJSON statuses

It retrieves Statuses which belong to one of Profile (profileId) friends. Friends is array of references to other Profiles. Profile schema with friends defined:

schema = new mongoose.Schema
  # ...

  friends: [
    type: mongoose.Schema.Types.ObjectId
    ref: 'Profile'
    unique: true
    index: true
  ]

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How do I extract Month and Year in a MySQL date and compare them?

If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use

SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
 FROM Table Where Condition = 'Condition';

How to calculate the angle between a line and the horizontal axis?

Based on reference "Peter O".. Here is the java version

private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX)); }

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Auto-increment primary key in SQL tables

  1. Presumably you are in the design of the table. If not: right click the table name - "Design".
  2. Click the required column.
  3. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

enter image description here

How to set a ripple effect on textview or imageview on Android?

You can use android-ripple-background

Start Effect

final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
ImageView imageView=(ImageView)findViewById(R.id.centerImage);
imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        rippleBackground.startRippleAnimation();
    }
});

Stop animation:

rippleBackground.stopRippleAnimation();

For KOTLIN

val rippleBackground = findViewById(R.id.content) as RippleBackground
val imageView: ImageView = findViewById(R.id.centerImage) as ImageView
imageView.setOnClickListener(object : OnClickListener() {
    fun onClick(view: View?) {
        rippleBackground.startRippleAnimation()
    }
})

How do I get a background location update every n minutes in my iOS application?

On iOS 8/9/10 to make background location update every 5 minutes do the following:

  1. Go to Project -> Capabilities -> Background Modes -> select Location updates

  2. Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)

  3. To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.

I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.

@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;

@end

@implementation LocationManager

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        LocationManager *instance = sharedInstance;
        instance.locationManager = [CLLocationManager new];
        instance.locationManager.delegate = instance;
        instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
        instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
    });

    return sharedInstance;
}

- (void)startUpdatingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.locationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *mostRecentLocation = locations.lastObject;
    NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));

    NSDate *now = [NSDate date];
    NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;

    if (!self.lastTimestamp || interval >= 5 * 60)
    {
        self.lastTimestamp = now;
        NSLog(@"Sending current location to web service.");
    }
}

@end

How do I measure a time interval in C?

Here's a header file I wrote to do some simple performance profiling (using manual timers):

#ifndef __ZENTIMER_H__
#define __ZENTIMER_H__

#ifdef ENABLE_ZENTIMER

#include <stdio.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#elif HAVE_INTTYPES_H
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
typedef unsigned long long uint64_t;
#endif

#ifdef __cplusplus
extern "C" {
#pragma }
#endif /* __cplusplus */

#define ZTIME_USEC_PER_SEC 1000000

/* ztime_t represents usec */
typedef uint64_t ztime_t;

#ifdef WIN32
static uint64_t ztimer_freq = 0;
#endif

static void
ztime (ztime_t *ztimep)
{
#ifdef WIN32
    QueryPerformanceCounter ((LARGE_INTEGER *) ztimep);
#else
    struct timeval tv;

    gettimeofday (&tv, NULL);

    *ztimep = ((uint64_t) tv.tv_sec * ZTIME_USEC_PER_SEC) + tv.tv_usec;
#endif
}

enum {
    ZTIMER_INACTIVE = 0,
    ZTIMER_ACTIVE   = (1 << 0),
    ZTIMER_PAUSED   = (1 << 1),
};

typedef struct {
    ztime_t start;
    ztime_t stop;
    int state;
} ztimer_t;

#define ZTIMER_INITIALIZER { 0, 0, 0 }

/* default timer */
static ztimer_t __ztimer = ZTIMER_INITIALIZER;

static void
ZenTimerStart (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztimer->state = ZTIMER_ACTIVE;
    ztime (&ztimer->start);
}

static void
ZenTimerStop (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztime (&ztimer->stop);
    ztimer->state = ZTIMER_INACTIVE;
}

static void
ZenTimerPause (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztime (&ztimer->stop);
    ztimer->state |= ZTIMER_PAUSED;
}

static void
ZenTimerResume (ztimer_t *ztimer)
{
    ztime_t now, delta;

    ztimer = ztimer ? ztimer : &__ztimer;

    /* unpause */
    ztimer->state &= ~ZTIMER_PAUSED;

    ztime (&now);

    /* calculate time since paused */
    delta = now - ztimer->stop;

    /* adjust start time to account for time elapsed since paused */
    ztimer->start += delta;
}

static double
ZenTimerElapsed (ztimer_t *ztimer, uint64_t *usec)
{
#ifdef WIN32
    static uint64_t freq = 0;
    ztime_t delta, stop;

    if (freq == 0)
        QueryPerformanceFrequency ((LARGE_INTEGER *) &freq);
#else
#define freq ZTIME_USEC_PER_SEC
    ztime_t delta, stop;
#endif

    ztimer = ztimer ? ztimer : &__ztimer;

    if (ztimer->state != ZTIMER_ACTIVE)
        stop = ztimer->stop;
    else
        ztime (&stop);

    delta = stop - ztimer->start;

    if (usec != NULL)
        *usec = (uint64_t) (delta * ((double) ZTIME_USEC_PER_SEC / (double) freq));

    return (double) delta / (double) freq;
}

static void
ZenTimerReport (ztimer_t *ztimer, const char *oper)
{
    fprintf (stderr, "ZenTimer: %s took %.6f seconds\n", oper, ZenTimerElapsed (ztimer, NULL));
}

#ifdef __cplusplus
}
#endif /* __cplusplus */

#else /* ! ENABLE_ZENTIMER */

#define ZenTimerStart(ztimerp)
#define ZenTimerStop(ztimerp)
#define ZenTimerPause(ztimerp)
#define ZenTimerResume(ztimerp)
#define ZenTimerElapsed(ztimerp, usec)
#define ZenTimerReport(ztimerp, oper)

#endif /* ENABLE_ZENTIMER */

#endif /* __ZENTIMER_H__ */

The ztime() function is the main logic you need — it gets the current time and stores it in a 64bit uint measured in microseconds. You can then later do simple math to find out the elapsed time.

The ZenTimer*() functions are just helper functions to take a pointer to a simple timer struct, ztimer_t, which records the start time and the end time. The ZenTimerPause()/ZenTimerResume() functions allow you to, well, pause and resume the timer in case you want to print out some debugging information that you don't want timed, for example.

You can find a copy of the original header file at http://www.gnome.org/~fejj/code/zentimer.h in the off chance that I messed up the html escaping of <'s or something. It's licensed under MIT/X11 so feel free to copy it into any project you do.

how to remove time from datetime

Use this SQL:

SELECT DATE_FORMAT(date_column_here,'%d/%m/%Y') FROM table_name;

Install gitk on Mac

What I ended up doing was: brew info git

Which gave me info that git was cloned into: /usr/local/Cellar/git/1.9.0

So I just added: /usr/local/Cellar/git/1.9.0/bin to the beginning of my PATH env variable.

Note: I don't know how to use homebrew... just want to get going quickly as I have other things to do... this basically gets gitk running for me so I'm sticking to it for now. (probably not the way to work with homebrew though).

Best way to remove duplicate entries from a data table

Do dtEmp on your current working DataTable:

DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);

It's nice.

How to solve npm install throwing fsevents warning on non-MAC OS?

I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,

sudo npm cache clean --force 
sudo npm uninstall 
sudo npm install

One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common

In C - check if a char exists in a char array

I believe the original question said:

a character belongs to a list/array of invalid characters

and not:

belongs to a null-terminated string

which, if it did, then strchr would indeed be the most suitable answer. If, however, there is no null termination to an array of chars or if the chars are in a list structure, then you will need to either create a null-terminated string and use strchr or manually iterate over the elements in the collection, checking each in turn. If the collection is small, then a linear search will be fine. A large collection may need a more suitable structure to improve the search times - a sorted array or a balanced binary tree for example.

Pick whatever works best for you situation.

How to set column widths to a jQuery datatable?

The best solution I found this to work for me guys after trying all the other solutions.... Basically i set the sScrollX to 200% then set the individual column widths to the required % that I wanted. The more columns that you have and the more space that you require then you need to raise the sScrollX %... The null means that I want those columns to retain the datatables auto width they have set in their code. enter image description here

            $('#datatables').dataTable
            ({  
                "sScrollX": "200%", //This is what made my columns increase in size.
                "bScrollCollapse": true,
                "sScrollY": "320px",

                "bAutoWidth": false,
                "aoColumns": [
                    { "sWidth": "10%" }, // 1st column width 
                    { "sWidth": "null" }, // 2nd column width 
                    { "sWidth": "null" }, // 3rd column width
                    { "sWidth": "null" }, // 4th column width 
                    { "sWidth": "40%" }, // 5th column width 
                    { "sWidth": "null" }, // 6th column width
                    { "sWidth": "null" }, // 7th column width 
                    { "sWidth": "10%" }, // 8th column width 
                    { "sWidth": "10%" }, // 9th column width
                    { "sWidth": "40%" }, // 10th column width
                    { "sWidth": "null" } // 11th column width
                    ],
                "bPaginate": true,              
                "sDom": '<"H"TCfr>t<"F"ip>',
                "oTableTools": 
                {
                    "aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
                    "sSwfPath": "copy_cvs_xls_pdf.swf"
                },
                "sPaginationType":"full_numbers",
                "aaSorting":[[0, "desc"]],
                "bJQueryUI":true    

            });

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

Why does my Eclipse keep not responding?

Very likely your filesystem is out of sync with your Eclipse... Resource is out of sync with the file system. Using SVN? If you "Refresh" all of your projects in explorer, speed returns to normal.

How do I get IntelliJ to recognize common Python modules?

This is how i solved my problem (i have imported the project and it was showing there only, newly created files were not showing those errors):

1) Command + alt + R (Control in case of windows

2) Debug window will appear, select your file and press right arrow (->) and choose Edit then press enter (Edit configuration setting window will appear)

3) Under configuration, at the bottom you can see the error (please select a module with a valid python sdk), So in Python Interpreter, check Use Specified Interpreter, then in drop down you select your Python version

(In case python is not there download python plugin for intelliJ using following link https://www.jetbrains.com/help/idea/2016.3/installing-updating-and-uninstalling-repository-plugins.html

4) Click on apply then close it.

Bingo it's done.

When should I write the keyword 'inline' for a function/method?

gcc by default does not inline any functions when compiling without optimization enabled. I don't know about visual studio – deft_code

I checked this for Visual Studio 9 (15.00.30729.01) by compiling with /FAcs and looking at the assembly code: The compiler produced calls to member functions without optimization enabled in debug mode. Even if the function is marked with __forceinline, no inline runtime code is produced.

How to prevent line breaks in list items using CSS

You could add this little snippet of code to add a nice "…" to the ending of the line if the content is to large to fit on one line:

li {
  overflow: hidden; 
  text-overflow: ellipsis;
  white-space: nowrap;
}

Java optional parameters

VarArgs and overloading have been mentioned. Another option is a Bloch Builder pattern, which would look something like this:

 MyObject my = new MyObjectBuilder().setParam1(value)
                                 .setParam3(otherValue)
                                 .setParam6(thirdValue)
                                 .build();

Although that pattern would be most appropriate for when you need optional parameters in a constructor.

Count the number of occurrences of each letter in string

One simple possibility would be to make an array of 26 ints, each is a count for a letter a-z:

int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc

Then loop through the string and increment the count for each letter:

for(int i = 0; i<strlen(mystring); i++)      //for the whole length of the string
    if(isalpha(mystring[i]))
        alphacount[tolower(mystring[i])-'a']++;  //make the letter lower case (if it's not)
                                                 //then use it as an offset into the array
                                                 //and increment

It's a simple idea that works for A-Z, a-z. If you want to separate by capitals you just need to make the count 52 instead and subtract the correct ASCII offset

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

If using Tomcat 6 and earlier, make sure the keystore password and the key password are same. If using Tomcat 7 and later, make sure they are the same or that the key password is specified in the server.xml file.

How to check if a file is empty in Bash?

[[ -s file ]] --> Checks if file has size greater than 0

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done

Trying to merge 2 dataframes but get ValueError

At first check the type of columns which you want to merge. You will see one of them is string where other one is int. Then convert it to int as following code:

df["something"] = df["something"].astype(int)

merged = df.merge[df1, on="something"]

Xcode 10 Error: Multiple commands produce

While checking the build log, I noticed a warning:

note: Using new build system
note: Planning build
note: Constructing build description
Build system information
warning: The Copy Bundle Resources build phase contains this target's Info.plist file '/Users/<redacted>/Repositories/Whitesmith/optimize-ios/Carthage/Checkouts/WSStatusBarNotification/Miscellaneous/Info.plist'. (in target 'JDStatusBarNotification')

So, if that's your case then just go to your target:

  1. Build Phases
  2. Copy Bundle Resource
  3. Remove info.plist.

Difference between abstract class and interface in Python

Python >= 2.6 has Abstract Base Classes.

Abstract Base Classes (abbreviated ABCs) complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy. Python comes with many builtin ABCs for data structures (in the collections module), numbers (in the numbers module), and streams (in the io module). You can create your own ABC with the abc module.

There is also the Zope Interface module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page here that might help.

In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).

How to verify a Text present in the loaded page through WebDriver

For Ruby programmers here is how you can assert. Have to include Minitest to get the asserts

    assert(@driver.find_element(:tag_name => "body").text.include?("Name"))

Send parameter to Bootstrap modal window?

I found the solution at: Passing data to a bootstrap modal

So simply use:

 $(e.relatedTarget).data('book-id'); 

with 'book-id' is a attribute of modal with pre-fix 'data-'

Sublime Text 2 multiple line edit

Worked for me on OS X + Sublime build 3083:

OPTION (ALT) + select lines

Make a table fill the entire window

Try using

<html style="height: 100%;">
    <body style="height: 100%;">
        <table style="height: 100%;">
        ...

in order to force all parents of the table element to expand over the available vertical space (which will eliminate the need to use absolute positioning).

Works in Firefox 28, IE 11 and Chromium 34 (and hence probably Google Chrome as well)

Source: http://www.dailycoding.com/posts/howtoset100tableheightinhtml.aspx

Setting value of active workbook in Excel VBA

Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.

DataSet panel (Report Data) in SSRS designer is gone

With a report (rdl) file selected in your solution, select View and then Report Data.

It is a shortcut of Ctrl+Alt+D.

enter image description here

jQuery, get html of a whole element

You can clone it to get the entire contents, like this:

var html = $("<div />").append($("#div1").clone()).html();

Or make it a plugin, most tend to call this "outerHTML", like this:

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

Then you can just call:

var html = $("#div1").outerHTML();

How to store NULL values in datetime fields in MySQL?

Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

Hope that helps!

MySQL duplicate entry error even though there is no duplicate entry

In case anyone else finds this thread with my problem -- I was using an "integer" column type in MySQL. The row I was attempting to insert had a primary key with a value larger than allowed by integer. Switching to "bigint" fixed the problem.

What is the best way to auto-generate INSERT statements for a SQL Server table?

The first link to sp_generate_inserts is pretty cool, here is a really simple version:

DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table  VARCHAR(max); SET @Table  = 'Queues'               -- your table

DECLARE @SQL    VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) + 
 ''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
PRINT @S'

EXEC (@SQL)

On my system, I get this result:

INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION 
SELECT 'Car/Lar', '11' UNION 
SELECT 'Scan Line', '21' UNION 
SELECT 'OCR', '22' UNION 
SELECT 'Dynamic Template', '23' UNION 
SELECT 'Fix MICR', '41' UNION 
SELECT 'Fix MICR (Supervisor)', '42' UNION 
SELECT 'Foreign MICR', '43' UNION 
...

Entity Framework is Too Slow. What are my options?

We have an similar application (Wcf -> EF -> database) that does 120 Requests per second easily, so I am more than sure that EF is not your problem here, that being said, I have seen major performance improvements with compiled queries.

Removing first x characters from string?

Use del.

Example:

>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

Excel to JSON javascript code?

@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:

npm install xlsx --save

Then in my component code, import with:

import XLSX from 'xlsx'

The component UI should look like this:

<input
  accept=".xlsx"
  type="file"
  onChange={this.fileReader}
/>

It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

Convert multiple rows into one with comma as separator

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

source: http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

What's the most efficient way to check if a record exists in Oracle?

Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.

    DECLARE
    rec_count NUMBER := 0;

    BEGIN

    select count(*) 
    into rec_count  
    from EMPLOYEETABLE  
    WHERE employee_id = inEMPLOYEE_ID  
    AND department_nbr = inDEPARTMENT_NBR;  


    if rec_count > 0 then  
       {UPDATE EMPLOYEETABLE}
    else  
       {INSERT INTO EMPLOYEETABLE}  
    end if;  

    END;

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)