Programs & Examples On #Settings bundle

Unstage a deleted file in git

Assuming you're wanting to undo the effects of git rm <file> or rm <file> followed by git add -A or something similar:

# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>

To undo git add <file>, the first line above suffices, assuming you haven't committed yet.

How to know user has clicked "X" or the "Close" button?

It determines when to close the application if a form is closed (if your application is not attached to a specific form).

    private void MyForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (Application.OpenForms.Count == 0) Application.Exit();
    }

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

How do I change the select box arrow

You can skip the container or background image with pure css arrow:

select {

  /* make arrow and background */

  background:
    linear-gradient(45deg, transparent 50%, blue 50%),
    linear-gradient(135deg, blue 50%, transparent 50%),
    linear-gradient(to right, skyblue, skyblue);
  background-position:
    calc(100% - 21px) calc(1em + 2px),
    calc(100% - 16px) calc(1em + 2px),
    100% 0;
  background-size:
    5px 5px,
    5px 5px,
    2.5em 2.5em;
  background-repeat: no-repeat;

  /* styling and reset */

  border: thin solid blue;
  font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
  line-height: 1.5em;
  padding: 0.5em 3.5em 0.5em 1em;

  /* reset */

  border-radius: 0;
  margin: 0;      
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-appearance:none;
  -moz-appearance:none;
}

Sample here

assign value using linq

It can be done this way as well

foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                {
                    //do your stuff here
                    company.Id= 2;
                    company.Name= "Sample"
                }

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

How do you check what version of SQL Server for a database using TSQL?

Try

SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber

For more information see: Querying for version/edition info

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Android: ProgressDialog.show() crashes with getApplicationContext

I don't think this is a timing issue around a null application context

Try extending Application within your app (or just use it if you already have)

public class MyApp extends Application

Make the instance available as a private singleton. This is never null

private static MyApp appInstance;

Make a static helper in MyApp (which will use the singleton)

    public static void showProgressDialog( CharSequence title, CharSequence message )
{
    prog = ProgressDialog.show(appInstance, title, message, true); // Never Do This!
}

BOOM!!

Also, check out android engineer's answer here: WindowManager$BadTokenException

One cause of this error may be trying to display an application window/dialog through a Context that is not an Activity.

Now, i agree, it does not make sense that the method takes a Context param, instead of Activity..

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

What is the purpose of using -pedantic in GCC/G++ compiler?

I use it all the time in my coding.

The -ansi flag is equivalent to -std=c89. As noted, it turns off some extensions of GCC. Adding -pedantic turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.

The Eclipse executable launcher was unable to locate its companion launcher jar windows

Windows 8 follow these 3 steps:

  1. Locate eclipse file.
  2. create shortcut on desktop.
  3. Double click on the eclipse shortcut to open the application.

'mvn' is not recognized as an internal or external command,

On my Windows 7 machine I have the following environment variables:

  • JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07

  • M2_HOME=C:\apache-maven-3.0.3

On my PATH variable, I have (among others) the following:

  • %JAVA_HOME%\bin;%M2_HOME%\bin

I tried doing what you've done with %M2% having the nested %M2_HOME% and it also works.

Text Progress Bar in the Console

With the great advices above I work out the progress bar.

However I would like to point out some shortcomings

  1. Every time the progress bar is flushed, it will start on a new line

    print('\r[{0}]{1}%'.format('#' * progress* 10, progress))  
    

    like this:
    [] 0%
    [#]10%
    [##]20%
    [###]30%

2.The square bracket ']' and the percent number on the right side shift right as the '###' get longer.
3. An error will occur if the expression 'progress / 10' can not return an integer.

And the following code will fix the problem above.

def update_progress(progress, total):  
    print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')

Generating random number between 1 and 10 in Bash Shell Script

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.

 echo $RANDOM % 10 + 1 | bc

Changing :hover to touch/click for mobile devices

I think this simple method can achieve this goal. With CSS you can turn off pointer event to 'none' then use jQuery to switch classes.

_x000D_
_x000D_
.item{_x000D_
   pointer-events:none;_x000D_
 }_x000D_
_x000D_
.item.clicked{_x000D_
   pointer-events:inherit;_x000D_
 }_x000D_
 _x000D_
.item:hover,.item:active{_x000D_
  /* Your Style On Hover Converted to Tap*/_x000D_
  background:#000;_x000D_
}
_x000D_
_x000D_
_x000D_

Use jQuery to switch classed:

_x000D_
_x000D_
jQuery('.item').click(function(e){_x000D_
  e.preventDefault();_x000D_
  $(this).addClass('clicked')l_x000D_
});
_x000D_
_x000D_
_x000D_

PHP - Get bool to echo false when false

json_encode will do it out-of-the-box, but it's not pretty (indented, etc):

echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));

...gives...

{"whatever":true,"somethingelse":false}

Meaning of 'const' last in a function declaration of a class?

I would like to add the following point.

You can also make it a const & and const &&

So,

struct s{
    void val1() const {
     // *this is const here. Hence this function cannot modify any member of *this
    }
    void val2() const & {
    // *this is const& here
    }
    void val3() const && {
    // The object calling this function should be const rvalue only.
    }
    void val4() && {
    // The object calling this function should be rvalue reference only.
    }

};

int main(){
  s a;
  a.val1(); //okay
  a.val2(); //okay
  // a.val3() not okay, a is not rvalue will be okay if called like
  std::move(a).val3(); // okay, move makes it a rvalue
}

Feel free to improve the answer. I am no expert

Formatting a float to 2 decimal places

I believe:

String.Format("{0:0.00}",Sale);

Should do it.

See Link String Format Examples C#

How to import JSON File into a TypeScript file?

For Angular 7+,

1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):

declare module "*.json" {
    const value: any;
    export default value;
}

2) import and access JSON data either:

import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data.default);
    }

}

or:

import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data);
    }

}

Android OnClickListener - identify a button

Button mybutton = new Button(ViewPagerSample.this);
mybutton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

mySQL :: insert into table, data from another table?

This query is for add data from one table to another table using foreign key

let qry = "INSERT INTO `tb_customer_master` (`My_Referral_Code`, `City_Id`, `Cust_Name`, `Reg_Date_Time`, `Mobile_Number`, `Email_Id`, `Gender`, `Cust_Age`, `Profile_Image`, `Token`, `App_Type`, `Refer_By_Referral_Code`, `Status`) values ('" + randomstring.generate(7) + "', '" + req.body.City_Id + "', '" + req.body.Cust_Name + "', '" + req.body.Reg_Date_Time + "','" + req.body.Mobile_Number + "','" + req.body.Email_Id + "','" + req.body.Gender + "','" + req.body.Cust_Age + "','" + req.body.Profile_Image + "','" + req.body.Token + "','" + req.body.App_Type + "','" + req.body.Refer_By_Referral_Code + "','" + req.body.Status + "')";
                        connection.query(qry, (err, rows) => {
                            if (err) { res.send(err) } else {
                                let insert = "INSERT INTO `tb_customer_and_transaction_master` (`Cust_Id`)values ('" + rows.insertId + "')";
                                connection.query(insert, (err) => {
                                    if (err) {
                                        res.json(err)
                                    } else {
                                        res.json("Customer added")
                                    }
                                })
                            }
    
    
                        })
                    }
                }
    
            }
        })
    })

laravel compact() and ->with()

the best way for me :

    $data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
      ];
return View::make('view',$data);

Get unique values from arraylist in java

ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique

Python calling method in class

Could someone explain to me, how to call the move method with the variable RIGHT

>>> myMissile = MissileDevice(myBattery)  # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)

If you have programmed in any other language with classes, besides python, this sort of thing

class Foo:
    bar = "baz"

is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar, above, you can just call it Foo.bar; you can also access class attributes through instances of the class, like Foo().bar.


Im utterly baffled about what 'self' refers too,

>>> class Foo:
...     def quux(self):
...         print self
...         print self.bar
...     bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>

When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

How can I force clients to refresh JavaScript files?

For ASP.NET I suppose next solution with advanced options (debug/release mode, versions):

Js or Css files included by such way:

<script type="text/javascript" src="Scripts/exampleScript<%=Global.JsPostfix%>" />
<link rel="stylesheet" type="text/css" href="Css/exampleCss<%=Global.CssPostfix%>" />

Global.JsPostfix and Global.CssPostfix is calculated by the following way in Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    ...
    string jsVersion = ConfigurationManager.AppSettings["JsVersion"];
    bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings["UpdateJsEveryAppStart"]);
    int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;
    JsPostfix = "";
#if !DEBUG
    JsPostfix += ".min";
#endif      
    JsPostfix += ".js?" + jsVersion + "_" + buildNumber;
    if (updateEveryAppStart)
    {
        Random rand = new Random();
        JsPosfix += "_" + rand.Next();
    }
    ...
}

Get Return Value from Stored procedure in asp.net

You need a parameter with Direction set to ParameterDirection.ReturnValue in code but no need to add an extra parameter in SP. Try this

  SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
  returnParameter.Direction = ParameterDirection.ReturnValue;
  cmd.ExecuteNonQuery();

  int id = (int) returnParameter.Value;

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .

How to capture UIView to UIImage without loss of quality on retina display

Swift 2.0:

Using extension method:

extension UIImage{

   class func renderUIViewToImage(viewToBeRendered:UIView?) -> UIImage
   {
       UIGraphicsBeginImageContextWithOptions((viewToBeRendered?.bounds.size)!, false, 0.0)
       viewToBeRendered!.drawViewHierarchyInRect(viewToBeRendered!.bounds, afterScreenUpdates: true)
       viewToBeRendered!.layer.renderInContext(UIGraphicsGetCurrentContext()!)

       let finalImage = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()

       return finalImage
   }

}

Usage:

override func viewDidLoad() {
    super.viewDidLoad()

    //Sample View To Self.view
    let sampleView = UIView(frame: CGRectMake(100,100,200,200))
    sampleView.backgroundColor =  UIColor(patternImage: UIImage(named: "ic_120x120")!)
    self.view.addSubview(sampleView)    

    //ImageView With Image
    let sampleImageView = UIImageView(frame: CGRectMake(100,400,200,200))

    //sampleView is rendered to sampleImage
    var sampleImage = UIImage.renderUIViewToImage(sampleView)

    sampleImageView.image = sampleImage
    self.view.addSubview(sampleImageView)

 }

How to implement Android Pull-to-Refresh

I think the best library is : https://github.com/chrisbanes/Android-PullToRefresh.

Works with:

ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

How to manually deploy artifacts in Nexus Repository Manager OSS 3

For Windows:

mvn deploy:deploy-file -DgroupId=joda-time -DartifactId=joda-time -Dversion=2.7 -Dpackaging=jar -Dfile=joda-time-2.7.jar 
-DgeneratePom=true -DrepositoryId=[Your ID] -Durl=[YourURL]

What do these three dots in React do?

This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:

let array = [1,2,3]
let array2 = [...array]
// array2 is now filled with the items from array

And with an object/keys:

// lets pass an object as props to a react component
let myParameters = {myKey: 5, myOtherKey: 7}
let component = <MyComponent {...myParameters}/>
// this is equal to <MyComponent myKey=5 myOtherKey=7 />

What's really cool is you can use it to mean "the rest of the values".

const myFunc = (value1, value2, ...values) {
    // Some code
}

myFunc(1, 2, 3, 4, 5)
// when myFunc is called, the rest of the variables are placed into the "values" array

use jQuery's find() on JSON object

The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/or map methods. Probably not much better than using $.each

jQuery.grep(TestObj, function(obj) {
    return obj.id === "A";
});

or

jQuery.map(TestObj, function(obj) {
    if(obj.id === "A")
         return obj; // or return obj.name, whatever.
});

Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.

But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.

function getObjects(obj, key, val) {
    var retv = [];

    if(jQuery.isPlainObject(obj))
    {
        if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
            retv.push(obj);

        var objects = jQuery.grep(obj, function(elem) {
            return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
        });

        retv.concat(jQuery.map(objects, function(elem){
            return getObjects(elem, key, val);
        }));
    }

    return retv;
}

Essentially the same as Box9's answer, but using the jQuery utility functions where useful.

········

Removing body margin in CSS

This should help you get rid of body margins and default top margin of <h1> tag

body{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

Override back button to act like home button

Working example..

Make sure don't call super.onBackPressed();

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background

Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed

How to check if spark dataframe is empty?

For Spark 2.1.0, my suggestion would be to use head(n: Int) or take(n: Int) with isEmpty, whichever one has the clearest intent to you.

df.head(1).isEmpty
df.take(1).isEmpty

with Python equivalent:

len(df.head(1)) == 0  # or bool(df.head(1))
len(df.take(1)) == 0  # or bool(df.take(1))

Using df.first() and df.head() will both return the java.util.NoSuchElementException if the DataFrame is empty. first() calls head() directly, which calls head(1).head.

def first(): T = head()
def head(): T = head(1).head

head(1) returns an Array, so taking head on that Array causes the java.util.NoSuchElementException when the DataFrame is empty.

def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)

So instead of calling head(), use head(1) directly to get the array and then you can use isEmpty.

take(n) is also equivalent to head(n)...

def take(n: Int): Array[T] = head(n)

And limit(1).collect() is equivalent to head(1) (notice limit(n).queryExecution in the head(n: Int) method), so the following are all equivalent, at least from what I can tell, and you won't have to catch a java.util.NoSuchElementException exception when the DataFrame is empty.

df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty

I know this is an older question so hopefully it will help someone using a newer version of Spark.

How can I see what I am about to push with git?

For a list of files to be pushed, run:

git diff --stat --cached [remote/branch]

example:

git diff --stat --cached origin/master

For the code diff of the files to be pushed, run:

git diff [remote repo/branch]

To see full file paths of the files that will change, run:

git diff --numstat [remote repo/branch]

If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.

Android Webview - Completely Clear the Cache

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db")

Did the trick

Using if elif fi in shell scripts

Josh Lee's answer works, but you can use the "&&" operator for better readability like this:

echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then 
    echo "Two of the provided args are equal."
    exit 3
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
then
    echo "All of the specified args are equal"
    exit 0
else
    echo "All of the specified args are different"
    exit 4 
fi

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

How to upload file using Selenium WebDriver in Java

First make sure that the input element is visible

As stated by Mark Collin in the discussion here:

Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.

Instead you can use:

driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");

myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.

Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

Windows command to get service status?

according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.

Android Debug Bridge (adb) device - no permissions

...the OP’s own answer is wrong in so far, that there are no “special system permissions”. – The “no permission” problem boils down to ... no permissions.

Unfortunately it is not easy to debug, because adb makes it a secret which device it tries to access! On Linux, it tries to open the “USB serial converter” device of the phone, which is e.g. /dev/bus/usb/001/115 (your bus number and device address will vary). This is sometimes linked and used from /dev/android_adb.

lsusb will help to find bus number and device address. Beware that the device address will change for sure if you re-plug, as might the bus number if the port gets confused about which speed to use (e.g. one physical port ends up on one logical bus or another).

An lsusb-line looks similar to this: Bus 001 Device 115: ID 4321:fedc bla bla bla

lsusb -v might help you to find the device if the “bla bla bla” is not hint enough (sometimes it does neither contain the manufacturer, nor the model of the phone).

Once you know the device, check with your own eyes that ls -a /dev/bus/usb/001/115 is really accessible for the user in question! Then check that it works with chmod and fix your udev setup.

PS1: /dev/android_adb can only point to one device, so make sure it does what you want.

PS2: Unrelated to this question, but less well known: adb has a fixed list of vendor ids it goes through. This list can be extended from ~/.android/adb_usb.ini, which should contain 0x4321 (if we follow my example lsusb line from above). – Not needed here, as you don’t even get a “no permissions” if the vendor id is not known.

Passing additional variables from command line to make

it seems

command args overwrite environment variable

Makefile

send:
    echo $(MESSAGE1) $(MESSAGE2)

Run example

$ MESSAGE1=YES MESSAGE2=NG  make send MESSAGE2=OK
echo YES OK
YES OK

CORS with POSTMAN

As @Musa comments it, it seems that the reason is that:

Postman doesn't care about SOP, it's a dev tool not a browser

By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).

Check here if you want to learn more about Cross-Origin and why it's working for extensions.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

   Class.forName("oracle.jdbc.driver.OracleDriver");

This line causes ClassNotFoundException, because you haven't placed ojdbc14.jar file in your lib folder of the project. or YOu haven't set the classpath of the required jar

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

How to uncommit my last commit in Git

git reset --soft HEAD^ Will keep the modified changes in your working tree.

git reset --hard HEAD^ WILL THROW AWAY THE CHANGES YOU MADE !!!

How to find out the location of currently used MySQL configuration file in linux

If you are using terminal just type the following:

locate my.cnf

CodeIgniter -> Get current URL relative to base url

For the parameter or without parameter URLs Use this :

Method 1:

 $currentURL = current_url(); //for simple URL
 $params = $_SERVER['QUERY_STRING']; //for parameters
 $fullURL = $currentURL . '?' . $params; //full URL with parameter

Method 2:

$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Method 3:

base_url(uri_string());

AngularJS - Create a directive that uses ng-model

Since Angular 1.5 it's possible to use Components. Components are the-way-to-go and solves this problem easy.

<myComponent data-ng-model="$ctrl.result"></myComponent>

app.component("myComponent", {
    templateUrl: "yourTemplate.html",
    controller: YourController,
    bindings: {
        ngModel: "="
    }
});

Inside YourController all you need to do is:

this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed

Angular IE Caching issue for $http

I get it resolved appending datetime as an random number:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

Fetch API with Cookie

In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'

Sample JSON fetch request:

fetch(url, {
  method: 'GET',
  credentials: 'include'
})
  .then((response) => response.json())
  .then((json) => {
    console.log('Gotcha');
  }).catch((err) => {
    console.log(err);
});

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

Creating .pem file for APNS?

->> Apple's own tutorial <<- is the only working set of instructions I've come across. It's straight forward and I can confirm it works brilliantly on both a linux php server and a windows php server.

You can find their 5-step pem creation process right at the bottom of the page.

How to check if JavaScript object is JSON

I wrote an npm module to solve this problem. It's available here:

object-types: a module for finding what literal types underly objects

Install

  npm install --save object-types


Usage

const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

C# 4.0 optional out/ref arguments

What about like this?

public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
    return true;
}

You still have to pass a value to the parameter from C# but it is an optional ref param.

Show and hide a View with a slide up/down animation

Suragch's answer in Kotlin. This worked for me.

class MainActivity : AppCompatActivity() {

var isUp: Boolean = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var myView: View = findViewById(R.id.my_view)
    var myButton: Button = findViewById(R.id.my_button)

    //Initialize as invisible
    myView.visibility = View.INVISIBLE
    myButton.setText("Slide up")

    isUp = false

}


fun View.slideUp(duration: Int = 500){
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, this.height.toFloat(), 0f)
    animate.duration = duration.toLong()
    animate.fillAfter = true
    this.startAnimation(animate)
}

fun View.slideDown(duration: Int = 500) {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, 0f, this.height.toFloat())
    animate.duration = duration.toLong()
    animate.fillAfter = true
    this.startAnimation(animate)
}

fun onSlideViewButtonClick(view: View){
    if(isUp){
        my_view.slideDown()
        my_button.setText("Slide Up")

    }
    else{
        my_view.slideUp()
        my_button.setText("Slide Down")
    }
    isUp = !isUp
}

}

Why is sed not recognizing \t as a tab?

You don't need to use sed to do a substitution when in actual fact, you just want to insert a tab in front of the line. Substitution for this case is an expensive operation as compared to just printing it out, especially when you are working with big files. Its easier to read too as its not regex.

eg using awk

awk '{print "\t"$0}' $filename > temp && mv temp $filename

Nesting CSS classes

No.

You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.

See also my article on CSS inheritance.

How do you convert an entire directory with ffmpeg?

This will create mp4 video from all the jpg files from current directory.

echo exec("ffmpeg -framerate 1/5 -i photo%d.jpg -r 25 -pix_fmt yuv420p output.mp4");

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

<SELECT multiple> - how to allow only one item selected?

Just don't make it a select multiple, but set a size to it, such as:

  <select name="user" id="userID" size="3">
    <option>John</option>
    <option>Paul</option>
    <option>Ringo</option>
    <option>George</option>
  </select>

Working example: https://jsfiddle.net/q2vo8nge/

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

Angularjs on page load call function

    var someVr= element[0].querySelector('#showSelector');
        myfunction(){
        alert("hi");
        }   
        angular.element(someVr).ready(function () {
           myfunction();
            });

This will do the job.

Detect all Firefox versions in JS

For a long time I have used the alternative:

('netscape' in window) && / rv:/.test(navigator.userAgent)

because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.

Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

How can I add new array elements at the beginning of an array in Javascript?

you can first reverse array and then add elem to array then reverse back it.

const arr = [2,3,4,5,6];
const arr2 = 1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

console.log(arr.reverse()); // [1,2,3,4,5,6]

good lock

ali alizadeh.

What's the best way to check if a String represents an integer in Java?

For kotlin, isDigitsOnly() (Also for Java's TextUtils.isDigitsOnly()) of String always returns false it has a negative sign in front though the rest of the character is digit only. For example -

/** For kotlin*/
var str = "-123" 
str.isDigitsOnly()  //Result will be false 

/** For Java */
String str = "-123"
TextUtils.isDigitsOnly(str) //Result will be also false 

So I made a quick fix by this -

 var isDigit=str.matches("-?\\d+(\\.\\d+)?".toRegex()) 
/** Result will be true for now*/

How can I change the Java Runtime Version on Windows (7)?

Go to control panel --> Java You can select the active version here

Sort a list of tuples by 2nd item (integer value)

The fact that the sort values in the OP are integers isn't relevant to the question per se. In other words, the accepted answer would work if the sort value was text. I bring this up to also point out that the sort can be modified during the sort (for example, to account for upper and lower case).

>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: x[1])
[(148, 'ABC'), (221, 'DEF'), (121, 'abc'), (231, 'def')]
>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: str.lower(x[1]))
[(121, 'abc'), (148, 'ABC'), (231, 'def'), (221, 'DEF')]

how to pass list as parameter in function

You should always avoid using List<T> as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List first.

Converting an IEnumerable into a List costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.

TL;DR you should always use a proper interface like IEnumerable or IQueryable based on what do you want to do with your collection. ;)

In your case:

public void foo(IEnumerable<DateTime> dateTimes)
{
}

How to scroll to bottom in a ScrollView on activity startup

After initializing your UI component and fill it with data. add those line to your on create method

Runnable runnable=new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };
    scrollView.post(runnable);

mysql error 1364 Field doesn't have a default values

This is caused by the STRICT_TRANS_TABLES SQL mode defined in the

%PROGRAMDATA%\MySQL\MySQL Server 5.6\my.ini

file. Removing that setting and restarting MySQL should fix the problem.

See https://www.farbeyondcode.com/Solution-for-MariaDB-Field--xxx--doesn-t-have-a-default-value-5-2720.html

If editing that file doesn't fix the issue, see http://dev.mysql.com/doc/refman/5.6/en/option-files.html for other possible locations of config files.

How to access parameters in a Parameterized Build?

Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:

getBinding().hasVariable("MY_PARAM")

Is not working anymore. Please try this instead:

def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false

Prevent BODY from scrolling when a modal is opened

Try this code:

$('.entry_details').dialog({
    width:800,
    height:500,
    draggable: true,
    title: entry.short_description,
    closeText: "Zamknij",
    open: function(){
        //    blokowanie scrolla dla body
        var body_scroll = $(window).scrollTop();
        $(window).on('scroll', function(){
            $(document).scrollTop(body_scroll);
        });
    },
    close: function(){
        $(window).off('scroll');
    }
}); 

How can I check if a checkbox is checked?

You can try this:

if ($(#remember).is(':checked')){
   alert('checked');
}else{
   alert('not checked')
}

Maintain image aspect ratio when changing height

I just had the same issue. Use the flex align to center your elements. You need to use align-items: center instead of align-content: center. This will maintain the aspect ratio, while align-content will not keep the aspect ratio.

How to log Apache CXF Soap Request and Soap Response using Log4j?

Another easy way is to set the logger like this- ensure that you do it before you load the cxf web service related classes. You can use it in some static blocks.

YourClientConstructor() {

  LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);

  URL wsdlURL = YOurURL;//

  //create the service
  YourService = new YourService(wsdlURL, SERVICE_NAME);
  port = yourService.getServicePort(); 

  Client client = ClientProxy.getClient(port);
  client.getInInterceptors().add(new LoggingInInterceptor());
  client.getOutInterceptors().add(new LoggingOutInterceptor());
}

Then the inbound and outbound messages will be printed to Log4j file instead of the console. Make sure your log4j is configured properly

How to pass arguments to a Button command in Tkinter?

I personally prefer to use lambdas in such a scenario, because imo it's clearer and simpler and also doesn't force you to write lots of wrapper methods if you don't have control over the called method, but that's certainly a matter of taste.

That's how you'd do it with a lambda (note there's also some implementation of currying in the functional module, so you can use that too):

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

Underscore prefix for property and method names in JavaScript

That's only a convention. The Javascript language does not give any special meaning to identifiers starting with underscore characters.

That said, it's quite a useful convention for a language that doesn't support encapsulation out of the box. Although there is no way to prevent someone from abusing your classes' implementations, at least it does clarify your intent, and documents such behavior as being wrong in the first place.

How do I load the contents of a text file into a javascript variable?

If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

How to sort a List of objects by their date (java collections, List<Object>)

You can use this:

Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());

What are the differences between a superkey and a candidate key?

A super key is any combination of columns that uniquely identifies a row in a table. A candidate key is a super key which cannot have any columns removed from it without losing the unique identification property. This property is sometimes known as minimality or (better) irreducibility.

A super key ? a primary key in general. The primary key is simply a candidate key chosen to be the main key. However, in dependency theory, candidate keys are important and the primary key is not more important than any of the other candidate keys. Non-primary candidate keys are also known as alternative keys.

Consider this table of Elements:

CREATE TABLE elements
(
    atomic_number   INTEGER NOT NULL PRIMARY KEY
                    CHECK (atomic_number > 0 AND atomic_number < 120),
    symbol          CHAR(3) NOT NULL UNIQUE,
    name            CHAR(20) NOT NULL UNIQUE,
    atomic_weight   DECIMAL(8,4) NOT NULL,
    period          SMALLINT NOT NULL
                    CHECK (period BETWEEN 1 AND 7),
    group           CHAR(2) NOT NULL
                    -- 'L' for Lanthanoids, 'A' for Actinoids
                    CHECK (group IN ('1', '2', 'L', 'A', '3', '4', '5', '6',
                                     '7', '8', '9', '10', '11', '12', '13',
                                     '14', '15', '16', '17', '18')),
    stable          CHAR(1) DEFAULT 'Y' NOT NULL
                    CHECK (stable IN ('Y', 'N'))
);

It has three unique identifiers - atomic number, element name, and symbol. Each of these, therefore, is a candidate key. Further, unless you are dealing with a table that can only ever hold one row of data (in which case the empty set (of columns) is a candidate key), you cannot have a smaller-than-one-column candidate key, so the candidate keys are irreducible.

Consider a key made up of { atomic number, element name, symbol }. If you supply a consistent set of values for these three fields (say { 6, Carbon, C }), then you uniquely identify the entry for an element - Carbon. However, this is very much a super key that is not a candidate key because it is not irreducible; you can eliminate any two of the three fields without losing the unique identification property.

As another example, consider a key made up of { atomic number, period, group }. Again, this is a unique identifier for a row; { 6, 2, 14 } identifies Carbon (again). If it were not for the Lanthanoids and Actinoids, then the combination of { period, group } would be unique, but because of them, it is not. However, as before, atomic number on its own is sufficient to uniquely identify an element, so this is a super key and not a candidate key.

How to handle-escape both single and double quotes in an SQL-Update statement

Depending on what language you are programming in, you can use a function to replace double quotes with two double quotes.

For example in PHP that would be:

str_replace('"', '""', $string);

If you are trying to do that using SQL only, maybe REPLACE() is what you are looking for.

So your query would look something like this:

"UPDATE Table SET columnname = '" & REPLACE(@wstring, '"', '""') & "' where ... blah ... blah "

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.

Either break your files up into smaller parts, like setting the error levels in one file and then includeing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.

Python: Assign Value if None Exists

Here is the easiest way I use, hope works for you,

var1 = var1 or 4

This assigns 4 to var1 only if var1 is None , False or 0

Android: How can I print a variable on eclipse console?

toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...

Is there a RegExp.escape function in JavaScript?

XRegExp has an escape function:

XRegExp.escape('Escaped? <.>'); // -> 'Escaped\?\ <\.>'

More on: http://xregexp.com/api/#escape

How can I pass some data from one controller to another peer controller

Use a service to achieve this:

MyApp.app.service("xxxSvc", function () {

var _xxx = {};

return {
    getXxx: function () {
        return _xxx;
    },
    setXxx: function (value) {
        _xxx = value;
    }
};

});

Next, inject this service into both controllers.

In Controller1, you would need to set the shared xxx value with a call to the service: xxxSvc.setXxx(xxx)

Finally, in Controller2, add a $watch on this service's getXxx() function like so:

  $scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
        if (newValue != null) {
            //update Controller2's xxx value
            $scope.xxx= newValue;
        }
    }, true);

Choose newline character in Notepad++

For a new document: Settings -> Preferences -> New Document/Default Directory -> New Document -> Format -> Windows/Mac/Unix

And for an already-open document: Edit -> EOL Conversion

How to find time complexity of an algorithm

Although there are some good answers for this question. I would like to give another answer here with several examples of loop.

  • O(n): Time Complexity of a loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. For example following functions have O(n) time complexity.

    // Here c is a positive integer constant   
    for (int i = 1; i <= n; i += c) {  
        // some O(1) expressions
    }
    
    for (int i = n; i > 0; i -= c) {
        // some O(1) expressions
    }
    
  • O(n^c): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example the following sample loops have O(n^2) time complexity

    for (int i = 1; i <=n; i += c) {
       for (int j = 1; j <=n; j += c) {
          // some O(1) expressions
       }
    }
    
    for (int i = n; i > 0; i += c) {
       for (int j = i+1; j <=n; j += c) {
          // some O(1) expressions
    }
    

    For example Selection sort and Insertion Sort have O(n^2) time complexity.

  • O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables is divided / multiplied by a constant amount.

    for (int i = 1; i <=n; i *= c) {
       // some O(1) expressions
    }
    for (int i = n; i > 0; i /= c) {
       // some O(1) expressions
    }
    

    For example Binary Search has O(Logn) time complexity.

  • O(LogLogn) Time Complexity of a loop is considered as O(LogLogn) if the loop variables is reduced / increased exponentially by a constant amount.

    // Here c is a constant greater than 1   
    for (int i = 2; i <=n; i = pow(i, c)) { 
       // some O(1) expressions
    }
    //Here fun is sqrt or cuberoot or any other constant root
    for (int i = n; i > 0; i = fun(i)) { 
       // some O(1) expressions
    }
    

One example of time complexity analysis

int fun(int n)
{    
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j < n; j += i)
        {
            // Some O(1) task
        }
    }    
}

Analysis:

For i = 1, the inner loop is executed n times. For i = 2, the inner loop is executed approximately n/2 times. For i = 3, the inner loop is executed approximately n/3 times. For i = 4, the inner loop is executed approximately n/4 times. ……………………………………………………. For i = n, the inner loop is executed approximately n/n times.

So the total time complexity of the above algorithm is (n + n/2 + n/3 + … + n/n), Which becomes n * (1/1 + 1/2 + 1/3 + … + 1/n)

The important thing about series (1/1 + 1/2 + 1/3 + … + 1/n) is equal to O(Logn). So the time complexity of the above code is O(nLogn).


Ref: 1 2 3

Why doesn't Python have a sign function?

"copysign" is defined by IEEE 754, and part of the C99 specification. That's why it's in Python. The function cannot be implemented in full by abs(x) * sign(y) because of how it's supposed to handle NaN values.

>>> import math
>>> math.copysign(1, float("nan"))
1.0
>>> math.copysign(1, float("-nan"))
-1.0
>>> math.copysign(float("nan"), 1)
nan
>>> math.copysign(float("nan"), -1)
nan
>>> float("nan") * -1
nan
>>> float("nan") * 1
nan
>>> 

That makes copysign() a more useful function than sign().

As to specific reasons why IEEE's signbit(x) is not available in standard Python, I don't know. I can make assumptions, but it would be guessing.

The math module itself uses copysign(1, x) as a way to check if x is negative or non-negative. For most cases dealing with mathematical functions that seems more useful than having a sign(x) which returns 1, 0, or -1 because there's one less case to consider. For example, the following is from Python's math module:

static double
m_atan2(double y, double x)
{
        if (Py_IS_NAN(x) || Py_IS_NAN(y))
                return Py_NAN;
        if (Py_IS_INFINITY(y)) {
                if (Py_IS_INFINITY(x)) {
                        if (copysign(1., x) == 1.)
                                /* atan2(+-inf, +inf) == +-pi/4 */
                                return copysign(0.25*Py_MATH_PI, y);
                        else
                                /* atan2(+-inf, -inf) == +-pi*3/4 */
                                return copysign(0.75*Py_MATH_PI, y);
                }
                /* atan2(+-inf, x) == +-pi/2 for finite x */
                return copysign(0.5*Py_MATH_PI, y);

There you can clearly see that copysign() is a more effective function than a three-valued sign() function.

You wrote:

If I were a python designer, I would been the other way around: no cmp() builtin, but a sign()

That means you don't know that cmp() is used for things besides numbers. cmp("This", "That") cannot be implemented with a sign() function.

Edit to collate my additional answers elsewhere:

You base your justifications on how abs() and sign() are often seen together. As the C standard library does not contain a 'sign(x)' function of any sort, I don't know how you justify your views. There's an abs(int) and fabs(double) and fabsf(float) and fabsl(long) but no mention of sign. There is "copysign()" and "signbit()" but those only apply to IEEE 754 numbers.

With complex numbers, what would sign(-3+4j) return in Python, were it to be implemented? abs(-3+4j) return 5.0. That's a clear example of how abs() can be used in places where sign() makes no sense.

Suppose sign(x) were added to Python, as a complement to abs(x). If 'x' is an instance of a user-defined class which implements the __abs__(self) method then abs(x) will call x.__abs__(). In order to work correctly, to handle abs(x) in the same way then Python will have to gain a sign(x) slot.

This is excessive for a relatively unneeded function. Besides, why should sign(x) exist and nonnegative(x) and nonpositive(x) not exist? My snippet from Python's math module implementation shows how copybit(x, y) can be used to implement nonnegative(), which a simple sign(x) cannot do.

Python should support have better support for IEEE 754/C99 math function. That would add a signbit(x) function, which would do what you want in the case of floats. It would not work for integers or complex numbers, much less strings, and it wouldn't have the name you are looking for.

You ask "why", and the answer is "sign(x) isn't useful." You assert that it is useful. Yet your comments show that you do not know enough to be able to make that assertion, which means you would have to show convincing evidence of its need. Saying that NumPy implements it is not convincing enough. You would need to show cases of how existing code would be improved with a sign function.

And that it outside the scope of StackOverflow. Take it instead to one of the Python lists.

Two models in one view in ASP MVC 3

In fact there is a way to use two or more models on one view without wrapping them in a class that contains both.

Using Employee as an example model:

@model Employee

Is actually treated like.

@{ var Model = ViewBag.model as Employee; }

So the View(employee) method is setting your model to the ViewBag and then the ViewEngine is casting it.

This means that,

ViewBag.departments = GetListOfDepartments();
    return View(employee);

Can be used like,

            @model  Employee
        @{
                var DepartmentModel = ViewBag.departments as List<Department>;
        }

Essentially, you can use whatever is in your ViewBag as a "Model" because that's how it works anyway. I'm not saying that this is architecturally ideal, but it is possible.

Check if any type of files exist in a directory using BATCH script

A roll your own function.

Supports recursion or not with the 2nd switch.

Also, allow names of files with ; which the accepted answer fails to address although a great answer, this will get over that issue.

The idea was taken from https://ss64.com/nt/empty.html

Notes within code.

@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written:               2020.01.26
:: Posted on the thread here:   https://stackoverflow.com/q/10813943/8262102
:: Based on:                    https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>"   = Your path wrapped in quotes.
:: <BOOLEAN>  = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE      = if directory doesn't exist.
:: 0-inf      = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
  echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
  ) else if not "%~1"=="" (
  set count=0 & set msg= & set dirExists=
  if not exist "!%~1!" (set msg=FALSE)
  if exist "!%~1!" (
   if {%~2}=={TRUE} (
    >nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
    set msg=!count!
    )
   if {%~2}=={FALSE} (
    for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
    set msg=!count!
    )
   )
  )
  set "%~1=!msg!" & goto :eof
  )

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

how do I initialize a float to its max/min value?

You can either use -FLT_MAX (or -DBL_MAX) for the maximum magnitude negative number and FLT_MAX (or DBL_MAX) for positive. This gives you the range of possible float (or double) values.

You probably don't want to use FLT_MIN; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.

FLT_MIN and FLT_MAX correspond to std::numeric_limits<float>::min() and std::numeric_limits<float>::max().

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

How to style the parent element when hovering a child element?

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to change the spinner background in Android?

You just use this code

            <LinearLayout

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:baselineAligned="false">

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.80">

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|start"
                    android:paddingBottom="5dp"
                    android:paddingTop="5dp">

                    <Spinner
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"

                        android:background="@drawable/spiner_back"
                        android:visibility="visible" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical|end"
                        android:src="@drawable/ic_arrow_drop_down_black_24dp" />
                </FrameLayout>


            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.20">

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@color/colorred"
                    android:fontFamily="@font/raleway_extrabold"
                    android:text="GO"
                    android:textColor="@color/colorwhite" />

            </LinearLayout>
        </LinearLayout>

And This is background which i used...

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@color/colorwhite" />

and here we go this is view which i archive... enter image description here

Oracle Insert via Select from multiple tables where one table may not have a row

Try:

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
       ts.tax_status_id, 
       ( select r.recipient_id
         from recipient r
         where r.recipient_code = ?
       )
from tax_status ts
where ts.tax_status_code = ?

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to catch a click event on a button?

The absolutely best way: Just let your activity implement View.OnClickListener, and write your onClick method like this:

public void onClick(View v) {
    final int id = v.getId();
    switch (id) {
    case R.id.button1:
        // your code for button1 here
        break;
    case R.id.button2:
        // your code for button2 here
        break;
    // even more buttons here
    }
}

Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick:

<Button
    android:id="@+id/button1"
    android:onClick="onClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1" />

That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.

How to check if activity is in foreground or in visible background?

That's exactly the difference between onPause and onStop events of the activity as described in the Activity class documentation.

If I understand you correctly, what you want to do is call finish() from your activity onStop to terminate it. See the attached image of the Activity Lifecycle Demo App. This is how it looks like when Activity B is launched from Activity A. The order of events is from bottom to top so you can see that Activity A onStop is called after Activity B onResume was already called.

Activity lifecycle demo

In case a dialog is shown your activity is dimmed in the background and only onPause is called.

How do I analyze a .hprof file?

You can use JHAT, The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. A very useful view is the "heap histogram" link at the very bottom.

ex: jhat -port 7401 -J-Xmx4G dump.hprof

jhat can execute OQL "these days" as well (bottom link "execute OQL")

How do I replace all line breaks in a string with <br /> elements?

This worked for me when value came from a TextBox:

string.replace(/\n|\r\n|\r/g, '<br/>');

Failed to add the host to the list of know hosts

This command worked for me,

sudo chown -v $USER ~/.ssh/known_hosts

as mentioned by @kenorb.

The error was coming due to broken permissions, for the current user.

Where does pip install its packages?

In a Python interpreter or script, you can do

import site
site.getsitepackages() # List of global package locations

and

site.getusersitepackages() # String for user-specific package location

For locations third-party packages (those not in the core Python distribution) are installed to.

On my Homebrew-installed Python on macOS, the former outputs

['/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'],

which canonicalizes to the same path output by pip show, as mentioned in a previous answer:

$ readlink -f /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
/usr/local/lib/python3.7/site-packages

Reference: https://docs.python.org/3/library/site.html#site.getsitepackages

Pytorch tensor to numpy array

While other answers perfectly explained the question I will add some real life examples converting tensors to numpy array:

Example: Shared storage

PyTorch tensor residing on CPU shares the same storage as numpy array na

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
tensor([[10.,  1.]])

Example: Eliminate effect of shared storage, copy numpy array first

To avoid the effect of shared storage we need to copy() the numpy array na to a new numpy array nac. Numpy copy() method creates the new separate storage.

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
nac = na.copy()
nac[0][0]=10
?print(nac)
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
[[1. 1.]]
tensor([[1., 1.]])

Now, just the nac numpy array will be altered with the line nac[0][0]=10, na and a will remain as is.

Example: CPU tensor with requires_grad=True

import torch
a = torch.ones((1,2), requires_grad=True)
print(a)
na = a.detach().numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], requires_grad=True)
[[10.  1.]]
tensor([[10.,  1.]], requires_grad=True)

In here we call:

na = a.numpy() 

This would cause: RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead., because tensors that require_grad=True are recorded by PyTorch AD. Note that tensor.detach() is the new way for tensor.data.

This explains why we need to detach() them first before converting using numpy().

Example: CUDA tensor with requires_grad=False

a = torch.ones((1,2), device='cuda')
print(a)
na = a.to('cpu').numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0')
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0')

?

Example: CUDA tensor with requires_grad=True

a = torch.ones((1,2), device='cuda', requires_grad=True)
print(a)
na = a.detach().to('cpu').numpy()
na[0][0]=10
?print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0', requires_grad=True)
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0', requires_grad=True)

Without detach() method the error RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead. will be set.

Without .to('cpu') method TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. will be set.

You could use cpu() but instead of to('cpu') but I prefer the newer to('cpu').

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

Radio buttons and label to display in same line

fieldset {
  overflow: hidden
}

.class {
  float: left;
  clear: none;
}

label {
  float: left;
  clear: both;
  display:initial;
}

input[type=radio],input.radio {
  float: left;
  clear: both;     
}

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

How do I detect a click outside an element?

Using not():

$("#id").not().click(function() {
    alert('Clicked other that #id');
});

If input value is blank, assign a value of "empty" with Javascript

This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

ASP.NET does not search bin/debug or any subfolder under bin for assemblies like other types of applications do. You can instruct the runtime to look in a different place using the following configuration:

<configuration>
   <runtime>   
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <probing privatePath="bin;bin\Debug;bin\Release"/>
      </assemblyBinding>
   </runtime>   
</configuration>

Easier way to debug a Windows service

For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.

For new Windows Service program, I would suggest using James Michael Hare's method http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

Accessing a resource via codebehind in WPF

You should use System.Windows.Controls.UserControl's FindResource() or TryFindResource() methods.

Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).

Are there inline functions in java?

Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.

How to check the version of scipy

on command line

 example$:python
 >>> import scipy
 >>> scipy.__version__
 '0.9.0'

Importing class/java files in Eclipse

import class folder does not work for me, but add jar worked!

1. put the class folder under the project folder

2. Zip the class folder

3. Highlight project name, click "Project" in the top toolbar, click "Properties", click "Libraries" tab, click "Add External jars".

4. Add the zip file. Done!

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

PHP write file from input to txt

Your form should look like this :

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

and the PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

I wrote to /tmp/mydata.txt because this way I know exactly where it is. using data.txt writes to that file in the current working directory which I know nothing of in your example.

file_put_contents opens, writes and closes files for you. Don't mess with it.

Further reading: file_put_contents

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

jQuery multiselect drop down menu

<select id="mycontrolId" multiple="multiple">
   <option value="1" >one</option>
   <option value="2" >two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

var data = "1,3,4"; var dataarray = data.split(",");

$("#mycontrolId").val(dataarray);

Pass a datetime from javascript to c# (Controller)

Update: Please see marked answer as a better solution to implement this. The following solution is no longer required.

Converting the json date to this format "mm/dd/yyyy HH:MM:ss"
dateFormat is a jasondate format.js file found at blog.stevenlevithan.com

var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");

jQuery UI DatePicker to show year only

  $(function() {
    $('#datepicker1').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});?

Style should be

.ui-datepicker-calendar {
    display: none;
    }?

working demo

Multiple simultaneous downloads using Wget?

use xargs to make wget working in multiple file in parallel

#!/bin/bash

mywget()
{
    wget "$1"
}

export -f mywget

# run wget in parallel using 8 thread/connection
xargs -P 8 -n 1 -I {} bash -c "mywget '{}'" < list_urls.txt

Aria2 options, The right way working with file smaller than 20mb

aria2c -k 2M -x 10 -s 10 [url]

-k 2M split file into 2mb chunk

-k or --min-split-size has default value of 20mb, if you not set this option and file under 20mb it will only run in single connection no matter what value of -x or -s

javascript - replace dash (hyphen) with a space

var str = "This-is-a-news-item-";
while (str.contains("-")) {
  str = str.replace("-", ' ');
}
alert(str);

I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.

http://jsfiddle.net/LGCYF/

When to catch java.lang.Error?

In multithreaded environment, you most often want to catch it! When you catch it, log it, and terminate whole application! If you don't do that, some thread that might be doing some crucial part would be dead, and rest of the application will think that everything is normal. Out of that, many unwanted situations can happen. One smallest problem is that you wouldn't be able to easily find root of the problem, if other threads start throwing some exceptions because of one thread not working.

For example, usually loop should be:

try {
   while (shouldRun()) {
       doSomething();
   }
}
catch (Throwable t) {
   log(t);
   stop();
   System.exit(1);
}

Even in some cases, you would want to handle different Errors differently, for example, on OutOfMemoryError you would be able to close application regularly (even maybe free some memory, and continue), on some others, there is not much you can do.

How do I pass a list as a parameter in a stored procedure?

You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):

declare @p1 dbo.string_list_type
insert into @p1 values(N'myFirstString')
insert into @p1 values(N'mySecondString')

Example use when executing a stored proc:

exec MyStoredProc @MyParam=@p1

Connect to SQL Server through PDO using SQL Server Driver

Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:

$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I'm not sure I understand your intent perfectly, but perhaps the following would be close to what you want:

select n1.name, n1.author_id, count_1, total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select id, author_id, count(1) as total_count
              from names
              group by id, author_id) n2
  on (n2.id = n1.id and n2.author_id = n1.author_id)

Unfortunately this adds the requirement of grouping the first subquery by id as well as name and author_id, which I don't think was wanted. I'm not sure how to work around that, though, as you need to have id available to join in the second subquery. Perhaps someone else will come up with a better solution.

Share and enjoy.

Calculating the SUM of (Quantity*Price) from 2 different tables

i think this - including null value = 0

 SELECT oi.id, 
         SUM(nvl(oi.quantity,0) * nvl(p.price,0)) AS total_qty 
    FROM ORDERITEM oi 
    JOIN PRODUCT p ON p.id = oi.productid 
   WHERE oi.orderid = @OrderId 
GROUP BY oi.id 

Operator overloading on class templates

You need to say the following (since you befriend a whole template instead of just a specialization of it, in which case you would just need to add a <> after the operator<<):

template<typename T>
friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

Actually, there is no need to declare it as a friend unless it accesses private or protected members. Since you just get a warning, it appears your declaration of friendship is not a good idea. If you just want to declare a single specialization of it as a friend, you can do that like shown below, with a forward declaration of the template before your class, so that operator<< is regognized as a template.

// before class definition ...
template <class T>
class MyClass;

// note that this "T" is unrelated to the T of MyClass !
template<typename T>
std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

// in class definition ...
friend std::ostream& operator<< <>(std::ostream& out, const MyClass<T>& classObj);

Both the above and this way declare specializations of it as friends, but the first declares all specializations as friends, while the second only declares the specialization of operator<< as a friend whose T is equal to the T of the class granting friendship.

And in the other case, your declaration looks OK, but note that you cannot += a MyClass<T> to a MyClass<U> when T and U are different type with that declaration (unless you have an implicit conversion between those types). You can make your += a member template

// In MyClass.h
template<typename U>
MyClass<T>& operator+=(const MyClass<U>& classObj);


// In MyClass.cpp
template <class T> template<typename U>
MyClass<T>& MyClass<T>::operator+=(const MyClass<U>& classObj) {
  // ...
  return *this;
}

Composer Warning: openssl extension is missing. How to enable in WAMP

C:\laravel-master>composer create-project laravel/laravel Installing laravel/laravel (v4.0.6) - Installing laravel/laravel (v4.0.6) [RuntimeException] You must enable the openssl extension to download files via https

I'm using EasyPhp (WAMP type). In the EasyPHP Icon in the taskbar, right click and select configuration then select PHP. I will open the PHP.ini file configuration in a Notepad, search-find or CTRL+F in notepad for the word OPENSSL you will find this ;extension=php_openssl.dll just remove the ; and the extension=php_openssl.dll is active.

C:\laravel-master>composer create-project laravel/laravel Installing laravel/laravel (v4.0.6) - Installing laravel/laravel (v4.0.6) Downloading: 100% Created project in C:\laravel-master\laravel Loading composer repositories with package information Installing dependencies (including require-dev)

Creating a new user and password with Ansible

Mxx's answer is correct but you the python crypt.crypt() method is not safe when different operating systems are involved (related to glibc hash algorithm used on your system.)

For example, It won't work if your generate your hash from MacOS and run a playbook on linux. In such case , You can use passlib (pip install passlib to install locally).

from passlib.hash import md5_crypt
python -c 'import crypt; print md5_crypt.encrypt("This is my Password,salt="SomeSalt")'
'$1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.'

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

How to play videos in android from assets folder or raw folder?

Did you try to put manually Video on SDCard and try to play video store on SDCard ?

If it's working you can find the way to copy from Raw to SDcard here :

android-copy-rawfile-to-sdcard-video-mp4.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

How to append text to a text file in C++?

I got my code for the answer from a book called "C++ Programming In Easy Steps". The could below should work.

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    ofstream writer("filename.file-extension" , ios::app);

    if (!writer)
    {
        cout << "Error Opening File" << endl;
        return -1;
    }

    string info = "insert text here";
    writer.append(info);

    writer << info << endl;
    writer.close;
    return 0;   
} 

I hope this helps you.

How do I find the time difference between two datetime objects in python?

I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it

from datetime import datetime

class TimeLogger:
    time_cursor = None

    def pin_time(self):
        global time_cursor
        time_cursor = datetime.now()

    def log(self, text=None) -> float:
        global time_cursor

        if not time_cursor:
            time_cursor = datetime.now()

        now = datetime.now()
        t_delta = now - time_cursor

        seconds = t_delta.total_seconds()

        result = str(now) + ' tl -----------> %.5f' % seconds
        if text:
            result += "   " + text
        print(result)

        self.pin_time()

        return seconds


time_logger = TimeLogger()

Using:

from .tests_time_logger import time_logger
class Tests(TestCase):
    def test_workflow(self):
    time_logger.pin_time()

    ... my functions here ...

    time_logger.log()

    ... other function(s) ...

    time_logger.log(text='Tests finished')

and i have something like that in log output

2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished

Which characters need to be escaped in HTML?

It depends upon the context. Some possible contexts in HTML:

  • document body
  • inside common attributes
  • inside script tags
  • inside style tags
  • several more!

See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

converting multiple columns from character to numeric format in r

I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)

#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]

DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)

Cross browser method to fit a child div to its parent's width

In case you want to use that padding space... then here's something:

http://jsfiddle.net/qD4zd/

All the colors are background colors.

Linq to Entities - SQL "IN" clause

You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.

There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:

Query Syntax:

var selected = from u in users
               where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
               select u

foreach(user u in selected)
{
    //Do your stuff on each selected user;
}

Method Syntax:

var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));

foreach(user u in selected)
{
    //Do stuff on each selected user;
}

My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:

foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:

foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

Call an overridden method from super class in typescript

The order of execution is:

  1. A's constructor
  2. B's constructor

The assignment occurs in B's constructor after A's constructor—_super—has been called:

function B() {
    _super.apply(this, arguments);   // MyvirtualMethod called in here
    this.testString = "Test String"; // testString assigned here
}

So the following happens:

var b = new B();     // undefined
b.MyvirtualMethod(); // "Test String"

You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod() in B's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A's constructor and working that out somehow... there's lots of possibilities.

UTL_FILE.FOPEN() procedure not accepting path for directory?

The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.

Open files always in a new tab

I came up with the same problem, and open setting.json file, add the following:

"workbench.editor.enablePreview": false

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

Parse JSON in TSQL

CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX), -- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200), --the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character


  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0, --set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK --no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString, '"' AS ToString
         UNION ALL SELECT '\\', '\'
         UNION ALL SELECT '\/', '/'
         UNION ALL SELECT '\b', CHAR(08)
         UNION ALL SELECT '\f', CHAR(12)
         UNION ALL SELECT '\n', CHAR(10)
         UNION ALL SELECT '\r', CHAR(13)
         UNION ALL SELECT '\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;

                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5), @@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN

  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject

  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token, LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true', 'false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' ' Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
  SELECT '-',1, NULL, '', @parent_id-1, @type
--
   RETURN
END
GO

---Pase JSON

Declare @pars varchar(MAX) = 
' {"shapes":[{"type":"polygon","geofenceName":"","geofenceDescription":"",
"geofenceCategory":"1","color":"#1E90FF","paths":[{"path":[{
"lat":"26.096254906968525","lon":"65.709228515625"}
,{"lat":"28.38173504322308","lon":"66.741943359375"}
,{"lat":"26.765230565697482","lon":"68.983154296875"}
,{"lat":"26.254009699865737","lon":"68.609619140625"}
,{"lat":"25.997549919572112","lon":"68.104248046875"}
,{"lat":"26.843677401113002","lon":"67.115478515625"}
,{"lat":"25.363882272740255","lon":"65.819091796875"}]}]}]}'
Select * from parseJSON(@pars) AS MyResult 

How to efficiently remove duplicates from an array without using Set

 package javaa;

public class UniqueElementinAnArray 
{

 public static void main(String[] args) 
 {
    int[] a = {10,10,10,10,10,100};
    int[] output = new int[a.length];
    int count = 0;
    int num = 0;

    //Iterate over an array
    for(int i=0; i<a.length; i++)
    {
        num=a[i];
        boolean flag = check(output,num);
        if(flag==false)
        {
            output[count]=num;
            ++count;
        }

    }

    //print the all the elements from an array except zero's (0)
    for (int i : output) 
    {
        if(i!=0 )
            System.out.print(i+"  ");
    }

}

/***
 * If a next number from an array is already exists in unique array then return true else false
 * @param arr   Unique number array. Initially this array is an empty.
 * @param num   Number to be search in unique array. Whether it is duplicate or unique.
 * @return  true: If a number is already exists in an array else false 
 */
public static boolean check(int[] arr, int num)
{
    boolean flag = false;
    for(int i=0;i<arr.length; i++)
    {
        if(arr[i]==num)
        {
            flag = true;
            break;
        }
    }
    return flag;
}

}

read file in classpath

Change . to / as the path separator and use getResourceAsStream:

reader = new BufferedReader(new InputStreamReader(
    getClass().getClassLoader().getResourceAsStream(
        "com/company/app/dao/sql/SqlQueryFile.sql")));

or

reader = new BufferedReader(new InputStreamReader(
    getClass().getResourceAsStream(
        "/com/company/app/dao/sql/SqlQueryFile.sql")));

Note the leading slash when using Class.getResourceAsStream() vs ClassLoader.getResourceAsStream. getSystemResourceAsStream uses the system classloader which isn't what you want.

I suspect that using slashes instead of dots would work for ClassPathResource too.

How can I concatenate a string and a number in Python?

Either something like this:

"abc" + str(9)

or

"abs{0}".format(9)

or

"abs%d" % (9,)

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

Metadata file '.dll' could not be found

I faced this problem. In my case I delete all bin and obj folders from all projects then this error will resolve for me. Try this for one more try to resolve the problem

Correct way to handle conditional styling in React

 <div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>

Checkout the above code. That will do the trick.

disable a hyperlink using jQuery

Try:

$(this).prop( "disabled", true );

Getting full JS autocompletion under Sublime Text

There are three approaches

  • Use SublimeCodeIntel plug-in

  • Use CTags plug-in

  • Generate .sublime-completion file manually

Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

From an array of objects, extract value of a property as array

It depends of your definition of "better".

The other answers point out the use of map, which is natural (especially for guys used to functional style) and concise. I strongly recommend using it (if you don't bother with the few IE8- IT guys). So if "better" means "more concise", "maintainable", "understandable" then yes, it's way better.

In the other hand, this beauty don't come without additional costs. I'm not a big fan of microbench, but I've put up a small test here. The result are predictable, the old ugly way seems to be faster than the map function. So if "better" means "faster", then no, stay with the old school fashion.

Again this is just a microbench and in no way advocating against the use of map, it's just my two cents :).

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Viewing unpushed Git commits

All the other answers talk about "upstream" (the branch you pull from).
But a local branch can push to a different branch than the one it pulls from.

master might not push to the remote tracking branch "origin/master".
The upstream branch for master might be origin/master, but it could push to the remote tracking branch origin/xxx or even anotherUpstreamRepo/yyy.
Those are set by branch.*.pushremote for the current branch along with the global remote.pushDefault value.

It is that remote-tracking branch which counts when seeking unpushed commits: the one that tracks the branch at the remote where the local branch would be pushed to.
The branch at the remote can be, again, origin/xxx or even anotherUpstreamRepo/yyy.

Git 2.5+ (Q2 2015) introduces a new shortcut for that: <branch>@{push}

See commit 29bc885, commit 3dbe9db, commit adfe5d0, commit 48c5847, commit a1ad0eb, commit e291c75, commit 979cb24, commit 1ca41a1, commit 3a429d0, commit a9f9f8c, commit 8770e6f, commit da66b27, commit f052154, commit 9e3751d, commit ee2499f [all from 21 May 2015], and commit e41bf35 [01 May 2015] by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit c4a8354, 05 Jun 2015)

Commit adfe5d0 explains:

sha1_name: implement @{push} shorthand

In a triangular workflow, each branch may have two distinct points of interest: the @{upstream} that you normally pull from, and the destination that you normally push to. There isn't a shorthand for the latter, but it's useful to have.

For instance, you may want to know which commits you haven't pushed yet:

git log @{push}..

Or as a more complicated example, imagine that you normally pull changes from origin/master (which you set as your @{upstream}), and push changes to your own personal fork (e.g., as myfork/topic).
You may push to your fork from multiple machines, requiring you to integrate the changes from the push destination, rather than upstream.
With this patch, you can just do:

git rebase @{push}

rather than typing out the full name.

Commit 29bc885 adds:

for-each-ref: accept "%(push)" format

Just as we have "%(upstream)" to report the "@{upstream}" for each ref, this patch adds "%(push)" to match "@{push}".
It supports the same tracking format modifiers as upstream (because you may want to know, for example, which branches have commits to push).

If you want to see how many commit your local branches are ahead/behind compared to the branch you are pushing to:

git for-each-ref --format="%(refname:short) %(push:track)" refs/heads

inherit from two classes in C#

You can define a base class for A and B where you can hold a common methods/properties/fields of those.

After implement C:Base.

Or in order to simulate multiple inheritance, define a common interface(s) and implement them in C

Hope this helps.

How can you get the Manifest Version number from the App's (Layout) XML variables?

Late to the game, but you can do it without @string/xyz by using ?android:attr

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionName"
     />
    <!-- or -->
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionCode"
     />

How can I use Python to get the system hostname?

To get fully qualified hostname use socket.getfqdn()

import socket

print socket.getfqdn()

Group by month and year in MySQL

GROUP BY DATE_FORMAT(summaryDateTime,'%Y-%m')

What's a simple way to get a text input popup dialog box on an iPhone

Building on John Riselvato's answer, to retrieve the string back from the UIAlertView...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })

Can't subtract offset-naive and offset-aware datetimes

I came up with an ultra-simple solution:

import datetime

def calcEpochSec(dt):
    epochZero = datetime.datetime(1970,1,1,tzinfo = dt.tzinfo)
    return (dt - epochZero).total_seconds()

It works with both timezone-aware and timezone-naive datetime values. And no additional libraries or database workarounds are required.

Deserialize JSON array(or list) in C#

Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

How can I make SQL case sensitive string comparison on MySQL?

You can use BINARY to case sensitive like this

select * from tb_app where BINARY android_package='com.Mtime';

unfortunately this sql can't use index, you will suffer a performance hit on queries reliant on that index

mysql> explain select * from tb_app where BINARY android_package='com.Mtime';
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | tb_app | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 1590351 |   100.00 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+---------+----------+-------------+

Fortunately, I have a few tricks to solve this problem

mysql> explain select * from tb_app where android_package='com.Mtime' and BINARY android_package='com.Mtime';
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys             | key                       | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | tb_app | NULL       | ref  | idx_android_pkg           | idx_android_pkg           | 771     | const |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-----------------------+  

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

Bootstrap visible and hidden classes not working properly

If you give display table property in css some div bootstrap hidden class will not effect on that div

Catch checked change event of a checkbox

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>

Get Today's date in Java at midnight time

For Current Date and Time :

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

This will shown as :

Feb 5, 2013 12:40:24PM

Batch file to copy files from one folder to another folder

@echo off

rem The * at the end of the destination file is to avoid File/Directory Internal Question.

rem You can do this for each especific file. (Make sure you already have permissions to the path)
xcopy /Y "\\Oldeserver\storage\data\MyFile01.txt" "\\New server\storage\data\MyFile01.txt"*
pause

rem You can use "copy" instead of "xcopy "for this example.

Switch statement: must default be the last case?

yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

I think this answers the question best, it actually changes the alpha value of something that has been drawn already. Maybe this wasn't part of the api when this question was asked.

Given 2d context c.

function reduceAlpha(x, y, w, h, dA) {
    let screenData = c.getImageData(x, y, w, h);
    for(let i = 3; i < screenData.data.length; i+=4){
        screenData.data[i] -= dA; //delta-Alpha
    }
    c.putImageData(screenData, x, y );
}

Convert generic list to dataset in C#

Brute force code to answer your question:

DataTable dt = new DataTable();

//for each of your properties
dt.Columns.Add("PropertyOne", typeof(string));

foreach(Entity entity in entities)
{
  DataRow row = dt.NewRow();

  //foreach of your properties
  row["PropertyOne"] = entity.PropertyOne;

  dt.Rows.Add(row);
}

DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;

Now for the actual question. Why would you want to do this? As mentioned earlier, you can bind directly to an object list. Maybe a reporting tool that only takes datasets?

How to cast ArrayList<> from List<>

The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.

However the first approach should work just fine, if and only if getAllTasks return an ArrayList.

It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.

If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.

How do I reference the input of an HTML <textarea> control in codebehind?

First make sure you have the runat="server" attribute in your textarea tag like this

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

Then you can access the content via:

string body = TextArea1.value;

Javascript: Setting location.href versus location

Like as has been said already, location is an object. But that person suggested using either. But, you will do better to use the .href version.

Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location object, it has a property called .href. And by not specifying ANY property during the assignment, it will assume "href" by default.

This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.

If you mean href, you should specify href.

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

How to change button background image on mouseOver?

I made a quick project in visual studio 2008 for a .net 3.5 C# windows form application and was able to create the following code. I found events for both the enter and leave methods.

In the InitializeComponent() function. I added the event handler using the Visual Studio designer.

this.button1.MouseLeave += new System.EventHandler( this.button1_MouseLeave );
this.button1.MouseEnter += new System.EventHandler( this.button1_MouseEnter );

In the button event handler methods set the background images.

/// <summary>
/// Handles the MouseEnter event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseEnter( object sender, EventArgs e )
{
      this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}

/// <summary>
/// Handles the MouseLeave event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseLeave( object sender, EventArgs e )
{
       this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}