Programs & Examples On #Active script

The Active Script rule format provides a mechanism that allows business rules to be implemented using a range of procedural programming languages that support the ActiveX scripting engine standard.

For files in directory, only echo filename (no path)

Just use basename:

echo `basename "$filename"`

The quotes are needed in case $filename contains e.g. spaces.

Change select box option background color

Another option is to use Javascript:

if (document.getElementById('selectID').value == '1') {
       document.getElementById('optionID').style.color = '#000';

(Not as clean as the CSS attribute selector, but more powerful)

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

Aborting a shell script if any command returns a non-zero value

I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

Which is the same as cmd || exit errcode as someone showed.

For example, I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

Cross-browser window resize event - JavaScript / jQuery

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

$rootScope.$broadcast vs. $scope.$emit

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

Difference in months between two dates

Public Class ClassDateOperation
    Private prop_DifferenceInDay As Integer
    Private prop_DifferenceInMonth As Integer
    Private prop_DifferenceInYear As Integer


    Public Function DayMonthYearFromTwoDate(ByVal DateStart As Date, ByVal DateEnd As Date) As ClassDateOperation
        Dim differenceInDay As Integer
        Dim differenceInMonth As Integer
        Dim differenceInYear As Integer
        Dim myDate As Date

        DateEnd = DateEnd.AddDays(1)

        differenceInYear = DateEnd.Year - DateStart.Year

        If DateStart.Month <= DateEnd.Month Then
            differenceInMonth = DateEnd.Month - DateStart.Month
        Else
            differenceInYear -= 1
            differenceInMonth = (12 - DateStart.Month) + DateEnd.Month
        End If


        If DateStart.Day <= DateEnd.Day Then
            differenceInDay = DateEnd.Day - DateStart.Day
        Else

            myDate = CDate("01/" & DateStart.AddMonths(1).Month & "/" & DateStart.Year).AddDays(-1)
            If differenceInMonth <> 0 Then
                differenceInMonth -= 1
            Else
                differenceInMonth = 11
                differenceInYear -= 1
            End If

            differenceInDay = myDate.Day - DateStart.Day + DateEnd.Day

        End If

        prop_DifferenceInDay = differenceInDay
        prop_DifferenceInMonth = differenceInMonth
        prop_DifferenceInYear = differenceInYear

        Return Me
    End Function

    Public ReadOnly Property DifferenceInDay() As Integer
        Get
            Return prop_DifferenceInDay
        End Get
    End Property

    Public ReadOnly Property DifferenceInMonth As Integer
        Get
            Return prop_DifferenceInMonth
        End Get
    End Property

    Public ReadOnly Property DifferenceInYear As Integer
        Get
            Return prop_DifferenceInYear
        End Get
    End Property

End Class

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Fix the looming 2002 socket error – which is linking where MySQL places the socket and where OSX thinks it should be, MySQL puts it in /tmp and OSX looks for it in /var/mysql the socket is a type of file that allows mysql client/server communication.

sudo mkdir /var/mysql

and then

sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

source: http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/

How to set column widths to a jQuery datatable?

by using css we can easily add width to the column.

here im adding first column width to 300px on header (thead)

_x000D_
_x000D_
::ng-deep  table thead tr:last-child th:nth-child(1) {_x000D_
    width: 300px!important;_x000D_
}
_x000D_
_x000D_
_x000D_

now add same width to tbody first column by,

_x000D_
_x000D_
  <table datatable class="display table ">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th class="text-left" style="width: 300px!important;">name</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
           _x000D_
            <tr>_x000D_
                <td class="text-left" style="width: 300px!important;">jhon mathew</td>_x000D_
                _x000D_
            </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
       
_x000D_
_x000D_
_x000D_

by this way you can easily change width by changing the order of nth child. if you want 3 column then ,add nth-child(3)

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Can I add background color only for padding?

This would be a proper CSS solution which works for IE8/9 as well (IE8 with html5shiv ofcourse): codepen

nav {
  margin:0px auto;
  height:50px;
  background-color:gray;
  padding:10px;
  border:2px solid red;
  position: relative;
  color: white;
  z-index: 1;
}

nav:after {
  content: '';
  background: black;
  display: block;
  position: absolute;
  margin: 10px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1;
}

See full command of running/stopped container in Docker

Use runlike from git repository https://github.com/lavie/runlike

To install runlike

pip install runlike

As it accept container id as an argument so to extract container id use following command

docker ps -a -q

You are good to use runlike to extract complete docker run command with following command

runlike <docker container ID>

Where does Vagrant download its .box files to?

In addition to

Mac:
~/.vagrant.d/

Windows:
C:\Users\%userprofile%\.vagrant.d\boxes

You have to delete the files in VirtualBox/OtherVMprovider to make a clean start.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-many

The one-to-many table relationship looks as follows:

One-to-many

In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.

In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_comment
ADD CONSTRAINT
    fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post

One-to-one

The one-to-one table relationship looks as follows:

One-to-one

In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.

Therefore, we can say that the child table shares the Primary Key with the parent table.

In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_details
ADD CONSTRAINT
    fk_post_details_id
FOREIGN KEY (id) REFERENCES post

Many-to-many

The many-to-many table relationship looks as follows:

Many-to-many

In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.

In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post

And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag

Calling dynamic function with dynamic number of parameters

Couldn't you just pass the arguments array along?

function mainfunc (func){
    // remove the first argument containing the function name
    arguments.shift();
    window[func].apply(null, arguments);
}

function calledfunc1(args){
    // Do stuff here
}

function calledfunc2(args){
    // Do stuff here
}

mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');

How to animate CSS Translate

You need set the keyframes animation in you CSS. And use the keyframe with jQuery:

_x000D_
_x000D_
$('#myTest').css({"animation":"my-animation 2s infinite"});
_x000D_
#myTest {_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
@keyframes my-animation {_x000D_
  0% {_x000D_
    background: red;  _x000D_
  }_x000D_
  50% {_x000D_
    background: blue;  _x000D_
  }_x000D_
  100% {_x000D_
    background: green;  _x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myTest"></div>
_x000D_
_x000D_
_x000D_

How to enable mod_rewrite for Apache 2.2

Try setting: AllowOverride All.


Second most common issue is not having mod rewrite enabled: a2enmod rewrite and then restart apache.

How to get substring from string in c#?

Riya,

Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:

// add @ to the string to allow split over multiple lines 
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance. 
            The substring starts at a specified character position. great";

// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
    .Where(x => x.Length > 0).Select(x => x.Trim());

// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
    Console.WriteLine(subword);
}

enjoy...

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Understanding string reversal via slicing

the first two bounds default to 0 and the length of the sequence, as before, and a stride of -1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.

name="ravi"
print(name[::-1]) #ivar

How do you find the first key in a dictionary?

easiest way is:

first_key = my_dict.keys()[0]

but some times you should be more careful and assure that your entity is a valuable list so:

first_key = list(my_dict.keys())[0]

git pull fails "unable to resolve reference" "unable to update local ref"

I just would like to add how it may happen that a reference breaks.

Possible root cause

On my system (Windows 7 64-bit), when a BSOD happens, some of the stored reference files (most likely currently opened/being written into when BSOD happened) are overwritten with NULL characters (ASCII 0).

As others mentioned, to fix it, it's enough to just delete those invalid reference files and re-fetch or re-pull the repository.

Example

Error: cannot lock ref 'refs/remotes/origin/some/branch': unable to resolve reference 'refs/remotes/origin/some/branch': reference broken

Solution: delete the file %repo_root%/.git/refs/remotes/origin/some/branch

File path issues in R using Windows ("Hex digits in character string" error)

Replace back slashes \ with forward slashes / when running windows machine

jQuery Ajax PUT with parameters

Use:

$.ajax({
    url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
        console.log(data);
    }
});

Always remember to use _METHOD=PUT.

How to convert all tables in database to one collation?

If you're using PhpMyAdmin, you can now:

  1. Select the database.
  2. Click the "Operations" tab.
  3. Under "Collation" section, select the desired collation.
  4. Click the "Change all tables collations" checkbox.
  5. A new "Change all tables columns collations" checkbox will appear.
  6. Click the "Change all tables columns collations" checkbox.
  7. Click the "Go" button.

I had over 250 tables to convert. It took a little over 5 minutes.

How to deploy correctly when using Composer's develop / production switch?

Actually, I would highly recommend AGAINST installing dependencies on the production server.

My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.

Why?

  • on shared hosting, you might not be able to get to a command line
  • even if you did, PHP might be restricted there in terms of commands, memory or network access
  • repository CLI tools (Git, Svn) are likely to not be installed, which would fail if your lock file has recorded a dependency to checkout a certain commit instead of downloading that commit as ZIP (you used --prefer-source, or Composer had no other way to get that version)
  • if your production machine is more like a small test server (think Amazon EC2 micro instance) there is probably not even enough memory installed to execute composer install
  • while composer tries to no break things, how do you feel about ending with a partially broken production website because some random dependency could not be loaded during Composers install phase

Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.

What's the correct way to deploy this without installing the -dev dependencies?

The command to use is

composer install --no-dev

This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.

The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.

If you don't mind deploying development software components on a production server, running composer install would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.

How to check if an element is in an array

what about using a hash table for the job, like this?

first, creating a "hash map" generic function, extending the Sequence protocol.

extension Sequence where Element: Hashable {

    func hashMap() -> [Element: Int] {
        var dict: [Element: Int] = [:]
        for (i, value) in self.enumerated() {
            dict[value] = i
        }
        return dict
    }
}

This extension will work as long as the items in the array conform to Hashable, like integers or strings, here is the usage...

let numbers = Array(0...50) 
let hashMappedNumbers = numbers.hashMap()

let numToDetect = 35

let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!

print(indexOfnumToDetect) // prints 35

But for now, let's just focus in check if the element is in the array.

let numExists = indexOfnumToDetect != nil // if the key does not exist 
means the number is not contained in the collection.

print(numExists) // prints true

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

How do I install the ext-curl extension with PHP 7?

If you are using PHP7.1 ( try php -version to find your PHP version)

sudo apt-get install php7.1-curl

then restart apache

sudo service apache2 restart

How to fully delete a git repository created with init?

I tried:

rm -rf .git and also

Git keeps all of its files in the .git directory. Just remove that one and init again.

Neither worked for me. Here's what did:

  • Delete all files except for .git
  • git add . -A
  • git commit -m "deleted entire project"
  • git push

Then create / restore the project from backup:

  • Create new project files (or copy paste a backup)
  • git add . -A
  • git commit -m "recreated project"
  • git push

Swing/Java: How to use the getText and setText string properly

in your action performed method, call:

label1.setText(nameField.getText());

This way, when the button is clicked, label will be updated to the nameField text.

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I think you can also execute the pwd() function on the particular node:

node {
    def PWD = pwd();
    ...
}

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

Difference between [routerLink] and routerLink

You'll see this in all the directives:

When you use brackets, it means you're passing a bindable property (a variable).

  <a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!

But with variables, you have the opportunity to make it dynamic right?

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!


    updateRouterLinkVariable(){

        this.routerLinkVariable = '/about';
    }

Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.

<a routerLink="/home"></a>

UPDATE :

The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:

So adding a new variable

export class myComponent {
        private dynamicParameter = '129';
        public routerLinkVariable = "/home"; 

Updating the [routerLink]

  <a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>

When you want to click on this link, it would become:

  <a href="/home/129"></a>

Where can I find the error logs of nginx, using FastCGI and Django?

Errors are stored in the nginx log file. You can specify it in the root of the nginx configuration file:

error_log  /var/log/nginx/nginx_error.log  warn;

On Mac OS X with Homebrew, the log file was found by default at the following location:

/usr/local/var/log/nginx

T-sql - determine if value is integer

Use PATINDEX

DECLARE @input VARCHAR(10)='102030.40'
SELECT PATINDEX('%[^0-9]%',RTRIM(LTRIM(@input))) AS IsNumber

reference http://www.intellectsql.com/post-how-to-check-if-the-input-is-numeric/

A fast way to delete all rows of a datatable at once

Just use dt.Clear()

Also you can set your TableAdapter/DataAdapter to clear before it fills with data.

$(window).width() not the same as media query

Use

window.innerWidth

This solved my problem

Why does an onclick property set with setAttribute fail to work in IE?

Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).

Determine version of Entity Framework I am using?

If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.

Get first and last day of month using threeten, LocalDate

You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:

    LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
    LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
    System.out.println("Start of month: " + start);
    System.out.println("End of month: " + end);

Result:

>     Start of month: 2019-12-01
>     End of month: 2019-12-30

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:

1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)

2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array

<?php /*

 $lang = array (
  'english' => 'English',

  'arabic' => 'Arabic',  // i add this here

  'spanish' => 'Español'

Now save and run the application. It's worked fine.

Convert one date format into another in PHP

To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime I go like this:

$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');

Use string.Contains() with switch()

You can do the check at first and then use the switch as you like.

For example:

string str = "parameter"; // test1..test2..test3....

if (!message.Contains(str)) return ;

Then

switch(str)
{
  case "test1" : {} break;
  case "test2" : {} break;
  default : {} break;
}

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

How to scroll up or down the page to an anchor using jQuery?

function scroll_to_anchor(anchor_id){
    var tag = $("#"+anchor_id+"");
    $('html,body').animate({scrollTop: tag.offset().top},'slow');
}

Find records from one table which don't exist in another

SELECT t1.ColumnID,
CASE 
    WHEN NOT EXISTS( SELECT t2.FieldText  
                     FROM Table t2 
                     WHERE t2.ColumnID = t1.ColumnID) 
    THEN t1.FieldText
    ELSE t2.FieldText
END FieldText       
FROM Table1 t1, Table2 t2

Is there a way to specify a default property value in Spring XML?

http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  <property name="location"><value>my_config.properties</value></property>  
  <property name="properties">  
    <props>  
      <prop key="entry.1">123</prop>  
    </props>  
  </property>  
</bean> 

git: patch does not apply

git apply --reverse --reject example.patch

When you created a patch file with the branch names reversed:

ie. git diff feature_branch..master instead of git diff master..feature_branch

How can I permanently enable line numbers in IntelliJ?

NOT a solution, rather a TEMPORARY solution which only works only for the current editor and current session:

Simply right click on the place where the line-numbers should be, and there you'll see a small menu.

then, mark the "Show Line Numbers" option.

enter image description here

Please note that this only works on a per-file basis, however. Enjoy.

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

How to remove "onclick" with JQuery?

Removing onclick property

Suppose you added your click event inline, like this :

<button id="myButton" onclick="alert('test')">Married</button>

Then, you can remove the event like this :

$("#myButton").prop('onclick', null); // Removes 'onclick' property if found

Removing click event listeners

Suppose you added your click event by defining an event listener, like this :

$("button").on("click", function() { alert("clicked!"); });

... or like this:

$("button").click(function() { alert("clicked!"); });

Then, you can remove the event like this :

$("#myButton").off('click');          // Removes other events if found

Removing both

If you're uncertain how your event has been added, you can combine both, like this :

$("#myButton").prop('onclick', null)  // Removes 'onclick' property if found
              .off('click');          // Removes other events if found

How to disable/enable select field using jQuery?

Good question - I think the only way to achieve this is to filter the items in the select.
You can do this through a jquery plugin. Check the following link, it describes how to achieve something similar to what you need. Thanks
jQuery disable SELECT options based on Radio selected (Need support for all browsers)

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me the solution was one of the methods had to be void, I had it as Boolean.

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Use jQuery to change a second select list based on the first select list option

I built on sabithpocker's idea and made a more generalized version that lets you control more than one selectbox from a given trigger.

I assigned the selectboxes I wanted to be controlled the classname "switchable," and cloned them all like this:

$j(this).data('options',$j('select.switchable option').clone());

and used a specific naming convention for the switchable selects, which could also translate into classes. In my case, "category" and "issuer" were the select names, and "category_2" and "issuer_1" the class names.

Then I ran an $.each on the select.switchable groups, after making a copy of $(this) for use inside the function:

var that = this;
$j("select.switchable").each(function() { 
    var thisname = $j(this).attr('name');
    var theseoptions = $j(that).data('options').filter( '.' + thisname + '_' + id );
    $j(this).html(theseoptions);
});     

By using a classname on the ones you want to control, the function will safely ignore other selects elsewhere on the page (such as the last one in the example on Fiddle).

Here's a Fiddle with the complete code:

Difference Between One-to-Many, Many-to-One and Many-to-Many?

this would probably call for a many-to-many relation ship as follows



public class Person{

    private Long personId;
    @manytomany

    private Set skills;
    //Getters and setters
}

public class Skill{
    private Long skillId;
    private String skillName;
    @manyToMany(MappedBy="skills,targetClass="Person")
    private Set persons; // (people would not be a good convenion)
    //Getters and setters
}

you may need to define a joinTable + JoinColumn but it will possible work also without...

How to get MD5 sum of a string using python?

You can use b character in front of a string literal:

import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())

Out:

e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548

System.BadImageFormatException An attempt was made to load a program with an incorrect format

i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem

How to mark-up phone numbers?

As one would expect, WebKit's support of tel: extends to the Android mobile browser as well - FYI

Case-insensitive search in Rails model

Similar to Andrews which is #1:

Something that worked for me is:

name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)

This eliminates the need to do a #where and #first in the same query. Hope this helps!

Import error: No module name urllib2

In python 3, to get text output:

import io
import urllib.request

response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)

AngularJS check if form is valid in controller

I have updated the controller to:

.controller('BusinessCtrl',
    function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
        $scope.$watch('createBusinessForm.$valid', function(newVal) {
            //$scope.valid = newVal;
            $scope.informationStatus = true;
        });
        ...

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

Proper Linq where clauses

Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider of Collection, this might be optimized away or not.

When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.

When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

How to exit from ForEach-Object in PowerShell

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup 
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

This is how I was able to solve the problem when I faced it

  1. Start SQL Management Studio.
  2. Expand the Server Node (in the 'Object Explorer').
  3. Expand the Databases Node and then expand the specific Database which you are trying to access using the specific user.
  4. Expand the Users node under the Security node for the database.
  5. Right click the specific user and click 'properties'. You will get a dialog box.
  6. Make sure the user is a member of the db_owner group (please read the comments below before you use go this path) and other required changes using the view. (I used this for 2016. Not sure how the specific dialog look like in other version and hence not being specific)

PackagesNotFoundError: The following packages are not available from current channels:

Conda itself provides a quite detailed guidance about installing non-conda packages. Details can be found here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html

The basic idea is to use conda-forge. If it doesn't work, activate the environment and use pip.

Git: Could not resolve host github.com error while cloning remote repository in git

192.30.252.128 is the current IP of github.com which can be set in your local DNS (/etc/hosts in Linux and C:\Windows\System32\drivers\etc\hosts)

How to import a class from default package

Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

How to loop and render elements in React.js without an array of objects to map?

Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

How to read a text file directly from Internet using Java?

I did that in the following way for an image, you should be able to do it for text using similar steps.

// folder & name of image on PC          
File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 

Boolean testB = fileObj.createNewFile();

System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);

// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
InputStream webIS = url.openStream();

FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
    c = webIS.read();
    System.out.println("==============> " + c);
    if (c !=-1) {
        fo.write((byte) c);
    }
} while(c != -1);

webIS.close();
fo.close();

SQL ROWNUM how to return rows between a specific range

select * 
from emp 
where rownum <= &upperlimit 
minus 
select * 
from emp 
where rownum <= &lower limit ;

How do you update a DateTime field in T-SQL?

UPDATE TABLE
   SET EndDate = CAST('2017-12-31' AS DATE)
 WHERE Id = '123'

Clearing a string buffer/builder after loop

StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();

i think this code is faster.

Deserialize JSON into C# dynamic object?

Use DataSet(C#) with JavaScript. A simple function for creating a JSON stream with DataSet input. Create JSON content like (multi table dataset):

[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]

Just client side, use eval. For example,

var d = eval('[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]')

Then use:

d[0][0].a // out 1 from table 0 row 0

d[1][1].b // out 59 from table 1 row 1

// Created by Behnam Mohammadi And Saeed Ahmadian
public string jsonMini(DataSet ds)
{
    int t = 0, r = 0, c = 0;
    string stream = "[";

    for (t = 0; t < ds.Tables.Count; t++)
    {
        stream += "[";
        for (r = 0; r < ds.Tables[t].Rows.Count; r++)
        {
            stream += "{";
            for (c = 0; c < ds.Tables[t].Columns.Count; c++)
            {
                stream += ds.Tables[t].Columns[c].ToString() + ":'" +
                          ds.Tables[t].Rows[r][c].ToString() + "',";
            }
            if (c>0)
                stream = stream.Substring(0, stream.Length - 1);
            stream += "},";
        }
        if (r>0)
            stream = stream.Substring(0, stream.Length - 1);
        stream += "],";
    }
    if (t>0)
        stream = stream.Substring(0, stream.Length - 1);
    stream += "];";
    return stream;
}

How to get the real and total length of char * (char array)?

This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0' and then using strlen() ? This would give you your so-called real value since it would stop counting at the first '\0' it encounters.

Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.

Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:

Use component from another module

You have to export it from your NgModule:

@NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule],
  providers: []
})
export class TaskModule{}

Practical uses of different data structures

As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.

Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.

  • primitive data structures are basic building blocks for all data structures, they have a continuous memory for them: boolean, char, int, float, double, string.
  • composite data structures are data structures that are composed of more than one primitive data types.class, structure, union, array/record.
  • abstract datatypes are composite datatypes that have way to access them efficiently which is called as an algorithm. Depending on the way the data is accessed data structures are divided into linear and non linear datatypes. Linked lists, stacks, queues, etc are linear data types. heaps, binary trees and hash tables etc are non linear data types.

I hope this helps you dive in.

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

Phone validation regex

I tried :

^(1[ \-\+]{0,3}|\+1[ -\+]{0,3}|\+1|\+)?((\(\+?1-[2-9][0-9]{1,2}\))|(\(\+?[2-8][0-9][0-9]\))|(\(\+?[1-9][0-9]\))|(\(\+?[17]\))|(\([2-9][2-9]\))|([ \-\.]{0,3}[0-9]{2,4}))?([ \-\.][0-9])?([ \-\.]{0,3}[0-9]{2,4}){2,3}$

I took care of special country codes like 1-97... as well. Here are the numbers I tested against (from Puneet Lamba and MCattle):

***** PASS *****
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(+230) 5 911 4450
123345678
(1) 345 654 67
+1 245436
1-976 33567
(1-734) 5465654
+(230) 2 345 6568
***** CORRECTLY FAILING *****
(003) 555-1212
(103) 555-1212
(911) 555-1212
1-800-555-1234p
800x555x1234
+1 800 555x1234
***** FALSE POSITIVES *****
180055512345
1 800 5555 1234
+867 800 555 1234
1 (800)  555-1234
86 800 555 1212

Originally posted here: Regular expression to match standard 10 digit phone number

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

Suppress console output in PowerShell

It is a duplicate of this question, with an answer that contains a time measurement of the different methods.

Conclusion: Use [void] or > $null.

Is String.Contains() faster than String.IndexOf()?

By using Reflector, you can see, that Contains is implemented using IndexOf. Here's the implementation.

public bool Contains(string value)
{
   return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

So Contains is likely a wee bit slower than calling IndexOf directly, but I doubt that it will have any significance for the actual performance.

Structure of a PDF file?

One way to get some clues is to create a PDF file consisting of a blank page. I have CutePDF Writer on my computer, and made a blank Wordpad document of one page. Printed to a .pdf file, and then opened the .pdf file using Notepad.

Next, use a copy of this file and eliminate lines or blocks of text that might be of interest, then reload in Acrobat Reader. You'd be surprised at how little information is needed to make a working one-page PDF document.

I'm trying to make up a spreadsheet to create a PDF form from code.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

how to destroy bootstrap modal window completely?

I have to destroy the modal right after it is closed through a button click, and so I came up with the following.

$("#closeModal").click(function() {
    $("#modal").modal('hide').on('hidden.bs.modal', function () {
        $("#modal").remove();
    });
});

Note that this works with Bootstrap 3.

When to use Comparable and Comparator

There had been a similar question here: When should a class be Comparable and/or Comparator?

I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID

Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.

How can I count all the lines of code in a directory recursively?

You want a simple for loop:

total_count=0
for file in $(find . -name *.php -print)
do
    count=$(wc -l $file)
    let total_count+=count
done
echo "$total_count"

How to use a variable inside a regular expression?

You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.

if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
    # Successful match**strong text**
else:
    # Match attempt failed

Open Redis port for remote connections

For me, I needed to do the following:

1- Comment out bind 127.0.0.1

2- Change protected-mode to no

3- Protect my server with iptables (https://www.digitalocean.com/community/tutorials/how-to-implement-a-basic-firewall-template-with-iptables-on-ubuntu-14-04)

How to create User/Database in script for Docker Postgres

EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

How to echo or print an array in PHP?

To see the contents of array you can use.

1) print_r($array); or if you want nicely formatted array then:

echo '<pre>'; print_r($array); echo '</pre>';

2) use var_dump($array) to get more information of the content in the array like datatype and length.

3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website:
http://in3.php.net/manual/en/control-structures.foreach.php

Multiple ping script in Python

import subprocess,os,threading,time
from queue import Queue
lock=threading.Lock()
_start=time.time()
def check(n):
    with open(os.devnull, "wb") as limbo:
                ip="192.168.21.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()
                with lock:                    
                    if not result:
                        print (ip, "active")                    
                    else:
                        pass                        

def threader():
    while True:
        worker=q.get()
        check(worker)
        q.task_done()
q=Queue()

for x in range(255):
    t=threading.Thread(target=threader)
    t.daemon=True
    t.start()
for worker in range(1,255):
    q.put(worker)
q.join()
print("Process completed in: ",time.time()-_start)

I think this will be better one.

How to terminate a python subprocess launched with shell=True

Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.

Here's the code:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

How do you reindex an array in PHP but with indexes starting from 1?

It feels like all of the array_combine() answers are all copying the same "mistake" (the unnecessary call of array_values()).

array_combine() ignores the keys of both parameters that it receives.

Code: (Demo)

$array = [
    2 => (object)['title' => 'Section', 'linked' => 1],
    1 => (object)['title' => 'Sub-Section', 'linked' => 1],
    0 => (object)['title' => 'Sub-Sub-Section', 'linked' => null]
];

var_export(array_combine(range(1, count($array)), $array));

Output:

array (
  1 => 
  (object) array(
     'title' => 'Section',
     'linked' => 1,
  ),
  2 => 
  (object) array(
     'title' => 'Sub-Section',
     'linked' => 1,
  ),
  3 => 
  (object) array(
     'title' => 'Sub-Sub-Section',
     'linked' => NULL,
  ),
)

Is there a way to avoid null check before the for-each loop iteration starts?

How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

Convert sqlalchemy row object to python dict

In most scenarios, column name is fit for them. But maybe you write the code like follows:

class UserModel(BaseModel):
    user_id = Column("user_id", INT, primary_key=True)
    email = Column("user_email", STRING)

the column.name "user_email" while the field name is "email", the column.name could not work well as before.

sqlalchemy_base_model.py

also i write the answer here

Open multiple Projects/Folders in Visual Studio Code

To run one project at a time in same solution

Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

I can not find my.cnf on my windows computer

Here is my answer:

  1. Win+R (shortcut for 'run'), type services.msc, Enter
  2. You should find an entry like 'MySQL56', right click on it, select properties
  3. You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Full answer here: https://stackoverflow.com/a/20136523/1316649

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

SQL Query for Student mark functionality

I like the simple solution using windows functions:

select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where t.mark = maxmark

Or, alternatively:

select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where markseqnum = 1

Python SQL query string formatting

You've obviously considered lots of ways to write the SQL such that it prints out okay, but how about changing the 'print' statement you use for debug logging, rather than writing your SQL in ways you don't like? Using your favourite option above, how about a logging function such as this:

def debugLogSQL(sql):
     print ' '.join([line.strip() for line in sql.splitlines()]).strip()

sql = """
    select field1, field2, field3, field4
    from table"""
if debug:
    debugLogSQL(sql)

This would also make it trivial to add additional logic to split the logged string across multiple lines if the line is longer than your desired length.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.

Once I corrected all the references everything worked perfectly.

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

Defining and using a variable in batch file

input location.bat

@echo off
cls

set /p "location"="bob"
echo We're working with %location%
pause

output

We're working with bob

(mistakes u done : space and " ")

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Do I use <img>, <object>, or <embed> for SVG files?

This jQuery function captures all errors in svg images and replaces the file extension with an alternate extension

Please open the console to see the error loading image svg

_x000D_
_x000D_
(function($){_x000D_
  $('img').on('error', function(){_x000D_
    var image = $(this).attr('src');_x000D_
    if ( /(\.svg)$/i.test( image )) {_x000D_
      $(this).attr('src', image.replace('.svg', '.png'));_x000D_
    }_x000D_
  })  _x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<img src="https://jsfiddle.net/img/logo.svg">
_x000D_
_x000D_
_x000D_

MS SQL compare dates?

Use the DATEDIFF function with a datepart of day.

SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0

Note that if you want to test that date1 <= date2 then you need to test that DATEDIFF(day, date1, date2) >= 0, or alternatively you could test DATEDIFF(day, date2, date1) <= 0.

How to add a downloaded .box file to Vagrant?

Solution for Windows:

  • Open the cmd or powershell as admin
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box 'name_of_my_box.box'
  • vagrant box list should show the new box in the list

Solution for MAC:

  • Open terminal
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box "./name_of_my_box.box"
  • vagrant box list should show the new box in the list

JQUERY ajax passing value from MVC View to Controller

Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".

$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

<div id="_content"></div>

Not really a direct answer to ur question but its some info u should be aware of ;).

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Jquery: how to trigger click event on pressing enter key

You can use this code

$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
       alert('You pressed a ENTER key.');
    }
});

How to make a class property?

If you use Django, it has a built in @classproperty decorator.

from django.utils.decorators import classproperty

indexOf and lastIndexOf in PHP?

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

string substr ( string $string , int $start [, int $length ] )

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the desired length by the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

Creating and Update Laravel Eloquent

2020 Update

As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate().

For example for asked question you can use something like:

$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Above code will check the table represented by ShopMeta, which will be most likely shop_metas unless not defined otherwise in model itself

and it will try to find entry with

column shopId = $theID

and

column metadateKey = 2001

and if it finds then it will update column shopOwner of found row to New One.

If it finds more than one matching rows then it will update the very first row that means which has lowest primary id.

If not found at all then it will insert a new row with :

shopId = $theID,metadateKey = 2001 and shopOwner = New One

Notice Check your model for $fillable and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id column auto incremented one.

Otherwise it will throw error when executing above example:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'

As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable or it doesnt have default value.

For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent

One example from there is:

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

which pretty much clears everything.

Query Builder Update

Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.

Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:

$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Of course, don't forget to add DB facade:

use Illuminate\Support\Facades\DB;

OR

use DB;

I hope it helps

What is the difference between Cygwin and MinGW?

Cygwin emulates entire POSIX environment, while MinGW is minimal tool set for compilation only (compiles native Win application.) So if you want to make your project cross-platform the choice between the two is obvious, MinGW.

Although you might consider using VS on Windows, GCC on Linux/Unices. Most open source projects do that (e.g. Firefox or Python).

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I just fixed this problem by adding the following code in header:

    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

How do you find out the caller function in JavaScript?

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...

How to load a resource bundle from a file resource in Java?

The file name should have .properties extension and the base directory should be in classpath. Otherwise it can also be in a jar which is in classpath Relative to the directory in classpath the resource bundle can be specified with / or . separator. "." is preferred.

jQuery Mobile: document ready vs. page events

This is the correct way:

To execute code that will only be available to the index page, we could use this syntax:

$(document).on('pageinit', "#index",  function() {
    ...
});

Different class for the last element in ng-repeat

The answer given by Fabian Perez worked for me, with a little change

Edited html is here:

<div ng-repeat="file in files" ng-class="!$last ? 'other' : 'class-for-last'"> {{file.name}} </div>

How do I convert a C# List<string[]> to a Javascript array?

Many way to Json Parse but i have found most effective way to

 @model  List<string[]>

     <script>

         function DataParse() {
             var model = '@Html.Raw(Json.Encode(Model))';
             var data = JSON.parse(model);  

            for (i = 0; i < data.length; i++) {
            ......
             }

     </script>

Get the ID of a drawable in ImageView

I think if I understand correctly this is what you are doing.

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        switch(getDrawableId(imageView)) {
            case R.drawable.foo:
                imageView.setDrawableResource(R.drawable.bar);
                break;
            case R.drawable.bar:
            default:
                imageView.setDrawableResource(R.drawable.foo);
            break;
        }
    });

Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        // See here
        Integer integer = (Integer) imageView.getTag();
        integer = integer == null ? 0 : integer;

        switch(integer) {
        case R.drawable.foo:
            imageView.setDrawableResource(R.drawable.bar);
            imageView.setTag(R.drawable.bar);
            break;
        case R.drawable.bar:
        default:
            imageView.setDrawableResource(R.drawable.foo);
            imageView.setTag(R.drawable.foo);
            break;
        }
    });

Why do we use arrays instead of other data structures?

Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.

Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.

In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.

  MyArray   [5]
     ^       ^
  Pointer  Offset

All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).

For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================

In an array, we know that each element is next to each other in memory. A C array (Called MyArray here) is simply a pointer to the first element:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^
MyArray

If we wanted to look up MyArray[4], internally it would be accessed like this:

   0     1     2     3     4 
=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
                           ^
MyArray + 4 ---------------/
(Pointer + Offset)

Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000] would take the same amount of time as getting MyArray[5].

An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node

========    ========    ========    ========    ========
| Data |    | Data |    | Data |    | Data |    | Data |
|      | -> |      | -> |      | -> |      | -> |      | 
|  P1  |    |  P2  |    |  P3  |    |  P4  |    |  P5  |        
========    ========    ========    ========    ========

P(X) stands for Pointer to next node.

Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.

If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.

This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.

Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.

You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.

Take our array again. This time, I want to find the array element that holds the value '5'.

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^     ^     ^     ^     ^   FOUND!

In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.

Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.

Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.

A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.

         ==========
         |  Root  |         
         ==========
        /          \ 
  =========       =========
  | Child |       | Child |
  =========       =========
                  /       \
            =========    =========
            | Child |    | Child |
            =========    =========

 Assume that each connector is really a Pointer

When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.

This means that the values in a binary tree could look like this:

         ==========
         |   100  |         
         ==========
        /          \ 
  =========       =========
  |  200  |       |   50  |
  =========       =========
                  /       \
            =========    =========
            |   75  |    |   25  |
            =========    =========

When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:

  • Is 75 less than 100? Look at Right Node
  • Is 75 greater than 50? Look at Left Node
  • There is the 75!

Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.

That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.

This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.

Converting String array to java.util.List

On Java 14 you can do this

List<String> strings = Arrays.asList("one", "two", "three");

Using success/error/finally/catch with Promises in AngularJS

Forget about using success and error method.

Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.

With the following example, I'll try to demonstrate what I mean about success and error being not chainable-friendly. Suppose we call an API that returns a user object with an address:

User object:

{name: 'Igor', address: 'San Francisco'}

Call to the API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

What happened?

Because success and error return the original promise, i.e. the one returned by $http.get, the object passed to the callback of the then is the whole user object, that is to say the same input to the preceding success callback.

If we had chained two then, this would have been less confusing:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

How to create a data file for gnuplot?

Create your Datafile like this:

# X      Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45

And plot it with

$ gnuplot -p -e "plot 'filename.dat'"

There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/

C# switch statement limitations - why?

I agree with this comment that using a table driven approach is often better.

In C# 1.0 this was not possible because it didn't have generics and anonymous delegates. New versions of C# have the scaffolding to make this work. Having a notation for object literals is also helps.

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

Convert Dictionary to JSON in Swift

Swift 3.0

With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

let dic = ["2": "B", "1": "A", "3": "C"]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type        
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

Swift 2.x

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // here "decoded" is of type `AnyObject`, decoded from JSON data

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

Swift 1

var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
    if error != nil {
        println(error)
    } else {
        // here "jsonData" is the dictionary encoded in JSON data
    }
}

if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
    if error != nil {
        println(error)
    } else {
        // here "decoded" is the dictionary decoded from JSON data
    }
}

How to run 'sudo' command in windows

in Windows, you can use the runas command. For linux users, there are some alternatives for sudo in windows, you can check this out

http://helpdeskgeek.com/free-tools-review/5-windows-alternatives-linux-sudo-command/

Mercurial undo last commit

hg rollback is what you want.

In TortoiseHg, the hg rollback is accomplished in the commit dialog. Open the commit dialog and select "Undo".

alt text

Change DataGrid cell colour based on values

In my case convertor must return string value. I don't why, but it works.

*.xaml (common style file, which is included in another xaml files)

<Style TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>

*.cs

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
    return "#" + color.Name;
}

hide/show a image in jquery

Use the .css() jQuery manipulators, or better yet just call .show()/.hide() on the image once you've obtained a handle to it (e.g. $('#img' + id)).

BTW, you should not write javascript handlers with the "javascript:" prefix.

LaTeX package for syntax highlighting of code in various languages

I mostly use lstlistings in papers, but for coloured output (for slides) I use pygments instead.

How to set a parameter in a HttpServletRequest?

The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/***
 * Request wrapper enabling the update of a request-parameter.
 * 
 * @author E.K. de Lang
 *
 */
final class HttpServletRequestReplaceParameterWrapper
    extends HttpServletRequestWrapper
{

    private final Map<String, String[]> keyValues;

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
    {
        super(request);

        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        // Can override the values in the request
        keyValues.put(key, new String[] { value });

    }

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
    {
        super(request);
        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
            keyValues.put(entry.getKey(), new String[] { entry.getValue() });
        }

    }

    @Override
    public String getParameter(String name)
    {
        if (keyValues.containsKey(name)) {
            String[] strings = keyValues.get(name);
            if (strings == null || strings.length == 0) {
                return null;
            }
            else {
                return strings[0];
            }
        }
        else {
            // Just in case the request has some tricks of it's own.
            return super.getParameter(name);
        }
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] value = this.keyValues.get(name);
        if (value == null) {
            // Just in case the request has some tricks of it's own.
            return super.getParameterValues(name);
        }
        else {
            return value;
        }
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        return this.keyValues;
    }

}

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

function declaration isn't a prototype

Quick answer: change int testlib() to int testlib(void) to specify that the function takes no arguments.

A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).

A non-prototype function declaration like

int foo();

is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.

For a function that takes one or more arguments, you can specify the type of each argument in the declaration:

int bar(int x, double y);

Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that an argument but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void keyword:

int foo(void); /* foo takes no arguments */

A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:

int testlib()
{
    /* code that implements testlib */
}

This provides a non-prototype declaration for testlib. As a definition, this tells the compiler that testlib has no parameters, but as a declaration, it only tells the compiler that testlib takes some unspecified but fixed number and type(s) of arguments.

If you change () to (void) the declaration becomes a prototype.

The advantage of a prototype is that if you accidentally call testlib with one or more arguments, the compiler will diagnose the error.

(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void) syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the () in C++ and the (void) syntax in C.)

Matplotlib 2 Subplots, 1 Colorbar

This topic is well covered but I still would like to propose another approach in a slightly different philosophy.

It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3

# Make a new figure
fig = plt.figure(constrained_layout=True)

# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)

# Fill your figure with desired plots
axes = []
for i in range(nrow):
    for j in range(ncol):
        axes.append(fig.add_subplot(gs[i, j]))
        im = axes[-1].pcolormesh(np.random.random((10,10)))

# Shared colorbar    
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])

plt.show()

enter image description here

How to convert the background to transparent?

Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".

How to send a “multipart/form-data” POST in Android with Volley

This is my way of doing it. It may be useful to others :

private void updateType(){
    // Log.i(TAG,"updateType");
     StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

         @Override
         public void onResponse(String response) {
             // running on main thread-------
             try {
                 JSONObject res = new JSONObject(response);
                 res.getString("result");
                 System.out.println("Response:" + res.getString("result"));

                 }else{
                     CustomTast ct=new CustomTast(context);
                     ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
                 }

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

                 //Log.e("Response", "==> " + e.getMessage());
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError volleyError) {
             // running on main thread-------
             VolleyLog.d(TAG, "Error: " + volleyError.getMessage());

         }
     }) {
         protected Map<String, String> getParams() {
             HashMap<String, String> hashMapParams = new HashMap<String, String>();
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value"));
             hashMapParams.put("key", "value");
             System.out.println("Hashmap:" + hashMapParams);
             return hashMapParams;
         }
     };
     AppController.getInstance().addToRequestQueue(request);

 }

Show DialogFragment with animation growing from a point

To get a full-screen dialog with animation, write the following ...

Styles:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionModeBackground">?attr/colorPrimary</item>
    <item name="windowActionModeOverlay">true</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.NoActionBar.FullScreenDialog">
    <item name="android:windowAnimationStyle">@style/Animation.WindowSlideUpDown</item>
</style>

<style name="Animation.WindowSlideUpDown" parent="@android:style/Animation.Activity">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>
</style>

res/anim/slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="100%"
        android:toYDelta="0%"/>
</set>

res/anim/slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="0%"
        android:toYDelta="100%"/>
</set>

Java code:

public class MyDialog extends DialogFragment {

    @Override
    public int getTheme() {
        return R.style.AppTheme_NoActionBar_FullScreenDialog;
    }
}

private void showDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    Fragment previous = getSupportFragmentManager().findFragmentByTag(MyDialog.class.getName());
    if (previous != null) {
        fragmentTransaction.remove(previous);
    }
    fragmentTransaction.addToBackStack(null);

    MyDialog dialog = new MyDialog();
    dialog.show(fragmentTransaction, MyDialog.class.getName());
}

Android - SMS Broadcast receiver

Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.

Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:

<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

How to detect chrome and safari browser (webkit)

Most of the answers here are obsolete, there is no more jQuery.browser, and why would anyone even use jQuery or would sniff the User Agent is beyond me.

Instead of detecting a browser, you should rather detect a feature
(whether it's supported or not).

The following is false in Mozilla Firefox, Microsoft Edge; it is true in Google Chrome.

"webkitLineBreak" in document.documentElement.style

Note this is not future-proof. A browser could implement the -webkit-line-break property at any time in the future, thus resulting in false detection. Then you can just look at the document object in Chrome and pick anything with webkit prefix and check for that to be missing in other browsers.

Auto-indent spaces with C in vim?

I wrote all about tabs in vim, which gives a few interesting things you didn't ask about. To automatically indent braces, use:

:set cindent

To indent two spaces (instead of one tab of eight spaces, the vim default):

:set shiftwidth=2

To keep vim from converting eight spaces into tabs:

:set expandtab

If you ever want to change the indentation of a block of text, use < and >. I usually use this in conjunction with block-select mode (v, select a block of text, < or >).

(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)

How do I run Python script using arguments in windows command line

I found this thread looking for information about dealing with parameters; this easy guide was so cool:

import argparse

parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")

args = parser.parse_args()

opt1_value = args.opt1
opt2_value = args.opt2

run like:

python myScript.py --opt2 = 'hi'

How to use .htaccess in WAMP Server?

Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it

LoadModule rewrite_module modules/mod_rewrite.so

and restart all service.

Curl not recognized as an internal or external command, operable program or batch file

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

Ternary operation in CoffeeScript

In almost any language this should work instead:

a = true  && 5 || 10
a = false && 5 || 10

What is the difference between localStorage, sessionStorage, session and cookies?

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Android SDK installation doesn't find JDK

While this question has already been answered. Here is what exact steps you need to do when you are setting up for development. In general anything related to Java Development.

Setting Up Java

Make sure you are using latest jdk url

curl -L -O -H "Cookie: oraclelicense=accept-securebackup-cookie" -k "http://download.oracle.com/otn-pub/java/jdk/8u60-b27/jdk-8u60-linux-x64.tar.gz"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/local/jdk1.7.0_67/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/local/jdk1.7.0_67/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/local/jdk1.7.0_67/bin/javaws" 1
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws

Setting up your system in this case ubuntu/mac

export ANDROID_HOME=/home/ashish/android-sdks
export ANDROID_SDK=/home/ashish/android-sdks
export JAVA_HOME=/usr/local/jdk1.8.0_45
export JDK_HOME=/usr/local/jdk1.8.0_45/
export JRE_HOME=/usr/local/jdk1.8.0_45/jre
export PATH=$PATH:$ANT_HOME/bin:$JAVA_HOME/bin:$JRE_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools

this contents needs to appear in .profile in ubuntu or .bash_profile in mac in home folder we can go there using cd ~

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Mount current directory as a volume in Docker on Windows 10

In Windows Command Line (cmd), you can mount the current directory like so:

docker run --rm -it -v %cd%:/usr/src/project gcc:4.9

In PowerShell, you use ${PWD}, which gives you the current directory:

docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9

On Linux:

docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Cross Platform

The following options will work on both PowerShell and on Linux (at least Ubuntu):

docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9
docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Node - how to run app.js?

The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.

How to find and replace string?

Not exactly that, but std::string has many replace overloaded functions.

Go through this link to see explanation of each, with examples as to how they're used.

Also, there are several versions of string::find functions (listed below) which you can use in conjunction with string::replace.

  • find
  • rfind
  • find_first_of
  • find_last_of
  • find_first_not_of
  • find_last_not_of

Also, note that there are several versions of replace functions available from <algorithm> which you can also use (instead of string::replace):

  • replace
  • replace_if
  • replace_copy
  • replace_copy_if

How to return values in javascript

Its very simple. Call one function inside another function with parameters.

    function fun1()
    {
     var a=10;
     var b=20;
     fun2(a,b); //calling function fun2() and passing 2 parameters
    }

   function fun2(num1,num2)
   {
    var sum;
    sum = num1+num2;
    return sum;
   }

   fun1(); //trigger function fun1

How to make a drop down list in yii2?

Html::activeDropDownList($model, 'id', ArrayHelper::map(AttendanceLabel::find()->all(), 'id', 'label_name'), ['prompt'=>'Attendance Status'] );

Renaming a branch in GitHub

The following commands rename the branch locally, delete the old branch on the remote location and push the new branch, setting the local branch to track the new remote:

git branch -m old_branch new_branch
git push origin :old_branch
git push --set-upstream origin new_branch

How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then [IO.Path]::Combine won't have the params string[] overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

Join-Path C: (Join-Path  "Program Files" "Microsoft Office")

or

Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"

How can I tell if a Java integer is null?

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

This indicates it only applies to hash or array elements!

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

TortoiseSVN icons not showing up under Windows 7

Also restarting your PC is not needed. Instead restart explorer.exe:

  1. Press Ctrl+Shift+Esc.
  2. Click the Processes tab.
  3. Right-click on explorer.exe.
  4. Select End Process.
  5. Click End Process button.
  6. Click the Applications tab.
  7. Right-click.
  8. Click New Task (Run).
  9. Set Open to: explorer
  10. Click OK.

Windows Explorer has restarted and the TortoiseSVN icons reappear.

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?

Most likely mechanizm that you are looking for is AsyncTask. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.

If you don't know how to start here is nice tutorial:

Note: Also there is possibility to use IntentService with ResultReceiver that works as well.

Using BeautifulSoup to extract text without tags

you can try this indside findall for loop:

item_price = item.find('span', attrs={'class':'s-item__price'}).text

it extracts only text and assigs it to "item_pice"

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

I had this issue on resx files in my solution. I'm using Onedrive. However none of the above solutions fixed it.

The problem was the icon I used was in the MyWindow.resx files for the windows.

I removed that then grabbed the icon from the App Local Resources resource folder.

 private ResourceManager rm = App_LocalResources.LocalResources.ResourceManager;
 
 ..
 
InitializeComponent();
this.Icon = (Icon)rm.GetObject("IconName");

This happened after an update to VS2019.

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here

The socket plugin checks whether the socket user name (the operating system user name) matches the MySQL user name specified by the client program to the server, and permits the connection only if the names match.

Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.

About the method to achieve that, I recommend this instead.

Moving from one activity to another Activity in Android

It is mainly due to unregistered activity in manifest file as "NextActivity" Firstly register NextActivity in Manifest like

<activity android:name=".NextActivity">

then use the code in the where you want

Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);

where you have to call the NextActivity..

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

Find if variable is divisible by 2

You don't need jQuery. Just use JavaScript's Modulo operator.

What is the default access modifier in Java?

Yes, it is visible in the same package. Anything outside that package will not be allowed to access it.

How to get item's position in a list?

Why complicate things?

testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
    if item == 1:
        print position

Counter in foreach loop in C#

The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for loop instead.

An example class that can be used in foreach:

    class Foo {

        public iterator GetEnumerator() {
            return new iterator();
        }

        public class iterator {
            public Bar Current {
                get{magic}
            }

            public bool MoveNext() {
                incantation
            }
        }
    }

Tracking the script execution time in PHP

On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:

// Script start
$rustart = getrusage();

// Code ...

// Script end
function rutime($ru, $rus, $index) {
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
    " ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
    " ms in system calls\n";

Note that you don't need to calculate a difference if you are spawning a php instance for every test.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

grep exclude multiple strings

Another option is to create a exclude list, this is particulary usefull when you have a long list of things to exclude.

vi /root/scripts/exclude_list.txt

Now add what you would like to exclude

Nopaging the limit is
keyword to remove is

Now use grep to remove lines from your file log file and view information not excluded.

grep -v -f /root/scripts/exclude_list.txt /var/log/admin.log

Javascript "Not a Constructor" Exception while creating objects

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)

std::string to char*

char* result = strcpy((char*)malloc(str.length()+1), str.c_str());

Append String in Swift

let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"