Programs & Examples On #Rdflib

RDFLib is a Python library for working with RDF. It supports parsers and serializers for different syntaxes (RDF/XML, N3, N-Triples, Turtle, TriX and RDFa) as well of remote and local SPARQL queries. Please do not use this tag for rdflib.js.

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

How do I export an Android Studio project?

It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).

Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.

Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.

Remove menubar from Electron app

As of 7.0.0, most of the above solutions no longer work. BrowserWindow.setMenu() has been replaced by Menu.setApplicationMenu(), which now changes the menu on all windows. setMenu(), removeMenu() no longer do anything, Which by the way are still mentioned in the docs.

setAutoHideMenuBar() still works, but could be a nuisance if you planned to use Alt as a hotkey modifier. Once menu is visible you have to click away from window (loose focus) to hide menu again.

If your application has more than one window, you can't set/remove menus separately on each window. The only way to remove a menu is to use the frameless window approach. That happens to be what I want in my current application, but not a good solution in all cases.

Arrays in cookies PHP

Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode). Be aware that there is a limit on the length of the string you can store though.

_tkinter.TclError: no display name and no $DISPLAY environment variable

I also met this problem while using Xshell to connect Linux server.

After seaching for methods, I find Xming + Xshell to solve image imshow problem with matplotlib.

If solutions aboved can't solve your problem, just try to download Xming under the condition you're using Xshell. Then set the attribute in Xshell, SSH->tunnel->X11transfer->choose X DISPLAY localhost:0.0

how to have two headings on the same line in html

The Css vertical-align property should help you out here:

vertical-align: bottom;

is what you need for your smaller header :)

Vertical-Align

Python 3 Float Decimal Points/Precision

Try this:

num = input("Please input your number: ")

num = float("%0.2f" % (num))

print(num)

I believe this is a lot simpler. For 1 decimal place use %0.1f. For 2 decimal places use %0.2f and so on.

Or, if you want to reduce it all to 2 lines:

num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

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

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

return, return None, and no return at all?

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      

How do I extend a class with c# extension methods?

I would do the same as Kumu

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
           return date.AddDays(1);
        }    
    }
}

but call it like this new DateTime().Tomorrow();

Think it makes more seens than DateTime.Now.Tomorrow();

TypeError: 'NoneType' object has no attribute '__getitem__'

The function move.CompleteMove(events) that you use within your class probably doesn't contain a return statement. So nothing is returned to self.values (==> None). Use return in move.CompleteMove(events) to return whatever you want to store in self.values and it should work. Hope this helps.

How do I overload the square-bracket operator in C#?

you can find how to do it here. In short it is:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}

If you only need a getter the syntax in answer below can be used as well (starting from C# 6).

Error 405 (Method Not Allowed) Laravel 5

This might help someone so I'll put my inputs here as well.

I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148

After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.

I whitelisted those rules and voila, the 405 error was gone.

Hope this helps someone.

How to put wildcard entry into /etc/hosts?

use dnsmasq

pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with

(sudo) systemctl status dnsmasq

If it is just disabled start it with

(sudo) systemctl start dnsmasq

If you have to install it, write

(sudo) apt-get install dnsmasq

To define domains to resolve edit /etc/dnsmasq.conf like this

address=/example.com/127.0.0.1

to resolve *.example.com

! You need to reload dnsmasq to take effect for the changes !

systemctl reload dnsmasq

Cannot read property 'addEventListener' of null

Thanks from all, Load the Scripts in specific pages that you use, not for all pages, sometimes using swiper.js or other library it may cause this error message, the only way to solve this issue it to load the JS library on specific pages that ID is exist and prevent loading of the same library in all pages.

Hope this help you.

Get an element by index in jQuery

You can use the eq method or selector:

$('ul').find('li').eq(index).css({'background-color':'#343434'});

Random character generator with a range of (A..Z, 0..9) and punctuation

Why reinvent the wheel? RandomStringUtils from Apache Commons has functions to which you can specify the character set from which characters are generated. You can take what you need to your app:

http://kickjava.com/src/org/apache/commons/lang/RandomStringUtils.java.htm

gpg decryption fails with no secret key error

When migrating from one machine to another-

  1. Check the gpg version and supported algorithms between the two systems.

    gpg --version

  2. Check the presence of keys on both systems.

    gpg --list-keys

    pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04

    gpg --list-secret-keys

    sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04

Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.

If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.

Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.

gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>

gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key

HTML5 Video Stop onClose

Try this:

if ($.browser.msie)
{
   // Some other solution as applies to whatever IE compatible video player used.
}
else
{
   $('video')[0].pause();
}

But, consider that $.browser is deprecated, but I haven't found a comparable solution.

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

Can't bind to 'dataSource' since it isn't a known property of 'table'

Remember to import the MatTableModule module and remove the table element show below for reference.
wrong implementation
<table mat-table [dataSource]=”myDataArray”> ... </table>
correct implementation:
<mat-table [dataSource]="myDataArray"> </mat-table>

(Mac) -bash: __git_ps1: command not found

Solution for MacOS Sierra and git version 2.10.1 <2017-2-06>

Step 1: Install the Git

You can skip this step if you already installed the latest git.

Download git package from browser https://git-scm.com/download/

Note: if you install with curl [option] https://... option to download, you would have to make sure your system support SSL. So for new comer, to download from browser and install directly from git installer is much easier.

Installation Verification:
  • Show where is your git directory at: which git
  • Show which version your git currently is: git --version current version should be 2.10.1.

Step 2: Add your git profile to your shell

  1. Open your shell profile:
    • nano ~/.bash_profile or nano ~/.bashrc Depends on where your modification is.
  2. Add the following code to the file:
    • source /usr/local/git/contrib/completion/git-completion.bash
    • source /usr/local/git/contrib/completion/git-prompt.sh

Note: git installation location changed from opt/ directory to usr/local/ after OSX upgrade to El Capitain, and this is why some of the old answer above doesn't work anymore in MacOS Sierra.

  1. Add the following code to your PS1 configuration:

    • Option 1: add directly to your PS1: export PS1='\w$(__git_ps1 "(%s)") > '

      I prefer this simple approach since I already know the .git-completion.bash is there in my home directory, and I can add other prompt format in the front of it. here is my personal prompt for your reference: export PS1='\t H#\! \u:\w$(__git_ps1 "{%s}") -->> '
    • Option 2: Add a selection script

    if [ -f ~/.git-completion.bash ]; then
          export PS1='\w$(__git_ps1 "(%s)") > '
    fi
  2. Save and use the profile: source ~/.bash_profile or source ~/.bashrc

Now you should see the git prompt working properly and shows which branch you are in right now.

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

You probably need to change your mount command from:

[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder

to:

[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder

where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".

Send data through routing paths in Angular

There is a new method what came with Angular 7.2.0

https://angular.io/api/router/NavigationExtras#state

Send:

this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Receive:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
}

You can find some additional info here:

https://github.com/angular/angular/pull/27198

The link above contains this example which can be useful: https://stackblitz.com/edit/angular-bupuzn

How to load image files with webpack file-loader

I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.

I used the following settings in the webpack:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.

Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.

I updated my webpack with the following settings

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

I then used the following command to import the images

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />
</div>

How to convert comma separated string into numeric array in javascript

You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

var arr = [1,2,3],
    strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
    arr.push( + strings[i] );

Or, in one step, using Array map to convert them and applying them to one single push:

arr.push.apply(arr, strVale.split(",").map(Number));

Length of a JavaScript object

Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.

Object.prototype.size = function () {
    var size = 0,
        key;
    for (key in this) {
        if (this.hasOwnProperty(key)) size++;
    }
    return size;
};

var x = {
    one: 1,
    two: 2,
    three: 3
};

x.size() === 3;

jsfiddle example: http://jsfiddle.net/qar4j/1/

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case I had two issues...

1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"

enter image description here

2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

enter image description here

Expand and collapse with angular js

In html

button ng-click="myMethod()">Videos</button>

In angular

 $scope.myMethod = function () {
         $(".collapse").collapse('hide');    //if you want to hide
         $(".collapse").collapse('toggle');  //if you want toggle
         $(".collapse").collapse('show');    //if you want to show
}

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

It's a kludge, but assuming there's a minimum length for SEARCHSTRING, for example 2 characters, substring the SEARCHSTRING parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu") and SEARCHSTRING2 ("ll"). Concatenate them back together when executing the query to the database.

How to restore SQL Server 2014 backup in SQL Server 2008

Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493

How to give a user only select permission on a database

create LOGIN guest WITH PASSWORD='guest@123', CHECK_POLICY = OFF;

Be sure when you want to exceute the following

DENY VIEW ANY DATABASE TO guest;

ALTER AUTHORIZATION ON DATABASE::BiddingSystemDB TO guest

Selected Database should be Master

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

Import Excel spreadsheet columns into SQL Server database

go
sp_configure 'show advanced options',1  
reconfigure with override  
go  
sp_configure 'Ad Hoc Distributed Queries',1  
reconfigure with override  
go
SELECT * into temptable
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
                'Excel 8.0;Database=C:\Documents and Settings\abhisharma\Desktop\exl\ImportExcel2SQLServer\ImportExcel2SQLServer\example.xls;IMEX=1',
                'SELECT * FROM [Sheet1$]')

select * from temptable

How set background drawable programmatically in Android

Use butterknife to bind the drawable resource to a variable by adding this to the top of your class (before any methods).

@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;

then inside one of your methods add

layout.setBackground(background);

That's all you need

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays have numerical indexes. So,

a = new Array();
a['a1']='foo';
a['a2']='bar';

and

b = new Array(2);
b['b1']='foo';
b['b2']='bar';

are not adding elements to the array, but adding .a1 and .a2 properties to the a object (arrays are objects too). As further evidence, if you did this:

a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length);   // outputs zero because there are no items in the array

Your third option:

c=['c1','c2','c3'];

is assigning the variable c an array with three elements. Those three elements can be accessed as: c[0], c[1] and c[2]. In other words, c[0] === 'c1' and c.length === 3.

Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.

a = {};
a['a1']='foo';
a['a2']='bar';

It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

Submit two forms with one button

The currently chosen best answer is too fuzzy to be reliable.

This feels to me like a fairly safe way to do it:

(Javascript: using jQuery to write it simpler)

$('#form1').submit(doubleSubmit);

function doubleSubmit(e1) {
    e1.preventDefault();
    e1.stopPropagation();
    var post_form1 = $.post($(this).action, $(this).serialize());

    post_form1.done(function(result) {
            // would be nice to show some feedback about the first result here
            $('#form2').submit();
        });
};

Post the first form without changing page, wait for the process to complete. Then post the second form. The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).

I didn't test the code, though.

How to execute UNION without sorting? (SQL)

I assume your tables are table1 and table2 respectively, and your solution is;

(select * from table1 MINUS select * from table2)
UNION ALL
(select * from table2 MINUS select * from table1)

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.

then,

use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   image{i}=csvread(strcat(path,'\',file(i).name));   
   % process the image in here
end

pwd also can be used.

Programmatically getting the MAC of an Android device

You can get mac address:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();

Set Permission in Menifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

How to get value by class name in JavaScript or jquery?

Without jQuery:

textContent:

var text = document.querySelector('.someClassname').textContent;

Markup:

var text = document.querySelector('.someClassname').innerHTML;

Markup including the matched element:

var text = document.querySelector('.someClassname').outerHTML;

though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.

Align <div> elements side by side

keep it simple

<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.

EDIT:

Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

What is the difference between T(n) and O(n)?

Theta is a shorthand way of referring to a special situtation where the big O and Omega are the same.

Thus, if one claims The Theta is expression q, then they are also necessarily claiming that Big O is expression q and Omega is expression q.


Rough analogy:

If: Theta claims, "That animal has 5 legs." then it follows that: Big O is true ("That animal has less than or equal to 5 legs.") and Omega is true("That animal has more than or equal to 5 legs.")

It's only a rough analogy because the expressions aren't necessarily specific numbers, but instead functions of varying orders of magnitude such as log(n), n, n^2, (etc.).

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

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

One option if the number of keys is small is to use chained gets:

value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

But if you have keySet defined, this might be clearer:

value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]
        break

The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

laravel 5.3 new Auth::routes()

If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php

How to make Sonar ignore some classes for codeCoverage metric?

For jacoco: use this properties:

-Dsonar.jacoco.excludes=**/*View.java

How to disable all <input > inside a form with jQuery?

The definitive answer (covering changes to jQuery api at version 1.6) has been given by Gnarf

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

How to get Exception Error Code in C#

You should look at the members of the thrown exception, particularly .Message and .InnerException.

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

How do I import other TypeScript files?

If you are doing something for the web you need to use the js file extension:

import { moo } from 'file.js';


If you are doing something for nodejs I don't think use the js file extension:

import { moo } from 'file';

Get lengths of a list in a jinja2 template

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

"Line contains NULL byte" in CSV reader (Python)

This is long settled, but I ran across this answer because I was experiencing an unexpected error while reading a CSV to process as training data in Keras and TensorFlow.

In my case, the issue was much simpler, and is worth being conscious of. The data being produced into the CSV wasn't consistent, resulting in some columns being completely missing, which seems to end up throwing this error as well.

The lesson: If you're seeing this error, verify that your data looks the way that you think it does!

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

How to declare a variable in MySQL?

  • Declare: SET @a = 1;

  • Usage: INSERT INTO `t` (`c`) VALUES (@a);

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

Styling a input type=number

the above code for chrome is working fine. i have tried like this in mozila but its not working. i found the solution for that

For mozila

input[type=number] { 
  -moz-appearance: textfield;
  appearance: textfield;
  margin: 0; 
}

Thanks Sanjib

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

PHP XML how to output nice format

With a SimpleXml object, you can simply

$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
/* @var $xml SimpleXMLElement */
$domxml->loadXML($xml->asXML());
$domxml->save($newfile);

$xml is your simplexml object

So then you simpleXml can be saved as a new file specified by $newfile

javascript toISOString() ignores timezone offset

moment.js FTW!!!

Just convert your date to a moment and manipulate it however you please:

var d = new Date(twDate);
var m = moment(d).format();
console.log(m);
// example output:
// 2016-01-08T00:00:00-06:00

http://momentjs.com/docs/

PHP compare two arrays and get the matched values not the difference

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);

Java client certificates over HTTPS/SSL

While not recommended, you can also disable SSL cert validation alltogether:

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLTool {

  public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { 
          return new X509Certificate[0]; 
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }};

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) { return true; }
    };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
  }
}

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

How can I make Jenkins CI with Git trigger on pushes to master?

In my current organization, we don't do this in master but do do it on both develop and release/ branches (we are using Git Flow), in order to generate snapshot builds.

As we are using a multi branch pipeline, we do this in the Jenkinsfile with the when{} syntax...

stage {
    when { 
        expression { 
            branch 'develop'
        }
    }
}

This is detailed in this blog post: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/#longer-pipeline

How to sort a Collection<T>?

You can't if T is all you get. It must be injected by the provider:

Collection<T extends Comparable>

or pass in the Comparator

Collections.sort(...)

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

At runtime, find all classes in a Java application that extend a base class

Thanks all who answered this question.

It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.

public abstract class Animal{
    private static Animal[] animals= null;
    public static Animal[] getAnimals(){
        if (animals==null){
            animals = new Animal[]{
                new Dog(),
                new Cat(),
                new Lion()
            };
        }
        return animals;
    }
}

It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.

I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.

Thanks again!

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Application Crashes With "Internal Error In The .NET Runtime"

with exit code 80131506

That's a nasty one, ExecutionEngineException. Starting with .NET 4.0, this exception immediately terminates the program. The generic cause is corruption of the state of the garbage collected heap. Which in turn is invariably caused by unmanaged code. The exact location in code at which this exception is raised isn't helpful, the corruption usually occurred well before the damage is detected.

Finding the exact cause for this is going to be difficult. Review any unmanaged code your service might be using. Suspect environmental problems if there is no obvious candidate, misbehaving malware scanners are notorious. If it repeats very poorly then suspect hardware problems like soft RAM errors.

How do I change the hover over color for a hover over table in Bootstrap?

Give this a try:

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #color;
}

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

Best way to use PHP to encrypt and decrypt passwords?

Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php

And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)

Get file path of image on Android

In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:

private void capture(){
    String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
    String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
    File directory = new File(directoryPath);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    this.capturePath = filePath; // you will process the image from this path if the capture goes well
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
    startActivityForResult(intent, REQUEST_CAPTURE);                

}

I just copied the above portion from another answer I gave.

However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.

Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device: Deleting a gallery image after camera intent photo taken

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1

Corrupt jar file

This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.

The problem occurs when you zip back the folder.

A valid Runnable/Executable JAR has the next structure:

myJAR (Main-Directory)
    |-META-INF (Mandatory)
             |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
    |-com 
         |-MainClass.class (must to implement the main method, mandatory)
    |-properties files (optional)
    |-etc (optional)

If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar

Once you're done try execute it on the command line using:

java -jar myJAR.jar 

When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:

**myJAR (Main-Directory)
    |-myJAR (creates another directory making the file corrupted)**
          |-META-INF (Mandatory)
                   |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
          |-com 
              |-MainClass.class (must to implement the main method, mandatory)
          |-properties files (optional)
          |-etc (optional)

:)

When is a timestamp (auto) updated?

Add a trigger in database:

DELIMITER //
CREATE TRIGGER update_user_password 
  BEFORE UPDATE ON users
  FOR EACH ROW
    BEGIN
      IF OLD.password <> NEW.password THEN
        SET NEW.password_changed_on = NOW();
      END IF;
    END //
DELIMITER ;

The password changed time will update only when password column is changed.

Detect all changes to a <input type="text"> (immediately) using JQuery

Well, best way is to cover those three bases you listed by yourself. A simple :onblur, :onkeyup, etc won't work for what you want, so just combine them.

KeyUp should cover the first two, and if Javascript is modifying the input box, well I sure hope it's your own javascript, so just add a callback in the function that modifies it.

Razor Views not seeing System.Web.Mvc.HtmlHelper

Just to expand on Matt DeKrey's answer, just deleting the csproj.user file (without needing to recreate solutions) was able to fix the problem for me.

The only side effect I had was I needed to reset the Start Action back to using a specific page.

How to extract a substring using regex

you can use this i use while loop to store all matches substring in the array if you use

if (matcher.find()) { System.out.println(matcher.group(1)); }

you will get on matches substring so you can use this to get all matches substring

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);

How can I export a GridView.DataSource to a datatable or dataset?

Ambu,

I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

    DataTable dt = new DataTable();

    // add the columns to the datatable            
    if (GridView1.HeaderRow != null)
    {

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
        }
    }

    //  add each of the data rows to the table
    foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

    //  add the footer row to the table
    if (GridView1.FooterRow != null)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
        {
            dr[i] = GridView1.FooterRow.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

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

If notepad is already started, you should write:

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

//...

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

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

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

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

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

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

This will achieve what you're asking about:

INSERT INTO table1 (ID, Name)
    VALUES (123, 'Timmy'), 
           (124, 'Jonny'), 
           (125, 'Sally');

For future developers, you can also insert from another table:

INSERT INTO table1 (ID, Name)
    SELECT 
         ID, 
         Name 
    FROM table2

Or even from multiple tables:

INSERT INTO table1 (column2, column3)
    SELECT 
         t2.column, 
         t3.column
    FROM table2 t2
         INNER JOIN table3 t3
         ON t2.ID = t3.ID

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

It worked for me after adding the following dependency in pom,

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>4.3.0.Final</version>
</dependency>

Setting background color for a JFrame

This is the simplest and the correct method. All you have to do is to add this code after initComponents();

getContentPane().setBackground(new java.awt.Color(204, 166, 166));

That is an example RGB color, you can replace that with your desired color. If you dont know the codes of RGB colors, please search on internet... there are a lot of sites that provide custom colors like this.

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Differences in In python 2 and 3 version:

If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.

If you wanted class methods, but you declared them as instance methods instead.

An instance method is a method that is used when to create an instance of the class.

An example would be

   def user_group(self):   #This is an instance method
        return "instance method returning group"

Class label method:

   @classmethod
   def user_group(groups):   #This is an class-label method
        return "class method returning group"

In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.

Java NIO FileChannel versus FileOutputstream performance / usefulness

Based on my tests (Win7 64bit, 6GB RAM, Java6), NIO transferFrom is fast only with small files and becomes very slow on larger files. NIO databuffer flip always outperforms standard IO.

  • Copying 1000x2MB

    1. NIO (transferFrom) ~2300ms
    2. NIO (direct datababuffer 5000b flip) ~3500ms
    3. Standard IO (buffer 5000b) ~6000ms
  • Copying 100x20mb

    1. NIO (direct datababuffer 5000b flip) ~4000ms
    2. NIO (transferFrom) ~5000ms
    3. Standard IO (buffer 5000b) ~6500ms
  • Copying 1x1000mb

    1. NIO (direct datababuffer 5000b flip) ~4500s
    2. Standard IO (buffer 5000b) ~7000ms
    3. NIO (transferFrom) ~8000ms

The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method: How to copy a large file in Windows XP?

SLF4J: Class path contains multiple SLF4J bindings

I had the same problem. In my pom.xml i had both

 <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.28</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>

When i deleted the spring-boot-starter-web dependency, problem was solved.

Android, How to limit width of TextView (and add three dots at the end of text)?

The approach of @AzharShaikh works fine.

android:ellipsize="end"
android:maxLines="1"

But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:

test long_line_without_any_space_abcdefgh

the TextView will display:

test...

And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:

yourString.replace(" ", "\u00A0");

The result:

test long_line_without_any_space_abc...

How to restart a node.js server

If it's just running (not a daemon) then just use Ctrl-C.

If it's daemonized then you could try:

$ ps aux | grep node
you   PID  1.5  0.2  44172  8260 pts/2    S    15:25   0:00 node app.js
$ kill -2 PID

Where PID is replaced by the number in the output of ps.

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

How can I convert my Java program to an .exe file?

The latest Java Web Start has been enhanced to allow good offline operation as well as allowing "local installation". It is worth looking into.

EDIT 2018: Java Web Start is no longer bundled with the newest JDK's. Oracle is pushing towards a "deploy your app locally with an enclosed JRE" model instead.

What should every programmer know about security?

Every programmer should know how to write exploit code.

Without knowing how systems are exploited you are accidentally stopping vulnerabilities. Knowing how to patch code is absolutely meaningless unless you know how to test your patches. Security isn't just a bunch of thought experiments, you must be scientific and test your experiments.

Adding custom HTTP headers using JavaScript

The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.

Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.

Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.

Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.

Does C# have a String Tokenizer like Java's?

If you're trying to do something like splitting command line arguments in a .NET Console app, you're going to have issues because .NET is either broken or is trying to be clever (which means it's as good as broken). I needed to be able to split arguments by the space character, preserving any literals that were quoted so they didn't get split in the middle. This is the code I wrote to do the job:

private static List<String> Tokenise(string value, char seperator)
{
    List<string> result = new List<string>();
    value = value.Replace("  ", " ").Replace("  ", " ").Trim();
    StringBuilder sb = new StringBuilder();
    bool insideQuote = false;
    foreach(char c in value.ToCharArray())
    {
        if(c == '"')
        {
            insideQuote = !insideQuote;
        }
        if((c == seperator) && !insideQuote)
        {
            if (sb.ToString().Trim().Length > 0)
            {
                result.Add(sb.ToString().Trim());
                sb.Clear();
            }
        }
        else
        {
            sb.Append(c);
        }
    }
    if (sb.ToString().Trim().Length > 0)
    {
        result.Add(sb.ToString().Trim());
    }

    return result;
}

How to scroll UITableView to specific position

Simply single line of code:

self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

Text in HTML Field to disappear when clicked?

Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">

How can I detect the touch event of an UIImageView?

Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

How can I get relative path of the folders in my android project?

Are you looking for the root folder of the application? Then I would use

 String path = getClass().getClassLoader().getResource(".").getPath();

to actually "find out where I am".

ImportError: No module named MySQLdb

Got so many errors related to permissions and what not. You may wanna try this :

xcode-select --install

JSON post to Spring Controller

Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.

batch file - counting number of files in folder and storing in a variable

FOR /f "delims=" %%i IN ('attrib.exe ./*.* ^| find /v "File not found - " ^| find /c /v ""') DO SET myVar=%%i
ECHO %myVar%

This is based on the (much) earlier post that points out that the count would be wrong for an empty directory if you use DIR rather than attrib.exe.

For anyone else who got stuck on the syntax for putting the command in a FOR loop, enclose the command in single quotes (assuming it doesn't contain them) and escape pipes with ^.

How to implement static class member functions in *.cpp file?

@crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:

::::::::::::::
main.cpp
::::::::::::::

#include <iostream>

#include "UseSomething.h"
#include "Something.h"

int main()
{
    UseSomething y;
    std::cout << y.getValue() << '\n';
}

::::::::::::::
Something.h
::::::::::::::

#ifndef SOMETHING_H_
#define SOMETHING_H_

class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};
#endif

::::::::::::::
Something.cpp
::::::::::::::

#include "Something.h"

int Something::s_value = 1; // initializer

::::::::::::::
UseSomething.h
::::::::::::::

#ifndef USESOMETHING_H_
#define USESOMETHING_H_

class UseSomething
{
public:
    int getValue();
};

#endif

::::::::::::::
UseSomething.cpp
::::::::::::::

#include "UseSomething.h"
#include "Something.h"

int UseSomething::getValue()
{
    return(Something::getValue());
}

Visual Studio window which shows list of methods

In VS 2012, just go to View > Class View...then you get the Class View GUI in the main tab area. Now, drag this over to the side dock and you have the exact same layout as you would in Eclipse.

-e

How do you count the lines of code in a Visual Studio solution?

Regular expressions have changed between VS2010 and 2012, so most of the regular expression solutions here no longer work

(^(?!(\s*//.+)))+(^(?!(#.+)))+(^(?!(\s*\{.+)))+(^(?!(\s*\}.+)))+(^(?!(\s*\r?$)))+

Will find all lines that are not blank, are not just a single bracket ( '{' or '}' ) and not just a #include or other preprocessor.

Use Ctrl-shift-f and make sure regular expressions are enabled.

The corresponding regular expression for VS 2010 and older is

^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

How do I get the full path to a Perl script that is executing?

The problem with __FILE__ is that it will print the core module ".pm" path not necessarily the ".cgi" or ".pl" script path that is running. I guess it depends on what your goal is.

It seems to me that Cwd just needs to be updated for mod_perl. Here is my suggestion:

my $path;

use File::Basename;
my $file = basename($ENV{SCRIPT_NAME});

if (exists $ENV{MOD_PERL} && ($ENV{MOD_PERL_API_VERSION} < 2)) {
  if ($^O =~/Win/) {
    $path = `echo %cd%`;
    chop $path;
    $path =~ s!\\!/!g;
    $path .= $ENV{SCRIPT_NAME};
  }
  else {
    $path = `pwd`;
    $path .= "/$file";
  }
  # add support for other operating systems
}
else {
  require Cwd;
  $path = Cwd::getcwd()."/$file";
}
print $path;

Please add any suggestions.

Spring Boot Program cannot find main class

Main class is configurable in pom.xml

<properties>
    <start-class>com.bt.collab.alu.api.webapp.Application</start-class>
</properties>

Open Sublime Text from Terminal in macOS

The following worked for me

open -a Sublime\ Text file_name.txt
open -a Sublime\ Text Folder_Path

You can use alias to make it event simple like

Add the following line in your

~/.bash_profile

alias sublime="open -a Sublime\ Text $@"

Then next time you can use following command to open files/folders

sublime file_name.txt
sublime Folder_Path

How to get the last char of a string in PHP?

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

How to read and write xml files?

Writing XML using JAXB (Java Architecture for XML Binding):

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
        e.printStackTrace();
          }

    }
}

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

So, I spent some time with this issue and found a solution. It is not pretty one, but at least a start point - maybe someone will supplement this with some useful comments.

Some info about mapping that I found in process:

  • Class that contains basic mapping of Hibernate types to property types is org.hibernate.type.TypeFactory. All this mappings are stored in unmodifiable map

    private static final Map BASIC_TYPES;
    ...
    basics.put( java.util.Date.class.getName(), Hibernate.TIMESTAMP );
    ...
    BASIC_TYPES = Collections.unmodifiableMap( basics );
    

As you can see with java.util.Date type assosited with Hibernate type org.hibernate.type.TimestampType

  • Next interesting moment - creation of Hibernate org.hibernate.cfg.Configuration - object that contains all info about mapped classes. This classes and their properties can be extracted like this:

    Iterator clsMappings = cfg.getClassMappings();
    while(clsMappings.hasNext()){
        PersistentClass mapping = (PersistentClass) clsMappings.next();
        handleProperties(mapping.getPropertyIterator(), map);
    }
    
  • Vast majority of properties are the objects of org.hibernate.mapping.SimpleValue types. Our point of interest is the method SimpleValue.getType() - in this method is defined what type will be used to convert properties values back-and-forth while working with DB

    Type result = TypeFactory.heuristicType(typeName, typeParameters);
    

At this point I understand that I am unable to modify BASIC_TYPES - so the only way - to replace SimpleValue object to the properties of java.util.Date types to my custom Object that will be able to know the exact type to convert.

The solution:

  • Create custom container entity manager factory by extending HibernatePersistence class and overriding its method createContainerEntityManagerFactory:

    public class HibernatePersistenceExtensions extends HibernatePersistence {
    
        @Override
        public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
    
            if ("true".equals(map.get("hibernate.use.custom.entity.manager.factory"))) {
                return CustomeEntityManagerFactoryFactory.createCustomEntityManagerFactory(info, map);
            } else {
                return super.createContainerEntityManagerFactory(info, map);
            }
        }
    }
    
  • Create Hibernate configuration object, modify value ojects for java.util.Date properties and then create custom entity manager factory.

    public class ReattachingEntityManagerFactoryFactory {
    
    
        @SuppressWarnings("rawtypes")
        public static EntityManagerFactory createContainerEntityManagerFactory(
        PersistenceUnitInfo info, Map map) {
            Ejb3Configuration cfg = new Ejb3Configuration();
    
            Ejb3Configuration configured = cfg.configure( info, map );
    
            handleClassMappings(cfg, map);
    
            return configured != null ? configured.buildEntityManagerFactory() : null;
        }
    
        @SuppressWarnings("rawtypes")
        private static void handleClassMappings(Ejb3Configuration cfg, Map map) {
            Iterator clsMappings = cfg.getClassMappings();
            while(clsMappings.hasNext()){
                 PersistentClass mapping = (PersistentClass) clsMappings.next();
                 handleProperties(mapping.getPropertyIterator(), map);
            }
        } 
    
    
    
        private static void handleProperties(Iterator props, Map map) {
    
            while(props.hasNext()){
                 Property prop = (Property) props.next();
                 Value value = prop.getValue();
                 if (value instanceof Component) {
                     Component c = (Component) value;
                     handleProperties(c.getPropertyIterator(), map);
                 } else {
    
                     handleReturnUtilDateInsteadOfTimestamp(prop, map);
    
                 }
             }
    
        private static void handleReturnUtilDateInsteadOfTimestamp(Property prop, Map map) {
            if ("true".equals(map.get("hibernate.return.date.instead.of.timestamp"))) {
                Value value = prop.getValue();
    
                if (value instanceof SimpleValue) {
                    SimpleValue simpleValue = (SimpleValue) value;
                    String typeName = simpleValue.getTypeName();
                    if ("java.util.Date".equals(typeName)) {
                        UtilDateSimpleValue udsv = new UtilDateSimpleValue(simpleValue);
                        prop.setValue(udsv);
                    }
                }
            }
        }
    
    }
    

As you can see I just iterate over every property and substitute SimpleValue-object for UtilDateSimpleValue for properties of type java.util.Date. This is very simple class - it implements the same interface as SimpleValue object, e.g org.hibernate.mapping.KeyValue. In constructor original SimpleValue object is passed - so every call to UtilDateSimpleValue is redirected to the original object with one exception - method getType(...) return my custom Type.

public class UtilDateSimpleValue implements KeyValue{

    private SimpleValue value;

    public UtilDateSimpleValue(SimpleValue value) {
        this.value = value;
    }

    public SimpleValue getValue() {
        return value;
    }

    @Override
    public int getColumnSpan() {
        return value.getColumnSpan();
    }

    ...

    @Override
    public Type getType() throws MappingException {
        final String typeName = value.getTypeName();

        if (typeName == null) {
                throw new MappingException("No type name");
        }

        Type result = new UtilDateUserType();

        return result;
    }
    ...
}
  • And the last step is implementation of UtilDateUserType. I just extend original org.hibernate.type.TimestampType and override its method get() like this:

    public class UtilDateUserType extends TimestampType{
    
        @Override
        public Object get(ResultSet rs, String name) throws SQLException {
            Timestamp ts = rs.getTimestamp(name);
    
            Date result = null;
            if(ts != null){
                result = new Date(ts.getTime());
            }
    
            return result;
        }
    }
    

That is all. A little bit tricky, but now every java.util.Date property is returned as java.util.Date without any additional modifications of existing code (annotations or modifying setters). As I find out in Hibernate 4 or above there is a much more easier way to substitute your own type (see details here: Hibernate TypeResolver). Any suggestions or criticism are welcome.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

As of iOS 11 this is publicly available in UITableViewDelegate. Here's some sample code:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                         title:@"DELETE"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of delete: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UIContextualAction *rename = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                         title:@"RENAME"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of rename: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UISwipeActionsConfiguration *swipeActionConfig = [UISwipeActionsConfiguration configurationWithActions:@[rename, delete]];
    swipeActionConfig.performsFirstActionWithFullSwipe = NO;

    return swipeActionConfig;
}

Also available:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath;

Docs: https://developer.apple.com/documentation/uikit/uitableviewdelegate/2902367-tableview?language=objc

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

How do you change the size of figures drawn with matplotlib?

USING plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

Conversion to cm

The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.

C# DateTime to "YYYYMMDDHHMMSS" format

An easy Method, Full control over 'from type' and 'to type', and only need to remember this code for future castings

DateTime.ParseExact(InputDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));

Select multiple records based on list of Id's with linq

Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:

_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);

And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set<>. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:

    private static void Main(string[] args)
    {
        var userProfiles = GenerateUserProfiles();
        var idList = GenerateIds();
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
        Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
        stopWatch.Restart();
        userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
        Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
        Console.ReadLine();
    }

    private static IEnumerable<int> GenerateIds()
    {
       // var result = new List<int>();
        for (int i = 100000; i > 0; i--)
        {
            yield return i;
        }
    }

    private static IEnumerable<UserProfile> GenerateUserProfiles()
    {
        for (int i = 0; i < 100000; i++)
        {
            yield return new UserProfile {ID = i};
        }
    }

Console output:

Elapsed .Join time: 00:00:00.0322546

Elapsed .Where .Contains time: 00:02:19.4072107

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

Open file dialog and select a file using WPF controls and C#

Something like that should be what you need

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 


    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();


    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;
    }
}

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]> which means a list of Object tables and not a list of Employee.

Object[0] refers an Employee entity 
Object[1] refers a Departement entity 

When you use fetch, there is just one select and the result is the list of Employee List<Employee> containing the list of departements. It overrides the lazy declaration of the entity.

Why is "except: pass" a bad programming practice?

The #1 reason has already been stated - it hides errors that you did not expect.

(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.

(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.

php variable in html no other way than: <?php echo $var; ?>

There are plenty of templating systems that offer more compact syntax for your views. Smarty is venerable and popular. This article lists 10 others.

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

Generate random array of floats between a range

Why not to combine random.uniform with a list comprehension?

>>> def random_floats(low, high, size):
...    return [random.uniform(low, high) for _ in xrange(size)]
... 
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]

Fixed footer in Bootstrap

You can do this by wrapping the page contents in a div with the following id styling applied:

<style>
#wrap {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -60px;
}
</style>

<div id="wrap">
    <!-- Your page content here... -->
</div>

Worked for me.

How to see query history in SQL Server Management Studio

The system doesn't record queries in that way. If you know you want to do that ahead of time though, you can use SQL Profiler to record what is coming in and track queries during the time Profiler is running.

PHP code is not being executed, instead code shows on the page

Try restarting the apache server. This was the mistake I had made - forgetting to restart the server after installing php!

service httpd restart

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

tSQL - Conversion from varchar to numeric works for all but integer

Try this

declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end

and

declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end

Android OnClickListener - identify a button

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

The accepted answer doesn't work if some package vendors it's own copy of urllib3, in which case this will still work:

import warnings

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

How to catch all exceptions in c# using try and catch?

Both ways are correct.

If you need to do something with the Exception object in the catch block then you should use

try {
    // code....
}
catch (Exception ex){}

and then use ex in the catch block.

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

Where does PHP's error log reside in XAMPP?

\xampp\apache\logs\error.log is the default location of error logs in php.

Find full path of the Python interpreter?

sys.executable contains full path of the currently running Python interpreter.

import sys

print(sys.executable)

which is now documented here

How do I add 24 hours to a unix timestamp in php?

You could use the DateTime class as well:

$timestamp = mktime(15, 30, 00, 3, 28, 2015);

$d = new DateTime();
$d->setTimestamp($timestamp);

Add a Period of 1 Day:

$d->add(new DateInterval('P1D'));
echo $d->format('c');

See DateInterval for more details.

angularjs ng-style: background-image isn't working

Just for the records you can also define your object in the controller like this:

this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };

and then you can define a function to change the property of the object directly:

this.changeBackgroundImage = function (){
        this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
    }

Doing it in that way you can modify dinamicaly your style.

How to write a PHP ternary operator

PHP 8 (Left-associative ternary operator change)

Left-associative ternary operator deprecation https://wiki.php.net/rfc/ternary_associativity. The ternary operator has some weird quirks in PHP. This RFC adds a deprecation warning for nested ternary statements. In PHP 8, this deprecation will be converted to a compile time error.

1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok

source: https://stitcher.io/blog/new-in-php-74#numeric-literal-separator-rfc

Get custom product attributes in Woocommerce

You can get the single value for the attribute with below code:

$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

How do I echo and send console output to a file in a bat script?

I made a simple C# console which can handle real-time output to both cmd screen and log

class Tee
{
    static int Main(string[] args)
    {
        try
        {
            string logFilePath = Path.GetFullPath(args[0]);

            using (StreamWriter writer = new StreamWriter(logFilePath, true))
            {
                for (int value; (value = Console.In.Read()) != -1;)
                {
                    var word = Char.ConvertFromUtf32(value);
                    Console.Write(word);
                    writer.Write(word);
                }
            }
        }
        catch (Exception)
        {
            return 1;
        }
        return 0;
    }
}

The batch file usage is the same as how you use Unix tee

foo | tee xxx.log

And here is the repository which includes the Tee.exe in case you don't have tool to compile https://github.com/iamshiao/Tee

LINQ extension methods - Any() vs. Where() vs. Exists()

Where returns a new sequence of items matching the predicate.

Any returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).

I'm not sure about Exists - it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any? (There's an Exists method in List<T> which is similar to Any(predicate) but that predates LINQ.)

Use custom build output folder when using create-react-app

Edit your package.json:

"build": "react-scripts build && mv build webapp"

REACT - toggle class onclick

using React you can add toggle class to any id/element, try

style.css

.hide-text{
    display: none !important;
    /* transition: 2s all ease-in 0.9s; */
  }
.left-menu-main-link{
    transition: all ease-in 0.4s;
}
.leftbar-open{
    width: 240px;
    min-width: 240px;
    /* transition: all ease-in 0.4s; */
}
.leftbar-close{
    width: 88px;
    min-width:88px;
    transition: all ease-in 0.4s;
}

fileName.js

......
    ToggleMenu=()=>{
             this.setState({
                isActive: !this.state.isActive
              })
              console.log(this.state.isActive)
        }
        render() {
            return (
                <div className={this.state.isActive===true ? "left-panel leftbar-open" : "left-panel leftbar-close"} id="leftPanel">
                    <div className="top-logo-container"  onClick={this.ToggleMenu}>
                            <span className={this.state.isActive===true ? "left-menu-main-link hide-from-menu" : "hide-text"}>Welcome!</span>
                    </div>

                    <div className="welcome-member">
                        <span className={this.state.isActive===true ? "left-menu-main-link hide-from-menu" : "hide-text"}>Welcome<br/>SDO Rizwan</span>
                    </div>
    )
    }
......

How to trigger click on page load?

try this,

$("document").ready(function(){

$("your id here").trigger("click");
});

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

What does android:layout_weight mean?

one of the best explanations for me was this one (from the Android tutorial, look for step 7):

layout_weight is used in LinearLayouts to assign "importance" to Views within the layout. All Views have a default layout_weight of zero, meaning they take up only as much room on the screen as they need to be displayed. Assigning a value higher than zero will split up the rest of the available space in the parent View, according to the value of each View's layout_weight and its ratio to the overall layout_weight specified in the current layout for this and other View elements.

To give an example: let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important). If the first one has a layout_weight of 1 and the second has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).

How to sort a HashSet?

You can use a TreeSet instead.

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

AngularJS ngClass conditional

I am going to show you two methods by which you can dynamically apply ng-class

Step-1

By using ternary operator

<div ng-class="condition?'class1':'class2'"></div>

Output

If your condition is true then class1 will be applied to your element else class2 will be applied.

Disadvantage

When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.

Step-2

<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>

Output

if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.

Hope this will help you.

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

How to remove &quot; from my Json in javascript?

The following works for me:

function decodeHtml(html) {
    let areaElement = document.createElement("textarea");
    areaElement.innerHTML = html;

    return areaElement.value;
}

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

Pandas - Compute z-score for all columns

The almost one-liner solution:

df2 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std()
df2['ID'] = df['ID']

Adding to a vector of pair

Or you can use initialize list:

revenue.push_back({"string", map[i].second});

Print PHP Call Stack

See debug_print_backtrace. I guess you can call flush afterwards if you want.

Android Fragment no view found for ID?

I encountered this problem when I tried to replace view with my fragment in onCreateView(). Like this:

public class MyProjectListFrag extends Fragment {


    private MyProjectListFragment myProjectListFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();
    }

It told me

11-25 14:06:04.848: E/AndroidRuntime(26040): java.lang.IllegalArgumentException: No view found for id 0x7f05003f (com.example.myays:id/container_for_my_pro_list) for fragment MyProjectListFragment{41692f40 #2 id=0x7f05003f myProjectListFragment}

Then I fixed this issue with putting replace into onActivityCreated(). Like this:

public class MyProjectListFrag extends Fragment {

    private final static String TAG = "lch";

    private MyProjectListFragment myProjectListFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater
                .inflate(R.layout.frag_my_project_list, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();

    }
  1. You have to return a view in onCreateView() so that you can replace it later
  2. You can put any operation towards this view in the following function in fragment liftcycle, like onActivityCreated()

Hope this helps!

How to find out what the date was 5 days ago?

Try this

$date = date("Y-m-d", strtotime("-5 day"));

What is the difference between fastcgi and fpm?

FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.

Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).

Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.

count number of rows in a data frame in R based on group

Here is another way of using aggregate to count rows by group:

my.data <- read.table(text = '
    month.year    my.cov
      Jan.2000     apple
      Jan.2000      pear
      Jan.2000     peach
      Jan.2001     apple
      Jan.2001     peach
      Feb.2002      pear
', header = TRUE, stringsAsFactors = FALSE, na.strings = NA)

rows.per.group  <- aggregate(rep(1, length(my.data$month.year)),
                             by=list(my.data$month.year), sum)
rows.per.group

#    Group.1 x
# 1 Feb.2002 1
# 2 Jan.2000 3
# 3 Jan.2001 2

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

Alter a MySQL column to be AUTO_INCREMENT

You can do it like this:

 alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;

Cannot resolve symbol 'AppCompatActivity'

If Invalidating caches not helps, just close the project then re-open it. Steps:

  • File > Close Project
  • Remove the project out of the starting project list
  • Close Android Studio
  • Open Android Studio
  • Open existed Project with this project

Mac install and open mysql using terminal

In MacOS, Mysql's executable file is located in /usr/local/mysql/bin/mysql and you can easily login to it with the following command:

/usr/local/mysql/bin/mysql -u USERNAME -p

But this is a very long command and very boring, so you can add mysql path to Os's Environment variable and access to it much easier.

For macOS Catalina and later

Starting with macOS Catalina, Mac devices use zsh as the default login shell and interactive shell and you have to update .zprofile file in your home directory.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofile
source ~/.zprofile
mysql -u USERNAME -p

For macOS Mojave and earlier

Although you can always switch to zsh, bash is the default shell in macOS Mojave and earlier and with bash you have to update .bash_profile file.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.bash_profile
source ~/.bash_profile
mysql -u USERNAME -p

How to get the Android device's primary e-mail address

Sadly accepted answer isn't working.

I'm late, but here's the solution for internal Android Email application unless the content uri is changed by provider:

Uri EMAIL_ACCOUNTS_DATABASE_CONTENT_URI = 
              Uri.parse("content://com.android.email.provider/account");

public ArrayList<String> GET_EMAIL_ADDRESSES ()
{
    ArrayList<String> names = new ArrayList<String>();
    ContentResolver cr      = m_context.getContentResolver();
    Cursor cursor           = cr.query(EMAIL_ACCOUNTS_DATABASE_CONTENT_URI ,null, 
                             null, null, null);

    if (cursor == null) {
        Log.e("TEST", "Cannot access email accounts database");
        return null;
    }

    if (cursor.getCount() <= 0) {
        Log.e("TEST", "No accounts");
        return null;
    }

    while (cursor.moveToNext()) {
        names.add(cursor.getString(cursor.getColumnIndex("emailAddress")));
        Log.i("TEST", cursor.getString(cursor.getColumnIndex("emailAddress")));
    }
    return names;
}

What does map(&:name) mean in Ruby?

It basically execute the method call tag.name on each tags in the array.

It is a simplified ruby shorthand.

PHP - check if variable is undefined

You can use -

$isTouch = isset($variable);

It will return true if the $variable is defined. if the variable is not defined it will return false.

Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

If you want to check for false, 0 etc You can then use empty() -

$isTouch = empty($variable);

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

How To: Best way to draw table in console app (C#)

public static void ToPrintConsole(this DataTable dataTable)
    {
        // Print top line
        Console.WriteLine(new string('-', 75));

        // Print col headers
        var colHeaders = dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName);
        foreach (String s in colHeaders)
        {
            Console.Write("| {0,-20}", s);
        }
        Console.WriteLine();

        // Print line below col headers
        Console.WriteLine(new string('-', 75));

        // Print rows
        foreach (DataRow row in dataTable.Rows)
        {
            foreach (Object o in row.ItemArray)
            {
                Console.Write("| {0,-20}", o.ToString());
            }
            Console.WriteLine();
        }

        // Print bottom line
        Console.WriteLine(new string('-', 75));
    }

Getting an element from a Set

you can use Iterator class

import java.util.Iterator;
import java.util.HashSet;

public class MyClass {
 public static void main(String[ ] args) {
 HashSet<String> animals = new HashSet<String>();
animals.add("fox");
animals.add("cat");
animals.add("dog");
animals.add("rabbit");

Iterator<String> it = animals.iterator();
while(it.hasNext()) {
  String value = it.next();
  System.out.println(value);   
 }
 }
}

jQuery events .load(), .ready(), .unload()

NOTE: .load() & .unload() have been deprecated


$(window).load();

Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.

$(document).ready();

This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.

$(window).unload();

This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.

To sum up, ready() will be fired before load(), and unload() will be the last to be fired.

How to right align widget in horizontal linear layout Android?

setting the view's layout_weight="1" would do the trick.!

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

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

How to convert a Drawable to a Bitmap?

 // get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);

    if (requestCode == 1) {
        if (intent != null && resultcode == RESULT_OK) {             
            Uri selectedImage = intent.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);

            //display image using BitmapFactory

            cursor.close(); bmp = BitmapFactory.decodeFile(filepath); 
            iv.setBackgroundResource(0);
            iv.setImageBitmap(bmp);
        }
    }
}

Produce a random number in a range using C#

Try below code.

Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51

Already defined in .obj - no double inclusions

You probably don't want to do this:

#include "client.cpp"

A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.

Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS, however, each file that has #include "client.cpp" is built independently and as such will find SOCKET_CLIENT_CLASS not yet defined. Therefore it's contents will be included, not #ifdef'd out.

If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

Is there an auto increment in sqlite?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below: Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

How to add two strings as if they were numbers?

If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:

function addStrings(str1, str2){
  str1a = str1.split('').reverse();
  str2a = str2.split('').reverse();
  let output = '';
  let longer = Math.max(str1.length, str2.length);
  let carry = false;
  for (let i = 0; i < longer; i++) {
    let result
    if (str1a[i] && str2a[i]) {
      result = parseInt(str1a[i]) + parseInt(str2a[i]);

    } else if (str1a[i] && !str2a[i]) {
      result = parseInt(str1a[i]);

    } else if (!str1a[i] && str2a[i]) {
      result = parseInt(str2a[i]);
    }

    if (carry) {
        result += 1;
        carry = false;
    }
    if(result >= 10) {
      carry = true;
      output += result.toString()[1];
    }else {
      output += result.toString();
    }
  }
  output = output.split('').reverse().join('');

  if(carry) {
    output = '1' + output;
  }
  return output;
}

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

JQuery window scrolling event?

See jQuery.scroll(). You can bind this to the window element to get your desired event hook.

On scroll, then simply check your scroll position:

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop();
  if ( scrollTop > $(headerElem).offset().top ) { 
    // display add
  }
});

Change Volley timeout duration

Alternative solution if all above solutions are not working for you

By default, Volley set timeout equally for both setConnectionTimeout() and setReadTimeout() with the value from RetryPolicy. In my case, Volley throws timeout exception for large data chunk see:

com.android.volley.toolbox.HurlStack.openConnection(). 

My solution is create a class which extends HttpStack with my own setReadTimeout() policy. Then use it when creates RequestQueue as follow:

Volley.newRequestQueue(mContext.getApplicationContext(), new MyHurlStack())

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

How to store directory files listing into an array?

Running any shell command inside $(...) will help to store the output in a variable. So using that we can convert the files to array with IFS.

IFS=' ' read -r -a array <<< $(ls /path/to/dir)

Escaping double quotes in JavaScript onClick event handler

Did you try

&quot; or \x22

instead of

\"

?

Detect application heap size in Android

There are two ways to think about your phrase "application heap size available":

  1. How much heap can my app use before a hard error is triggered? And

  2. How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?

There is a different method for determining each of the above.

For item 1 above: maxMemory()

which can be invoked (e.g., in your main activity's onCreate() method) as follows:

Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

This method tells you how many total bytes of heap your app is allowed to use.

For item 2 above: getMemoryClass()

which can be invoked as follows:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));

This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop() / onResume() cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.

This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.

For a stock version of Android, maxMemory() will typically return about the same number of megabytes as are indicated in getMemoryClass() (i.e., approximately a million times the latter value).

The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".

NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.

Here are my test results showing the values returned by maxMemory() and getMemoryClass() for four different devices running CyanogenMod, using two different (manually-set) heap values for each:

  • G1:
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 16
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 16
  • Moto Droid:
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 24
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 24
  • Nexus One:
    • With VM Heap size set to 32MB:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 32
  • Viewsonic GTab:
    • With VM Heap Size set to 32:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap Size set to 64:
      • maxMemory: 67108864
      • getMemoryClass: 32

In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.

For that device, here are the results:

  • Novo7
    • maxMemory: 62914560
    • getMemoryClass: 60

Also (per Kishore in a comment below):

  • HTC One X
    • maxMemory: 67108864
    • getMemoryClass: 64

And (per akauppi's comment):

  • Samsung Galaxy Core Plus
    • maxMemory: (Not specified in comment)
    • getMemoryClass: 48
    • largeMemoryClass: 128

Per a comment from cmcromance:

  • Galaxy S3 (Jelly Bean) large heap
    • maxMemory: 268435456
    • getMemoryClass: 64

And (per tencent's comments):

  • LG Nexus 5 (4.4.3) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • LG Nexus 5 (4.4.3) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192
  • Galaxy Nexus (4.3) normal
    • maxMemory: 100663296
    • getMemoryClass: 96
  • Galaxy Nexus (4.3) large heap
    • maxMemory: 268435456
    • getMemoryClass: 96
  • Galaxy S4 Play Store Edition (4.4.2) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • Galaxy S4 Play Store Edition (4.4.2) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192

Other Devices

  • Huawei Nexus 6P (6.0.1) normal
    • maxMemory: 201326592
    • getMemoryClass: 192

I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.

My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory() while leaving getMemoryClass() alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."

If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).

Note that the memory class apparently need not be a multiple of 8MB.

We can see from the above that the getMemoryClass() result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.

My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.

So, you cannot go over the amount of memory specified by maxMemory(). And, you should try to stay within the limits specified by getMemoryClass(). One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.

Finally, if you do plan to go over the number of megabytes specified in getMemoryClass(), my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop() / onResume() cycle occurs.

In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.

But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory() is telling you that you can go much higher than the 16MB that getMemoryClass() is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop() / onResume() works seamlessly.

getMemoryClass(), as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.

By contrast, maxMemory(), according to the documentation, is available all the way back to API level 1. maxMemory(), on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory() value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory() indicates is allowed.