Programs & Examples On #Avcapturesession

iPhone - To perform a real-time or offline capture, you instantiate an AVCaptureSession object and add appropriate inputs (such as AVCaptureDeviceInput), and outputs (such as AVCaptureMovieFileOutput).

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Turn on torch/flash on iPhone

See a better answer below: https://stackoverflow.com/a/10054088/308315


Old answer:

First, in your AppDelegate .h file:

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : NSObject <UIApplicationDelegate> {

    AVCaptureSession *torchSession;

}

@property (nonatomic, retain) AVCaptureSession * torchSession;

@end

Then in your AppDelegate .m file:

@implementation AppDelegate

@synthesize torchSession;

- (void)dealloc {
    [torchSession release];

    [super dealloc];
}

- (id) init {
    if ((self = [super init])) {

    // initialize flashlight
    // test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
        Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
        if (captureDeviceClass != nil) {

            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

            if ([device hasTorch] && [device hasFlash]){

                if (device.torchMode == AVCaptureTorchModeOff) {

                NSLog(@"Setting up flashlight for later use...");

                    AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
                    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

                    AVCaptureSession *session = [[AVCaptureSession alloc] init];

                [session beginConfiguration];
                    [device lockForConfiguration:nil];

                    [session addInput:flashInput];
                    [session addOutput:output];

                    [device unlockForConfiguration];

                    [output release];

                [session commitConfiguration];
                [session startRunning];

                [self setTorchSession:session];
                [session release];
                    }

            }

        }
    } 
    return self;
}

Then anytime you want to turn it on, just do something like this:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOn];
    [device setFlashMode:AVCaptureFlashModeOn];

    [device unlockForConfiguration];

}

And similar for turning it off:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOff];
    [device setFlashMode:AVCaptureFlashModeOff];

    [device unlockForConfiguration];
}

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Not really to answer OP's question (it's resolved anyway), but to help people who may stumble into the similar issue.

Here is what we had:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x0000000000000000, pid=11, tid=139910430250752
#
# JRE version: Java(TM) SE Runtime Environment (8.0_77-b03) (build 1.8.0_77-b03)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.77-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  0x0000000000000000
#
# Core dump written. Default location: /builds/c5b22963/0/reporting/arsng2/core or core.11
#

The reason was defective RAM.

Is there a printf converter to print in binary format?

Maybe someone will find this solution useful:

void print_binary(int number, int num_digits) {
    int digit;
    for(digit = num_digits - 1; digit >= 0; digit--) {
        printf("%c", number & (1 << digit) ? '1' : '0');
    }
}

File Upload without Form

All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).

I posted similar answer also here.

Does "\d" in regex mean a digit?

In Python-style regex, \d matches any individual digit. If you're seeing something that doesn't seem to do that, please provide the full regex you're using, as opposed to just describing that one particular symbol.

>>> import re
>>> re.match(r'\d', '3')
<_sre.SRE_Match object at 0x02155B80>
>>> re.match(r'\d', '2')
<_sre.SRE_Match object at 0x02155BB8>
>>> re.match(r'\d', '1')
<_sre.SRE_Match object at 0x02155B80>

Strangest language feature

In JavaScript this:

var something = 12;

function nicelyCraftedFunction()
{
  something = 13;
  // ... some other code
  // ... and in Galaxy far, far away this:
  if( false ) // so the block never executes:
  { 
    var something; 
  }
}
nicelyCraftedFunction(); // call of the function

Normally you would expect that something variable will get value of 13. But not in JavaScript - variables there have function scope so later declaration affects everything up-stream.

In languages that use C/C++/Java notation (like JS) you would expect variables having block scope, not like this ...

So dead block of code that compiler can even remove from final generated bytecode still have side effects in the rest of code that executes normally.

Therefore something will be still 12 - not change after invocation of the function.

ng-change not working on a text input

One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.

<div ng-app="myApp" ng-controller="myCtrl">      
        <input type='text' ng-model='name' ng-change='change()'>
        <br/> <span>changed {{counter}} times </span>
 </div>

...

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
      $scope.name = 'Australia';
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
});

https://jsfiddle.net/as0nyre3/1/

jQuery.click() vs onClick

Onclick Function Jquery

$('#selector').click(function(){ //Your Functionality });

Selenium WebDriver findElement(By.xpath()) not working for me

Just need to add * at the beginning of xpath and closing bracket at last.

element = findElement(By.xpath("//*[@test-id='test-username']"));

Unable to call the built in mb_internal_encoding method?

apt-get install php7.3-mbstring solved the issue on ubuntu, php version is php-fpm 7.3

What is external linkage and internal linkage?

As dudewat said external linkage means the symbol (function or global variable) is accessible throughout your program and internal linkage means that it is only accessible in one translation unit.

You can explicitly control the linkage of a symbol by using the extern and static keywords. If the linkage is not specified then the default linkage is extern (external linkage) for non-const symbols and static (internal linkage) for const symbols.

// In namespace scope or global scope.
int i; // extern by default
const int ci; // static by default
extern const int eci; // explicitly extern
static int si; // explicitly static

// The same goes for functions (but there are no const functions).
int f(); // extern by default
static int sf(); // explicitly static 

Note that instead of using static (internal linkage), it is better to use anonymous namespaces into which you can also put classes. Though they allow extern linkage, anonymous namespaces are unreachable from other translation units, making linkage effectively static.

namespace {
  int i; // extern by default but unreachable from other translation units
  class C; // extern by default but unreachable from other translation units
}

Get names of all files from a folder with Ruby

You may also want to use Rake::FileList (provided you have rake dependency):

FileList.new('lib/*') do |file|
  p file
end

According to the API:

FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

How to use sha256 in php5.3.0

You should use Adaptive hashing like http://en.wikipedia.org/wiki/Bcrypt for securing passwords

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

How can I use "." as the delimiter with String.split() in java

Have you tried escaping the dot? like this:

String[] words = line.split("\\.");

top -c command in linux to filter processes listed based on processname

In htop, you can simply search with

/process-name

Difference between webdriver.Dispose(), .Close() and .Quit()

close():- Suppose you have opened multiple browser windows with same driver instance, now calling close() on the driver instance will close the current window the driver instance is pointed to. But the driver instance still remain in memory and can be used to handle other open browser windows.

quit():- If you call quit() on the driver instance and there are one or more browser windows open, it will close all the open browser windows and the driver instance is garbage collected i.e. removed from the memory. So now you cannot use this driver instance to do other operation after calling quit() on it. If you do it will throw an Exception.

dispose():- I don't think there is a dispose method for a WebDriver instance.

You can go to the this selenium official java doc link for reference.

Read line by line in bash script

while read CMD; do
    echo $CMD
done  << EOF
data line 1
data line 2
..
EOF

How do pointer-to-pointer's work in C? (and when might you use them?)

Consider the below figure and program to understand this concept better.

Double pointer diagram

As per the figure, ptr1 is a single pointer which is having address of variable num.

ptr1 = &num;

Similarly ptr2 is a pointer to pointer(double pointer) which is having the address of pointer ptr1.

ptr2 = &ptr1;

A pointer which points to another pointer is known as double pointer. In this example ptr2 is a double pointer.

Values from above diagram :

Address of variable num has : 1000
Address of Pointer ptr1 is: 2000
Address of Pointer ptr2 is: 3000

Example:

#include <stdio.h>

int main ()
{
   int  num = 10;
   int  *ptr1;
   int  **ptr2;

   // Take the address of var 
   ptr1 = &num;

   // Take the address of ptr1 using address of operator &
   ptr2 = &ptr1;

   // Print the value
   printf("Value of num = %d\n", num );
   printf("Value available at *ptr1 = %d\n", *ptr1 );
   printf("Value available at **ptr2 = %d\n", **ptr2);
}

Output:

Value of num = 10
Value available at *ptr1 = 10
Value available at **ptr2 = 10

What is apache's maximum url length?

The default limit for the length of the request line is 8190 bytes (see LimitRequestLine directive). And if we subtract three bytes for the request method (i.e. GET), eight bytes for the version information (i.e. HTTP/1.0/HTTP/1.1) and two bytes for the separating space, we end up with 8177 bytes for the URI path plus query.

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

How to compute the similarity between two text documents?

I am combining the solutions from answers of @FredFoo and @Renaud. My solution is able to apply @Renaud's preprocessing on the text corpus of @FredFoo and then display pairwise similarities where the similarity is greater than 0. I ran this code on Windows by installing python and pip first. pip is installed as part of python but you may have to explicitly do it by re-running the installation package, choosing modify and then choosing pip. I use the command line to execute my python code saved in a file "similarity.py". I had to execute the following commands:

>set PYTHONPATH=%PYTHONPATH%;C:\_location_of_python_lib_
>python -m pip install sklearn
>python -m pip install nltk
>py similarity.py

The code for similarity.py is as follows:

from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
import numpy as np
nltk.download('punkt') # if necessary...

stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

corpus = ["I'd like an apple", 
           "An apple a day keeps the doctor away", 
           "Never compare an apple to an orange", 
           "I prefer scikit-learn to Orange", 
           "The scikit-learn docs are Orange and Blue"]  

vect = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vect.fit_transform(corpus)   
                                                                                                                                                                                                                    
pairwise_similarity = tfidf * tfidf.T

#view the pairwise similarities 
print(pairwise_similarity)

#check how a string is normalized
print(normalize("The scikit-learn docs are Orange and Blue"))

How to link home brew python version and set it as default

If you used

brew install python

before 'unlink' you got

brew info python
/usr/local/Cellar/python/2.7.11

python -V
Python 2.7.10

so do

brew unlink python && brew link python

and open a new terminal shell

python -V
Python 2.7.11

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

importing a CSV into phpmyadmin

This is happen due to the id(auto increment filed missing). If you edit it in a text editor by adding a comma for the ID field this will be solved.

Is there a way to SELECT and UPDATE rows at the same time?

It'd be easier to do your UPDATE first and then run 'SELECT ID FROM INSERTED'.

Take a look at SQL Tips for more info and examples.

What is the purpose of Android's <merge> tag in XML layouts?

To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.

activity_main.xml

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

    <include layout="@layout/content_profile" />

</LinearLayout>

content_profile.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</LinearLayout>

In here, the entire layout file when inflated looks like this.

<LinearLayout>
    <LinearLayout>
        <TextView />
        <TextView />
    </LinearLayout>
</LinearLayout>

See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.

enter image description here

content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</merge>

Now our layout looks like this

<LinearLayout>
    <TextView />
    <TextView />
</LinearLayout>

Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.

enter image description here

So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.

PHP - Debugging Curl

Here is an even simplier way, by writing directly to php error output

curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, fopen('php://stderr', 'w'));

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.

  • Assign and implement tableview dataSource and delegate
  • Assign UITableViewAutomaticDimension to rowHeight & estimatedRowHeight
  • Implement delegate/dataSource methods (i.e. heightForRowAt and return a value UITableViewAutomaticDimension to it)

-

Objective C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

Swift:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    // Swift 4.2 onwards
    table.rowHeight = UITableView.automaticDimension
    table.estimatedRowHeight = UITableView.automaticDimension


    // Swift 4.1 and below
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension

}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Swift 4.2 onwards
    return UITableView.automaticDimension

    // Swift 4.1 and below
    return UITableViewAutomaticDimension
}

For label instance in UITableviewCell

  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

enter image description here

Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

problem with php mail 'From' header

I solved this by adding email accounts in Cpanel and also adding that same email to the header from field like this

$header = 'From: XXXXXXXX <[email protected]>' . "\r\n";

Why does range(start, end) not include end?

It's also useful for splitting ranges; range(a,b) can be split into range(a, x) and range(x, b), whereas with inclusive range you would write either x-1 or x+1. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b] includes the a-th element but not the b-th. Then range having the same property makes it nicely consistent.

Joda DateTime to Timestamp conversion

Actually this is not a duplicate question. And this how i solve my problem after several times :

   int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());

This is the way to get offset from desired timezone.

Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.

   DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
                         DateTimeZone.forID("anytimezone"));

Now we will add our offset to the datetime, and get the timestamp from it.

    dt = dt.plusMillis(offset);
    Timestamp ts = new Timestamp(dt.getMillis());

May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

How can I convert the "arguments" object to an array in JavaScript?

ES6 using rest parameters

If you are able to use ES6 you can use:

Rest Parameters

_x000D_
_x000D_
function sortArgs(...args) {_x000D_
  return args.sort(function (a, b) { return a - b; });_x000D_
}_x000D_
_x000D_
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
_x000D_
_x000D_
_x000D_

As you can read in the link

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

If you are curious about the ... syntax, it is called Spread Operator and you can read more here.

ES6 using Array.from()

Using Array.from:

_x000D_
_x000D_
function sortArgs() {_x000D_
  return Array.from(arguments).sort(function (a, b) { return a - b; });_x000D_
}_x000D_
_x000D_
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
_x000D_
_x000D_
_x000D_

Array.from simply convert Array-like or Iterable objects into Array instances.



ES5

You can actually just use Array's slice function on an arguments object, and it will convert it into a standard JavaScript array. You'll just have to reference it manually through Array's prototype:

function sortArgs() {
    var args = Array.prototype.slice.call(arguments);
    return args.sort();
}

Why does this work? Well, here's an excerpt from the ECMAScript 5 documentation itself:

NOTE: The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.

Therefore, slice works on anything that has a length property, which arguments conveniently does.


If Array.prototype.slice is too much of a mouthful for you, you can abbreviate it slightly by using array literals:

var args = [].slice.call(arguments);

However, I tend to feel that the former version is more explicit, so I'd prefer it instead. Abusing the array literal notation feels hacky and looks strange.

Convert an int to ASCII character

I suppose that

std::to_string(i)

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

Max length for client ip address

There's a caveat with the general 39 character IPv6 structure. For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this:

IPv6 (39 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD

IPv4-mapped IPv6 (45 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190

Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the . character), so the maximum is DDD.DDD.DDD.DDD).

The correct maximum IPv6 string length, therefore, is 45.

This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

Space between two rows in a table?

You can't change the margin of a table cell. But you CAN change the padding. Change the padding of the TD, which will make the cell larger and push the text away from the side with the increased padding. If you have border lines, however, it still won't be exactly what you want.

IE Enable/Disable Proxy Settings via Registry

The problem is that IE won't reset the proxy settings until it either

  1. closes, or
  2. has its configuration refreshed.

Below is the code that I've used to get this working:

function Refresh-System
{
  $signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@

$INTERNET_OPTION_SETTINGS_CHANGED   = 39
$INTERNET_OPTION_REFRESH            = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
return $a -and $b
}

Date difference in years using C#

int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;

To calculate the elapsed years (age), the result will be minus one.

var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;

Getting only Month and Year from SQL DATE

I had a specific requirement to do something similar where it would show month-year which can be done by the following:

SELECT DATENAME(month, GETDATE()) + '-' + CAST(YEAR(GETDATE()) AS nvarchar) AS 'Month-Year'

In my particular case, I needed to have it down to the 3 letter month abreviation with a 2 digit year, looking something like this: SELECT LEFT(DATENAME(month, GETDATE()), 3) + '-' + CAST(RIGHT(YEAR(GETDATE()),2) AS nvarchar(2)) AS 'Month-Year'

Android Closing Activity Programmatically

finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.

Recommendation for compressing JPG files with ImageMagick

If the image has big dimenssions is hard to get good results without resizing, below is a 60 percent resizing which for most of the purposes doesn't destroys too much of the image.

I use this with good result for gray-scale images (I convert from PNG):

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace Gray -quality 20  {}.jpg

I use this for scanned B&W pages get them to gray-scale images (the extra arguments cleans shadows from previous pages):

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace Gray -quality 20 -density 300 -fill white -fuzz 40% +opaque "#000000" -density 300 {}.jpg 

I use this for color images:

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace RGB -quality 20  {}.jpg 

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

What is the purpose of Order By 1 in SQL select statement?

As mentioned in other answers ORDER BY 1 orders by the first column.

I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name in the below.

SELECT Name, Name FROM Segment ORDER BY 1

How can I listen for a click-and-hold in jQuery?

Here's my current implementation:

$.liveClickHold = function(selector, fn) {

    $(selector).live("mousedown", function(evt) {

        var $this = $(this).data("mousedown", true);

        setTimeout(function() {
            if ($this.data("mousedown") === true) {
                fn(evt);
            }
        }, 500);

    });

    $(selector).live("mouseup", function(evt) {
        $(this).data("mousedown", false);
    });

}

nodejs mongodb object id to string

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

object._id ? object._id.toHexString():object.toHexString();

This is because object._id exists only if the object is populated, if not the object is an ObjectId

AngularJS disable partial caching on dev machine

For Development you can also deactivate the browser cache - In Chrome Dev Tools on the bottom right click on the gear and tick the option

Disable cache (while DevTools is open)

Update: In Firefox there is the same option in Debugger -> Settings -> Advanced Section (checked for Version 33)

Update 2: Although this option appears in Firefox some report it doesn't work. I suggest using firebug and following hadaytullah answer.

Settings to Windows Firewall to allow Docker for Windows to share drive

As stated in one other answer Docker doesn't play nice with a VPN. If you're using Nordvpn you have to disable "Invisibility on LAN" and probably "Internet Kill Switch".

If you've done so it should work even with the VPN active.

NordVPN Client

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Java - Relative path of a file in a java web application

Do you really need to load it from a file? If you place it along your classes (in WEB-INF/classes) you can get an InputStream to it using the class loader:

InputStream csv = 
   SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");

Fill an array with random numbers

You need to add logic to assign random values to double[] array using randomFill method.

Change

 public static double[] list(){
    anArray = new double[10];   
    return anArray;
 }

To

 public static double[] list() {
    anArray = new double[10];
    for(int i=0;i<anArray.length;i++)
    {
        anArray[i] = randomFill();
    }
    return anArray;
}

Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.

 public static void main(String args[]) {

list();
print();
 }

One result is as follows:

-2.89783865E8 
1.605018025E9 
-1.55668528E9 
-1.589135498E9 
-6.33159518E8 
-1.038278095E9 
-4.2632203E8 
1.310182951E9 
1.350639892E9 
6.7543543E7 

error while loading shared libraries: libncurses.so.5:

On Arch Linux you can install ncurses5-compat-libs AUR package.

FYI it is mentioned in Arch Wiki android page, just in case if you'll need some other dependencies for Android Studio: https://wiki.archlinux.org/index.php/Android

Android Studio - Device is connected but 'offline'

Download and Install your device driver manually through visiting manufacturer website like :Samsung,micromax,intex etc.

Class extending more than one class Java?

Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.

class A extends Object
class B extends A

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Well, I believe the question is answered and has already been accepted. But I am going to write what I faced and how I solved it.

I did receive also the same error:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1

I wasn't fortunate to apply all the settings and got success. But when I tried to Debug the project again. This time I got Three Error (including above):

Error:Java HotSpot(TM) 64-Bit Server VM warning: CodeCache is full. Compiler has been disabled.

and

Error:Java HotSpot(TM) 64-Bit Server VM warning: Try increasing the code cache size using -XX:ReservedCodeCacheSize=

So what I did? I just go to Android Studio:

File > Invalidate Caches / Restart.. > Invalidate & Restart

Quick Fix!

Extra Note:

What I found in Gradle Console:

:app:incrementalDebugTasks :app:prePackageMarkerForDebug :app:fastDeployDebugExtractor :app:generateDebugInstantRunAppInfo :app:transformClassesWithDexForDebug To run dex in process, the Gradle daemon needs a larger heap. It currently has approximately 910 MB. For faster builds, increase the maximum heap size for the Gradle daemon to more than 2048 MB. To do this set org.gradle.jvmargs=-Xmx2048M in the project gradle.properties. For more information see https://docs.gradle.org/current/userguide/build_environment.html :app:transformClassesWithDexForDebug FAILED

Read More about it Here on Oracle Blog

mongo - couldn't connect to server 127.0.0.1:27017

Simply create a folder named "data" in C drive and inside data folder create another folder named "db". Then execute mongod.exe :)

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

C: socket connection timeout

The answers about using select()/poll() are right and code should be written this way to be portable.

However, since you're on Linux, you can do this:

int synRetries = 2; // Send a total of 3 SYN packets => Timeout ~7s
setsockopt(fd, IPPROTO_TCP, TCP_SYNCNT, &synRetries, sizeof(synRetries));

See man 7 tcp and man setsockopt.

I used this to speed up the connect-timeout in a program I needed to patch quickly. Hacking it to timeout via select()/poll() was not an option.

server error:405 - HTTP verb used to access this page is not allowed

In my case, IIS was fine but.. uh.. all the files in the folder except web.config had been deleted (a manual deployment half-done on a test site).

How to log out user from web site using BASIC authentication?

I've just tested the following in Chrome (79), Firefox (71) and Edge (44) and it works fine. It applies the script solution as others noted above.

Just add a "Logout" link and when clicked return the following html

    <div>You have been logged out. Redirecting to home...</div>    

<script>
    var XHR = new XMLHttpRequest();
    XHR.open("GET", "/Home/MyProtectedPage", true, "no user", "no password");
    XHR.send();

    setTimeout(function () {
        window.location.href = "/";
    }, 3000);
</script>

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

How to set image to UIImage

Create a UIImageView and add UIImage to it:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image Name"]] ;

Then add it to your view:

[self.view addSubView: imageView];

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

How to view the current heap size that an application is using?

Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop

PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

How to make input type= file Should accept only pdf and xls

Try this one:-

              <MyTextField
                id="originalFileName"
                type="file"
                inputProps={{ accept: '.xlsx, .xls, .pdf' }}
                required
                label="Document"
                name="originalFileName"
                onChange={e => this.handleFileRead(e)}
                size="small"
                variant="standard"
              />

SQL Inner-join with 3 tables?

This is correct query for join 3 table with same id**

select a.empname,a.empsalary,b.workstatus,b.bonus,c.dateofbirth from employee a, Report b,birth c where a.empid=b.empid and a.empid=c.empid and b.empid='103';

employee first table. report second table. birth third table

javascript find and remove object in array based on key value

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

If you are using jQuery, use jQuery.grep like this:

items = $.grep(items, function(item) { 
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

Using ES5 Array.prototype.filter:

items = items.filter(function(item) { 
  return item.id !== '88'; 
});
// items => [{ id: "99" }, { id: "108" }]

How can you print a variable name in python?

Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

How do I read a text file of about 2 GB?

There are quite number of tools available for viewing large files. http://download.cnet.com/Large-Text-File-Viewer/3000-2379_4-90541.html This for instance. However, I was successful with larger files viewing in Visual studio. Thought it took some time to load, it worked.

Problems with entering Git commit message with Vim

You can change the comment character to something besides # like this:

git config --global core.commentchar "@"

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

Using local makefile for CLion instead of CMake

Update: If you are using CLion 2020.2, then it already supports Makefiles. If you are using an older version, read on.


Even though currently only CMake is supported, you can instruct CMake to call make with your custom Makefile. Edit your CMakeLists.txt adding one of these two commands:

When you tell CLion to run your program, it will try to find an executable with the same name of the target in the directory pointed by PROJECT_BINARY_DIR. So as long as your make generates the file where CLion expects, there will be no problem.

Here is a working example:

Tell CLion to pass its $(PROJECT_BINARY_DIR) to make

This is the sample CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.4)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest COMMAND make -C ${mytest_SOURCE_DIR}
                         CLION_EXE_DIR=${PROJECT_BINARY_DIR})

Tell make to generate the executable in CLion's directory

This is the sample Makefile:

all:
    echo Compiling $(CLION_EXE_DIR)/$@ ...
    g++ mytest.cpp -o $(CLION_EXE_DIR)/mytest

That is all, you may also want to change your program's working directory so it executes as it is when you run make from inside your directory. For this edit: Run -> Edit Configurations ... -> mytest -> Working directory

Working with $scope.$emit and $scope.$on

You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit or $broadcast to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :

function ParentController($scope, testService) {
    testService.getList()
        .then(function(data) {
            $scope.list = testService.list;
        })
        .finally(function() {
            $scope.$emit('listFetched');
        })


    function ChildController($scope, testService) {
        $scope.$on('listFetched', function(event, data) {
            // use the data accordingly
        })
    }

and my service looks like this

    app.service('testService', ['$http', function($http) {

        this.list = [];

        this.getList = function() {
            return $http.get(someUrl)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        list = response.data.results;

                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    // something went wrong
                    return $q.reject(response.data);
                });

        }

    }])

How to create two columns on a web page?

I agree with @haha on this one, for the most part. But there are several cross-browser related issues with using the "float:right" and could ultimately give you more of a headache than you want. If you know what the widths are going to be for each column use a float:left on both and save yourself the trouble. Another thing you can incorporate into your methodology is build column classes into your CSS.

So try something like this:

CSS

.col-wrapper{width:960px; margin:0 auto;}
.col{margin:0 10px; float:left; display:inline;}
.col-670{width:670px;}
.col-250{width:250px;}

HTML

<div class="col-wrapper">
    <div class="col col-670">[Page Content]</div>
    <div class="col col-250">[Page Sidebar]</div>
</div>

How can I refresh a page with jQuery?

window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.

So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Check if IIS Express is installed. If IIS Express is missing, Visual Studio might discard the setting <UseIISExpress>false</UseIISExpress> and still look for the express.

What is ADT? (Abstract Data Type)

Simply Abstract Data Type is nothing but a set of operation and set of data is used for storing some other data efficiently in the machine. There is no need of any perticular type declaration. It just require a implementation of ADT.

How to move the layout up when the soft keyboard is shown android

Try this in the android manifest file corresponding to the activity.

<activity android:windowSoftInputMode="adjustPan"> </activity>

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

Combining multiple commits before pushing in Git

What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

How to fire an event when v-model changes?

This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input 
  type="radio" 
  name="optionsRadios" 
  id="optionsRadios2" 
  value=""
  v-model="srStatus" 
  v-on:change="foo"> //here

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){
    foo();
},

Generate random string/characters in JavaScript

How about this compact little trick?

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stringLength = 5;

function pickRandom() {
    return possible[Math.floor(Math.random() * possible.length)];
}

var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).join('');

You need the Array.apply there to trick the empty array into being an array of undefineds.

If you're coding for ES2015, then building the array is a little simpler:

var randomString = Array.from({ length: stringLength }, pickRandom).join('');

How do I align a label and a textarea?

Try setting a height on your td elements.

vertical-align: middle; 

means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.

How to put text in the upper right, or lower right corner of a "box" using css

Float right the text you want to appear on the right, and in the markup make sure that this text and its surrounding span occurs before the text that should be on the left. If it doesn't occur first, you may have problems with the floated text appearing on a different line.

<html>
  <body>
    <div>
      <span style="float:right">here</span>Lorem Ipsum etc<br/>
      blah<br/>
      blah blah<br/>
      blah<br/>
      <span style="float:right">and here</span>lorem ipsums<br/>
    </div>
  </body>
</html>

Note that this works for any line, not just the top and bottom corners.

Regex match digits, comma and semicolon?

Try word.matches("^[0-9,;]+$");

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Add a runtime first and select project properties. Then check the server name from the 'Runtimes' tab as shown in the image.

Select runtime from Project Facets as shown the in image

XMLHttpRequest status 0 (responseText is empty)

To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)

Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.

My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.

I already had:

Access-Control-Allow-Origin: *

But not:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

in the response header of my web service.

After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.

Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.

I need to therefore host my web service on https.

Knowing how to get the true error message - priceless!

VirtualBox error "Failed to open a session for the virtual machine"

On Ubuntu, this can also be caused by incorrect permissions. I chmod 755 Logs/ which fixed the issue.

What is the significance of 1/1/1753 in SQL Server?

1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.

An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)

What permission do I need to access Internet from an Android application?

forget about adding the permission into the manifest Add this code as a method

public static boolean hasPermissions(Context context, String... permissions)
{
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null)
    {
        for (String permission : permissions)
        {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
            {
                return false;
            }
        }
    }
    return true;
}

and write this in your Main

int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA};

    if (!hasPermissions(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

Explicitly calling return in a function or not

My question is: Why is not calling return faster

It’s faster because return is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return is a keyword, but not a function call: it doesn’t translate to any runtime code execution.

That said, calling a primitive function in this way is pretty fast in R, and calling return incurs a minuscule overhead. This isn’t the argument for omitting return.

or better, and thus preferable?

Because there’s no reason to use it.

Because it’s redundant, and it doesn’t add useful redundancy.

To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).

Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:

# Add one to the result
result = x + 1

Using return in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return?” There needs to be a positive reason, since the default is not to use it.

One such positive reason is to signal early exit from a function, say in a guard clause:

f = function (a, b) {
    if (! precondition(a)) return() # same as `return(NULL)`!
    calculation(b)
}

This is a valid, non-redundant use of return. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if does not require return:

sign = function (num) {
    if (num > 0) {
        1
    } else if (num < 0) {
        -1
    } else {
        0
    }
}

We can even rewrite f like this:

f = function (a, b) {
    if (precondition(a)) calculation(b)
}

… where if (cond) expr is the same as if (cond) expr else NULL.

Finally, I’d like to forestall three common objections:

  1. Some people argue that using return adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return as a marker of returning a value isn’t just redundant, it’s actively misleading.

  2. Relatedly, the Zen of Python has a marvellous guideline that should always be followed:

    Explicit is better than implicit.

    How does dropping redundant return not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.

    In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat). Except R has a better marker than return for this case: invisible. For instance, I would write

    save_results = function (results, file) {
        # … code that writes the results to a file …
        invisible()
    }
    
  3. But what about long functions? Won’t it be easy to lose track of what is being returned?

    Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.

    But more importantly, the problem in long functions isn’t the lack of explicit return markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

"Input string was not in a correct format."

If you are not validating explicitly for numbers in the text field, in any case its better to use

int result=0;
if(int.TryParse(textBox1.Text,out result))

Now if the result is success then you can proceed with your calculations.

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

Execute a command line binary with Node.js

I just wrote a Cli helper to deal with Unix/windows easily.

Javascript:

define(["require", "exports"], function (require, exports) {
    /**
     * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
     * Requires underscore or lodash as global through "_".
     */
    var Cli = (function () {
        function Cli() {}
            /**
             * Execute a CLI command.
             * Manage Windows and Unix environment and try to execute the command on both env if fails.
             * Order: Windows -> Unix.
             *
             * @param command                   Command to execute. ('grunt')
             * @param args                      Args of the command. ('watch')
             * @param callback                  Success.
             * @param callbackErrorWindows      Failure on Windows env.
             * @param callbackErrorUnix         Failure on Unix env.
             */
        Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
            if (typeof args === "undefined") {
                args = [];
            }
            Cli.windows(command, args, callback, function () {
                callbackErrorWindows();

                try {
                    Cli.unix(command, args, callback, callbackErrorUnix);
                } catch (e) {
                    console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
                }
            });
        };

        /**
         * Execute a command on Windows environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.windows = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(process.env.comspec, _.union(['/c', command], args));
                callback(command, args, 'Windows');
            } catch (e) {
                callbackError(command, args, 'Windows');
            }
        };

        /**
         * Execute a command on Unix environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.unix = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(command, args);
                callback(command, args, 'Unix');
            } catch (e) {
                callbackError(command, args, 'Unix');
            }
        };

        /**
         * Execute a command no matters what's the environment.
         *
         * @param command   Command to execute. ('grunt')
         * @param args      Args of the command. ('watch')
         * @private
         */
        Cli._execute = function (command, args) {
            var spawn = require('child_process').spawn;
            var childProcess = spawn(command, args);

            childProcess.stdout.on("data", function (data) {
                console.log(data.toString());
            });

            childProcess.stderr.on("data", function (data) {
                console.error(data.toString());
            });
        };
        return Cli;
    })();
    exports.Cli = Cli;
});

Typescript original source file:

 /**
 * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
 * Requires underscore or lodash as global through "_".
 */
export class Cli {

    /**
     * Execute a CLI command.
     * Manage Windows and Unix environment and try to execute the command on both env if fails.
     * Order: Windows -> Unix.
     *
     * @param command                   Command to execute. ('grunt')
     * @param args                      Args of the command. ('watch')
     * @param callback                  Success.
     * @param callbackErrorWindows      Failure on Windows env.
     * @param callbackErrorUnix         Failure on Unix env.
     */
    public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
        Cli.windows(command, args, callback, function () {
            callbackErrorWindows();

            try {
                Cli.unix(command, args, callback, callbackErrorUnix);
            } catch (e) {
                console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
            }
        });
    }

    /**
     * Execute a command on Windows environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(process.env.comspec, _.union(['/c', command], args));
            callback(command, args, 'Windows');
        } catch (e) {
            callbackError(command, args, 'Windows');
        }
    }

    /**
     * Execute a command on Unix environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(command, args);
            callback(command, args, 'Unix');
        } catch (e) {
            callbackError(command, args, 'Unix');
        }
    }

    /**
     * Execute a command no matters what's the environment.
     *
     * @param command   Command to execute. ('grunt')
     * @param args      Args of the command. ('watch')
     * @private
     */
    private static _execute(command, args) {
        var spawn = require('child_process').spawn;
        var childProcess = spawn(command, args);

        childProcess.stdout.on("data", function (data) {
            console.log(data.toString());
        });

        childProcess.stderr.on("data", function (data) {
            console.error(data.toString());
        });
    }
}

Example of use:

    Cli.execute(Grunt._command, args, function (command, args, env) {
        console.log('Grunt has been automatically executed. (' + env + ')');

    }, function (command, args, env) {
        console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');

    }, function (command, args, env) {
        console.error('------------- Unix "' + command + '" command failed too. ---------------');
    });

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

Using psql to connect to PostgreSQL in SSL mode

psql -h <host> -p <port> -U <user> -d <db>

and update /var/lib/pgsql/10/data/pg_hba.conf to change the auth method to cert. Check the following link for more information:

https://www.postgresql.org/docs/9.1/auth-pg-hba-conf.html

Bootstrap 3 Align Text To Bottom of Div

I think your best bet would be to use a combination of absolute and relative positioning.

Here's a fiddle: http://jsfiddle.net/PKVza/2/

given your html:

<div class="row">
    <div class="col-sm-6">
        <img src="~/Images/MyLogo.png" alt="Logo" />
    </div>
    <div class="bottom-align-text col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

use the following CSS:

@media (min-width: 768px ) {
  .row {
      position: relative;
  }

  .bottom-align-text {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}

EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.

send Content-Type: application/json post with node.js

As the official documentation says:

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

When sending JSON you just have to put it in body of the option.

var options = {
    uri: 'https://myurl.com',
    method: 'POST',
    json: true,
    body: {'my_date' : 'json'}
}
request(options, myCallback)

WCF - How to Increase Message Size Quota

For HTTP:

<bindings>
  <basicHttpBinding>
    <binding name="basicHttp" allowCookies="true"
             maxReceivedMessageSize="20000000" 
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
        <readerQuotas maxDepth="200" 
             maxArrayLength="200000000"
             maxBytesPerRead="4096"
             maxStringContentLength="200000000"
             maxNameTableCharCount="16384"/>
    </binding>
  </basicHttpBinding>
</bindings>

For TCP:

<bindings>
  <netTcpBinding>
    <binding name="tcpBinding"
             maxReceivedMessageSize="20000000"
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
      <readerQuotas maxDepth="200"
           maxArrayLength="200000000"
           maxStringContentLength="200000000"
           maxBytesPerRead="4096"
           maxNameTableCharCount="16384"/>
    </binding>
  </netTcpBinding>
</bindings>

IMPORTANT:

If you try to pass complex object that has many connected objects (e.g: a tree data structure, a list that has many objects...), the communication will fail no matter how you increased the Quotas. In such cases, you must increase the containing objects count:

<behaviors>
  <serviceBehaviors>
    <behavior name="NewBehavior">
      ...
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

How can I use an ES6 import in Node.js?

I just wanted to use the import and export in JavaScript files.

Everyone says it's not possible. But, as of May 2018, it's possible to use above in plain Node.js, without any modules like Babel, etc.

Here is a simple way to do it.

Create the below files, run, and see the output for yourself.

Also don't forget to see Explanation below.

File myfile.mjs

function myFunc() {
    console.log("Hello from myFunc")
}

export default myFunc;

File index.mjs

import myFunc from "./myfile.mjs"  // Simply using "./myfile" may not work in all resolvers

myFunc();

Run

node  --experimental-modules  index.mjs

Output

(node:12020) ExperimentalWarning: The ESM module loader is experimental.

Hello from myFunc

Explanation:

  1. Since it is experimental modules, .js files are named .mjs files
  2. While running you will add --experimental-modules to the node index.mjs
  3. While running with experimental modules in the output you will see: "(node:12020) ExperimentalWarning: The ESM module loader is experimental. "
  4. I have the current release of Node.js, so if I run node --version, it gives me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS.
  5. Someday in the future, you could use .js instead of .mjs, as the features become stable instead of Experimental.
  6. More on experimental features, see: https://nodejs.org/api/esm.html

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Here is what worked for me:

If you are installing on a 64-bit machine, make sure the application properties under the Build tab have "Any CPU" as the platform target, and unselect the check box for "Prefer 32-bit" if you have the option. Crystal is very touchy about 32/64 bit assemblies, and makes some pretty counterintuitive assumptions which are very difficult to troubleshoot.

How to have Ellipsis effect on Text

use numberOfLines

https://rnplay.org/plays/ImmKkA/edit

or if you know/or can compute the max character count per row, JS substring may be used.

<Text>{ ((mytextvar).length > maxlimit) ? 
    (((mytextvar).substring(0,maxlimit-3)) + '...') : 
    mytextvar }
</Text>

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Free easy way to draw graphs and charts in C++?

I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot

(Only for the plots part)

If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart

Print string to text file

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.

The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)

Using this regex:

^(?!.*function).*(\&\$)

it is possible to search project-wide for the occurrence of &$ only in lines that are not a function definition.

This still turns up a lot of false positives, but it does make the job easier.

VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

How to delete a file via PHP?

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

C# how to use enum with switch

The correct answer is already given, nevertheless here is the better way (than switch):

private Dictionary<Operator, Func<int, int, double>> operators =
    new Dictionary<Operator, Func<int, int, double>>
    {
        { Operator.PLUS, ( a, b ) => a + b },
        { Operator.MINUS, ( a, b ) => a - b },
        { Operator.MULTIPLY, ( a, b ) => a * b },
        { Operator.DIVIDE ( a, b ) => (double)a / b },
    };

public double Calculate( int left, int right, Operator op )
{
    return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}

How do I create a user account for basic authentication?

It looks to me like Windows 8 and IIS 7 no longer provides any UI to create a user name and password for basic authentication that is NOT a windows local user account. It is clearly a superior approach to create an IIS-only user/password authentication pair, but it is not clear and easy how it is done.

Command line tools exist for this purpose. Some people create a Windows account and then remove the Log on Locally User Privilege.

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

"elseif" syntax in JavaScript

Just add a space:

if (...) {

} else if (...) {

} else {

}

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Android: ProgressDialog.show() crashes with getApplicationContext

If you're calling ProgressDialog.show() in a fragment, casting the mContext to Activity worked for me.

     ProgressDialog pd = new ProgressDialog((Activity) mContext);

How do I loop through children objects in javascript?

I’m surprised no-one answered with this code:

for(var child=elt.firstChild;
    child;
    child=child.nextSibling){
  do_thing(child);
}

Or, if you only want children which are elements, this code:

for(var child=elt.firstElementChild;
    child;
    child=child.nextElementSibling){
  do_thing(child);
}

When does a process get SIGABRT (signal 6)?

A case when process get SIGABRT from itself: Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this. Here when d is to be constructed, it first calls its base class A ctor, and passes inside pointer to itself. the A ctor calls pure virtual method before table was filled with valid pointer, because d is not constructed yet.

#include<iostream>
using namespace std;
class A {
public:
 A(A *pa){pa->f();}
 virtual void f()=0;
};
class D : public A {
public:
 D():A(this){}
 virtual void f() {cout<<"D::f\n";}
};
int main(){
 D d;
 A *pa = &d;
 pa->f();
 return 0;
}

compile: g++ -o aa aa.cpp

ulimit -c unlimited

run: ./aa

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

now lets quickly see the core file, and validate that SIGABRT was indeed called:

gdb aa core

see regs:

i r
rdx            0x6      6
rsi            0x69a    1690
rdi            0x69a    1690
rip            0x7feae3170c37

check code:

disas 0x7feae3170c37

mov    $0xea,%eax  = 234  <- this is the kill syscall, sends signal to process
syscall   <-----

http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/

234 sys_tgkill pid_t tgid pid_t pid int sig = 6 = SIGABRT

:)

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Solution to the problem

as mentioned by Uberfuzzy [ real cause of problem ]

If you look at the PHP constant [PATH_SEPARATOR][1], you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/ph

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

That was the cause of error.

Now coming to solution

  1. Step 1 : Find you php.ini file using command php --ini ( in my case : /etc/php5/cli/php.ini )
  2. Step 2 : find include_path in vi using esc then press /include_path then enter
  3. Step 3 : uncomment that line if commented and include your server directory, your path should look like this include_path = ".:/usr/share/php:/var/www/<directory>/"
  4. Step 4 : Restart apache sudo service apache2 restart

This is it. Hope it helps.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

Convert a secure string to plain text

The easiest way to convert back it in PowerShell

[System.Net.NetworkCredential]::new("", $SecurePassword).Password

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

How to create Password Field in Model Django

See my code which may help you. models.py

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=100)
    instrument_purchase = models.CharField(max_length=100)
    house_no = models.CharField(max_length=100)
    address_line1 = models.CharField(max_length=100)
    address_line2 = models.CharField(max_length=100)
    telephone = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=20)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)

    def __str__(self):
        return self.name

forms.py

from django import forms
from models import *

class CustomerForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = Customer
        fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

jQuery `.is(":visible")` not working in Chrome

This is the piece of code from jquery.js which executes when is(":visible") is called :

if (jQuery.expr && jQuery.expr.filters){

    jQuery.expr.filters.hidden = function( elem ) {
        return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
    };

    jQuery.expr.filters.visible = function( elem ) {
        return !jQuery.expr.filters.hidden( elem );
    };
}

As you can see, it uses more than just the CSS display property. It also depends on the width and height of content of the element. Hence, make sure the element has some width and height. And for doing this, you may need to set the display property to "inline-block" or "block"

Laravel Eloquent: Ordering results of all()

Try this:

$categories     =   Category::all()->sortByDesc("created_at");

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

How can I open a Shell inside a Vim Window?

Not absolutely what you are asking for, but you may be interested by my plugin vim-notebook which allows the user to keep a background process alive and to make it evaluate part of the current document (and to write the output in the document). It is intended to be used on notebook-style documents containing pieces of code to be evaluated.

Mysql - delete from multiple tables with one query

Normally you can't DELETE from multiple tables at once, unless you'll use JOINs as shown in other answers.

However if all yours tables starts with certain name, then this query will generate query which would do that task:

SELECT CONCAT('DELETE FROM ', GROUP_CONCAT(TABLE_NAME SEPARATOR ' WHERE user_id=123;DELETE FROM ') , 'FROM table1;' ) AS statement FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%'

then pipe it (in shell) into mysql command for execution.

For example it'll generate something like:

DELETE FROM table1 WHERE user_id=123;
DELETE FROM table2 WHERE user_id=123;
DELETE FROM table3 WHERE user_id=123;

More shell oriented example would be:

echo "SHOW TABLES LIKE 'table%'" | mysql | tail -n +2 | xargs -L1 -I% echo "DELETE FROM % WHERE user_id=123;" | mysql -v

If you want to use only MySQL for that, you can think of more advanced query, such as this:

SET @TABLES = (SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%');
PREPARE drop_statement FROM 'DELETE FROM @tables';
EXECUTE drop_statement USING @TABLES;
DEALLOCATE PREPARE drop_statement;

The above example is based on: MySQL – Delete/Drop all tables with specific prefix.

How do I horizontally center a span element inside a div

another option would be to give the span display:table; and center it via margin:0 auto;

span {
display:table;
margin:0 auto;
}

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

Get selected value in dropdown list using JavaScript

Just use

  • $('#SelectBoxId option:selected').text(); for getting the text as listed

  • $('#SelectBoxId').val(); for getting the selected index value

Response.Redirect to new window

If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:

protected void MyButton_OnPreRender(object sender, EventArgs e)
{
    string URL = "~/MyPage.aspx";
    URL = Page.ResolveClientUrl(URL);
    MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}

java.math.BigInteger cannot be cast to java.lang.Long

It's a very old post, but if it benefits anyone, we can do something like this:

Long max=((BigInteger) Collections.max(dynamics)).longValue(); 

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

Maximum packet size for a TCP connection

There're no packets in TCP API.

There're packets in underlying protocols often, like when TCP is done over IP, which you have no interest in, because they have nothing to do with the user except for very delicate performance optimizations which you are probably not interested in (according to the question's formulation).

If you ask what is a maximum number of bytes you can send() in one API call, then this is implementation and settings dependent. You would usually call send() for chunks of up to several kilobytes, and be always ready for the system to refuse to accept it totally or partially, in which case you will have to manually manage splitting into smaller chunks to feed your data into the TCP send() API.

Remove a character at a certain position in a string - javascript

Turn the string into array, cut a character at specified index and turn back to string

let str = 'Hello World'.split('')

str.splice(3, 1)
str = str.join('')

// str = 'Helo World'.

Find the number of employees in each department - SQL Oracle

Please try:

select count(*) as count,dept.DNAME 
from emp 
inner join dept on emp.DEPTNO = dept.DEPTNO 
group by dept.DNAME

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

X is a dataframe and can't be accessed via slice terminology like X[:, 3]. You must access via iloc or X.values. However, the way you constructed X made it a copy... so. I'd use values

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')

dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()

#  I changed this line
X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])

Split string into string array of single characters

Try this:

var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

undefined reference to WinMain@16 (codeblocks)

  1. You need to open the project file of your program and it should appear on Management panel.

  2. Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)

  3. Compile and enjoy. Hope, I could help you.

How to create a inset box-shadow only on one side?

This might not be the exact thing you are looking for, but you can create a very similar effect by using rgba in combination with linear-gradient:

  background: linear-gradient(rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%);

This creates a linear-gradient from black with 50% opacity (rgba(0,0,0,.5)) to transparent (rgba(0,0,0,0)) which starts being competently transparent 30% from the top. You can play with those values to create your desired effect. You can have it on a different side by adding a deg-value (linear-gradient(90deg, rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%)) or switching the colors around. If you want really complex shadows like different angles on different sides you could even start layering linear-gradient.

Here is a snippet to see it in action:

_x000D_
_x000D_
.box {_x000D_
  background: linear-gradient(rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%);_x000D_
}_x000D_
_x000D_
.text {_x000D_
  padding: 20px;_x000D_
}
_x000D_
<div class="box">_x000D_
  <div class="text">_x000D_
    Lorem ipsum ...._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

How do I concatenate strings in Swift?

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

CSS media query to target iPad and iPad only?

I am a bit late to answer this but none of the above worked for me.

This is what worked for me

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
    //your styles here
   }

HashSet vs. List performance

Depends on what you're hashing. If your keys are integers you probably don't need very many items before the HashSet is faster. If you're keying it on a string then it will be slower, and depends on the input string.

Surely you could whip up a benchmark pretty easily?

Error message "Linter pylint is not installed"

Try doing this if you're running Visual Studio Code on a Windows machine and getting this error (I'm using Windows 10).

Go to the settings and change the Python path to the location of YOUR python installation.

I.e.,

Change: "python.pythonPath": "python"

To: "python.pythonPath": "C:\\Python36\\python.exe"

And then: Save and reload Visual Studio Code.

Now when you get the prompt telling you that "Linter pylint is not installed", just select the option to 'install pylint'.

Since you've now provided the correct path to your Python installation, the Pylint installation will be successfully completed in the Windows PowerShell Terminal.

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

How to find the last day of the month from date?

t returns the number of days in the month of a given date (see the docs for date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

Why is there no Char.Empty like String.Empty?

Use Char.MinValue which works the same as '\0'. But be careful it is not the same as String.Empty.

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

Short form for Java if statement

Simple & clear:

String manType = hasMoney() ? "rich" : "poor";

long version:

      String manType;
    if (hasMoney()) {
        manType = "rich";
    } else {
        manType = "poor";
    }

or how I'm using it to be clear for other code readers:

 String manType = "poor";
    if (hasMoney())
        manType = "rich";

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

Get Country of IP Address with PHP

Use the widget www.feedsalive.com, to get the country informations & last page information as well.

smooth scroll to top

Elegant easy solution using jQuery.

<script>
    function call() {
        var body = $("html, body");
        body.stop().animate({scrollTop:0}, 500, 'swing', function() {
        });
    }
</script>

and in your html : <div onclick="call()"><img src="../img/[email protected]"></div>

JAXB :Need Namespace Prefix to all the elements

MSK,

Have you tried setting a namespace declaration to your member variables like this? :

@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;

@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;

For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Looping through JSON with node.js

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

How can I make my string property nullable?

You don't need to do anything, the Model Binding will pass null to property without any problem.

Could not instantiate mail function. Why this error occurring

Had same problem. Just did a quick look up apache2 error.log file and it said exactly what was the problem:

> sh: /usr/sbin/sendmail: Permission denied

So, the solution was to give proper permissions for /usr/sbin/sendmail file (it wasn't accessible from php).

Command to do this would be:

> chmod 777 /usr/sbin/sendmail

be sure that it even exists!

How to prevent scrollbar from repositioning web page?

If changing size or after loading some data it is adding the scroll bar then you can try following, create class and apply this class.

.auto-scroll {
   overflow-y: overlay;
   overflow-x: overlay;
}

Linux/Unix command to determine if process is running?

This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.

   egrep -m1  "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3

Little explanation what is going on:

  1. -m1 - stop process on first match
  2. "mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
  3. /proc/[0-9]* - bash will match line which started with any number
  4. cut - just split the output by delimiter '/' and extract field 3

#define macro for debug printing in C?

For a portable (ISO C90) implementation, you could use double parentheses, like this;

#include <stdio.h>
#include <stdarg.h>

#ifndef NDEBUG
#  define debug_print(msg) stderr_printf msg
#else
#  define debug_print(msg) (void)0
#endif

void
stderr_printf(const char *fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
}

int
main(int argc, char *argv[])
{
  debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
  return 0;
}

or (hackish, wouldn't recommend it)

#include <stdio.h>

#define _ ,
#ifndef NDEBUG
#  define debug_print(msg) fprintf(stderr, msg)
#else
#  define debug_print(msg) (void)0
#endif

int
main(int argc, char *argv[])
{
  debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
  return 0;
}

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

_x000D_
_x000D_
this.setState((state =>{_x000D_
  return{_x000D_
    something_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

Play sound on button click android

public class MainActivity extends AppCompatActivity {

    public void clickMe (View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
        mp.start();

    }

create a button with a method could be called when the button pressed (onCreate),

then create a variable for (MediaPlayer) class with the path of your file

MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);

finally run start method in that class

mp.start();

the file will run when the button pressed, hope this was helpful!

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

How do I get the current date in Cocoa

You can also use:


CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02.0f", currentDate.hour, currentDate.minute, currentDate.second];
CFRelease(currentDate); // Don't forget this! VERY important

I think this has the following advantages:

  1. No direct memory allocation.
  2. Seconds is a double instead of an integer.
  3. No message calls.
  4. Faster.

Access files stored on Amazon S3 through web browser

I found this related question: Directory Listing in S3 Static Website

As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.

There are three ways you could go for generating listings:

  • Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.

  • Use a client-side S3 browser tool.

  • Use a server-side browser tool.

    • s3browser (PHP)
    • s3index Scala. Going by the existence of a Procfile, it may be readily deployable to Heroku. Not sure since I don't have any experience with Scala.

How to make Python speak

There are a number of ways to make Python speak in both Python3 and Python2, two great methods are:

  • Using os

If you are on mac you will have the os module built into your computer. You can import the os module using:

import os

You can then use os to run terminal commands using the os.system command:

os.system("Your terminal")

In terminal, the way you make your computer speak is using the "say" command, thus to make the computer speak you simply use:

os.system("say 'some text'")

If you want to use this to speak a variable you can use:

os.system("say " + myVariable)

The second way to get python to speak is to use

  • The pyttsx module

You will have to install this using

pip isntall pyttsx3

or for Python3

pip3 install pyttsx3

You can then use the following code to get it to speak:

import pyttsx3
engine = pyttsx3.init()

engine.say("Your Text")

engine.runAndWait()

I hope this helps! :)

Remove IE10's "clear field" X button on certain inputs?

I found it's better to set the width and height to 0px. Otherwise, IE10 ignores the padding defined on the field -- padding-right -- which was intended to keep the text from typing over the 'X' icon that I overlayed on the input field. I'm guessing that IE10 is internally applying the padding-right of the input to the ::--ms-clear pseudo element, and hiding the pseudo element does not restore the padding-right value to the input.

This worked better for me:

.someinput::-ms-clear {
  width : 0;
  height: 0;
}

Using C++ filestreams (fstream), how can you determine the size of a file?

Like this:

long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;

How to extract filename.tar.gz file

Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Inline instantiation of a constant List

You'll need to use a static readonly list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T> rather than List<T>.

private static readonly ReadOnlyCollection<string> _metrics =
    new ReadOnlyCollection<string>(new[]
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        });

public static ReadOnlyCollection<string> Metrics
{
    get { return _metrics; }
}