Programs & Examples On #Selecteditemchanged

Data binding to SelectedItem in a WPF Treeview

I realise this has already had an answer accepted, but I put this together to solve the problem. It uses a similar idea to Delta's solution, but without the need to subclass the TreeView:

public class BindableSelectedItemBehavior : Behavior<TreeView>
{
    #region SelectedItem Property

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));

    private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var item = e.NewValue as TreeViewItem;
        if (item != null)
        {
            item.SetValue(TreeViewItem.IsSelectedProperty, true);
        }
    }

    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
        }
    }

    private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        this.SelectedItem = e.NewValue;
    }
}

You can then use this in your XAML as:

<TreeView>
    <e:Interaction.Behaviors>
        <behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
    </e:Interaction.Behaviors>
</TreeView>

Hopefully it will help someone!

Why can't radio buttons be "readonly"?

For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:

<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>

How do you find out the caller function in JavaScript?

To recap (and make it clearer) ...

this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

Working with $scope.$emit and $scope.$on

Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)

<body ng-app="App">

    <div ng-controller="parentCtrl">

        <p>City : {{city}} </p>
        <p> Address : {{address}} </p>

        <div ng-controller="subCtrlOne">
            <input type="text" ng-model="city" />
            <button ng-click="getCity(city)">City !!!</button>
        </div>

        <div ng-controller="subCtrlTwo">

            <input type="text" ng-model="address" />
            <button ng-click="getAddrress(address)">Address !!!</button>

        </div>

    </div>

</body>

var App = angular.module('App', []);

// parent controller
App.controller('parentCtrl', parentCtrl);

parentCtrl.$inject = ["$scope"];

function parentCtrl($scope) {

    $scope.$on('cityBoom', function(events, data) {
        $scope.city = data;
    });

    $scope.$on('addrBoom', function(events, data) {
        $scope.address = data;
    });
}

// sub controller one

App.controller('subCtrlOne', subCtrlOne);

subCtrlOne.$inject = ['$scope'];

function subCtrlOne($scope) {

    $scope.getCity = function(city) {

        $scope.$emit('cityBoom', city);    
    }
}

// sub controller two

App.controller('subCtrlTwo', subCtrlTwo);

subCtrlTwo.$inject = ["$scope"];

function subCtrlTwo($scope) {

    $scope.getAddrress = function(addr) {

        $scope.$emit('addrBoom', addr);   
    }
}

http://jsfiddle.net/shushanthp/zp6v0rut/

How to change mysql to mysqli?

The ultimate guide to upgrading mysql_* functions to MySQLi API

The reason for the new mysqli extension was to take advantage of new features found in MySQL systems versions 4.1.3 and newer. When changing your existing code from mysql_* to mysqli API you should avail of these improvements, otherwise your upgrade efforts could go in vain.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Enhanced debugging capabilities

When upgrading from mysql_* functions to MySQLi, it is important to take these features into consideration, as well as some changes in the way this API should be used.

1. Object-oriented interface versus procedural functions.

The new mysqli object-oriented interface is a big improvement over the older functions and it can make your code cleaner and less susceptible to typographical errors. There is also the procedural version of this API, but its use is discouraged as it leads to less readable code, which is more prone to errors.

To open new connection to the database with MySQLi you need to create new instance of MySQLi class.

$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

Using procedural style it would look like this:

$mysqli = mysqli_connect($host, $user, $password, $dbName);
mysqli_set_charset($mysqli, 'utf8mb4');

Keep in mind that only the first 3 parameters are the same as in mysql_connect. The same code in the old API would be:

$link = mysql_connect($host, $user, $password);
mysql_select_db($dbName, $link);
mysql_query('SET NAMES utf8');

If your PHP code relied on implicit connection with default parameters defined in php.ini, you now have to open the MySQLi connection passing the parameters in your code, and then provide the connection link to all procedural functions or use the OOP style.

For more information see the article: How to connect properly using mysqli

2. Support for Prepared Statements

This is a big one. MySQL has added support for native prepared statements in MySQL 4.1 (2004). Prepared statements are the best way to prevent SQL injection. It was only logical that support for native prepared statements was added to PHP. Prepared statements should be used whenever data needs to be passed along with the SQL statement (i.e. WHERE, INSERT or UPDATE are the usual use cases).

The old MySQL API had a function to escape the strings used in SQL called mysql_real_escape_string, but it was never intended for protection against SQL injections and naturally shouldn't be used for the purpose.
The new MySQLi API offers a substitute function mysqli_real_escape_string for backwards compatibility, which suffers from the same problems as the old one and therefore should not be used unless prepared statements are not available.

The old mysql_* way:

$login = mysql_real_escape_string($_POST['login']);
$result = mysql_query("SELECT * FROM users WHERE user='$login'");

The prepared statement way:

$stmt = $mysqli->prepare('SELECT * FROM users WHERE user=?');
$stmt->bind_param('s', $_POST['login']);
$stmt->execute();
$result = $stmt->get_result();

Prepared statements in MySQLi can look a little off-putting to beginners. If you are starting a new project then deciding to use the more powerful and simpler PDO API might be a good idea.

3. Enhanced debugging capabilities

Some old-school PHP developers are used to checking for SQL errors manually and displaying them directly in the browser as means of debugging. However, such practice turned out to be not only cumbersome, but also a security risk. Thankfully MySQLi has improved error reporting capabilities.

MySQLi is able to report any errors it encounters as PHP exceptions. PHP exceptions will bubble up in the script and if unhandled will terminate it instantly, which means that no statement after the erroneous one will ever be executed. The exception will trigger PHP Fatal error and will behave as any error triggered from PHP core obeying the display_errors and log_errors settings. To enable MySQLi exceptions use the line mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) and insert it right before you open the DB connection.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

If you were used to writing code such as:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

or

$result = mysql_query('SELECT * WHERE 1=1') or die(mysql_error());

you no longer need to die() in your code.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

$result = $mysqli->query('SELECT * FROM non_existent_table');
// The following line will never be executed due to the mysqli_sql_exception being thrown above
foreach ($result as $row) {
    // ...
}

If for some reason you can't use exceptions, MySQLi has equivalent functions for error retrieval. You can use mysqli_connect_error() to check for connection errors and mysqli_error($mysqli) for any other errors. Pay attention to the mandatory argument in mysqli_error($mysqli) or alternatively stick to OOP style and use $mysqli->error.

$result = $mysqli->query('SELECT * FROM non_existent_table') or trigger_error($mysqli->error, E_USER_ERROR);

See these posts for more explanation:
mysqli or die, does it have to die?
How to get MySQLi error information in different environments?

4. Other changes

Unfortunately not every function from mysql_* has its counterpart in MySQLi only with an "i" added in the name and connection link as first parameter. Here is a list of some of them:

  • mysql_client_encoding() has been replaced by mysqli_character_set_name($mysqli)
  • mysql_create_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_drop_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_db_name & mysql_list_dbs support has been dropped in favour of SQL's SHOW DATABASES
  • mysql_list_tables support has been dropped in favour of SQL's SHOW TABLES FROM dbname
  • mysql_list_fields support has been dropped in favour of SQL's SHOW COLUMNS FROM sometable
  • mysql_db_query -> use mysqli_select_db() then the query or specify the DB name in the query
  • mysql_fetch_field($result, 5) -> the second parameter (offset) is not present in mysqli_fetch_field. You can use mysqli_fetch_field_direct keeping in mind the different results returned
  • mysql_field_flags, mysql_field_len, mysql_field_name, mysql_field_table & mysql_field_type -> has been replaced with mysqli_fetch_field_direct
  • mysql_list_processes has been removed. If you need thread ID use mysqli_thread_id
  • mysql_pconnect has been replaced with mysqli_connect() with p: host prefix
  • mysql_result -> use mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
  • mysql_tablename support has been dropped in favour of SQL's SHOW TABLES
  • mysql_unbuffered_query has been removed. See this article for more information Buffered and Unbuffered queries

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

What is a raw type and why shouldn't we use it?

A raw type is the name of a generic class or interface without any type arguments. For example, given the generic Box class:

public class Box<T> {
    public void set(T t) { /* ... */ }
    // ...
}

To create a parameterized type of Box<T>, you supply an actual type argument for the formal type parameter T:

Box<Integer> intBox = new Box<>();

If the actual type argument is omitted, you create a raw type of Box<T>:

Box rawBox = new Box();

Therefore, Box is the raw type of the generic type Box<T>. However, a non-generic class or interface type is not a raw type.

Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0. When using raw types, you essentially get pre-generics behavior — a Box gives you Objects. For backward compatibility, assigning a parameterized type to its raw type is allowed:

Box<String> stringBox = new Box<>();
Box rawBox = stringBox;               // OK

But if you assign a raw type to a parameterized type, you get a warning:

Box rawBox = new Box();           // rawBox is a raw type of Box<T>
Box<Integer> intBox = rawBox;     // warning: unchecked conversion

You also get a warning if you use a raw type to invoke generic methods defined in the corresponding generic type:

Box<String> stringBox = new Box<>();
Box rawBox = stringBox;
rawBox.set(8);  // warning: unchecked invocation to set(T)

The warning shows that raw types bypass generic type checks, deferring the catch of unsafe code to runtime. Therefore, you should avoid using raw types.

The Type Erasure section has more information on how the Java compiler uses raw types.

Unchecked Error Messages

As mentioned previously, when mixing legacy code with generic code, you may encounter warning messages similar to the following:

Note: Example.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

This can happen when using an older API that operates on raw types, as shown in the following example:

public class WarningDemo {
    public static void main(String[] args){
        Box<Integer> bi;
        bi = createBox();
    }

    static Box createBox(){
        return new Box();
    }
}

The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety. The "unchecked" warning is disabled, by default, though the compiler gives a hint. To see all "unchecked" warnings, recompile with -Xlint:unchecked.

Recompiling the previous example with -Xlint:unchecked reveals the following additional information:

WarningDemo.java:4: warning: [unchecked] unchecked conversion
found   : Box
required: Box<java.lang.Integer>
        bi = createBox();
                      ^
1 warning

To completely disable unchecked warnings, use the -Xlint:-unchecked flag. The @SuppressWarnings("unchecked") annotation suppresses unchecked warnings. If you are unfamiliar with the @SuppressWarnings syntax, see Annotations.

Original source: Java Tutorials

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Creating an empty Pandas DataFrame, then filling it?

NEVER grow a DataFrame!

TLDR; (just read the bold text)

Most answers here will tell you how to create an empty DataFrame and fill it out, but no one will tell you that it is a bad thing to do.

Here is my advice: Accumulate data in a list, not a DataFrame.

Use a list to collect your data, then initialise a DataFrame when you are ready. Either a list-of-lists or list-of-dicts format will work, pd.DataFrame accepts both.

data = []
for a, b, c in some_function_that_yields_data():
    data.append([a, b, c])

df = pd.DataFrame(data, columns=['A', 'B', 'C'])

Pros of this approach:

  1. It is always cheaper to append to a list and create a DataFrame in one go than it is to create an empty DataFrame (or one of NaNs) and append to it over and over again.

  2. Lists also take up less memory and are a much lighter data structure to work with, append, and remove (if needed).

  3. dtypes are automatically inferred (rather than assigning object to all of them).

  4. A RangeIndex is automatically created for your data, instead of you having to take care to assign the correct index to the row you are appending at each iteration.

If you aren't convinced yet, this is also mentioned in the documentation:

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

But what if my function returns smaller DataFrames that I need to combine into one large DataFrame?

That's fine, you can still do this in linear time by growing or creating a python list of smaller DataFrames, then calling pd.concat.

small_dfs = []
for small_df in some_function_that_yields_dataframes():
    small_dfs.append(small_df)

large_df = pd.concat(small_dfs, ignore_index=True)

or, more concisely:

large_df = pd.concat(
    list(some_function_that_yields_dataframes()), ignore_index=True)


These options are horrible

append or concat inside a loop

Here is the biggest mistake I've seen from beginners:

df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
    df = df.append({'A': i, 'B': b, 'C': c}, ignore_index=True) # yuck
    # or similarly,
    # df = pd.concat([df, pd.Series({'A': i, 'B': b, 'C': c})], ignore_index=True)

Memory is re-allocated for every append or concat operation you have. Couple this with a loop and you have a quadratic complexity operation.

The other mistake associated with df.append is that users tend to forget append is not an in-place function, so the result must be assigned back. You also have to worry about the dtypes:

df = pd.DataFrame(columns=['A', 'B', 'C'])
df = df.append({'A': 1, 'B': 12.3, 'C': 'xyz'}, ignore_index=True)

df.dtypes
A     object   # yuck!
B    float64
C     object
dtype: object

Dealing with object columns is never a good thing, because pandas cannot vectorize operations on those columns. You will need to do this to fix it:

df.infer_objects().dtypes
A      int64
B    float64
C     object
dtype: object

loc inside a loop

I have also seen loc used to append to a DataFrame that was created empty:

df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
    df.loc[len(df)] = [a, b, c]

As before, you have not pre-allocated the amount of memory you need each time, so the memory is re-grown each time you create a new row. It's just as bad as append, and even more ugly.

Empty DataFrame of NaNs

And then, there's creating a DataFrame of NaNs, and all the caveats associated therewith.

df = pd.DataFrame(columns=['A', 'B', 'C'], index=range(5))
df
     A    B    C
0  NaN  NaN  NaN
1  NaN  NaN  NaN
2  NaN  NaN  NaN
3  NaN  NaN  NaN
4  NaN  NaN  NaN

It creates a DataFrame of object columns, like the others.

df.dtypes
A    object  # you DON'T want this
B    object
C    object
dtype: object

Appending still has all the issues as the methods above.

for i, (a, b, c) in enumerate(some_function_that_yields_data()):
    df.iloc[i] = [a, b, c]


The Proof is in the Pudding

Timing these methods is the fastest way to see just how much they differ in terms of their memory and utility.

enter image description here

Benchmarking code for reference.

Python match a string with regex

r stands for a raw string, so things like \ will be automatically escaped by Python.

Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

short explanation

In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

As per re.match vs re.search here's an example that will clarify it for you:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>

So search will find a match anywhere, match will only start at the beginning

Left Join With Where Clause

The where clause is filtering away rows where the left join doesn't succeed. Move it to the join:

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

Find a file in python

For fast, OS-independent search, use scandir

https://github.com/benhoyt/scandir/#readme

Read http://bugs.python.org/issue11406 for details why.

How do I add a library path in cmake?

might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a)

System.MissingMethodException: Method not found?

I got this exception while testing out some code a coworker had written. Here is a summary of the exception info.:

Method not found: "System.Threading.Tasks.Task1<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry1<System_Canon>> Microsoft.EntityFrameworkCore.DbSet`1.AddAsync...

This was in Visual Studio 2019 in a class library targeting .NET Core 3.1. The fix was to use the Add method instead of AddAsync on the DbSet.

TransactionRequiredException Executing an update/delete query

Using @PersistenceContext with @Modifying as below fixes error while using createNativeQuery

    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.transaction.annotation.Transactional;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    @Modifying
    public <S extends T> S save(S entity) {
         Query q = entityManager.createNativeQuery(...);
         q.setParameter...
         q.executeUpdate();
         return entity;
    }

How do you find all subclasses of a given class in Java?

I did this several years ago. The most reliable way to do this (i.e. with official Java APIs and no external dependencies) is to write a custom doclet to produce a list that can be read at runtime.

You can run it from the command line like this:

javadoc -d build -doclet com.example.ObjectListDoclet -sourcepath java/src -subpackages com.example

or run it from ant like this:

<javadoc sourcepath="${src}" packagenames="*" >
  <doclet name="com.example.ObjectListDoclet" path="${build}"/>
</javadoc>

Here's the basic code:

public final class ObjectListDoclet {
    public static final String TOP_CLASS_NAME =  "com.example.MyClass";        

    /** Doclet entry point. */
    public static boolean start(RootDoc root) throws Exception {
        try {
            ClassDoc topClassDoc = root.classNamed(TOP_CLASS_NAME);
            for (ClassDoc classDoc : root.classes()) {
                if (classDoc.subclassOf(topClassDoc)) {
                    System.out.println(classDoc);
                }
            }
            return true;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

For simplicity, I've removed command line argument parsing and I'm writing to System.out rather than a file.

How to get visitor's location (i.e. country) using geolocation?

You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.

var requestUrl = "http://ip-api.com/json";

$.ajax({
  url: requestUrl,
  type: 'GET',
  success: function(json)
  {
    console.log("My country is: " + json.country);
  },
  error: function(err)
  {
    console.log("Request failed, error= " + err);
  }
});

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

It is because of the period in the file name. It is stupid, but anytime there is a period in the js file name you will get this error, and I have come across situations where it will actually prevent the js file from loading.

Get the records of last month in SQL server

select * from [member] where DatePart("m", date_created) = DatePart("m", DateAdd("m", -1, getdate())) AND DatePart("yyyy", date_created) = DatePart("yyyy", DateAdd("m", -1, getdate()))

Android Button setOnClickListener Design

Implement OnClickListener() on your Activity...

public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...

buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...

@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .NET < 4.0 (e.x: Unity) you can write an extension method to have the TimeSpan.ToString(string format) behavior like .NET > 4.0

public static class TimeSpanExtensions
{
    public static string ToString(this TimeSpan time, string format)
    {
        DateTime dateTime = DateTime.Today.Add(time);
        return dateTime.ToString(format);
    }
}

And from anywhere in your code you can use it like:

var time = TimeSpan.FromSeconds(timeElapsed);

string formattedDate = time.ToString("hh:mm:ss:fff");

This way you can format any TimeSpanobject by simply calling ToString from anywhere of your code.

Multiline TextView in Android?

TextView will be multi line when it wont get enough space to fit in the single line and singLine not set to true.

If it gets the space in one line it wont be multi line.

[] and {} vs list() and dict(), which is better?

In terms of speed, it's no competition for empty lists/dicts:

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077

and for non-empty:

>>> timeit("[1,2,3]")
0.24316302770330367
>>> timeit("list((1,2,3))")
0.44744206316727286
>>> timeit("list(foo)", setup="foo=(1,2,3)")
0.446036018543964
>>> timeit("{'a':1, 'b':2, 'c':3}")
0.20868602015059423
>>> timeit("dict(a=1, b=2, c=3)")
0.47635635255323905
>>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")
0.9028228448029267

Also, using the bracket notation lets you use list and dictionary comprehensions, which may be reason enough.

Import pfx file into particular certificate store from command line

In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.

Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""

Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""

For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]

Set focus on textbox in WPF

Try this : MyTextBox.Focus ( );

Renaming columns in Pandas

Renaming columns in Pandas is an easy task.

df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)

SQL - Query to get server's IP address

--Try this script it works to my needs. Reformat to read it.

SELECT  
SERVERPROPERTY('ComputerNamePhysicalNetBios')  as 'Is_Current_Owner'
    ,SERVERPROPERTY('MachineName')  as 'MachineName'
    ,case when @@ServiceName = 
    Right (@@Servername,len(@@ServiceName)) then @@Servername 
      else @@servername +' \ ' + @@Servicename
      end as '@@Servername \ Servicename',  
    CONNECTIONPROPERTY('net_transport') AS net_transport,
    CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
    dec.local_tcp_port,
    CONNECTIONPROPERTY('local_net_address') AS local_net_address,
    dec.local_net_address as 'dec.local_net_address'
    FROM sys.dm_exec_connections AS dec
    WHERE dec.session_id = @@SPID;

here-document gives 'unexpected end of file' error

The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:

cat -A myfile.sh

Once you see the output from cat -A the solution will be obvious: remove the offending characters.

Why is Ant giving me a Unsupported major.minor version error

  1. Check whether u have jdk installed in the path "C:\Program Files\Java" If not Install the JDK in your machine

  2. In Eclipse, right click on "build.xml" then select Run As > External Tools Configuration

  3. Click on "JRE" tab then click on "Installed JREs" > "ADD" > "Standard VM" > Click "Next

  4. Select the Directory "C:\Program Files\Java\jdk1.7.x_xx" and the directory will be added to the "installed jres"

  5. Select the new JDK directory and Click "OK"

  6. Click on "Seperate JRE" dropdown and select the JDK version "jdk1.7.x_xx" and click on "Run"

This would help:)

How to dynamically add and remove form fields in Angular 2

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

let form = this.form;

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

}

Infinity symbol with HTML

Like ?egDwight said, you can use the HTML entity &infin; or &#8734;. A easy source of getting these codes, is to look at this entity list.

You can also use them in CSS, which was what I was looking for, just like font-awesome does. A simple CSS based solution would be to have something like:

.infinity-ico:before {
    content: '\221E';
}

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to find and replace string?

void replace(char *str, char *strFnd, char *strRep)
{
    for (int i = 0; i < strlen(str); i++)
    {
        int npos = -1, j, k;
        if (str[i] == strFnd[0])
        {
            for (j = 1, k = i+1; j < strlen(strFnd); j++)
                if (str[k++] != strFnd[j])
                    break;
            npos = i;
        }
        if (npos != -1)
            for (j = 0, k = npos; j < strlen(strRep); j++)
                str[k++] = strRep[j];
    }

}

int main()
{
    char pst1[] = "There is a wrong message";
    char pfnd[] = "wrong";
    char prep[] = "right";

    cout << "\nintial:" << pst1;

    replace(pst1, pfnd, prep);

    cout << "\nfinal : " << pst1;
    return 0;
}

How do I parse a HTML page with Node.js

jsdom is too strict to do any real screen scraping sort of things, but beautifulsoup doesn't choke on bad markup.

node-soupselect is a port of python's beautifulsoup into nodejs, and it works beautifully

Error: Selection does not contain a main type

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

Remove all newlines from inside a string

or you can try this:

string1 = 'Hello \n World'
tmp = string1.split()
string2 = ' '.join(tmp)

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

You don't need to call $.toJSON and add traditional = true

data: { sendInfo: array },
traditional: true

would do.

Getting indices of True values in a boolean list

You can use filter for it:

filter(lambda x: self.states[x], range(len(self.states)))

The range here enumerates elements of your list and since we want only those where self.states is True, we are applying a filter based on this condition.

For Python > 3.0:

list(filter(lambda x: self.states[x], range(len(self.states))))

jQuery date/time picker

I make one function like this:

function getTime()
{
    var date_obj = new Date();
    var date_obj_hours = date_obj.getHours();
    var date_obj_mins = date_obj.getMinutes();
    var date_obj_second = date_obj.getSeconds();

    var date_obj_time = "'"+date_obj_hours+":"+date_obj_mins+":"+date_obj_second+"'";
    return date_obj_time;
}

Then I use the jQuery UI datepicker like this:

$("#selector").datepicker( "option", "dateFormat", "yy-mm-dd "+getTime()+"" );

So, I get the value like this: 2010-10-31 12:41:57

Unable to install boto3

I have faced the same issue and also not using virtual environment. easy_install is working for me.

easy_install boto3

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Java equivalent to C# extension methods

Java does not have such feature. Instead you can either create regular subclass of your list implementation or create anonymous inner class:

List<String> list = new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
};

The problem is to call this method. You can do it "in place":

new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
}.getData();

What's the difference between RANK() and DENSE_RANK() functions in oracle?

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

What is the difference between utf8mb4 and utf8 charsets in MySQL?

The utf8mb4 character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.

A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

Sum one number to every element in a list (or array) in Python

try this. (I modified the example on the purpose of making it non trivial)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster

%timeit map(operator.add, a, a1)

than adding with numpy

%timeit an+1

How to get the hostname of the docker host from inside a docker container on that host without env vars

You can easily pass it as an environment variable

docker run .. -e HOST_HOSTNAME=`hostname` ..

using

-e HOST_HOSTNAME=`hostname`

will call the hostname and use it's return as an environment variable called HOST_HOSTNAME, of course you can customize the key as you like.

note that this works on bash shell, if you using a different shell you might need to see the alternative for "backtick", for example a fish shell alternative would be

docker run .. -e HOST_HOSTNAME=(hostname) ..

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Yet another solution to the same problem:

This happened to me every time I imported an eclipse project into studio using the wizard (studio version 1.3.2).

What I found, quite by chance, was that quitting out of Android studio and then restarting studio again made the problem go away.

Frustrating, but hope this helps someone...

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

Computed / calculated / virtual / derived columns in PostgreSQL

Well, not sure if this is what You mean but Posgres normally support "dummy" ETL syntax. I created one empty column in table and then needed to fill it by calculated records depending on values in row.

UPDATE table01
SET column03 = column01*column02; /*e.g. for multiplication of 2 values*/
  1. It is so dummy I suspect it is not what You are looking for.
  2. Obviously it is not dynamic, you run it once. But no obstacle to get it into trigger.

EL access a map value by Integer key

Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:

<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

How to make rectangular image appear circular with CSS

For those who use Bootstrap 3, it has a great CSS class to do the job:

<img src="..." class="img-circle">

Display HTML snippets in HTML

You could use a server side language like PHP to insert raw text:

<?php
  $str = <<<EOD
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="Minimal HTML5">
    <meta name="keywords" content="HTML5,Minimal">
    <title>This is the title</title>
    <link rel='stylesheet.css' href='style.css'>
  </head>
  <body>
  </body>
  </html>
  EOD;
?>

then dump out the value of $str htmlencoded:

<div style="white-space: pre">
  <?php echo htmlentities($str); ?>
</div>

How do you check current view controller class in Swift?

if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
            let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
            self.navigationController?.popToViewController(vc, animated: true)
        } else {
            self.navigationController?.popToRootViewController(animated: true)
        }

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

Force sidebar height 100% using CSS (with a sticky bottom image)?

Until CSS's flexbox becomes more mainstream, you can always just absolutely position the sidebar, sticking it zero pixels away from the top and bottom, then set a margin on your main container to compensate.

JSFiddle

http://jsfiddle.net/QDCGv/

HTML

<section class="sidebar">I'm a sidebar.</section>

<section class="main">I'm the main section.</section>

CSS

section.sidebar {
  width: 250px;
  position: absolute;
  top: 0;
  bottom: 0;
  background-color: green;
}

section.main { margin-left: 250px; }

Note: This is an über simple way to do this but you'll find bottom does not mean "bottom of page," but "bottom of window." The sidebar will probably abrubtly end if your main content scrolls down.

How to mention C:\Program Files in batchfile

I had a similar issue as you, although I was trying to use start to open Chrome and using the file path. I used only start chrome.exe and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.

Here are some examples (using the file name you gave in a comment on another answer):

  • Instead of C:\Program^ Files\temp.exe you can try temp.exe.

  • Instead of start C:\Program^ Files\temp.exe you can try start temp.exe

Can two Java methods have same name with different return types?

If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.

Can jQuery get all CSS styles associated with an element?

A couple years late, but here is a solution that retrieves both inline styling and external styling:

function css(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css) {
    var s = {};
    if (!css) return s;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                s[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var l = css[i].split(": ");
            s[l[0].toLowerCase()] = (l[1]);
        }
    }
    return s;
}

Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);

:)

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

String.strip() in Python

strip removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.

Location of ini/config files in linux/unix?

(1) No (unfortunately). Edit: The other answers are right, per-user configuration is usually stored in dot-files or dot-directories in the users home directory. Anything above user level often is a lot of guesswork.

(2) System-wide ini file -> user ini file -> environment -> command line options (going from lowest to highest precedence)

Image resizing client-side with JavaScript before upload to the server

If you were resizing before uploading I just found out this http://www.plupload.com/

It does all the magic for you in any imaginable method.

Unfortunately HTML5 resize only is supported with Mozilla browser, but you can redirect other browsers to Flash and Silverlight.

I just tried it and it worked with my android!

I was using http://swfupload.org/ in flash, it does the job very well, but the resize size is very small. (cannot remember the limit) and does not go back to html4 when flash is not available.

How can I obfuscate (protect) JavaScript?

I can recommend JavaScript Utility by Patrick J. O'Neil. It can obfuscate/compact and compress and it seems to be pretty good at these. That said, I never tried integrating it in a build script of any kind.

As for obfuscating vs. minifying - I am not a big fan of the former. It makes debugging impossible (Error at line 1... "wait, there is only one line") and they always take time to unpack. But if you need to... well.

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

Psql could not connect to server: No such file or directory, 5432 error?

I am just posting this for anyone who is feeling lost and hopeless as I did when I found this question. It seems that sometimes by editing some psotgresql-related config files, one can accidentally change the permissions of the file:

enter image description here

Note how pg_hba.conf belongs to root, and users cannot even read it. This causes postgres to not be able to open this file and therefore not be able to start the server, throwing the error seen in the original question.

By running

sudo chmod +r pg_hba.conf

I was able to make this file once again accessible to the postgres user and then after running

sudo service postgresql start

Was able to get the server running again.

"No cached version... available for offline mode."

Since you mention you have a proxy connection I will tell you what worked for me: I went to properties (as friedrich mentioned) ensuring the Offline Work was unchecked. I opened up the gradle.properties file in the IDE and added my proxy settings. Here's a generic version:

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Then at the top of the properties file in the IDE there was a "Try Again" link which I clicked. That did it.

How do I print the content of a .txt file in Python?

with open("filename.txt", "w+") as file:
  for line in file:
    print line

This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

Visual Studio debugging/loading very slow

Go to your environment variables and look for the key _NT_SYMBOL_PATH.

Delete it.

Voila, worked like a charm.

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

Why won't my PHP app send a 404 error?

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
    header('HTTP/1.0 404 Not Found');
    echo "<h1>404 Not Found</h1>";
    echo "The page that you have requested could not be found.";
    exit();
}

If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.

Connect Android Studio with SVN

There is a "Enable Version Control Integration..." option from the VCS popup (control V). Until you do this and select a VCS the VCS system context menus do not show up and the VCS features are not fully integrated. Not sure why this is so hidden?

Enable Version Control Integration

PHP 5 disable strict standards error

All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess at root folder. Just to hide the errors. [Put one of the followling lines in the file]

php_flag display_errors off

Or

php_value display_errors 0

Next, to set the error reporting

php_value error_reporting 30719

If you are wondering how the value 30719 came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719)

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.

Gradle project refresh failed after Android Studio update

Make sure that nothing is interfering with your app files (specially in Windows), in my case this problem arise due to a text editor that was holding some XML file and Android Studio wasn't able to modify it.

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

This is what worked for our particular situation.

Notes are from Wikipedia on Basic Auth from the Client Side. Thank you to @briantist's answer for the help!

Combine the username and password into a single string username:password

$user = "shaunluttin"
$pass = "super-strong-alpha-numeric-symbolic-long-password"
$pair = "${user}:${pass}"

Encode the string to the RFC2045-MIME variant of Base64, except not limited to 76 char/line.

$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)

Create the Auth value as the method, a space, and then the encoded pair Method Base64String

$basicAuthValue = "Basic $base64"

Create the header Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

$headers = @{ Authorization = $basicAuthValue }

Invoke the web-request

Invoke-WebRequest -uri "https://api.github.com/user" -Headers $headers

The PowerShell version of this is more verbose than the cURL version is. Why is that? @briantist pointed out that GitHub is breaking the RFC and PowerShell is sticking to it. Does that mean that cURL is also breaking with the standard?

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

The value of 262,144 bytes is the key to the diagnosis. You'll see this magic number pop up in PHP questions all over the place. Why? Because that is the value PHP will end up with as its memory limit if you attempt to update the limit with a value it can't use. An empty string will produce this memory limit, as will an incorrect unit notation like '128MB' instead of the correct '128M'.

262,144 bytes is exactly 256 Kibibytes. Why PHP runs home to that value when it gets confused is beyond me.

isn't it weird that allowed memory is bigger than allocated memory?

The allocated amount shown is just the most recent allocation attempt, the one that ran afoul of the memory limit. See Allowed memory size in PHP when allocating less.

Component based game engine design

I researched and implemented this last semester for a game development course. Hopefully this sample code can point you in the right direction of how you might approach this.

class Entity {
public:
    Entity(const unsigned int id, const std::string& enttype);
    ~Entity();

    //Component Interface
    const Component* GetComponent(const std::string& family) const;
    void SetComponent(Component* newComp);
    void RemoveComponent(const std::string& family);
    void ClearComponents();

    //Property Interface
    bool HasProperty(const std::string& propName) const;
    template<class T> T& GetPropertyDataPtr(const std::string& propName);
    template<class T> const T& GetPropertyDataPtr(const std::string& propName) const;

    //Entity Interface
    const unsigned int GetID() const;
    void Update(float dt);

private:
    void RemoveProperty(const std::string& propName);
    void ClearProperties();
    template<class T> void AddProperty(const std::string& propName);
    template<class T> Property<T>* GetProperty(const std::string& propName);
    template<class T> const Property<T>* GetProperty(const std::string& propName) const;

    unsigned int m_Id;
    std::map<const string, IProperty*> m_Properties;
    std::map<const string, Component*> m_Components;
};

Components specify behavior and operate on properties. Properties are shared between all components by a reference and get updates for free. This means no large overhead for message passing. If there's any questions I'll try to answer as best I can.

How do I show the value of a #define at compile-time?

You could write a program that prints out BOOST_VERSION and compile and run it as part of your build system. Otherwise, I think you're out of luck.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

to_string is not a member of std, says g++ (mingw)

For anyone wondering why this happens on Android, it's probably because you're using a wrong c++ standard library. Try changing the c++ library in your build.gradle from gnustl_static to c++_static and the c++ standard in your CMakeLists.txt from -std=gnu++11 to -std=c++11

What is the default value for Guid?

The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)

This can be invoked using Guid.Empty or new Guid()

If you want a new GUID, you use Guid.NewGuid()

Wait till a Function with animations is finished until running another Function

add the following to the end of the first function

return $.Deferred().resolve();

call both functions like so

functionOne().done(functionTwo);

Stop handler.postDelayed()

this may be old, but for those looking for answer you can use this...

public void stopHandler() {
   handler.removeMessages(0);
}

cheers

Is there a "do ... until" in Python?

There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:

import itertools

def dowhile(predicate):
  it = itertools.repeat(None)
  for _ in it:
    yield
    if not predicate(): break

so, for example:

i=7; j=3
for _ in dowhile(lambda: i<j):
  print i, j
  i+=1; j-=1

executes one leg, as desired, even though the predicate's already false at the start.

It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:

def incandec(i, j, delta=1):
  while True:
    yield i, j
    if j <= i: break
    i+=delta; j-=delta

which you can use like:

for i, j in incandec(i=7, j=3):
  print i, j

It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).

MVC 4 client side validation not working

For me this was a lot of searching. Eventually I decided to use NuGet instead of downloading the files myself. I deleted all involved scripts and scriptbundles and got the following packages (latest versions as of now)

  • jQuery (3.1.1)
  • jQuery Validation (1.15.1)
  • Microsoft jQuery Ubobtrusive Ajax (3.2.3)
  • Microsoft jQuery Unobtrusive Validation (3.2.3)

Then I added these bundles to the BundleConfig file:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate.js",
                "~/Scripts/jquery.validate.unobtrusive.js",
                "~/Scripts/jquery.unobtrusive-ajax.js"));

I added this reference to _Layout.cshtml:

@Scripts.Render("~/bundles/jquery")

And I added this reference to whichever view I needed validation:

@Scripts.Render("~/bundles/jqueryval")

Now everything worked.

Don't forget these things (many people forget them):

  • Form tags (@using (Html.BeginForm()))
  • Validation Summary (@Html.ValidationSummary())
  • Validation Message on your input (Example: @Html.ValidationMessageFor(model => model.StartDate))
  • Configuration ()
  • The order of the files added to the bundle (as stated above)

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

What's the difference between Thread start() and Runnable run()

The difference is that Thread.start() starts a thread that calls the run() method, while Runnable.run() just calls the run() method on the current thread.

Oracle TNS names not showing when adding new connection to SQL Developer

In SQLDeveloper browse Tools --> Preferences, as shown in below image.

enter image description here

In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
Then click on Ok.
as shown in below diagram.

enter image description here

You have Done!

Now you can connect via the TNSnames options.

AngularJS : Clear $watch

Some time your $watch is calling dynamically and it will create its instances so you have to call deregistration function before your $watch function

if(myWatchFun)
  myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});

In php, is 0 treated as empty?

http://php.net/empty

The following things are considered to be empty:

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

Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

box-shadow on bootstrap 3 container

Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.

Example: http://jsfiddle.net/SHLu4/2/

It'll be something like:

<div class="container drop-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-8">Main Area</div>
            <div class="col-md-4">Side Area</div>
        </div>
    </div>
</div>

And your CSS:

<style>
    .drop-shadow {
        -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
        box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
    }
    .container.drop-shadow {
        padding-left:0;
        padding-right:0;
    }
</style>

String MinLength and MaxLength validation don't work (asp.net mvc)

Try using this attribute, for example for password min length:

[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]

Quicksort with Python

This answer is an in-place QuickSort for Python 2.x. My answer is an interpretation of the in-place solution from Rosetta Code which works for Python 3 too:

import random

def qsort(xs, fst, lst):
    '''
    Sort the range xs[fst, lst] in-place with vanilla QuickSort

    :param xs:  the list of numbers to sort
    :param fst: the first index from xs to begin sorting from,
                must be in the range [0, len(xs))
    :param lst: the last index from xs to stop sorting at
                must be in the range [fst, len(xs))
    :return:    nothing, the side effect is that xs[fst, lst] is sorted
    '''
    if fst >= lst:
        return

    i, j = fst, lst
    pivot = xs[random.randint(fst, lst)]

    while i <= j:
        while xs[i] < pivot:
            i += 1
        while xs[j] > pivot:
            j -= 1

        if i <= j:
            xs[i], xs[j] = xs[j], xs[i]
            i, j = i + 1, j - 1
    qsort(xs, fst, j)
    qsort(xs, i, lst)

And if you are willing to forgo the in-place property, below is yet another version which better illustrates the basic ideas behind quicksort. Apart from readability, its other advantage is that it is stable (equal elements appear in the sorted list in the same order that they used to have in the unsorted list). This stability property does not hold with the less memory-hungry in-place implementation presented above.

def qsort(xs):
    if not xs: return xs # empty sequence case
    pivot = xs[random.choice(range(0, len(xs)))]

    head = qsort([x for x in xs if x < pivot])
    tail = qsort([x for x in xs if x > pivot])
    return head + [x for x in xs if x == pivot] + tail

Redirect stderr and stdout in Bash

For tcsh, I have to use the following command :

command >& file

If use command &> file , it will give "Invalid null command" error.

Colspan all columns

According to the specification colspan="0" should result in a table width td.

However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...

http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan

I cannot test it on older browsers, but this is part of specification since 4.0...

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

PostgreSQL: days/months/years between two dates

I would like to expand on Riki_tiki_tavi's answer and get the data out there. I have created a datediff function that does almost everything sql server does. So that way we can take into account any unit.

create function datediff(units character varying, start_t timestamp without time zone, end_t timestamp without time zone) returns integer
language plpgsql
 as
 $$
DECLARE
 diff_interval INTERVAL; 
 diff INT = 0;
 years_diff INT = 0;
BEGIN
 IF units IN ('yy', 'yyyy', 'year', 'mm', 'm', 'month') THEN
   years_diff = DATE_PART('year', end_t) - DATE_PART('year', start_t);

   IF units IN ('yy', 'yyyy', 'year') THEN
     -- SQL Server does not count full years passed (only difference between year parts)
     RETURN years_diff;
   ELSE
     -- If end month is less than start month it will subtracted
     RETURN years_diff * 12 + (DATE_PART('month', end_t) - DATE_PART('month', start_t)); 
   END IF;
 END IF;

 -- Minus operator returns interval 'DDD days HH:MI:SS'  
 diff_interval = end_t - start_t;

 diff = diff + DATE_PART('day', diff_interval);

 IF units IN ('wk', 'ww', 'week') THEN
   diff = diff/7;
   RETURN diff;
 END IF;

 IF units IN ('dd', 'd', 'day') THEN
   RETURN diff;
 END IF;

 diff = diff * 24 + DATE_PART('hour', diff_interval); 

 IF units IN ('hh', 'hour') THEN
    RETURN diff;
 END IF;

 diff = diff * 60 + DATE_PART('minute', diff_interval);

 IF units IN ('mi', 'n', 'minute') THEN
    RETURN diff;
 END IF;

 diff = diff * 60 + DATE_PART('second', diff_interval);

 RETURN diff;
END;
$$;

Remove all line breaks from a long string of text

The canonic answer, in Python, would be :

s = ''.join(s.splitlines())

It splits the string into lines (letting Python doing it according to its own best practices). Then you merge it. Two possibilities here:

  • replace the newline by a whitespace (' '.join())
  • or without a whitespace (''.join())

What is the easiest way to parse an INI file in Java?

The library I've used is ini4j. It is lightweight and parses the ini files with ease. Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API

This is an example on how the library is used:

Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));

try/catch blocks with async/await

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
  apiClient.getCurrentUser()
);

What does an exclamation mark mean in the Swift language?

john is an optional var and it can contain a nil value. To ensure that the value isn't nil use a ! at the end of the var name.

From documentation

“Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.”

Another way to check non nil value is (optional unwrapping)

    if let j = json {
        // do something with j
    }

Secure hash and salt for PHP passwords

A much shorter and safer answer - don't write your own password mechanism at all, use a tried and tested mechanism.

  • PHP 5.5 or higher: password_hash() is good quality and part of PHP core.
  • PHP 4.x (obsolete): OpenWall's phpass library is much better than most custom code - used in WordPress, Drupal, etc.

Most programmers just don't have the expertise to write crypto related code safely without introducing vulnerabilities.

Quick self-test: what is password stretching and how many iterations should you use? If you don't know the answer, you should use password_hash(), as password stretching is now a critical feature of password mechanisms due to much faster CPUs and the use of GPUs and FPGAs to crack passwords at rates of billions of guesses per second (with GPUs).

For example, you can crack all 8-character Windows passwords in 6 hours using 25 GPUs installed in 5 desktop PCs. This is brute-forcing i.e. enumerating and checking every 8-character Windows password, including special characters, and is not a dictionary attack. That was in 2012, as of 2018 you could use fewer GPUs, or crack faster with 25 GPUs.

There are also many rainbow table attacks on Windows passwords that run on ordinary CPUs and are very fast. All this is because Windows still doesn't salt or stretch its passwords, even in Windows 10 - don't make the same mistake as Microsoft did!

See also:

  • excellent answer with more about why password_hash() or phpass are the best way to go.
  • good blog article giving recommmended 'work factors' (number of iterations) for main algorithms including bcrypt, scrypt and PBKDF2.

Find and replace with a newline in Visual Studio Code

Also note, after hitting the regex icon, to actually replace \n text with a newline, I had to use \\n as search and \n as replace.

How to initialize List<String> object in Java?

We created soyuz-to to simplify 1 problem: how to convert X to Y (e.g. String to Integer). Constructing of an object is also kind of conversion so it has a simple function to construct Map, List, Set:

import io.thedocs.soyuz.to;

List<String> names = to.list("John", "Fedor");

Please check it - it has a lot of other useful features

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

What Does 'zoom' do in CSS?

This property controls the magnification level for the current element. The rendering effect for the element is that of a “zoom” function on a camera. Even though this property is not inherited, it still affects the rendering of child elements.

Example

 div { zoom: 200% }
 <div style=”zoom: 200%”>This is x2 text </div>

What is the equivalent of Java's System.out.println() in Javascript?

I'm also about to ask the same question. But from what I've learned from codeacademy.com below code is enough to display the output or text?

print("hello world")  

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

The error comes (at least sometimes) from paths that are too long. In my project simply reducing the output file path does the job: "Properties/Configuration Properties/General/Intermediate Directory"

Seems that I have hit the 250 character path limitation.

Cordova : Requirements check failed for JDK 1.8 or greater

It's an old question, but since i just had the same problem, but the error had another source, here a short answer.

Problem accured on Windows (only) and with the Webstorm IDE 2019.2

In the version 2019.2 Webstorm had an issue, because it internally used open jdk for the %JAVA_HOME% variable instead of the (from the os) targeted java jdk.

In my case (yeah it's old, it's an old cordova project ... )

executing java -version in Windows cmd.exe:

$ java -version
java version "1.8.0_221"

but executing java -version in Webstorms terminal:

$ java -version
openjdk version "11.0.3" 2019-04-16
// more output

A fix came with the patch released later (today), version 2019.2.1. Now Webstorm uses the os %JAVA_HOME% variable as it should and the java -version output is identical in both cases.

Hope it helps someone!

HTML: Image won't display?

If you put <img src="iwojimaflag.jpg"/> in html code then place iwojimaflag.jpg and html file in same folder.

If you put <img src="images/iwojimaflag.jpg"/> then you must create "images" folder and put image iwojimaflag.jpg in that folder.

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

How do I scroll to an element using JavaScript?

To scroll to a given element, just made this javascript only solution below.

Simple usage:

EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);

Engine object (you can fiddle with filter, fps values):

/**
 *
 * Created by Borbás Geri on 12/17/13
 * Copyright (c) 2013 eppz! development, LLC.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */


var EPPZScrollTo =
{
    /**
     * Helpers.
     */
    documentVerticalScrollPosition: function()
    {
        if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
        if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
        if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
        return 0; // None of the above.
    },

    viewportHeight: function()
    { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },

    documentHeight: function()
    { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },

    documentMaximumScrollPosition: function()
    { return this.documentHeight() - this.viewportHeight(); },

    elementVerticalClientPositionById: function(id)
    {
        var element = document.getElementById(id);
        var rectangle = element.getBoundingClientRect();
        return rectangle.top;
    },

    /**
     * Animation tick.
     */
    scrollVerticalTickToPosition: function(currentPosition, targetPosition)
    {
        var filter = 0.2;
        var fps = 60;
        var difference = parseFloat(targetPosition) - parseFloat(currentPosition);

        // Snap, then stop if arrived.
        var arrived = (Math.abs(difference) <= 0.5);
        if (arrived)
        {
            // Apply target.
            scrollTo(0.0, targetPosition);
            return;
        }

        // Filtered position.
        currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);

        // Apply target.
        scrollTo(0.0, Math.round(currentPosition));

        // Schedule next tick.
        setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
    },

    /**
     * For public use.
     *
     * @param id The id of the element to scroll to.
     * @param padding Top padding to apply above element.
     */
    scrollVerticalToElementById: function(id, padding)
    {
        var element = document.getElementById(id);
        if (element == null)
        {
            console.warn('Cannot find element with id \''+id+'\'.');
            return;
        }

        var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
        var currentPosition = this.documentVerticalScrollPosition();

        // Clamp.
        var maximumScrollPosition = this.documentMaximumScrollPosition();
        if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;

        // Start animation.
        this.scrollVerticalTickToPosition(currentPosition, targetPosition);
    }
};

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

jQuery - multiple $(document).ready ...?

$(document).ready(); is the same as any other function. it fires once the document is ready - ie loaded. the question is about what happens when multiple $(document).ready()'s are fired not when you fire the same function within multiple $(document).ready()'s

//this
<div id="target"></div>

$(document).ready(function(){
   jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 3<br>');
});

//is the same as
<div id="target"></div>

$(document).ready(function(){

    jQuery('#target').append('target edit 1<br>');

    jQuery('#target').append('target edit 2<br>');

    jQuery('#target').append('target edit 3<br>');

});

both will behave exactly the same. the only difference is that although the former will achieve the same results. the latter will run a fraction of a second faster and requires less typing. :)

in conclusion where ever possible only use 1 $(document).ready();

//old answer

They will both get called in order. Best practice would be to combine them. but dont worry if its not possible. the page will not explode.

Adding elements to a C# array

Use List<string> instead of string[].

List allows you to add and remove items with good performance.

Testing javascript with Mocha - how can I use console.log to debug a test?

If you are testing asynchronous code, you need to make sure to place done() in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.

How to delete a file after checking whether it exists

if (File.Exists(path))
{
    File.Delete(path);
}

How to Disable landscape mode in Android?

Just add this attribute in your activity tag.

 android:screenOrientation="portrait"

Why do Twitter Bootstrap tables always have 100% width?

I've tried to add style="width: auto !important" and works great for me!

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

pip3: command not found

its possible if you already have a python installed (pip) you could do a upgrade on mac by

brew upgrade python

Alternate table row color using CSS?

can i write my html like this with use css ?

Yes you can but then you will have to use the :nth-child() pseudo selector (which has limited support though):

table.alternate_color tr:nth-child(odd) td{
   /* styles here */
}
table.alternate_color tr:nth-child(even) td{
   /* styles here */
}

Formatting numbers (decimal places, thousands separators, etc) with CSS

You could use Jstl tag Library for formatting for JSP Pages

JSP Page
//import the jstl lib
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}" 
        type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number" 
        maxFractionDigits="3" value="${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type="number" 
        groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent" 
        minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number" 
        pattern="###.###E0" value="${balance}" /></p>

Result

Formatted Number (1): £120,000.23

Formatted Number (2): 000.231

Formatted Number (3): 120,000.231

Formatted Number (4): 120000.231

Formatted Number (5): 023%

Formatted Number (6): 12,000,023.0900000000%

Formatted Number (7): 023%

Formatted Number (8): 120E3

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

Using two values for one switch case statement

JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

Now you can:

  • directly assign variable from switch expression,
  • use new form of switch label (case L ->):

    The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

  • use multiple constants per case, separated by commas,
  • and also there are no more value breaks:

    To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

So the demo from one of the answers might look like this:

public class SwitchExpression {

  public static void main(String[] args) {
      int month = 9;
      int year = 2018;
      int numDays = switch (month) {
        case 1, 3, 5, 7, 8, 10, 12 -> 31;
        case 4, 6, 9, 11 -> 30;
        case 2 -> {
          if (java.time.Year.of(year).isLeap()) {
            System.out.println("Wow! It's leap year!");
            yield 29;
          } else {
            yield 28;
          }
        }
        default -> {
          System.out.println("Invalid month.");
          yield 0;
        }
      };
      System.out.println("Number of Days = " + numDays);
  }
}

Difference between e.target and e.currentTarget

e.currentTarget is always the element the event is actually bound do. e.target is the element the event originated from, so e.target could be a child of e.currentTarget, or e.target could be === e.currentTarget, depending on how your markup is structured.

What is the difference between XAMPP or WAMP Server & IIS?

WAMP: acronym for Windows Operating System, Apache(Web server), MySQL Database and PHP Language.

XAMPP: acronym for X (any Operating System), Apache (Web server), MySQL Database, PHP Language and PERL.


XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people.

Their differences are in the format/structure of the package, the configurations, and the included management applications.

In short: XAMPP supports more OSes and includes more features

How to encrypt String in Java

Here are some links you can read what Java supports

Encrypting/decrypting a data stream.

This example demonstrates how to encrypt (using a symmetric encryption algorithm such as AES, Blowfish, RC2, 3DES, etc) a large amount of data. The data is passed in chunks to one of the encrypt methods: EncryptBytes, EncryptString, EncryptBytesENC, or EncryptStringENC. (The method name indicates the type of input (string or byte array) and the return type (encoded string or byte array). The FirstChunk and LastChunk properties are used to indicate whether a chunk is the first, middle, or last in a stream to be encrypted. By default, both FirstChunk and LastChunk equal true -- meaning that the data passed is the entire amount.

JCERefGuide

Java Encryption Examples

Docker how to change repository name or rename image?

As a shorthand you can run:

docker tag d58 myname/server:latest

Where d58 represents the first 3 characters of the IMAGE ID,in this case, that's all you need.

Finally, you can remove the old image as follows:

docker rmi server

Create a List that contain each Line of a File

my_list = [line.split(',') for line in open("filename.txt")]

Returning JSON object from an ASP.NET page

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

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

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

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

Understanding implicit in Scala

Also, in the above case there should be only one implicit function whose type is double => Int. Otherwise, the compiler gets confused and won't compile properly.

//this won't compile

implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0

Delete item from array and shrink array

Arrays are fixed in size, you cannot resize them after creating them. You can remove an existing item by setting it to null:

objects[4] = null;

But you won't be able to delete that entire slot off the array and reduce its size by 1.

If you need a dynamically-sized array, you can use an ArrayList. With it, you can add() and remove() objects, and it will grow and shrink as needed.

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

How to make ng-repeat filter out duplicate results

Here's a straightforward and generic example.

The filter:

sampleApp.filter('unique', function() {

  // Take in the collection and which field
  //   should be unique
  // We assume an array of objects here
  // NOTE: We are skipping any object which
  //   contains a duplicated value for that
  //   particular key.  Make sure this is what
  //   you want!
  return function (arr, targetField) {

    var values = [],
        i, 
        unique,
        l = arr.length, 
        results = [],
        obj;

    // Iterate over all objects in the array
    // and collect all unique values
    for( i = 0; i < arr.length; i++ ) {

      obj = arr[i];

      // check for uniqueness
      unique = true;
      for( v = 0; v < values.length; v++ ){
        if( obj[targetField] == values[v] ){
          unique = false;
        }
      }

      // If this is indeed unique, add its
      //   value to our values and push
      //   it onto the returned array
      if( unique ){
        values.push( obj[targetField] );
        results.push( obj );
      }

    }
    return results;
  };
})

The markup:

<div ng-repeat = "item in items | unique:'name'">
  {{ item.name }}
</div>
<script src="your/filters.js"></script>

Python constructor and default value

Mutable default arguments don't generally do what you want. Instead, try this:

class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList 
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList 

How can I write a heredoc to a file in Bash script?

I like this method for concision, readability and presentation in an indented script:

<<-End_of_file >file
?       foo bar
End_of_file

Where ?        is a tab character.

Tomcat 7 "SEVERE: A child container failed during start"

This seems like that the servlet api version which you using is older than the xsd you are using in web.xml eg 3.0

use this one ****http://java.sun.com/xml/ns/javaee/" id="WebApp_ID" version="2.5"> ****

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

Generating a WSDL from an XSD file

we can generate wsdl file from xsd but you have to use oracle enterprise pack of eclipse(OEPE). simply create xsd and then right click->new->wsdl...

Browser detection in JavaScript?

I recommend using the tiny javascript library Bowser, yes no r. It is based on the navigator.userAgent and quite well tested for all browsers including iphone, android etc.

https://github.com/ded/bowser

You can use simply say:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello IE');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Chrome');
} else if (bowser.safari){
  alert('Hello Safari');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}

openpyxl - adjust column width size

My variation of Bufke's answer. Avoids a bit of branching with the array and ignores empty cells / columns.

Now fixed for non-string cell values.

ws = your current worksheet
dims = {}
for row in ws.rows:
    for cell in row:
        if cell.value:
            dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value))))    
for col, value in dims.items():
    ws.column_dimensions[col].width = value

As of openpyxl version 3.0.3 you need to use

 dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.value))))

as the openpyxl library will raise a TypeError if you pass column_dimensions a number instead of a column letter, everything else can stay the same.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Simply check that the directory/package of the class is marked as "Sources Root". I believe the package should be application or execution in your case.

To do so, right click on the package, and select Mark Directory As->Sources Root.

1

.NET unique object identifier

I know that this has been answered, but it's at least useful to note that you can use:

http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx

Which will not give you a "unique id" directly, but combined with WeakReferences (and a hashset?) could give you a pretty easy way of tracking various instances.

How to determine the longest increasing subsequence using dynamic programming?

Here's another O(n^2) JAVA implementation. No recursion/memoization to generate the actual subsequence. Just a string array that stores the actual LIS at every stage and an array to store the length of the LIS for each element. Pretty darn easy. Have a look:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Shreyans on 4/16/2015
 */

class LNG_INC_SUB//Longest Increasing Subsequence
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter Numbers Separated by Spaces to find their LIS\n");
        String[] s1=br.readLine().split(" ");
        int n=s1.length;
        int[] a=new int[n];//Array actual of Numbers
        String []ls=new String[n];// Array of Strings to maintain LIS for every element
        for(int i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(s1[i]);
        }
        int[]dp=new int[n];//Storing length of max subseq.
        int max=dp[0]=1;//Defaults
        String seq=ls[0]=s1[0];//Defaults
        for(int i=1;i<n;i++)
        {
            dp[i]=1;
            String x="";
            for(int j=i-1;j>=0;j--)
            {
                //First check if number at index j is less than num at i.
                // Second the length of that DP should be greater than dp[i]
                // -1 since dp of previous could also be one. So we compare the dp[i] as empty initially
                if(a[j]<a[i]&&dp[j]>dp[i]-1)
                {
                    dp[i]=dp[j]+1;//Assigning temp length of LIS. There may come along a bigger LIS of a future a[j]
                    x=ls[j];//Assigning temp LIS of a[j]. Will append a[i] later on
                }
            }
            x+=(" "+a[i]);
            ls[i]=x;
            if(dp[i]>max)
            {
                max=dp[i];
                seq=ls[i];
            }
        }
        System.out.println("Length of LIS is: " + max + "\nThe Sequence is: " + seq);
    }
}

Code in action: http://ideone.com/sBiOQx

How to remove selected commit log entries from a Git repository while keeping their changes?

I find this process much safer and easier to understand by creating another branch from the SHA1 of A and cherry-picking the desired changes so I can make sure I'm satisfied with how this new branch looks. After that, it is easy to remove the old branch and rename the new one.

git checkout <SHA1 of A>
git log #verify looks good
git checkout -b rework
git cherry-pick <SHA1 of D>
....
git log #verify looks good
git branch -D <oldbranch>
git branch -m rework <oldbranch>

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++) {
  //code
}

In simplest terms

int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1;  //i = 2
if (i < 8) //code
i = i + 1;  //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass

How in node to split string by newline ('\n')?

Try splitting on a regex like /\r?\n/ to be usable by both Windows and UNIX systems.

> "a\nb\r\nc".split(/\r?\n/)
[ 'a', 'b', 'c' ]

How can I get the source code of a Python function?

If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

If foo is defined as:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a  

Then:

import inspect
lines = inspect.getsource(foo)
print(lines)

Returns:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a                

But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

SQL Server Text type vs. varchar data type

If you're using SQL Server 2005 or later, use varchar(MAX). The text datatype is deprecated and should not be used for new development work. From the docs:

Important

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

How do C++ class members get initialized if I don't do it explicitly?

If it is on the stack, the contents of uninitialized members that don't have their own constructor will be random and undefined. Even if it is global, it would be a bad idea to rely on them being zeroed out. Whether it is on the stack or not, if a member has its own constructor, that will get called to initialize it.

So, if you have string* pname, the pointer will contain random junk. but for string name, the default constructor for string will be called, giving you an empty string. For your reference type variables, I'm not sure, but it'll probably be a reference to some random chunk of memory.

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can use the HTML5 pattern attribute or use JavaScript.

The pattern could look for example like this:

<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />

But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.

As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.

What is the list of supported languages/locales on Android?

First we need to plan how the application will render differently in different locals. Here it shows example, where the text string and images have to go.

de-rDE German / Germany res/values-de/ res/drawable-de-rDE/ 
fr-rFR French / France res/values-fr/ res/drawable-fr-rFR/ 
fr-rCA French / Canada res/values-fr/ res/drawable-fr-rCA/ 
en-rCA English / Canada (res/values/) res/drawable-en-rCA/ 
ja-rJP Japanese / Japan res/values-ja/ res/drawable-ja-rJP/ 
en-rUS English / United States (res/values/) res/drawable-en-rUS/ 

For more info you can see the page Localization

How to convert int to string on Arduino?

You just need to wrap it around a String object like this:

String numberString = String(n);

You can also do:

String stringOne = "Hello String";                     // using a constant String
String stringOne =  String('a');                       // converting a constant char into a String
String stringTwo =  String("This is a string");        // converting a constant string into a String object
String stringOne =  String(stringTwo + " with more");  // concatenating two strings
String stringOne =  String(13);                        // using a constant integer
String stringOne =  String(analogRead(0), DEC);        // using an int and a base
String stringOne =  String(45, HEX);                   // using an int and a base (hexadecimal)
String stringOne =  String(255, BIN);                  // using an int and a base (binary)
String stringOne =  String(millis(), DEC);             // using a long and a base

OS X Terminal Colors

MartinVonMartinsgrün and 4Levels methods confirmed work great on Mac OS X Mountain Lion.

The file I needed to update was ~/.profile.

However, I couldn't leave this question without recommending my favorite application, iTerm 2.

iTerm 2 lets you load global color schemes from a file. Really easy to experiment and try a bunch of color schemes.

Here's a screenshot of the iTerm 2 window and the color preferences. iTerm2 Color Preferences Screenshot Mac

Once I added the following to my ~/.profile file iTerm 2 was able to override the colors.

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Here is a great repository with some nice presets:

iTerm2 Color Schemes on Github by mbadolato

Bonus: Choose "Show/hide iTerm2 with a system-wide hotkey" and bind the key with BetterTouchTool for an instant hide/show the terminal with a mouse gesture.

Add all files to a commit except a single file?

While Ben Jackson is correct, I thought I would add how I've been using that solution as well. Below is a very simple script I use (that I call gitadd) to add all changes except a select few that I keep listed in a file called .gittrackignore (very similar to how .gitignore works).

#!/bin/bash
set -e

git add -A
git reset `cat .gittrackignore`

And this is what my current .gittrackignore looks like.

project.properties

I'm working on an Android project that I compile from the command line when deploying. This project depends on SherlockActionBar, so it needs to be referenced in project.properties, but that messes with the compilation, so now I just type gitadd and add all of the changes to git without having to un-add project.properties every single time.

Monitor network activity in Android Phones

The common approach is to call "cat /proc/net/netstat" as described here:

Android network stats

How to SUM two fields within an SQL query

Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0

I know this was an older posting but wanted to add this for completeness.

How to find out the number of CPUs using python

multiprocessing.cpu_count() will return the number of logical CPUs, so if you have a quad-core CPU with hyperthreading, it will return 8. If you want the number of physical CPUs, use the python bindings to hwloc:

#!/usr/bin/env python
import hwloc
topology = hwloc.Topology()
topology.load()
print topology.get_nbobjs_by_type(hwloc.OBJ_CORE)

hwloc is designed to be portable across OSes and architectures.

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

Make REST API call in Swift

Swift 4

Create an app using Alamofire with Api Post method

Install pod file -pod 'Alamofire', '~> 4.0' for Swift 3 with Xcode 9

Create Webservices.swift class, import Alamofire

Design storyBoard ,Login View

insert following Code for the ViewControllerClass

import UIKit

class ViewController: UIViewController {

    @IBOutlet var usernameTextField: UITextField!

    @IBOutlet var passwordTextField: UITextField!
    var usertypeStr :String = "-----------"
    var loginDictionary : NSDictionary?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loginButtonClicked(_ sender: Any) {
        WebServices.userLogin(userName: usernameTextField.text!, password: passwordTextField.text!,userType: usertypeStr) {(result, message, status )in
            if status {
                let loginDetails = result as? WebServices
                self.loginDictionary = loginDetails?.loginData
                if self.loginDictionary?["status"] as? String == "error"
                {
                    self.alertMessage(alerttitle: "Login Error", (self.loginDictionary?["message"] as? String)!)
                } else if self.loginDictionary?["status"] as? String == "ok" {
                    self.alertMessage(alerttitle: "", "Success")

                }else {
                    self.alertMessage(alerttitle: "", (self.loginDictionary?["message"] as? String)!)
                }
            } else {
                self.alertMessage(alerttitle: "", "Sorry")
            }
        }
    }

    func alertMessage(alerttitle:String,_ message : String){
        let alertViewController = UIAlertController(title:alerttitle,  message:message, preferredStyle: .alert)
        alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alertViewController, animated: true, completion: nil)
    }

}

Insert Following Code For WebserviceClass

import Foundation
import Alamofire
class WebServices: NSObject {
    enum WebServiceNames: String {
        case baseUrl = "https://---------------"
        case UserLogin = "------------"
    }

    // MARK: - Login Variables
    var loginData : NSDictionary?

    class func userLogin(userName: String,password : String,userType : String, completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> ()) {
        let url = WebServiceNames.baseUrl.rawValue + WebServiceNames.UserLogin.rawValue
        let params = ["USER": userName,"PASS":password,"API_Key" : userType]
        WebServices.postWebService(urlString: url, params: params as [String : AnyObject]) { (response, message, status) in
            print(response ?? "Error")
            let result = WebServices()
            if let data = response as? NSDictionary {
                print(data)
                result.loginData = data
                completion(result, "Success", true)

            }else {
                completion("" as AnyObject?, "Failed", false)
            }
        }
    }
    //MARK :- Post
    class func postWebService(urlString: String, params: [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void) {
        alamofireFunction(urlString: urlString, method: .post, paramters: params) { (response, message, success) in
            if response != nil {
                completion(response as AnyObject?, "", true)
            }else{
                completion(nil, "", false)
            }
        }
    }

    class func alamofireFunction(urlString : String, method : Alamofire.HTTPMethod, paramters : [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void){

        if method == Alamofire.HTTPMethod.post {
            Alamofire.request(urlString, method: .post, parameters: paramters, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

                print(urlString)

                if response.result.isSuccess{
                    completion(response.result.value as AnyObject?, "", true)
                }else{
                    completion(nil, "", false)
                }
            }

        }else {
            Alamofire.request(urlString).responseJSON { (response) in

                if response.result.isSuccess{
                    completion(response.result.value as AnyObject?, "", true)
                }else{
                    completion(nil, "", false)
                }
            }
        }
    }



    //Mark:-Cancel
    class func cancelAllRequests()
    {
        Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
            dataTasks.forEach { $0.cancel() }
            uploadTasks.forEach { $0.cancel() }
            downloadTasks.forEach { $0.cancel() }
        }
    }
}

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

Change Placeholder Text using jQuery

You can use following code to update a placeholder by id:

$("#serMemtb").attr("placeholder", "Type a Location").val("").focus().blur();

align textbox and text/labels in html?

I like to set the 'line-height' in the css for the divs to get them to line up properly. Here is an example of how I do it using asp and css:

ASP:

<div id="profileRow1">
    <div id="profileRow1Col1" class="righty">
        <asp:Label ID="lblCreatedDateLabel" runat="server" Text="Date Created:"></asp:Label><br />
        <asp:Label ID="lblLastLoginDateLabel" runat="server" Text="Last Login Date:"></asp:Label><br />
        <asp:Label ID="lblUserIdLabel" runat="server" Text="User ID:"></asp:Label><br />
        <asp:Label ID="lblUserNameLabel" runat="server" Text="Username:"></asp:Label><br />
        <asp:Label ID="lblFirstNameLabel" runat="server" Text="First Name:"></asp:Label><br />
        <asp:Label ID="lblLastNameLabel" runat="server" Text="Last Name:"></asp:Label><br />
    </div>
    <div id="profileRow1Col2">
        <asp:Label ID="lblCreatedDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblLastLoginDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblUserId" runat="server" Text="UserId"></asp:Label><br />
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
    </div>
</div>

And here is the code in the CSS file to make all of the above fields look nice and neat:

#profileRow1{width:100%;line-height:40px;}
#profileRow1Col1{float:left; width:25%; margin-right:20px;}
#profileRow1Col2{float:left; width:25%;}
.righty{text-align:right;}

you can basically pull everything but the DIV tags and replace with your own content.

Trust me when I say it looks aligned the way the image in the original post does!

I would post a screenshot but Stack wont let me: Oops! Your edit couldn't be submitted because: We're sorry, but as a spam prevention mechanism, new users aren't allowed to post images. Earn more than 10 reputation to post images.

:)

android pinch zoom

In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

How do I find all the files that were created today in Unix/Linux?

If you're did something like accidentally rsync'd to the wrong directory, the above suggestions work to find new files, but for me, the easiest was connecting with an SFTP client like Transmit then ordering by date and deleting.

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

Use a loop on the split values

string values = "0,1,2,3,4,5,6,7,8,9";

foreach(string value in values.split(','))
{
    //do something with individual value
}

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How to ignore parent css style

you can create another definition lower in your CSS stylesheet that basically reverses the initial rule. you could also append "!important" to said rule to make sure it sticks.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

In my case,

image = cv2.imread(filepath)
final_img = cv2.resize(image, size_img)

filepath was incorrect, cv2.imshow didn't give any error in this case but due to wrong path cv2.resize was giving me error.

How can I remount my Android/system as read-write in a bash script using adb?

mount -o rw,remount $(mount | grep /dev/root | awk '{print $3}')

this does the job for me, and should work for any android version.

py2exe - generate single executable file

I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.

This was the setup.py I used

from distutils.core import setup
import py2exe

setup(console=['post-review'])

It created a directory containing the exe file and the libraries needed. I don't think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.

One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can't include them. This is covered in the py2exe docs.

Java: Replace all ' in a string with \'

You could also try using something like StringEscapeUtils to make your life even easier: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

s = StringEscapeUtils.escapeJava(s);

Java Replace Line In Text File

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

Original Text File Content:

Do the dishes0
Feed the dog0
Cleaned my room1

Output:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

New text file content:

Do the dishes1
Feed the dog0
Cleaned my room1


And as a note, if the text file was:

Do the dishes1
Feed the dog0
Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.


Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Why use getters and setters/accessors?

From a object orientation design standpoint both alternatives can be damaging to the maintenance of the code by weakening the encapsulation of the classes. For a discussion you can look into this excellent article: http://typicalprogrammer.com/?p=23

How do I choose the URL for my Spring Boot webapp?

You need to set the property server.contextPath to /myWebApp.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely application.properties) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath as has been correctly mentioned in this answer.

MemoryStream - Cannot access a closed Stream

When the using() for your StreamReader is ending, it's disposing the object and closing the stream, which your StreamWriter is still trying to use.

Angular.js How to change an elements css class on click and to remove all others

To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.

Javascript:

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

angular.module('directives', []).directive('toggleClass', function () {
    var directiveDefinitionObject = {
        restrict: 'A',
        template: '<span ng-click="localFunction()" ng-class="selected"  ng-transclude></span>',
        replace: true,
        scope: {
            model: '='
        },
        transclude: true,
        link: function (scope, element, attrs) {
            scope.localFunction = function () {
                scope.model.value = scope.$id;
            };
            scope.$watch('model.value', function () {
                // Is this set to my scope?
                if (scope.model.value === scope.$id) {
                    scope.selected = "active";
                } else {
                    // nope
                    scope.selected = '';
                }
            });
        }
    };
    return directiveDefinitionObject;
});

HTML:

<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>

<br/>
<br/>
<span toggle-class model="model">span1</span>

<br/><span toggle-class model="model">span2</span>

<br/><span toggle-class model="model">span3</span>

CSS:

.active {
     color:red;
 }

I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.

The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.

Twitter Bootstrap Modal Form Submit

Old, but maybe useful for readers to have a full example of how use modal.

I do like following ( working example jsfiddle ) :

$('button.btn.btn-success').click(function(event)
{

event.preventDefault();

$.post('getpostcodescript.php', $('form').serialize(), function(data, status, xhr)
    {
        // do something here with response;
        console.info(data);
        console.info(status);
        console.info(xhr);
    })
    .done(function() {
        // do something here if done ;
        alert( "saved" );
    })
    .fail(function() {
        // do something here if there is an error ;
        alert( "error" );
    })
    .always(function() {
        // maybe the good state to close the modal
        alert( "finished" );
        // Set a timeout to hide the element again
        setTimeout(function(){
          $("#myModal").hide();
        }, 3000);
    });
});

To deal easier with modals, I recommend using eModal, which permit to go faster on base use of bootstrap 3 modals.

HTML5 iFrame Seamless Attribute

iO8 has removed support for the iframe seamless attribute.

  • Tested in Safari, HomeScreen, new WKWebView and UIWebView.

Full Details and performance review of other iOS 8 changes: