Programs & Examples On #Editcontrol

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

How to cast an object in Objective-C

Typecasting in Objective-C is easy as:

NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];

However, what happens if first object is not UIView and you try to use it:

NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!

It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:

UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");

Those assertions doesn't look very nice, so we could improve them with this handy category:

@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end


@implementation NSObject (TypecastWithAssertion)

+ (instancetype)typecastWithAssertion:(id)object {
    if (object != nil)
        NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
    return object;
}

@end

This is much better:

UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];

P.S. For collections type safety Xcode 7 have a much better than typecasting - generics

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

non-null assertion operator

With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.

Example

TS code

function simpleExample(nullableArg: number | undefined | null) {
   const normal: number = nullableArg; 
    //   Compile err: 
    //   Type 'number | null | undefined' is not assignable to type 'number'.
    //   Type 'undefined' is not assignable to type 'number'.(2322)

   const operatorApplied: number = nullableArg!; 
    // compiles fine because we tell compiler that null | undefined are excluded 
}

Compiled JS code

Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

_x000D_
_x000D_
"use strict";
function simpleExample(nullableArg) {
    const normal = nullableArg;
    const operatorApplied = nullableArg;
 }
_x000D_
_x000D_
_x000D_

How to sort an ArrayList?

You can use like that

ArrayList<Group> groupList = new ArrayList<>();
Collections.sort(groupList, Collections.reverseOrder());
Collections.reverse(groupList);

iPhone Safari Web App opens links in new window

This is slightly adapted version of Sean's which was preventing back button

// this function makes anchor tags work properly on an iphone

$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
  // For iOS Apps
  $("a").on("click", function(e){

    var new_location = $(this).attr("href");
    if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
      e.preventDefault();
      window.location = new_location;
    }
  });
}

});

What does the "+=" operator do in Java?

It's one of the assignment operators. It takes the value of x, adds 0.1 to it, and then stores the result of (x + 0.1) back into x.

So:

double x = 1.3;
x += 0.1;    // sets 'x' to 1.4

It's functionally identical to, but shorter than:

double x = 1.3;
x = x + 0.1;

NOTE: When doing floating-point math, things don't always work the way you think they will.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

If you are using the portable XAMPP installation and Windows 7, and, like me have the version after they removed the XAMPP shell from the control panel none of the suggested answers here will do you much good as the packages will not install.

The problem is with the config file. I found the correct settings after a lot of trial and error.

Simply pull up a command window in the \xampp\php directory and run

pear config-set doc_dir :\xampp\php\docs\PEAR
pear config-set cfg_dir :\xampp\php\cfg
pear config-set data_dir :\xampp\php\data\PEAR
pear config-set test_dir :\xampp\php\tests
pear config-set www_dir :\xampp\php\www

you will want to replace the ':' with the actual drive letter that your portable drive is running on at the moment. Unfortunately, this needs to be done any time this drive letter changes, but it did get the module I needed installed.

Get escaped URL parameter

You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.

I've created a tiny module that can parse the query string into an object. Use it like this:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

Split string in JavaScript and detect line break

In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.

Split string by newline:

Result.split('\n');

Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:

Result.split('\\n');

Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case: enter image description here

split string only on first instance - java

String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
   if(apple.charAt(i)=='='){
      tmp[0]=apple.substring(0,i);
      tmp[1]=apple.substring(i+1,apple.length);
      break;
   }
}
return tmp;
}
//returns string_ARRAY_!

i like writing own methods :)

How can I loop through a List<T> and grab each item?

Just for completeness, there is also the LINQ/Lambda way:

myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));

How to compare two dates along with time in java

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Like

if(date1.compareTo(date2)>0) 

string sanitizer for filename

The best I know today is static method Strings::webalize from Nette framework.

BTW, this translates all diacritic signs to their basic.. š=>s ü=>u ß=>ss etc.

For filenames you have to add dot "." to allowed characters parameter.

/**
 * Converts to ASCII.
 * @param  string  UTF-8 encoding
 * @return string  ASCII
 */
public static function toAscii($s)
{
    static $transliterator = NULL;
    if ($transliterator === NULL && class_exists('Transliterator', FALSE)) {
        $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
    }

    $s = preg_replace('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s);
    $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
    $s = str_replace(
        array("\xE2\x80\x9E", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x9A", "\xE2\x80\x98", "\xE2\x80\x99", "\xC2\xB0"),
        array("\x03", "\x03", "\x03", "\x02", "\x02", "\x02", "\x04"), $s
    );
    if ($transliterator !== NULL) {
        $s = $transliterator->transliterate($s);
    }
    if (ICONV_IMPL === 'glibc') {
        $s = str_replace(
            array("\xC2\xBB", "\xC2\xAB", "\xE2\x80\xA6", "\xE2\x84\xA2", "\xC2\xA9", "\xC2\xAE"),
            array('>>', '<<', '...', 'TM', '(c)', '(R)'), $s
        );
        $s = @iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); // intentionally @
        $s = strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e"
            . "\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
            . "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8"
            . "\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe"
            . "\x96\xa0\x8b\x97\x9b\xa6\xad\xb7",
            'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.');
        $s = preg_replace('#[^\x00-\x7F]++#', '', $s);
    } else {
        $s = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); // intentionally @
    }
    $s = str_replace(array('`', "'", '"', '^', '~', '?'), '', $s);
    return strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
}


/**
 * Converts to web safe characters [a-z0-9-] text.
 * @param  string  UTF-8 encoding
 * @param  string  allowed characters
 * @param  bool
 * @return string
 */
public static function webalize($s, $charlist = NULL, $lower = TRUE)
{
    $s = self::toAscii($s);
    if ($lower) {
        $s = strtolower($s);
    }
    $s = preg_replace('#[^a-z0-9' . preg_quote($charlist, '#') . ']+#i', '-', $s);
    $s = trim($s, '-');
    return $s;
}

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

DateTime's representation in milliseconds?

Using the answer of Andoma, this is what I'm doing

You can create a Struct or a Class like this one

struct Date
    {
        public static double GetTime(DateTime dateTime)
        {
            return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        public static DateTime DateTimeParse(double milliseconds)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
        }

    }

And you can use this in your code as following

DateTime dateTime = DateTime.Now;

double total = Date.GetTime(dateTime);

dateTime = Date.DateTimeParse(total);

I hope this help you

Using Cygwin to Compile a C program; Execution error

Look for (that is, cd to)

/cygdrive/c/

that will usually be your C:\


Also look at Using Cygwin, the Lifehacker introduction (June/2006) and, this biomed page at PhysioNet.

Find a file in python

I used a version of os.walk and on a larger directory got times around 3.5 sec. I tried two random solutions with no great improvement, then just did:

paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()]

While it's POSIX-only, I got 0.25 sec.

From this, I believe it's entirely possible to optimise whole searching a lot in a platform-independent way, but this is where I stopped the research.

How many threads can a Java VM support?

This depends on the CPU you're using, on the OS, on what other processes are doing, on what Java release you're using, and other factors. I've seen a Windows server have > 6500 Threads before bringing the machine down. Most of the threads were not doing anything, of course. Once the machine hit around 6500 Threads (in Java), the whole machine started to have problems and become unstable.

My experience shows that Java (recent versions) can happily consume as many Threads as the computer itself can host without problems.

Of course, you have to have enough RAM and you have to have started Java with enough memory to do everything that the Threads are doing and to have a stack for each Thread. Any machine with a modern CPU (most recent couple generations of AMD or Intel) and with 1 - 2 Gig of memory (depending on OS) can easily support a JVM with thousands of Threads.

If you need a more specific answer than this, your best bet is to profile.

Delete element in a slice

... is syntax for variadic arguments.

I think it is implemented by the complier using slice ([]Type), just like the function append :

func append(slice []Type, elems ...Type) []Type

when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

a[0:0] is a slice which has nothing

a[1:] is "Hello2 Hello3"

This is how it works

How to execute powershell commands from a batch file?

Type in cmd.exe Powershell -Help and see the examples.

What exactly does an #if 0 ..... #endif block do?

Not quite

int main(void)
{
   #if 0
     the apostrophe ' causes a warning
   #endif
   return 0;
}

It shows "t.c:4:19: warning: missing terminating ' character" with gcc 4.2.4

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

When the project was originally created, the click-once signing certificate was added on the signing tab of the project's properties. This signs the click-once manifest when you build it. Between then and now, that certificate is no longer available. Either this wasn't the machine you originally built it on or it got cleaned up somehow. You need to re-add that certificate to your machine or chose another certificate.

Chart creating dynamically. in .net, c#

Add a reference to System.Windows.Form.DataVisualization, then add the appropriate using statement:

using System.Windows.Forms.DataVisualization.Charting;

private void CreateChart()
{
    var series = new Series("Finance");

    // Frist parameter is X-Axis and Second is Collection of Y- Axis
    series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
    chart1.Series.Add(series);

}

How to echo with different colors in the Windows command line

I just converted from Win 7 Home to Win 10 Pro and wanted to replace the batch I call from other batches to echo info in color. Reviewing what is discussed above I use the following which will directly replace my previous batch. NOTE the addition of "~" to the message so that messages with spaces may be used. Instead of remembering codes I use letters for the colors I needed.

If %2 contains spaces requires "..." %1 Strong Colors on black: R=Red G=GREEN Y=YELLOW W=WHITE

ECHO OFF
IF "%1"=="R" ECHO ^[91m%~2[0m
IF "%1"=="G" ECHO ^[92m%~2[0m
IF "%1"=="Y" ECHO ^[93m%~2[0m
IF "%1"=="W" ECHO ^[97m%~2[0m

ASP.NET MVC 404 Error Handling

What I can recomend is to look on FilterAttribute. For example MVC already has HandleErrorAttribute. You can customize it to handle only 404. Reply if you are interesed I will look example.

BTW

Solution(with last route) that you have accepted in previous question does not work in much of the situations. Second solution with HandleUnknownAction will work but require to make this change in each controller or to have single base controller.

My choice is a solution with HandleUnknownAction.

Constructors in JavaScript objects

So what is the point of "constructor" property? Cannot figure out where it could be useful, any ideas?

The point of the constructor property is to provide some way of pretending JavaScript has classes. One of the things you cannot usefully do is change an object's constructor after it's been created. It's complicated.

I wrote a fairly comprehensive piece on it a few years ago: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

Using jQuery, Restricting File Size Before Uploading

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Clear data in MySQL table with PHP?

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

Select mysql query between date?

You can use now() like:

Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();

How to resolve TypeError: Cannot convert undefined or null to object

Generic answer

This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example

Object.keys(null)
Object.assign(window.UndefinedVariable, {})

As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.

Object.keys({'key': 'value'})
if (window.UndefinedVariable) {
    Object.assign(window.UndefinedVariable, {})
}

Answer specific to the code in question

The line if (obj === 'null') { return null;} // null unchanged will not evaluate when given null, only if given the string "null". So if you pass the actual null value to your script, it will be parsed in the Object part of the code. And Object.keys(null) throws the TypeError mentioned. To fix it, use if(obj === null) {return null} - without the qoutes around null.

How to base64 encode image in linux bash / shell

Single line result:

base64 -w 0 DSC_0251.JPG

For HTML:

echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

As file:

base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64

In variable:

IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"

In variable for HTML:

IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

Get you readable data back:

base64 -d DSC_0251.base64 > DSC_0251.JPG 

See: http://www.greywyvern.com/code/php/binary2base64

How to sync with a remote Git repository?

You need to add the original repository (the one that you forked) as a remote.

git remote add github (clone url for the orignal repository)

Then you need to bring in the changes to your local repository

git fetch github

Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master. With these branches you can do what you will. Merge them into your branches etc

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

Simple way to encode a string according to a password?

Working encode/decode functions in python3 (adapted very little from qneill's answer):

def encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = (ord(clear[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return base64.urlsafe_b64encode(bytes(enc))

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

Key Shortcut for Eclipse Imports

Ctrl+Space : Show Imports

This displays imports as you're typing a non-standard class name provided the proper references have been added to the project.

This works on partial or complete class names as you are typing them or after the fact (Just place the cursor back on the class name with squigglies).

Batch file to perform start, run, %TEMP% and delete all

If you want to remove all the files in the %TEMP% folder you could just do this:

del %TEMP%\*.* /f /s /q

That will remove everything, any file with any extension (*.*) and do the same for all sub-folders (/s), without prompting you for anything (/q), it will just do it, including read only files (/f).

Hope this helps.

tar: add all files and directories in current directory INCLUDING .svn and so on

You can fix the . form by using --exclude:

tar -czf workspace.tar.gz --exclude=workspace.tar.gz .

How to run code after some delay in Flutter?

You can use Future.delayed to run your code after some time. e.g.:

Future.delayed(const Duration(milliseconds: 500), () {

// Here you can write your code

  setState(() {
    // Here you can write your code for open new view
  });

});

In setState function, you can write a code which is related to app UI e.g. refresh screen data, change label text, etc.

How can I convert string to datetime with format specification in JavaScript?

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

Remove empty elements from an array in Javascript

For removing holes, you should use

arr.filter(() => true)
arr.flat(0) // New in ES2019, check compatibility before using this

For removing hole, null, and, undefined:

arr.filter(x => x != null)

For removing hole, and, falsy (null, undefined, 0, -0, 0n, NaN, "", false, document.all) values:

arr.filter(x => x)

_x000D_
_x000D_
arr = [, null, (void 0), 0, -0, 0n, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, 0n, NaN, false, '', 42]
console.log(arr.filter(x => x != null)); // [0, -0, 0n, NaN, false, "", 42]
console.log(arr.filter(x => x)); // [42]
_x000D_
_x000D_
_x000D_

How to cut an entire line in vim and paste it?

Pressing Shift+v would select that entire line and pressing d would delete it.

You can also use dd, which is does not require you to enter visual mode.

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

How do I select an element with its name attribute in jQuery?

$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

JavaScript: Is there a way to get Chrome to break on all errors?

Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.

I realize this question has an answer, but it's no longer accurate. Use the link above ^


(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)

Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.

Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Virtual box version 4.3.28 worked with Genymotion 2.5.2 for me. Nothing else seemed to work.

Best way to require all files from a directory in ruby?

I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:

Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }

What is the cleanest way to get the progress of JQuery ajax request?

Something like this for $.ajax (HTML5 only though):

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress here
            }
       }, false);

       xhr.addEventListener("progress", function(evt) {
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               //Do something with download progress
           }
       }, false);

       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});

How to create full compressed tar file using Python?

In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)

with tarfile.open("save.tar.gz","w:gz"):
      for file in ["a.txt","b.log","c.png"]:
           tar.add(os.path.basename(file))

its use in tar.gz file compress in directory

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

display Java.util.Date in a specific format

If you want to simply output a date, just use the following:

System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());

As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:

String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());

You can also customize your output by following the Java API on Date/Time conversions.

Java Round up Any Number

I don't know why you are dividing by 100 but here my assumption int a;

int b = (int) Math.ceil( ((double)a) / 100);

or

int b = (int) Math.ceil( a / 100.0);

Can I scale a div's height proportionally to its width using CSS?

One way usefull when you work with images, but can be used as workaround otherwise:

<html>
<head>
</head>
<style>
    #someContainer {
        width:50%;
        position: relative;
    }
    #par {
        width: 100%;
        background-color:red;
    }
    #image {
        width: 100%;
        visibility: hidden;
    }
    #myContent {
        position:absolute;
    }
</style>
<div id="someContainer">
    <div id="par">
        <div id="myContent">
            <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </p>    
        </div>
        <img src="yourImage" id="image"/>
    </div>
</div>
</html>

To use replace yourImage with your image url. You use image with width / height ratio you desire.

div id="myContent" is here as example of workaround where myContent will overlay over image.

This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

How to change the background-color of jumbrotron?

You can use the following to change the background-color of a Jumbotron:

<div class="container">
    <div class="jumbotron text-white" style="background-color: #8c6278;">
        <h1>Coffee lover project !</h1>
    </div>
</div>

How to use http.client in Node.js if there is basic authorization

var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );

How do I activate a virtualenv inside PyCharm's terminal?

On Mac it's PyCharm => Preferences... => Tools => Terminal => Activate virtualenv, which should be enabled by default.

Check if current directory is a Git repository

if ! [[ $(pwd) = *.git/* || $(pwd) = *.git ]]; then 
  if type -P git >/dev/null; then
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
     printf '\n%s\n\n' "GIT repository detected." && git status
    }
  fi
fi

Thank you ivan_pozdeev, Now I have a test if inside the .git directory the code will not run so no errors printed out or false exit status.

The "! [[ $(pwd) = .git/ || $(pwd) = *.git ]]" tests if you're not inside a .git repo then it will run the git command. The builtin type command is use to check if you have git installed or it is within your PATH. see help type

Getting return value from stored procedure in C#

This SP looks very strange. It does not modify what is passed to @b. And nowhere in the SP you assign anything to @b. And @Password is not defined, so this SP will not work at all.

I would guess you actually want to return @Password, or to have SET @b = (SELECT...)

Much simpler will be if you modify your SP to (note, no OUTPUT parameter):

set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go

ALTER PROCEDURE [dbo].[Validate] @a varchar(50)

AS

SELECT TOP 1 Password FROM dbo.tblUser WHERE Login = @a

Then, your code can use cmd.ExecuteScalar, and receive the result.

How to keep keys/values in same order as declared?

Generally, you can design a class that behaves like a dictionary, mainly be implementing the methods __contains__, __getitem__, __delitem__, __setitem__ and some more. That class can have any behaviour you like, for example prividing a sorted iterator over the keys ...

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

Rounding to two decimal places in Python 2.7?

You can use str.format(), too:

>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23

Convert interface{} to int

I am assuming: If you sent the JSON value through browser then any number you sent that will be the type float64 so you cant get the value directly int in golang.

So do the conversion like:

//As that says: 
fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64

var iAreaId int = int(val.(float64))

This way you can get exact value what you wanted.

Random state (Pseudo-random number) in Scikit learn

sklearn.model_selection.train_test_split(*arrays, **options)[source]

Split arrays or matrices into random train and test subsets

Parameters: ... 
    random_state : int, RandomState instance or None, optional (default=None)

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune

What is a stack pointer used for in microprocessors?

You got more preparing [for the exam] to do ;-)

The Stack Pointer is a register which holds the address of the next available spot on the stack.

The stack is a area in memory which is reserved to store a stack, that is a LIFO (Last In First Out) type of container, where we store the local variables and return address, allowing a simple management of the nesting of function calls in a typical program.

See this Wikipedia article for a basic explanation of the stack management.

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

jQuery - Trigger event when an element is removed from the DOM

For those who use jQuery UI:

jQuery UI has overridden some of the jQuery methods to implement a remove event that gets handled not only when you explicitly remove the given element, but also if the element gets removed from the DOM by any self-cleaning jQuery methods (e.g. replace, html, etc.). This basically allows you to put a hook into the same events that get fired when jQuery is "cleaning up" the events and data associated with a DOM element.

John Resig has indicated that he's open to the idea of implementing this event in a future version of jQuery core, but I'm not sure where it stands currently.

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

transform object to array with lodash

Object to Array

Of all the answers I think this one is the best:

let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))

that transforms:

{
  a: { p: 1, q: 2},
  b: { p: 3, q: 4}
}

to:

[
  { key: 'a', p: 1, q: 2 }, 
  { key: 'b', p: 3, q: 4 }
]

Array to Object

To transform back:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})

To transform back keeping the key in the value:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})

Will give:

{
  a: { key: 'a', p: 1, q: 2 },
  b: { key: 'b', p: 3, q: 4 }
}

For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

How to start an application using android ADB tools?

adb shell
am start -n com.package.name/com.package.name.ActivityName

Or you can use this directly:

adb shell am start -n com.package.name/com.package.name.ActivityName

You can also specify actions to be filter by your intent-filters:

am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName 

Format date as dd/MM/yyyy using pipes

You have to pass the locale string as an argument to DatePipe.

var ddMMyyyy = this.datePipe.transform(new Date(),"dd-MM-yyyy");

Pre-defined format options:

1.      'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
2.      'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
3.      'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
4.      'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
5.      'shortDate': equivalent to 'M/d/yy' (6/15/15).
6.      'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
7.      'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
8.      'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
9.      'shortTime': equivalent to 'h:mm a' (9:03 AM).
10. 'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
11. 'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
12. 'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

add datepipe in app.component.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {DatePipe} from '@angular/common';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    DatePipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

CSS Background Image Not Displaying

body { 
        background: url("../img/debut_dark.png") no-repeat center center fixed;
    }

Worked for me.

How do I find out what is hammering my SQL Server?

This query uses DMV's to identify the most costly queries by CPU

SELECT TOP 20
    qs.sql_handle,
    qs.execution_count,
    qs.total_worker_time AS Total_CPU,
    total_CPU_inSeconds = --Converted from microseconds
        qs.total_worker_time/1000000,
    average_CPU_inSeconds = --Converted from microseconds
        (qs.total_worker_time/1000000) / qs.execution_count,
    qs.total_elapsed_time,
    total_elapsed_time_inSeconds = --Converted from microseconds
        qs.total_elapsed_time/1000000,
    st.text,
    qp.query_plan
FROM
    sys.dm_exec_query_stats AS qs
CROSS APPLY 
    sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY
    sys.dm_exec_query_plan (qs.plan_handle) AS qp
ORDER BY 
    qs.total_worker_time DESC

For a complete explanation see: How to identify the most costly SQL Server queries by CPU

What happened to console.log in IE8?

I really like the approach posted by "orange80". It's elegant because you can set it once and forget it.

The other approaches require you to do something different (call something other than plain console.log() every time), which is just asking for trouble… I know that I'd eventually forget.

I've taken it a step further, by wrapping the code in a utility function that you can call once at the beginning of your javascript, anywhere as long as it's before any logging. (I'm installing this in my company's event data router product. It will help simplify the cross-browser design of its new admin interface.)

/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
function fixConsole(alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
}

How do I loop through a date range?

DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;

while ((startDate = startDate.AddDays(interval)) <= stopDate)
{
    // do your thing
}

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Simply just append your fields and their values to the elements:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);

What does "commercial use" exactly mean?

"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.

Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).

Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.

You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:

  • Use it internally as much as you want (see here)
  • Run it on your internal servers for external users / clients / customers, or run it on your internal servers for paying clients if you're an ISP / hosting provider. (If Screwturn were licensed under the AGPL instead of the GPL, that might restrict this.)
  • Distribute it to others, either free of charge or for a payment that covers the shipping, as long as you're willing to also distribute the source code
  • Incorporate it into your product, as long as you're willing to also distribute the source code, and as long as either (a) it remains a separate program that you merely aggregate with your product or (b) you release the source code to your product under an open source license compatible with the GPL

In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.

All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.

PHP foreach change original array values

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.

Keyboard shortcuts in WPF

Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement, especially when the Window is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.

Snippet

public sealed class AttachedProperties
{
    // Define the key gesture type converter
    [System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
    public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
    {
        return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
    }

    public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
    {
        dependencyObject?.SetValue(FocusShortcutProperty, value);
    }

    /// <summary>
    /// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
    /// </summary>
    // Using a DependencyProperty as the backing store for FocusShortcut.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FocusShortcutProperty =
        DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));

    private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is UIElement element) || e.NewValue == e.OldValue)
            return;

        var window = FindParentWindow(d);
        if (window == null)
            return;

        var gesture = GetFocusShortcut(d);
        if (gesture == null)
        {
            // Remove previous added input binding.
            for (int i = 0; i < window.InputBindings.Count; i++)
            {
                if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
                    window.InputBindings.RemoveAt(i--);
            }
        }
        else
        {
            // Add new input binding with the dedicated FocusElementCommand.
            // see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
            var command = new FocusElementCommand(element);
            window.InputBindings.Add(new InputBinding(command, gesture));
        }
    }
}

With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.

Usage (XAML)

<TextBox x:Name="SearchTextBox"
         Text={Binding Path=SearchText}
         local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>

Source code

The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d

Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

Find files in created between a date range

You can use the below to find what you need.

Find files older than a specific date/time:

find ~/ -mtime $(echo $(date +%s) - $(date +%s -d"Dec 31, 2009 23:59:59") | bc -l | awk '{print $1 / 86400}' | bc -l)

Or you can find files between two dates. First date more recent, last date, older. You can go down to the second, and you don't have to use mtime. You can use whatever you need.

find . -mtime $(date +%s -d"Aug 10, 2013 23:59:59") -mtime $(date +%s -d"Aug 1, 2013 23:59:59")

How can I split a text into sentences?

Instead of using regex for spliting the text into sentences, you can also use nltk library.

>>> from nltk import tokenize
>>> p = "Good morning Dr. Adams. The patient is waiting for you in room number 3."

>>> tokenize.sent_tokenize(p)
['Good morning Dr. Adams.', 'The patient is waiting for you in room number 3.']

ref: https://stackoverflow.com/a/9474645/2877052

How can I time a code segment for testing performance with Pythons timeit?

The testing suite doesn't make an attempt at using the imported timeit so it's hard to tell what the intent was. Nonetheless, this is a canonical answer so a complete example of timeit seems in order, elaborating on Martijn's answer.

The docs for timeit offer many examples and flags worth checking out. The basic usage on the command line is:

$ python -mtimeit "all(True for _ in range(1000))"
2000 loops, best of 5: 161 usec per loop
$ python -mtimeit "all([True for _ in range(1000)])"
2000 loops, best of 5: 116 usec per loop

Run with -h to see all options. Python MOTW has a great section on timeit that shows how to run modules via import and multiline code strings from the command line.

In script form, I typically use it like this:

import argparse
import copy
import dis
import inspect
import random
import sys
import timeit

def test_slice(L):
    L[:]

def test_copy(L):
    L.copy()

def test_deepcopy(L):
    copy.deepcopy(L)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--n", type=int, default=10 ** 5)
    parser.add_argument("--trials", type=int, default=100)
    parser.add_argument("--dis", action="store_true")
    args = parser.parse_args()
    n = args.n
    trials = args.trials
    namespace = dict(L = random.sample(range(n), k=n))
    funcs_to_test = [x for x in locals().values() 
                     if callable(x) and x.__module__ == __name__]
    print(f"{'-' * 30}\nn = {n}, {trials} trials\n{'-' * 30}\n")

    for func in funcs_to_test:
        fname = func.__name__
        fargs = ", ".join(inspect.signature(func).parameters)
        stmt = f"{fname}({fargs})"
        setup = f"from __main__ import {fname}"
        time = timeit.timeit(stmt, setup, number=trials, globals=namespace)
        print(inspect.getsource(globals().get(fname)))

        if args.dis:
            dis.dis(globals().get(fname))

        print(f"time (s) => {time}\n{'-' * 30}\n")

You can pretty easily drop in the functions and arguments you need. Use caution when using impure functions and take care of state.

Sample output:

$ python benchmark.py --n 10000
------------------------------
n = 10000, 100 trials
------------------------------

def test_slice(L):
    L[:]

time (s) => 0.015502399999999972
------------------------------

def test_copy(L):
    L.copy()

time (s) => 0.01651419999999998
------------------------------

def test_deepcopy(L):
    copy.deepcopy(L)

time (s) => 2.136012
------------------------------

Best implementation for Key Value Pair Data Structure?

There is an actual Data Type called KeyValuePair, use like this

KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I got it solved by installing OpenSSL according to the following recommendation: https://github.com/conda/conda/issues/8046#issuecomment-450515815

Corresponding ticket in the conda repository: https://github.com/conda/conda/issues/8046

Update: the problem (in PyCharm) should be solved in 2019.1 version (Early Access Preview build is already available https://www.jetbrains.com/pycharm/nextversion/).

Open source face recognition for Android

Here are some links that I found on face recognition libraries.

Image Identification links:

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

If you have to use the older client, here is my experience.

We are running a 32bit server so the development machines run the 32bit client. We run the 11.1 install, 11.2 gets the error. Once you have installed the 11.2 version you have to manually delete the files Oracle.Web.dll and System.Data.OracleClient.dll from the %windir%\Microsoft.NET\Framework\v2.0.50727, reinstall 11.1, then register the dlls with gacutil.exe.

This fixed the issue with my systems.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

The octothorpe/number-sign/hashmark has a special significance in an URL, it normally identifies the name of a section of a document. The precise term is that the text following the hash is the anchor portion of an URL. If you use Wikipedia, you will see that most pages have a table of contents and you can jump to sections within the document with an anchor, such as:

https://en.wikipedia.org/wiki/Alan_Turing#Early_computers_and_the_Turing_test

https://en.wikipedia.org/wiki/Alan_Turing identifies the page and Early_computers_and_the_Turing_test is the anchor. The reason that Facebook and other Javascript-driven applications (like my own Wood & Stones) use anchors is that they want to make pages bookmarkable (as suggested by a comment on that answer) or support the back button without reloading the entire page from the server.

In order to support bookmarking and the back button, you need to change the URL. However, if you change the page portion (with something like window.location = 'http://raganwald.com';) to a different URL or without specifying an anchor, the browser will load the entire page from the URL. Try this in Firebug or Safari's Javascript console. Load http://minimal-github.gilesb.com/raganwald. Now in the Javascript console, type:

window.location = 'http://minimal-github.gilesb.com/raganwald';

You will see the page refresh from the server. Now type:

window.location = 'http://minimal-github.gilesb.com/raganwald#try_this';

Aha! No page refresh! Type:

window.location = 'http://minimal-github.gilesb.com/raganwald#and_this';

Still no refresh. Use the back button to see that these URLs are in the browser history. The browser notices that we are on the same page but just changing the anchor, so it doesn't reload. Thanks to this behaviour, we can have a single Javascript application that appears to the browser to be on one 'page' but to have many bookmarkable sections that respect the back button. The application must change the anchor when a user enters different 'states', and likewise if a user uses the back button or a bookmark or a link to load the application with an anchor included, the application must restore the appropriate state.

So there you have it: Anchors provide Javascript programmers with a mechanism for making bookmarkable, indexable, and back-button-friendly applications. This technique has a name: It is a Single Page Interface.

p.s. There is a fourth benefit to this technique: Loading page content through AJAX and then injecting it into the current DOM can be much faster than loading a new page. In addition to the speed increase, further tricks like loading certain portions in the background can be performed under the programmer's control.

p.p.s. Given all of that, the 'bang' or exclamation mark is a further hint to Google's web crawler that the exact same page can be loaded from the server at a slightly different URL. See Ajax Crawling. Another technique is to make each link point to a server-accessible URL and then use unobtrusive Javascript to change it into an SPI with an anchor.

Here's the key link again: The Single Page Interface Manifesto

How to create a md5 hash of a string in C?

To be honest, the comments accompanying the prototypes seem clear enough. Something like this should do the trick:

void compute_md5(char *str, unsigned char digest[16]) {
    MD5Context ctx;
    MD5Init(&ctx);
    MD5Update(&ctx, str, strlen(str));
    MD5Final(digest, &ctx);
}

where str is a C string you want the hash of, and digest is the resulting MD5 digest.

What is App.config in C#.NET? How to use it?

At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.

Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.

Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.

Application-level config files inherit settings from global configuration files, e.g. the machine.config.

Reading from the App.Config

Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>   
        <add name="MyKey" 
             connectionString="Data Source=localhost;Initial Catalog=ABC;"
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.

string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;

Writing to the App.Config

Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.

See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.

Note that ideally you would perform such configuration changes from a simple installer.

Location of the App.Config at Runtime

Q: Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?

A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a "text.exe.config" in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.

1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.

.NET Core

New configuration options were introduced with .NET Core. The way that *.config files works does not appear to have changed, but developers are free to choose new, more flexible configuration paradigms.

Python CSV error: line contains NULL byte

I bumped into this problem as well. Using the Python csv module, I was trying to read an XLS file created in MS Excel and running into the NULL byte error you were getting. I looked around and found the xlrd Python module for reading and formatting data from MS Excel spreadsheet files. With the xlrd module, I am not only able to read the file properly, but I can also access many different parts of the file in a way I couldn't before.

I thought it might help you.

ld.exe: cannot open output file ... : Permission denied

i experienced a similar issue. Bitdefender automatically quarantined each exe-file i created by MinGW g++. Instead of the full exe-file i found a file with a weird extension 'qzquar' testAutoPtr1.exe.48352.gzquar

When i opened quarantined items in Bitdefender i found my exe-file quarantined there.

How to get last key in an array?

A solution would be to use a combination of end and key (quoting) :

  • end() advances array 's internal pointer to the last element, and returns its value.
  • key() returns the index element of the current array position.

So, a portion of code such as this one should do the trick :

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

end($array);         // move the internal pointer to the end of the array
$key = key($array);  // fetches the key of the element pointed to by the internal pointer

var_dump($key);

Will output :

string 'last' (length=4)

i.e. the key of the last element of my array.

After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.

How to remove Firefox's dotted outline on BUTTONS as well as links?

button::-moz-focus-inner { border: 0; }

Where button can be whatever CSS selector for which you want to disable the behavior.

store return value of a Python script in a bash script

read it in the docs. If you return anything but an int or None it will be printed to stderr.

To get just stderr while discarding stdout do:

output=$(python foo.py 2>&1 >/dev/null)

Celery Received unregistered task of type (run example)

I've found that one of our programmers added the following line to one of the imports:

os.chdir(<path_to_a_local_folder>)

This caused the Celery worker to change its working directory from the projects' default working directory (where it could find the tasks) to a different directory (where it couldn't find the tasks).

After removing this line of code, all tasks were found and registered.

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

Are loops really faster in reverse?

It used to be said that --i was faster (in C++) because there is only one result, the decremented value. i-- needs to store the decremented value back to i and also retain the original value as the result (j = i--;). In most compilers this used up two registers rather than one which could cause another variable to have to be written to memory rather than retained as a register variable.

I agree with those others that have said it makes no difference these days.

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

Select all columns except one in MySQL?

In mysql definitions (manual) there is no such thing. But if you have a really big number of columns col1, ..., col100, the following can be useful:

DROP TABLE IF EXISTS temp_tb;
CREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb;
ALTER TABLE temp_tb DROP col_x;
   #// ALTER TABLE temp_tb DROP col_a, ... , DROP col_z; #// for a few columns to drop
SELECT * FROM temp_tb;

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

How do I create a singleton service in Angular 2?

You can use useValue in providers

import { MyService } from './my.service';

@NgModule({
...
  providers: [ { provide: MyService, useValue: new MyService() } ],
...
})

Capturing URL parameters in request.GET

Someone would wonder how to set path in file urls.py, such as

domain/search/?q=CA

so that we could invoke query.

The fact is that it is not necessary to set such a route in file urls.py. You need to set just the route in urls.py:

urlpatterns = [
    path('domain/search/', views.CityListView.as_view()),
]

And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though

request.GET.get('q', None).

Here is an example (file views.py)

class CityListView(generics.ListAPIView):
    serializer_class = CityNameSerializer

    def get_queryset(self):
        if self.request.method == 'GET':
            queryset = City.objects.all()
            state_name = self.request.GET.get('q', None)
            if state_name is not None:
                queryset = queryset.filter(state__name=state_name)
            return queryset

In addition, when you write query string in the URL:

http://servername:port/domain/search/?q=CA

Do not wrap query string in quotes. For example,

http://servername:port/domain/search/?q="CA"

Grant Select on a view not base table when base table is in a different database

I tried this in one of my databases.

To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.

Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

Why am I getting tree conflicts in Subversion?

I came across this problem today as well, though my particular issue probably isn't related to yours. After inspecting the list of files, I realized what I had done -- I had temporarily been using a file in one assembly from another assembly. I have made lots of changes to it and didn't want to orphan the SVN history, so in my branch I had moved the file over from the other assembly's folder. This isn't tracked by SVN, so it just looks like the file is deleted and then re-added. This ends up causing a tree conflict.

I resolved the problem by moving the file back, committing, and then merging my branch. Then I moved the file back afterward. :) That seemed to do the trick.

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

The registry entries for MSBuild key worked fine to me. It's important to remember that it must be done for 64-bit or 32-bit branches depending on which version of MSBuild you run. I wouldn't recommend to use environment variables as it may cause problems in different versions of MSBuild.

This registry file fixes that for both cases:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\10.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\11.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\12.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\10.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\11.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\12.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"

How to display special characters in PHP

This works for me. Try this one before the start of HTML. I hope it will also work for you.

_x000D_
_x000D_
<?php header('Content-Type: text/html; charset=iso-8859-15'); ?>_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html lang="en-US">_x000D_
<head>
_x000D_
_x000D_
_x000D_

How do I access the HTTP request header fields via JavaScript?

This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

Limiting the number of characters per line with CSS

The latest way to go is to use the unit 'ch' which stands for character.

You can simply write:

p { max-width: 75ch; }

The only trick is that whitespaces won't be counted as characters..

Check also this post: https://stackoverflow.com/a/26975271/4069992

Java: Reading integers from a file into an array

File file = new File("E:/Responsibility.txt");  
    Scanner scanner = new Scanner(file);
    List<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    System.out.println(integers);

Creating a daemon in Linux

You cannot create a process in linux that cannot be killed. The root user (uid=0) can send a signal to a process, and there are two signals which cannot be caught, SIGKILL=9, SIGSTOP=19. And other signals (when uncaught) can also result in process termination.

You may want a more general daemonize function, where you can specify a name for your program/daemon, and a path to run your program (perhaps "/" or "/tmp"). You may also want to provide file(s) for stderr and stdout (and possibly a control path using stdin).

Here are the necessary includes:

#include <stdio.h>    //printf(3)
#include <stdlib.h>   //exit(3)
#include <unistd.h>   //fork(3), chdir(3), sysconf(3)
#include <signal.h>   //signal(3)
#include <sys/stat.h> //umask(3)
#include <syslog.h>   //syslog(3), openlog(3), closelog(3)

And here is a more general function,

int
daemonize(char* name, char* path, char* outfile, char* errfile, char* infile )
{
    if(!path) { path="/"; }
    if(!name) { name="medaemon"; }
    if(!infile) { infile="/dev/null"; }
    if(!outfile) { outfile="/dev/null"; }
    if(!errfile) { errfile="/dev/null"; }
    //printf("%s %s %s %s\n",name,path,outfile,infile);
    pid_t child;
    //fork, detach from process group leader
    if( (child=fork())<0 ) { //failed fork
        fprintf(stderr,"error: failed fork\n");
        exit(EXIT_FAILURE);
    }
    if (child>0) { //parent
        exit(EXIT_SUCCESS);
    }
    if( setsid()<0 ) { //failed to become session leader
        fprintf(stderr,"error: failed setsid\n");
        exit(EXIT_FAILURE);
    }

    //catch/ignore signals
    signal(SIGCHLD,SIG_IGN);
    signal(SIGHUP,SIG_IGN);

    //fork second time
    if ( (child=fork())<0) { //failed fork
        fprintf(stderr,"error: failed fork\n");
        exit(EXIT_FAILURE);
    }
    if( child>0 ) { //parent
        exit(EXIT_SUCCESS);
    }

    //new file permissions
    umask(0);
    //change to path directory
    chdir(path);

    //Close all open file descriptors
    int fd;
    for( fd=sysconf(_SC_OPEN_MAX); fd>0; --fd )
    {
        close(fd);
    }

    //reopen stdin, stdout, stderr
    stdin=fopen(infile,"r");   //fd=0
    stdout=fopen(outfile,"w+");  //fd=1
    stderr=fopen(errfile,"w+");  //fd=2

    //open syslog
    openlog(name,LOG_PID,LOG_DAEMON);
    return(0);
}

Here is a sample program, which becomes a daemon, hangs around, and then leaves.

int
main()
{
    int res;
    int ttl=120;
    int delay=5;
    if( (res=daemonize("mydaemon","/tmp",NULL,NULL,NULL)) != 0 ) {
        fprintf(stderr,"error: daemonize failed\n");
        exit(EXIT_FAILURE);
    }
    while( ttl>0 ) {
        //daemon code here
        syslog(LOG_NOTICE,"daemon ttl %d",ttl);
        sleep(delay);
        ttl-=delay;
    }
    syslog(LOG_NOTICE,"daemon ttl expired");
    closelog();
    return(EXIT_SUCCESS);
}

Note that SIG_IGN indicates to catch and ignore the signal. You could build a signal handler that can log signal receipt, and set flags (such as a flag to indicate graceful shutdown).

adb remount permission denied, but able to access super user in shell -- android

In case anyone has the same problem in the future:

$ adb shell
$ su
# mount -o rw,remount /system

Both adb remount and adb root don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.

Remove category & tag base from WordPress url - without a plugin

Adding "." or "/" won't work if you want a consolidated blog view. Also, I have know idea what that solutions would do for the RSS or XML feeds. I feel better sticking with the WP convention. However, I did come up with a more elegant approach.

First, I name the base category url "blog"

Then I created a category called "all". Finally, I but all my subcategories under "all". So I get a url structure like this.

/blog - 404 - recommend 301 redirect to /blog/all/    
/blog/all/ -  all posts combined.
/blog/all/category1/ - posts filtered by category1
/blog/all/category2/ - posts filterer by category2

I put a custom label on the menu item called "Blog", but it goes to blog/all. It would be a good idea to 301 redirect /blog to /blog/all in the .htaccess file to avoid the 404 on /blog.

Converting List<Integer> to List<String>

What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformer and the collect method from Apache Commons, e.g.:

public class IntegerToStringTransformer implements Transformer<Integer, String> {
   public String transform(final Integer i) {
      return (i == null ? null : i.toString());
   }
}

..and then..

CollectionUtils.collect(
   collectionOfIntegers, 
   new IntegerToStringTransformer(), 
   newCollectionOfStrings);

"java.lang.OutOfMemoryError : unable to create new native Thread"

I had this same issue and it turned out to be an improper usage of an java API. I was initializing a builder in a batch processing method that was that not supposed to be initiallized more than once.

Basically I was doing something like:

for (batch in batches) {
    process_batch(batch)
}

def process_batch(batch) {
    var client = TransportClient.builder().build()
    client.processList(batch)
}

when I should have done this:

for (batch in batches) {
    var client = TransportClient.builder().build()
    process_batch(batch, client)
}

def process_batch(batch, client) {
    client.processList(batch)
}

Two color borders

Yep: Use the outline property; it acts as a second border outside of your border. Beware, tho', it can interact in a wonky fashion with margins, paddings and drop-shadows. In some browsers you might have to use a browser-specific prefix as well; in order to make sure it picks up on it: -webkit-outline and the like (although WebKit in particular doesn't require this).

This can also be useful in the case where you want to jettison the outline for certain browsers (such as is the case if you want to combine the outline with a drop shadow; in WebKit the outline is inside of the shadow; in FireFox it is outside, so -moz-outline: 0 is useful to ensure that you don't get a gnarly line around your beautiful CSS drop shadow).

.someclass {
  border: 1px solid blue;
  outline: 1px solid darkblue;
}

Edit: Some people have remarked that outline doesn't jive well with IE < 8. While this is true; supporting IE < 8 really isn't something you should be doing.

Search for executable files using find command

So as to have another possibility1 to find the files that are executable by the current user:

find . -type f -exec test -x {} \; -print

(the test command here is the one found in PATH, very likely /usr/bin/test, not the builtin).


1 Only use this if the -executable flag of find is not available! this is subtly different from the -perm +111 solution.

How to start new activity on button click

Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.

  1. Using the onClick attribute of the Button. (Beginner)
  2. Assigning an OnClickListener() via an anonymous class. (Intermediate)
  3. Activity wide interface method using the switch statement. (Pro)

Here's the link to my example if you want to follow along:

1. Using the onClick attribute of the Button. (Beginner)

Buttons have an onClick attribute that is found within the .xml file:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnActivity"
    android:text="to an activity" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnotherActivity"
    android:text="to another activity" />

In Java class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

public void goToAnActivity(View view) {
    Intent intent = new Intent(this, AnActivity.class);
    startActivity(intent);
}

public void goToAnotherActivity(View view) {
    Intent intent = new Intent(this, AnotherActivity.class);
    startActivity(intent);
}

Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent.

Disadvantage: Difficult readability when reviewing.

2. Assigning an OnClickListener() via an anonymous class. (Intermediate)

This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.

In Java class:

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnActivity.class);
                view.getContext().startActivity(intent);}
            });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnotherActivity.class);
                view.getContext().startActivity(intent);}
            });

Advantage: Easy to make on the fly.

Disadvantage: There will be a lot of anonymous classes which will make readability difficult when reviewing.

3. Activity wide interface method using the switch statement. (Pro)

This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.

In Java class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button1:
            Intent intent1 = new Intent(this, AnActivity.class);
            startActivity(intent1);
            break;
        case R.id.button2:
            Intent intent2 = new Intent(this, AnotherActivity.class);
            startActivity(intent2);
            break;
        default:
            break;
    }

Advantage: Easy button management because all button intents are registered in a single onClick() method


For the second part of the question, passing data, please see How do I pass data between Activities in Android application?

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I did try giving access to the folders but that did not help. My solution was to make the below highlighted options in red selected for the logged in user

This is what you see when you right click and select the username you have logged in for windows authentication mode.

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

Return positions of a regex match() in Javascript?

exec returns an object with a index property:

_x000D_
_x000D_
var match = /bar/.exec("foobar");_x000D_
if (match) {_x000D_
    console.log("match found at " + match.index);_x000D_
}
_x000D_
_x000D_
_x000D_

And for multiple matches:

_x000D_
_x000D_
var re = /bar/g,_x000D_
    str = "foobarfoobar";_x000D_
while ((match = re.exec(str)) != null) {_x000D_
    console.log("match found at " + match.index);_x000D_
}
_x000D_
_x000D_
_x000D_

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Shared-memory objects in multiprocessing

Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.

I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle'd bytestrings generated by pickle.dumps(...).

The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain object.

$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma

from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)

brain['a'] = [1]*10000

brain['a']
# >>> [1,1,1,1,...]

Add back button to action bar

this one worked for me:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_activity);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // ... other stuff
}

@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}

The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.

Default keystore file does not exist?

For Mac/Linux debug keystore, the Android docs have:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return in terminal after the backslash so that the second that starts with -alias is on a new line. Simply pasting as-is will not work.

Your terminal (if successful) will look something like this:

$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password: 

The default debug password is: android

Side note: In Android Studio you can manage signing in:

File > Project Structure > Modules - (Your App) > Signing

how to extract only the year from the date in sql server 2008?

year(table_column)

Example:

select * from mytable where year(transaction_day)='2013' 

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Below are the reasons of Error: redirect_uri_mismatch issue occurs :

  1. Redirect URL field blank at your google project.
  2. Redirect URL does not match with your site
  3. Important! It will work only with working domain like example.com, book.com etc (Not work with local host or AWS LB URL)

Recommended to use domain URL

Wait Until File Is Completely Written

There is only workaround for the issue you are facing.

Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.

1st Method, copied directly from this answer:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

2nd Method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

Returning a boolean from a Bash function

Be careful when checking directory only with option -d !
if variable $1 is empty the check will still be successfull. To be sure, check also that the variable is not empty.

#! /bin/bash

is_directory(){

    if [[ -d $1 ]] && [[ -n $1 ]] ; then
        return 0
    else
        return 1
    fi

}


#Test
if is_directory $1 ; then
    echo "Directory exist"
else
    echo "Directory does not exist!" 
fi

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

What does %~d0 mean in a Windows batch file?

%~d0 gives you the drive letter of argument 0 (the script name), %~p0 the path.

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True

or

Not Isnull(myvar)

TabLayout tab selection

add for your viewpager:

 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                array.clear();
                switch (position) {
                    case 1:
                        //like a example
                        setViewPagerByIndex(0);
                        break;
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

//on handler to prevent crash outofmemory

private void setViewPagerByIndex(final int index){
    Application.getInstance().getHandler().post(new Runnable() {
        @Override
        public void run() {
            viewPager.setCurrentItem(index);
        }
    });
}

Getting the class name of an instance?

To get instance classname:

type(instance).__name__

or

instance.__class__.__name__

both are the same

How to use pip with Python 3.x alongside Python 2.x

If you don't want to have to specify the version every time you use pip:

Install pip:

$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python3

and export the path:

$ export PATH=/Library/Frameworks/Python.framework/Versions/<version number>/bin:$PATH

Finding absolute value of a number without using Math.abs()

-num will equal to num for Integer.MIN_VALUE as

 Integer.MIN_VALUE =  Integer.MIN_VALUE * -1

Android: remove left margin from actionbar's custom layout

I found an other resolution (reference appcompat-v7 ) that change the toolbarStyle ,following code:

<item name="toolbarStyle">@style/Widget.Toolbar</item>


<style name="Widget.Toolbar" parent="@style/Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
</style>

How to replace a hash key with another key

For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:

hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }

hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}

How can I set the value of a DropDownList using jQuery?

If you just need to set the value of a dropdown then the best way is

$("#ID").val("2");

If You have to trigger any script after updating the dropdown value like If you set any onChange event on the dropdown and you want to run this after update the dropdown than You need to use like this

$("#ID").val("2").change();

Android: Tabs at the BOTTOM

There is a way to remove the line.

1) Follow this tutorial: android-tabs-with-fragments

2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).

You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.

Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.

enter image description here

Running CMD command in PowerShell

One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.

PS C:\> "notepad.exe" | cmd

Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.


Edits

CMD's Startup Message is Shown

As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

Check for false

Like this:

if(borrar())
{
   // Do something
}

If borrar() returns true then do something (if it is not false).

Windows 7 environment variable not working in path

In my Windows 7.

// not working for me
D:\php\php-7.2.6-nts\php.exe

// works fine
D:\php\php-7.2.6-nts

Generating random numbers with normal distribution in Excel

About the recalculation:

You can keep your set of random values from changing every time you make an adjustment, by adjusting the automatic recalculation, to: manual recalculate. (Re)calculations are then only done when you press F9. Or shift F9.

See this link (though for older excel version than the current 2013) for some info about it: https://support.office.com/en-us/article/Change-formula-recalculation-iteration-or-precision-73fc7dac-91cf-4d36-86e8-67124f6bcce4.

Right Align button in horizontal LinearLayout

You should use the Relativelayout instead of Linearlayout as main layout. If you use Relativelayout as main then easily handle the button on right side because relative layout provide us alignParent right, left,top and bottom.

Specifying a custom DateTime format when serializing with Json.Net

Some times decorating the json convert attribute will not work ,it will through exception saying that "2010-10-01" is valid date. To avoid this types i removed json convert attribute on the property and mentioned in the deserilizedObject method like below.

var addresss = JsonConvert.DeserializeObject<AddressHistory>(address, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });

Check if Cookie Exists

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage:

Request.Cookies.Exists("MyCookie")

What's the difference between a single precision and double precision floating point operation?

I read a lot of answers but none seems to correctly explain where the word double comes from. I remember a very good explanation given by a University professor I had some years ago.

Recalling the style of VonC's answer, a single precision floating point representation uses a word of 32 bit.

  • 1 bit for the sign, S
  • 8 bits for the exponent, 'E'
  • 24 bits for the fraction, also called mantissa, or coefficient (even though just 23 are represented). Let's call it 'M' (for mantissa, I prefer this name as "fraction" can be misunderstood).

Representation:

          S  EEEEEEEE   MMMMMMMMMMMMMMMMMMMMMMM
bits:    31 30      23 22                     0

(Just to point out, the sign bit is the last, not the first.)

A double precision floating point representation uses a word of 64 bit.

  • 1 bit for the sign, S
  • 11 bits for the exponent, 'E'
  • 53 bits for the fraction / mantissa / coefficient (even though only 52 are represented), 'M'

Representation:

           S  EEEEEEEEEEE   MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
bits:     63 62         52 51                                                  0

As you may notice, I wrote that the mantissa has, in both types, one bit more of information compared to its representation. In fact, the mantissa is a number represented without all its non-significative 0. For example,

  • 0.000124 becomes 0.124 × 10-3
  • 237.141 becomes 0.237141 × 103

This means that the mantissa will always be in the form

0.a1a2...at × ßp

where ß is the base of representation. But since the fraction is a binary number, a1 will always be equal to 1, thus the fraction can be rewritten as 1.a2a3...at+1 × 2p and the initial 1 can be implicitly assumed, making room for an extra bit (at+1).

Now, it's obviously true that the double of 32 is 64, but that's not where the word comes from.

The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.

With that said, it's easy to estimate the number of decimal digits which can be safely used:

  • single precision: log10(224), which is about 7~8 decimal digits
  • double precision: log10(253), which is about 15~16 decimal digits

android EditText - finished typing event

I had the same problem when trying to implement 'now typing' on chat app. try to extend EditText as follows:

public class TypingEditText extends EditText implements TextWatcher {

private static final int TypingInterval = 2000;


public interface OnTypingChanged {
    public void onTyping(EditText view, boolean isTyping);
}
private OnTypingChanged t;
private Handler handler;
{
    handler = new Handler();
}
public TypingEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context) {
    super(context);
    this.addTextChangedListener(this);
}

public void setOnTypingChanged(OnTypingChanged t) {
    this.t = t;
}

@Override
public void afterTextChanged(Editable s) {
    if(t != null){
        t.onTyping(this, true);
        handler.removeCallbacks(notifier);
        handler.postDelayed(notifier, TypingInterval);
    }

}

private Runnable notifier = new Runnable() {

    @Override
    public void run() {
        if(t != null)
            t.onTyping(TypingEditText.this, false);
    }
};

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }


@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { }

}

Installing SciPy and NumPy using pip

What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Is it possible to capture the stdout from the sh DSL command in the pipeline

A short version would be:

echo sh(script: 'ls -al', returnStdout: true).result

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

I have some vague recollections of Oracle databases needing a bit of fiddling when you reboot for the first time after installing the database. However, you haven't given us enough information to work on. To start with:

  • What code are you using to connect to the database?
  • It's not clear whether the database instance has been started. Can you connect to the database using sqlplus / as sysdba from within the VM?
  • What has been written to the listener.log file (in %ORACLE_HOME%\network\log) since the last reboot?

EDIT: I've now been able to come up with a scenario which generates the same error message you got. It looks to me like the database you're attempting to connect to has not been started up. The example I present below uses Oracle XE on Linux, but I don't think this makes a significant difference.

First, let us confirm that the database is shut down:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:43 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

It's the text Connected to an idle instance that tells us that the database is shut down.

Using sqlplus / as sysdba connects us to the database as SYS without needing a password, but it only works on the same machine as the database itself. In your case, you'd need to run this inside the virtual machine. SYS has permission to start up and shut down the database, and to connect to it when it is shut down, but normal users don't have these permissions.

Now let us disconnect and try reconnecting as a normal user, one that does not have permission to startup/shutdown the database nor connect to it when it is down:

SQL> exit
Disconnected

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:47 2010                                                                                                               

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

ERROR:
ORA-12505: TNS:listener does not currently know of SID given in connect
descriptor                                                             


SP2-0751: Unable to connect to Oracle.  Exiting SQL*Plus

That's the error message you've been getting.

Now, let's start the database up:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:00 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup
ORACLE instance started.

Total System Global Area  805306368 bytes
Fixed Size                  1261444 bytes
Variable Size             209715324 bytes
Database Buffers          591396864 bytes
Redo Buffers                2932736 bytes
Database mounted.
Database opened.
SQL> exit
Disconnected from Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

Now that the database is up, let's attempt to log in as a normal user:

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:11 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.


Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> 

We're in.

I hadn't seen an ORA-12505 error before because I don't normally connect to an Oracle database by entering the entire connection string on the command line. This is likely to be similar to how you are attempting to connect to the database. Usually, I either connect to a local database, or connect to a remote database by using a TNS name (these are listed in the tnsnames.ora file, in %ORACLE_HOME%\network\admin). In both of these cases you get a different error message if you attempt to connect to a database that has been shut down.

If the above doesn't help you (in particular, if the database has already been started, or you get errors starting up the database), please let us know.

EDIT 2: it seems the problems you were having were indeed because the database hadn't been started. It also appears that your database isn't configured to start up when the service starts. It is possible to get the database to start up when the service is started, and to shut down when the service is stopped. To do this, use the Oracle Administration Assistant for Windows, see here.

How to import existing *.sql files in PostgreSQL 8.4?

From the command line:

psql -f 1.sql
psql -f 2.sql

From the psql prompt:

\i 1.sql
\i 2.sql

Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:

for f in *.sql ; do psql -f $f ; done

Here's the documentation of the psql application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);

XSD - how to allow elements in any order any number of times?

In the schema you have in your question, child1 or child2 can appear in any order, any number of times. So this sounds like what you are looking for.

Edit: if you wanted only one of them to appear an unlimited number of times, the unbounded would have to go on the elements instead:

Edit: Fixed type in XML.

Edit: Capitalised O in maxOccurs

<xs:element name="foo">
   <xs:complexType>
     <xs:choice maxOccurs="unbounded">
       <xs:element name="child1" type="xs:int" maxOccurs="unbounded"/>
       <xs:element name="child2" type="xs:string" maxOccurs="unbounded"/>
     </xs:choice>
   </xs:complexType>
</xs:element>

Numpy converting array from float to strings

You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.

The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'.

A accurate string representation of a floating point number produces a variable length string.

Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.

If you use x.astype('str'), it will always convert things to an array of strings of length 1.

For example, using x = np.array(1.344566), x.astype('str') yields '1'!

You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array.

For example, use x.astype('|S10') to convert the array to strings of length 10.

Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Assigning a variable NaN in python without numpy

nan = float('nan')

And now you have the constant, nan.

You can similarly create NaN values for decimal.Decimal.:

dnan = Decimal('nan')

When to use IList and when to use List

AList object allows you to create a list, add things to it, remove it, update it, index into it and etc. List is used whenever you just want a generic List where you specify object type in it and that's it.

IList on the other hand is an Interface. Basically, if you want to create your own type of List, say a list class called BookList, then you can use the Interface to give you basic methods and structure to your new class. IList is for when you want to create your own, special sub-class that implements List.

Another difference is: IList is an Interface and cannot be instantiated. List is a class and can be instantiated. It means:

IList<string> MyList = new IList<string>();

List<string> MyList = new List<string>

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Add/remove HTML inside div using JavaScript

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

How to refresh or show immediately in datagridview after inserting?

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

Using python's eval() vs. ast.literal_eval()?

ast.literal_eval() only considers a small subset of Python's syntax to be valid:

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Passing __import__('os').system('rm -rf /a-path-you-really-care-about') into ast.literal_eval() will raise an error, but eval() will happily delete your files.

Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval(). It safely does what you want and nothing more.

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

Algorithm to compare two images

It is indeed much less simple than it seems :-) Nick's suggestion is a good one.

To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...


One of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).

http://en.wikipedia.org/wiki/RGB_color_space
http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace


Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.

http://homepages.inf.ed.ac.uk/amos/hough.html
http://rkb.home.cern.ch/rkb/AN16pp/node122.html
http://en.wikipedia.org/wiki/Hough_transform

How can I check if a value is a json object?

If you have jQuery, use isPlainObject.

if ($.isPlainObject(my_var)) {}

How to Insert Double or Single Quotes

To Create New Quoted Values from Unquoted Values

  • Column A contains the names.
  • Put the following formula into Column B = """" & A1 & """"
  • Copy Column B and Paste Special -> Values

Using a Custom Function

Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
    Enquote = quoteCharacter & cell.value & quoteCharacter
End Function

=OfficePersonal.xls!Enquote(A1)

=OfficePersonal.xls!Enquote(A1, "'")

To get permanent quoted strings, you will have to copy formula values and paste-special-values.

How can I update NodeJS and NPM to the next versions?

I think the best way to manage node.js is to use NVM. NVM stands for Node Version Manager.

It's a must-have tool for node.js developers!

You can install NVM using the following command, open terminal and run any one of the following:-

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

or

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

After installing this it's recommended to close the current terminal and open a new one since NVM will be adding some environment variables so terminal needs to be restarted.

I'll list down some of the basic commands for using NVM.

  • This will fetch all the node versions from the internet. All node versions from beginning till date will be shown, It will also mention LTS versions alongside.
nvm ls-remote 
  • This will install the node version which you want (version list is obtained using the above command)
nvm install v10.15.1
  • This command will give us the list of node versions that are installed locally
nvm ls
  • This command is used to remove the node version that you want from your computer
nvm uninstall v10.15.1
  • The following command will help you upgrade to the latest working npm on the current node version
nvm install-latest-npm
  • NVM can be used to manage multiple node versions simultaneously
  • It can also help you install all the global npm packages from one version to another instead of manually installing each one of them!
  • There are many other uses of nvm the details of which and the commands can be found here Node Version Manager

Passing multiple values for a single parameter in Reporting Services

This works great for me:

WHERE CHARINDEX(CONVERT(nvarchar, CustNum), @CustNum) > 0

Return JSON response from Flask view

I like this way:

    @app.route("/summary")
    def summary():
        responseBody = { "message": "bla bla bla", "summary": make_summary() }
        return make_response(jsonify(responseBody), 200)

phpMyAdmin - The MySQL Extension is Missing

Installing bzip2 and zip PHP extensions solved my issue in Ubuntu:

sudo apt-get install php7.0-bz2
sudo apt-get install php7.0-zip

Use php(you version)-(extension) to install and enable any missing modules that is required in the phpmyadmin readme.

How to get a MemoryStream from a Stream in .NET?

In .NET 4, you can use Stream.CopyTo to copy a stream, instead of the home-brew methods listed in the other answers.

MemoryStream _ms;

public MyClass(Stream sourceStream)

    _ms = new MemoryStream();
    sourceStream.CopyTo(_ms);
}

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

How can I change image tintColor in iOS and WatchKit

Swift 4

Change tint of UIImage SVG / PDF, that work for image with unique color :

enter image description here enter image description here

import Foundation
    
// MARK: - UIImage extensions

public extension UIImage {

    //
    /// Tint Image
    ///
    /// - Parameter fillColor: UIColor
    /// - Returns: Image with tint color
    func tint(with fillColor: UIColor) -> UIImage? {
        let image = withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        fillColor.set()
        image.draw(in: CGRect(origin: .zero, size: size))

        guard let imageColored = UIGraphicsGetImageFromCurrentImageContext() else {
            return nil
        }
        
        UIGraphicsEndImageContext()
        return imageColored
    }
}

Change tint of UIImageView, that work for image with unique color :

enter image description here enter image description here

let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 50, height: 50))
imageView.image = UIImage(named: "hello.png")!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .yellow

Change tint of UIImage for picture, use that :

enter image description here enter image description here

import Foundation

// MARK: - Extensions UIImage

public extension UIImage {

    /// Tint, Colorize image with given tint color
    /// This is similar to Photoshop's "Color" layer blend mode
    /// This is perfect for non-greyscale source images, and images that 
    /// have both highlights and shadows that should be preserved<br><br>
    /// white will stay white and black will stay black as the lightness of 
    /// the image is preserved
    ///
    /// - Parameter TintColor: Tint color
    /// - Returns:  Tinted image
    public func tintImage(with fillColor: UIColor) -> UIImage {
        
        return modifiedImage { context, rect in
            // draw black background - workaround to preserve color of partially transparent pixels
            context.setBlendMode(.normal)
            UIColor.black.setFill()
            context.fill(rect)
            
            // draw original image
            context.setBlendMode(.normal)
            context.draw(cgImage!, in: rect)
            
            // tint image (loosing alpha) - the luminosity of the original image is preserved
            context.setBlendMode(.color)
            fillColor.setFill()
            context.fill(rect)
            
            // mask by alpha values of original image
            context.setBlendMode(.destinationIn)
            context.draw(context.makeImage()!, in: rect)
        }
    }
    
    /// Modified Image Context, apply modification on image
    ///
    /// - Parameter draw: (CGContext, CGRect) -> ())
    /// - Returns:        UIImage
    fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -> ()) -> UIImage {
        
        // using scale correctly preserves retina images
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context: CGContext! = UIGraphicsGetCurrentContext()
        assert(context != nil)
        
        // correctly rotate image
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        
        let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
        
        draw(context, rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

I also get this issue when i change package name of my application.

In your android studio project find "google-services.json" file. Open it. and check whether package name of your application is same as written in this file.

The package name of your application and package name written in "google-services.json" file must be same.

What is the difference between a field and a property?

Fields are the variables in classes. Fields are the data which you can encapsulate through the use of access modifiers.

Properties are similar to Fields in that they define states and the data associated with an object.

Unlike a field a property has a special syntax that controls how a person reads the data and writes the data, these are known as the get and set operators. The set logic can often be used to do validation.

Nginx - Customizing 404 page

The "error_page" parameter makes a redirect, converting the request method to "GET", it is not a custom response page.

The easiest solution is

     server{
         root /var/www/html;
         location ~ \.php {
            if (!-f $document_root/$fastcgi_script_name){
                return 404;
            }
            fastcgi_pass   127.0.0.1:9000;
            include fastcgi_params.default;
            fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
        }

By the way, if you want Nginx to process 404 status returned by PHP scripts, you need to add

[fastcgi_intercept_errors][1] on;

E.g.

     location ~ \.php {
            #...
            error_page  404   404.html;
            fastcgi_intercept_errors on;
         }

Can you install and run apps built on the .NET framework on a Mac?

You can use a .Net environment Visual studio, Take a look at the differences with the PC version.

A lighter editor would be Visual Code

Alternatives :

  1. Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)

  2. Virtual machine (VMWare Fusion perhaps)

  3. Update your codebase to .Net Core, (before choosing this option take a look at this migration process)

    • .Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux

    • As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.

[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license

How Long Does it Take to Learn Java for a Complete Newbie?

It depends on how hard you want to work, but yes it's possible. The problem you are going to have is that you have to learn to program along with learning java. These are two very different things. Programming is knowing how to read and write logic and Java is a language you write it in. If you have a math or physics background, this is going to be a lot easier, as you are already exposed to thinking in such a manner.

If you don't have books on beginning Java I would go buy one of those.

I would also pick up the book Code (I would try and get through this in a few days, if not over the weekend if possible). Actually with 10 weeks I would do this first as it will be a foundation for what you'll need to know to program Java.

With 10 weeks, you are going to have to pretty much study every night to get the hang of it by the time you go to class. My best advice is that when you take the class, take lots of notes, and don't expect to understand everything. Most of what gets thrown at you there will probably go over your head at first and you'll forget. That's ok. After the class if over, go back and review the notes etc until it starts to make sense.

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

Using Merlyn's solution caused other applications to be killed like firefox. These processes were using the same port, but not as a listener:

eg:

netstat -a -n -o | findstr :8085
  TCP    0.0.0.0:8085           0.0.0.0:0              LISTENING       6568
  TCP    127.0.0.1:49616        127.0.0.1:8085         TIME_WAIT       0
  TCP    127.0.0.1:49618        127.0.0.1:8085         TIME_WAIT       0

Therefore, can excluded these by adding "LISTENING" to the findstr as follows:

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8085.*LISTENING') DO TaskKill.exe /PID %%P

Way to run Excel macros from command line or batch file?

@ Robert: I have tried to adapt your code with a relative path, and created a batch file to run the VBS.

The VBS starts and closes but doesn't launch the macro... Any idea of where the issue could be?

Option Explicit

On Error Resume Next

ExcelMacroExample

Sub ExcelMacroExample() 

  Dim xlApp 
  Dim xlBook 

  Set xlApp = CreateObject("Excel.Application")
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  strFilePath = objFSO.GetAbsolutePathName(".") 
  Set xlBook = xlApp.Workbooks.Open(strFilePath, "Excels\CLIENTES.xlsb") , 0, True) 
  xlApp.Run "open_form"


  Set xlBook = Nothing 
  Set xlApp = Nothing 

End Sub

I removed the "Application.Quit" because my macro is calling a userform taking care of it.

Cheers

EDIT

I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:

Issues I was facing:

1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.

I first wrote a macro to launch my userform while hiding the application:

Sub open_form()
 Application.Visible = False
 frmAddClient.Show vbModeless
End Sub

I then created a vbs to launch this macro (doing it with a relative path has been tricky):

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"

And I finally did a batch file to execute the VBS...

@echo off
pushd %~dp0
cscript Add_Client.vbs

Note that I have also included the "Set back to visible" in my Userform_QueryClose:

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    ThisWorkbook.Close SaveChanges:=True
    Application.Visible = True
    Application.Quit
End Sub

Anyway, thanks for your help, and I hope this will help if someone needs it

Get list of data-* attributes using javascript / jQuery

You can just iterate over the data attributes like any other object to get keys and values, here's how to do it with $.each:

    $.each($('#myEl').data(), function(key, value) {
        console.log(key);
        console.log(value);
    });

Safe navigation operator (?.) or (!.) and null property paths

Update:

Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352


You can try to write a custom function like that.

The main advantage of the approach is a type-checking and partial intellisense.

export function nullSafe<T, 
    K0 extends keyof T, 
    K1 extends keyof T[K0],
    K2 extends keyof T[K0][K1],
    K3 extends keyof T[K0][K1][K2],
    K4 extends keyof T[K0][K1][K2][K3],
    K5 extends keyof T[K0][K1][K2][K3][K4]>
    (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
    let result: any = obj;

    const keysCount = arguments.length - 1;
    for (var i = 1; i <= keysCount; i++) {
        if (result === null || result === undefined) return result;
        result = result[arguments[i]];
    }

    return result;
}

And usage (supports up to 5 parameters and can be extended):

nullSafe(a, 'b', 'c');

Example on playground.

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

This is an old post, but if anyone comes up with this problem, i post what solved my problem:

I was trying to add the Action Bar Sherlock to my proyect when i get the error:

Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Holo.ActionBar'.

I turns out that the action bar sherlock proyect and my proyect had differents minSdkVersion and targetSdkVersion. Changing that parameters to match in both proyect solved my problem.

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/>

/usr/bin/ld: cannot find

When you make the call to gcc it should say

g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator

not -libcalc.so 

I have a similar problem with auto-generated makes.

You can create a soft link from your compile directory to the library directory. Then the library becomes "local".

cd /compile/directory

ln -s  /path/to/libcalc.so libcalc.so