Programs & Examples On #Parentheses

The symbols "(" and ")", commonly used in programming languages. Please use this tag only if the specific usage of these symbols is a relevant part of the question.

How to select between brackets (or quotes or ...) in Vim?

I would add a detail to the most voted answer:

If you're using gvim and want to copy to the clipboard, use

"+<command>

To copy all the content between brackets (or parens or curly brackets)

For example: "+yi} will copy to the clipboard all the content between the curly brackets your cursor is.

Parenthesis/Brackets Matching using Stack algorithm

Algorithm to use for checking well balanced parenthesis -

  1. Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
  2. Declare a set openingParenSet and initialize it with the values of matchingParenMap.
  3. Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
  4. Now traverse the string expression input.

    1. If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.

    2. If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.

  5. After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.

I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

How do I execute a command and get the output of the command within C++ using POSIX?

Two possible approaches:

  1. I don't think popen() is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command).

  2. On the off-chance that there is no popen(), you can use system("./some_command >/tmp/some_command.out");, then use the normal I/O functions to process the output file.

What does an exclamation mark mean in the Swift language?

What does it mean to "unwrap the instance"? Why is it necessary?

As far as I can work out (this is very new to me, too)...

The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.

When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)), or not (None).

If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T from Some(T)).

How is john!.apartment = number73 different from john.apartment = number73? (Paraphrased)

If you write the name of an Optional variable (eg text john, without the !), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john isn't an instance of Person, and it doesn't have an apartment member:

john.apartment
// 'Person?' does not have a member named 'apartment'

The actual Person value can be unwrapped in various ways:

  • "forced unwrapping": john! (gives the Person value if it exists, runtime error if it is nil)
  • "optional binding": if let p = john { println(p) } (executes the println if the value exists)
  • "optional chaining": john?.learnAboutSwift() (executes this made-up method if the value exists)

I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).

Update:

The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals".

In the examples so far, the john variable has been declared as var john:Person?, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.

If it were declared as var john:Person! instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john can be used without additional syntax. But Apple's book says:

Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

Update 2:

The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing.

Update 3:

Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?) or implicitly unwrapped (using !) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe.

Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.

How to return a result (startActivityForResult) from a TabHost Activity?

You could implement a onActivityResult in Class B as well and launch Class C using startActivityForResult. Once you get the result in Class B then set the result there (for Class A) based on the result from Class C. I haven't tried this out but I think this should work.

Another thing to look out for is that Activity A should not be a singleInstance activity. For startActivityForResult to work your Class B needs to be a sub activity to Activity A and that is not possible in a single instance activity, the new Activity (Class B) starts in a new task.

Asp.net MVC ModelState.Clear

Well, this seemed to work on my Razor Page and never even did a round trip to the .cs file. This is old html way. It might be useful.

<input type="reset" value="Reset">

How to [recursively] Zip a directory in PHP?

I needed to run this Zip function in Mac OSX

so I would always zip that annoying .DS_Store.

I adapted https://stackoverflow.com/users/2019515/user2019515 by including additionalIgnore files.

function zipIt($source, $destination, $include_dir = false, $additionalIgnoreFiles = array())
{
    // Ignore "." and ".." folders by default
    $defaultIgnoreFiles = array('.', '..');

    // include more files to ignore
    $ignoreFiles = array_merge($defaultIgnoreFiles, $additionalIgnoreFiles);

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
        }
    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        if ($include_dir) {

            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) { 
                $source .= '/' . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // purposely ignore files that are irrelevant
            if( in_array(substr($file, strrpos($file, '/')+1), $ignoreFiles) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

SO to ignore the .DS_Store from zip, you run

zipIt('/path/to/folder', '/path/to/compressed.zip', false, array('.DS_Store'));

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

How to run ~/.bash_profile in mac terminal

If the problem is that you are not seeing your changes to the file take effect, just open a new terminal window, and it will be "sourced". You will be able to use the proper PATH etc with each subsequent terminal window.

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

How would you make a comma-separated string from a list of strings?

@Peter Hoffmann

Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

proper way to sudo over ssh

echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost 
echo \"$varCommand\" | sudo bash

How do I create a foreign key in SQL Server?

This script is about creating tables with foreign key and I added referential integrity constraint sql-server.

create table exams
(  
    exam_id int primary key,
    exam_name varchar(50),
);

create table question_bank 
(
    question_id int primary key,
    question_exam_id int not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id_fk
       foreign key references exams(exam_id)
               ON DELETE CASCADE
);

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Bulk Insert Correctly Quoted CSV File in SQL Server

I had this same problem, and I didn't want to have to go the SSIS route, so I found a PowerShell script that is easy to run and handles the case of the quotes with the comma in that particular field:

Source Code and DLL for the PowerShell Script: https://github.com/billgraziano/CsvDataReader

Here's a blog that explains the usage: http://www.sqlteam.com/article/fast-csv-import-in-powershell-to-sql-server

XML Schema Validation : Cannot find the declaration of element

Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.

For completeness, here is the corrected XML and XSD

Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)

<?xml version="1.0" encoding="UTF-8"?>

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="urn:Test.Namespace"  
      xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
    <element1 id="001">
        <element2 id="001.1">
            <element3 id="001.1" />
        </element2>
    </element1>
</Root>

and, here is the Schema

<?xml version="1.0"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:Test.Namespace"
            xmlns="urn:Test.Namespace"
            elementFormDefault="qualified">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
       
    <xsd:complexType name="element1Type">
        <xsd:sequence>
            <xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>
       
    <xsd:complexType name="element2Type">
        <xsd:sequence>
            <xsd:element name="element3" type="element3Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>

    <xsd:complexType name="element3Type">
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>        
</xsd:schema>

Thanks again to everyone, I hope this is of use to somebody else in the future.

Calling a javascript function recursively

You can use the Y-combinator: (Wikipedia)

// ES5 syntax
var Y = function Y(a) {
  return (function (a) {
    return a(a);
  })(function (b) {
    return a(function (a) {
      return b(b)(a);
    });
  });
};

// ES6 syntax
const Y = a=>(a=>a(a))(b=>a(a=>b(b)(a)));

// If the function accepts more than one parameter:
const Y = a=>(a=>a(a))(b=>a((...a)=>b(b)(...a)));

And you can use it as this:

// ES5
var fn = Y(function(fn) {
  return function(counter) {
    console.log(counter);
    if (counter > 0) {
      fn(counter - 1);
    }
  }
});

// ES6
const fn = Y(fn => counter => {
  console.log(counter);
  if (counter > 0) {
    fn(counter - 1);
  }
});

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Test if executable exists in Python?

Added windows support

def which(program):
    path_ext = [""];
    ext_list = None

    if sys.platform == "win32":
        ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]

    def is_exe(fpath):
        exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
        # search for executable under windows
        if not exe:
            if ext_list:
                for ext in ext_list:
                    exe_path = "%s%s" % (fpath,ext)
                    if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
                        path_ext[0] = ext
                        return True
                return False
        return exe

    fpath, fname = os.path.split(program)

    if fpath:
        if is_exe(program):
            return "%s%s" % (program, path_ext[0])
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return "%s%s" % (exe_file, path_ext[0])
    return None

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

How To Pass GET Parameters To Laravel From With GET Method ?

Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GET arguments. Use filters, for example:

Create a route without parameters:

$Route::get('/history', ['uses'=>'ExampleController@history']);

Specify action with two parameters and attach the filter:

class ExampleController extends BaseController
{
    public function __construct($browser)
    {
        $this->beforeFilter('filterDates', array(
            'only' => array('history')
        ));
    }

    public function history($fromDate, $toDate)
    {
        /* ... */
    }

}

Filter that translates GET into action's arguments :

Route::filter('filterDates', function($route, Request $request) {
    $notSpecified = '_';

    $fromDate = $request->get('fromDate', $notSpecified);
    $toDate = $request->get('toDate', $notSpecified);

    $route->setParameter('fromDate', $fromDate);
    $route->setParameter('toDate', $toDate);
});

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

How can I compare two ordered lists in python?

Just use the classic == operator:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

Lists are equal if elements at the same index are equal. Ordering is taken into account then.

How to add 20 minutes to a current date?

Just add 20 minutes in milliseconds to your date:

  var currentDate = new Date();

  currentDate.setTime(currentDate.getTime() + 20*60*1000);

Use FontAwesome or Glyphicons with css :before

<ul class="icons-ul">
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
</ul>

All the font awesome icons comes default with Bootstrap.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

PHP array: count or sizeof?

I know this is old but just wanted to mention that I tried this with PHP 7.2:

<?php
//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
{
    $a[] = 100;
}

//Measure
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
    $b = count($a);
}
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");

$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
    $b = sizeof($a);
}
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");
?>

and the result was:

1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec

So just use count().

multiple where condition codeigniter

Yes, multiple calls to where() is a perfectly valid way to achieve this.

$this->db->where('username',$username);
$this->db->where('status',$status);

http://www.codeigniter.com/user_guide/database/query_builder.html

VLook-Up Match first 3 characters of one column with another column

=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))

Get value from text area

Use val():

 if ($("textarea").val()!== "") {
        alert($("textarea").val());
    }

Java: Finding the highest value in an array

To find the highest (max) or lowest (min) value from an array, this could give you the right direction. Here is an example code for getting the highest value from a primitive array.

Method 1:

public int maxValue(int array[]){
  List<Integer> list = new ArrayList<Integer>();
  for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
  }
 return Collections.max(list);

}

To get the lowest value, you can use

Collections.min(list)

Method 2:

public int maxValue(int array[]){
  int max = Arrays.stream(array).max().getAsInt();
  return max;
}

Now the following line should work.

System.out.println("The highest maximum for the December is: " + maxValue(decMax)); 

The backend version is not supported to design database diagrams or tables

This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.


Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.

Return multiple fields as a record in PostgreSQL with PL/pgSQL

You can achieve this by using simply as a returns set of records using return query.

CREATE OR REPLACE FUNCTION schemaName.get_two_users_from_school(schoolid bigint)
 RETURNS SETOF record
 LANGUAGE plpgsql
AS $function$
begin

 return query
  SELECT id, name FROM schemaName.user where school_id = schoolid;

end;
$function$

And call this function as : select * from schemaName.get_two_users_from_school(schoolid) as x(a bigint, b varchar);

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

This is how I fixed my problem, after cloning into different repositories, for Visual Studio 2015:

In Visual Studio:

  1. Click Tools->Options
  2. In the left pane, click Debugging->Symbols
  3. Click "Empty Symbol Cache"

What is &amp used for

HTML doesn't recognize the & but it will recognize &amp; because it is equal to & in HTML

I looked over this post someone had made: http://www.webmasterworld.com/forum21/8851.htm

http://localhost/phpMyAdmin/ unable to connect

You dont start phpmyadmin from your webbrowser. When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel. When you've started phpmyadmin from your control-panel you can access it from the web-browser.

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

Split string into tokens and save them in an array

#include <stdio.h>
#include <string.h>

int main ()
{
    char buf[] ="abc/qwe/ccd";
    int i = 0;
    char *p = strtok (buf, "/");
    char *array[3];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok (NULL, "/");
    }

    for (i = 0; i < 3; ++i) 
        printf("%s\n", array[i]);

    return 0;
}

How to read/process command line arguments?

I recommend looking at docopt as a simple alternative to these others.

docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.

Read from file in eclipse

Have you tried using an absolute path:

File file = new File(System.getProperty("user.dir") + "/file.txt");

How should I have explained the difference between an Interface and an Abstract class?

An interface is like a set of genes that are publicly documented to have some kind of effect: A DNA test will tell me whether I've got them - and if I do, I can publicly make it known that I'm a "carrier" and part of my behavior or state will conform to them. (But of course, I may have many other genes that provide traits outside this scope.)

An abstract class is like the dead ancestor of a single-sex species(*): She can't be brought to life but a living (i.e. non-abstract) descendant inherits all her genes.

(*) To stretch this metaphor, let's say all members of the species live to the same age. This means all ancestors of a dead ancestor must also be dead - and likewise, all descendants of a living ancestor must be alive.

Sorting Characters Of A C++ String

You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;


        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

Insertion Sort vs. Selection Sort

Both insertion sort and selection sort have an outer loop (over every index), and an inner loop (over a subset of indices). Each pass of the inner loop expands the sorted region by one element, at the expense of the unsorted region, until it runs out of unsorted elements.

The difference is in what the inner loop does:

  • In selection sort, the inner loop is over the unsorted elements. Each pass selects one element, and moves it to its final location (at the current end of the sorted region).

  • In insertion sort, each pass of the inner loop iterates over the sorted elements. Sorted elements are displaced until the loop finds the correct place to insert the next unsorted element.

So, in a selection sort, sorted elements are found in output order, and stay put once they are found. Conversely, in an insertion sort, the unsorted elements stay put until consumed in input order, while elements of the sorted region keep getting moved around.

As far as swapping is concerned: selection sort does one swap per pass of the inner loop. Insertion sort typically saves the element to be inserted as temp before the inner loop, leaving room for the inner loop to shift sorted elements up by one, then copies temp to the insertion point afterwards.

Convert a character digit to the corresponding integer in C

As per other replies, this is fine:

char c = '5';
int x = c - '0';

Also, for error checking, you may wish to check isdigit(c) is true first. Note that you cannot completely portably do the same for letters, for example:

char c = 'b';
int x = c - 'a'; // x is now not necessarily 1

The standard guarantees that the char values for the digits '0' to '9' are contiguous, but makes no guarantees for other characters like letters of the alphabet.

How to print a specific row of a pandas DataFrame?

When you call loc with a scalar value, you get a pd.Series. That series will then have one dtype. If you want to see the row as it is in the dataframe, you'll want to pass an array like indexer to loc.

Wrap your index value with an additional pair of square brackets

print(df.loc[[159220]])

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

How can I pretty-print JSON using node.js?

what about this?

console.table(object)

sample

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

Center fixed div with dynamic width (CSS)

This approach will not limit element's width when using margins in flexbox

top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Also for centering it vertically

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

Download a file by jQuery.Ajax

Noone posted this @Pekka's solution... so I'll post it. It can help someone.

You don't need to do this through Ajax. Just use

window.location="download.action?para1=value1...."

Is it possible to send a variable number of arguments to a JavaScript function?

There are two methods as of ES2015.

The arguments Object

This object is built into functions, and it refers to, appropriately, the arguments of a function. It is not technically an array, though, so typical array operations won't work on it. The suggested method is to use Array.from or the spread operator to create an array from it.

I've seen other answers mention using slice. Don't do that. It prevents optimizations (source: MDN).

Array.from(arguments)
[...arguments]

However, I would argue that arguments is problematic because it hides what a function accepts as input. An arguments function typically is written like this:

function mean(){
    let args = [...arguments];
    return args.reduce((a,b)=>a+b) / args.length;
}

Sometimes, the function header is written like the following to document the arguments in a C-like fashion:

function mean(/* ... */){ ... }

But that is rare.

As for why it is problematic, take C, for example. C is backwards compatible with an ancient pre-ANSI dialect of the language known as K&R C. K&R C allows function prototypes to have an empty arguments list.

int myFunction();
/* This function accepts unspecified parameters */

ANSI C provides a facility for varargs (...), and void to specify an empty arguments-list.

int myFunction(void);
/* This function accepts no parameters */

Many people inadvertently declare functions with an unspecified arguments list (int myfunction();), when they expect the function to take zero arguments. This is technically a bug because the function will accept arguments. Any number of them.

A proper varargs function in C takes the form:

int myFunction(int nargs, ...);

And JavaScript actually does have something similar to this.

Spread Operator / Rest Parameters

I've already shown you the spread operator, actually.

...name

It's pretty versatile, and can also be used in a function's argument-list ("rest parameters") to specify varargs in a nicely documented fashion:

function mean(...args){
    return args.reduce((a,b)=>a+b) / args.length;
}

Or as a lambda expression:

((...args)=>args.reduce((a,b)=>a+b) / args.length)(1,2,3,4,5); // 3

I much prefer the spread operator. It is clean and self-documenting.

variable or field declared void

The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like

initializeJSP(Experiment);

'if' in prolog?

A standard prolog predicate will do this.

   isfive(5). 

will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=

isNotEqual(A,B):- A\=B.

Technically it is does not unify, but it is similar to not equal.

Learn Prolog Now is a good website for learning prolog.

Edit: To add another example.

isEqual(A,A). 

Transaction isolation levels relation with locks on table

I want to understand the lock each transaction isolation takes on the table

For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT statement to read data. C reads and updates data. All these process work on the same table T.

  • READ UNCOMMITTED - no lock on the table. You can read data in the table while writing on it. This means A writes data (uncommitted) and B can read this uncommitted data and use it (for any purpose). If A executes a rollback, B still has read the data and used it. This is the fastest but most insecure way to work with data since can lead to data holes in not physically related tables (yes, two tables can be logically but not physically related in real-world apps =\).
  • READ COMMITTED - lock on committed data. You can read the data that was only committed. This means A writes data and B can't read the data saved by A until A executes a commit. The problem here is that C can update data that was read and used on B and B client won't have the updated data.
  • REPEATABLE READ - lock on a block of SQL(which is selected by using select query). This means B reads the data under some condition i.e. WHERE aField > 10 AND aField < 20, A inserts data where aField value is between 10 and 20, then B reads the data again and get a different result.
  • SERIALIZABLE - lock on a full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, especially the bosses).

I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also

Using JDBC, you define it using Connection#setTransactionIsolation.

Using Hibernate:

<property name="hibernate.connection.isolation">2</property>

Where

  • 1: READ UNCOMMITTED
  • 2: READ COMMITTED
  • 4: REPEATABLE READ
  • 8: SERIALIZABLE

Hibernate configuration is taken from here (sorry, it's in Spanish).

By the way, you can set the isolation level on RDBMS as well:

and on and on...

Two versions of python on linux. how to make 2.7 the default

I guess you have installed the 2.7 version manually, while 2.6 comes from a package?

The simple answer is: uninstall python package.

The more complex one is: do not install manually in /usr/local. Build a package with 2.7 version and then upgrade.

Package handling depends on what distribution you use.

How can I know which radio button is selected via jQuery?

I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It'll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

node.js + mysql connection pooling

I am using this base class connection with mysql:

"base.js"

var mysql   = require("mysql");

var pool = mysql.createPool({
    connectionLimit : 10,
    host: Config.appSettings().database.host,
    user: Config.appSettings().database.username,
    password: Config.appSettings().database.password,
    database: Config.appSettings().database.database
});


var DB = (function () {

    function _query(query, params, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                connection.release();
                callback(null, err);
                throw err;
            }

            connection.query(query, params, function (err, rows) {
                connection.release();
                if (!err) {
                    callback(rows);
                }
                else {
                    callback(null, err);
                }

            });

            connection.on('error', function (err) {
                connection.release();
                callback(null, err);
                throw err;
            });
        });
    };

    return {
        query: _query
    };
})();

module.exports = DB;

Just use it like that:

var DB = require('../dal/base.js');

DB.query("select * from tasks", null, function (data, error) {
   callback(data, error);
});

What is an IIS application pool?

IIS-Internet information Service is a web server used to host one or more web application . Lets take any example here say Microsoft is maintaining web server and we are running our website abc.com (news content based)on this IIS. Since, Microsoft is a big shot company it might take or also ready to host another website say xyz.com(ecommerce based).

Now web server is hosting i.e providing memory to run both websites on its single web server.Thus , here application pools come into picture . abc.com has its own rules, business logic , data etc and same applies to xyz.com.

IIS provides two application pools (path) to run two websites in their own world (data) smoothly in a single webserver without affecting each ones matter (security, scalability).This is application pool in IIS.

So you can have any number of application pool depending upon on servers capacity

How to fix "unable to open stdio.h in Turbo C" error?

Make sure the folder with the standard header files is in the projects path.

I don't know where this is in Turbo C, but I would think there's a way of doing this.

Hide Command Window of .BAT file that Executes Another .EXE File

Create a .vbs file with this code:

CreateObject("Wscript.Shell").Run "your_batch.bat",0,True

This .vbs will run your_batch.bat hidden.

Works fine for me.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

  1. The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.

  2. There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.

I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).

Cannot connect to MySQL 4.1+ using old authentication

IF,

  1. You are using a shared hosting, and don't have root access.
  2. you are getting the said error while connecting to a remote database ie: not localhost.
  3. and your using Xampp.
  4. and the code is running fine on live server, but the issue is only on your development machine running xampp.

Then,

It is highly recommended that you install xampp 1.7.0 . Download Link

Note: This is not a solution to the above problem, but a FIX which would allow you to continue with your development.

Can an int be null in Java?

Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

Eg: Integer i=null;

HttpServletRequest to complete URL

Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:

import javax.servlet.http.HttpServletRequest;

public class GetRequestUrl{
    /**
     * <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
     *  (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
     *  that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
     * <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
     *  >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
     * @author Mark A. Ziesemer
     *  <a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
     */
    public String getRequestUrl(final HttpServletRequest req){
        final String scheme = req.getScheme();
        final int port = req.getServerPort();
        final StringBuilder url = new StringBuilder(256);
        url.append(scheme);
        url.append("://");
        url.append(req.getServerName());
        if(!(("http".equals(scheme) && (port == 0 || port == 80))
                || ("https".equals(scheme) && port == 443))){
            url.append(':');
            url.append(port);
        }
        url.append(req.getRequestURI());
        final String qs = req.getQueryString();
        if(qs != null){
            url.append('?');
            url.append(qs);
        }
        final String result = url.toString();
        return result;
    }
}

Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.

See also:

Can you put two conditions in an xslt test attribute?

It does have to be wrapped in an <xsl:choose> since it's a when. And lowercase the "and".

<xsl:choose>
   <xsl:when test="4 &lt; 5 and 1 &lt; 2" >
   <!-- do something -->
   </xsl:when>
   <xsl:otherwise>
   <!-- do something else -->
   </xsl:otherwise>
</xsl:choose>

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How to set a class attribute to a Symfony2 form input

You can do it with FormBuilder. Add this to the array in your FormBuilder:

'attr'=> array('class'=>'span2')

How to load external scripts dynamically in Angular?

import { Injectable } from '@angular/core';
import * as $ from 'jquery';

interface Script {
    src: string;
    loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
    public _scripts: Script[] = [];

    /**
     * @deprecated
     * @param tag
     * @param {string} scripts
     * @returns {Promise<any[]>}
     */
    load(tag, ...scripts: string[]) {
        scripts.forEach((src: string) => {
            if (!this._scripts[src]) {
                this._scripts[src] = { src: src, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(src => promises.push(this.loadScript(tag, src)));

        return Promise.all(promises);
    }

    /**
     * Lazy load list of scripts
     * @param tag
     * @param scripts
     * @param loadOnce
     * @returns {Promise<any[]>}
     */
    loadScripts(tag, scripts, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        scripts.forEach((script: string) => {
            if (!this._scripts[script]) {
                this._scripts[script] = { src: script, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(script => promises.push(this.loadScript(tag, script, loadOnce)));

        return Promise.all(promises);
    }

    /**
     * Lazy load a single script
     * @param tag
     * @param {string} src
     * @param loadOnce
     * @returns {Promise<any>}
     */
    loadScript(tag, src: string, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        if (!this._scripts[src]) {
            this._scripts[src] = { src: src, loaded: false };
        }

        return new Promise((resolve, _reject) => {
            // resolve if already loaded
            if (this._scripts[src].loaded && loadOnce) {
                resolve({ src: src, loaded: true });
            } else {
                // load script tag
                const scriptTag = $('<script/>')
                    .attr('type', 'text/javascript')
                    .attr('src', this._scripts[src].src);

                $(tag).append(scriptTag);

                this._scripts[src] = { src: src, loaded: true };
                resolve({ src: src, loaded: true });
            }
        });
    }

    reloadOnSessionChange() {
        window.addEventListener('storage', function(data) {
            if (data['key'] === 'token' && data['oldValue'] == null && data['newValue']) {
                document.location.reload();
            }
        });
    }
}

Using JQuery to check if no radio button in a group has been checked

You could do something like this:

var radio_buttons = $("input[name='html_elements']");
if( radio_buttons.filter(':checked').length == 0){
  // None checked
} else {
  // If you need to use the result you can do so without
  // another (costly) jQuery selector call:
  var val = radio_buttons.val();
}

How do I import a .sql file in mysql database using PHP?

// Import data 
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);

function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
    $connection = mysqli_connect($host,$uname,$pass)
    or die("Database Connection Failed");
    $selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected"); 

$templine = '';
$lines = file($filename); // Read entire file

foreach ($lines as $line){
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
        continue;

        // Add this line to the current segment
        $templine .= $line;
        // If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';')
        {
            mysqli_query($connection, $templine)
            or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
            $templine = '';
        }
    }
    echo "Tables imported successfully";
}




// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');

function backup_tables($host,$user,$pass,$name,$tables = '*'){
    $link = mysqli_connect($host,$user,$pass);
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_select_db($link,$name);
    //get all of the tables
    if($tables == '*'){
        $tables = array();
        $result = mysqli_query($link,'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }else{
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    foreach($tables as $table)
    {
        $result = mysqli_query($link,'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
        $row2 = mysqli_fetch_row($row_query);
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysqli_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j < $num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n", '\n', $row[$j]);
                    if (isset($row[$j])) { 
                        $return.= '"'.$row[$j].'"' ; 
                    } else { 
                        $return.= '""'; 
                    }
                    if ($j < ($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

Cannot open include file with Visual Studio

I had this same issue going from e.g gcc to visual studio for C programming. Make sure your include file is actually in the directory -- not just shown in the VS project tree. For me in other languages copying into a folder in the project tree would indeed move the file in. With Visual Studio 2010, pasting into "Header Files" was NOT putting the .h file there.

Please check your actual directory for the presence of the include file. Putting it into the "header files" folder in project/solution explorer was not enough.

Add values to app.config and retrieve them

To Get The Data From the App.config

Keeping in mind you have to:

  1. Added to the References -> System.Configuration
  2. and also added this using statement -> using System.Configuration;

Just Simply do this

string value1 = ConfigurationManager.AppSettings["Value1"];

Alternatively, you can achieve this in one line, if you don't want to add using System.Configuration; explicitly.

string value1 = System.Configuration.ConfigurationManager.AppSettings["Value1"]

join on multiple columns

tableB.col1 = tableA.col1 
OR tableB.col2 = tableA.col1  
OR tableB.col1 = tableA.col2  
OR tableB.col1 = tableA.col2

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Difference between binary tree and binary search tree

A tree can be called as a binary tree if and only if the maximum number of children of any of the nodes is two.

A tree can be called as a binary search tree if and only if the maximum number of children of any of the nodes is two and the left child is always smaller than the right child.

What's the difference between :: (double colon) and -> (arrow) in PHP?

The => operator is used to assign key-value pairs in an associative array. For example:

$fruits = array(
  'Apple'  => 'Red',
  'Banana' => 'Yellow'
);

It's meaning is similar in the foreach statement:

foreach ($fruits as $fruit => $color)
  echo "$fruit is $color in color.";

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

How to write a full path in a batch file having a folder name with space?

CD E:\Documents and Settings\All Users\Application Data

E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll

How to delete multiple files at once in Bash on Linux?

if you want to delete all files that belong to a directory at once. For example: your Directory name is "log" and "log" directory include abc.log.2012-03-14, abc.log.2012-03-15,... etc files. You have to be above the log directory and:

rm -rf /log/*

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:

(function($) { ...code...})(jQuery);

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Failure [INSTALL_FAILED_OLDER_SDK] basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion specified in your app.

N/B Froyo 2.2 API 8

To fix this simply change

targetSdkVersion="17" to targetSdkVersion="8"

cheers.

PHP order array by date?

I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

usort($array, function($a, $b) {
  return ($a['date'] < $b['date']) ? -1 : 1;
});

How to set commands output as a variable in a batch file

I most cases, creating a temporary file named after your variable name might be acceptable. (as you are probably using meaningful variables name...)

Here, my variable name is SSH_PAGEANT_AUTH_SOCK

dir /w "\\.\pipe\\"|find "pageant" > %temp%\SSH_PAGEANT_AUTH_SOCK && set /P SSH_PAGEANT_AUTH_SOCK=<%temp%\SSH_PAGEANT_AUTH_SOCK

Should I use past or present tense in git commit messages?

Stick with the present tense imperative because

  • it's good to have a standard
  • it matches tickets in the bug tracker which naturally have the form "implement something", "fix something", or "test something."

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How/when to use ng-click to call a route?

Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.

angular.module('mymodule', [])

// Click to navigate
// similar to <a href="#/partial"> but hash is not required, 
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
    return {
        link: function(scope, element, attrs) {
            element.on('click', function() {
                scope.$apply(function() {
                    $location.path(attrs.clickLink);
                });
            });
        }
    }
}]);

It has some useful features, but I'm new to Angular so there's probably room for improvement.

Regular expression matching a multiline block of text

Try this:

re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)

I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.

Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:

re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)

BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.

Angular update object in object array

Another approach could be:

let myList = [{id:'aaa1', name: 'aaa'}, {id:'bbb2', name: 'bbb'}, {id:'ccc3', name: 'ccc'}];
let itemUpdated = {id: 'aaa1', name: 'Another approach'};

myList.find(item => item.id == itemUpdated.id).name = itemUpdated.name;

How do I detect "shift+enter" and generate a new line in Textarea?

I found this thread looking for a way to control Shift + any key. I pasted together other solutions to make this combined function to accomplish what I needed. I hope it helps someone else.

function () {
    return this.each(function () {
    $(this).keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        // Shift + anything is not desired
        if (e.shiftKey) {
            return false;
        }
        // allow backspace, tab, delete, enter, arrows, numbers 
        //and keypad numbers ONLY
        // home, end, period, and numpad decimal
        return (
            key == 8 ||
            key == 9 ||
            key == 13 ||
            key == 46 ||
            key == 110 ||
            key == 190 ||
            (key >= 35 && key <= 40) ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105));
    });
});

how to change directory using Windows command line

cd /driveName driveName:\pathNamw

How get permission for camera in android.(Specifically Marshmallow)

First check if the user has granted the permission:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)

Then, you could use this to request to the user:

ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

And in Marshmallow, it will appear in a dialog

JUnit Testing Exceptions

Though @Test(expected = MyException.class) and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:

@Test public void yourTest() {
  try {
    systemUnderTest.doStuff();
    fail("MyException expected.");
  } catch (MyException expected) {

    // Though the ExpectedException rule lets you write matchers about
    // exceptions, it is sometimes useful to inspect the object directly.

    assertEquals(1301, expected.getMyErrorCode());
  }

  // In both @Test(expected=...) and ExpectedException code, the
  // exception-throwing line will be the last executed line, because Java will
  // still traverse the call stack until it reaches a try block--which will be
  // inside the JUnit framework in those cases. The only way to prevent this
  // behavior is to use your own try block.

  // This is especially useful to test the state of the system after the
  // exception is caught.

  assertTrue(systemUnderTest.isInErrorState());
}

Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final methods.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I had the same issue, don't know what is the reason behind it but i fixed by typing in terminal

svn update

and then I commit and boom it worked!

The imported project "C:\Microsoft.CSharp.targets" was not found

This is a global solution, not dependent on particular package or bin.

In my case, I removed Packages folder from my root directory.

Maybe it happens because of your packages are there but compiler is not finding it's reference. so remove older packages first and add new packages.

Steps to Add new packages

  • First remove, packages folder (it will be near by or one step up to your current project folder).
  • Then restart the project or solution.
  • Now, Rebuild solution file.
  • Project will get new references from nuGet package manager. And your issue will be resolved.

This is not proper solution, but I posted it here because I face same issue.

In my case, I wasn't even able to open my solution in visual studio and didn't get any help with other SO answers.

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

get specific row from spark dataframe

This Works for me in PySpark

df.select("column").collect()[0][0]

How do I set up HttpContent for my HttpClient PostAsync second parameter?

This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.

In summary, you can't directly set up an instance of HttpContent because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

Open URL in Java to get the content

String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));

SSH library for Java

http://code.google.com/p/connectbot/, Compile src\com\trilead\ssh2 on windows linux or android , it can create Local Port Forwarder or create Dynamic Port Forwarder or other else

Get selected row item in DataGrid WPF

if I select the second row -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText will be 646. This is VB, but you get it.

How to read numbers from file in Python?

Assuming you don't have extraneous whitespace:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

You could condense the last for loop into a nested list comprehension:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

Check if a class is derived from a generic class

JaredPar's code works but only for one level of inheritance. For unlimited levels of inheritance, use the following code

public bool IsTypeDerivedFromGenericType(Type typeToCheck, Type genericType)
{
    if (typeToCheck == typeof(object))
    {
        return false;
    }
    else if (typeToCheck == null)
    {
        return false;
    }
    else if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == genericType)
    {
        return true;
    }
    else
    {
        return IsTypeDerivedFromGenericType(typeToCheck.BaseType, genericType);
    }
}

How to make a link open multiple pages when clicked

You can open multiple windows on single click... Try this..

<a href="http://--" 
     onclick=" window.open('http://--','','width=700,height=700'); 
               window.open('http://--','','width=700,height=500'); ..// add more"
               >Click Here</a>`

Vertical Text Direction

This is a bit hacky but cross browser solution which requires no CSS

_x000D_
_x000D_
<div>
  <div>h</div>
  <div>e</div>
  <div>l</div>
  <div>l</div>
  <div>o</div>
<div>
_x000D_
_x000D_
_x000D_

How to add months to a date in JavaScript?

I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):

var one_month_from_your_date = your_date_object.add(1).month();

What's nice about datejs is that it handles edge cases, because technically you can do this using the native Date object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs has taken care of for you.

Plus it's open source!

Tensorflow import error: No module named 'tensorflow'

The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.

create a new separate environment in Anaconda dedicated to TensorFlow as follows:

conda create -n newenvt anaconda python=python_version

replace python_version by your python version

activate the new environment as follows:

activate newenvt

Then install tensorflow into the new environment (newenvt) as follows:

conda install tensorflow

Now you can check it by issuing the following python code and it will work fine.

import tensorflow

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

i solved this problem by changing jre required for server (in my case is tomcat). From Server tab in eclipse, double click on the server (in order to open page for server configuration), click on Runtime environment, then change JRE required

How can I generate an MD5 hash?

I have made this using php as follows

<?php
$goodtext = "Not found";
// If there is no parameter, this code is all skipped
if ( isset($_GET['md5']) ) {
    $time_pre = microtime(true);
    $md5 = $_GET['md5'];
    // This is our alphabet
    $txt = "0123456789";
    $show = 15;
    // Outer loop go go through the alphabet for the
    // first position in our "possible" pre-hash
    // text
    for($i=0; $i<strlen($txt); $i++ ) {
        $ch1 = $txt[$i];   // The first of two characters
        // Our inner loop Note the use of new variables
        // $j and $ch2 
        for($j=0; $j<strlen($txt); $j++ ) {
            $ch2 = $txt[$j];  // Our second character
            for($k=0; $k<strlen($txt); $k++ ) {
                $ch3 = $txt[$k];
                for($l=0; $l<strlen($txt); $l++){
                    $ch4 = $txt[$l];
                    // Concatenate the two characters together to 
                    // form the "possible" pre-hash text
                    $try = $ch1.$ch2.$ch3.$ch4;
                    // Run the hash and then check to see if we match
                    $check = hash('md5', $try);
                    if ( $check == $md5 ) {
                        $goodtext = $try;
                        break;   // Exit the inner loop
                    }
                    // Debug output until $show hits 0
                    if ( $show > 0 ) {
                        print "$check $try\n";
                        $show = $show - 1;
                    }
                    if($goodtext == $try){
                        break;
                    }
                }
                if($goodtext == $try){
                    break;
                }
            }
            if($goodtext == $try) {
                break;  
            }
        }
        if($goodtext == $try){
            break;
        }
    }
    // Compute ellapsed time
    $time_post = microtime(true);
    print "Ellapsed time: ";
    print $time_post-$time_pre;
    print "\n";
}
?>

you may refer this - source

jQuery event for images loaded

imagesLoaded Plugin is way to go ,if you need a crossbrowser solution

 $("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
 if($broken.length > 0){
 //Error CallBack
 console.log('Error');
 }
 else{
 // Load CallBack
 console.log('Load');
 }
 });

If You Just Need a IE WorkAround,This Will Do

 var img = $("<img>", {
    error: function() {console.log('error'); },
    load: function() {console.log('load');}
    });
  img.attr('src','image.jpg');

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How to subtract days from a plain Date?

var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;

How do I get my C# program to sleep for 50 msec?

There are basically 3 choices for waiting in (almost) any programming language:

  1. Loose waiting
    • Executing thread blocks for given time (= does not consume processing power)
    • No processing is possible on blocked/waiting thread
    • Not so precise
  2. Tight waiting (also called tight loop)
    • processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time)
    • Some actions can be performed while waiting
    • Very precise
  3. Combination of previous 2
    • It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.

for 1. - Loose waiting in C#:

Thread.Sleep(numberOfMilliseconds);

However, windows thread scheduler causes acccuracy of Sleep() to be around 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).

for 2. - Tight waiting in C# is:

Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
    //some other processing to do possible
    if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
    {
        break;
    }
}

We could also use DateTime.Now or other means of time measurement, but Stopwatch is much faster (and this would really become visible in tight loop).

for 3. - Combination:

Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
    //some other processing to do STILL POSSIBLE
    if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
    {
        break;
    }
    Thread.Sleep(1); //so processor can rest for a while
}

This code regularly blocks thread for 1ms (or slightly more, depending on OS thread scheduling), so processor is not busy for that time of blocking and code does not consume 100% of processor's power. Other processing can still be performed in-between blocking (such as: updating of UI, handling of events or doing interaction/communication stuff).

How to check the maximum number of allowed connections to an Oracle database?

Use gv$session for RAC, if you want get the total number of session across the cluster.

dlib installation on Windows 10

I have recently installed dlib on python 3.7. First I have installed cmake from anaconda navigator (cmake version 3.14.0) Next i installed visual studio 2019 and installed Desktop development with C++ . Then I do pip install dlib and now its working

How to check size of a file using Bash?

I would use du's --threshold for this. Not sure if this option is available in all versions of du but it is implemented in GNU's version.

Quoting from du(1)'s manual:

-t, --threshold=SIZE
       exclude entries smaller than SIZE if positive, or entries greater
       than SIZE if negative

Here's my solution, using du --threshold= for OP's use case:

THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
    mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
    mv -f /root/tmp/file.txt /var/www/file.txt
fi

The advantage of that, is that du can accept an argument to that option in a known format - either human as in 10K, 10MiB or what ever you feel comfortable with - you don't need to manually convert between formats / units since du handles that.

For reference, here's the explanation on this SIZE argument from the man page:

The SIZE argument is an integer and optional unit (example: 10K is 
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

How do I split a string, breaking at a particular character?

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

What is the difference between 'typedef' and 'using' in C++11?

Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int); is clearer than with typedef int (*T)(int, int);. Second is that template alias form is not possible with typedef. Third is that exposing C API would require typedef in public headers.

PHP mkdir: Permission denied problem

Since you are on a mac, you could add yourself to the _www (the apache user group) group on your mac:

sudo dseditgroup -o edit -a $USER -t user _www

and add _www user to the wheel group which seems to be what the mac creates files as:

sudo dseditgroup -o edit -a _www -t user wheel

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

Python Pandas - Find difference between two data frames

In addition to accepted answer, I would like to propose one more wider solution that can find a 2D set difference of two dataframes with any index/columns (they might not coincide for both datarames). Also method allows to setup tolerance for float elements for dataframe comparison (it uses np.isclose)


import numpy as np
import pandas as pd

def get_dataframe_setdiff2d(df_new: pd.DataFrame, 
                            df_old: pd.DataFrame, 
                            rtol=1e-03, atol=1e-05) -> pd.DataFrame:
    """Returns set difference of two pandas DataFrames"""

    union_index = np.union1d(df_new.index, df_old.index)
    union_columns = np.union1d(df_new.columns, df_old.columns)

    new = df_new.reindex(index=union_index, columns=union_columns)
    old = df_old.reindex(index=union_index, columns=union_columns)

    mask_diff = ~np.isclose(new, old, rtol, atol)

    df_bool = pd.DataFrame(mask_diff, union_index, union_columns)

    df_diff = pd.concat([new[df_bool].stack(),
                         old[df_bool].stack()], axis=1)

    df_diff.columns = ["New", "Old"]

    return df_diff

Example:

In [1]

df1 = pd.DataFrame({'A':[2,1,2],'C':[2,1,2]})
df2 = pd.DataFrame({'A':[1,1],'B':[1,1]})

print("df1:\n", df1, "\n")

print("df2:\n", df2, "\n")

diff = get_dataframe_setdiff2d(df1, df2)

print("diff:\n", diff, "\n")
Out [1]

df1:
   A  C
0  2  2
1  1  1
2  2  2 

df2:
   A  B
0  1  1
1  1  1 

diff:
     New  Old
0 A  2.0  1.0
  B  NaN  1.0
  C  2.0  NaN
1 B  NaN  1.0
  C  1.0  NaN
2 A  2.0  NaN
  C  2.0  NaN 

What's the difference between JavaScript and JScript?

JScript is Microsoft's equivalent of JavaScript.
Java is an Oracle product and used to be a Sun product.

Oracle bought Sun.

JavaScript + Microsoft = JScript

javascript get x and y coordinates on mouse click

simple solution is this:

game.js:

document.addEventListener('click', printMousePos, true);
function printMousePos(e){

      cursorX = e.pageX;
      cursorY= e.pageY;
      $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}

Hash and salt passwords in C#

Bah, this is better! http://sourceforge.net/projects/pwdtknet/ and it is better because ..... it performs Key Stretching AND uses HMACSHA512 :)

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

I got this error, while using it on my rocketchat to communicate with my gitlab via enterprise proxy,

Because, was using the https://:8080 but actually, it worked for http://:8080

How to convert empty spaces into null values, using SQL Server?

This code generates some SQL which can achieve this on every table and column in the database:

SELECT
   'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL 
   WHERE [' + COLUMN_NAME + '] = '''''
FROM 
    INFORMATION_SCHEMA.columns C
INNER JOIN
    INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE 
    DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'

Saving and Reading Bitmaps/Images from Internal memory in Android

// mutiple image retrieve

 File folPath = new File(getIntent().getStringExtra("folder_path"));
 File[] imagep = folPath.listFiles();

 for (int i = 0; i < imagep.length ; i++) {
     imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
 }
 imagesAdapter.notifyDataSetChanged();

How can I force input to uppercase in an ASP.NET textbox?

**I would do like:
<asp:TextBox ID="txtName" onkeyup="this.value=this.value.toUpperCase()" runat="server"></asp:TextBox>**

No submodule mapping found in .gitmodule for a path that's not a submodule

in the file .gitmodules, I replaced string

"path = thirdsrc\boost" 

with

"path = thirdsrc/boost", 

and it solved! - -

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

Check if user is using IE

I know this is an old question, but in case anyone comes across it again and has issues with detecting IE11, here is a working solution for all current versions of IE.

var isIE = false;
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
    isIE = true;   
}

How to comment out particular lines in a shell script

You can comment section of a script using a conditional.

For example, the following script:

DEBUG=false
if ${DEBUG}; then
echo 1
echo 2
echo 3
echo 4
echo 5
fi
echo 6
echo 7

would output:

6
7

In order to uncomment the section of the code, you simply need to comment the variable:

#DEBUG=false

(Doing so would print the numbers 1 through 7.)

Javascript objects: get parent

There is a more 'smooth' solution for this :)

var Foo = function(){
  this.par = 3;

  this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
    this.p = t;
    this.subFunction = function(){
      alert(this.p.par);
    }
  })(this);
}

var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;

myObj.par = 5;
myObj.sub.subFunction() // will popup 5;

SQL Server Installation - What is the Installation Media Folder?

If you are using an executable,

  • just run the executable (for example: "en_sql_server_2012_express_edition_with_advanced_services_x64.exe")
  • Navigate to the "options" tab
  • Copy the "Installation Media Root Directory" (should look something like the below snipping)
  • Paste it into the open "Browse for SQL server Installation Media" window

enter image description here

Save yourself the hastle of renaming and unzipping etc.!

What does principal end of an association means in 1:1 relationship in Entity framework

You can also use the [Required] data annotation attribute to solve this:

public class Foo
{
    public string FooId { get; set; }

    public Boo Boo { get; set; }
}

public class Boo
{
    public string BooId { get; set; }

    [Required]
    public Foo Foo {get; set; }
}

Foo is required for Boo.

global variable for all controller and views

Okay, I'm going to completely ignore the ridiculous amount of over engineering and assumptions that the other answers are rife with, and go with the simple option.

If you're okay for there to be a single database call during each request, then the method is simple, alarmingly so:

class BaseController extends \Controller
{

    protected $site_settings;

    public function __construct() 
    {
        // Fetch the Site Settings object
        $this->site_settings = Setting::all();
        View::share('site_settings', $this->site_settings);
    }

}

Now providing that all of your controllers extend this BaseController, they can just do $this->site_settings.

If you wish to limit the amount of queries across multiple requests, you could use a caching solution as previously provided, but based on your question, the simple answer is a class property.

Python - Get path of root project structure

I've recently been trying to do something similar and I have found these answers inadequate for my use cases (a distributed library that needs to detect project root). Mainly I've been battling different environments and platforms, and still haven't found something perfectly universal.

Code local to project

I've seen this example mentioned and used in a few places, Django, etc.

import os
print(os.path.dirname(os.path.abspath(__file__)))

Simple as this is, it only works when the file that the snippet is in is actually part of the project. We do not retrieve the project directory, but instead the snippet's directory

Similarly, the sys.modules approach breaks down when called from outside the entrypoint of the application, specifically I've observed a child thread cannot determine this without relation back to the 'main' module. I've explicitly put the import inside a function to demonstrate an import from a child thread, moving it to top level of app.py would fix it.

app/
|-- config
|   `-- __init__.py
|   `-- settings.py
`-- app.py

app.py

#!/usr/bin/env python
import threading


def background_setup():
    # Explicitly importing this from the context of the child thread
    from config import settings
    print(settings.ROOT_DIR)


# Spawn a thread to background preparation tasks
t = threading.Thread(target=background_setup)
t.start()

# Do other things during initialization

t.join()

# Ready to take traffic

settings.py

import os
import sys


ROOT_DIR = None


def setup():
    global ROOT_DIR
    ROOT_DIR = os.path.dirname(sys.modules['__main__'].__file__)
    # Do something slow

Running this program produces an attribute error:

>>> import main
>>> Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python2714\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python2714\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "main.py", line 6, in background_setup
    from config import settings
  File "config\settings.py", line 34, in <module>
    ROOT_DIR = get_root()
  File "config\settings.py", line 31, in get_root
    return os.path.dirname(sys.modules['__main__'].__file__)
AttributeError: 'module' object has no attribute '__file__'

...hence a threading-based solution

Location independent

Using the same application structure as before but modifying settings.py

import os
import sys
import inspect
import platform
import threading


ROOT_DIR = None


def setup():
    main_id = None
    for t in threading.enumerate():
        if t.name == 'MainThread':
            main_id = t.ident
            break

    if not main_id:
        raise RuntimeError("Main thread exited before execution")

    current_main_frame = sys._current_frames()[main_id]
    base_frame = inspect.getouterframes(current_main_frame)[-1]

    if platform.system() == 'Windows':
        filename = base_frame.filename
    else:
        filename = base_frame[0].f_code.co_filename

    global ROOT_DIR
    ROOT_DIR = os.path.dirname(os.path.abspath(filename))

Breaking this down: First we want to accurately find the thread ID of the main thread. In Python3.4+ the threading library has threading.main_thread() however, everybody doesn't use 3.4+ so we search through all threads looking for the main thread save it's ID. If the main thread has already exited, it won't be listed in the threading.enumerate(). We raise a RuntimeError() in this case until I find a better solution.

main_id = None
for t in threading.enumerate():
    if t.name == 'MainThread':
        main_id = t.ident
        break

if not main_id:
    raise RuntimeError("Main thread exited before execution")

Next we find the very first stack frame of the main thread. Using the cPython specific function sys._current_frames() we get a dictionary of every thread's current stack frame. Then utilizing inspect.getouterframes() we can retrieve the entire stack for the main thread and the very first frame. current_main_frame = sys._current_frames()[main_id] base_frame = inspect.getouterframes(current_main_frame)[-1] Finally, the differences between Windows and Linux implementations of inspect.getouterframes() need to be handled. Using the cleaned up filename, os.path.abspath() and os.path.dirname() clean things up.

if platform.system() == 'Windows':
    filename = base_frame.filename
else:
    filename = base_frame[0].f_code.co_filename

global ROOT_DIR
ROOT_DIR = os.path.dirname(os.path.abspath(filename))

So far I've tested this on Python2.7 and 3.6 on Windows as well as Python3.4 on WSL

ng-options with simple array init

You can use ng-repeat with option like this:

<form>
    <select ng-model="yourSelect" 
        ng-options="option as option for option in ['var1', 'var2', 'var3']"
        ng-init="yourSelect='var1'"></select>
    <input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>

When you submit your form you can get value of input hidden.


DEMO

ng-selected ng-repeat

insert datetime value in sql database with c#

INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')

No Network Security Config specified, using platform default - Android Log

I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.

android:usesCleartextTraffic="true"

Removing whitespace from strings in Java

\W means "non word character". The pattern for whitespace characters is \s. This is well documented in the Pattern javadoc.

PHP Configuration: It is not safe to rely on the system's timezone settings

I modified /etc/php.ini

[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone =('Asia/kolkata')

and now working fine.

Vipin Pal

Jquery : Refresh/Reload the page on clicking a button

If your button is loading from an AJAX call, you should use

$(document).on("click", ".delegate_update_success", function(){
    location.reload(true);
});

instead of

$( ".delegate_update_success" ).click(function() {
    location.reload();
});

Also note the true parameter for the location.reload function.

How to get the full path of running process?

By combining Sanjeevakumar Hiremath's and Jeff Mercado's answers you can actually in a way get around the problem when retrieving the icon from a 64-bit process in a 32-bit process.

using System;
using System.Management;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int processID = 6680;   // Change for the process you would like to use
            Process process = Process.GetProcessById(processID);
            string path = ProcessExecutablePath(process);
        }

        static private string ProcessExecutablePath(Process process)
        {
            try
            {
                return process.MainModule.FileName;
            }
            catch
            {
                string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

                foreach (ManagementObject item in searcher.Get())
                {
                    object id = item["ProcessID"];
                    object path = item["ExecutablePath"];

                    if (path != null && id.ToString() == process.Id.ToString())
                    {
                        return path.ToString();
                    }
                }
            }

            return "";
        }
    }
}

This may be a bit slow and doesn't work on every process which lacks a "valid" icon.

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

Extract directory path and filename

Use the basename command to extract the filename from the path:

[/tmp]$ export fspec=/exp/home1/abc.txt 
[/tmp]$ fname=`basename $fspec`
[/tmp]$ echo $fname
abc.txt

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Why is 2 * (i * i) faster than 2 * i * i in Java?

Interesting observation using Java 11 and switching off loop unrolling with the following VM option:

-XX:LoopUnrollLimit=0

The loop with the 2 * (i * i) expression results in more compact native code1:

L0001: add    eax,r11d
       inc    r8d
       mov    r11d,r8d
       imul   r11d,r8d
       shl    r11d,1h
       cmp    r8d,r10d
       jl     L0001

in comparison with the 2 * i * i version:

L0001: add    eax,r11d
       mov    r11d,r8d
       shl    r11d,1h
       add    r11d,2h
       inc    r8d
       imul   r11d,r8d
       cmp    r8d,r10d
       jl     L0001

Java version:

java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

Benchmark results:

Benchmark          (size)  Mode  Cnt    Score     Error  Units
LoopTest.fast  1000000000  avgt    5  694,868 ±  36,470  ms/op
LoopTest.slow  1000000000  avgt    5  769,840 ± 135,006  ms/op

Benchmark source code:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@Fork(1)
public class LoopTest {

    @Param("1000000000") private int size;

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
            .include(LoopTest.class.getSimpleName())
            .jvmArgs("-XX:LoopUnrollLimit=0")
            .build();
        new Runner(opt).run();
    }

    @Benchmark
    public int slow() {
        int n = 0;
        for (int i = 0; i < size; i++)
            n += 2 * i * i;
        return n;
    }

    @Benchmark
    public int fast() {
        int n = 0;
        for (int i = 0; i < size; i++)
            n += 2 * (i * i);
        return n;
    }
}

1 - VM options used: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:LoopUnrollLimit=0

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

Check if xdebug is working

Just to extend KsaRs answer and provide a possibility to check xdebug from command line:

php -r "echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';"

Convert an object to an XML string

 public static class XMLHelper
    {
        /// <summary>
        /// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
        /// </summary>
        /// <typeparam name="T">Ki?u d? li?u</typeparam>
        /// <param name="value">giá tr?</param>
        /// <param name="omitXmlDeclaration">b? qua declare</param>
        /// <param name="removeEncodingDeclaration">xóa encode declare</param>
        /// <returns>xml string</returns>
        public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                var xmlWriterSettings = new XmlWriterSettings
                {
                    Indent = true,
                    OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
                    Encoding = Encoding.UTF8,
                    NewLineChars = "", // remove \r\n
                };

                var xmlserializer = new XmlSerializer(typeof(T));

                using (var memoryStream = new MemoryStream())
                {
                    using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlserializer.Serialize(xmlWriter, value);
                        //return stringWriter.ToString();
                    }

                    memoryStream.Position = 0;
                    using (var sr = new StreamReader(memoryStream))
                    {
                        var pureResult = sr.ReadToEnd();
                        var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
                        if (omitEncodingDeclaration)
                            return resultAfterOmitEncoding;
                        return pureResult;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XMLSerialize error: ", ex);
            }
        }

        private static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);

            if (pos < 0)
            {
                return text;
            }

            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

Difference between static, auto, global and local variable in the context of c and c++

There are two separate concepts here:

  • scope, which determines where a name can be accessed, and
  • storage duration, which determines when a variable is created and destroyed.

Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:

void f() {
    int i;
    i = 1; // OK: in scope
}
void g() {
    i = 2; // Error: not in scope
}

Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:

int i;
void f() {
    i = 1; // OK: in scope
}
void g() {
    i = 2; // OK: still in scope
}

(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)

Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.

for (int i = 0; i < 5; ++i) {
    int n = 0;
    printf("%d ", ++n);  // prints 1 1 1 1 1  - the previous value is lost
}

Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.

for (int i = 0; i < 5; ++i) {
    static int n = 0;
    printf("%d ", ++n);  // prints 1 2 3 4 5  - the value persists
}

Note that the static keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.

How to make button look like a link?

_x000D_
_x000D_
button {_x000D_
  background: none!important;_x000D_
  border: none;_x000D_
  padding: 0!important;_x000D_
  /*optional*/_x000D_
  font-family: arial, sans-serif;_x000D_
  /*input has OS specific font-family*/_x000D_
  color: #069;_x000D_
  text-decoration: underline;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<button> your button that looks like a link</button>
_x000D_
_x000D_
_x000D_

Instagram: Share photo from webpage

As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.

Good luck.

Sorting Directory.GetFiles()

From msdn:

The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.

The Sort() method is the standard Array.Sort(), which takes in IComparables (among other overloads), so if you sort by creation date, it will handle localization based on the machine settings.

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

Very simple C# CSV reader

You can try the some thing like the below LINQ snippet.

string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");

    var query = from line in allLines
                let data = line.Split(',')
                select new
                {
                    Device = data[0],
                    SignalStrength = data[1],
                    Location = data[2], 
                    Time = data[3],
                    Age = Convert.ToInt16(data[4])
                };

UPDATE: Over a period of time, things evolved. As of now, I would prefer to use this library http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx

Can we set a Git default to fetch all tags during a remote pull?

You should be able to accomplish this by adding a refspec for tags to your local config. Concretely:

[remote "upstream"]
    url = <redacted>
    fetch = +refs/heads/*:refs/remotes/upstream/*
    fetch = +refs/tags/*:refs/tags/*

Better way to set distance between flexbox items

Well, the simplest solution regarding to your CSS, imo, is to add spacers into HTML:

<div id='box'>
  <div class='item'></div>
  <div style='width: 5px;'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

so, you may control it with inline-style or class names.. sometimes, it's also possible to do spacing with padding.

here is the example

how to convert rgb color to int in java

If you are developing for Android, Color's method for this is rgb(int, int, int)

So you would do something like

myPaint.setColor(Color.rgb(int, int, int)); 

For retrieving the individual color values you can use the methods for doing so:

Color.red(int color) 
Color.blue(int color) 
Color.green(int color) 

Refer to this document for more info

Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

Calling a phone number in swift

For Swift 4.2 and above

if let phoneCallURL = URL(string: "tel://\(01234567)"), UIApplication.shared.canOpenURL(phoneCallURL)
{
    UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}

Create tap-able "links" in the NSAttributedString of a UILabel?

I'd strongly recommend using a library that automatically detects URLs in text and converts them to links. Try:

Both are under MIT license.

Are there any free Xml Diff/Merge tools available?

KDiff3 is not XML specific, but it is free. It does a nice job of comparing and merging text files.

How to change background color in android app

Simplest way

android:background="@android:color/white"

No need to define anything. It uses predefined colors in android.R.

Slide right to left Android Animations

<translate
    android:fromXDelta="100%p"
    android:toXDelta="0%p"
    android:duration="500" />

$(document).click() not working correctly on iPhone. jquery

Change this:

$(document).click( function () {

To this

$(document).on('click touchstart', function () {

Maybe this solution don't fit on your work and like described on the replies this is not the best solution to apply. Please, check another fixes from another users.

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

You can obtain all of the parameters from the confusion matrix. The structure of the confusion matrix(which is 2X2 matrix) is as follows (assuming the first index is related to the positive label, and the rows are related to the true labels):

TP|FN
FP|TN

So

TP = cm[0][0]
FN = cm[0][1]
FP = cm[1][0]
TN = cm[1][1]

More details at https://en.wikipedia.org/wiki/Confusion_matrix

How to implement a Keyword Search in MySQL?

You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches

This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.

Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching

In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:

SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance  FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;

I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.

Depending in your criterias you can use either options.

No server in Eclipse; trying to install Tomcat

Steps to follow:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters Extensions
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

Python/Json:Expecting property name enclosed in double quotes

For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:

import json 

predictions = []

def get_top_k_predictions(predictions_path):
    '''load the predictions'''
    
    with open (predictions_path) as json_lines_file:
        for line in json_lines_file:
            predictions.append(json.loads(line.replace("'", "\"")))
            
    
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")

Passing by reference in C

pointers and references are two different thigngs.

A couple of things I have not seen mentioned.

A pointer is the address of something. A pointer can be stored and copied like any other variable. It thus have a size.

A reference should be seen as an ALIAS of something. It does not have a size and cannot be stored. It MUST reference something, ie. it cannot be null or changed. Well, sometimes the compiler needs to store the reference as a pointer, but that is an implementation detail.

With references you don't have the issues with pointers, like ownership handling, null checking, de-referencing on use.

Change the color of a checked menu item in a navigation drawer

I believe app:itemBackground expects a drawable. So follow the steps below :

Make a drawable file highlight_color.xml with following contents :

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>

Make another drawable file nav_item_drawable.xml with following contents:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>

Finally add app:itemBackground tag in the NavView :

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">

here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.

This worked for me. Hopefully this will help.

********************************************** UPDATED **********************************************

Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.

So what you can do is, you can define a ThemeOverlay in the styles.xml for the NavigationView like this :

    <style name="ThemeOverlay.AppCompat.navTheme">

        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/color_of_your_choice</item> 

        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/color_of_your_choice</item> 

    </style>

now apply this ThemeOverlay to app:theme attribute of NavigationView, like this:

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">

I hope this will help.

What represents a double in sql server?

float is the closest equivalent.

SqlDbType Enumeration

For Lat/Long as OP mentioned.

A metre is 1/40,000,000 of the latitude, 1 second is around 30 metres. Float/double give you 15 significant figures. With some quick and dodgy mental arithmetic... the rounding/approximation errors would be the about the length of this fill stop -> "."

Proper usage of Optional.ifPresent()

Why write complicated code when you could make it simple?

Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...

if (user.isPresent())
{
    doSomethingWithUser(user.get());
}

This code has the advantages of being

  1. readable
  2. easy to debug (breakpoint)
  3. not tricky

Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

print data['places']['latitude']

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

print data['places'][0]['post code']

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Sorting arrays in javascript by object key value

Not spectacular different than the answers already given, but more generic is :

sortArrayOfObjects = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] - b[key];
    });
};

sortArrayOfObjects(yourArray, "distance");

"Strict Standards: Only variables should be passed by reference" error

This should be OK

   $value = explode(".", $value);
   $extension = strtolower(array_pop($value));   //Line 32
   // the file name is before the last "."
   $fileName = array_shift($value);  //Line 34

ImportError: cannot import name main when running pip --version command in windows7 32 bit

I had the same problem, but uninstall and reinstall with apt and pip didn't work for me.

I saw another solution that presents a easy way to recover pip3 path:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

href overrides ng-click in Angular.js

//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($scope.data, function(value, key) {
     //add new value to object
    value.new_url  = "your url";
});

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>