Programs & Examples On #Migradoc

MigraDoc Foundation is an open source .NET library that easily creates documents based on an object model with paragraphs, tables, styles, etc. and renders them into PDF or RTF. Use this tag for questions related to MigraDoc using any platform and any programming language.

Chrome, Javascript, window.open in new tab

if you use window.open(url, '_blank') , it will be blocked(popup blocker) on Chrome,Firefox etc

try this,

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});

working js fiddle for this http://jsfiddle.net/safeeronline/70kdacL4/2/

working js fiddle for ajax window open http://jsfiddle.net/safeeronline/70kdacL4/1/

What is the __del__ method, How to call it?

__del__ is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.

In a simple case this could be right after you say del x or, if x is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.

However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.

Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.

Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__() — instead, this code belongs to finally clause of the try block or to a context manager in a with statement. However, there are valid use cases for __del__: e.g. if an object X references Y and also keeps a copy of Y reference in a global cache (cache['X -> Y'] = Y) then it would be polite for X.__del__ to also delete the cache entry.

If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__(). Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using

type(x).__del__ = my_safe_cleanup_method  

sort dict by value python

If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']

comma separated string of selected values in mysql

The default separator between values in a group is comma(,). To specify any other separator, use SEPARATOR as shown below.

SELECT GROUP_CONCAT(id SEPARATOR '|')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;

5|6|9|10|12|14|15|17|18|779

To eliminate the separator, then use SEPARATOR ''

SELECT GROUP_CONCAT(id SEPARATOR '')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;

Refer for more info GROUP_CONCAT

jQuery check if it is clicked or not

This is the one that i've tried & it works pretty well for me

$('.mybutton').on('click', function() {
       if (!$(this).data('clicked')) {
           //do your stuff here if the button is not clicked
           $(this).data('clicked', true);
       } else {
           //do your stuff here if the button is clicked
           $(this).data('clicked', false);
       }

   });

for more reference check this link JQuery toggle click

Accidentally committed .idea directory files into git

Its better to perform this over Master branch

Edit .gitignore file. Add the below line in it.

.idea

Remove .idea folder from remote repo. using below command.

git rm -r --cached .idea

For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them

Stage .gitignore file. Using below command

git add .gitignore

Commit

git commit -m 'Removed .idea folder'

Push to remote

git push origin master

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

Session state can only be used when enableSessionState is set to true either in a configuration

Session State may be broken if you have the following in Web.Config:

<httpModules>
  <clear/>
</httpModules>

If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

Leader Not Available Kafka in Console Producer

For me, it was happen due to a miss configuration
Docker port (9093)
Kafka command port "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TopicName"
I checked my configuration to match port and now everything is ok

How can I make a CSS table fit the screen width?

There is already a good solution to the problem you are having. Everyone has been forgetting the CSS property font-size: the last but not least solution. One can decrease the font size by 2 to 3 pixels. It may still be visible to the user and for somewhat you can decrease the width of the table. This worked for me. My table has 5 columns with 4 showing perfectly, but the fifth column went out of the viewport. To fix the problem, I decreased the font size and all five columns were fitted onto the screen.

table th td {
  font-size: 14px;
}

For your information, if your table has too many columns and you are not able to decrease, then make the font size small. It will get rid of the horizontal scroll. There are two advantages: your style for mobile web will remain the same (good without horizontal scroll) and when user sees small sizes, most users will zoom into the table to their comfort level.

How do you clone an Array of Objects in Javascript?

If you only need a shallow clone, the best way to do this clone is as follows:

Using the ... ES6 spread operator.

Here's the most simple Example:

var clonedObjArray = [...oldObjArray];

This way we spread the array into individual values and put it in a new array with the [] operator.

Here's a longer example that shows the different ways it works:

_x000D_
_x000D_
let objArray = [ {a:1} , {b:2} ];

let refArray = objArray; // this will just point to the objArray
let clonedArray = [...objArray]; // will clone the array

console.log( "before:" );
console.log( "obj array" , objArray );
console.log( "ref array" , refArray );
console.log( "cloned array" , clonedArray );

objArray[0] = {c:3};

console.log( "after:" );
console.log( "obj array" , objArray ); // [ {c:3} , {b:2} ]
console.log( "ref array" , refArray ); // [ {c:3} , {b:2} ]
console.log( "cloned array" , clonedArray ); // [ {a:1} , {b:2} ]
_x000D_
_x000D_
_x000D_

Use jQuery to hide a DIV when the user clicks outside of it

Return false if you click on .form_wrapper:

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

twitter bootstrap text-center when in xs mode

There is nothing built into bootstrap for this, but some simple css could fix it. Something like this should work. Not tested though

 @media (max-width: 768px) {
      .col-xs-12.text-right, .col-xs-12.text-left {
              text-align: center;
       } 
    }

How can I write these variables into one line of code in C#?

Look into composite formatting:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);

You could also write (although it's not really recommended):

Console.WriteLine(mon + "." + da + "." + yer);

And, with the release of C# 6.0, you have string interpolation expressions:

Console.WriteLine($"{mon}.{da}.{yer}");  // note the $ prefix.

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

New Intent() starts new instance with Android: launchMode="singleTop"

This should do the trick.

<activity ... android:launchMode="singleTop" />

When you create an intent to start the app use:

Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

This is that should be needed.

Using a RegEx to match IP addresses in Python

This works for python 2.7:

import re
a=raw_input("Enter a valid IP_Address:")
b=("[0-9]+"+".")+"{3}"
if re.match(b,a) and b<255:
    print "Valid"
else:
    print "invalid"

npm install doesn't create node_modules directory

See @Cesco's answer: npm init is really all you need


I was having the same issue - running npm install somePackage was not generating a node_modules dir.

I created a package.json file at the root, which contained a simple JSON obj:

{
    "name": "please-work"
}

On the next npm install the node_modules directory appeared.

Keyboard shortcuts with jQuery

There is a new version of hotKeys.js that works with 1.10+ version of jQuery. It is small, 100 line javascript file. 4kb or just 2kb minified. Here are some Simple usage examples are :

$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);

$('#myBody').hotKey({ key: 'f4' }, doSomethingElse);

$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
            doSomethingWithaParameter('Daniel');
        });

$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);

Clone the repo from github : https://github.com/realdanielbyrne/HoyKeys.git or go to the github repo page https://github.com/realdanielbyrne/HoyKeys or fork and contribute.

Where does MySQL store database files on Windows and what are the names of the files?

1) Locate the my.ini, which store in the MySQL installation folder.

For example,

C:\Program Files\MySQL\MySQL Server 5.1\my.ini

2) Open the “my.ini” with our favor text editor.

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"

#Path to the database root/"
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data

Find the “datadir”, this is the where does MySQL stored the data in Windows.

What is an NP-complete in computer science?

The definitions for NP complete problems above is correct, but I thought I might wax lyrical about their philosophical importance as nobody has addressed that issue yet.

Almost all complex problems you'll come up against will be NP Complete. There's something very fundamental about this class, and which just seems to be computationally different from easily solvable problems. They sort of have their own flavour, and it's not so hard to recognise them. This basically means that any moderately complex algorithm is impossible for you to solve exactly -- scheduling, optimising, packing, covering etc.

But not all is lost if a problem you'll encounter is NP Complete. There is a vast and very technical field where people study approximation algorithms, which will give you guarantees for being close to the solution of an NP complete problem. Some of these are incredibly strong guarantees -- for example, for 3sat, you can get a 7/8 guarantee through a really obvious algorithm. Even better, in reality, there are some very strong heuristics, which excel at giving great answers (but no guarantees!) for these problems.

Note that two very famous problems -- graph isomorphism and factoring -- are not known to be P or NP.

php delete a single file in directory

http://php.net/manual/en/function.unlink.php

Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')

if (is_file($filepath))
  {
    unlink($filepath);
  }

contenteditable change events

To avoid timers and "save" buttons, you may use blur event wich fires when the element loses focus. but to be sure that the element was actually changed (not just focused and defocused), its content should be compared against its last version. or use keydown event to set some "dirty" flag on this element.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

Use .get(), which if the key is not found, returns None.

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

Java 8: Difference between two LocalDateTime in multiple units

After more than five years I answer my question. I think that the problem with a negative duration can be solved by a simple correction:

LocalDateTime fromDateTime = LocalDateTime.of(2014, 9, 9, 7, 46, 45);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 46, 45);

Period period = Period.between(fromDateTime.toLocalDate(), toDateTime.toLocalDate());
Duration duration = Duration.between(fromDateTime.toLocalTime(), toDateTime.toLocalTime());

if (duration.isNegative()) {
    period = period.minusDays(1);
    duration = duration.plusDays(1);
}
long seconds = duration.getSeconds();
long hours = seconds / SECONDS_PER_HOUR;
long minutes = ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
long secs = (seconds % SECONDS_PER_MINUTE);
long time[] = {hours, minutes, secs};
System.out.println(period.getYears() + " years "
            + period.getMonths() + " months "
            + period.getDays() + " days "
            + time[0] + " hours "
            + time[1] + " minutes "
            + time[2] + " seconds.");

Note: The site https://www.epochconverter.com/date-difference now correctly calculates the time difference.

Thank you all for your discussion and suggestions.

OSError - Errno 13 Permission denied

supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id

Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id

then type

chown -R user-id:group-id .

Replace user-id and group-id

. at the end indicates current partition / repository

// chown -R 1001:1001 . (that was my case)

Kubernetes how to make Deployment to update image

It seems that k8s expects us to provide a different image tag for every deployment. My default strategy would be to make the CI system generate and push the docker images, tagging them with the build number: xpmatteo/foobar:456.

For local development it can be convenient to use a script or a makefile, like this:

# create a unique tag    
VERSION:=$(shell date +%Y%m%d%H%M%S)
TAG=xpmatteo/foobar:$(VERSION)

deploy:
    npm run-script build
    docker build -t $(TAG) . 
    docker push $(TAG)
    sed s%IMAGE_TAG_PLACEHOLDER%$(TAG)% foobar-deployment.yaml | kubectl apply -f - --record

The sed command replaces a placeholder in the deployment document with the actual generated image tag.

How do you delete a column by name in data.table?

Suppose your dt has columns col1, col2, col3, col4, col5, coln.

To delete a subset of them:

vx <- as.character(bquote(c(col1, col2, col3, coln)))[-1]
DT[, paste0(vx):=NULL]

jQuery - Getting form values for ajax POST

$("#registerSubmit").serialize() // returns all the data in your form
$.ajax({
     type: "POST",
     url: 'your url',
     data: $("#registerSubmit").serialize(),
     success: function() {
          //success message mybe...
     }
});

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

From the book VS 2015 succintly

Shared Projects allows sharing code, assets, and resources across multiple project types. More specifically, the following project types can reference and consume shared projects:

  • Console, Windows Forms, and Windows Presentation Foundation.
  • Windows Store 8.1 apps and Windows Phone 8.1 apps.
  • Windows Phone 8.0/8.1 Silverlight apps.
  • Portable Class Libraries.

Note:- Both shared projects and portable class libraries (PCL) allow sharing code, XAML resources, and assets, but of course there are some differences that might be summarized as follows.

  • A shared project does not produce a reusable assembly, so it can only be consumed from within the solution.
  • A shared project has support for platform-specific code, because it supports environment variables such as WINDOWS_PHONE_APP and WINDOWS_APP that you can use to detect which platform your code is running on.
  • Finally, shared projects cannot have dependencies on third-party libraries.
  • By comparison, a PCL produces a reusable .dll library and can have dependencies on third-party libraries, but it does not support platform environment variables

jQuery animated number counter from zero to value

this inside the step callback isn't the element but the object passed to animate()

$('.Count').each(function (_, self) {
    jQuery({
        Counter: 0
    }).animate({
        Counter: $(self).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            $(self).text(Math.ceil(this.Counter));
        }
    });
});

Another way to do this and keep the references to this would be

$('.Count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

FIDDLE

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

Convert double/float to string

Use snprintf() from stdlib.h. Worked for me.

double num = 123412341234.123456789; 
char output[50];

snprintf(output, 50, "%f", num);

printf("%s", output);

Xcode/Simulator: How to run older iOS version?

Open xcode and in the top menu go to xcode > Preferences > Downloads and you will be given the option to download old sdks to use with xcode. You can also download command line tools and Device Debugging Support.

enter image description here

No resource found that matches the given name '@style/Theme.AppCompat.Light'

The steps described above do work, however I've encountered this problem on IntelliJ IDEA and have found that I'm having these problems with existing projects and the only solution is to remove the 'appcompat' module (not the library) and re-import it.

How to get last 7 days data from current datetime to last 7 days in sql server

Try something like:

 SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
 FROM News 
 WHERE CreatedDate >= DATEADD(day,-7, GETDATE())

Confused by python file mode "w+"

Both seems to be working same but there is a catch.

r+ :-

  • Open the file for Reading and Writing
  • Once Opened in the beginning file pointer will point to 0
  • Now if you will want to Read then it will start reading from beginning
  • if you want to Write then start writing, But the write process will begin from pointer 0. So there would be overwrite of characters, if there is any
  • In this case File should be present, either will FileNotFoundError will be raised.

w+ :-

  • Open the file for Reading and Writing
  • If file exist, File will be opened and all data will be erased,
  • If file does not exist, then new file will be created
  • In the beginning file pointer will point to 0 (as there is not data)
  • Now if you want to write something, then write
  • File pointer will be Now pointing to end of file (after write process)
  • If you want to read the data now, seek to specific point. (for beginning seek(0))

So, Overall saying both are meant to open the file to read and write but difference is whether we want to erase the data in the beginning and then do read/write or just start as it is.

abc.txt - in beginning

1234567
abcdefg
0987654
1234

Code for r+

with open('abc.txt', 'r+') as f:      # abc.txt should exist before opening
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0
567
abcdefg
0987654
1234

abc.txt - After Run:

abcd567
abcdefg
0987654
1234Sunny

Resetting abc.txt as initial

Code for w+

with open('abc.txt', 'w+') as f:     
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0


abc.txt - After Run:

abcdSunny

Change Oracle port from port 8080

Just open Run SQL Command Line and login as sysadmin and then enter below command

Exec DBMS_XDB.SETHTTPPORT(8181);

That's it. You are done.....

How to select true/false based on column value?

At least in Postgres you can use the following statement:

SELECT EntityID, EntityName, EntityProfile IS NOT NULL AS HasProfile FROM Entity

Notice: Trying to get property of non-object error

The response is an array.

var_dump($pjs[0]->{'player_name'});

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

How to add facebook share button on my website?

Share Dialog without requiring Facebook login

You can Trigger a Share Dialog using the FB.ui function with the share method parameter to share a link. This dialog is available in the Facebook SDKs for JavaScript, iOS, and Android by performing a full redirect to a URL.

You can trigger this call:

FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/', // Link to share
}, function(response){});

You can also include open graph meta tags on the page at this URL to customise the story that is shared back to Facebook.

Note that response.error_message will appear only if someone using your app has authenticated your app with Facebook Login.

Also you can directly share link with call by having Javascript Facebook SDK.

https://www.facebook.com/dialog/share&app_id=145634995501895&display=popup&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer

https://www.facebook.com/dialog/share&app_id={APP_ID}&display=popup&href={LINK_TO_SHARE}&redirect_uri={REDIRECT_AFTER_SHARE}
  • app_id => Your app's unique identifier. (Required.)

  • redirect_uri => The URL to redirect to after a person clicks a button on the dialog. Required when using URL redirection.

  • display => Determines how the dialog is rendered.

If you are using the URL redirect dialog implementation, then this will be a full page display, shown within Facebook.com. This display type is called page. If you are using one of our iOS or Android SDKs to invoke the dialog, this is automatically specified and chooses an appropriate display type for the device. If you are using the Facebook SDK for JavaScript, this will default to a modal iframe type for people logged into your app or async when using within a game on Facebook.com, and a popup window for everyone else. You can also force the popup or page types when using the Facebook SDK for JavaScript, if necessary. Mobile web apps will always default to the touch display type. share Parameters

  • href => The link attached to this post. Required when using method share. Include open graph meta tags in the page at this URL to customize the story that is shared.

How to get year and month from a date - PHP

I will share my code:

In your given example date:

$dateValue = '2012-01-05';

It will go like this:

dateName($dateValue);



   function dateName($date) {

        $result = "";

        $convert_date = strtotime($date);
        $month = date('F',$convert_date);
        $year = date('Y',$convert_date);
        $name_day = date('l',$convert_date);
        $day = date('j',$convert_date);


        $result = $month . " " . $day . ", " . $year . " - " . $name_day;

        return $result;
    }

and will return a value: January 5, 2012 - Thursday

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Git Symlinks in Windows

It ought to be implemented in msysgit, but there are two downsides:

  • Symbolic links are only available in Windows Vista and later (should not be an issue in 2011, and yet it is...), since older versions only support directory junctions.
  • (the big one) Microsoft considers symbolic links a security risk and so only administrators can create them by default. You'll need to elevate privileges of the git process or use fstool to change this behavior on every machine you work on.

I did a quick search and there is work being actively done on this, see issue 224.

C# Enum - How to Compare Value

You should convert the string to an enumeration value before comparing.

Enum.TryParse("Retailer", out AccountType accountType);

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

What are the ways to make an html link open a folder

The URL file://[servername]/[sharename] should open an explorer window to the shared folder on the network.

gradlew: Permission Denied

This error is gradle permission related . Just paste below line in your terminal and run...

chmod a+rx android/gradlew

Select a Column in SQL not in Group By

The columns in the result set of a select query with group by clause must be:

  • an expression used as one of the group by criteria , or ...
  • an aggregate function , or ...
  • a literal value

So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:

I want to find the individual claim row bearing the most recent creation date within each group in my claims table

Given

create table dbo.some_claims_table
(
  claim_id     int      not null ,
  group_id     int      not null ,
  date_created datetime not null ,

  constraint some_table_PK primary key ( claim_id                ) ,
  constraint some_table_AK01 unique    ( group_id , claim_id     ) ,
  constraint some_Table_AK02 unique    ( group_id , date_created ) ,

)

The first thing to do is identify the most recent creation date for each group:

select group_id ,
       date_created = max( date_created )
from dbo.claims_table
group by group_id

That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select query:

select *
from dbo.claims_table t
join ( select group_id ,
       date_created = max( date_created )
       from dbo.claims_table
       group by group_id
      ) x on x.group_id     = t.group_id
         and x.date_created = t.date_created

If the table is not unique by date_created within group_id (AK02), you you can get duplicate rows for a given group.

foreach for JSON array , syntax

Sure, you can use JS's foreach.

for (var k in result) {
  something(result[k])
}

How to show imageView full screen on imageView click?

Use this property for an Image view such as,

1) android:scaleType="fitXY" - It means the Images will be stretched to fit all the sides of the parent that is based on your ImageView!

2) By using above property, it will affect your Image resolution so if you want to maintain the resolution then add a property such as android:scaleType="centerInside".

Android Canvas: drawing too large bitmap

if you use Picasso change to Glide like this.

Remove picasso

Picasso.get().load(Uri.parse("url")).into(imageView)

Change Glide

Glide.with(context).load("url").into(imageView)

More efficient Glide than Picasso draw to large bitmap

How can I make a checkbox readonly? not disabled?

There is no property to make the checkbox readonly. But you can try this trick.

<input type="checkbox" onclick="return false" />

DEMO

Get value of a string after last slash in JavaScript

Try;

var str = "foo/bar/test.html";
var tmp = str.split("/");
alert(tmp.pop());

Changing upload_max_filesize on PHP

I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:

upload_max_filesize = "20M"
post_max_size = "25M"

This is the recommended solution for Heroku.

"use database_name" command in PostgreSQL

The basic problem while migrating from MySQL I faced was, I thought of the term database to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin, the result would not be as expected. As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.

For this, we can use the SET search_path command. This does switch the current schema to the specified schema name for the current session.

example:

SET search_path = different_schema_name;

This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf file.

Sending email through Gmail SMTP server with C#

Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.

In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.

So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!

I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.

Angular 2 - innerHTML styling

The simple solution you need to follow is

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

Easy way to export multiple data.frame to multiple Excel worksheets

You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:

library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:

wb = createWorkbook()

sheet = createSheet(wb, "Sheet 1")

addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)

sheet = createSheet(wb, "Sheet 2")

addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)

saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx: http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software

Testing web application on Mac/Safari when I don't own a Mac

https://turbo.net/ offers a browser sandbox in which containerised virtual machines run browser sessions for you. I tried it with Safari on my Windows development machine and it seems to work very well.

Code coverage for Jest built on top of Jasmine

When using Jest 21.2.1, I can see code coverage at the command line and create a coverage directory by passing --coverage to the Jest script. Below are some examples:

I tend to install Jest locally, in which case the command might look like this:

npx jest --coverage

I assume (though haven't confirmed), that this would also work if I installed Jest globally:

jest --coverage

The very sparse docs are here

When I navigated into the coverage/lcov-report directory I found an index.html file that could be loaded into a browser. It included the information printed at the command line, plus additional information and some graphical output.

How to refresh datagrid in WPF

From MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

Possible to change where Android Virtual Devices are saved?

Another way to specify ANDROID_SDK_HOME without messing around with environment variables (especially when using ec2) is simply create a shortcut of eclipse and add the following as target

C:\Windows\System32\cmd.exe /C "setx ANDROID_SDK_HOME YOUR AVD PATH /M & YOUR ECLIPSE.EXE PATH"

This will set ANDROID_SDK_HOME as system variable whenever you launch eclipse.

HTH Paul

AssertionError: View function mapping is overwriting an existing endpoint function: main

For users that use @app.route it is better to use the key-argument endpoint rather then chaning the value of __name__ like Roei Bahumi stated. Taking his example will be:

@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
    pass

@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
    pass

uppercase first character in a variable with bash

Alternative and clean solution for both Linux and OSX, it can also be used with bash variables

python -c "print(\"abc\".capitalize())"

returns Abc

Obtain form input fields using jQuery?

All answers are good, but if there's a field that you like to ignore in that function? Easy, give the field a property, for example ignore_this:

<input type="text" name="some_name" ignore_this>

And in your Serialize Function:

if(!$(name).prop('ignorar')){
   do_your_thing;
}

That's the way you ignore some fields.

git push rejected: error: failed to push some refs

I did the following steps to resolve the issue. On the branch which was giving me the error:

  1. git pull origin [branch-name]<current branch>
  2. After pulling, got some merge issues, solved them, pushed the changes to the same branch.
  3. Created the Pull request with the pushed branch... tada, My changes were reflecting, all of them.

Resize height with Highcharts

According to the API Reference:

By default the height is calculated from the offset height of the containing element. Defaults to null.

So, you can control it's height according to the parent div using redraw event, which is called when it changes it's size.

References

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

or MVC 2.0:

<%= Html.RadioButtonFor(model => model.blah, true) %> Yes
<%= Html.RadioButtonFor(model => model.blah, false) %> No

Get the last non-empty cell in a column in Google Sheets

for a row:

=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))

for a column:

=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))

Laravel Migration table already exists, but I want to add new not the older

You can delete all the tables but it will be not a good practice, instead try this command

php artisan migrate:fresh

Make sure to use the naming convention correctly. I have tested this in version laravel 5.7 It is important to not try this command when your site is on server because it drops all information.

Bootstrap $('#myModal').modal('show') is not working

After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.

Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using

setTimeout(() => {  $('#modalID').modal('show'); }, 500);

Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it

Moving up one directory in Python

>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

How to make inline plots in Jupyter Notebook larger?

The default figure size (in inches) is controlled by

matplotlib.rcParams['figure.figsize'] = [width, height]

For example:

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]

creates a figure with 10 (width) x 5 (height) inches

JavaScript open in a new window, not tab

try that method.....

function popitup(url) {
       //alert(url);
       newwindow=window.open("http://www.zeeshanakhter.com","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
       newwindow.moveTo(350,150);
   if (window.focus) 
          {
             newwindow.focus()
          }
   return false;
  }

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

How to combine date from one field with time from another field - MS SQL Server

If the time element of your date column and the date element of your time column are both zero then Lieven's answer is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated:

SELECT DATEADD(day, 0, DATEDIFF(day, 0, your_date_column)) +
    DATEADD(day, 0 - DATEDIFF(day, 0, your_time_column), your_time_column)
FROM your_table

how to remove time from datetime

You may try the following:

SELECT CONVERT(VARCHAR(10),yourdate,101);

or this:

select cast(floor(cast(urdate as float)) as datetime);

Breaking a list into multiple columns in Latex

I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.

Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!

How to change text color of cmd with windows batch script every 1 second

Try this script. This can write any text on any position of screen and don't use temporary files or ".com, .exe" executables. Just make shure you have the "debug.exe" executable in windows\system or windows\system32 folders.

http://pastebin.com/bzYhfLGc

@echo off
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init


:howuse ---------------------------------------------------------------

    echo ------------------
    echo ECOL.BAT - ver 1.0
    echo ------------------
    echo Print colored text in batch script
    echo Written by BrendanLS - http://640kbworld.forum.st
    echo.
    echo Syntax:
    echo ECOL.BAT [COLOR] [X] [Y] "Insert your text"
    echo COLOR value must be a hexadecimal number
    echo.
    echo Example:
    echo ECOL.BAT F0 20 30 "The 640KB World Forum"
    echo.
    echo Enjoy ;^)
    goto quit

:error ----------------------------------------------------------------

    set /a "_er=_er | (%~1)"
    goto quit

:geth -----------------------------------------------------------------

        set return=
        set bts=%~1

:hshift ---------------------------------------------------------------

        set /a "nn = bts & 0xff"
        set return=!h%nn%!%return%
        set /a "bts = bts >> 0x8"
        if %bts% gtr 0 goto hshift
        goto quit

:init -----------------------------------------------------------------

    if "%~4"=="" call :error 0xff

    (
        set /a _cl=0x%1
        call :error !errorlevel!
        set _cl=%1
        call :error "0x!_cl! ^>^> 8"
        set /a _px=%2
        call :error !errorlevel!
        set /a _py=%3
        call :error !errorlevel!
    ) 2>nul 1>&2

    if !_er! neq 0 (
        echo.
        echo ERROR: value exception "!_er!" occurred.
        echo.
        goto howuse
    )

    set nsys=0123456789abcdef
    set /a _val=-1

        for /l %%a in (0,1,15) do (
                for /l %%b in (0,1,15) do (
                        set /a "_val += 1"
                        set byte=!nsys:~%%a,1!!nsys:~%%b,1!
                        set h!_val!=!byte!
                )
        )

    set /a cnb=0
    set /a cnl=0

:parse ----------------------------------------------------------------

    set _ch=!_ln:~%_n%,1!
    if "%_ch%"=="" goto perform

    set /a "cnb += 1"
    if %cnb% gtr 7 (
        set /a cnb=0
        set /a "cnl += 1"
    )

    set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
    set /a "_n += 1"
    goto parse

:perform --------------------------------------------------------------

    set /a "in = ((_py * 160) + (_px * 2)) & 0xffff"
    call :geth %in%
    set ntr=!return!
    set /a jmp=0xe


    @for /l %%x in (0,1,%cnl%) do (
        set bl8086%%x=eb800:!ntr! !bln%%x!
        set /a "in=!jmp! + 0x!ntr!"
        call :geth !in!
        set ntr=!return!
        set /a jmp=0x10
    )

    (
    echo.%bl80860%&echo.%bl80861%&echo.%bl80862%&echo.%bl80863%&echo.%bl80864%
    echo.q
    )|debug >nul 2>&1

:quit

What is the difference between smoke testing and sanity testing?

Smoke testing

Smoke testing came from the hardware environment where testing should be done to check whether the development of a new piece of hardware causes no fire and smoke for the first time.

In the software environment, smoke testing is done to verify whether we can consider for further testing the functionality which is newly built.

Sanity testing

A subset of regression test cases are executed after receiving a functionality or code with small or minor changes in the functionality or code, to check whether it resolved the issues or software bugs and no other software bug is introduced by the new changes.


Difference between smoke testing and sanity testing

Smoke testing

  • Smoke testing is used to test all areas of the application without going into too deep.

  • A smoke test always use an automated test or a written set of tests. It is always scripted.

  • Smoke testing is designed to include every part of the application in a not thorough or detailed way.

  • Smoke testing always ensures whether the most crucial functions of a program are working, but not bothering with finer details.

Sanity testing

  • Sanity testing is a narrow test that focuses on one or a few areas of functionality, but not thoroughly or in-depth.

  • A sanity test is usually unscripted.

  • Sanity testing is used to ensure that after a minor change a small part of the application is still working.

  • Sanity testing is a cursory testing, which is performed to prove that the application is functioning according to the specifications. This level of testing is a subset of regression testing.

Hope these points help you to understand the difference between smoke testing and sanity testing.


References

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

in android

Replace: String webServiceUrl = "http://localhost:8080/Service1.asmx"

With : String webServiceUrl = "http://10.0.2.2:8080/Service1.asmx"

Good luck!

How to remove last n characters from every element in the R vector

Similar to @Matthew_Plourde using gsub

However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:

cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"    ""    ""

Difference is, {0,3} quantifier indicates 0 to 3 matches, whereas {3} requires exactly 3 matches otherwise no match is found in which case gsub returns the original, unmodified string.

N.B. using {,3} would be equivalent to {0,3}, I simply prefer the latter notation.

See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

How to make a SIMPLE C++ Makefile

Why does everyone like to list out source files? A simple find command can take care of that easily.

Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...

appname := myapp

CXX := clang++
CXXFLAGS := -std=c++11

srcfiles := $(shell find . -name "*.C")
objects  := $(patsubst %.C, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Round double value to 2 decimal places

Use NSNumber *aNumber = [NSNumber numberWithDouble:number]; instead of NSNumber *aNumber = [NSNumber numberWithFloat:number];

+(NSString *)roundToNearestValue:(double)number
{
    NSNumber *aNumber = [NSNumber numberWithDouble:number];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setUsesGroupingSeparator:NO];
    [numberFormatter setMaximumFractionDigits:2];
    [numberFormatter setMinimumFractionDigits:0];
    NSString *string = [numberFormatter stringFromNumber:aNumber];        
    return string;
}

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

ERROR: Cannot open source file " "

This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.

I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ; of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Check, using jQuery, if an element is 'display:none' or block on click

Use this condition:

if (jQuery(".profile-page-cont").css('display') == 'block'){
    // Condition 
}

Sending commands and strings to Terminal.app with Applescript

As neat solution, try-

$ open -a /Applications/Utilities/Terminal.app  *.py

or

$ open -b com.apple.terminal *.py

For the shell launched, you can go to Preferences > Shell > set it to exit if no error.

That's it.

Javascript loop through object array?

for (let key in data) {
    let value = data[key];
    for (i = 0; i < value.length; i++) {
      console.log(value[i].msgFrom);
      console.log(value[i].msgBody);
    }
  }

MySQL Workbench - Connect to a Localhost

enter image description here

I think you want to config your database server firstly after the installation, as shown in picture, you can reconfigure MySql server

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

How do I compile jrxml to get jasper?

In eclipse,

  • Install Jaspersoft Studio for eclipse.
  • Right click the .jrxml file and select Open with JasperReports Book Editor
  • Open the Design tab for the .jrxml file.
  • On top of the window you can see the Compile Report icon.

How to insert a new line in strings in Android

I use <br> in a CDATA tag. As an example, my strings.xml file contains an item like this:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>

and prints

My name is John
Nice to meet you

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had the same problem. It was caused because I compiled the Boost with the Visual C++ 2010(v100) and I tried to use the library with the Visual Studio 2012 (v110) by mistake.

So, I changed the configurations (in Visual Studio 2012) going to Project properties -> General -> Plataform Toolset and change the value from Visual Studio 2012 (v110) to Visual Studio 2010 (v100).

How do I make a burn down chart in Excel?

Why not graph the percentage complete. If you include the last date as a 100% complete value you can force the chart to show the linear trend as well as the actual data. This should give you a reasonable idea of whether you are above or below the line.

I would include a screenshot but not enough rep. Here is a link to one I prepared earlier. Burn Down Chart.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

Is there any use for unique_ptr with array?

  • You need your structure to contain just a pointer for binary-compatibility reasons.
  • You need to interface with an API that returns memory allocated with new[]
  • Your firm or project has a general rule against using std::vector, for example, to prevent careless programmers from accidentally introducing copies
  • You want to prevent careless programmers from accidentally introducing copies in this instance.

There is a general rule that C++ containers are to be preferred over rolling-your-own with pointers. It is a general rule; it has exceptions. There's more; these are just examples.

Entity Framework Core add unique constraint code-first

Solution for EF Core

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Passport { get; set; }
}

public class ApplicationContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public ApplicationContext()
    {
        Database.EnsureCreated();
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=efbasicsappdb;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasAlternateKey(u => u.Passport);
        //or: modelBuilder.Entity<User>().HasAlternateKey(u => new { u.Passport, u.Name})
    }
}

DB table will look like this:

CREATE TABLE [dbo].[Users] (
    [Id]       INT            IDENTITY (1, 1) NOT NULL,
    [Name]     NVARCHAR (MAX) NULL,
    [Passport] NVARCHAR (450) NOT NULL,
    CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [AK_Users_Passport] UNIQUE NONCLUSTERED ([Passport] ASC)
);

Ref to EF Core docs

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

Switch on Enum in Java

Article on Programming.Guide: Switch on enum


enum MyEnum { CONST_ONE, CONST_TWO }

class Test {
        public static void main(String[] args) {
            MyEnum e = MyEnum.CONST_ONE;

            switch (e) {
                case CONST_ONE: System.out.println(1); break;
                case CONST_TWO: System.out.println(2); break;
            }
        }
    }

Switches for strings are implemented in Java 7.

UIView frame, bounds and center

I found this image most helpful for understanding frame, bounds, etc.

enter image description here

Also please note that frame.size != bounds.size when the image is rotated.

How to iterate over a string in C?

  1. sizeof() includes the terminating null character. You should use strlen() (but put the call outside the loop and save it in a variable), but that's probably not what's causing the exception.
  2. you should use "%c", not "%s" in printf - you are printing a character, not a string.

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

How do I test which class an object is in Objective-C?

What means about isKindOfClass in Apple Documentation

Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:

// DO NOT DO THIS!
if ([myArray isKindOfClass:[NSMutableArray class]])
{
    // Modify the object
}

If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.

How does Java handle integer underflows and overflows and how would you check for it?

There is one case, that is not mentioned above:

int res = 1;
while (res != 0) {
    res *= 2;

}
System.out.println(res);

will produce:

0

This case was discussed here: Integer overflow produces Zero.

How to test if list element exists?

rlang::has_name() can do this too:

foo = list(a = 1, bb = NULL)
rlang::has_name(foo, "a")  # TRUE
rlang::has_name(foo, "b")  # FALSE. No partial matching
rlang::has_name(foo, "bb")  # TRUE. Handles NULL correctly
rlang::has_name(foo, "c")  # FALSE

As you can see, it inherently handles all the cases that @Tommy showed how to handle using base R and works for lists with unnamed items. I would still recommend exists("bb", where = foo) as proposed in another answer for readability, but has_name is an alternative if you have unnamed items.

Could not connect to React Native development server on Android

When I started a new project

react-native init MyPrroject

I got could not connect to development server on both platforms iOS and Android.

My solution is to

sudo lsof -i :8081
//find a PID of node
kill -9 <node_PID>

Also make sure that you use your local IP address

ipconfig getifaddr en0

Add a Progress Bar in WebView

The best approch which worked for me is

webView.setWebViewClient(new WebViewClient() {

    @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          mProgressBar.setVisibility(ProgressBar.VISIBLE);
          webView.setVisibility(View.INVISIBLE);
        }

    @Override public void onPageCommitVisible(WebView view, String url) {
      super.onPageCommitVisible(view, url);
      mProgressBar.setVisibility(ProgressBar.GONE);
      webView.setVisibility(View.VISIBLE);
      isWebViewLoadingFirstPage=false;
    }
}

IsNull function in DB2 SQL?

I think COALESCE function partially similar to the isnull, but try it.

Why don't you go for null handling functions through application programs, it is better alternative.

Difference between dates in JavaScript

var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

Usage

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

OR

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // m || y || d

var qtMonths = DateDiff('month', new Date('2015-05-05'), new Date()); // month || year || day

var qtMonths = DateDiff('months', new Date('2015-05-05'), new Date()); // months || years || days

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}

Permission denied for relation

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

Why use pip over easy_install?

Many of the answers here are out of date for 2015 (although the initially accepted one from Daniel Roseman is not). Here's the current state of things:

  • Binary packages are now distributed as wheels (.whl files)—not just on PyPI, but in third-party repositories like Christoph Gohlke's Extension Packages for Windows. pip can handle wheels; easy_install cannot.
  • Virtual environments (which come built-in with 3.4, or can be added to 2.6+/3.1+ with virtualenv) have become a very important and prominent tool (and recommended in the official docs); they include pip out of the box, but don't even work properly with easy_install.
  • The distribute package that included easy_install is no longer maintained. Its improvements over setuptools got merged back into setuptools. Trying to install distribute will just install setuptools instead.
  • easy_install itself is only quasi-maintained.
  • All of the cases where pip used to be inferior to easy_install—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can pip install ., pip install git+https://.
  • pip comes with the official Python 2.7 and 3.4+ packages from python.org, and a pip bootstrap is included by default if you build from source.
  • The various incomplete bits of documentation on installing, using, and building packages have been replaced by the Python Packaging User Guide. Python's own documentation on Installing Python Modules now defers to this user guide, and explicitly calls out pip as "the preferred installer program".
  • Other new features have been added to pip over the years that will never be in easy_install. For example, pip makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.

The only good reason that I know of to use easy_install in 2015 is the special case of using Apple's pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included easy_install, but as of 10.10 they still don't include pip. With 10.9+, you should still just use get-pip.py, but for 10.5-10.8, this has some problems, so it's easier to sudo easy_install pip. (In general, easy_install pip is a bad idea; it's only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include readline in a way that easy_install knows how to kludge around but pip doesn't, so you also want to sudo easy_install readline if you want to upgrade that.

Unix command-line JSON parser?

You could try jsawk as suggested in this answer.

Really you could whip up a quick python script to do this though.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

test if event handler is bound to an element in jQuery

Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.

I therefore use die() or unbind() like this:

$("#someid").die("click").live("click",function(){...

or

$("#someid").unbind("click").bind("click",function(){...

or in recent jQuery versions:

$("#someid").off("click").on("click",function(){...

LaTeX source code listing like in professional books

And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.

Try setting fixed-width font with this:

\lstset{basicstyle=\ttfamily}

How to set Java SDK path in AndroidStudio?

C:\Program Files\Android\Android Studio\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

Somehow the Studio installer would install another version under:

C:\Program Files\Android\Android Studio\jre\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

where the latest version was installed the Java DevKit installer in:

C:\Program Files\Java\jre1.8.0_121\bin>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Need to clean up the Android Studio so it would use the proper latest 1.8.0 versions.

According to How to set Java SDK path in AndroidStudio? one could override with a specific JDK but when I renamed

C:\Program Files\Android\Android Studio\jre\jre\

to:

C:\Program Files\Android\Android Studio\jre\oldjre\

And restarted Android Studio, it would complain that the jre was invalid. When I tried to aecify an JDK to pick the one in C:\Program Files\Java\jre1.8.0_121\bin or:

C:\Program Files\Java\jre1.8.0_121\

It said that these folders are invalid. So I guess that the embedded version must have some special purpose.

Maximum call stack size exceeded error

Check the error details in the Chrome dev toolbar console, this will give you the functions in the call stack, and guide you towards the recursion that's causing the error.

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.

So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'

I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.

G.

Internet Access in Ubuntu on VirtualBox

How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

Regular expression for URL validation (in JavaScript)

I couldn't find one that worked well for my needs. Written and post @ https://gist.github.com/geoffreyrobichaux/0a7774b424703b6c0fffad309ab0ad0a

_x000D_
_x000D_
function validURL(s) {_x000D_
    var regexp = /^(ftp|http|https|chrome|:\/\/|\.|@){2,}(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\S*:\w*@)*([a-zA-Z]|(\d{1,3}|\.){7}){1,}(\w|\.{2,}|\.[a-zA-Z]{2,3}|\/|\?|&|:\d|@|=|\/|\(.*\)|#|-|%)*$/gum_x000D_
    return regexp.test(s);_x000D_
}
_x000D_
_x000D_
_x000D_

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

how to generate public key from windows command prompt

ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key

error: use of deleted function

gcc 4.6 supports a new feature of deleted functions, where you can write

hdealt() = delete;

to disable the default constructor.

Here the compiler has obviously seen that a default constructor can not be generated, and =delete'd it for you.

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

How to mock location on device?

This worked for me (Android Studio):

Disable GPS and WiFi tracking on the phone. On Android 5.1.1 and below, select "enable mock locations" in Developer Options.

Make a copy of your manifest in the src/debug directory. Add the following to it (outside of the "application" tag):

uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"

Set up a map Fragment called "map". Include the following code in onCreate():

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new MyLocationListener();
if (lm.getProvider("Test") == null) {
    lm.addTestProvider("Test", false, false, false, false, false, false, false, 0, 1);
}
lm.setTestProviderEnabled("Test", true);
lm.requestLocationUpdates("Test", 0, 0, ll);

map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng l) {
        Location loc = new Location("Test");
        loc.setLatitude(l.latitude);
        loc.setLongitude(l.longitude);
        loc.setAltitude(0); 
        loc.setAccuracy(10f);
        loc.setElapsedRealtimeNanos(System.nanoTime());
        loc.setTime(System.currentTimeMillis()); 
        lm.setTestProviderLocation("Test", loc);
    }
};

Note that you may have to temporarily increase "minSdkVersion" in your module gradle file to 17 in order to use the "setElapsedRealtimeNanos" method.

Include the following code inside the main activity class:

private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        // do whatever you want, scroll the map, etc.
    }
}

Run your app with AS. On Android 6.0 and above you will get a security exception. Now go to Developer Options in Settings and select "Select mock location app". Select your app from the list.

Now when you tap on the map, onLocationChanged() will fire with the coordinates of your tap.

I just figured this out so now I don't have to tramp around the neighborhood with phones in hand.

How do I enable NuGet Package Restore in Visual Studio?

It took far too long but I finally found this document on Migrating MSBuild-Integrated solutions to Automatic Package Restore and I was able to resolve the issue using the methods described here.

  1. Remove the '.nuget' solution directory along from the solution
  2. Remove all references to nuget.targets from your .csproj or .vbproj files. Though not officially supported, the document links to a PowerShell script if you have a lot of projects which need to be cleaned up. I manually edited mine by hand so I can't give any feedback regarding my experience with it.

When editing your files by hand, here's what you'll be looking for:

Solution File (.sln)

Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
    .nuget\NuGet.Config = .nuget\NuGet.Config
    .nuget\NuGet.exe = .nuget\NuGet.exe
    .nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject

Project File (.csproj / .vbproj)

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

Can I make a <button> not submit a form?

Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".

Android - Pulling SQlite database android device

 adb shell "run-as [package.name] chmod -R 777 /data/data/[package.name]/databases" 
 adb shell "mkdir -p /sdcard/tempDB" 
 adb shell "cp -r /data/data/[package.name]/databases/ /sdcard/tempDB/." 
 adb pull sdcard/tempDB/ . 
 adb shell "rm -r /sdcard/tempDB/*"

How to clear the interpreter console?

>>> ' '*80*25

UPDATE: 80x25 is unlikely to be the size of console windows, so to get the real console dimensions, use functions from pager module. Python doesn't provide anything similar from core distribution.

>>> from pager import getheight
>>> '\n' * getheight()

How do I set up IntelliJ IDEA for Android applications?

Just in case someone is lost. For both new application or existing ones go to File->Project Structure. Then in Project settings on the left pane select Project for the Java SDK and select Modules for Android SDK.

Android Service needs to run always (Never pause or stop)

A simple solution is to restart the service when the system stops it.

I found this very simple implementation of this method:

How to make android service unstoppable

How do I add records to a DataGridView in VB.Net?

If your DataGridView is bound to a DataSet, you can not just add a new row in your DataGridView display. It will now work properly.

Instead you should add the new row in the DataSet with this code:

BindingSource[Name].AddNew()

This code will also automatically add a new row in your DataGridView display.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

one line only

<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

How can I send the "&" (ampersand) character via AJAX?

You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).

JavaScript (Docu)

var wysiwyg_clean = window.btoa( wysiwyg );

PHP (Docu):

var wysiwyg = base64_decode( $_POST['wysiwyg'] );

How do I open multiple instances of Visual Studio Code?

In Linux (tested with Ubuntu and Kali Linux) you can also right click the tile on the dock and select New Window.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to print the values of slices

I prefer fmt.Printf("%+q", arr) which will print

["some" "values" "list"]

https://play.golang.org/p/XHfkENNQAKb

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

Delaying AngularJS route change until model loaded to prevent flicker

I like darkporter's idea because it will be easy for a dev team new to AngularJS to understand and worked straight away.

I created this adaptation which uses 2 divs, one for loader bar and another for actual content displayed after data is loaded. Error handling would be done elsewhere.

Add a 'ready' flag to $scope:

$http({method: 'GET', url: '...'}).
    success(function(data, status, headers, config) {
        $scope.dataForView = data;      
        $scope.ready = true;  // <-- set true after loaded
    })
});

In html view:

<div ng-show="!ready">

    <!-- Show loading graphic, e.g. Twitter Boostrap progress bar -->
    <div class="progress progress-striped active">
        <div class="bar" style="width: 100%;"></div>
    </div>

</div>

<div ng-show="ready">

    <!-- Real content goes here and will appear after loading -->

</div>

See also: Boostrap progress bar docs

How to stop PHP code execution?

Apart from the obvious die() and exit(), this also works:

<?php
echo "start";
__halt_compiler();
echo "you should not see this";
?>

How do I redirect a user when a button is clicked?

if using JQuery, you can do this :

<script type="text/javascript">
    $('#buttonid').click(function () {
        document.location = '@Url.Action("ActionName","ControllerName")';
    });
</script>

Find row in datatable with specific id

DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
    // code
}

If it is a typed DataSet:

MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
    // code
}

Why do we use __init__ in Python classes?

By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. __init__ doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. The class is a concept of an object. When you see Fido and Spot, you recognise their similarity, their doghood. That's the class.

When you say

class Dog:
    def __init__(self, legs, colour):
        self.legs = legs
        self.colour = colour

fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")

You're saying, Fido is a brown dog with 4 legs while Spot is a bit of a cripple and is mostly yellow. The __init__ function is called a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self. The notation self.legs is an attribute called legs of the object in the variable self. Attributes are kind of like variables, but they describe the state of an object, or particular actions (functions) available to the object.

However, notice that you don't set colour for the doghood itself - it's an abstract concept. There are attributes that make sense on classes. For instance, population_size is one such - it doesn't make sense to count the Fido because Fido is always one. It does make sense to count dogs. Let us say there're 200 million dogs in the world. It's the property of the Dog class. Fido has nothing to do with the number 200 million, nor does Spot. It's called a "class attribute", as opposed to "instance attributes" that are colour or legs above.

Now, to something less canine and more programming-related. As I write below, class to add things is not sensible - what is it a class of? Classes in Python make up of collections of different data, that behave similarly. Class of dogs consists of Fido and Spot and 199999999998 other animals similar to them, all of them peeing on lampposts. What does the class for adding things consist of? By what data inherent to them do they differ? And what actions do they share?

However, numbers... those are more interesting subjects. Say, Integers. There's a lot of them, a lot more than dogs. I know that Python already has integers, but let's play dumb and "implement" them again (by cheating and using Python's integers).

So, Integers are a class. They have some data (value), and some behaviours ("add me to this other number"). Let's show this:

class MyInteger:
    def __init__(self, newvalue)
        # imagine self as an index card.
        # under the heading of "value", we will write
        # the contents of the variable newvalue.
        self.value = newvalue
    def add(self, other):
        # when an integer wants to add itself to another integer,
        # we'll take their values and add them together,
        # then make a new integer with the result value.
        return MyInteger(self.value + other.value)

three = MyInteger(3)
# three now contains an object of class MyInteger
# three.value is now 3
five = MyInteger(5)
# five now contains an object of class MyInteger
# five.value is now 5
eight = three.add(five)
# here, we invoked the three's behaviour of adding another integer
# now, eight.value is three.value + five.value = 3 + 5 = 8
print eight.value
# ==> 8

This is a bit fragile (we're assuming other will be a MyInteger), but we'll ignore now. In real code, we wouldn't; we'd test it to make sure, and maybe even coerce it ("you're not an integer? by golly, you have 10 nanoseconds to become one! 9... 8....")

We could even define fractions. Fractions also know how to add themselves.

class MyFraction:
    def __init__(self, newnumerator, newdenominator)
        self.numerator = newnumerator
        self.denominator = newdenominator
        # because every fraction is described by these two things
    def add(self, other):
        newdenominator = self.denominator * other.denominator
        newnumerator = self.numerator * other.denominator + self.denominator * other.numerator
        return MyFraction(newnumerator, newdenominator)

There's even more fractions than integers (not really, but computers don't know that). Let's make two:

half = MyFraction(1, 2)
third = MyFraction(1, 3)
five_sixths = half.add(third)
print five_sixths.numerator
# ==> 5
print five_sixths.denominator
# ==> 6

You're not actually declaring anything here. Attributes are like a new kind of variable. Normal variables only have one value. Let us say you write colour = "grey". You can't have another variable named colour that is "fuchsia" - not in the same place in the code.

Arrays solve that to a degree. If you say colour = ["grey", "fuchsia"], you have stacked two colours into the variable, but you distinguish them by their position (0, or 1, in this case).

Attributes are variables that are bound to an object. Like with arrays, we can have plenty colour variables, on different dogs. So, fido.colour is one variable, but spot.colour is another. The first one is bound to the object within the variable fido; the second, spot. Now, when you call Dog(4, "brown"), or three.add(five), there will always be an invisible parameter, which will be assigned to the dangling extra one at the front of the parameter list. It is conventionally called self, and will get the value of the object in front of the dot. Thus, within the Dog's __init__ (constructor), self will be whatever the new Dog will turn out to be; within MyInteger's add, self will be bound to the object in the variable three. Thus, three.value will be the same variable outside the add, as self.value within the add.

If I say the_mangy_one = fido, I will start referring to the object known as fido with yet another name. From now on, fido.colour is exactly the same variable as the_mangy_one.colour.

So, the things inside the __init__. You can think of them as noting things into the Dog's birth certificate. colour by itself is a random variable, could contain anything. fido.colour or self.colour is like a form field on the Dog's identity sheet; and __init__ is the clerk filling it out for the first time.

Any clearer?

EDIT: Expanding on the comment below:

You mean a list of objects, don't you?

First of all, fido is actually not an object. It is a variable, which is currently containing an object, just like when you say x = 5, x is a variable currently containing the number five. If you later change your mind, you can do fido = Cat(4, "pleasing") (as long as you've created a class Cat), and fido would from then on "contain" a cat object. If you do fido = x, it will then contain the number five, and not an animal object at all.

A class by itself doesn't know its instances unless you specifically write code to keep track of them. For instance:

class Cat:
    census = [] #define census array

    def __init__(self, legs, colour):
        self.colour = colour
        self.legs = legs
        Cat.census.append(self)

Here, census is a class-level attribute of Cat class.

fluffy = Cat(4, "white")
spark = Cat(4, "fiery")
Cat.census
# ==> [<__main__.Cat instance at 0x108982cb0>, <__main__.Cat instance at 0x108982e18>]
# or something like that

Note that you won't get [fluffy, sparky]. Those are just variable names. If you want cats themselves to have names, you have to make a separate attribute for the name, and then override the __str__ method to return this name. This method's (i.e. class-bound function, just like add or __init__) purpose is to describe how to convert the object to a string, like when you print it out.

CURRENT_TIMESTAMP in milliseconds

The correct way of extracting miliseconds from a timestamp value on PostgreSQL accordingly to current documentation is:

SELECT date_part('milliseconds', current_timestamp);

--OR

SELECT EXTRACT(MILLISECONDS FROM current_timestamp);

with returns: The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

PHP Regex to check date is in YYYY-MM-DD format

Check and validate YYYY-MM-DD date in one line statement

function isValidDate($date) {
    return preg_match("/^(\d{4})-(\d{1,2})-(\d{1,2})$/", $date, $m)
        ? checkdate(intval($m[2]), intval($m[3]), intval($m[1]))
        : false;
}

The output will be:

var_dump(isValidDate("2018-01-01")); // bool(true)
var_dump(isValidDate("2018-1-1"));   // bool(true)
var_dump(isValidDate("2018-02-28")); // bool(true)
var_dump(isValidDate("2018-02-30")); // bool(false)

Day and month without leading zero are allowed. If you don't want to allow this, the regexp should be:

"/^(\d{4})-(\d{2})-(\d{2})$/"

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

Difference between jar and war in Java

WAR stands for Web application ARchive

JAR stands for Java ARchive

enter image description here

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item

<div class="carousel-item active"></div>

RENAMED To the following:

<div class="item active"></div>

Android Failed to install HelloWorld.apk on device (null) Error

go setting- security verify apps if checked, change to unchecked status, then change to checked status

How to list the size of each file and directory and sort by descending size in Bash?

Simply navigate to directory and run following command:

du -a --max-depth=1 | sort -n

OR add -h for human readable sizes and -r to print bigger directories/files first.

du -a -h --max-depth=1 | sort -hr

How to dynamically add and remove form fields in Angular 2

addAccordian(type, data) { console.log(type, data);

let form = this.form;

if (!form.controls[type]) {
  let ownerAccordian = new FormArray([]);
  const group = new FormGroup({});
  ownerAccordian.push(
    this.applicationService.createControlWithGroup(data, group)
  );
  form.controls[type] = ownerAccordian;
} else {
  const group = new FormGroup({});
  (<FormArray>form.get(type)).push(
    this.applicationService.createControlWithGroup(data, group)
  );
}
console.log(this.form);

}

Radio Buttons ng-checked with ng-model

Please explain why same ng-model is used? And what value is passed through ng- model and how it is passed? To be more specific, if I use console.log(color) what would be the output?

How to implement the Softmax function in Python

A more concise version is:

def softmax(x):
    return np.exp(x) / np.exp(x).sum(axis=0)

Installing R with Homebrew

I used this tutorial to install R on my mac, and it had me install xquartz and a fortran complier (gfortran) as well.

My suggestion would be to brew untap homebrew/science and then brew tap homebrew/science and try again, also, make sure you don't have any errors when you run brew doctor

Hope this helps

How to select only the records with the highest date in LINQ

Go a simple way to do this :-

Created one class to hold following information

  • Level (number)
  • Url (Url of the site)

Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.

var query = from MyClass object in objCollection 
    orderby object.Level descending 
    select object

Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row

MyClass topObject = query.FirstRow<MyClass>()

This worked like charm.

How to print a single backslash?

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))
\

When tracing out variables in the console, How to create a new line?

The worst thing of using just

console.log({'some stuff': 2} + '\n' + 'something')

is that all stuff are converted to the string and if you need object to show you may see next:

[object Object]

Thus my variant is the next code:

console.log({'some stuff': 2},'\n' + 'something');

How to completely remove node.js from Windows

In my case, the above alone didn't work. I had installed and uninstalled several versions of nodejs to fix this error: npm in windows Error: EISDIR, read at Error (native) that I kept getting on any npm command I tried to run, including getting the npm version with: npm -v.

So the npm directory was deleted in the nodejs folder and the latest npm version was copied over from the npm dist: and then everything started working.

What does the return keyword do in a void method in Java?

You can have return in a void method, you just can't return any value (as in return 5;), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:

void someFunct(int arg)
{
    if (arg == 0)
    {
        //Leave because this is a bad value
        return;
    }
    //Otherwise, do something
}

SQL Server AS statement aliased column within WHERE statement

Both accepted answer and Logical Processing Order explain why you could not do what you proposed.

Possible solution:

  • use derived table (cte/subquery)
  • use expression in WHERE
  • create view/computed column

From SQL Server 2008 you could use APPLY operator combined with Table valued Constructor:

SELECT *, s.distance
FROM poi_table 
CROSS APPLY (VALUES(6371*1000*acos(cos(radians(42.3936868308))*cos(radians(lat))*cos(radians(lon)-radians(-72.5277256966))+sin(radians(42.3936868308))*sin(radians(lat))))) AS s(distance)
WHERE distance < 500;

LiveDemo

Match line break with regular expression

You could search for:

<li><a href="#">[^\n]+

And replace with:

$0</a>

Where $0 is the whole match. The exact semantics will depend on the language are you using though.


WARNING: You should avoid parsing HTML with regex. Here's why.

Why am I getting InputMismatchException?

Are you providing write input to the console ?

Scanner reader = new Scanner(System.in);
num = reader.nextDouble();  

This is return double if you just enter number like 456. In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .

Create a tag in a GitHub repository

In case you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

Selecting empty text input using jQuery

As mentioned in the top ranked post, the following works with the Sizzle engine.

$('input:text[value=""]');

In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.

So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.

How to split one string into multiple variables in bash shell?

If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

I chose cut here because you could simply extend the code for a few more variables...

Calculate age based on date of birth

Reference Link http://www.calculator.net/age-calculator.html

$hours_in_day   = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;

$birth_date     = new DateTime("1988-07-31T00:00:00");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";
echo $hours     = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins      = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds   = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Android Studio-No Module

I had the same issue when using Kotlin DSL. The project level build.gradle.kts file seemed to be causing problems in that Android Studio could not detect it. What solved this for me was:

Rename build.gradle.kts -> build.gradle
File -> Sync Project with Gradle Files
Rename build.gradle -> build.gradle.kts

Hope it helps.